Datasets:

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
139ed14018b74e745cd16b882d50b4f47380adec
C#
yavorvasilev/CSharp-Advanced
/FunctionalProgrammingExercises/07PredicateForNames/PredicateForNames.cs
3.515625
4
namespace _07PredicateForNames { using System; using System.Linq; public class PredicateForNames { public static void Main() { var numberOfLetters = int.Parse(Console.ReadLine()); var inputNames = Console.ReadLine().Split(); Action<string[]> printNames = names => names.Where(n => n.Length <= numberOfLetters) .ToList() .ForEach(n => Console.WriteLine(n)); printNames(inputNames); } } }
22be5ff222c773fb62e546c7a7910b400d5e7d63
C#
bfriesen/garply
/src/garply/List.cs
2.890625
3
using System.Text; namespace Garply { internal struct List { public readonly Value Head; public readonly int TailIndex; internal List(Value head, int tailIndex) { Head = head; TailIndex = tailIndex; } public bool IsEmpty => Head.Type == Types.error; public override string ToString() { var sb = new StringBuilder(); sb.Append('['); var first = true; List list = this; while (true) { if (first) first = false; else sb.Append(','); sb.Append(list.Head.ToString()); if (list.TailIndex == 0) break; list = Heap.GetList(list.TailIndex); } sb.Append(']'); return sb.ToString(); } } }
b46f55849b60f04bb9c36e44d8ff38051efc4e6a
C#
18877761327/UnityStudio
/UnityStudio/Assets/Examples/AStar/Scripts/AStarPoint.cs
2.640625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AStarPoint { public int X; public int Y; public float F; /// <summary> /// 开始节点到自身节点的距离 /// </summary> public float G; /// <summary> /// 自身节点到结束节点的距离 /// </summary> public float H; public AStarPoint ParentPoint; public bool IsWall; public AStarPoint(int x, int y,AStarPoint point=null,bool isWall=false) { X = x; Y = y; ParentPoint = point; IsWall = isWall; } public void Update(AStarPoint parentPoint,float g) { ParentPoint = parentPoint; G = g; F = G + H; } }
6c9486d05c413d3933cb751977d463eff8cc7c21
C#
AsbjornHenriksen/CiiMac2.0
/CiiMac2.0/Host/Program.cs
2.65625
3
using BusinessLogic.Controllers; using Model; using Service; using System; using System.Collections.Generic; using System.Net; using System.ServiceModel.Web; using System.Timers; namespace Host { class Program { static UpdateDatabaseCtr updateDatabaseCtr; static void Main(string[] args) { WebServiceHost host = new WebServiceHost(typeof(Service.MVCServices)); host.Open(); Console.WriteLine("Host started @ " + DateTime.Now.ToString()); Update(); DisplayHost(host); Console.ReadLine(); host.Close(); } private static void DisplayHost(WebServiceHost host) { foreach (System.ServiceModel.Description.ServiceEndpoint se in host.Description.Endpoints) { Console.WriteLine($"Address: {se.Address}"); Console.WriteLine($"Binding: { se.Binding}"); Console.WriteLine($"Contract: {se.Contract}"); } Console.WriteLine("------------------"); } private static void Update() { updateDatabaseCtr = new UpdateDatabaseCtr(); updateDatabaseCtr.UpdateDatabase(); } } }
4f79de2a1996cdd99998a618b4b787f665b3d316
C#
marhoily/Accountant
/Accountant/Core/Accounting.Calculation/MoneyBag.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using NewModel.Accounting.Core; namespace NewModel.Accounting.Calculation { public sealed class MoneyBag : List<Money> { public MoneyBag() {} public MoneyBag(IEnumerable<Money> money) : base(money) { } public MoneyBag(params Money[] money) : base(money) { } public decimal this[Currency index] { get { var m = this.FirstOrDefault(c => c.Currency == index); return m == null ? 0 : m.Amount; } } public bool IsZero { get { return Count == 0; } } public static MoneyBag operator -(MoneyBag x) { return new MoneyBag(x.Select(m => new Money(m.Currency, -m.Amount))); } public static MoneyBag operator -(MoneyBag x, MoneyBag y) { return x + (-y); } public static MoneyBag operator +(MoneyBag x, MoneyBag y) { return new MoneyBag(x .Concat(y) .GroupBy(m => m.Currency) .Select(Sum) .Where(m => m.Amount != 0)); } static Money Sum(IEnumerable<Money> source) { var list = source.ToList(); if (list.Count == 0) throw new Exception("Empty sequence"); if (list.Count == 1) return list[0]; if (list.Select(i => i.Currency).Distinct().Count() != 1) throw new Exception("Cannot sum different currencies"); return new Money(list[0].Currency, list.Sum(i => i.Amount)); } public static MoneyBag operator +(MoneyBag x, Money y) { return x + new MoneyBag(y); } public override string ToString() { return string.Join(", ", this); } } }
290b30a6a5a05c57ca71df8fbec005977822cdb5
C#
sychoi3/WarnerMediaAPI
/WarnerMedia/Resources/Response/PagedResponse.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WarnerMedia.Resources.Response { public class PagedResponse<T> { public int count { get; set; } public int totalPages { get; set; } public int pageSize { get; set; } //public string next { get; set; } //public string previous { get; set; } public IList<T> results { get; set; } public PagedResponse() { } } public static class PaginationHelpers { public static PagedResponse<T> ToPagedResponse<T>(this IList<T> data, int pageNumber, int pageSize, int totalCount) where T : class { var totalPages = totalCount > 0 ? ((double)totalCount / (double)pageSize) : 0; int roundedTotalPages = Convert.ToInt32(Math.Ceiling(totalPages)); //var nextPage = pageNumber < roundedTotalPages // ? uriService.GetPageUri(pageNumber + 1).ToString() // : null; //var previousPage = pageNumber - 1 >= 1 // ? uriService.GetPageUri(pageNumber - 1).ToString() // : null; return new PagedResponse<T> { results = data, count = totalCount, //next = nextPage, //previous = previousPage, pageSize = data.Count, totalPages = roundedTotalPages }; } } }
ee70ab3700c972f89e5bd53dc838b813735e029a
C#
shendongnian/download4
/first_version_download2/390508-33823534-104567080-2.cs
2.5625
3
string xmlAsString; using (var xmlWebClient = new WebClient()) { xmlWebClient.Encoding = Encoding.UTF8; xmlAsString = xmlWebClient.DownloadString(url); } XmlDocument currentXml = new XmlDocument(); currentXml.Load(xmlAsString);
386520d91818d16c3ed63718c51d743d3d108b9c
C#
SiP001/Hello
/Hello/DateTimeMethod.cs
3.75
4
namespace Hello { using System; using System.Globalization; class DateTimeMethod { public int MonthsSince(DateTime date) { int months = (((DateTime.Now.Year - date.Year) * 12) + (DateTime.Now.Month - date.Month)); return months; } public int YearsSince(DateTime date) { int years; if ((DateTime.Now.Month == date.Month) && (DateTime.Now.Day == date.Day)) { Console.WriteLine("It's your birthday!"); years = (DateTime.Now.Year - date.Year); } else if (((DateTime.Now.Month == date.Month) && (DateTime.Now.Day < date.Day)) || (DateTime.Now.Month < date.Month)) { years = (DateTime.Now.Year - date.Year - 1); } else { years = (DateTime.Now.Year - date.Year); } return years; } public bool CheckDate(string strDate) { try { DateTime.ParseExact(strDate, "d/M/yyyy", CultureInfo.InvariantCulture); return true; } catch { return false; } } public TimeSpan TimeSince(DateTime date) { return DateTime.Now.Subtract(date); } public string GetDaySuffix(int day) { switch (day) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } } public string GetGreating(int hour) { if ((hour >= 0) && (hour < 12)) { return "Good Morning"; } else if ((hour >= 12) && (hour < 17)) { return "Good Afternoon"; } else if ((hour >= 17) && (hour < 20)) { return "Good Evening"; } else { return "Goodnight"; } } public string DayOfDate(DateTime date) { string day = date.DayOfWeek.ToString(); return day; } } }
0f05e0536611d702b132bf687407908679967e5f
C#
pervinpashazade/Code-Academy-Winform-Final-Project
/LibraryFinalTask/Forms/ReportsForm.cs
2.578125
3
using LibraryFinalTask.Data; using LibraryFinalTask.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LibraryFinalTask.Forms { public partial class ReportsForm : Form { private readonly LibraryDbContext _db; public ReportsForm() { _db = new LibraryDbContext(); InitializeComponent(); } private void BtnSearch_Click(object sender, EventArgs e) { if (dateEnd.Value > dateStart.Value) { DialogResult d = MessageBox.Show("The end date cannot be smaller than the start date", "Oops, Search Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } dgvReports.Rows.Clear(); var query = _db.OrderItems.Include("Order") .Include("Book") .Where(o => (o.OrderDate.Year == dateStart.Value.Year && o.OrderDate.Month == dateStart.Value.Month && o.OrderDate.Day == dateStart.Value.Day) && (o.OrderDate.Year <= dateEnd.Value.Year && o.OrderDate.Month <= dateEnd.Value.Month && o.OrderDate.Day <= dateEnd.Value.Day)) .ToList(); List<OrderItem> orders = query; foreach (var item in orders) { dgvReports.Rows.Add(item.Id, item.OrderId, item.Book.Name, item.Count, item.Amount, item.OrderDate, item.ReturnDate); } } private void IconRefresh_Click(object sender, EventArgs e) { dateStart.Value = DateTime.Now; dateEnd.Value = DateTime.Now; dgvReports.Rows.Clear(); } private void BtnExport_Click(object sender, EventArgs e) { } } }
a32392c27cbfb024215ae84b94eaada5e237c470
C#
Acerinth/MaliDronovi
/DronePositioningSimulator/DronePositioningSimulator/frmIzlaz.cs
2.546875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Media; namespace DronePositioningSimulator { public partial class frmIzlaz : Form { public frmIzlaz() { InitializeComponent(); } private void frmIzlaz_Load(object sender, EventArgs e) { this.DoubleBuffered = true; this.Paint += new PaintEventHandler(frmIzlaz_Paint); } private void frmIzlaz_Paint(object sender, PaintEventArgs e) { /* foreach (Dron d in Dron.listaDronova) { SolidBrush boja = new SolidBrush(d.Boja); Pen olovka = new Pen(d.Boja); //for (int i = 0; i < 800; i++) //{ // for (int j = 0; j < 600; j++) // { // if (g.polje[i,j].greskaX != 0) // { // e.Graphics.DrawEllipse(Pens.Black, i, j, 1, 1); // } // } //} e.Graphics.FillEllipse(boja, d.TrenX-5, d.TrenY-5, 10, 10); //e.Graphics.FillEllipse(Brushes.Black, d.KorX - 5, d.KorY - 5, 10, 10); d.GreskaX = g.polje[Math.Abs((int)d.TrenX), Math.Abs((int)d.TrenY)].greskaX; d.GreskaY = g.polje[Math.Abs((int)d.TrenX), Math.Abs((int)d.TrenY)].greskaY; e.Graphics.DrawEllipse(olovka, d.TrenX- d.GreskaX, d.TrenY- d.GreskaY, d.GreskaX*2, d.GreskaY*2); } */ foreach (Dron d in Dron.listaDronova) { foreach (Region r in d.listaVijenaca) { if (d.PrikazVijenaca) { e.Graphics.FillRegion(System.Drawing.Brushes.Beige, r); } } foreach (System.Drawing.Drawing2D.GraphicsPath gp in d.listaElipsi) { if (d.PrikazVijenaca) { System.Drawing.Pen olovka2 = new System.Drawing.Pen(d.Boja); e.Graphics.DrawPath(olovka2, gp); } } if (tmrDrawingTimer.Enabled == true) { e.Graphics.FillRegion(System.Drawing.Brushes.LightBlue, d.regijaPogreske); } SolidBrush boja = new SolidBrush(d.Boja); System.Drawing.Pen olovka = new System.Drawing.Pen(d.Boja); e.Graphics.FillEllipse(boja, d.TrenX - 5, d.TrenY - 5, 10, 10); d.GreskaX = GeneratorGreske.polje[Math.Abs((int)d.TrenX), Math.Abs((int)d.TrenY)].greskaX; d.GreskaY = GeneratorGreske.polje[Math.Abs((int)d.TrenX), Math.Abs((int)d.TrenY)].greskaY; e.Graphics.DrawEllipse(olovka, d.TrenX - d.GreskaX, d.TrenY - d.GreskaY, d.GreskaX * 2, d.GreskaY * 2); } } private void tmrDrawingTimer_Tick(object sender, EventArgs e) { foreach (Dron d in Dron.listaDronova) { d.provjeriRub(this.ClientSize.Width-5, this.ClientSize.Height - 5); d.pomakniDron(); d.pronadjiDronove(); d.korigirajPogresku(); } this.Refresh(); } /*public void pokaziDronove() { foreach (DronView d in DronView.listaDronova) { if (!this.Controls.Contains(d)) { this.Controls.Add(d); } } }*/ } }
0457f4af311cde187864fd76071297ec72e26763
C#
CreativeModeOverlay/CreativeModeProject
/Assets/BaseProject/Scripts/Application/DesktopUI/Components/Widgets/DragAndDrop/DragAndDropVisualizer.cs
2.578125
3
using System; using System.Collections.Generic; using DG.Tweening; using UniRx; using UnityEngine; namespace CreativeMode { public class DragAndDropVisualizer : MonoBehaviour { public GenericText itemPrefab; public RectTransform root; private readonly List<DragAndDropInstance> instances = new List<DragAndDropInstance>(); private void Start() { DragAndDropManager.Instance.DragStarted .Subscribe(s => OnDragStart(s.pointerId, s.draggedObject.name)) .AddTo(this); DragAndDropManager.Instance.DragEnded .Subscribe(s => OnDragEnd(s.pointerId, s.isSuccess)) .AddTo(this); } private void OnDragStart(int pointerId, string name) { var panel = Instantiate(itemPrefab, root, false); panel.gameObject.SetActive(true); panel.Text = name; AnimateAppear(panel); instances.Add(new DragAndDropInstance { pointerId = pointerId, panel = panel }); } private void OnDragEnd(int pointerId, bool isSuccess) { for (var i = 0; i < instances.Count; i++) { var instance = instances[i]; if (instance.pointerId != pointerId) continue; AnimateDisappear(instance.panel, isSuccess); instances.RemoveAt(i); return; } } private void Update() { for (var i = 0; i < instances.Count; i++) { var instance = instances[i]; DesktopUIInputModule.Instance.GetPointerData(instance.pointerId, out var pointer); MoveToPointerPosition(instance.panel, pointer.position); } } private void AnimateAppear(GenericText panel) { panel.RectTransform.localScale = Vector2.zero; panel.Group.alpha = 0; DOTween.Sequence() .Insert(0, panel.RectTransform.DOScale(Vector3.one, 0.25f)) .Insert(0, panel.Group.DOFade(1f, 0.25f)); } private void MoveToPointerPosition(GenericText panel, Vector2 position) { panel.RectTransform.localPosition = position; } private void AnimateDisappear(GenericText panel, bool isSuccess) { DOTween.Sequence() .Insert(0, panel.RectTransform.DOScale(isSuccess ? new Vector3(0.5f, 0.5f, 0.5f) : new Vector3(1.5f, 1.5f, 1.5f), 0.25f)) .Insert(0, panel.Group.DOFade(0f, 0.25f)) .OnComplete(() => Destroy(panel.gameObject)); } private struct DragAndDropInstance { public int pointerId; public GenericText panel; } } }
d5b96180a1cae0fd8068790d4de5794c48913bb7
C#
cosminprunaru/CSharpHackerRank
/Override II/Motorcycle.cs
3.375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Override_II { class Motorcycle : Bicycle { public Motorcycle() { Console.WriteLine("Hello, I am a motorcycle, I am {0}", define_me()); String temp = base.define_me(); Console.WriteLine("My ancestor is a cycle who is {0}", temp); } public new String define_me() { return "a cycle with an engine"; } } }
4e4a0d0d6e06629477844e1c414b8551751ad8af
C#
Shaurr/PartikelGame
/Assets/Scripts/EnemyTwo.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyTwo : EnemieController { protected GameObject player; // initializes public override void Initialize() { type = 1; gc = FindObjectOfType<GameController>(); player = gc.GetCurrentPlayer(); SearchTarget(); initialized = true; } // sets new target ecvery update public override void Update() { if (initialized) { SearchTarget(); base.Update(); } } // sets playerposition as target public override void SearchTarget() { float x = player.transform.position.x; float y = player.transform.position.y; target = new Vector3(x, y, 0); base.SearchTarget(); } // do nothing on collision public override void OnCollisionEnter2D(Collision2D collision) { } }
d632733f5a8aa7118fd36cfa9f9b54bab5d5b851
C#
kasparkallas/CodingBat
/CodingBat/Warmup2.cs
3.9375
4
using System; namespace CodingBat { public class Warmup2 { /// <summary> /// Given a string and a non-negative int n, return a larger string that is n copies of the original string. /// /// stringTimes("Hi", 2) → "HiHi" /// stringTimes("Hi", 3) → "HiHiHi" /// stringTimes("Hi", 1) → "Hi" /// </summary> public String stringTimes(String str, int n) { throw new NotImplementedException(); } /// <summary> /// Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. /// Return n copies of the front; /// /// frontTimes("Chocolate", 2) → "ChoCho" /// frontTimes("Chocolate", 3) → "ChoChoCho" /// frontTimes("Abc", 3) → "AbcAbcAbc" /// </summary> public String frontTimes(String str, int n) { throw new NotImplementedException(); } /// <summary> /// Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx". /// /// countXX("abcxx") → 1 /// countXX("xxx") → 2 /// countXX("xxxx") → 3 /// </summary> public int countXX(String str) { throw new NotImplementedException(); } /// <summary> /// Given a string, return true if the first instance of "x" in the string is immediately followed by another "x". /// /// doubleX("axxbb") → true /// doubleX("axaxax") → false /// doubleX("xxxxx") → true /// </summary> public bool doubleX(String str) { throw new NotImplementedException(); } /// <summary> /// Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo". /// /// stringBits("Hello") → "Hlo" /// stringBits("Hi") → "H" /// stringBits("Heeololeo") → "Hello" /// </summary> public String stringBits(String str) { throw new NotImplementedException(); } /// <summary> /// Given a non-empty string like "Code" return a string like "CCoCodCode". /// /// stringSplosion("Code") → "CCoCodCode" /// stringSplosion("abc") → "aababc" /// stringSplosion("ab") → "aab" /// </summary> public String stringSplosion(String str) { throw new NotImplementedException(); } /// <summary> /// Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring). /// /// last2("hixxhi") → 1 /// last2("xaxxaxaxx") → 1 /// last2("axxxaaxx") → 2 /// </summary> public int last2(String str) { throw new NotImplementedException(); } /// <summary> /// Given an array of ints, return the number of 9's in the array. /// /// arrayCount9([1, 2, 9]) → 1 /// arrayCount9([1, 9, 9]) → 2 /// arrayCount9([1, 9, 9, 3, 9]) → 3 /// </summary> public int arrayCount9(int[] nums) { throw new NotImplementedException(); } /// <summary> /// Given an array of ints, return true if one of the first 4 elements in the array is a 9. /// The array length may be less than 4. /// /// arrayFront9([1, 2, 9, 3, 4]) → true /// arrayFront9([1, 2, 3, 4, 9]) → false /// arrayFront9([1, 2, 3, 4, 5]) → false /// </summary> public bool arrayFront9(int[] nums) { throw new NotImplementedException(); } /// <summary> /// Given an array of ints, return true if the sequence of numbers 1, 2, 3 appears in the array somewhere. /// /// array123([1, 1, 2, 3, 1]) → true /// array123([1, 1, 2, 4, 1]) → false /// array123([1, 1, 2, 1, 2, 3]) → true /// </summary> public bool array123(int[] nums) { throw new NotImplementedException(); } /// <summary> /// Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. /// So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings. /// /// stringMatch("xxcaazz", "xxbaaz") → 3 /// stringMatch("abc", "abc") → 2 /// stringMatch("abc", "axc") → 0 /// </summary> public int stringMatch(String a, String b) { throw new NotImplementedException(); } /// <summary> /// Given a string, return a version where all the "x" have been removed. Except an "x" at the very start or end should not be removed. /// /// stringX("xxHxix") → "xHix" /// stringX("abxxxcd") → "abcd" /// stringX("xabxxxcdx") → "xabcdx" /// </summary> public String stringX(String str) { throw new NotImplementedException(); } /// <summary> /// Given a string, return a string made of the chars at indexes 0,1, 4,5, 8,9 ... so "kittens" yields "kien". /// /// altPairs("kitten") → "kien" /// altPairs("Chocolate") → "Chole" /// altPairs("CodingHorror") → "Congrr" /// </summary> public String altPairs(String str) { throw new NotImplementedException(); } /// <summary> /// Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap. /// /// stringYak("yakpak") → "pak" /// stringYak("pakyak") → "pak" /// stringYak("yak123ya") → "123ya" /// </summary> public String stringYak(String str) { throw new NotImplementedException(); } /// <summary> /// Given an array of ints, return the number of times that two 6's are next to each other in the array. /// Also count instances where the second "6" is actually a 7. /// /// array667([6, 6, 2]) → 1 /// array667([6, 6, 2, 6]) → 1 /// array667([6, 7, 2, 6]) → 1 /// </summary> public int array667(int[] nums) { throw new NotImplementedException(); } /// <summary> /// Given an array of ints, we'll say that a triple is a value appearing 3 times in a row in the array. Return true if the array does not contain any triples. /// /// noTriples([1, 1, 2, 2, 1]) → true /// noTriples([1, 1, 2, 2, 2, 1]) → false /// noTriples([1, 1, 1, 2, 2, 2, 1]) → false /// </summary> public bool noTriples(int[] nums) { throw new NotImplementedException(); } /// <summary> /// Given an array of ints, return true if it contains a 2, 7, 1 pattern: a value, followed by the value plus 5, followed by the value minus 1. Additionally the 271 counts even if the "1" differs by 2 or less from the correct value. /// /// has271([1, 2, 7, 1]) → true /// has271([1, 2, 8, 1]) → false /// has271([2, 7, 1]) → true /// </summary> public bool has271(int[] nums) { throw new NotImplementedException(); } } }
8df37c0c4adb57105856a49b418d3f78610934d6
C#
PacktPublishing/Learn-C-With-Visual-Studio-2017-and-Console-Programs
/Lesson26IfElseWithMethod/Lesson26IfElseWithMethod/Lesson26IfElseWithMethod/Program.cs
3.375
3
using static System.Console; class Program { static void Main() { string text = "hello"; string texToFind = "sd"; if (text.Contains(texToFind)) WriteLine($"{texToFind} found in {text}"); else WriteLine($"{texToFind} not found in {text}"); } }
286fabdd65dec4c343d6780f6d4ddb07f9cba4ed
C#
saper150/smutna-biedronka
/Services/MongoService.cs
2.65625
3
using System; using MongoDB.Driver; using Microsoft.Extensions.Configuration; using LanguageExt; using LanguageExt.DataTypes.Serialisation; public interface Try<T> { Either<Exception, U> Try<U>(Func<T, U> action); event Action<bool> databaseStatusChange; bool IsOnline { get; } } class TryMongoService : Try<IMongoDatabase> { IMongoDatabase db; public event Action<bool> databaseStatusChange; public bool IsOnline { get; private set; } = true; public TryMongoService() { this.db = new MongoClient("mongodb://localhost/analitics").GetDatabase("analytics"); } public Either<Exception, T> Try<T>(Func<IMongoDatabase, T> action) { try { var result = action(this.db); if (!IsOnline) { IsOnline = true; databaseStatusChange(true); } if (result == null) { return new Exception("Element not found"); } return result; } catch (System.Exception ex) { if (IsOnline) { IsOnline = false; databaseStatusChange(false); } return ex; } } }
95d3a24fb9228636f9fa29d237ffb31158e96bef
C#
radomirKrastev/OOP
/Old Exams/14 April 2019/Skeleton/MortalEngines/Entities/Models/Fighter.cs
3.109375
3
namespace MortalEngines.Entities.Models { using System.Text; using Contracts; public class Fighter : BaseMachine, IFighter { private const double InitialHealthPoints = 200; private bool aggressiveMode = true; public Fighter(string name, double attackPoints, double defencePoints) : base(name, attackPoints, defencePoints, InitialHealthPoints) { this.AdjustStatsDependingOnAgression(); } public bool AggressiveMode => this.aggressiveMode; public void ToggleAggressiveMode() { if (this.AggressiveMode) { this.aggressiveMode = false; } else { this.aggressiveMode = true; } this.AdjustStatsDependingOnAgression(); } public override string ToString() { StringBuilder output = new StringBuilder(); output.AppendLine(base.ToString()); string agressionStatus = this.AggressiveMode ? "ON" : "OFF"; output.AppendLine($" *Aggressive: {agressionStatus}"); return output.ToString().TrimEnd(); } private void AdjustStatsDependingOnAgression() { if (this.AggressiveMode) { this.AttackPoints += 50; this.DefensePoints -= 25; } else { this.DefensePoints += 25; this.AttackPoints -= 50; } } } }
4fde9207760276b88acddd05366bfee1f7ca5a9a
C#
cahue129/DataStructures
/SinglyLinkedList/SinglyLinkedList/Program.cs
3.78125
4
using System; namespace SinglyLinkedList { public class Node { public string data; public Node next; public Node() { this.data = null; this.next = null; } public Node(string data) { this.data = data; this.next = null; } } public class List { public Node head; int count; public List() { this.head = null; } public void AddNodeToFront(string data) { Node newNode = new Node(data); newNode.next = head; // head = newNode; count++; } public void AddNodeToEnd(string data) { Node newNode = new Node(data); Node runner = new Node(); runner = head; while (runner!=null) { if (runner.next==null) { runner.next = newNode; break; } runner = runner.next; } } //delete front public void DeleteFromFront() { Node tmp = new Node(); tmp = head; head = head.next; Delete(tmp); } //find and delete node public void FindAndDelete(String data) { Node runner = new Node(); Node trailer = new Node(); runner = head; trailer = head; while (runner != null) { if (runner.data == data) { trailer.next = runner.next; Delete(runner); break; } trailer = runner; runner = runner.next; } } //Delete from end public void DeleteFromEnd() { Node runner = new Node(); Node trailer = new Node(); runner = head; trailer = head; while (runner != null) { if (runner.next==null) { trailer.next = null; Delete(runner); break; } trailer = runner; runner = runner.next; } } public void Print() { Node runner = new Node(); runner = head; while (runner != null) { Console.WriteLine(runner.data); runner = runner.next; } } public void Delete(Node tmp) { tmp = null; } } class Program { static void Main(string[] args) { List myList = new List(); Console.WriteLine(); myList.AddNodeToFront("0"); myList.AddNodeToFront("1"); myList.AddNodeToFront("2"); myList.AddNodeToFront("3"); myList.AddNodeToFront("5"); myList.Print(); Console.WriteLine(); myList.DeleteFromEnd(); myList.Print(); Console.WriteLine(); } } }
95468adfcadc6d12c4478036939299fa4a4d43d0
C#
ChrisDill/Raylib-cs
/Examples/Shapes/ColorsPalette.cs
2.578125
3
/******************************************************************************************* * * raylib [shapes] example - Colors palette * * This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * * Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * ********************************************************************************************/ using System.Numerics; using static Raylib_cs.Raylib; namespace Examples.Shapes; public class ColorsPalette { public static int Main() { // Initialization //-------------------------------------------------------------------------------------- const int screenWidth = 800; const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - colors palette"); Color[] colors = new[] { Color.DARKGRAY, Color.MAROON, Color.ORANGE, Color.DARKGREEN, Color.DARKBLUE, Color.DARKPURPLE, Color.DARKBROWN, Color.GRAY, Color.RED, Color.GOLD, Color.LIME, Color.BLUE, Color.VIOLET, Color.BROWN, Color.LIGHTGRAY, Color.PINK, Color.YELLOW, Color.GREEN, Color.SKYBLUE, Color.PURPLE, Color.BEIGE }; string[] colorNames = new[] { "DARKGRAY", "MAROON", "ORANGE", "DARKGREEN", "DARKBLUE", "DARKPURPLE", "DARKBROWN", "GRAY", "RED", "GOLD", "LIME", "BLUE", "VIOLET", "BROWN", "LIGHTGRAY", "PINK", "YELLOW", "GREEN", "SKYBLUE", "PURPLE", "BEIGE" }; // Rectangles array Rectangle[] colorsRecs = new Rectangle[colors.Length]; // Fills colorsRecs data (for every rectangle) for (int i = 0; i < colorsRecs.Length; i++) { colorsRecs[i].X = 20 + 100 * (i % 7) + 10 * (i % 7); colorsRecs[i].Y = 80 + 100 * (i / 7) + 10 * (i / 7); colorsRecs[i].Width = 100; colorsRecs[i].Height = 100; } // Color state: 0-DEFAULT, 1-MOUSE_HOVER int[] colorState = new int[colors.Length]; Vector2 mousePoint = new(0.0f, 0.0f); SetTargetFPS(60); //-------------------------------------------------------------------------------------- // Main game loop while (!WindowShouldClose()) { // Update //---------------------------------------------------------------------------------- mousePoint = GetMousePosition(); for (int i = 0; i < colors.Length; i++) { if (CheckCollisionPointRec(mousePoint, colorsRecs[i])) { colorState[i] = 1; } else { colorState[i] = 0; } } //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- BeginDrawing(); ClearBackground(Color.RAYWHITE); DrawText("raylib colors palette", 28, 42, 20, Color.BLACK); DrawText( "press SPACE to see all colors", GetScreenWidth() - 180, GetScreenHeight() - 40, 10, Color.GRAY ); // Draw all rectangles for (int i = 0; i < colorsRecs.Length; i++) { DrawRectangleRec(colorsRecs[i], ColorAlpha(colors[i], colorState[i] != 0 ? 0.6f : 1.0f)); if (IsKeyDown(KeyboardKey.KEY_SPACE) || colorState[i] != 0) { DrawRectangle( (int)colorsRecs[i].X, (int)(colorsRecs[i].Y + colorsRecs[i].Height - 26), (int)colorsRecs[i].Width, 20, Color.BLACK ); DrawRectangleLinesEx(colorsRecs[i], 6, ColorAlpha(Color.BLACK, 0.3f)); DrawText( colorNames[i], (int)(colorsRecs[i].X + colorsRecs[i].Width - MeasureText(colorNames[i], 10) - 12), (int)(colorsRecs[i].Y + colorsRecs[i].Height - 20), 10, colors[i] ); } } EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization //-------------------------------------------------------------------------------------- CloseWindow(); //-------------------------------------------------------------------------------------- return 0; } }
cb3717f5f6f2e98d05f2c2f6701e069eea36be51
C#
KajulNisha-21/demo
/CustomAuthorize.cs
2.609375
3
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Webapi_Microservices_Docker { public class CustomAuthorize:ActionFilterAttribute { public CustomAuthorize():base() { } public override void OnActionExecuted(ActionExecutedContext context) { var headers = context.HttpContext.Request.Headers; bool isAuthorized = false; if (headers.Keys.Contains("auth_key")) { var header = headers.FirstOrDefault(x => x.Key == "auth_key").Value.FirstOrDefault(); if(header!=null) { isAuthorized = string.Equals(header,"core"); } } if (!isAuthorized) { context.Result = new ContentResult() { Content="Authorization has been denied !!", ContentType = "text/plain", StatusCode=401 }; } } } }
786cc50244edd092c07ca0267e9a8687dbdd10b6
C#
szymszer/CSteganography
/CSteganography/Form1.cs
2.578125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Collections; using System.IO; namespace CSteganography { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void load_Click(object sender, EventArgs e) { OpenFileDialog openDialog = new OpenFileDialog(); openDialog.Filter = "BMP Images (*.bmp, *.jpg, *.png) | *.bmp; *.jpg; *.png"; if(openDialog.ShowDialog() == DialogResult.OK) { filepath.Text = openDialog.FileName.ToString(); pictureBox1.ImageLocation = filepath.Text; Bitmap img = new Bitmap(filepath.Text); long length = new System.IO.FileInfo(filepath.Text).Length; ImageInfo.Text = (String.Join(Environment.NewLine, img.Size.ToString(), "Pixels: " + (img.Width * img.Height).ToString(), "Size: " + length + " bytes", "Format:" + Path.GetExtension(filepath.Text) )); msg_find(); capacity.Text = "Capacity: " + ((((img.Width * img.Height)-8) * 3 * (lsb_bit.Value)) / 8).ToString() + " bytes"; //button enable b_encode.Enabled = true; b_decode.Enabled = true; b_show_bits.Enabled = true; lsb_bit.Enabled = true; textBox1.Enabled = true; //clear text textBox1.Text = null; decode_bits.Text = null; decode_text.Text = null; } } public int bit_set(string s, int pixel, int bit) { int c = pixel; if (s == "1") { c |= (1 << bit); } else if (s == "0") { c &= ~(1 << bit); } return c; } public bool bit_read(int pixel, int bit) { bool a = (pixel & (1 << bit)) != 0; return a; } public int msg_find() { int msg_length = 0; Bitmap img = new Bitmap(filepath.Text); string s = ""; string result = ""; for (int i = 8; i > 0; i--) { Color pixel = img.GetPixel(img.Width - i, img.Height - 1); s += Convert.ToByte(bit_read(pixel.R, 1)); s += Convert.ToByte(bit_read(pixel.R, 0)); s += Convert.ToByte(bit_read(pixel.G, 1)); s += Convert.ToByte(bit_read(pixel.G, 0)); s += Convert.ToByte(bit_read(pixel.B, 1)); s += Convert.ToByte(bit_read(pixel.B, 0)); } int a1 = Convert.ToInt32(s.Substring(0, 8), 2); s = s.Substring(8); int a11 = Convert.ToInt32(s.Substring(0, 8), 2); s = s.Substring(8); int a2 = Convert.ToInt16(s.Substring(0, 16), 2); s = s.Substring(16); int a3 = Convert.ToInt32(s.Substring(0, 8), 2); s = s.Substring(8); int a33 = Convert.ToInt32(s.Substring(0, 8), 2); // '|' char id 124 if (a1=='B') { result += (char)a1; result += (char)a11; result += (short)a2; result += (char)a3; result += (char)a33; lsb_info.Text = Convert.ToString(result); //lsb_info.Text = Convert.ToString(result) + " Bytes encoded"; msg_length = a2; } else { lsb_info.Text = "No Secret Message Here."; } return msg_length*8; } private void ImageInfo_TextChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { Bitmap img = new Bitmap(filepath.Text); SaveFileDialog saveFile = new SaveFileDialog(); saveFile.Filter = "Image Files (*.bmp, *.jpg, *.png) | *.bmp; *.png; *.jpg"; if (message.Text == "") { bits.Text = "Nothing to encode."; return; } string vv = string.Join("", Encoding.UTF8.GetBytes(message.Text).Select(n => Convert.ToString(n, 2).PadLeft(8, '0'))); string[] msg = vv.ToCharArray().Select(c => c.ToString()).ToArray(); if (Convert.ToInt32(textlength.Text) > ((((img.Width * img.Height)-8) * 3 * (lsb_bit.Value + 1)) / 8)) { bits.Text = "Message too long."; return; } int msg_c = 0; int r, g, b; int l = Convert.ToInt16(lsb_bit.Value-1); for (int i = 0; i < img.Height; i++) { for (int j = 0; j < img.Width; j++) { Color pixel = img.GetPixel(j, i); r = pixel.R; for (int n = l; n >= 0; n--) { if (msg_c < msg.Length) r = bit_set(msg[msg_c++], r, n); else { //var random = new Random(); //string test = Convert.ToString(random.Next(0, 2)); msg_c = 0; r = bit_set(msg[msg_c++], r, n); } } g = pixel.G; for (int n = l; n >= 0; n--) { if (msg_c < msg.Length) g = bit_set(msg[msg_c++], g, n); else { //var random = new Random(); //string test = Convert.ToString(random.Next(0, 2)); //g = bit_set(test, g, n); msg_c = 0; r = bit_set(msg[msg_c++], r, n); } } b = pixel.B; for (int n = l; n >= 0; n--) { if (msg_c < msg.Length) b = bit_set(msg[msg_c++], b, n); else { //var random = new Random(); //string test = Convert.ToString(random.Next(0, 2)); //b = bit_set(test, b, n); msg_c = 0; r = bit_set(msg[msg_c++], r, n); } } img.SetPixel(j, i, Color.FromArgb(r, g, b)); } if (msg_c > msg.Length) break; } /////////////////// LAST 8 BITS - lenght info short a2 = 0; string a1, a11, a3, a33, a22; a2 = Convert.ToInt16(message.TextLength); a1 = "B" + Convert.ToString(lsb_bit.Value); a3 = "FF"; //decode_bits.Text = (Convert.ToString(a2, 2).PadLeft(16, '0')); a11 = string.Join("", Encoding.UTF8.GetBytes(a1).Select(n => Convert.ToString(n, 2).PadLeft(8, '0'))); a22 = (Convert.ToString(a2, 2).PadLeft(16, '0')); a33 = string.Join("", Encoding.UTF8.GetBytes(a3).Select(n => Convert.ToString(n, 2).PadLeft(8, '0'))); //string x = string.Join("", Encoding.UTF8.GetBytes(z).Select(n => Convert.ToString(n, 2).PadLeft(8, '0'))); string x = a11 + a22 + a33; string[] zx = x.ToCharArray().Select(c => c.ToString()).ToArray(); // B = 00000000 [0-7] = 00000000 lp = [00000000 00000000] format = [00000000 00000000] (BM/JP/PN/TX/FF...) int counter = 0; for (int i = 8; i > 0; i--) { Color pixel = img.GetPixel(img.Width - i, img.Height - 1); r = pixel.R; g = pixel.G; b = pixel.B; r = bit_set(zx[counter++], r, 1); r = bit_set(zx[counter++], r, 0); g = bit_set(zx[counter++], g, 1); g = bit_set(zx[counter++], g, 0); b = bit_set(zx[counter++], b, 1); b = bit_set(zx[counter++], b, 0); img.SetPixel(img.Width-i, img.Height-1 , Color.FromArgb(r, g, b)); } /////////////////////// //SAVE if (saveFile.ShowDialog() == DialogResult.OK) { filepath.Text = saveFile.FileName.ToString(); pictureBox1.ImageLocation = filepath.Text; img.Save(filepath.Text); } } private void button1_Click(object sender, EventArgs e) { } private void b_save_Click(object sender, EventArgs e) { FileStream fs = new FileStream(t_p.Text, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; message.Text = ""; for (int i = 0; i < 10; i++) { int bytesread = fs.Read(buffer, 0, buffer.Length); message.Text += Encoding.ASCII.GetString(buffer, 0, bytesread); } fs.Close(); } private void b_decode_Click(object sender, EventArgs e) { decode_bits.Enabled = true; decode_text.Enabled = true; Bitmap img = new Bitmap(filepath.Text); BitArray bitArray = new BitArray(bits.TextLength); decode_bits.Text = ""; int msg_len = 0; if (decode_length.Text != "") msg_len = Convert.ToInt32(decode_length.Text)*8; else msg_len = msg_find(); int c = 0; int lsb = Convert.ToInt16(lsb_bit.Value-1); string rr="", gg="", bb=""; for (int i = 0; i < img.Height; i++) { if (c > msg_len) break; for (int j = 0; j< img.Width; j++) { if (c > msg_len) break; Color pixel = img.GetPixel(j, i); for (int n = lsb; n >= 0; n--) { var r = bit_read(pixel.R, n); var g = bit_read(pixel.G, n); var b = bit_read(pixel.B, n); c += 3; rr += Convert.ToByte(r); gg += Convert.ToByte(g); bb += Convert.ToByte(b); } decode_bits.Text += rr; decode_bits.Text += gg; decode_bits.Text += bb; rr = gg = bb = ""; } } //decode_bits.Text = decode_bits.Text.Substring(0, msg_len); string s = decode_bits.Text; //string result = ""; decode_text.Text = ""; while (s.Length >= 8) { var first8 = s.Substring(0, 8); s = s.Substring(8); var number = Convert.ToInt32(first8, 2); //result += (char)number; decode_text.Text += Convert.ToString((char)number); } } private void textBox1_TextChanged(object sender, EventArgs e) { } private void message_TextChanged(object sender, EventArgs e) { textlength.Text = Convert.ToString(message.TextLength); // bits.Text = string.Join("", Encoding.UTF8.GetBytes(message.Text).Select(n => Convert.ToString(n, 2).PadLeft(8, '0'))); // bits.Enabled = true; } private void tobit_Click(object sender, EventArgs e) { bits.Text = string.Join("", Encoding.UTF8.GetBytes(message.Text).Select(n => Convert.ToString(n, 2).PadLeft(8, '0'))); } private void show_bits_Click(object sender, EventArgs e) { Bitmap img = new Bitmap(filepath.Text); textBox1.Text = null; string[] pad = { "0000000 0", "000000 00", "00000 000", "0000 0000", "000 00000", "00 000000", "0 0000000", "00000000" }; for (int i = 0; i < img.Height; i++) { for (int j = 0; j < img.Width; j++) { Color pixel = img.GetPixel(j, i); if (i < 10 && j < 10) { textBox1.Text += (String.Join(Environment.NewLine, Int32.Parse(Convert.ToString(pixel.R, 2)).ToString(pad[Convert.ToInt32(lsb_bit.Value-1)]) + " | " + Int32.Parse(Convert.ToString(pixel.G, 2)).ToString(pad[Convert.ToInt32(lsb_bit.Value-1)]) + " | " + Int32.Parse(Convert.ToString(pixel.B, 2)).ToString(pad[Convert.ToInt32(lsb_bit.Value-1)]), "")); } } } } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged_1(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void bits_TextChanged(object sender, EventArgs e) { } private void lsb_info_TextChanged(object sender, EventArgs e) { } private void decode_lsb_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged_2(object sender, EventArgs e) { } private void lsb_bit_ValueChanged(object sender, EventArgs e) { Bitmap img = new Bitmap(filepath.Text); textBox1.Text = null; capacity.Text = "Capacity: " + (((img.Width * img.Height * 3 * (lsb_bit.Value))/8)-3).ToString()+" bytes"; string[] pad = { "0000000 0", "000000 00", "00000 000", "0000 0000", "000 00000", "00 000000", "0 0000000", "00000000" }; for (int i = 0; i < img.Height; i++) { for (int j = 0; j < img.Width; j++) { Color pixel = img.GetPixel(j, i); if (i < 10 && j < 10) { textBox1.Text += (String.Join(Environment.NewLine, Int32.Parse(Convert.ToString(pixel.R, 2)).ToString(pad[Convert.ToInt32(lsb_bit.Value-1)]) + " | " + Int32.Parse(Convert.ToString(pixel.G, 2)).ToString(pad[Convert.ToInt32(lsb_bit.Value-1)]) + " | " + Int32.Parse(Convert.ToString(pixel.B, 2)).ToString(pad[Convert.ToInt32(lsb_bit.Value-1)]), "")); } } } } private void capacity_TextChanged(object sender, EventArgs e) { } private void t_l_Click(object sender, EventArgs e) { OpenFileDialog openDialog = new OpenFileDialog(); openDialog.Filter = "Any file (*.txt, *.bmp, *.jpg) | *.txt; *.bmp; *.jpg; *.png"; if (openDialog.ShowDialog() == DialogResult.OK) { t_p.Text = openDialog.FileName.ToString(); FileStream fs = new FileStream(t_p.Text, FileMode.Open, FileAccess.Read); //byte[] buffer = new byte[1024]; message.Text = ""; byte[] buff = File.ReadAllBytes(t_p.Text); //for (int i = 0; i < 10; i++) //while(byte [] buff = File.ReadAllBytes(t_p.Text); // { // int bytesread = fs.Read(buffer, 0, buffer.Length); message.Text += Encoding.ASCII.GetString(buff); //} fs.Close(); } //message.Text = Encoding.ASCII.GetString(File.ReadAllBytes(t_p.Text)); } private void filepath_TextChanged(object sender, EventArgs e) { } private void t_p_TextChanged(object sender, EventArgs e) { } private void mab_Click(object sender, EventArgs e) { bits.Text = string.Join("", Encoding.UTF8.GetBytes(message.Text).Select(n => Convert.ToString(n, 2).PadLeft(8, '0'))); } } }
d0a2b5ba5188c1ae83e474f35e21a62956e51c3a
C#
huashi0103/CSharpTest
/CSharpTest/Program.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Globalization; using System.Text.RegularExpressions; using WinDraw; using System.Diagnostics; using System.Threading; using System.Net.NetworkInformation; using System.Threading.Tasks; using System.Data.SqlClient; using System.Reflection; namespace CSharpTest { public class Mine { public int[,] Set(int r,int c,int hard) { int[,] data = new int[r,c]; Random rd=new Random(); for (int i = 0; i < r*c; i++) { data[i / c, i % c] = rd.Next(hard) == 1 ? 1 : 0; } return data; } public int[,] GetNewData(int[,] data) { int r = data.GetLength(0); int c= data.GetLength(1); int[,] newdata = new int[r, c]; for (int i = 0; i < r * c; i++) { if (data[i / c, i % c] == 1) { newdata[i / c, i % c] = 9; } else { int d = 0; for (int j = 0; j < 9; j++) { if (i / c + (j / 3 - 1)>=0 && i % c + (j % 3 - 1) >= 0 && i / c + (j / 3 - 1) < r && i % c + (j % 3 - 1) < c && data[i / c + (j / 3 - 1), i % c + (j % 3 - 1)] == 1) { d++; } } newdata[i / c, i % c] = d; } } return newdata; } } delegate void testDelegate(object s); [Serializable] class Program { public class Node { public int NodeData; public Node LeftChild; public Node RightChild; } public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode (int x) { val = x; } } static bool check() { int[][] array = new int[4][] { new[] { 1, 5, 9, 13 }, new[] { 2, 6, 10, 14, 20, 30 }, new[] { 3, 7, 11, 15 }, new[] { 4, 8, 12, 16, 21 } }; int a = 20; Node tree = null; Action<int> func = null; func = (b) => { Node Parent; var newNode = new Node() { NodeData = b }; if (tree == null) { tree = newNode; } else { Node Current = tree; while (true) { Parent = Current; if (newNode.NodeData < Current.NodeData) { Current = Current.LeftChild; if (Current == null) { Parent.LeftChild = newNode; break; } } else { Current = Current.RightChild; if (Current == null) { Parent.RightChild = newNode; //插入叶子后跳出循环 break; } } } } }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array[i].Length; j++) { func(array[i][j]); } } var current = tree; if (current == null) return false; while (true) { if (a < current.NodeData) { if (current.LeftChild == null) break; current = current.LeftChild; } else if (a > current.NodeData) { if (current.RightChild == null) break; current = current.RightChild; } else { return true; } } return false; }     static TreeNode reConstructBinaryTree(int [] pre,int [] tin) { TreeNode root = reConstructBinaryTree(pre, 0, pre.Length - 1, tin, 0, tin.Length - 1);          return root;      }      //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}      static TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] tin,int startIn,int endIn) {                    if(startPre>endPre||startIn>endIn)              return null;          TreeNode root=new TreeNode(pre[startPre]); for (int i = startIn; i <= endIn; i++) { if (tin[i] == pre[startPre]) { root.left = reConstructBinaryTree(pre, startPre + 1, startPre + i - startIn, tin, startIn, i - 1); root.right = reConstructBinaryTree(pre, i - startIn + startPre + 1, endPre, tin, i + 1, endIn); } }          return root;      } static double calc() { double b = 1.4; double p = 0.25; double g = 0.39526; double zs = 0.2070; double H0 = 0.2720; double Q1 = 50; while(true) { double H = (zs - 0.4361) * g + H0; double deltg = b * (H + p); double v = (Q1 / 1000.0) / deltg; double I=H + Math.Pow(v, 2) / (2 * 9.81); double F = 0.627 + 0.018 * I / p; double Q2 = F * 2 * Math.Sqrt(2 * 9.81) * b * Math.Pow(I, 1.5) * 1000 / 3; if (Math.Abs(Q2 - Q1) < 0.01) { Q1 = Q2; break; } else { Q1 = Q2; } } return Q1; } public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } } static void func(string s) { Console.WriteLine(s); } static int sum(int n) { if (n <= 0) return 0; return n + sum(n - 1); } static void OldTest() { string filepath = @"D:\Desktop\MWXC08配置表.doc"; CSWord csword = null; List<MCU> datas = new List<MCU>(); try { csword = new CSWord(filepath, true); datas = csword.test(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (csword != null) csword.Dispose(); } Console.WriteLine("read over"); CSqlServerHelper.Connectionstr = @"Data Source =DESKTOP-9SCR28N\SQLEXPRESS12;Initial Catalog = MWDatabase;User ID = sa;Password = 123;"; CSqlServerHelper sqlhelper = CSqlServerHelper.GetInstance(); foreach (MCU mcu in datas) { Console.Write(mcu.ToString()); foreach (var point in mcu.SurveyPoint) { if (string.IsNullOrEmpty(point.Value)) continue; sqlhelper.DoPROCEDURE("update_Auto_Points", new SqlParameter("Survey_point_number", point.Value), new SqlParameter("MCU_Station", mcu.mcustation.Split('-')[0]), new SqlParameter("MCU_Number", mcu.mcustation), new SqlParameter("CJ_Number", point.Key), new SqlParameter("IP", mcu.IP)); } } } static void TestDom() { AppDomain appDomain = AppDomain.CreateDomain("testdom"); string path = "DomainTest.dll"; byte[] fsContent; using (FileStream fs = File.OpenRead(path)) { fsContent = new byte[fs.Length]; fs.Read(fsContent, 0, fsContent.Length); } appDomain.DoCallBack(() => { AppDomain cur = AppDomain.CurrentDomain; Console.WriteLine(cur.FriendlyName); Object obj = cur.CreateInstanceAndUnwrap("DomainTest", "DomainTest.TestClass"); var type = obj.GetType(); MethodInfo method = type.GetMethod("SayHi"); var res = method.Invoke(obj, new string[] { }); Console.WriteLine(res as string); var data = cur.GetData("AppData"); Console.WriteLine(data as string); }); AppDomain.Unload(appDomain); } static void w(string msg) { Console.WriteLine(msg); } static void w(string msg, params object[] msgs) { Console.WriteLine(string.Format(msg, msgs)); } static void Main(string[] args) { AutoResetEvent autoReset = new AutoResetEvent(false); Thread t1 = new Thread(() => { autoReset.WaitOne(); w("{0}:{1}","t1", DateTime.Now.ToString()); }); t1.Start(); Thread t2 = new Thread(() => { w("{0}:{1}", "t2", DateTime.Now.ToString()); Thread.Sleep(1000); autoReset.Set(); }); t2.Start(); int stat = 0; if(Interlocked.Exchange(ref stat, 1)==0) { } Console.WriteLine("OK"); Console.ReadLine(); } } }
924961468c0aad709d4bfcd0510092db0944bbfd
C#
OwenVanRijn/1.1-Programmeren
/week2/ProgrammerenWeek2/Opdracht2/Program.cs
3.296875
3
using System; namespace Opdracht_ { class Program { static void Main(string[] args) { double[] getallen = new double[3]; double result; string input; for (int i = 0; i < 3; i++) { Console.Write("Geef getal {0}: ", i + 1); input = Console.ReadLine(); getallen[i] = int.Parse(input); } result = (getallen[0] + getallen[1] + getallen[2]) / 3; Console.Write("\nGemiddelde: {0}\n", result); Console.ReadKey(); } } }
06074ee88174d366306254010952f35c3c464b99
C#
ParallelTask/DesignPatterns
/ChainOfResponsibilityPattern/ChainOfResponsibilityPattern/Factory/Program.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChainOfResponsibilityPattern.Factory { // When using a factory your code is still actually responsible for creating objects. // By DI you outsource that responsibility to another class or a framework, which is separate from your code // Factory pattern can be called as a tool to implement DI // Refer: https://stackoverflow.com/questions/557742/dependency-injection-vs-factory-pattern // Refer: https://softwareengineering.stackexchange.com/questions/337413/what-does-it-mean-when-one-says-encapsulate-what-varies // the creation of one interface called IPerson and two implementations called Villager and CityPerson. // Based on the type passed into the Factory object, we are returning the concrete object as IPerson. // Refer: https://en.wikipedia.org/wiki/Factory_method_pattern // Refer: https://softwareengineering.stackexchange.com/questions/81838/what-is-the-difference-between-the-factory-pattern-and-abstract-factory public class Program { public static void Run() { IDBFactory factory = new DBFactory(); IDBConnector sql = factory.GetDatabase("SQL"); IDBConnector oracle = factory.GetDatabase("ORACLE"); sql.Connect(); oracle.Connect(); sql.ExecuteQuery(); oracle.ExecuteQuery(); } } }
05cd9e57cd53a12ddaf8a31f4908a8f2347496ff
C#
keke8273/PrismSample
/QBR.Infrastructure/ValidationRules/GenericRangeCheck.cs
3.125
3
using System; using System.ComponentModel; using System.Globalization; using System.Windows.Controls; namespace QBR.Infrastructure.ValidationRules { public class GenericRangeCheck<T> : ValidationRule where T: IComparable { public T Max { get; set; } public T Min { get; set; } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if(string.IsNullOrEmpty((string)value)) { return new ValidationResult(false, "Field cannot be empty"); } try { var converter = TypeDescriptor.GetConverter(typeof(T)); var parsedValue = (T)converter.ConvertFromString((string)value); if (parsedValue.CompareTo(Max) > 0 || parsedValue.CompareTo(Min) < 0) return new ValidationResult(false, string.Format("Enter a value between {0} and {1}.", Min, Max)); } catch (Exception) { return new ValidationResult(false, "Illegal characters: " + (string)value); } return ValidationResult.ValidResult; } } }
c5d2316c58536886ed50bbce21164ba092780029
C#
daveac99/CycleFinder
/CycleFinder/Models/Wave.cs
2.71875
3
using System; using System.Collections.Generic; namespace CycleFinder.Models { public class Wave { public Wave(double period, double amplitude, string colour = "black") { Period = period; //years Amplitude = amplitude; Colour = colour; } public double Frequency { get; set; } public double Period { get; set; } public double Amplitude { get; set; } public string Colour { get; set; } public double TimeSpan { get; set; } } }
98318653bf63f5a5ee67009c8faf1de3613628a0
C#
ligaz/MicroModels
/Source/MicroModels/Description/ReflectPropertyDescriptor.cs
2.59375
3
using System; using System.Globalization; using System.Reflection; namespace MicroModels.Description { internal class ReflectPropertyDescriptor : PropertyDescriptor { private readonly MethodInfo getMethod; private readonly MethodInfo setMethod; private readonly Type propertyType; private readonly Type componentType; public ReflectPropertyDescriptor(Type componentType, string name, Type propertyType, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : base(name, attrs) { this.componentType = componentType; this.propertyType = propertyType; this.getMethod = getMethod; this.setMethod = setMethod; } public override Type PropertyType { get { return this.propertyType; } } public override Type ComponentType { get { return this.componentType; } } public override bool IsReadOnly { get { return this.setMethod == null; } } public override object GetValue(object component) { if (component == null) return null; try { return this.getMethod.Invoke(component, null); } catch (Exception getValueError) { if (getValueError is TargetInvocationException) { getValueError = getValueError.InnerException; } string message = getValueError.Message; if (message == null) { message = getValueError.GetType().Name; } throw new TargetInvocationException( string.Format(CultureInfo.InvariantCulture, "Could not get the value of property '{0}' value!\nError:\n{1}", this.Name, message), getValueError); } } public override void SetValue(object component, object value) { if (this.setMethod != null) { this.setMethod.Invoke(component, new[] { value }); } } public override bool CanResetValue(object component) { return false; } public override void ResetValue(object component) { throw new NotImplementedException(); } public override bool ShouldSerializeValue(object component) { return false; } } }
5046615711afd811c6adc4f36ba079006af8129c
C#
dotnet/runtime
/src/installer/tests/Assets/TestProjects/HammerServiceApp/Program.cs
2.796875
3
using System; using System.Reflection; namespace hammer { class Program { static void Main(string[] args) { var asm = Assembly.Load("Location, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); var location = asm.GetType("GPS.Location"); var city = location.GetProperty("City"); var cityName = city.GetValue(null); Console.WriteLine($"Hi {cityName}!"); } } }
619090fcfa6fed69bd73f4de32d9ff926567f89c
C#
WadeJr/fun-and-random
/TCP/Client/client.cs
2.8125
3
using SimpleTCP; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.Net; using System.Net.Sockets; using System.IO; namespace Client { public partial class client : Form { public static string ip = "192.168.0.10"; public static string port = "8910"; public client() { InitializeComponent(); } private void client_Load(object sender, EventArgs e) { txtHost.Text = ip; txtPort.Text = port; } private void btnConnect_Click(object sender, EventArgs e) { Thread mThread = new Thread(new ThreadStart(ConnectAsClient)); mThread.Start(); ScrollToBottom(); } private void ConnectAsClient() { try { TcpClient client = new TcpClient(); client.Connect(IPAddress.Parse(txtHost.Text), Convert.ToInt32(txtPort.Text)); updateUI("Connected to server."); NetworkStream stream = client.GetStream(); string s = "Client is connected"; byte[] message = Encoding.ASCII.GetBytes(s + System.Environment.NewLine); stream.Write(message, 0, message.Length); stream.Close(); client.Close(); } catch (Exception) { MessageBox.Show("Failed to connect to server."); } } private void btnSend_Click(object sender, EventArgs e) { Thread mThread = new Thread(new ThreadStart(SendMessageToServer)); mThread.Start(); ScrollToBottom(); } private void SendMessageToServer(string text) { try { TcpClient client = new TcpClient(); client.Connect(IPAddress.Parse(txtHost.Text), Convert.ToInt32(txtPort.Text)); updateUI("Message Sent."); NetworkStream stream = client.GetStream(); byte[] message = Encoding.ASCII.GetBytes(text + System.Environment.NewLine); stream.Write(message, 0, message.Length); stream.Close(); client.Close(); } catch (Exception) { MessageBox.Show("Failed to send message to server."); } } private void SendMessageToServer() { try { TcpClient client = new TcpClient(); client.Connect(IPAddress.Parse(txtHost.Text), Convert.ToInt32(txtPort.Text)); updateUI("Message Sent."); NetworkStream stream = client.GetStream(); byte[] message = Encoding.ASCII.GetBytes(txtMessage.Text + System.Environment.NewLine); stream.Write(message, 0, message.Length); stream.Close(); client.Close(); } catch (Exception) { MessageBox.Show("Failed to send message to server."); } } private void updateUI(string s) { Func<int> del = delegate () { txtStatus.AppendText(s + System.Environment.NewLine); return 0; }; Invoke(del); } private void ScrollToBottom() { txtStatus.SelectionStart = txtStatus.TextLength; txtStatus.ScrollToCaret(); } } } /* * SimpleTcpClient Client; public static string ip = "172.16.121.64"; public static string port = "8910"; public client() { InitializeComponent(); } private void client_Load(object sender, EventArgs e) { Client = new SimpleTcpClient(); Client.StringEncoder = Encoding.UTF8; Client.DataReceived += Client_DataRecieved; txtHost.Text = ip; txtPort.Text = port; } private void Client_DataRecieved(object sender, SimpleTCP.Message e) { txtStatus.Invoke((MethodInvoker)delegate () { txtStatus.Text += e.MessageString.Trim(); }); } private void btnConnect_Click(object sender, EventArgs e) { btnConnect.Enabled = false; Client.Connect(txtHost.Text, Convert.ToInt32(txtPort.Text)); Client.WriteLine("Client Connected." + "\r\n"); } private void btnSend_Click(object sender, EventArgs e) { string message = txtMessage.Text + "\r\n"; message.Trim(); Client.WriteLine("this is message: " + message); Client.WriteLine("This is just write line: " + txtMessage.Text + "\r\n"); // Client.WriteLineAndGetReply(txtMessage.Text + "\r\n", TimeSpan.FromSeconds(1)); } */
ad4afd551f7b5966544ebfade077370f40ae2798
C#
Ivan1Kot/1410b
/Assets/Scripts/GamePlay/Enemy/EnemyMoveManager.cs
2.609375
3
using System.Collections.Generic; using UnityEngine; public class EnemyMoveManager : MonoBehaviour { #region Fields #region Serialize Fields [SerializeField] private InvisiblePoint[] pointsQueueInic; #endregion #region Private Fields private Queue<InvisiblePoint> points; private InvisiblePoint activePoint; #endregion #region Public Fields public delegate void NewPoint(InvisiblePoint newPoint); public event NewPoint changePoint; public static EnemyMoveManager instance { get; private set; } #endregion #endregion #region Properties public InvisiblePoint ActivePoint { get { return activePoint; } set { activePoint = value; changePoint?.Invoke(activePoint); } } #endregion #region Unity Methods private void Awake() { instance = this; points = new Queue<InvisiblePoint>(); for (int i = 0; i < pointsQueueInic.Length; i++) { pointsQueueInic[i].die += nextPoint; points.Enqueue(pointsQueueInic[i]); } ActivePoint = points.Dequeue(); } #endregion #region Private Methods #endregion #region Private Fields private void nextPoint() { ActivePoint = points?.Dequeue(); if (ActivePoint == null) { return; } } #endregion }
59c94214e539ba27d5041fa15b180ac03e414de9
C#
vijit99/CSharp_Assignment-1
/CSharp_1_Assignement/CSharp_1_Assignement/Q6.cs
3.34375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp_1_Assignement { class Q6 { static void Main() { Console.WriteLine("Enter the temperature in Fahrenheit"); float f = 0.0f; f = float.Parse(Console.ReadLine()); float c = 0.0f; c = (f - 32) * 5 / 9; Console.WriteLine("{0}K in Celsius is {1}", f, c); } } }
7bb62e7d9e58524b31c5110bdfd68fa66775e475
C#
spencerkittleson/GitHubIssueCloseRate
/GitHubIssueCloseRate/Data/GitHubIssuesRepository.cs
2.765625
3
using GitHubIssueCloseRate.Entities; using GitHubIssueCloseRate.Interfaces; using RestSharp; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace GitHubIssueCloseRate.Data { public class GitHubIssuesRepository : IGitHubIssueRepository { private RestClient client; public GitHubIssuesRepository(){ Repo = "picturepan2/spectre"; client = new RestClient { BaseUrl = new Uri($"https://api.github.com/repos/{Repo}") }; } public string Repo { get;set;} public async Task<GitHubIssueModel> Get(string id) { var request = Request(Method.GET); request.Resource = $"/issues/{id}"; IRestResponse<GitHubIssueModel> response = await client.ExecuteTaskAsync<GitHubIssueModel>(request); return response.Data; } public async Task<IList<GitHubIssueModel>> List() { var request = Request(Method.GET); request.Resource = "/issues?per_page=100&sort=closed_at"; var response = await client.ExecuteTaskAsync<List<GitHubIssueModel>>(request); return response.Data; } private RestRequest Request(Method method) { var request = new RestRequest(method); request.AddHeader("Accept", "application/vnd.github.v3+json"); request.AddHeader("Content-Type", "application/json; charset=utf-8"); return request; } } }
5486406fdee4e9fad5bcbe3ff43400046ec78dd0
C#
JoseHenriqueRG/Abstract_Factory
/Models/Sofa.cs
3.21875
3
using Abstract_Factory.Interfaces; using System; namespace Abstract_Factory.Models { public class Sofa : ISofa { public Sofa(string modelo) { Montar(modelo); } public string Info { get; private set; } public void Montar(string modelo) { Info = $"Sofa {modelo} pronto."; } } }
5f1b797a19558768efe26bfad082cfd4604a2843
C#
dotnet/dotnet-api-docs
/snippets/csharp/System.Xml.Serialization/XmlAttributeEventArgs/ObjectBeingDeserialized/source.cs
2.859375
3
using System; using System.IO; using System.Xml; using System.Xml.Serialization; public class Sample { // <Snippet1> private void serializer_UnknownAttribute( object sender, XmlAttributeEventArgs e) { System.Xml.XmlAttribute attr = e.Attr; Console.WriteLine("Unknown Attribute Name and Value:" + attr.Name + "='" + attr.Value + "'"); Object x = e.ObjectBeingDeserialized; Console.WriteLine("ObjectBeingDeserialized: " + x.ToString()); } // </Snippet1> }
4ade93876e26a07b3591ada349b704932f6fc6ee
C#
soomker/Task5PizzaWorking
/Task5PiZZaApp/Engineer.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Threading; namespace Task5PiZZaApp { class Engineer { public string Name { get; private set; } public string Surname { get; private set;} private static string pathToLogFile; private StringBuilder strBuild = new StringBuilder(); private static StringBuilder stringBuildForFile = new StringBuilder(); private Random rnd; public Engineer(string name, string surname) { Name = name; Surname = surname; rnd = new Random(); pathToLogFile = "Pizza.log"; } public void GrabPizza(object count) { List<object> pizzaCount = (List<object>)count; GetPizza(pizzaCount); } private void GetPizza(List<object> countOfPieces) { strBuild.Clear(); int piecesOfPizzaWant = rnd.Next(1, 3); Thread.CurrentThread.Name = "This thread is " + Name; strBuild.AppendLine("I'm " + Name + " " + Surname + " and I want " + piecesOfPizzaWant + " pieces. " + Thread.CurrentThread.Name); try { lock (countOfPieces) { countOfPieces.RemoveRange(0, piecesOfPizzaWant); } strBuild.AppendLine(" After " + Name + " Pizza left: " + countOfPieces.Count); lock (stringBuildForFile) { stringBuildForFile.AppendLine(Name + " " + Surname + " have taken " + piecesOfPizzaWant + " pieces"); } } catch (Exception) { lock (stringBuildForFile) { strBuild.AppendLine(" Not enough pizza!! For " + Name); } } Console.WriteLine(strBuild); } public static void WriteLog() { lock (pathToLogFile) { File.AppendAllText(pathToLogFile, stringBuildForFile.ToString()); } } } }
233d2400ad37db962ec23b02b31419f652e14367
C#
downwithfooduci/mdp
/Assets/Scripts/Enzyme/ParticleGenerator.cs
2.828125
3
using UnityEngine; using System.Collections; /** * script used to generate particles in the enzyme game */ public class ParticleGenerator : MonoBehaviour { // variables to hold all the different types of particles that can spawn public GameObject parentCylCyl; //!< this represents two cylinders stuck together public GameObject parentCylCap; //!< this represents a cylinder and capsule stuck together public GameObject parentCylSphere; //!< this represents a cylinder and a sphere stuck together public GameObject parentSphereSphere; //!< this represents two spheres stuck together public GameObject parentSphereCyl; //!< this represents a sphere and a cylinder stuck together public GameObject parentSphereCap; //!< this represents a sphere and a capsule stuck together public GameObject parentCapCap; //!< this represents two capsules stuck together public GameObject parentCapCyl; //!< this represents a capsule and a cylinder stuck together public GameObject parentCapSphere; //!< this represents a capsule and a sphere stuck together public int numSpawn; //!< the number of particles to initially spawn when game starts Color[] colors; //!< array to hold the valid colors that a particle can spawn as GameObject[] parents; //!< array to hold the valid particle types that a particle can spawn as /** * Use this for initialization. * Sets valid particle colors and particle types in arrays. * Spawns any initial particles */ void Start () { // populate the color array with the possible choices // currently the choices are only red, blue, yellow, green, white colors = new Color[5]; colors [0] = Color.red; colors [1] = Color.blue; colors [2] = Color.yellow; colors [3] = Color.green; colors [4] = Color.white; // populate the parent array // put a reference to each type we can have parents = new GameObject[9]; parents[0] = parentCylCyl; parents[1] = parentCylCap; parents[2] = parentCylSphere; parents[3] = parentSphereSphere; parents[4] = parentSphereCyl; parents[5] = parentSphereCap; parents[6] = parentCapCap; parents[7] = parentCapCyl; parents[8] = parentCapSphere; // if the script is hardcoded from the unity editor to spawn a // certain number of particles on script starting, then do so for (int i = 0; i<numSpawn; i++) { SpawnParticle(); } } /** * function to spawn a new particle */ public void SpawnParticle () { // choose a random x and y location to spawn the particle float x = Random.Range(-10.0f, 10.0f); float y = Random.Range(-5.0f, 5.0f); // choose a random type of particle GameObject spawn = (GameObject)Instantiate (parents [Random.Range (0, parents.Length)], new Vector3 (Random.Range (-10f, 10f), Random.Range (-6f, 6f), 0), Quaternion.identity); MeshRenderer[] renderers = spawn.GetComponentsInChildren<MeshRenderer> (); // choose a random particle color and assign it to all the renderers Color color = colors [Random.Range (0, 5)]; for (int j = 0; j < renderers.Length; j++) { renderers [j].material.color = color; } // give the particle an initial impulse spawn.GetComponent<Rigidbody>().AddForce(new Vector3(x, y, 0), ForceMode.Impulse); } }
55f94d4561b11c8b000da71a7ace056b60aaf12b
C#
AnastasiyaKrasnova/OldFaker
/OldFaker/Faker/Plugin.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.IO; namespace Faker { class Plugin { public List<IGenerator> Plugins; private string pluginPath; public Plugin() { Plugins = new List<IGenerator>(); pluginPath = Path.Combine(Directory.GetCurrentDirectory(), "Plugins"); Plugins.Clear(); DirectoryInfo pluginDirectory = new DirectoryInfo(pluginPath); if (!pluginDirectory.Exists) pluginDirectory.Create(); var pluginFiles = Directory.GetFiles(pluginPath, "*.dll"); foreach (var file in pluginFiles) { Assembly asm = Assembly.LoadFrom(file); var types = asm.GetTypes(); foreach (Type type in types) { if (Array.Exists(type.GetInterfaces(), inter => inter.Name == "IGenerator")) { IGenerator plugin = Activator.CreateInstance(type) as IGenerator; Plugins.Add(plugin); } } } } } }
ad72212d5977a4104220cd30901c164c8e19f882
C#
vonwolfgang/C_sharp-Lessons
/6/6/Program.cs
3.484375
3
using System; namespace _6 { class Program { static void Main(string[] args) { // STRİNG TANIMLAMA FELAN string nick = "anonymous"; // string ifadeler böle tanımlanır foreach (var item in nick) { Console.WriteLine(item); // burda ise foreach döngüsünde tanımladığımız stringin her bir harfini // yazdırcak } Console.WriteLine("\n"); string nick_1 = "hello_anonymous"; string result = nick_1 + " " + nick; Console.WriteLine(result); // yukarıda bir tane daha değişken açıp o değişkene atadık // ve string topladık Console.WriteLine("\n"); Console.WriteLine(String.Format("{0} {1}", nick, nick_1)); // yeni bir değişken oluşturmadan da yukarıdaki gibi de yapabilirdik //--------------------------------------------------------------- // STRİNG İLE KULLANILAN METOTLAR string sentence = "bullet doesn't hurt the ideas"; var result_1 = sentence.Length; Console.WriteLine(result_1); Console.WriteLine("\n"); // cümledeki karakter sayısını sayar boşluk da bir karakterdir var result_2 = sentence.Clone(); Console.WriteLine(result_2); Console.WriteLine("\n"); // yukarıdaki Clone() şeysine klonladık ama asıl cümleyi değiştirsekde // result_2 değişmez. var result_3 = sentence.EndsWith("s"); Console.WriteLine(result_3); Console.WriteLine("\n"); // yukarıdaki şeyde EndsWith("s") ile kastettiğimiz bu cümle s ilemi bitiyor gibisinden // s yerine direk kelimede yazabilirdik bunun sonucu bool olarak döner. var result_4 = sentence.StartsWith("gdf"); Console.WriteLine(result_4); Console.WriteLine("\n"); // yukarıda da StartsWith("gdf") ile bu cümle gdf ile mi başlıyor diye sorduk // gene bunun sonucuda bool olarak döner. var result_5 = sentence.IndexOf("name"); Console.WriteLine(result_5); Console.WriteLine("\n"); // yukarıda yaptığımız şey cümlemizin içinden arıyor yani "name" dedikya // bunun sonucunda o fonksiyon bize "name"' in başladığı karakterin indexini döndürür // eğer verdiğimiz şeyi içinde bulamassa -1 döndürür eğer aradığımız şey cümlenin // içinde birden fazla var ise ilk bulduğu indexin numarasını döndürür. var result_6 = sentence.LastIndexOf(" "); Console.WriteLine(result_6); Console.WriteLine("\n"); // buda aramaya sondan başlar gene özellikleri aynı ama farkı aramaya sondan başlaması // bulduğunda ise indexlemeye baştan başlayarak index no sunu döndürür var result_7 = sentence.Insert(0,"hello anonymous, "); Console.WriteLine(result_7); Console.WriteLine("\n"); // Insert(0,"hello") yaptığımızda ise cümlenin 0. indexinden sonra hello eklicek // yani bişe eklemeye yarıyor. var result_8 = sentence.Substring(3,4); Console.WriteLine(result_8); Console.WriteLine("\n"); // yukarıdaki metot ise cümlemizi 3. indexden sonra 4 karakter al demek var result_9 = sentence.ToLower(); Console.WriteLine(result_9); Console.WriteLine("\n"); // bu ise tüm karakterleri küçük harf yapar var result_10 = sentence.ToUpper(); Console.WriteLine(result_10); Console.WriteLine("\n"); // bu ise tüm karakterleri büyük harf yapar var result_11 = sentence.Replace(" ","-"); Console.WriteLine(result_11); Console.WriteLine("\n"); // bu ise şu demek cümledeki boşluk karakterlerine "-" karkaterini koy demek // yani yer değiştiriyor var result_12 = sentence.Remove(2); Console.WriteLine(result_12); Console.WriteLine("\n"); // bu ise belli bi indexden sonrasını atmaya yarar yani 2. indexden sonrasını silicek var result_13 = sentence.Remove(2,5); Console.WriteLine(result_13); Console.WriteLine("\n"); // bu ise 2. indexden sonra 5 karakter siler } } }
c26ebb63184e347cc3a016a01bb70880f4edb03d
C#
rajandhaliwal80/InheritenceDemo
/InheritenceDemo/Person.cs
3.90625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InheritenceDemo { /// <summary> /// This is the person class /// /// </summary> class Person { //private instance variable(feilds) private string _name; private int _age; //public properties public string Name { get { return this._name; } set { this._name = value; } } public int Age { get { return this._age; } set { this._age = value; } } // constructor /// <summary> /// /// this is the constructor for the person class.it take two arguments. /// name which is string an age which is integer. /// </summary> /// <param name="name"></param> /// <param name="age"></param> public Person(string name,int age) { this.Name = name; this.Age = age; } //public methods /// <summary> /// /// this method allows the person to talk /// </summary> public void Talks() { Console.WriteLine(this.Name+" is talking"); } } }
6768557ff41b152b519117f9cb1f709ac3d56c1c
C#
Techcraft7/GenesisEdit
/GenesisEdit/Compiler/Sprite.cs
2.53125
3
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Runtime.Remoting; using System.Text; using System.Threading.Tasks; namespace GenesisEdit.Compiler { internal class Sprite : INameable { private string name = null; public byte Palette = 1; public string Name { get => name; set => name = value ?? $"Sprite_{new Random().Next():X}"; } public Bitmap Texture; public Sprite(string name) => Name = name; public bool Validate() { //temp bitmap to prevent NRE's using (Bitmap temp = new Bitmap(1, 1)) { return Utils.Validate(new List<Func<bool>>() { () => Texture != null, () => new int[] { 1 * 8, 2 * 8, 3 * 8, 4 * 8}.Contains(Texture == null ? temp.Width : Texture.Width), () => new int[] { 1 * 8, 2 * 8, 3 * 8, 4 * 8}.Contains(Texture == null ? temp.Height : Texture.Height), () => Utils.ValidateImage(Texture ?? temp) }); } } public string[] GetVariables() => new string[] { "GE_SPRITE_{0}_X", "GE_SPRITE_{0}_Y", "GE_SPRITE_{0}_DIR", "GE_SPRITE_{0}_SIZE", "GE_SPRITE_{0}_PAL", }.Select(v => v.Replace("{0}", Name) + ":\tRS.W\t1").ToArray(); public string InitVars() => string.Join(Environment.NewLine, GetVariables().Select(v => $"\t\tMOVE.W #{(v.Split('\t')[0].EndsWith("PAL") ? $"S_PAL{Palette}" : "0")},{v.Split('\t')[0]}")) + Environment.NewLine; } }
6e3db1519c3c2e89bf1fd7c4de53d03a7bb842ed
C#
MattWindsor91/roslyn
/concepts/code/ExpressionUtils/ExpressionUtils/NBE.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; // https://dlr.codeplex.com/ // An implementation of Normalization by Evaluation, based on Typeful Normalization by Evaluation, Danvy, Keller & Puesch // http://www.cs.au.dk/~mpuech/typeful.pdf // Needs much cleaning up - combines concepts with GADT namespace NBE { public abstract class Exp { } public class Val<T> : Exp { } public class VFun<T,U> : Val<Func<T,U>> { public Func<Val<T>, Val<U>> f; public VFun(Func<Val<T>, Val<U>> f) { this.f = f; } } public class VBase<T> : Val<Base<T>> { public Base<T> value; public VBase(Base<T> value) { this.value = value; } } public abstract class NF<T> { } public abstract class AT<T> { } public class NAt<T> : NF<Base<T>> { public AT<Base<T>> value; public NAt(AT<Base<T>> value){ this.value = value; } public override string ToString() => value.ToString(); } public class NFun<T, U> : NF<Func<T, U>> { public Func<Val<T>, NF<U>> value; public NFun(Func<Val<T>, NF<U>> value) { this.value = value; } public override string ToString() { var v = new Val<T>(); return "Fun(" + v.ToString() + "," + value(v).ToString() + ")"; } } public class AApp<T,U> : AT<U> { public AT<Func<T, U>> f; public NF<T> a; public AApp(AT<Func<T, U>> f, NF<T> a) { this.f = f; this.a = a; } public override string ToString() => f.ToString() + "" + a.ToString(); } public class AVar<T> : AT<T> { public Val<T> value; public AVar(Val<T> value) { this.value = value; } public override string ToString() => value.ToString(); } public abstract class Base<T> { } public class Atom<T> : Base<T> { public AT<Base<T>> atom; public Atom(AT<Base<T>> atom) { this.atom = atom; } } public abstract class Exp<T> : Exp { public abstract Val<T> Eval(); } public class Var<T> : Exp<T> { Val<T> value; public Var(Val<T> value) { this.value = value; } public Var() // TBR { } public override Val<T> Eval() => value; } public class Lam<T, U> : Exp<Func<T, U>> { public Func<Val<T>, Exp<U>> f; public Lam(Func<Val<T>, Exp<U>> f) { this.f = f; } public override Val<Func<T, U>> Eval() => new VFun<T, U>(x => f(x).Eval()); } public class App<T, U> : Exp<U> { public Exp<Func<T, U>> f; public Exp<T> e; public App(Exp<Func<T, U>> f, Exp<T> e) { this.f = f; this.e = e; } public override Val<U> Eval() { var fv = (f.Eval() as VFun<T, U>).f; //TODO pattern match instead return fv(e.Eval()); } } public static class Utils { public static Exp<Func<T, U>> Lam<T, U>(Func<Val<T>, Exp<U>> f) => new Lam<T, U>(f); public static Exp<U> Apply<T, U>(this Exp<Func<T, U>> f, Exp<T> e) => new App<T, U>(f, e); public static Exp<Func<T, V>> Compose<T, U, V>(Exp<Func<U, V>> f, Exp<Func<T, U>> g) => Lam<T, V>(x => f.Apply(g.Apply(new Var<T>(x)))); public static Exp<Func<T, T>> Pow<T>(Exp<Func<T, T>> f, int n) => (n > 0) ? Compose(f, Pow(f, n - 1)) : Lam<T, T>(x => new Var<T>(x)); } public concept Nbe<A> { NF<A> Reify(Val<A> a); Val<A> Reflect(AT<A> ea); } public instance NbeBase<T> : Nbe<Base<T>> { NF<Base<T>> Reify(Val<Base<T>> v) { var a = (v as VBase<T>).value; var r = (a as Atom<T>).atom; return new NAt<T>(r); } Val<Base<T>> Reflect(AT<Base<T>> r) { return new VBase<T>(new Atom<T>(r)); } } public instance NbeFunc<A, B, implicit NbeA, implicit NbeB> : Nbe<Func<A, B>> where NbeA : Nbe<A> where NbeB : Nbe<B> { NF<Func<A, B>> Reify(Val<Func<A, B>> v) { var f = (v as VFun<A, B>).f; return new NFun<A, B>((Val<A> x) => Reify(f(Reflect(new AVar<A>(x))))); } Val<Func<A, B>> Reflect(AT<Func<A, B>> a) => new VFun<A, B>(x => NbeB.Reflect(new AApp<A,B>(a,Reify(x)))); } public static class NbeUtils { public static NF<A> Nbe<A, implicit NbeA>(Exp<A> a) where NbeA : Nbe<A> => Reify(a.Eval()); } public static class Test { static void Main() { var e1 = new Lam<Base<int>,Base<int>>(x => new Var<Base<int>>(x)); var e = Utils.Compose(e1, e1); var e2 = Utils.Compose(e, e); var nf2 = NbeUtils.Nbe(e2); var nfs = nf2.ToString(); System.Console.WriteLine(nfs); System.Console.ReadLine(); } } }
ade1539550e40635cd816f5f2400d16bb2c98a93
C#
Tefferson/apa-api
/ApaApi/ApaApi/configurations/SigningConfiguration.cs
2.546875
3
using Microsoft.IdentityModel.Tokens; using System.Security.Cryptography; namespace ApaApi.configurations { /// <summary> /// Disponibiliza a configuração da assinatura /// </summary> public class SigningConfiguration { /// <summary> /// A chave de segurança /// </summary> public SecurityKey Key { get; } /// <summary> /// As credenciais da assinatura utilizadas apra validação da assinatura /// </summary> public SigningCredentials SigningCredentials { get; } /// <summary> /// Inicialiaza uma nova instância de SigningConfiguration /// </summary> public SigningConfiguration() { using (var provider = new RSACryptoServiceProvider(2048)) Key = new RsaSecurityKey(provider.ExportParameters(true)); SigningCredentials = new SigningCredentials( Key, SecurityAlgorithms.RsaSha256Signature); } } }
3d5eb63f47607b60381f0e622fb9f9a4ba9d8d4b
C#
NooartSkyline/GitCodecommit
/Windows_APP/Test_datetime/Test_datetime/Form1.cs
2.796875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Test_datetime { public partial class Form1 : Form { public Form1() { InitializeComponent(); //string sdate = Convert.ToString(DateTime.Now); //lb_datetime.Text ="Get : " + sdate + " ---> " + Convert.ToDateTime(sdate).ToString("yyyy-MM-dd", new CultureInfo("en-US"));//en-US DateTime oDate = DateTime.Now.Date; string sDate = oDate.ToString("yyyy-MM-dd", new CultureInfo("th-TH")); lb_datetime.Text = sDate; } private void txt_date_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { string sDate = txt_date.Text; lb_datetime.Text = "Get : " + sDate + " ---> " + Convert.ToDateTime(sDate).ToString("yyyy-MM-dd", new CultureInfo("en-US"));//en-US } } private void btn_getdate_Click(object sender, EventArgs e) { string sdate = Convert.ToString(DateTime.Now); lb_datetime.Text = "Get : " + sdate + " ---> " + Convert.ToDateTime(sdate).ToString("yyyy-MM-dd", new CultureInfo("en-US"));//en-US } } }
5c09741e8b198400c7c59cc0e6388c09886848e3
C#
barimahyaw/PointOS
/PointOS.BusinessLogic/ProductCategoryBusiness.cs
2.65625
3
using PointOS.BusinessLogic.Interfaces; using PointOS.Common.DTO.Request; using PointOS.Common.DTO.Response; using PointOS.DataAccess; using PointOS.DataAccess.Entities; using System; using System.Linq; using System.Threading.Tasks; namespace PointOS.BusinessLogic { public class ProductCategoryBusiness : IProductCategoryBusiness { private readonly IUnitOfWork _unitOfWork; public ProductCategoryBusiness(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } /// <summary> /// Saves a product category record /// </summary> /// <param name="request"></param> /// <returns>number of records affected</returns> public async Task<ResponseHeader> SaveAsync(ProductCategoryRequest request) { var entity = new ProductCategory { GuidId = Guid.NewGuid(), Name = request.Name, CreatedOn = DateTime.UtcNow, Status = request.Status, CreatedUserId = request.CreatedBy, CompanyId = request.CompanyId }; await _unitOfWork.ProductCategoryRepository.AddAsync(entity); var result = await _unitOfWork.SaveChangesAsync(); return result != 0 ? new ResponseHeader { StatusCode = 201, Message = $"Record created for {request.Name}", Success = true } : new ResponseHeader { Message = "" }; } /// <summary> /// Select a record of product category by it's integer Id /// </summary> /// <param name="id"></param> /// <returns>a single product category record</returns> public async Task<SingleResponse<ProductCategoryResponse>> FindByIdAsync(int id) { var entity = await _unitOfWork.ProductCategoryRepository.FindByIdAsync(id); if (entity == null) return new SingleResponse<ProductCategoryResponse>( new ResponseHeader { Message = "No record found." }, null); var result = ProductCategoryResponseEntity(entity); return new SingleResponse<ProductCategoryResponse>(new ResponseHeader { Success = true }, result); } /// <summary> /// Select a record of product category by it's Guid Id /// </summary> /// <param name="id"></param> /// <returns>a single product category record</returns> public async Task<SingleResponse<ProductCategoryResponse>> FindByIdAsync(Guid id) { var entity = await _unitOfWork.ProductCategoryRepository.FindByIdAsync(id); if (entity == null) return new SingleResponse<ProductCategoryResponse>( new ResponseHeader { Message = "No record found." }, null); var result = ProductCategoryResponseEntity(entity); return new SingleResponse<ProductCategoryResponse>(new ResponseHeader { Success = true }, result); } /// <summary> /// Select a record of product category by it's Guid Id or integer Id /// </summary> /// <param name="id"></param> /// <param name="guidValue"></param> /// <returns>a single product category record</returns> public async Task<SingleResponse<ProductCategoryResponse>> GetProductCategory(int? id, Guid? guidValue) { var entity = guidValue == Guid.Empty || string.IsNullOrWhiteSpace(guidValue.ToString()) ? await _unitOfWork.ProductCategoryRepository.FindByIdAsync(id.GetValueOrDefault()) : await _unitOfWork.ProductCategoryRepository.FindByIdAsync(guidValue.GetValueOrDefault()); if (entity == null) return new SingleResponse<ProductCategoryResponse>( new ResponseHeader { Message = "No record found." }, null); var result = ProductCategoryResponseEntity(entity); return new SingleResponse<ProductCategoryResponse>(new ResponseHeader { Success = true }, result); } /// <summary> /// Select all records of product category by a status /// </summary> /// <param name="status"></param> /// <returns>a list of product category records</returns> public async Task<ListResponse<ProductCategoryResponse>> FindAllAsync(bool status) { var entities = await _unitOfWork.ProductCategoryRepository.FindAllByStatusAsync(status); if (entities.Count <= 0) return new ListResponse<ProductCategoryResponse>(new ResponseHeader { Message = "No record found." }, null); var result = entities.Select(ProductCategoryResponseEntity); return new ListResponse<ProductCategoryResponse>(new ResponseHeader { Success = true }, result); } /// <summary> /// Select all records of product category /// </summary> /// <returns>a list of product category records</returns> public async Task<ListResponse<ProductCategoryResponse>> FindAllAsync(int companyId, int skip, int take) { var entities = await _unitOfWork.ProductCategoryRepository.FindAllAsync(companyId, skip, take); if (entities.Count <= 0) return new ListResponse<ProductCategoryResponse>(new ResponseHeader { Message = "No record found." }, null); var result = entities.Select(ProductCategoryResponseEntity); return new ListResponse<ProductCategoryResponse>(new ResponseHeader { Success = true, ReferenceNumber = _unitOfWork.ProductCategoryRepository.TotalProductTypes(companyId).ToString() }, result); } /// <summary> /// Select all records of product category by company Id /// </summary> /// <returns>a list of product category records</returns> public async Task<ListResponse<ProductCategoryResponse>> FindAllAsync(int companyId) { var entities = await _unitOfWork.ProductCategoryRepository.FindAllAsync(companyId); if (entities.Count <= 0) return new ListResponse<ProductCategoryResponse>(new ResponseHeader { Message = "No record found." }, null); var result = entities.Select(ProductCategoryResponseEntity); return new ListResponse<ProductCategoryResponse>(new ResponseHeader { Success = true, ReferenceNumber = _unitOfWork.ProductCategoryRepository.TotalProductTypes(companyId).ToString() }, result); } /// <summary> /// a private method to initiate and populate Product Category /// </summary> /// <param name="entity"></param> /// <returns>a single record</returns> private static ProductCategoryResponse ProductCategoryResponseEntity(ProductCategory entity) { var user = entity.CreatedUser; var result = new ProductCategoryResponse { Id = entity.Id, GuidValue = entity.GuidId, ProductName = entity.Name, Status = entity.Status ? "Active" : "Inactive", CreatedBy = user != null ? $"{user.FirstName} {user.MiddleName} {user.LastName}" : string.Empty, CreatedOn = entity.CreatedOn }; return result; } } }
b7bfdcfe9f918206928954af660d5f9bd0e66b66
C#
lucassilva996/WebApi-Lanches
/WebApi-Lanches/Controllers/LanchesController.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WebApi_Lanches.Data; using WebApi_Lanches.Models; namespace WebApi_Lanches.Controllers { [Route("api/[controller]")] [ApiController] public class LanchesController : ControllerBase { private readonly LanchesContext _context; public LanchesController(LanchesContext context) { _context = context; } // GET: api/Lanches [HttpGet] public async Task<ActionResult<IEnumerable<Lanches>>> GetLanches() { return await _context.Lanches.ToListAsync(); } // GET: api/Lanches/5 [HttpGet("{id}")] public async Task<ActionResult<Lanches>> GetLanches(int id) { var lanches = await _context.Lanches.FindAsync(id); if (lanches == null) { return NotFound(); } return lanches; } // PUT: api/Lanches/5 // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPut("{id}")] public async Task<IActionResult> PutLanches(int id, Lanches lanches) { if (id != lanches.LancheId) { return BadRequest(); } _context.Entry(lanches).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!LanchesExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Lanches // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPost] public async Task<ActionResult<Lanches>> PostLanches(Lanches lanches) { _context.Lanches.Add(lanches); await _context.SaveChangesAsync(); return CreatedAtAction("GetLanches", new { id = lanches.LancheId }, lanches); } // DELETE: api/Lanches/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteLanches(int id) { var lanches = await _context.Lanches.FindAsync(id); if (lanches == null) { return NotFound(); } _context.Lanches.Remove(lanches); await _context.SaveChangesAsync(); return NoContent(); } private bool LanchesExists(int id) { return _context.Lanches.Any(e => e.LancheId == id); } } }
aefc15d4549443c94fe714d7781d274e54b3d577
C#
shruti2898/Day-16-and-17
/Algorithm Programs/P3_InsertionSort.cs
4.03125
4
using System; using System.IO; namespace DataStructure { class P3_InsertionSort { public void insertionSort() { // Input text file path string file = @"C:\Users\Mehta\Desktop\Bridgelab\DataStructurePrograms\DataStructure\input.txt"; // Reading comma-separated values from text file string str = File.ReadAllText(file); // Converting content of text file into string array String[] strArray = str.Split(','); Console.Write("Array before sorting: \n"); printArray(strArray); //Insertion sort sorting(strArray); Console.Write("\nArray after sorting: \n"); printArray(strArray); } void sorting(string[] strArray) { for (int i = 1; i < strArray.Length; ++i) { string key = strArray[i]; int j = i - 1; while (j >= 0 && strArray[j].CompareTo(key)>0) { strArray[j + 1] = strArray[j]; j = j - 1; } strArray[j + 1] = key; } } void printArray(string[] strArray) { for (int i = 0; i < strArray.Length; ++i) { Console.Write(strArray[i] + "\n"); } } } }
f242722d0c65ec47723fea3c522b2d3a0bbb9581
C#
brendanSapience/AAE-MetaBot--Level-2
/MyApp4Lib/RestUtils.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace MyApp4Lib { public class RestUtils { public String CallRestGETNoAuth(String URL) { System.Net.HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL); httpWebRequest.ContentType = "text/json"; httpWebRequest.Method = "GET"; try { var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new System.IO.StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; } } catch (System.Net.WebException e) { return "Error:" + e.Message; } } } }
c52411c585a132662115e7424bf989ee6e8f8d43
C#
asaale/EotE_GMTool
/EotE_GMTool/Objects/Characters/Species/Twilek.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EotE_GMTool.Objects.Characters.Species { [Serializable] public class Twilek : Species { public Twilek() { StartingXp = 100; StartingWoundThreshold = 10; StartingStrainThreshold = 11; SpecialAbilities = "Twi'leks begin the game withone rank in either Charm or Deceit. They still may not train Charm or Deceit above rank 2 during character creation."; StartingBrawn = 1; StartingPresence = 3; StartingIntellect = 2; StartingCunning = 2; StartingAgility = 2; StartingWillpower = 2; Description = @" The Twi'leks are among the mo0st prominent non-human species in the galaxy. They are expert bargainers, sly at reading other species and using cunning to get what they want." + Environment.NewLine + " The government on Ryloth is an alliance of 'head clans', each of which control a small town or larger districts in the icty. Fa family's five most import Twi'leks lead their respected head-clans, with the power of influence radiating down the bloodline. According to tradition, when one leader of the head clan dies, the four remaining members must take exile to the sun-baked bright lands where the vicious lyleks roam. In practive, however, clan leaders find new and cunning w3ays to subvert exile." + Environment.NewLine + " The clan system has stratified Twi'lek society into castes. Twi'leks at the bottom of a bloodline are considered of the low birth caste and used as chattel in the slave trade. Twi'lek leaders exhibit disgust at any accusation of slavery and deny that they would ever put their own people in bondage. Nontheless, nearly every clan engages in 'contracted indenturehood'." + Environment.NewLine + " Ambitious clan members who want to rise in the family will do whatever it takes to get ahead within the social bounds. Direct confrontation is only a last resort for Twi'leks. They prefer more craft ways of bringing down their rivals, using political schemes to disgrace an opponent's entire family. On Ryloth, shame has more power than assassination - Twi'leks never forget the stains of a scandal."; } public override string ToString ( ) { return "Twi'lek"; } } }
46740d372b5d8868316ca8ecbcfdcf0d5268f901
C#
exiton3/TestSolution
/ConsoleApplication2/Program.cs
3.671875
4
using System.Collections.Generic; using System.Linq; using static System.Console; namespace ConsoleApplication2 { internal class Program { private static void Main(string[] args) { var cards = new List<Card> { new Card {Start = "Melburn", End = "Cologne"}, new Card {Start = "Moscow", End = "Paris"}, new Card {Start = "Cologne", End = "Moscow"} }; var result = CardSorter.SortCards(cards); foreach (var card in result) { Write("{0} -> {1} , ", card.Start, card.End); } ReadKey(); } static string GetStringFromArray(int[] a) { string result = string.Empty; Array.Sort(a); int start = a[0]; int end = a[0]; for (int i = 1; i < a.Length; i++) { if (a[i] - a[i - 1] == 1) { end = a[i]; } else { result += FormatString(start, end) + ","; start = a[i]; end = a[i]; } } result += FormatString(start, end); return result; } private static string FormatString(int start, int end) { return start == end ? start.ToString() : start + "-" + end; } } }
dcf90406bf824644392e77b37ad992dbe3ce0f01
C#
onartz/AmbitourSocketServerService
/ObjetsMetiers/Server.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Xml; using System.Xml.Serialization; using System.IO; using SocketServer; namespace AmbitourSocketServerService.ObjetsMetiers { // State object for reading client data asynchronously public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } class Server { //The port the server is listening to //static int port; // Thread signal. public static ManualResetEvent allDone = new ManualResetEvent(false); public static Socket listener; public Server() { } public static void StopListening() { listener.Disconnect(false); listener.Close(); } public static void StartListening(int port) { // Data buffer for incoming data. byte[] bytes = new Byte[1024]; IPHostEntry hostEntry = null; // Get host related information. hostEntry = Dns.GetHostByName("aip-olivier"); IPAddress ipAddress = hostEntry.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(100); while (true) { // Set the event to nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. //Console.WriteLine(String.Format("{0} is waiting for a connection on port {1}", ipAddress.ToString(), port)); listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); // Wait until a connection is made before continuing. allDone.WaitOne(); } } catch (Exception e) { throw e; } // Console.WriteLine("\nPress ENTER to continue..."); //Console.Read(); } public static void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. allDone.Set(); // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. StateObject state = new StateObject(); state.workSocket = handler; if(handler.Connected == true) handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } public static void ReadCallback(IAsyncResult ar) { XmlSerializer SerializerObj = new XmlSerializer(typeof(ACLMessage)); String content = String.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. try { int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString( state.buffer, 0, bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = state.sb.ToString(); if (content.IndexOf("<EOF>") > -1) { string strMessage = content.Replace("<EOF>", ""); // All the data has been read from the // client. Display it on the console. //Console.WriteLine("Read {0} bytes from socket. \n", // content.Length); //Deserialize message to ACLMessage : if OK, save to queue try { XmlReader xmlReader = XmlReader.Create(new StringReader(strMessage)); ACLMessage msg = (ACLMessage)SerializerObj.Deserialize(xmlReader); if (msg != null) { TextWriter tw = new StreamWriter(@"C:\Ambitour\incomingRequest\" + Guid.NewGuid() + ".xml"); SerializerObj.Serialize(tw, msg); tw.Close(); } } catch (XmlException ex) { throw ex; } // Echo the data back to the client. Send(handler, content); } else { // Not all data received. Get more. handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } } } catch (SocketException ex) { throw ex; // Console.WriteLine(ex.Message); } } ///* // * A intégrer dans Ambitour // */ //private static void SendToProxy(String data, String dest) //{ // string result = ""; // try // { // Console.WriteLine(String.Format("Sending {0}", data)); // result = SocketSendReceive("10.10.68.92", 6789, data); // Console.WriteLine(String.Format("Result {0}", result)); // //TODO: à modifier // //if (result.Contains("((done")) // //{ // // txtInventoryLevel.Text = (Int16.Parse(txtInventoryLevel.Text) - numericUpDown1.Value).ToString(); // // numericUpDown1.Value = 0; // //} // } // catch (SocketException ex) // { // //errorList.Add(ex.Message); // //updateLogView(); // return; // } //} private static Socket ConnectSocket(string server, int port) { Socket s = null; IPHostEntry hostEntry = null; // Get host related information. hostEntry = Dns.GetHostEntry(server); // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception that occurs when the host IP Address is not compatible with the address family // (typical in the IPv6 case). foreach (IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, port); Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { tempSocket.Connect(ipe); } catch (SocketException e) { throw e; } if (tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return s; } // This method sends a request and wait for answer from agent private static string SocketSendReceive(string server, int port, string request) { // Console.WriteLine(String.Format("Sending {0} to {1}:{2}",request, server, port)); // Console.WriteLine("Entering SocketSendReceive"); //string address = "[email protected]:1099/JADE"; Byte[] bytesSent = Encoding.ASCII.GetBytes(request); Byte[] bytesReceived = new Byte[256]; string page = ""; // Create a socket connection with the specified server and port. try { Socket s = ConnectSocket(server, port); if (s == null) return ("Connection failed"); // Send request to the server. s.Send(bytesSent, bytesSent.Length, 0); // Receive the server home page content. int bytes = 0; // The following will block until te page is transmitted. do { bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes); } while (bytes == bytesReceived.Length); } catch (SocketException e) { throw e; } return page; } private static void Send(Socket handler, String data) { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } private static void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket handler = (Socket)ar.AsyncState; // Complete sending the data to the remote device. int bytesSent = handler.EndSend(ar); // Console.WriteLine("Sent {0} bytes to client.", bytesSent); handler.Shutdown(SocketShutdown.Both); handler.Close(); } catch (Exception e) { throw e; // Console.WriteLine(e.ToString()); } } } }
dacae8a8cd2f4ab1887c8b37362223b91f63bbce
C#
Mato-ra/JsonSerializer
/JsonSerializer/JsonSerializer/JsonSerializer.cs
2.78125
3
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Linq; namespace JsonSerializer { public static partial class Json { public static string ReadJsonFile(string path) { if (!File.Exists(path)) { return null; } return RemoveFormatting(File.ReadAllText(path)); } public static bool WriteJsonFile(string path, string jsonData) { try { File.WriteAllText(path, AddFormatting(jsonData)); return true; } catch { return false; } } public static string GetValue(string jsonData, string keyOrIndex, bool caseSensitive) { switch (CheckValueType(jsonData)) { case ValueType.Object: return GetKvpValue(jsonData, keyOrIndex, caseSensitive); case ValueType.Array: return GetArrayEntry(jsonData, keyOrIndex); default: return null; } } public static string GetValue(string jsonData, string[] keysOrIndices, bool caseSensitive) { if (jsonData == null || keysOrIndices == null) { return null; } if (keysOrIndices.Length > 1) { switch (CheckValueType(jsonData)) { case ValueType.Object: return GetValue(GetValue(jsonData, keysOrIndices[0], caseSensitive), RemoveKeyOrIndex(keysOrIndices, 0), caseSensitive); case ValueType.Array: return GetValue(GetValue(jsonData, keysOrIndices[0], caseSensitive), RemoveKeyOrIndex(keysOrIndices, 0), caseSensitive); default: return null; } } else { return GetValue(jsonData, keysOrIndices[0], caseSensitive); } } public static string GetArrayEntry(string jsonArray, string index) { var arr = DeserializeArray(jsonArray); int i = -1; if (!TryDeserializeNumber(index, out i)) { return null; } if (arr.Length > i && i >= 0) { return arr[i]; } return null; } public static string GetKvpValue(string jsonObject, string key, bool caseSensitive) { var kvp = GetKeyValuePair(jsonObject, key, caseSensitive); if (kvp.Key != null) { return kvp.Value; } else { return null; } } public static string GetKvpValue(Dictionary<string, string> jsonObject, string key, bool caseSensitive) { var kvp = GetKeyValuePair(jsonObject, key, caseSensitive); if (kvp.Key != null) { return kvp.Value; } else { return null; } } public static KeyValuePair<string, string> GetKeyValuePair(string jsonObject, string key, bool caseSensitive) { if (jsonObject == null) { return new KeyValuePair<string, string>(null, null); } var dict = DeserializeObject(jsonObject); return GetKeyValuePair(dict, key, caseSensitive); } public static KeyValuePair<string, string> GetKeyValuePair(Dictionary<string, string> jsonObject, string key, bool caseSensitive) { var dict = jsonObject; if (dict == null) { return new KeyValuePair<string, string> ( null, null ); } if (!caseSensitive) { key = key.ToLower(); } foreach (var kvp in dict) { var k = kvp.Key; if (!caseSensitive) { k = k.ToLower(); } if (DeserializeString(k) == DeserializeString(key)) { return kvp; } } return new KeyValuePair<string, string>(null, null); } public static string CreateNewObject() { return "{}"; } public static string CreateNewArray() { return "[]"; } public static string EditArrayEntry(string jsonArray, string index, string value) { if (CheckValueType(jsonArray) != ValueType.Array) { return jsonArray; } int i = -1; if (!TryDeserializeNumber(index, out i)) { return jsonArray; } if (CheckValueType(value) == ValueType.Invalid) { value = SerializeString(value); } var arr = DeserializeArray(jsonArray); if (arr.Length > i && i >= 0) { arr[i] = value; } return SerializeArray(arr.ToArray()); } public static string EditValue(string jsonData, string[] keysOrIndices, string newValue, bool caseSensitive) { return AddValue(jsonData, keysOrIndices, newValue, caseSensitive, true, false, false); } public enum ArrayEntryOrKvpValue { Either, ArrayEntry, KvpValue, } } }
156376dd740240faf188cb140a4a7ee5f3a1a822
C#
mnitchie/MaintenanceTracker-Services
/MaintenanceTracker/Controllers/CarModelController.cs
2.578125
3
using EdmundsApiSDK; using MaintenanceTracker.Models; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace MaintenanceTracker.Controllers { public class CarModelController : ApiController { private IEdmunds _edmundsRepository; public CarModelController( IEdmunds edmundsRepository ) { this._edmundsRepository = edmundsRepository; } [HttpGet] public async Task<IHttpActionResult> GetModels( [FromUri] string make, [FromUri] string year = null ) { var edmundsModels = await _edmundsRepository.GetModelsByMake( make, year ); var models = edmundsModels.Select(em => new CarModel { Id = em.NiceName, Name = em.Name } ); return Ok( models ); } } }
da24addc3fd6190a308493dbcccd36223e3a25ab
C#
jibedoubleve/ioc-training
/src/Services/MyService.cs
2.625
3
using Ioc.Infrastructure; using System; namespace Ioc.Services { public class MyService { #region Fields private readonly BasicLogService Log = new BasicLogService(); #endregion Fields #region Methods public void SomeBehaviour() { Log.Warning("Keep attention here."); Console.WriteLine("\tStep 1"); Log.Info("Some log message"); Console.WriteLine("\tStep 2"); } #endregion Methods } }
1e8488e9e39ff070b2ce38e369c5bb6c4f92c1d9
C#
ricardoborges/NPortugol2
/src/NPortugol2.Tests/Dyn/Args/LoadArgsTestCase.cs
2.65625
3
using NPortugol2.Compiler; using NUnit.Framework; namespace NPortugol2.Tests.Dyn.Args { [TestFixture] public class LoadArgsTestCase { [Test] public void Should_Load_Args() { var result = new NPCompiler() .CompileMethod("funcao inteiro soma(inteiro x) retorne x fim") .Invoke(null, new object[]{20}); Assert.AreEqual(20, result); } [Test] public void Should_Load_Args2() { var result = new NPCompiler() .CompileMethod("funcao inteiro soma(inteiro x, inteiro y) retorne x + y fim") .Invoke(null, new object[] { 20, 30 }); Assert.AreEqual(50, result); } } }
021dc50f5fac40c0a82f4238f27517d02cf1dd4d
C#
kyulee2/Algorithm
/DifferentWaystoAddParentheses/t1.cs
3.671875
4
/* Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *. Example 1: Input: "2-1-1" Output: [0, 2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: Input: "2*3-4*5" Output: [-34, -14, -10, -10, 10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 */ // Comment: This is quite interesting problem. Initially tried to naively recursion, which failed. // Need to use Divide and Conquer. public class Solution { public IList<int> DiffWaysToCompute(string input) { var ans = new List<int>(); for(int i=0; i<input.Length; i++) { char c = input[i]; if (c=='+' || c=='-' || c=='*') { var ls = DiffWaysToCompute(input.Substring(0,i)); var rs = DiffWaysToCompute(input.Substring(i+1)); foreach(var l in ls) foreach(var r in rs) { switch(c) { case '+':ans.Add(l+r); break; case '-':ans.Add(l-r); break; case '*':ans.Add(l*r); break; } } } } if (ans.Count==0) { ans.Add(Convert.ToInt32(input)); } return ans; } }
f72affe1d6d983166383e0f9c35a7bc12f3dcfd0
C#
xavy88/WebAPI-CRM
/CRMAPI/Repository/DepartmentRepository.cs
3.046875
3
using CRMAPI.Data; using CRMAPI.Models; using CRMAPI.Repository.IRepository; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CRMAPI.Repository { public class DepartmentRepository : IDepartmentRepository { private readonly ApplicationDbContext _db; public DepartmentRepository(ApplicationDbContext db) { _db = db; } public bool ActiveDepartment(Department department) { _db.Departments.Update(department); return Save(); } public bool CreateDepartment(Department department) { _db.Departments.Add(department); return Save(); } public bool DeleteDepartment(Department department) { _db.Departments.Remove(department); return Save(); } public bool DepartmentExists(string name) { bool value = _db.Departments.Any(a => a.Name.ToLower().Trim() == name.ToLower().Trim()); return value; } public bool DepartmentExists(int id) { return _db.Departments.Any(a => a.Id == id); } public Department GetDepartment(int departmentId) { return _db.Departments.FirstOrDefault(a => a.Id == departmentId); } public ICollection<Department> GetDepartments() { return _db.Departments.OrderBy(a => a.Name).ToList(); } public bool InactiveDepartment(Department department) { _db.Departments.Update(department); return Save(); } public bool Save() { return _db.SaveChanges() >= 0 ? true : false; } public bool UpdateDepartment(Department department) { _db.Departments.Update(department); return Save(); } } }
1591f2e2e7e252231e10d7455ab8323c316862d8
C#
aws/aws-tools-for-powershell
/generator/AWSPSGeneratorLib/Writers/IndentedTextWriter.cs
3.1875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace AWSPowerShellGenerator.Writers { public class IndentedTextWriter : TextWriter { #region Private members private bool _justSawNewline = true; private TextWriter _writer; private void WriteIndents() { for (int i = 0; i < Indents; i++) _writer.Write(Indent); } #endregion #region Public members private int Indents { get; set; } public const string Indent = " "; public void OpenRegion(string regionDelimiter = "{") { WriteLine(regionDelimiter); Indents++; } public void CloseRegion(string regionDelimiter = "}") { Indents--; WriteLine(regionDelimiter); } public void IncreaseIndent() { Indents++; } public void DecreaseIndent() { Indents--; Indents = Math.Max(0, Indents); } #endregion #region Constructors public IndentedTextWriter(TextWriter baseWriter) : this(baseWriter, 0) { } public IndentedTextWriter(TextWriter baseWriter, int indents) { if (baseWriter == null) throw new ArgumentNullException("baseWriter"); _writer = baseWriter; Indents = indents; } #endregion #region Overrides public override void Write(char value) { if (value != '\r') { if (_justSawNewline) { WriteIndents(); _justSawNewline = false; } if (value == '\n') { foreach (char c in NewLine) { _writer.Write(c); } _justSawNewline = true; } else { _writer.Write(value); } } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (_writer != null) { _writer.Dispose(); _writer = null; } } public override Encoding Encoding { get { return _writer.Encoding; } } public override string ToString() { return _writer.ToString(); } public override void Close() { _writer.Close(); } public override void Flush() { _writer.Flush(); } public override IFormatProvider FormatProvider { get { return _writer.FormatProvider; } } public override string NewLine { get { return _writer.NewLine; } set { _writer.NewLine = value; } } #endregion } }
a45a01ffceb7a84b460bca36678a981591d56e62
C#
JoshuaKong4/LinkedList
/joshuaselectsort/joshuaselectsort/list.cs
3.5
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace joshuaselectsort { class List { int smallestindex = 0; int sortedindex = 0; public int count = 0; public int[] Array = new int[40]; public List() { } public void Addfirst (int addvalue) { Array[count] = addvalue; count++; } public void Sort() { for (int i = sortedindex; i < count; i++) { if (Array[i] < Array[smallestindex]) { smallestindex = i; } } int temp = Array[smallestindex]; Array[smallestindex] = Array[sortedindex]; Array[sortedindex] = temp; sortedindex++; smallestindex = sortedindex; } public void Display() { for(int i = 0; i<count; i++) { if (i == sortedindex) { Console.WriteLine($"{Array[i]}sorted"); } else if(i== smallestindex) { Console.WriteLine($"{Array[i]} smallest"); } else { Console.WriteLine($"{Array[i]}"); } } } } }
b4db8bf917b94b312186bd3947c8d774306de0f2
C#
PNNL-Comp-Mass-Spec/MultiAlign
/src/Library/MultiAlignCore/IO/MTDB/MTSMassTagDatabaseLoader.cs
2.65625
3
#region using System.Data; using System.Data.SqlClient; using FeatureAlignment.Algorithms.Options; using MultiAlignCore.Algorithms.Options; #endregion namespace MultiAlignCore.IO.MTDB { /// <summary> /// Access the mass tag system for downloading mass tag database information. /// </summary> public sealed class MtsMassTagDatabaseLoader : MassTagDatabaseLoader { /// <summary> /// Default password /// </summary> private const string DEFAULT_PASSWORD = "mt4fun"; /// <summary> /// Default user name. /// </summary> private const string DEFAULT_USERNAME = "mtuser"; /// <summary> /// Constructor. /// </summary> /// <param name="databaseName">Database name.</param> /// <param name="server">Server the database is hosted on.</param> /// <param name="options"></param> public MtsMassTagDatabaseLoader(string databaseName, string server, MassTagDatabaseOptions options) { UserName = DEFAULT_USERNAME; Password = DEFAULT_PASSWORD; DatabaseName = databaseName; ServerName = server; Options = options; } #region Properties /// <summary> /// Gets or sets the server name. /// </summary> public string ServerName { get; set; } /// <summary> /// Gets or sets the database name. /// </summary> public string DatabaseName { get; set; } /// <summary> /// Gets or sets the server password. /// </summary> public string Password { get; set; } /// <summary> /// Gets or sets the user name. /// </summary> public string UserName { get; set; } #endregion /// <summary> /// Creates an ADO connection to the Mass Tag system. /// </summary> /// <param name="connectionString">Connection to the database.</param> /// <returns></returns> protected override IDbConnection CreateConnection(string connectionString) { return new SqlConnection(connectionString); } /// <summary> /// Creates a valid SQL connection string to the MTS system. /// </summary> /// <returns></returns> protected override string CreateConnectionString() { return string.Format("Server={0};Database={1};Integrated Security=no; User ID={2}; PWD={3}", ServerName, DatabaseName, UserName, Password); } /// <summary> /// Creates a new sql data parameter for stored proc queries. /// </summary> /// <param name="name">Name of parameter.</param> /// <param name="value">Value of parameter to query with.</param> /// <returns>A new parameter</returns> protected override IDbDataParameter CreateParameter(string name, object value) { return new SqlParameter(name, value); } } }
ac7f2cbad6db53b4ae7ab79b8f1c74a358143455
C#
firebellys/countly-sdk-dotnet
/Entities/Device.cs
2.671875
3
/* Copyright (c) 2012, 2013, 2014, 2015 Countly Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using CountlySDK.Helpers; using System; using System.Linq; using System.Windows; using System.Management; using System.Reflection; namespace CountlySDK.Entitites { /// <summary> /// This class provides several static methods to retrieve information about the current device and operating environment. /// </summary> internal static class Device { /// <summary> /// Returns the unique device identificator /// This is pulling from the CPU ID of the local machine. /// </summary> public static string DeviceId { get { var name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_Processor").Get().OfType<ManagementObject>() select x.GetPropertyValue("ProcessorID")).FirstOrDefault(); return name != null ? name.ToString() : "Unknown"; } } /// <summary> /// Returns the display name of the current operating system /// </summary> public static string OS { get { var name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>() select x.GetPropertyValue("Caption")).FirstOrDefault(); return name != null ? name.ToString() : "Unknown"; } } /// <summary> /// Returns the current operating system version as a displayable string /// </summary> public static string OsVersion { get { return Environment.OSVersion.Version.ToString(); } } /// <summary> /// Returns the current Machine name of the device. /// </summary> public static string MachineName { get { return Environment.MachineName; } } /// <summary> /// Returns application version /// </summary> public static string AppVersion { get { return Assembly.GetExecutingAssembly().FullName; } } /// <summary> /// Returns device resolution in <width_px>x<height_px> format /// </summary> public static string Resolution { get { return "N/A"; } } /// <summary> /// Returns local domain name /// </summary> public static string Domain { get { return Environment.UserDomainName; } } } }
aea13067f54dfceae1bca34384a1e75922aff61c
C#
letalumil/JsonAssertions
/JsonAssertions.Tests/AssertJsonTests.cs
2.859375
3
using NUnit.Framework; namespace JsonAssertions.Tests { [TestFixture] public class AssertJsonTests { [Test] public void AreEquals_EqualJsonStrings_Success() { AssertJson.AreEquals("{name:'value'}", "{name:'value'}"); } [Test] public void AreEquals_UnequalPropertyValues_Fail() { const string expectedObject = "{prop1:'value1', name:'value'}"; const string actualObject = "{prop1:'value1', name:'value2'}"; var assertionException = Assert.Throws<AssertionException>(() => AssertJson.AreEquals(expectedObject, actualObject)); Assert.IsTrue( assertionException.Message.StartsWith(string.Format(" Property \"{0}\" does not match.", "name"))); } [Test] public void AreEquals_UnequalIntPropertyValues_Fail() { const string expectedObject = "{prop1:'value1', int:15}"; const string actualObject = "{prop1:'value1', int:16}"; var assertionException = Assert.Throws<AssertionException>(() => AssertJson.AreEquals(expectedObject, actualObject)); Assert.IsTrue( assertionException.Message.StartsWith(string.Format(" Property \"{0}\" does not match.", "int"))); } [Test] public void AreEquals_MissingProperty_Fail() { const string expectedObject = "{name:'value', missing:'yes'}"; const string actualObject = "{name:'value'}"; var assertionException = Assert.Throws<AssertionException>(() => AssertJson.AreEquals(expectedObject, actualObject)); Assert.AreEqual(assertionException.Message, string.Format("Object properties missing: missing")); } [Test] public void AreEquals_ExcessProperty_Fail() { const string expectedObject = "{name:'value'}"; const string actualObject = "{name:'value', excess:'yes'}"; var assertionException = Assert.Throws<AssertionException>(() => AssertJson.AreEquals(expectedObject, actualObject)); Assert.AreEqual(assertionException.Message, string.Format("Object has excess properties: excess")); } [Test] public void AreEquals_NestedObjects_Fail() { const string expectedObject = "{prop1:'value1', nested0:{}, nested: {key:'value'}}"; const string actualObject = "{prop1:'value1', nested0:{}, nested: {key:'value2'}}"; var assertionException = Assert.Throws<AssertionException>(() => AssertJson.AreEquals(expectedObject, actualObject)); Assert.IsTrue( assertionException.Message.StartsWith(string.Format(" Property \"{0}\" does not match.", "nested.key"))); } [Test] public void AreEquals_NestedArraysDifferentLength_Fail() { const string expectedObject = "{prop1:'value1', arr:[1, '2', {key: 'value'}, 5]}"; const string actualObject = "{prop1:'value1', arr:[1, '3', {key: 'value'}]}"; var assertionException = Assert.Throws<AssertionException>(() => AssertJson.AreEquals(expectedObject, actualObject)); Assert.AreEqual( string.Format("Different arrays length at {0}. Expected: {1}, but was: {2}", "arr", "4", "3"), assertionException.Message); } [Test] public void AreEquals_NestedArrays_Fail() { const string expectedObject = "{prop1:'value1', arr:[1, '2', {key: 'value'}]}"; const string actualObject = "{prop1:'value1', arr:[1, '3', {key: 'value'}]}"; var assertionException = Assert.Throws<AssertionException>(() => AssertJson.AreEquals(expectedObject, actualObject)); Assert.IsTrue( assertionException.Message.StartsWith(string.Format(" Property \"{0}\" does not match.", "arr[1]"))); } [Test] public void AreEquals_NestedArraysDiffObjects_Fail() { const string expectedObject = "{prop1:'value1', arr:[1, '2', {key: 'value2'}]}"; const string actualObject = "{prop1:'value1', arr:[1, '2', {key: 'value'}]}"; var assertionException = Assert.Throws<AssertionException>(() => AssertJson.AreEquals(expectedObject, actualObject)); Assert.IsTrue( assertionException.Message.StartsWith(string.Format(" Property \"{0}\" does not match.", "arr[2].key"))); } [Test] public void AreEquals_ComplexJson_Fail() { const string expectedObject = "{\"array\":[1,2,3],\"boolean\":true,\"null\":null,\"number\":123,\"object\":{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\",\"test\":{\"arr\":[{\"key\":{\"diff\":\"val\"}},{}]},\"name\":\"value\"},\"string\":\"Hello World\"}"; const string actualObject = "{\"array\":[1,2,3],\"boolean\":true,\"null\":null,\"number\":123,\"object\":{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\",\"test\":{\"arr\":[{\"key\":{\"diff\":\"val2\"}},{}]},\"name\":\"value\"},\"string\":\"Hello World\"}"; var assertionException = Assert.Throws<AssertionException>(() => AssertJson.AreEquals(expectedObject, actualObject)); Assert.IsTrue( assertionException.Message.StartsWith(string.Format(" Property \"{0}\" does not match.", "object.test.arr[0].key.diff"))); } } }
b0104a4c41b72dc41ee1d04750bf7a4803af7889
C#
shelbygrice/CSharpLibrary
/0.04_Conditionals_ReadLine/Program.cs
3.796875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _0._04_Conditionals_ReadLine { class Program { static void Main(string[] args) { Console.WriteLine("How are you feeling today from 1-5?"); string feelingNumber = Console.ReadLine(); if (feelingNumber == "5") { Console.WriteLine("Wow man. That's great to hear."); } else if (feelingNumber == "4") { Console.WriteLine("What can I do to help make your day better?"); } else if (feelingNumber == "3") { Console.WriteLine("Meh. We've all been there."); } else if (feelingNumber == "2") { Console.WriteLine("Well, it could be worse buddy."); } else if (feelingNumber == "1") { Console.WriteLine("Yikes. Sorry to hear that."); } else if (feelingNumber == "6") { Console.WriteLine("Shut up. No one can be that happy."); } else { Console.WriteLine("We gave you specific parameters to follow. Don't try to get smart and just follow the rules."); } Console.ReadLine(); } } }
9317e81e4c9e4469d4c2f4773fee40a12ae56790
C#
GregWickham/Echo
/SimpleNLG/RealizerSchema Extensions/WordElement.cs
2.71875
3
using System.Xml.Serialization; namespace SimpleNLG { public partial class WordElement { public WordElement Copy() => (WordElement)MemberwiseClone(); public WordElement CopyWithoutSpec() { WordElement result = Copy(); result.Base = null; return result; } [XmlIgnore] public string Base { get => @base; set => @base = value; } [XmlIgnore] public lexicalCategory PartOfSpeech { set { cat = value; catSpecified = true; } } [XmlIgnore] public string ID { set => id = value; } [XmlIgnore] public bool ExpletiveSubject { set { EXPLETIVE_SUBJECT = value; EXPLETIVE_SUBJECTSpecified = true; } } [XmlIgnore] public bool Proper { set { PROPER = value; PROPERSpecified = true; } } [XmlIgnore] public inflection Inflection { set { var = value; varSpecified = true; } } [XmlIgnore] public bool Canned { set { canned = value; cannedSpecified = true; } } public WordElement SetProper(bool proper) { Proper = proper; return this; } } }
aa0840ce76dcfe6a38bc83d8a19767657642747f
C#
ArkadiuszChorian/RunR
/RunR/TextBlockWriter.cs
2.8125
3
using System.IO; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace Archersoft.RunR { public class TextBlockWriter : TextWriter { private static readonly Dispatcher Dispatcher = Application.Current.Dispatcher; private readonly TextBox _textBox; public TextBlockWriter(TextBox textBox) { _textBox = textBox; } public override void Write(char value) { Dispatcher.Invoke(() => { _textBox.Text += value; _textBox.ScrollToEnd(); }); } public override void Write(string value) { Dispatcher.Invoke(() => { _textBox.Text += value; _textBox.ScrollToEnd(); }); } public override Encoding Encoding => Encoding.ASCII; } }
3f0596327151ac69a9b5642f5bfbc8c8edb92321
C#
castroi/EuroImport
/EuroImport/JsonReader.cs
2.671875
3
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; namespace EuroImport { public class JsonReader { public Dictionary<string, string> Read(string url) { using (WebClient wc = new WebClient { Encoding = Encoding.UTF8}) { ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072; var json = wc.DownloadString(url); return JsonConvert.DeserializeObject<Dictionary<string, string>>(json); } } public HeaderNames ReadHeaderNames(string fileFullPath) { var text = File.ReadAllText(fileFullPath); return JsonConvert.DeserializeObject<HeaderNames>(text); } } }
876a54fcb150412d990ea519df1b72eab02953d1
C#
Dmitry-Ischenko/GB-Algorithms-basics
/Lesson1/task2/Program.cs
3.65625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace task2 { class Program { static void Main(string[] args) { //Выполнил Ищенко Дмитрий //2. Найти максимальное из четырех чисел. Массивы не использовать. Console.WriteLine("Задача 2: \n 2. Найти максимальное из четырех чисел. Массивы не использовать.\n"); int num1, num2, num3, num4; ConsoleInput("Введите первое число: ",out num1); ConsoleInput("Введите второе число: ",out num2); ConsoleInput("Введите третье число: ",out num3); ConsoleInput("Введите четвертое число: ",out num4); int max = num1; if (max < num2) max = num2; if (max < num3) max = num3; if (max < num4) max = num4; Console.WriteLine($"Максимальное число из {num1},{num2},{num3},{num4} - {max}"); Console.ReadKey(); } static void ConsoleInput(string msg, out int arg) { do { Console.Write(msg); if (Int32.TryParse(Console.ReadLine(), out arg)) break; else Console.WriteLine("Введенное значение, не удалось пробразовать к типу Int32, попробуйте снова."); } while (true); } } }
d738e86cae5fcd3bfbdf61b06db648fe6f7c6481
C#
lanaolshanska/CargoExpress
/Source/DeliveryWebApplication/Delivery.Website/Delivery.Validators/DriverValidator/DriverValidator.cs
2.828125
3
using Delivery.BL.Contracts; using Delivery.Models; using Delivery.Models.DTO; using FluentValidation; namespace Delivery.Validators { public class DriverValidator : BaseValidator<DriverModel, Driver> { public DriverValidator(IDriverService driverService) : base(driverService) { RuleFor(x => x.FirstName) .NotEmpty().WithMessage("Enter first name") .MaximumLength(CustomMaxLength).WithMessage($"First name must not exceed {CustomMaxLength} characters") .Matches(RegExpForChars).WithMessage("First name must contain only letters"); RuleFor(x => x.LastName) .NotEmpty().WithMessage("Enter last name") .MaximumLength(CustomMaxLength).WithMessage($"Last name must not exceed {CustomMaxLength} characters") .Matches(RegExpForChars).WithMessage("Last name must contain only letters"); RuleFor(x => x.Birthdate) .Must(IsValidDate).WithMessage("Entered date format is invalid") .Unless(x => string.IsNullOrEmpty(x.Birthdate)); RuleFor(x => x.CellPhone) .Matches(RegExpForDigits).WithMessage("Phone must contain only digits") .MaximumLength(CustomMaxLength).WithMessage($"Phone must not exceed {CustomMaxLength} characters") .Unless(x => string.IsNullOrEmpty(x.CellPhone)); RuleFor(x => x.Address) .MaximumLength(MaxLength).WithMessage($"Address must not exceed {MaxLength} characters") .Unless(x => string.IsNullOrEmpty(x.Address)); RuleFor(x => x.StartedDrivingYear) .InclusiveBetween(MinYearRange, MaxYearRange).WithMessage($"Year must be in range between {MinYearRange} and {MaxYearRange}") .Unless(x => !x.StartedDrivingYear.HasValue); RuleFor(x => x.HasCriminalRecord) .NotNull().WithMessage("This field must be true or false"); } } }
de15d38f2926a598ce710edf31b29f81b92e2fb2
C#
Neikice/LGFrame
/Assets/Scripts/LGFrame/BehaviorTree/BTDecorators/Timer_DelayNode.cs
2.5625
3
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UniRx; namespace LGFrame.BehaviorTree.Decorate { /// <summary> /// 延迟执行修饰的Node,结果立即返回Success或Failure /// </summary> public class Timer_DelayNode : BTDecorator { public float DelayTime; #region 构造函数 public Timer_DelayNode(ITickNode node, float delayTime) : base(node) { this.name = "Decorator_Timer"; this.DelayTime = delayTime; } #endregion 构造函数 public override BTResult Tick() { if (this.State == BTResult.Running) return this.State; if (this.node.State == BTResult.Running) return this.State = BTResult.Running; if (this.State == BTResult.Ready) { this.State = BTResult.Running; Observable.Interval(TimeSpan.FromSeconds(DelayTime)).Take(1) .Subscribe(_ => { Debug.Log("等了秒 " + DelayTime); this.node.Tick(); this.State = BTResult.Success; Observable.NextFrame().Subscribe(x =>{ this.State = BTResult.Ready; }); }); } return this.State; } } }
fc07bef7a9411ed29084fcc760e175c30d3c1b7b
C#
tonngw/leetcode
/csharp/0179-largest-number.cs
3.390625
3
public class Solution { public string LargestNumber(int[] nums) { if(nums.All(_ => _ == 0)) return "0"; var s = nums.Select(_ => _.ToString()).ToList(); s.Sort((a, b) => (b+a).CompareTo(a+b)); return string.Concat(s); } }
3a10c254bc668a001f764c272a918e19645f9bc4
C#
davideastmond/csharpdelegateexample
/InfoObtained.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpDelegates { public class InfoObtained { public event GetInfo OnInfoObtained; public object p_sender; public string p_EventArgs; public InfoObtained() { } public void RaiseEvent (object sender, string e) { p_sender = sender; p_EventArgs = e; OnInfoObtained += InfoObtained_OnInfoObtained; OnInfoObtained(sender, e); } private void InfoObtained_OnInfoObtained(object sender, string e) { //throw new NotImplementedException(); } } }
48a0ba973dd3d1dc4c67411681cbedc3d8a84314
C#
KOKOS317/RestaurantHelper
/CatelDemo/Services/Logic/AuthorizationChecker.cs
2.671875
3
using System.Collections.Generic; using System.Linq; using RestaurantHelper.DAL; using RestaurantHelper.Models; namespace RestaurantHelper.Services.Logic { class AuthorizationChecker { private readonly UnitOfWork _unitOfWork = UnitOfWork.GetInstance(); private IEnumerable<User> _users; private User _user; public AuthorizationChecker(User user) { _user = user; } public bool IsMatchUser() { Refresh(); var find = _users?.ToList().Find(u => u.Login == _user.Login && u.Password == _user.Password); if (find == null) { return false; } _user = find; return true; } public bool IsExistsLogin() { Refresh(); var find = _users.ToList().Find(u => u.Login == _user.Login && u.Password != _user.Password); if (find == null) { return false; } return true; } private void Refresh() { _users = _unitOfWork.Users.GetAll(); } public User GetUser() { return _user; } public bool IsAdmin() { Refresh(); // TODO: переделать адекватно return _user.Login == "admin" && _user.Password == "admin"; } } }
513cf01b533a39e67f868020f2b514be59cc033b
C#
Lawo/ember-plus-sharp
/Lawo.EmberPlusSharp/Ember/FieldPath`2.cs
2.515625
3
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // <copyright>Copyright 2012-2017 Lawo AG (http://www.lawo.com).</copyright> // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace Lawo.EmberPlusSharp.Ember { using System; internal struct FieldPath<TTypeId, TFieldId> : IEquatable<FieldPath<TTypeId, TFieldId>> { public bool Equals(FieldPath<TTypeId, TFieldId> other) => this.field1.Equals(other.field1) && this.field2.Equals(other.field2) && this.field3.Equals(other.field3); public override int GetHashCode() => HashCode.Combine(this.field1.GetHashCode(), this.field2.GetHashCode(), this.field3.GetHashCode()); public override string ToString() { if (this.field1.HasValue) { return this.field1.ToString() + "." + this.field2.GetValueOrDefault().FieldId.ToString() + "." + this.field3.GetValueOrDefault().FieldId.ToString(); } else if (this.field2.HasValue) { return this.field2.ToString() + "." + this.field3.GetValueOrDefault().FieldId.ToString(); } else { return this.field3.ToString(); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// internal static FieldPath<TTypeId, TFieldId> Append( FieldPath<TTypeId, TFieldId> path, Field<TTypeId, TFieldId> field) { if (path.field1.HasValue) { throw new ArgumentException("Cannot be appended.", nameof(path)); } return new FieldPath<TTypeId, TFieldId>(path.field2, path.field3, field); } internal FieldPath(Field<TTypeId, TFieldId> field) : this(null, null, field) { } internal Field<TTypeId, TFieldId>? Tail => this.field3; //////////////////////////////////////////////////////////////////////////////////////////////////////////////// private readonly Field<TTypeId, TFieldId>? field1; private readonly Field<TTypeId, TFieldId>? field2; private readonly Field<TTypeId, TFieldId>? field3; private FieldPath( Field<TTypeId, TFieldId>? field1, Field<TTypeId, TFieldId>? field2, Field<TTypeId, TFieldId>? field3) { this.field1 = field1; this.field2 = field2; this.field3 = field3; } } }
f94fd063f7225d2d6cfbe7350a1f36aa989e78f1
C#
istoneshi/Dapper.UnitOfWork
/src/Dapper.UnitOfWork/Dapper.UnitOfWork/UnitOfWork.cs
2.921875
3
using System; using System.Data; namespace Dapper.UnitOfWork { public interface IUnitOfWork : IDisposable { void Commit(); T Query<T>(IQuery<T> query); void Execute(ICommand command); T Execute<T>(ICommand<T> command); void Rollback(); } public class UnitOfWork : IUnitOfWork { private bool _disposed; private IDbConnection _connection; private IDbTransaction _transaction; public UnitOfWork(IDbConnection connection, bool transactional = false) { _connection = connection; if (transactional) { _transaction = connection.BeginTransaction(); } } public T Query<T>(IQuery<T> query) { return query.Execute(_connection, _transaction); } public void Execute(ICommand command) { if (command.RequiresTransaction && _transaction == null) { throw new Exception($"The command {command.GetType()} requires a transaction"); } command.Execute(_connection, _transaction); } public T Execute<T>(ICommand<T> command) { if (command.RequiresTransaction && _transaction == null) { throw new Exception($"The command {command.GetType()} requires a transaction"); } return command.Execute(_connection, _transaction); } public void Commit() { _transaction?.Commit(); } public void Rollback() { _transaction?.Rollback(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~UnitOfWork() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { _transaction?.Dispose(); _connection?.Dispose(); } _transaction = null; _connection = null; _disposed = true; } } }
0ac81fdeb9a87a1bf59226c2c300f19c276e5bc0
C#
elangovana/hacker-projects
/AE.HackerRank.Samples.Tests/CoursePopularityTest.cs
2.609375
3
//using System; //using System.Collections.Generic; //using System.Linq; //using NUnit.Framework; //namespace AE.HackerRank.Samples.Tests //{ // [TestFixture] // public class CoursePopularityTest // { // [TestCase("A", "CSC1")] // public void Should(string iuser, string expectedRecomdedCourses) // { // //Arrange // ICourseRecommender sut = new CourseRecommender(); // var actual = sut.GetRecommendedCourse(iuser); // Assert.AreEqual(expectedRecomdedCourses, actual); // } // } // public interface ICourseRecommender // { // List<string> GetRecommendedCourse(string user); // } // public class CourseRecommender : ICourseRecommender // { // /// <summary> // /// Gets Recommended ranked courses for a user // /// </summary> // /// <param name="user">User name</param> // /// <returns>a list of recommnded courses ordered by popularity </returns> // public List<string> GetRecommendedCourse(string user) // { // var myattendedCourses = getAttendedCoursesForUser(user); // var applicableFriendsList = GetApplicableFriendsForUser(user); // var coursesWithPopularity = GetCoursesWithPopularity(applicableFriendsList); // var rankedCourseList = coursesWithPopularity.OrderByDescending(x => x.Value).Select(x => x.Key).ToList(); // return rankedCourseList.Where(x => !myattendedCourses.Contains(x)).ToList(); // } // /// <summary> // /// Caculates course popularity among friends // /// </summary> // /// <param name="applicableFriendsList">Friends list</param> // /// <returns>returns a dictionary of courses along with popularity</returns> // private Dictionary<string, int> GetCoursesWithPopularity(List<string> applicableFriendsList) // { // var coursePopularity = new Dictionary<string, int>(); // foreach (var friend in applicableFriendsList) // { // var courseList = getAttendedCoursesForUser(friend); // foreach (var course in courseList) // { // if (coursePopularity.ContainsKey(course)) coursePopularity[course] = coursePopularity[course] + 1; // else // { // coursePopularity.Add(course, 1); // } // } // } // return coursePopularity; // } // /// <summary> // /// Gets upto level 2 friends given user // /// </summary> // /// <param name="user">user name</param> // /// <returns>A list of direct and friends of direct friends </returns> // private List<string> GetApplicableFriendsForUser(string user) // { // //Level 1 friend // var directFriends = getDirectFriendsForUser(user); // var applicableFriendsList = new HashSet<string>(directFriends); // //Level 2 friends // foreach (var directFriend in directFriends) // { // var freinds = getDirectFriendsForUser(directFriend); // foreach (var friend in freinds) // { // //Ensure friends are not duplicated.. // if (!applicableFriendsList.Contains(friend)) applicableFriendsList.Add(friend); // } // } // //Result // return applicableFriendsList.ToList(); // } // private List<string> getAttendedCoursesForUser(string user) // { // throw new NotImplementedException(); // } // private List<string> getDirectFriendsForUser(string user) // { // throw new NotImplementedException(); // } // } //}
9751b6154c655c0c66ad7b262b2d0657cfa54475
C#
neotys-rd/rest-design-api
/model/CloseProjectParams.cs
2.515625
3
using Neotys.CommonAPI.Utils; using System; /* * Copyright (c) 2016, Neotys * All rights reserved. */ namespace Neotys.DesignAPI.Model { /// <summary> /// CloseProject is the method sent to the Design API Server. /// /// @author lcharlois /// /// </summary> public class CloseProjectParams : IComparable<CloseProjectParams> { private readonly bool forceStop; private readonly bool save; internal CloseProjectParams(CloseProjectParamsBuilder closeProjectParamsBuilder) { this.forceStop = closeProjectParamsBuilder.ForceStop; this.save = closeProjectParamsBuilder.Save; } public virtual bool ForceStop { get { return forceStop; } } public virtual bool Save { get { return save; } } public override string ToString() { return new ToStringBuilder<CloseProjectParams>(this).ReflectionToString(this); } public virtual int CompareTo(CloseProjectParams o) { return this.ToString().CompareTo(o.ToString()); } public override int GetHashCode() { return new HashCodeBuilder<CloseProjectParams>(this) .With(m => m.forceStop) .With(m => m.save) .HashCode; } public override bool Equals(object obj) { if (!(obj is CloseProjectParams)) { return false; } return new EqualsBuilder<CloseProjectParams>(this, obj) .With(m => m.forceStop) .With(m => m.save) .Equals(); } } }
0a7d0c4770af02712c916df4fba9f045d8375e0b
C#
credfeto/GallerySync
/src/Credfeto.Gallery.Image/ImageHelpers.cs
3.015625
3
using System; using System.Diagnostics.Contracts; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; namespace Credfeto.Gallery.Image; internal static class ImageHelpers { public static bool IsValidJpegImage(byte[] bytes, string context) { try { using (SixLabors.ImageSharp.Image.Load(data: bytes, out IImageFormat format)) { return format.DefaultMimeType == "image/jpeg"; } } catch (Exception exception) { Console.WriteLine(format: "Error: {0}", arg0: context); Console.WriteLine(format: "Error: {0}", arg0: exception); return false; } } /// <summary> /// Rotates the image if necessary. /// </summary> /// <param name="image"> /// The image. /// </param> /// <param name="degrees"> /// The degrees to rotate. /// </param> /// <remarks> /// Only 0, 90, 180 and 270 degrees are supported. /// </remarks> public static void RotateImageIfNecessary<TPixel>(Image<TPixel> image, int degrees) where TPixel : unmanaged, IPixel<TPixel> { Contract.Requires(image != null); Contract.Requires(degrees == 0 || degrees == 90 || degrees == 180 || degrees == 270); switch (degrees) { case 0: // No need to rotate return; case 90: // Rotate 90 degrees clockwise image.Mutate(operation: ctx => ctx.Rotate(degrees: 90)); return; case 180: // Rotate upside down image.Mutate(operation: ctx => ctx.Rotate(degrees: 180)); return; case 270: // Rotate 90 degrees anti-clockwise image.Mutate(operation: ctx => ctx.Rotate(degrees: 270)); return; default: // unknown - so can't rotate; return; } } }
ab019277c8a836882777acc27f1fb3fb03cfad97
C#
undrfined/undrClient
/back/MiNET/Blocks/Button.cs
2.578125
3
using System.Numerics; using MiNET.Utils; using MiNET.Worlds; namespace MiNET.Blocks { public abstract class Button : Block { public int TickRate { get; set; } protected Button(byte id) : base(id) { IsSolid = false; IsTransparent = true; BlastResistance = 2.5f; Hardness = 0.5f; } public override bool PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords) { Metadata = (byte) face; world.SetBlock(this); return true; } public override bool Interact(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoord) { Metadata = (byte) (Metadata | (0x8)); world.SetBlock(this); world.ScheduleBlockTick(this, TickRate); return true; } public override void OnTick(Level level, bool isRandom) { if (isRandom) return; Metadata = (byte) (Metadata & (0x7)); level.SetBlock(this); } } }
3a9524f91977cd200a32df185cecb16090a7e54c
C#
webmaster442/BookGen
/Libs/BookGen.Gui/Palette.cs
3.140625
3
using Spectre.Console; namespace BookGen.Gui; internal class Palette { private readonly Color[] _colors; private int _index; public Palette() { Random rnd = new Random(2); _colors = Generate(rnd, 32); _index = 0; } private static Color[] Generate(Random rnd, int count) { static Color Generate(Random rnd) { byte r = (byte)(rnd.Next(128) + 127); byte g = (byte)(rnd.Next(128) + 127); byte b = (byte)(rnd.Next(128) + 127); return new Color(r, g, b); } Color[] result = new Color[count]; for(int i=0; i<count; i++) { result[i] = Generate(rnd); } return result; } public void Reset() => _index = 0; public Color GetNextColor() { Color ret = _colors[_index]; _index = (_index + 1) % _colors.Length; return ret; } }
550e6838c826401b57f6acd55479bbb1c77758eb
C#
0xF6/Fluent.Sudo
/Fluent.sudo/Platforms/MacOS.cs
2.546875
3
namespace Fluent.sudo.Platforms { using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Etc; using Microsoft.Extensions.Logging; using MoreLinq; public class MacOS : ICommandExecuter { private readonly ILogger<MacOS> log; public MacOS() => log = Log.Get<MacOS>(); public async Task<ExecuteResult> Execute(string cmd, TimeSpan timeoutWait) { var tmp = Path.GetTempPath(); var uid = Guid.NewGuid().ToString(); var instanceID = Path.Combine(tmp, uid); var cwd = Directory.GetCurrentDirectory(); var zip = Path.Combine(instanceID, "sudo.zip"); Directory.CreateDirectory(instanceID); void cleanUp() { Directory.GetFiles(instanceID).Pipe(File.Delete).ForEach(x => log.LogTrace($"Remove '{x}'.")); Directory.Delete(instanceID, true); } File.WriteAllBytes($"{Path.Combine(instanceID, "sudo.zip")}", Convert.FromBase64String(APPLET)); await Process.Start("/usr/bin/unzip", $"-o {zip.E('"')} -d {instanceID.E('"')}").WaitForExitAsync(); var plist = new[] { "Contents", "Info.plist" }.Aggregate(instanceID, Path.Combine); const string key = "CFBundleName"; const string value = "sudo.app Password Prompt"; // TODO get app title in osx await Process.Start("/usr/bin/defaults", $"write {plist.E('"')} {key.E('"')} {value.E('"')}").WaitForExitAsync(); var cmdPath = new[] { "Contents", "MacOS", "sudo-prompt-command" }.Aggregate(instanceID, Path.Combine); File.WriteAllText(cmdPath, $"cd {cwd.E('"')}\n{cmd}"); var proc = new Process(); var binPath = new []{ "Contents", "MacOS", "applet" }.Aggregate(instanceID, Path.Combine); proc.StartInfo = new ProcessStartInfo($"./{Path.GetFileName(binPath)}") { WorkingDirectory = Path.GetFullPath(binPath) }; cwd = new[] { "Contents", "MacOS" }.Aggregate(instanceID, Path.Combine); Expression<Func<string, string>> raw = s => Path.Combine(cwd, s).AsFile().When(x => x.Exists, x => x.ReadAll()); var exp = raw.Compile(); var status = exp("status"); var stderr = exp("stderr"); var stdout = exp("stdout"); var result = ElevateResult.UNK; if (status == null) result = ElevateResult.PERMISSION_DENIED; else if (stdout == null) result = ElevateResult.ERROR; else { var status_code = int.Parse(status.Trim()); result = status_code == 0 ? ElevateResult.SUCCESS : ElevateResult.ERROR; } cleanUp(); return new ExecuteResult(result, stdout, stderr, status); } private static readonly string APPLET = "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"; } }
3e0af63bc4cfba4a20254c18a43f6ee0665c96b0
C#
Syngon/java-menace-master
/java-menace/java-menace/Movement/CollisionManager.cs
2.796875
3
using System.Collections.Generic; using System.Linq; using System.Numerics; using Windows.System; namespace java_menace.Movement { class CollisionManager { private List<Collider> Colliders; private Dictionary<VirtualKey, VirtualKey> ReverseKey; public CollisionManager() { Colliders = new List<Collider>(); ReverseKey = new Dictionary<VirtualKey, VirtualKey>() { { VirtualKey.W, VirtualKey.S}, { VirtualKey.S, VirtualKey.W}, { VirtualKey.A, VirtualKey.D}, { VirtualKey.D, VirtualKey.A} }; } public void AddCollider(Collider c) { Colliders.Add(c); c.CheckCollisionRequest += OnCheckCollisionRequest; } public void RemoveCollider(Collider c) { if (Colliders.Contains(c)){ Colliders.Remove(c); } } public void OnCheckCollisionRequest(object sender, CollisionRequestArgs e) { var RequestorCollider = (Collider)sender; var WatchedColliders = Colliders.Where(x => Vector2.Distance(RequestorCollider.VerticesCoordinates["Center"], x.VerticesCoordinates["Center"]) <= 72 && x != RequestorCollider); bool IsColliding = false; var _WatchedVertices = WatchedVertices(RequestorCollider, e.Key); foreach (var Collider in WatchedColliders) { if (IsInside(_WatchedVertices[0], Collider) && IsInside(_WatchedVertices[1], Collider)) { IsColliding = true; RequestorCollider.IsColliding[e.Key] = true; } } if (!IsColliding) { RequestorCollider.IsColliding[e.Key] = false; } } private Vector2[] WatchedVertices(Collider c, VirtualKey Key) { var Points = new Vector2[2]; Vector2[] AdjustmentVector; if (Key == VirtualKey.W || Key == VirtualKey.S) AdjustmentVector = new Vector2[] { new Vector2(1, 0), new Vector2(-1, 0) }; else AdjustmentVector = new Vector2[] { new Vector2(0, 1), new Vector2(0, -1) }; switch (Key) { case VirtualKey.W: Points[0] = (c.VerticesCoordinates["Top-Left"]); Points[1] = (c.VerticesCoordinates["Top-Right"]); break; case VirtualKey.S: Points[0] = (c.VerticesCoordinates["Bottom-Left"]); Points[1] = (c.VerticesCoordinates["Bottom-Right"]); break; case VirtualKey.A: Points[0] = c.VerticesCoordinates["Top-Left"]; Points[1] = c.VerticesCoordinates["Bottom-Left"]; break; case VirtualKey.D: Points[0] = c.VerticesCoordinates["Top-Right"]; Points[1] = c.VerticesCoordinates["Bottom-Right"]; break; } Points[0] += AdjustmentVector[0]; Points[1] += AdjustmentVector[1]; return Points; } private bool IsInside(Vector2 Vertice, Collider c) { if (Vertice.X < c.VerticesCoordinates["Top-Right"].X && Vertice.X > c.VerticesCoordinates["Top-Left"].X) { if (Vertice.Y > c.VerticesCoordinates["Top-Right"].Y && Vertice.Y < c.VerticesCoordinates["Bottom-Right"].Y) { return true; } } return false; } } }
286bea169c7359b2d8e276926e2cad85959c8fa3
C#
JamesFitz2304/Crossword-Generator
/CrosswordGenerator/GenerationManager/Generation.cs
2.875
3
using System; using System.Collections.Generic; using CrosswordGenerator.Generator.Models; namespace CrosswordGenerator.GenerationManager { public class Generation { public LetterBlock[,] Blocks; public readonly IList<PlacedWord> PlacedWords; public readonly IList<string> UnplacedWords; public Generation(LetterBlock[,] blocks, IList<PlacedWord> placedWords, IList<string> unplacedWords) { Blocks = blocks; PlacedWords = placedWords; UnplacedWords = unplacedWords; } public int NumberOfUnplacedWords => UnplacedWords.Count; public int BlocksSize => Blocks.GetLength(0) * Blocks.GetLength(1); public int XSize => Blocks.GetLength(1); public int YSize => Blocks.GetLength(0); public double SizeRatio => (double)Math.Min(XSize, YSize)/Math.Max(XSize, YSize); } }
b1ea2c2057384ae6b44f1b54ae03e6f058c279f2
C#
MangoNotation/MangoObjectNotation
/MangoObjectNotation/Parsing/PMethods.cs
3.5625
4
using System; using System.Collections.Generic; using System.Text; namespace MangoObjectNotation.Parsing { static class PMethods { public static string[] Tear(string text) { //Tear string into string[] where each member is one character of string //"dog" -> "d","o","g" int length = text.Length; string[] chars = new string[length]; for(int i = 0; i < length; i++) { chars[i] = text.Substring(i, 1); } return chars; } } }
b5d69cfaf44d236bb7f42327847d59f197c3e26e
C#
MarcioOlv95/CrudFuncionarios
/Business/Services/FuncionarioService.cs
2.703125
3
using Business.Interfaces; using Business.Models.Validations; using CrudFuncionarios.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.Services { public class FuncionarioService : IFuncionarioService { private readonly IFuncionarioRepository _funcionarioRepository; public FuncionarioService(IFuncionarioRepository funcionarioRepository) { _funcionarioRepository = funcionarioRepository; } public Task<bool> Atualizar(Funcionario funcionario) { var validator = new FuncionarioValidation(); var result = validator.Validate(funcionario); if (!result.IsValid) { return Task.FromResult(false); } if (funcionario.HabilidadeL != null) { funcionario.Habilidade = string.Join(",", funcionario.HabilidadeL); } int idade = DateTime.Now.Year - funcionario.DataNascimento.Year; if (DateTime.Now.DayOfYear < funcionario.DataNascimento.DayOfYear) idade = idade - 1; funcionario.Idade = idade; return _funcionarioRepository.Atualizar(funcionario); } public Task<Funcionario> Obter(int id) { return _funcionarioRepository.Obter(id); } public Task<List<Funcionario>> ObterTodos() { return _funcionarioRepository.ObterTodos(); } } }
9dbb46961ec154008ef83a55300002b40a3a26da
C#
Mike-Wazowski/PKRY-Server
/PKRY.Messages/Message.cs
2.734375
3
namespace PKRY.Messages { public class Message { public string Content { get; set; } public string Username { get; set; } public Message() { } public Message(string username, string content) { Content = content; Username = username; } public static Message Deserialize(BaseMessage baseMessage) { var deserializer = new MessageDeserializer<Message>(); return deserializer.Deserialize(baseMessage); } } }
b156e1c4e8100c6c8229dc19c0c3f81fcee5d2f7
C#
ashurja/BreakOut
/Assets/Scrits/Paddle.cs
2.6875
3
// Jamshed Ashurov // 03/15/18 // This is the script that moves and clamps the paddle using System.Collections; using System.Collections.Generic; using UnityEngine; public class Paddle : MonoBehaviour { public float paddleSpeed = 1f; private Vector3 playerPos = new Vector3 (0, -9.5f, 0); // Update is called once per frame void Update () { // Clamps the paddle so that it would not go out of the screen float xPos = transform.position.x + (Input.GetAxis ("Horizontal") * paddleSpeed); playerPos = new Vector3 (Mathf.Clamp (xPos, -8f, 8f), -9.5f, 0f); transform.position = playerPos; } }
1edef581b37410fd6bf37e3cd17336c09bc67ff7
C#
jquentin/ArtUnfrozen
/Okja/Assets/TigglyUtils/RandomUtils/SpawnAreaMonoBehaviour.cs
3.015625
3
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Class implementing the SpawnArea interface, that is also a MonoBehaviour. /// Using this class to declare a variable in a script will allow Unity Editor to /// expose the variable, leaving you free to select an instance of any sub-class. /// Example: /// public class Spawner : MonoBehaviour { /// public SpawnAreaMonoBehaviour spawnArea; /// } /// The editor will let you drag in any object inheriting SpawnAreaMonoBehaviour, /// no matter what technical implementation this object uses. /// </summary> public abstract class SpawnAreaMonoBehaviour : MonoBehaviour, SpawnArea { public abstract Vector3 PickPosition(bool local); public abstract List<Vector3> PickPositions(int number, float minDistance, bool local); }
c9492f6a4d9a999b1c90017549b62c2b41473891
C#
julyvz/5PFFE
/1ActivationKeys/Program.cs
3.515625
4
using System; namespace _1ActivationKeys { class Program { static void Main(string[] args) { string rawKey = Console.ReadLine(); string input = Console.ReadLine(); while (input != "Generate") { string[] tokens = input.Split(">>>"); switch (tokens[0]) { case "Contains": if (rawKey.Contains(tokens[1])) { Console.WriteLine($"{rawKey} contains {tokens[1]}"); } else { Console.WriteLine("Substring not found!"); } break; case "Flip": int startIdx = int.Parse(tokens[2]); int endIdx = int.Parse(tokens[3]); int count = endIdx - startIdx; string piece = rawKey.Substring(startIdx, count); rawKey = rawKey.Remove(startIdx, count); if (tokens[1] == "Upper") { piece = piece.ToUpper(); } else { piece = piece.ToLower(); } rawKey = rawKey.Insert(startIdx, piece); Console.WriteLine(rawKey); break; case "Slice": startIdx = int.Parse(tokens[1]); endIdx = int.Parse(tokens[2]); count = endIdx - startIdx; rawKey = rawKey.Remove(startIdx, count); Console.WriteLine(rawKey); break; default: Console.WriteLine("Wrong input!"); break; } input = Console.ReadLine(); } Console.WriteLine($"Your activation key is: {rawKey}"); } } }
b7ccf3a7bd4a86f67b8ac8e86b06feacffd4dc54
C#
Bassman2/TheTVDBWebApi
/Src/TheTVDBWebApiShare/TVDBWeb.Awards.cs
2.640625
3
namespace TheTVDBWebApi { public partial class TVDBWeb { /// <summary> /// Returns a list of award base records. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>List of award base records.</returns> public async Task<List<AwardBaseRecord>> GetAwardsAsync(CancellationToken cancellationToken = default) { return await GetDataAsync<List<AwardBaseRecord>>("v4/awards", cancellationToken); } /// <summary> /// Returns a single award base record. /// </summary> /// <param name="id">Id of the award base record.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Single award base record.</returns> public async Task<AwardBaseRecord> GetAwardAsync(long id, CancellationToken cancellationToken = default) { return await GetDataAsync<AwardBaseRecord>($"v4/awards/{id}", cancellationToken); } /// <summary> /// Returns a single award extended record. /// </summary> /// <param name="id">Id of the award extended record.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Single award extended record.</returns> public async Task<AwardExtendedRecord> GetAwardExtendedAsync(long id, CancellationToken cancellationToken = default) { return await GetDataAsync<AwardExtendedRecord>($"v4/awards/{id}/extended", cancellationToken); } /// <summary> /// Returns a single award category base record. /// </summary> /// <param name="id">Id of the award category base record.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Single award category base record.</returns> public async Task<AwardCategoryBaseRecord> GetAwardCategoryAsync(long id, CancellationToken cancellationToken = default) { return await GetDataAsync<AwardCategoryBaseRecord>($"v4/awards/categories/{id}", cancellationToken); } /// <summary> /// Returns a single award category extended record. /// </summary> /// <param name="id">Id of the award category extended record.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Single award category extended record.</returns> public async Task<AwardCategoryExtendedRecord> GetAwardCategoryExtendedAsync(long id, CancellationToken cancellationToken = default) { return await GetDataAsync<AwardCategoryExtendedRecord>($"v4/awards/categories/{id}/extended", cancellationToken); } } }
e3a4a6eb093e1f7554f3298f58886192fdef8f11
C#
randymcbride/LevelingUp
/DesignPatterns/Command/Classes/CommandQueue.cs
3.34375
3
using System.Collections.Generic; namespace DesignPatterns.Command.Classes { public class CommandQueue { private Queue<ICommand> commands = new Queue<ICommand>(); private bool processing; public static int FailureLimit = 4; public int TotalAttempts { get; private set; } public int FailCount { get; private set; } public void Add(ICommand command) { command.OnFail = failedCommand => { if (failedCommand.FailCount < FailureLimit) commands.Enqueue(failedCommand); else FailCount++; }; commands.Enqueue(command); InitiateProcessing(); } private void InitiateProcessing() { if (!processing) { processing = true; ProcessCommands(); processing = false; } } private void ProcessCommands() { ICommand currentCommand; while (commands.TryDequeue(out currentCommand)) { TotalAttempts++; currentCommand.ExecuteAsync(); }; } } }
8935a72b2ff2912eab89a85f8e751d02935a36b8
C#
superjacobl/SpookVooper
/SpookVooper/VoopAI/Game/Entities.cs
2.84375
3
using System; using System.Collections.Generic; using System.Text; namespace SpookVooper.VoopAIService.Game { public class GameEntity { public string _name; public string _adjective; public bool dead = false; public virtual int GetXP() { return (int)(baseUnit.maxhealth / 10f); } public string name { get { return $"{_adjective} {_name}"; } } public List<Item> items; private int _health; public int health { get { return _health; } set { _health = value; if (_health <= 0) { dead = true; _health = 0; } } } public Unit baseUnit; public GameEntity(Unit baseUnit) { this._name = Randoms.names.PickRandom(); this._adjective = Randoms.people_adjectives.PickRandom(); items = new List<Item>(); items.Add(new ItemFist()); int itemCount = VoopAI.random.Next(3); // Add two random possible items for (int i = 0; i < itemCount; i++) { items.Add(baseUnit.items.PickRandom()); } this.baseUnit = baseUnit; health = baseUnit.maxhealth; } } public class Player : GameEntity { public int coins; public int xp; public Player(Unit unit) : base(unit) { items = new List<Item>(); int itemCount = VoopAI.random.Next(5); items.Add(new ItemFist()); health *= 2; // Add two random possible items for (int i = 0; i < itemCount; i++) { items.Add(baseUnit.items.PickRandom()); } } } }
310919635b79b7137c9d11add8b113b41ca498e4
C#
Reatir/RandomGenerator
/RandomGenerator/RandomGenerator/Views/Random number generator.cs
2.859375
3
using RandomGenerator.Models; using RandomGenerator.Presenters; using RandomGenerator.Views; using System; using System.Windows.Forms; namespace RandomGenerator { public partial class RandomNumberGeneratorView : Form { public PresenterRandomNumberGenerator _Presenter { get; set; } public RandomNumberGeneratorView() { InitializeComponent(); } private void txtBotLimit_TextChanged(object sender, EventArgs e) { try { _Presenter.OnBotLimitChanged(int.Parse(txtBotLimit.Text)); } catch (Exception) { MessageBox.Show("la borne basse n'est pas un entier"); } } private void txtTopLimit_TextChanged(object sender, EventArgs e) { try { _Presenter.OnTopLimitChanged(int.Parse(txtTopLimit.Text)); } catch (Exception) { MessageBox.Show("la borne haute n'est pas un entier"); } } private void btGenerate_Click(object sender, EventArgs e) { if(txtBotLimit.Text != "" && txtTopLimit.Text !="" ) { _Presenter.OnGenerateClicked(); } else { MessageBox.Show("Le champ des bornes ne doivent pas être laisser vide"); } } public void UpdateView(int result_) { lblResult.Text = result_.ToString(); } public void UpdatePanelList(int result_) { Label label = new Label(); label.Text = result_.ToString(); PanelListResult.Controls.Add(label); } private void MenuItemPickNumber_Click(object sender, EventArgs e) { } private void MenuItemPickString_Click(object sender, EventArgs e) { ModelRandomStringGenerator model = new ModelRandomStringGenerator(); ViewRandomStringGenerator view = new ViewRandomStringGenerator(); PresenterRandomStringGenerator presenter = new PresenterRandomStringGenerator(view, model); view.Visible = true; this.Visible = false; } private void MenuItemSortList_Click(object sender, EventArgs e) { } } }
2ede2091acc8116e6b2604105eda4e986eb52fbd
C#
kerecsenlaci/ClientRegistry
/ClientRegistry/ViewModel/LoginVM.cs
2.734375
3
using CRegistry.Dal; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace ClientRegistry { public class LoginVM { DataManager context = new DataManager(); public User AuthenticateUser { get; set; } public string UserName { get; set; } public string Password { get; set; } public LoginVM() { if (context.GetParameretValue("NoLogin") == "Yes") AuthenticateUser = new User(context.GetUser().First(x => x.ID == -1)); } public bool Authentication() { var user = context.GetUser().FirstOrDefault(x => x.Name == UserName && x.Password == Password); if (user != null) { AuthenticateUser = new User(user); return true; } return false; } public static string GetMd5Hash(MD5 md5Hash, string input) { byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } } }
1d032b898df934d635fc091e5b09fcd58517d86e
C#
joeiren/smarths
/SmartHaiShu.WcfService/OpenDataLogic/BikeLocationLogic.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SmartHaisuModel; namespace SmartHaiShu.WcfService.OpenDataLogic { /// <summary> /// 自行车分布点位 /// </summary> public class BikeLocationLogic { /// <summary> /// 记录数 /// </summary> /// <returns></returns> public int BikeLocationCount() { var count = (from entity in ContextFactory.GetOpenDataContext().Db_b_t_ufp_0003_yh select entity).Count(); return count; } /// <summary> /// 分页获取 自行车分布点位 /// </summary> /// <param name="pageNo"></param> /// <param name="pageSize"></param> /// <returns></returns> public IEnumerable<b_t_ufp_4_1_2> LoadBikeLocation(int pageNo, int pageSize) { var result = (from entity in ContextFactory.GetOpenDataContext().Db_b_t_ufp_4_1_2 orderby entity.RELEASE_TIME descending, entity.CHECK_TIME descending select entity).Skip(Math.Max(0, pageNo - 1) * pageSize).Take(pageSize); return result; } } }
9561e25bcefa9025f291b13d9559753bca1a8364
C#
BasicLich/Hooks
/Assets/Scripts/State Machine/StateMachine.cs
2.890625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StateMachine : MonoBehaviour { public State state; private void Start() { if (this.state != null) { this.state.Enter(); } } public void Update() { if(this.state == null) { Debug.Log("State Machine " + this.gameObject.name + " has no state!", this.gameObject); return; } State newState = this.state.Execute(); if (newState != null) { this.Transition(newState); } } public void FixedUpdate() { if (this.state == null) { Debug.Log("State Machine " + this.gameObject.name + " has no state!", this.gameObject); return; } State newState = this.state.FixedExecute(); if (newState != null) { this.Transition(newState); } } public void Transition(State newState) { if (newState == null) return; if (this.state != null) { this.state.Exit(); } newState.PreviousState = this.state; this.state = newState; newState.Enter(); } }
aa749b1590af09a69c0e310ee3c961961b737a3b
C#
PlumpMath/DesignPattern-Projects
/AbstractFactoryPattern/AbstractEmployees/AbstractFactory.cs
2.84375
3
namespace AbstractFactoryPattern.AbstractEmployees { /// <summary> /// The 'AbstractFactory' abstract class /// </summary> abstract class AbstractFactory { public abstract AbstractEmployeeA CreateEmployeeA(); public abstract AbstractEmployeeB CreateEmployeeB(); } }
821279b1d5857a6b2565d53c1e8fe6b5d0bfc73e
C#
claupcv/Internship
/claupcv/2017/mai/Curs09mai/Curs09mai/Program.cs
3.4375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Curs09mai { class Program { static void Main(string[] args) { var array = new[] {1, 2, 3, 4, 5, 6, 7}; var queryEven = array.Where((int elem ) => { return elem % 2 != 0}); int[] set1 = new[] { 1, 4, 5, 3, 8, 9 }; int[] set2 = new[] { 2, 6, 9, 3 }; var result = set1.SelectMany( e1 => set2, (e1, e2) => new Tuple<int, int>(e1, e2)) .Where( tuple => (tuple.Item1 == tuple.Item2 - 1) || (tuple.Item1 == tuple.Item2 + 1)) .Select(tuple => $"{tuple.Item1}{tuple.Item2}"); foreach (int e in result) { Console.Write(e + ", "); } foreach (string e in result) { Console.Write($"{e.}"); } } } }
8b7e5396f2a09e353dd3ec851bf17a7fbe475a33
C#
NanishiTakana/StudyDelivarable
/Naruhodo/Chapter15/15-1/15-1/Program.cs
3.234375
3
using System; namespace _15_1 { class Program { static void Main(string[] args) { var array = new int[5] { 1,2,2,2,4 }; try { Console.WriteLine(array[5]); } catch(Exception ex) { Console.WriteLine( $"Type : {ex.GetType().Name}"); Console.WriteLine($"Type : {ex.Message}"); } } } }
923133649197d4540feff8cd66f6c37ee86b9210
C#
dalkumar500/badge
/CHALLENGE_3BADGE/ProgramUI.cs
3.40625
3
using Library; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CHALLENGE_3BADGE { class ProgramUI { private BadgeRepository _badgeRepo = new BadgeRepository(); //Method that Runs/Start the Application public void Run() { SeedItemsList(); Menu(); } private void Menu() { bool keepRunning = true; while (keepRunning) { //Display our option to the user Console.WriteLine("Select a Menu option:\n" + "1. Create a new badge\n" + "2. Update doors on an existing badge\n" + "3. Delete all doors from an existing badge\n" + "4. Show a list with all badge numbers and door access\n" + "5.Exit"); //Get the user's input string input = Console.ReadLine(); //Evaluate the user's input and act acoordingly switch (input) { case "1": //Create A new Badge CreateNewBadge(); break; case "2": //Update doors on an existing badge UpdateExicitingdoor(); break; case "3": //Delete all doors from an existing badge DeleteAllExistingDoors(); break; case "4": //Show a list with all badge numbers and door access ShowAList(); break; case "5": //Exit Console.WriteLine("Goodbye!"); keepRunning = false; break; default: Console.WriteLine("please enter a valid number"); break; } Console.WriteLine("please press any key to continue.."); Console.ReadKey(); Console.Clear(); } } // create new MenuContent private void CreateNewBadge() { Console.Clear(); Badge name = new Badge(); //Badge Console.WriteLine("Enter the badgeid:"); string badgeidASString = Console.ReadLine(); name.BadgeID = int.Parse(badgeidASString); //DoorNames Console.WriteLine("Enter the doornames seprated by space: "); string doorNames = Console.ReadLine(); name.DoorNames = doorNames.Split(' ').ToList(); //A name for the Badge Console.WriteLine("Enter the name for the badge:"); name.Anameforthebadge = Console.ReadLine(); _badgeRepo.Add(name); } //Update doors on an existing badge private void UpdateExicitingdoor() { } //Delete all doors from an existing badge private void DeleteAllExistingDoors() { // Get the meal they want to remove Console.WriteLine("\nEnter the BadgeID Number you'd like to remove:"); int input = int.Parse(Console.ReadLine()); // call the delete method bool wasDeleted = _badgeRepo.RemoveAllDoors(input); //If the BadgeID was deleated, say so // Otherwise say it could not be deleated if (wasDeleted) { Console.WriteLine("The BadgeId was successfully deleated"); } else { Console.WriteLine("The BadgeId Could not be delated."); } } //Show a list with all badge numbers and door access private void ShowAList() { } private void SeedItemsList() { Badge badgeid1 = new Badge(1222, new List <string>{"A4"}, "Steve" ); Badge badgeid2 = new Badge(1235, new List<string> { "A5" }, "john"); Badge badgeid3 = new Badge(1240, new List<string> { "B2" }, "Amy"); Badge badgeid4 = new Badge(1245, new List<string> { "B6" }, "April"); Badge badgeid5 = new Badge(1250, new List<string> { "A7" }, "Mike"); _badgeRepo.Add(badgeid1); _badgeRepo.Add(badgeid2); _badgeRepo.Add(badgeid3); _badgeRepo.Add(badgeid4); _badgeRepo.Add(badgeid5); } } }
6942cb393eba7d4f075b30703d1a8602dc77442f
C#
Matthijsvanspelde/Project-S2
/SocialNetwork.Logic/FriendRequestLogic.cs
2.59375
3
using SocialNetwork.DAL.IRepositories; using SocialNetwork.Logic.ILogic; using SocialNetwork.Models; using System.Collections.Generic; namespace SocialNetwork.Logic { public class FriendRequestLogic : IFriendRequestLogic { private readonly IFriendRequestRepository _FriendRequestRepository; public FriendRequestLogic(IFriendRequestRepository FriendRequestRepository) { _FriendRequestRepository = FriendRequestRepository; } public bool SendFriendRequest(FriendRequest friendRequest) { if (friendRequest.SenderId != friendRequest.RecieverId && !DoesFriendRequestExist(friendRequest) && !IsFollowing(friendRequest)) { return _FriendRequestRepository.SendFriendRequest(friendRequest); } else { return false; } } public void DeleteFriendRequest(FriendRequest friendRequest) { _FriendRequestRepository.DeleteFriendRequest(friendRequest); } public void AcceptFriendRequest(FriendRequest friendRequest) { _FriendRequestRepository.AcceptFriendRequest(friendRequest); } public bool DoesFriendRequestExist(FriendRequest friendRequest) { return _FriendRequestRepository.DoesFriendRequestExist(friendRequest); } public bool IsFollowing(FriendRequest friendRequest) { return _FriendRequestRepository.IsFollowing(friendRequest); } public IEnumerable<FriendRequest> GetFriendRequests(FriendRequest friendRequest) { return _FriendRequestRepository.GetFriendRequests(friendRequest); } } }
7f9059fcd0e0ff9640247d33e37d71c3c6ff5fe5
C#
riswey/ArduinoController
/Arduino/Parameters.cs
2.921875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Arduino { class ParameterState { public float p { get; set; } public float i { get; set; } public float d { get; set; } public int pulse_delay { get; set; } public long min_period { get; set; } public long max_period { get; set; } public float target_speed { get; set; } public float rotor_speed { get; set; } public string path { get; set; } private long start_t { get; set; } public static long GetTime() //millisecond time { return (long)Math.Round(DateTimeOffset.Now.UtcTicks / 10000.0d, 0); } //RM (Req. Min/Max) Timer pause //Put a timer block on Min/Max calls //Start/SetFreq reset min/max which takes 2s to stabilise const long RM_TIMER_PERIOD = 2000; long rm_timer { get; set; } = 0; public void StartRMTimer() { //Start/SetFreq events reset the MaxMin buffer //Takes time to give meaningful results rm_timer = GetTime(); } public bool IsRMDisabled() { return (GetTime() - rm_timer) > RM_TIMER_PERIOD; } public void Start(string path = "") { this.path = path; doWrite("-------------------------------------------\r\nt\tTarget\tActual\tP\tI\tD\tDelay\tMin\tMax"); start_t = GetTime(); } private void doWrite(string str) { using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + "Log.dat", true)) { file.WriteLine(str); } } public bool IsMMInRange() { return min_period != 1E7 && max_period != 0; } public void Write() { if (!IsMMInRange()) { //Don't log if min/max still at starting values return; } long millisecs = GetTime() - start_t; string str = String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}", millisecs, target_speed, rotor_speed, p, i, d, pulse_delay, min_period, max_period ); doWrite(str); } } }