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
683b3b85fdd27377a76df1a1101f93d0537fc140
C#
Minie17/days
/params/params/Program.cs
3.140625
3
using System; namespace param { class Program { static void Main(string[] args) { int add1 = Addition(1); int add2 = Addition(2, 2, 2, 2); int[] addarray = new int[3] { 3, 3, 3 }; int add3 = Addition(addarray); } static int Addition(params int[] values) { int answer = 0; foreach (int value in values) { answer += value; } return answer; } } }
cb5028b7006849a1f58ceb3c9420cc63d47ff45a
C#
toshinomi/Windows.Form
/CSharp/ImageProcessing/Lib/ComImageProcessingInfo.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// 画像処理の設定管理のロジック /// </summary> public class ComImageProcessingInfo { /// <summary> /// 現在の画像処理の名称 /// </summary> public string CurrentImageProcessingName { set; get; } /// <summary> /// エッジ検出の設定 /// </summary> public EdgeDetectionInfo EdgeDetectoinInfo { set; get; } /// <summary> /// グレースケールの設定 /// </summary> public GrayScaleInfo GrayScaleInfo { set; get; } /// <summary> /// 2値化の設定 /// </summary> public BinarizationInfo BinarizationInfo { set; get; } /// <summary> /// グレースケール2次微分の設定 /// </summary> public GrayScale2DiffInfo GrayScale2DiffInfo { set; get; } /// <summary> /// 色反転の設定 /// </summary> public ColorReversalInfo ColorReversalInfo { set; get; } /// <summary> /// コンストラクタ /// </summary> public ComImageProcessingInfo() { EdgeDetectoinInfo = new EdgeDetectionInfo(); GrayScaleInfo = new GrayScaleInfo(); BinarizationInfo = new BinarizationInfo(); GrayScale2DiffInfo = new GrayScale2DiffInfo(); ColorReversalInfo = new ColorReversalInfo(); } /// <summary> /// デスクトラクタ /// </summary> ~ComImageProcessingInfo() { } } /// <summary> /// エッジ検出の設定管理のロジック /// </summary> public class EdgeDetectionInfo { /// <summary> /// コンストラクタ /// </summary> public EdgeDetectionInfo() { } /// <summary> /// デスクトラクタ /// </summary> ~EdgeDetectionInfo() { } } /// <summary> /// グレースケールの設定管理のロジック /// </summary> public class GrayScaleInfo { /// <summary> /// コンストラクタ /// </summary> public GrayScaleInfo() { } /// <summary> /// デスクトラクタ /// </summary> ~GrayScaleInfo() { } } /// <summary> /// 2値化の設定管理のロジック /// </summary> public class BinarizationInfo { /// <summary> /// 閾値 /// </summary> public byte Thresh { set; get; } /// <summary> /// コンストラクタ /// </summary> public BinarizationInfo() { } /// <summary> /// デスクトラクタ /// </summary> ~BinarizationInfo() { } } /// <summary> /// グレースケール2次微分の設定管理のロジック /// </summary> public class GrayScale2DiffInfo { /// <summary> /// コンストラクタ /// </summary> public GrayScale2DiffInfo() { } /// <summary> /// デスクトラクタ /// </summary> ~GrayScale2DiffInfo() { } } /// <summary> /// 色反転の設定管理のロジック /// </summary> public class ColorReversalInfo { /// <summary> /// コンストラクタ /// </summary> public ColorReversalInfo() { } /// <summary> /// デスクトラクタ /// </summary> ~ColorReversalInfo() { } }
1520d9a3a25471f2e64f627ad7b2f36d25c53a35
C#
joelwjx/space-OSHA-re
/space-OSHA-re/Assets/Scripts/ScaleBounceLoop.cs
2.609375
3
using System.Collections; using UnityEngine; public class ScaleBounceLoop : MonoBehaviour { [SerializeField] private bool playOnAwake; [SerializeField, Min(0)] private float loopTime = 0; [SerializeField] private AnimationCurve xScaleCurve; [SerializeField] private AnimationCurve yScaleCurve; [SerializeField, Min(0)] private float initialDelay = 0; [SerializeField, Min(0), Tooltip("The percentage (as a decimal) of the initial scale that will change per second when the loop is stopped")] private float stopPercentage; private bool stop; // Start is called before the first frame update void Start() { if(playOnAwake) { Play(); } } public void Play() { StartCoroutine(PlayRoutine()); } public void Stop() { stop = true; } private IEnumerator PlayRoutine() { float delayTimer = 0; while(delayTimer < initialDelay) { yield return null; delayTimer += Time.deltaTime; } float playTime = 0; Vector3 initialScale = transform.localScale; while (!stop) { float e = Mathf.Lerp(0, 1, playTime / loopTime); Vector3 normalizedScale = new Vector3( xScaleCurve.Evaluate(e), yScaleCurve.Evaluate(e), 1); transform.localScale = initialScale.Mul(normalizedScale); yield return null; playTime += Time.deltaTime; playTime %= loopTime; } float stopTimer = 0; Vector3 stopScale = transform.localScale; float xPercent = Mathf.Abs(initialScale.x - stopScale.x) / initialScale.x; float yPercent = Mathf.Abs(initialScale.y - stopScale.y) / initialScale.y; float stopTime = Mathf.Max(xPercent, yPercent) / stopPercentage; while(stopTimer < stopTime) { transform.localScale = Vector3.Lerp(stopScale, initialScale, stopTimer / stopTime); yield return null; stopTimer += Time.deltaTime; } transform.localScale = initialScale; } }
bd5c0932bba35fee57c9ea86c7efc9ba9d191a2d
C#
seasun/Demo
/MyTestProjects/MyManageProject/FactoryMethodPattern/NPowerOperation.cs
3.328125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FactoryMethodPattern { class NPowerOperation : Operation { /// <summary> /// 返回a的b次方减1 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public override double GetResult(double a, double b) { return Math.Pow(a, b) - 1; } } }
860cb37f9936a75e89201fd8eba8c2f4b050b969
C#
martyna41236/Tetris
/Tetris2019.09.25/Tetris/Tetris/Form1.cs
3.28125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Tetris { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// To jest Handler eventu Paint. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Paint(object sender, PaintEventArgs e) //< ----- to 'e' jest skrótem od 'event' { //tutaj tworzymy pisak o kolorze niebieskim //i podstawiamy pod zmienną o nazwie 'bluePen' Pen bluePen; //<---- to jest deklaracja zmiennej o nazwie 'bluePen', //to znaczy, że mówie komputerowi, iż chcę mieć zmienną o nazwie 'bluePen' //i będę jej używał jako pisak (Pen) //mająć już zmienną, o której powiedziałem, że bedzie moim pisakime //przystawiam do niej ów pisak bluePen = new Pen(Color.Blue); //w tym miejscu mamy już pisak (niebieski) i chcemy teraz narysować poziomą kreskę //jednym ze sposobów rysowania linii jest podanie pisaka, który u nas jest przystawiony //do zmiennej o nazwie 'bluePen' oraz podanie początku i końca linii do narysowania e.Graphics.DrawLine(bluePen, 100, 100, 130, 100); e.Graphics.DrawLine(bluePen, 130, 100, 130, 90); e.Graphics.DrawLine(bluePen, 130, 90, 120, 90); e.Graphics.DrawLine(bluePen, 120, 90, 120, 80); e.Graphics.DrawLine(bluePen, 120, 80, 110, 80); e.Graphics.DrawLine(bluePen, 110, 80, 110, 90); e.Graphics.DrawLine(bluePen, 110, 90, 100, 90); e.Graphics.DrawLine(bluePen, 100, 90, 100, 100); e.Graphics.DrawLine(bluePen, 100, 100, 110, 100); e.Graphics.DrawLine(bluePen, 110, 100, 110, 200); e.Graphics.DrawLine(bluePen, 200, 110, 100, 200); e.Graphics.DrawLine(bluePen, 100, 200, 100, 100); //narysowawszy wszystkie linie ciągle mamy w łapie pisak //a więc musimy go teraz oddać //i tutaj go oddajemy bluePen.Dispose(); } public MainForm() { InitializeComponent(); _tetriminoT = new bool[2, 3]; } } }
cbe71dd9aeac57a5971be8d11805fd3e4fd1a8b4
C#
somnathchaudhary/FileUploade
/FileUplode/Controllers/UploadController.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FileUplode.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace FileUplode.Controllers { public class UploadController : Controller { private readonly IWebHostEnvironment _env; private readonly ILogger<UploadController> _logger; public UploadController (ILogger<UploadController>logger,IWebHostEnvironment env) { _logger = logger; _env = env; } public IActionResult Index() { return View(); } [HttpPost] public IActionResult UploadFile(Uploade fileUplode) { string strpath = System.IO.Path.GetExtension(fileUplode.ProfileImage.FileName); if (fileUplode.ProfileImage != null && (strpath == ".jpg" && strpath == ".jpeg" && strpath == ".gif" && strpath == ".png")) { string FilePath = $"{_env.WebRootPath}/images/{fileUplode.ProfileImage.FileName}"; var stream = System.IO.File.Create(FilePath); fileUplode.ProfileImage.CopyTo(stream); return Redirect("/FileUplode/Success"); } return Redirect("/"); } public IActionResult Success() { return View(); } } }
0e898065b44abae211f5b0c6a692f28e481085b4
C#
tonyhallett/MoqProtectedSourceGenerator
/EndToEndXUnit/TestClasses/Tests/MoqProtectedSourceGeneratorTest_HasSource.cs
2.578125
3
using Xunit; namespace EndToEndTests { public class MoqProtectedSourceGeneratorTest_HasSource : MoqProtectedSourceGeneratorTestBase { protected override string Source => @" using System; using Moq; using NUnit.Framework; namespace ClassLibrary1 { public abstract class MyProtected { protected abstract void AbstractMethod(); public void InvokeAbstractMethod() { AbstractMethod(); } protected abstract void AbstractMethodArgs(int value); public void InvokeAbstractMethodArgs(int value) { AbstractMethodArgs(value); } protected abstract int SomeProperty { get; } } public class ExpectedException : Exception { } public class Test { [Test] public void Generate() { var mock = new Mock<MyProtected>(); mock.AbstractMethod().Build().Setup().Throws(new ExpectedException()); Assert.Throws<ExpectedException>(() => mock.Object.InvokeAbstractMethod()); mock.AbstractMethodArgs(999).Build().Setup(); mock.AbstractMethodArgs(123).Build().Setup(); void Verify() { mock.AbstractMethodArgs(It.IsInRange(1, 10, Moq.Range.Inclusive)).Build().Verify(); } mock.Object.InvokeAbstractMethodArgs(999); Assert.Throws<MockException>(Verify); mock.Object.InvokeAbstractMethodArgs(1); Verify(); } } } "; [Fact] public void Execute() { Test(); } } }
c98d4b93c6290f12703080ae047b87219d09099c
C#
Danny-L1u/Personal-Project
/Assets/Scripts/TitleScreen.cs
2.625
3
//Code taken from: https://www.youtube.com/watch?v=zc8ac_qUXQY using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Audio; /** This class stops the current music if it is not done playing, then plays the menu music. It also plays the select sound effect when the "START" button is played and loads into the next Unity scene. */ public class TitleScreen : MonoBehaviour { public Animator transition; public AudioMixer audioMixer; //When the game starts set the volume to a specific amount void Start(){ audioMixer.SetFloat("Volume", 5f); } //When the "START" button is clicked public void PlayGame() { FindObjectOfType<AudioManager>().Play("Select"); AudioManager.instance.Stop("Title Screen Music"); AudioManager.instance.Play("Menu Music"); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } }
19ffcf1e7d27bad4264030117c5ce453934438dd
C#
nendo-code/Henacat_sharp
/Programs/CookieTest/CookieTest.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Henacat_sharp.servlet.http; using System.IO; namespace CookieTest { public class CookieTest : HttpServlet { protected override void doGet( HttpServletRequest request, HttpServletResponse response ) { response.setContentType("text/plain"); StreamWriter output = response.getWriter(); String counterStr = null; Cookie[] cookies = request.getCookies(); if ( cookies == null ) { output.WriteLine("cookies == null"); } else { output.WriteLine("cookies.length.." + cookies.Length); for ( int i = 0; i < cookies.Length; i++ ) { output.WriteLine("cookies[" + i + "].." + cookies[i].getName() + "/" + cookies[i].getValue()); if ( cookies[i].getName().Equals("COUNTER") ) { counterStr = cookies[i].getValue(); } } } int counter; if ( counterStr == null ) { counter = 1; } else { counter = Int32.Parse(counterStr) + 1; } Cookie newCookie = new Cookie("COUNTER", "" + counter); response.addCookie(newCookie); } } }
0602689255e0154b1989cd3a7bbbcc52694df7b3
C#
maramail/miaobox_open
/Assets/Scripts/PureMVC/Patterns/Mediator/Mediator.cs
2.71875
3
/* PureMVC C# Multi-Core Port by Tang Khai Phuong <phuong.tang@puremvc.org>, et al. PureMVC - Copyright(c) 2006-08 Futurescale, Inc., Some rights reserved. Your reuse is governed by the Creative Commons Attribution 3.0 License */ #region Using using System.Collections.Generic; using PureMVC.Interfaces; #endregion namespace PureMVC.Patterns { /// <summary> /// A base <c>IMediator</c> implementation /// </summary> /// <see cref="PureMVC.Core.View"/> public class Mediator : Notifier, IMediator { #region Constants /// <summary> /// The name of the <c>Mediator</c> /// </summary> /// <remarks> /// <para>Typically, a <c>Mediator</c> will be written to serve one specific control or group controls and so, will not have a need to be dynamically named</para> /// </remarks> public const string NAME = "Mediator"; #endregion #region Constructors /// <summary> /// Constructs a new mediator with the default name and no view component /// </summary> public Mediator() : this(NAME, null) { } /// <summary> /// Constructs a new mediator with the specified name and no view component /// </summary> /// <param name="mediatorName">The name of the mediator</param> public Mediator(string mediatorName) : this(mediatorName, null) { } /// <summary> /// Constructs a new mediator with the specified name and view component /// </summary> /// <param name="mediatorName">The name of the mediator</param> /// <param name="viewComponent">The view component to be mediated</param> public Mediator(string mediatorName, object viewComponent) { m_mediatorName = mediatorName ?? NAME; m_viewComponent = viewComponent; } #endregion #region Public Methods #region IMediator Members /// <summary> /// List the <c>INotification</c> names this <c>Mediator</c> is interested in being notified of /// </summary> /// <returns>The list of <c>INotification</c> names </returns> public virtual IEnumerable<string> ListNotificationInterests { get { return new List<string>(); } } /// <summary> /// Handle <c>INotification</c>s /// </summary> /// <param name="notification">The <c>INotification</c> instance to handle</param> /// <remarks> /// <para> /// Typically this will be handled in a switch statement, with one 'case' entry per <c>INotification</c> the <c>Mediator</c> is interested in. /// </para> /// </remarks> public virtual void HandleNotification(INotification notification) { } /// <summary> /// Called by the View when the Mediator is registered /// </summary> public virtual void OnRegister() { } /// <summary> /// Called by the View when the Mediator is removed /// </summary> public virtual void OnRemove() { } #endregion #endregion #region Accessors /// <summary> /// The name of the <c>Mediator</c> /// </summary> /// <remarks><para>You should override this in your subclass</para></remarks> public virtual string MediatorName { get { return m_mediatorName; } } /// <summary> /// The <code>IMediator</code>'s view component. /// </summary> /// <remarks> /// <para>Additionally, an implicit getter will usually be defined in the subclass that casts the view object to a type, like this:</para> /// <example> /// <code> /// private System.Windows.Form.ComboBox comboBox { /// get { return viewComponent as ComboBox; } /// } /// </code> /// </example> /// </remarks> public object ViewComponent { get { return m_viewComponent; } set { m_viewComponent = value; } } #endregion #region Members /// <summary> /// The mediator name /// </summary> protected string m_mediatorName; /// <summary> /// The view component being mediated /// </summary> protected object m_viewComponent; #endregion } }
039f73f53083282b3a376726af924578cf3bafab
C#
MetDaniel/CSharpHomework
/homework8/program1/OrderDetails.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace program1 { [Serializable] public class OrderDetails:Order { public string goodName { get; set; } public double price { get; set; } public OrderDetails(string num,string cusName,string phoneNum,string goodName,double price):base(num,cusName,phoneNum) { this.num = num; this.cusName = cusName; this.phoneNum = phoneNum; this.goodName = goodName; this.price = price; } } }
9903610faa50a3cba5255d0752b518b4659e8bd8
C#
Tonifolgado/LearningByExample
/Generics.cs
3.84375
4
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace LearningByExample1 { class Generics { public void usingGenericMethod() { int[] arrInts = new int[] { 2, 5, 4, 7, 6, 7, 1, 3, 9, 8 }; char[] arrChar = new char[] { 'f', 'a', 'r', 'c', 'h' }; // Sorting: integer Sort for (int i = 0; i < arrInts.Length; i++) { for (int j = i + 1; j < arrInts.Length; j++) { if (arrInts[i] > arrInts[j]) { swap<int>(ref arrInts[i], ref arrInts[j]); } } } foreach (var item in arrInts) { Console.WriteLine(item); } // Sorting: character Sort for (int i = 0; i < arrChar.Length; i++) { for (int j = i + 1; j < arrChar.Length; j++) { if (arrChar[i] > arrChar[j]) { swap<char>(ref arrChar[i], ref arrChar[j]); } } } foreach (var item in arrChar) { Console.WriteLine(item); } } static void swap<T>(ref T valueOne, ref T valueTwo) { T temp = valueOne; valueOne = valueTwo; valueTwo = temp; } public void stronglyTypedCollection() { //When you instantiate the collection, specify the type of object //the collection should contain using the generics syntax // Create an AssemblyName object for use during the example. AssemblyName assembly1 = new AssemblyName("com.microsoft.crypto, " + "Culture=en, PublicKeyToken=a5d015c7d5a0b012, Version=1.0.0.0"); // Create and use a Dictionary of AssemblyName objects. Dictionary<string, AssemblyName> assemblyDictionary = new Dictionary<string, AssemblyName>(); assemblyDictionary.Add("Crypto", assembly1); AssemblyName a1 = assemblyDictionary["Crypto"]; Console.WriteLine("Got AssemblyName from dictionary: {0}", a1); // Create and use a List of Assembly Name objects. List<AssemblyName> assemblyList = new List<AssemblyName>(); assemblyList.Add(assembly1); AssemblyName a2 = assemblyList[0]; Console.WriteLine("\nFound AssemblyName in list: {0}", a1); // Create and use a Stack of Assembly Name objects. Stack<AssemblyName> assemblyStack = new Stack<AssemblyName>(); assemblyStack.Push(assembly1); AssemblyName a3 = assemblyStack.Pop(); Console.WriteLine("\nPopped AssemblyName from stack: {0}", a1); // Wait to continue. Console.WriteLine("\nMain method complete. Press Enter"); } } //Implementation of a generic type class Bag<T> { // A List to hold the bags's contents. The list must be // of the same type as the bag. private List<T> items = new List<T>(); // A method to add an item to the bag. public void Add(T item) { items.Add(item); } // A method to get a random item from the bag. public T Remove() { T item = default(T); if (items.Count != 0) { // Determine which item to remove from the bag. Random r = new Random(); int num = r.Next(0, items.Count); // Remove the item. item = items[num]; items.RemoveAt(num); } return item; } // A method to provide an enumerator from the underlying list public IEnumerator<T> GetEnumerator() { return items.GetEnumerator(); } // A method to remove all items from the bag // and return them as an array public T[] RemoveAll() { T[] i = items.ToArray(); items.Clear(); return i; } public static void genericBagManagement() { // Create a new bag of strings. Bag<string> bag = new Bag<string>(); // Add strings to the bag. bag.Add("Darryl"); bag.Add("Bodders"); bag.Add("Gary"); bag.Add("Mike"); bag.Add("Nigel"); bag.Add("Ian"); Console.WriteLine("Bag contents are:"); foreach (string elem in bag) { Console.WriteLine("Element: {0}", elem); } // Take four strings from the bag and display. Console.WriteLine("\nRemoving individual elements"); Console.WriteLine("Removing = {0}", bag.Remove()); Console.WriteLine("Removing = {0}", bag.Remove()); Console.WriteLine("Removing = {0}", bag.Remove()); Console.WriteLine("Removing = {0}", bag.Remove()); Console.WriteLine("\nBag contents are:"); foreach (string elem in bag) { Console.WriteLine("Element: {0}", elem); } // Remove the remaining items from the bag. Console.WriteLine("\nRemoving all elements"); string[] s = bag.RemoveAll(); Console.WriteLine("\nBag contents are:"); foreach (string elem in bag) { Console.WriteLine("Element: {0}", elem); } // Wait to continue. Console.WriteLine("\nMain method complete. Press Enter"); Console.ReadLine(); } } }
867d47d1e9c73fe0a62819ba9cab8cedb649c63f
C#
berbulalauri/web-project-01
/modules-.NET/21-threads/Tutorials/tutorial-02/tutorial-02/Program.cs
3.609375
4
 using System; using System.Threading; namespace tutorial_02 { class Program { static int count = 0; static object locker = new object(); static void Main(string[] args) { Thread thread = new Thread(Proceed); thread.Start(1); Proceed(2); } static void Proceed(object diff) { for (int i = 0; i < 50; i++) { lock (locker) { count += (int)diff; Console.WriteLine($"ThreadID is {Thread.CurrentThread.ManagedThreadId} Count is {count}"); Thread.Sleep(50); } } } } } /* using System; using System.Threading; namespace tutorial02 { class Program { static int count = 0; static Mutex mutex = new Mutex(); static void Main(string[] args) { Thread[] thread = new Thread[100]; for (int i = 0; i < thread.Length; i++) { thread[i] = new Thread(Proceed); thread[i].Start(1); } static void Proceed(object numberOfThread) { while (true) { mutex.WaitOne(); var temp = count; Console.WriteLine($"Thread {numberOfThread} is here reading"); Thread.Sleep(1000); count = temp + 1; Console.WriteLine($"Thread {numberOfThread} is here incremented to {count}"); Thread.Sleep(1000); mutex.ReleaseMutex(); } } //thread.Start(1); // Proceed(2); } } } */
04daa2900790851b0900d934314acf0946c2f355
C#
modios/robust-predicates
/src/RobustPredicates/InCircle.cs
2.71875
3
using System; namespace RobustPredicates { public static class InCirlce { public static double Fast(double[] pa, double[] pb, double[] pc, double[] pd) { double adx = pa[0] - pd[0]; double ady = pa[1] - pd[1]; double bdx = pb[0] - pd[0]; double bdy = pb[1] - pd[1]; double cdx = pc[0] - pd[0]; double cdy = pc[1] - pd[1]; double abdet = adx * bdy - bdx * ady; double bcdet = bdx * cdy - cdx * bdy; double cadet = cdx * ady - adx * cdy; double alift = adx * adx + ady * ady; double blift = bdx * bdx + bdy * bdy; double clift = cdx * cdx + cdy * cdy; return alift * bcdet + blift * cadet + clift * abdet; } internal static double Exact(double[] pa, double[] pb, double[] pc, double[] pd) { MacrosHelpers.TwoProduct(pa[0], pb[1], out double axby1, out double axby0); MacrosHelpers.TwoProduct(pb[0], pa[1], out double bxay1, out double bxay0); var ab = new double[4]; MacrosHelpers.TwoTwoDiff(axby1, axby0, bxay1, bxay0, out ab[3], out ab[2], out ab[1], out ab[0]); var bc = new double[4]; MacrosHelpers.TwoProduct(pb[0], pc[1], out double bxcy1, out double bxcy0); MacrosHelpers.TwoProduct(pc[0], pb[1], out double cxby1, out double cxby0); MacrosHelpers.TwoTwoDiff(bxcy1, bxcy0, cxby1, cxby0, out bc[3], out bc[2], out bc[1], out bc[0]); var cd = new double[4]; MacrosHelpers.TwoProduct(pc[0], pd[1], out double cxdy1, out double cxdy0); MacrosHelpers.TwoProduct(pd[0], pc[1], out double dxcy1, out double dxcy0); MacrosHelpers.TwoTwoDiff(cxdy1, cxdy0, dxcy1, dxcy0, out cd[3], out cd[2], out cd[1], out cd[0]); var da = new double[4]; MacrosHelpers.TwoProduct(pd[0], pa[1], out double dxay1, out double dxay0); MacrosHelpers.TwoProduct(pa[0], pd[1], out double axdy1, out double axdy0); MacrosHelpers.TwoTwoDiff(dxay1, dxay0, axdy1, axdy0, out da[3], out da[2], out da[1], out da[0]); var ac = new double[4]; MacrosHelpers.TwoProduct(pa[0], pc[1], out double axcy1, out double axcy0); MacrosHelpers.TwoProduct(pc[0], pa[1], out double cxay1, out double cxay0); MacrosHelpers.TwoTwoDiff(axcy1, axcy0, cxay1, cxay0, out ac[3], out ac[2], out ac[1], out ac[0]); var bd = new double[4]; MacrosHelpers.TwoProduct(pb[0], pd[1], out double bxdy1, out double bxdy0); MacrosHelpers.TwoProduct(pd[0], pb[1], out double dxby1, out double dxby0); MacrosHelpers.TwoTwoDiff(bxdy1, bxdy0, dxby1, dxby0, out bd[3], out bd[2], out bd[1], out bd[0]); var temp8 = new double[8]; var templen = ArithmeticFunctions.FastExpansionSumZeroelim(4, cd, 4, da, temp8); var cda = new double[12]; var cdalen = ArithmeticFunctions.FastExpansionSumZeroelim(templen, temp8, 4, ac, cda); var dab = new double[12]; templen = ArithmeticFunctions.FastExpansionSumZeroelim(4, da, 4, ab, temp8); var dablen = ArithmeticFunctions.FastExpansionSumZeroelim(templen, temp8, 4, bd, dab); for (int i = 0; i < 4; i++) { bd[i] = -bd[i]; ac[i] = -ac[i]; } var abc = new double[12]; templen = ArithmeticFunctions.FastExpansionSumZeroelim(4, ab, 4, bc, temp8); var abclen = ArithmeticFunctions.FastExpansionSumZeroelim(templen, temp8, 4, ac, abc); templen = ArithmeticFunctions.FastExpansionSumZeroelim(4, bc, 4, cd, temp8); var bcd = new double[12]; var bcdlen = ArithmeticFunctions.FastExpansionSumZeroelim(templen, temp8, 4, bd, bcd); var det24x = new double[24]; var xlen = ArithmeticFunctions.ScaleExpansionZeroelim(bcdlen, bcd, pa[0], det24x); double[] det48x = new double[48]; xlen = ArithmeticFunctions.ScaleExpansionZeroelim(xlen, det24x, pa[0], det48x); double[] det24y = new double[24]; var ylen = ArithmeticFunctions.ScaleExpansionZeroelim(bcdlen, bcd, pa[1], det24y); double[] det48y = new double[48]; ylen = ArithmeticFunctions.ScaleExpansionZeroelim(ylen, det24y, pa[1], det48y); double[] adet = new double[96]; var alen = ArithmeticFunctions.FastExpansionSumZeroelim(xlen, det48x, ylen, det48y, adet); xlen = ArithmeticFunctions.ScaleExpansionZeroelim(cdalen, cda, pb[0], det24x); xlen = ArithmeticFunctions.ScaleExpansionZeroelim(xlen, det24x, -pb[0], det48x); ylen = ArithmeticFunctions.ScaleExpansionZeroelim(cdalen, cda, pb[1], det24y); ylen = ArithmeticFunctions.ScaleExpansionZeroelim(ylen, det24y, -pb[1], det48y); double[] bdet = new double[96]; var blen = ArithmeticFunctions.FastExpansionSumZeroelim(xlen, det48x, ylen, det48y, bdet); xlen = ArithmeticFunctions.ScaleExpansionZeroelim(dablen, dab, pc[0], det24x); xlen = ArithmeticFunctions.ScaleExpansionZeroelim(xlen, det24x, pc[0], det48x); ylen = ArithmeticFunctions.ScaleExpansionZeroelim(dablen, dab, pc[1], det24y); ylen = ArithmeticFunctions.ScaleExpansionZeroelim(ylen, det24y, pc[1], det48y); var cdet = new double[96]; var clen = ArithmeticFunctions.FastExpansionSumZeroelim(xlen, det48x, ylen, det48y, cdet); xlen = ArithmeticFunctions.ScaleExpansionZeroelim(abclen, abc, pd[0], det24x); xlen = ArithmeticFunctions.ScaleExpansionZeroelim(xlen, det24x, -pd[0], det48x); ylen = ArithmeticFunctions.ScaleExpansionZeroelim(abclen, abc, pd[1], det24y); ylen = ArithmeticFunctions.ScaleExpansionZeroelim(ylen, det24y, -pd[1], det48y); double[] ddet = new double[96]; var dlen = ArithmeticFunctions.FastExpansionSumZeroelim(xlen, det48x, ylen, det48y, ddet); double[] abdet = new double[192]; var ablen = ArithmeticFunctions.FastExpansionSumZeroelim(alen, adet, blen, bdet, abdet); double[] cddet = new double[192]; var cdlen = ArithmeticFunctions.FastExpansionSumZeroelim(clen, cdet, dlen, ddet, cddet); double[] deter = new double[384]; var deterlen = ArithmeticFunctions.FastExpansionSumZeroelim(ablen, abdet, cdlen, cddet, deter); return deter[deterlen - 1]; } private static double Adapt(double[] pa, double[] pb, double[] pc, double[] pd, double permanent) { var adx = pa[0] - pd[0]; var bdx = pb[0] - pd[0]; var cdx = pc[0] - pd[0]; var ady = pa[1] - pd[1]; var bdy = pb[1] - pd[1]; var cdy = pc[1] - pd[1]; MacrosHelpers.TwoProduct(bdx, cdy, out double bdxcdy1, out double bdxcdy0); MacrosHelpers.TwoProduct(cdx, bdy, out double cdxbdy1, out double cdxbdy0); var bc = new double[4]; MacrosHelpers.TwoTwoDiff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, out bc[3], out bc[2], out bc[1], out bc[0]); double[] axbc = new double[8]; var axbclen = ArithmeticFunctions.ScaleExpansionZeroelim(4, bc, adx, axbc); double[] axxbc = new double[16]; var axxbclen = ArithmeticFunctions.ScaleExpansionZeroelim(axbclen, axbc, adx, axxbc); double[] aybc = new double[8]; var aybclen = ArithmeticFunctions.ScaleExpansionZeroelim(4, bc, ady, aybc); double[] ayybc = new double[16]; var ayybclen = ArithmeticFunctions.ScaleExpansionZeroelim(aybclen, aybc, ady, ayybc); double[] adet = new double[32]; var alen = ArithmeticFunctions.FastExpansionSumZeroelim(axxbclen, axxbc, ayybclen, ayybc, adet); MacrosHelpers.TwoProduct(cdx, ady, out double cdxady1, out double cdxady0); MacrosHelpers.TwoProduct(adx, cdy, out double adxcdy1, out double adxcdy0); var ca = new double[4]; MacrosHelpers.TwoTwoDiff(cdxady1, cdxady0, adxcdy1, adxcdy0, out ca[3], out ca[2], out ca[1], out ca[0]); double[] bxca = new double[8]; var bxcalen = ArithmeticFunctions.ScaleExpansionZeroelim(4, ca, bdx, bxca); double[] bxxca = new double[16]; var bxxcalen = ArithmeticFunctions.ScaleExpansionZeroelim(bxcalen, bxca, bdx, bxxca); double[] byca = new double[8]; var bycalen = ArithmeticFunctions.ScaleExpansionZeroelim(4, ca, bdy, byca); double[] byyca = new double[16]; var byycalen = ArithmeticFunctions.ScaleExpansionZeroelim(bycalen, byca, bdy, byyca); double[] bdet = new double[32]; var blen = ArithmeticFunctions.FastExpansionSumZeroelim(bxxcalen, bxxca, byycalen, byyca, bdet); MacrosHelpers.TwoProduct(adx, bdy, out double adxbdy1, out double adxbdy0); MacrosHelpers.TwoProduct(bdx, ady, out double bdxady1, out double bdxady0); var ab = new double[4]; MacrosHelpers.TwoTwoDiff(adxbdy1, adxbdy0, bdxady1, bdxady0, out ab[3], out ab[2], out ab[1], out ab[0]); double[] cxab = new double[8]; var cxablen = ArithmeticFunctions.ScaleExpansionZeroelim(4, ab, cdx, cxab); double[] cxxab = new double[16]; var cxxablen = ArithmeticFunctions.ScaleExpansionZeroelim(cxablen, cxab, cdx, cxxab); double[] cyab = new double[8]; var cyablen = ArithmeticFunctions.ScaleExpansionZeroelim(4, ab, cdy, cyab); double[] cyyab = new double[16]; var cyyablen = ArithmeticFunctions.ScaleExpansionZeroelim(cyablen, cyab, cdy, cyyab); double[] cdet = new double[32]; var clen = ArithmeticFunctions.FastExpansionSumZeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet); double[] abdet = new double[64]; var ablen = ArithmeticFunctions.FastExpansionSumZeroelim(alen, adet, blen, bdet, abdet); double[] fin1 = new double[1152]; var finlength = ArithmeticFunctions.FastExpansionSumZeroelim(ablen, abdet, clen, cdet, fin1); var det = ArithmeticFunctions.Estimate(finlength, fin1); var errbound = MacrosHelpers.IccerrboundB * permanent; if ((det >= errbound) || (-det >= errbound)) { return det; } MacrosHelpers.TwoDiffTail(pa[0], pd[0], adx, out double adxtail); MacrosHelpers.TwoDiffTail(pa[1], pd[1], ady, out double adytail); MacrosHelpers.TwoDiffTail(pb[0], pd[0], bdx, out double bdxtail); MacrosHelpers.TwoDiffTail(pb[1], pd[1], bdy, out double bdytail); MacrosHelpers.TwoDiffTail(pc[0], pd[0], cdx, out double cdxtail); MacrosHelpers.TwoDiffTail(pc[1], pd[1], cdy, out double cdytail); if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) { return det; } errbound = MacrosHelpers.IccerrboundC * permanent + MacrosHelpers.Resulterrbound * Math.Abs(det); det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail) - (bdy * cdxtail + cdx * bdytail)) + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx)) + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail) - (cdy * adxtail + adx * cdytail)) + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx)) + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail) - (ady * bdxtail + bdx * adytail)) + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx)); if ((det >= errbound) || (-det >= errbound)) { return det; } var finnow = fin1; var fin2 = new double[1152]; var finother = fin2; double[] aa = new double[4]; double[] bb = new double[4]; double[] cc = new double[4]; if ((bdxtail != 0.0) || (bdytail != 0.0) || (cdxtail != 0.0) || (cdytail != 0.0)) { MacrosHelpers.Square(adx, out double adxadx1, out double adxadx0); MacrosHelpers.Square(ady, out double adyady1, out double adyady0); MacrosHelpers.TwoTwoSum(adxadx1, adxadx0, adyady1, adyady0, out aa[3], out aa[2], out aa[1], out aa[0]); } if ((cdxtail != 0.0) || (cdytail != 0.0) || (adxtail != 0.0) || (adytail != 0.0)) { MacrosHelpers.Square(bdx, out double bdxbdx1, out double bdxbdx0); MacrosHelpers.Square(bdy, out double bdybdy1, out double bdybdy0); MacrosHelpers.TwoTwoSum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, out bb[3], out bb[2], out bb[1], out bb[0]); } if ((adxtail != 0.0) || (adytail != 0.0) || (bdxtail != 0.0) || (bdytail != 0.0)) { MacrosHelpers.Square(cdx, out double cdxcdx1, out double cdxcdx0); MacrosHelpers.Square(cdy, out double cdycdy1, out double cdycdy0); MacrosHelpers.TwoTwoSum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, out cc[3], out cc[2], out cc[1], out cc[0]); } double[] finswap; double[] temp16a = new double[16]; double[] temp32a = new double[32]; double[] temp16b = new double[16]; double[] temp32b = new double[32]; double[] temp16c = new double[16]; double[] temp48 = new double[48]; double[] axtbc = new double[8]; int axtbclen = 0; if (adxtail != 0.0) { axtbclen = ArithmeticFunctions.ScaleExpansionZeroelim(4, bc, adxtail, axtbc); var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(axtbclen, axtbc, 2.0 * adx, temp16a); double[] axtcc = new double[8]; var axtcclen = ArithmeticFunctions.ScaleExpansionZeroelim(4, cc, adxtail, axtcc); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(axtcclen, axtcc, bdy, temp16b); double[] axtbb = new double[8]; var axtbblen = ArithmeticFunctions.ScaleExpansionZeroelim(4, bb, adxtail, axtbb); var temp16clen = ArithmeticFunctions.ScaleExpansionZeroelim(axtbblen, axtbb, -cdy, temp16c); var temp32alen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16clen, temp16c, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; } int aytbclen = 0; double[] aytbc = new double[8]; if (adytail != 0.0) { aytbclen = ArithmeticFunctions.ScaleExpansionZeroelim(4, bc, adytail, aytbc); var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(aytbclen, aytbc, 2.0 * ady, temp16a); double[] aytbb = new double[8]; var aytbblen = ArithmeticFunctions.ScaleExpansionZeroelim(4, bb, adytail, aytbb); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(aytbblen, aytbb, cdx, temp16b); double[] aytcc = new double[8]; var aytcclen = ArithmeticFunctions.ScaleExpansionZeroelim(4, cc, adytail, aytcc); var temp16clen = ArithmeticFunctions.ScaleExpansionZeroelim(aytcclen, aytcc, -bdx, temp16c); var temp32alen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16clen, temp16c, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; } int bxtcalen = 0; double[] bxtca = new double[8]; if (bdxtail != 0.0) { bxtcalen = ArithmeticFunctions.ScaleExpansionZeroelim(4, ca, bdxtail, bxtca); var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(bxtcalen, bxtca, 2.0 * bdx, temp16a); double[] bxtaa = new double[8]; var bxtaalen = ArithmeticFunctions.ScaleExpansionZeroelim(4, aa, bdxtail, bxtaa); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(bxtaalen, bxtaa, cdy, temp16b); double[] bxtcc = new double[8]; var bxtcclen = ArithmeticFunctions.ScaleExpansionZeroelim(4, cc, bdxtail, bxtcc); var temp16clen = ArithmeticFunctions.ScaleExpansionZeroelim(bxtcclen, bxtcc, -ady, temp16c); var temp32alen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16clen, temp16c, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; } int bytcalen = 0; double[] bytca = new double[8]; if (bdytail != 0.0) { bytcalen = ArithmeticFunctions.ScaleExpansionZeroelim(4, ca, bdytail, bytca); var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(bytcalen, bytca, 2.0 * bdy, temp16a); double[] bytcc = new double[8]; var bytcclen = ArithmeticFunctions.ScaleExpansionZeroelim(4, cc, bdytail, bytcc); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(bytcclen, bytcc, adx, temp16b); double[] bytaa = new double[8]; var bytaalen = ArithmeticFunctions.ScaleExpansionZeroelim(4, aa, bdytail, bytaa); var temp16clen = ArithmeticFunctions.ScaleExpansionZeroelim(bytaalen, bytaa, -cdx, temp16c); var temp32alen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16clen, temp16c, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; } int cxtablen = 0; double[] cxtab = new double[8]; if (cdxtail != 0.0) { cxtablen = ArithmeticFunctions.ScaleExpansionZeroelim(4, ab, cdxtail, cxtab); var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(cxtablen, cxtab, 2.0 * cdx, temp16a); double[] cxtbb = new double[8]; var cxtbblen = ArithmeticFunctions.ScaleExpansionZeroelim(4, bb, cdxtail, cxtbb); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(cxtbblen, cxtbb, ady, temp16b); double[] cxtaa = new double[8]; var cxtaalen = ArithmeticFunctions.ScaleExpansionZeroelim(4, aa, cdxtail, cxtaa); var temp16clen = ArithmeticFunctions.ScaleExpansionZeroelim(cxtaalen, cxtaa, -bdy, temp16c); var temp32alen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16clen, temp16c, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; } int cytablen = 0; double[] cytab = new double[8]; if (cdytail != 0.0) { cytablen = ArithmeticFunctions.ScaleExpansionZeroelim(4, ab, cdytail, cytab); var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(cytablen, cytab, 2.0 * cdy, temp16a); double[] cytaa = new double[8]; var cytaalen = ArithmeticFunctions.ScaleExpansionZeroelim(4, aa, cdytail, cytaa); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(cytaalen, cytaa, bdx, temp16b); double[] cytbb = new double[8]; var cytbblen = ArithmeticFunctions.ScaleExpansionZeroelim(4, bb, cdytail, cytbb); var temp16clen = ArithmeticFunctions.ScaleExpansionZeroelim(cytbblen, cytbb, -adx, temp16c); var temp32alen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16clen, temp16c, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; } int bcttlen; double[] bct = new double[8]; int bctlen; var bctt = new double[4]; double[] temp64 = new double[64]; double[] u = new double[5]; double[] v = new double[5]; if ((adxtail != 0.0) || (adytail != 0.0)) { if ((bdxtail != 0.0) || (bdytail != 0.0) || (cdxtail != 0.0) || (cdytail != 0.0)) { MacrosHelpers.TwoProduct(bdxtail, cdy, out double ti1, out double ti0); MacrosHelpers.TwoProduct(bdx, cdytail, out double tj1, out double tj0); MacrosHelpers.TwoTwoSum(ti1, ti0, tj1, tj0, out u[3], out u[2], out u[1], out u[0]); var negate = -bdy; MacrosHelpers.TwoProduct(cdxtail, negate, out ti1, out ti0); negate = -bdytail; MacrosHelpers.TwoProduct(cdx, negate, out tj1, out tj0); MacrosHelpers.TwoTwoSum(ti1, ti0, tj1, tj0, out v[3], out v[2], out v[1], out v[0]); bctlen = ArithmeticFunctions.FastExpansionSumZeroelim(4, u, 4, v, bct); MacrosHelpers.TwoProduct(bdxtail, cdytail, out ti1, out ti0); MacrosHelpers.TwoProduct(cdxtail, bdytail, out tj1, out tj0); MacrosHelpers.TwoTwoDiff(ti1, ti0, tj1, tj0, out bctt[3], out bctt[2], out bctt[1], out bctt[0]); bcttlen = 4; } else { bct[0] = 0.0; bctlen = 1; bctt[0] = 0.0; bcttlen = 1; } double[] temp8 = new double[8]; if (adxtail != 0.0) { var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(axtbclen, axtbc, adxtail, temp16a); double[] axtbct = new double[16]; var axtbctlen = ArithmeticFunctions.ScaleExpansionZeroelim(bctlen, bct, adxtail, axtbct); var temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(axtbctlen, axtbct, 2.0 * adx, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; if (bdytail != 0.0) { var temp8len = ArithmeticFunctions.ScaleExpansionZeroelim(4, cc, adxtail, temp8); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(temp8len, temp8, bdytail, temp16a); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp16alen, temp16a, finother); finswap = finnow; finnow = finother; finother = finswap; } if (cdytail != 0.0) { var temp8len = ArithmeticFunctions.ScaleExpansionZeroelim(4, bb, -adxtail, temp8); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(temp8len, temp8, cdytail, temp16a); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp16alen, temp16a, finother); finswap = finnow; finnow = finother; finother = finswap; } temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(axtbctlen, axtbct, adxtail, temp32a); double[] axtbctt = new double[8]; var axtbcttlen = ArithmeticFunctions.ScaleExpansionZeroelim(bcttlen, bctt, adxtail, axtbctt); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(axtbcttlen, axtbctt, 2.0 * adx, temp16a); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(axtbcttlen, axtbctt, adxtail, temp16b); var temp32blen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32b); var temp64len = ArithmeticFunctions.FastExpansionSumZeroelim(temp32alen, temp32a, temp32blen, temp32b, temp64); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp64len, temp64, finother); finswap = finnow; finnow = finother; finother = finswap; } if (adytail != 0.0) { double[] aytbct = new double[16]; var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(aytbclen, aytbc, adytail, temp16a); var aytbctlen = ArithmeticFunctions.ScaleExpansionZeroelim(bctlen, bct, adytail, aytbct); var temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(aytbctlen, aytbct, 2.0 * ady, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(aytbctlen, aytbct, adytail, temp32a); double[] aytbctt = new double[16]; var aytbcttlen = ArithmeticFunctions.ScaleExpansionZeroelim(bcttlen, bctt, adytail, aytbctt); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(aytbcttlen, aytbctt, 2.0 * ady, temp16a); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(aytbcttlen, aytbctt, adytail, temp16b); var temp32blen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32b); var temp64len = ArithmeticFunctions.FastExpansionSumZeroelim(temp32alen, temp32a, temp32blen, temp32b, temp64); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp64len, temp64, finother); finswap = finnow; finnow = finother; finother = finswap; } } double[] cat = new double[8]; double[] catt = new double[4]; if ((bdxtail != 0.0) || (bdytail != 0.0)) { int cattlen; int catlen; if ((cdxtail != 0.0) || (cdytail != 0.0) || (adxtail != 0.0) || (adytail != 0.0)) { MacrosHelpers.TwoProduct(cdxtail, ady, out double ti1, out double ti0); MacrosHelpers.TwoProduct(cdx, adytail, out double tj1, out double tj0); MacrosHelpers.TwoTwoSum(ti1, ti0, tj1, tj0, out u[3], out u[2], out u[1], out u[0]); var negate = -cdy; MacrosHelpers.TwoProduct(adxtail, negate, out ti1, out ti0); negate = -cdytail; MacrosHelpers.TwoProduct(adx, negate, out tj1, out tj0); MacrosHelpers.TwoTwoSum(ti1, ti0, tj1, tj0, out v[3], out v[2], out v[1], out v[0]); catlen = ArithmeticFunctions.FastExpansionSumZeroelim(4, u, 4, v, cat); MacrosHelpers.TwoProduct(cdxtail, adytail, out ti1, out ti0); MacrosHelpers.TwoProduct(adxtail, cdytail, out tj1, out tj0); MacrosHelpers.TwoTwoDiff(ti1, ti0, tj1, tj0, out catt[3], out catt[2], out catt[1], out catt[0]); cattlen = 4; } else { cat[0] = 0.0; catlen = 1; catt[0] = 0.0; cattlen = 1; } double[] temp8 = new double[8]; double[] bxtcat = new double[16]; double[] bxtcatt = new double[8]; if (bdxtail != 0.0) { var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(bxtcalen, bxtca, bdxtail, temp16a); var bxtcatlen = ArithmeticFunctions.ScaleExpansionZeroelim(catlen, cat, bdxtail, bxtcat); var temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(bxtcatlen, bxtcat, 2.0 * bdx, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; if (cdytail != 0.0) { var temp8len = ArithmeticFunctions.ScaleExpansionZeroelim(4, aa, bdxtail, temp8); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(temp8len, temp8, cdytail, temp16a); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp16alen, temp16a, finother); finswap = finnow; finnow = finother; finother = finswap; } if (adytail != 0.0) { var temp8len = ArithmeticFunctions.ScaleExpansionZeroelim(4, cc, -bdxtail, temp8); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(temp8len, temp8, adytail, temp16a); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp16alen, temp16a, finother); finswap = finnow; finnow = finother; finother = finswap; } temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(bxtcatlen, bxtcat, bdxtail, temp32a); var bxtcattlen = ArithmeticFunctions.ScaleExpansionZeroelim(cattlen, catt, bdxtail, bxtcatt); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(bxtcattlen, bxtcatt, 2.0 * bdx, temp16a); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(bxtcattlen, bxtcatt, bdxtail, temp16b); var temp32blen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32b); var temp64len = ArithmeticFunctions.FastExpansionSumZeroelim(temp32alen, temp32a, temp32blen, temp32b, temp64); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp64len, temp64, finother); finswap = finnow; finnow = finother; finother = finswap; } double[] bytcat = new double[16]; double[] bytcatt = new double[8]; if (bdytail != 0.0) { var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(bytcalen, bytca, bdytail, temp16a); var bytcatlen = ArithmeticFunctions.ScaleExpansionZeroelim(catlen, cat, bdytail, bytcat); var temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(bytcatlen, bytcat, 2.0 * bdy, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(bytcatlen, bytcat, bdytail, temp32a); var bytcattlen = ArithmeticFunctions.ScaleExpansionZeroelim(cattlen, catt, bdytail, bytcatt); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(bytcattlen, bytcatt, 2.0 * bdy, temp16a); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(bytcattlen, bytcatt, bdytail, temp16b); var temp32blen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32b); var temp64len = ArithmeticFunctions.FastExpansionSumZeroelim(temp32alen, temp32a, temp32blen, temp32b, temp64); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp64len, temp64, finother); finswap = finnow; finnow = finother; finother = finswap; } } double[] abt = new double[8]; double[] abtt = new double[4]; if ((cdxtail != 0.0) || (cdytail != 0.0)) { int abtlen; int abttlen; if ((adxtail != 0.0) || (adytail != 0.0) || (bdxtail != 0.0) || (bdytail != 0.0)) { MacrosHelpers.TwoProduct(adxtail, bdy, out double ti1, out double ti0); MacrosHelpers.TwoProduct(adx, bdytail, out double tj1, out double tj0); MacrosHelpers.TwoTwoSum(ti1, ti0, tj1, tj0, out u[3], out u[2], out u[1], out u[0]); var negate = -ady; MacrosHelpers.TwoProduct(bdxtail, negate, out ti1, out ti0); negate = -adytail; MacrosHelpers.TwoProduct(bdx, negate, out tj1, out tj0); MacrosHelpers.TwoTwoSum(ti1, ti0, tj1, tj0, out v[3], out v[2], out v[1], out v[0]); abtlen = ArithmeticFunctions.FastExpansionSumZeroelim(4, u, 4, v, abt); MacrosHelpers.TwoProduct(adxtail, bdytail, out ti1, out ti0); MacrosHelpers.TwoProduct(bdxtail, adytail, out tj1, out tj0); MacrosHelpers.TwoTwoDiff(ti1, ti0, tj1, tj0, out abtt[3], out abtt[2], out abtt[1], out abtt[0]); abttlen = 4; } else { abt[0] = 0.0; abtlen = 1; abtt[0] = 0.0; abttlen = 1; } double[] temp8 = new double[8]; double[] cxtabt = new double[16]; double[] cxtabtt = new double[8]; if (cdxtail != 0.0) { var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(cxtablen, cxtab, cdxtail, temp16a); var cxtabtlen = ArithmeticFunctions.ScaleExpansionZeroelim(abtlen, abt, cdxtail, cxtabt); var temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(cxtabtlen, cxtabt, 2.0 * cdx, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; if (adytail != 0.0) { var temp8len = ArithmeticFunctions.ScaleExpansionZeroelim(4, bb, cdxtail, temp8); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(temp8len, temp8, adytail, temp16a); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp16alen, temp16a, finother); finswap = finnow; finnow = finother; finother = finswap; } if (bdytail != 0.0) { var temp8len = ArithmeticFunctions.ScaleExpansionZeroelim(4, aa, -cdxtail, temp8); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(temp8len, temp8, bdytail, temp16a); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp16alen, temp16a, finother); finswap = finnow; finnow = finother; finother = finswap; } temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(cxtabtlen, cxtabt, cdxtail, temp32a); var cxtabttlen = ArithmeticFunctions.ScaleExpansionZeroelim(abttlen, abtt, cdxtail, cxtabtt); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(cxtabttlen, cxtabtt, 2.0 * cdx, temp16a); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(cxtabttlen, cxtabtt, cdxtail, temp16b); var temp32blen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32b); var temp64len = ArithmeticFunctions.FastExpansionSumZeroelim(temp32alen, temp32a, temp32blen, temp32b, temp64); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp64len, temp64, finother); finswap = finnow; finnow = finother; finother = finswap; } double[] cytabt = new double[16]; double[] cytabtt = new double[8]; if (cdytail != 0.0) { var temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(cytablen, cytab, cdytail, temp16a); var cytabtlen = ArithmeticFunctions.ScaleExpansionZeroelim(abtlen, abt, cdytail, cytabt); var temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(cytabtlen, cytabt, 2.0 * cdy, temp32a); var temp48len = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp32alen, temp32a, temp48); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp48len, temp48, finother); finswap = finnow; finnow = finother; finother = finswap; temp32alen = ArithmeticFunctions.ScaleExpansionZeroelim(cytabtlen, cytabt, cdytail, temp32a); var cytabttlen = ArithmeticFunctions.ScaleExpansionZeroelim(abttlen, abtt, cdytail, cytabtt); temp16alen = ArithmeticFunctions.ScaleExpansionZeroelim(cytabttlen, cytabtt, 2.0 * cdy, temp16a); var temp16blen = ArithmeticFunctions.ScaleExpansionZeroelim(cytabttlen, cytabtt, cdytail, temp16b); var temp32blen = ArithmeticFunctions.FastExpansionSumZeroelim(temp16alen, temp16a, temp16blen, temp16b, temp32b); var temp64len = ArithmeticFunctions.FastExpansionSumZeroelim(temp32alen, temp32a, temp32blen, temp32b, temp64); finlength = ArithmeticFunctions.FastExpansionSumZeroelim(finlength, finnow, temp64len, temp64, finother); finswap = finnow; finnow = finother; finother = finswap; } } return finnow[finlength - 1]; } public static double Robust(double[] pa, double[] pb, double[] pc, double[] pd) { var adx = pa[0] - pd[0]; var bdx = pb[0] - pd[0]; var cdx = pc[0] - pd[0]; var ady = pa[1] - pd[1]; var bdy = pb[1] - pd[1]; var cdy = pc[1] - pd[1]; var bdxcdy = bdx * cdy; var cdxbdy = cdx * bdy; var alift = adx * adx + ady * ady; var cdxady = cdx * ady; var adxcdy = adx * cdy; var blift = bdx * bdx + bdy * bdy; var adxbdy = adx * bdy; var bdxady = bdx * ady; var clift = cdx * cdx + cdy * cdy; var det = alift * (bdxcdy - cdxbdy) + blift * (cdxady - adxcdy) + clift * (adxbdy - bdxady); var permanent = (Math.Abs(bdxcdy) + Math.Abs(cdxbdy)) * alift + (Math.Abs(cdxady) + Math.Abs(adxcdy)) * blift + (Math.Abs(adxbdy) + Math.Abs(bdxady)) * clift; var errbound = MacrosHelpers.IccerrboundA * permanent; if ((det > errbound) || (-det > errbound)) { return det; } return Adapt(pa, pb, pc, pd, permanent); } } }
2657fecfc2183092370eddb8fcf69fd57722dea7
C#
Anonsubmission/DSV
/ASPNetWebStack/DotNetOpenAuth/src/DotNetOpenAuth.OpenId/OpenId/IdentifierContract.cs
2.75
3
//----------------------------------------------------------------------- // <copyright file="IdentifierContract.cs" company="Outercurve Foundation"> // Copyright (c) Outercurve Foundation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace DotNetOpenAuth.OpenId { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using DotNetOpenAuth.Messaging; /// <summary> /// Code Contract for the <see cref="Identifier"/> class. /// </summary> [ContractClassFor(typeof(Identifier))] internal abstract class IdentifierContract : Identifier { /// <summary> /// Prevents a default instance of the IdentifierContract class from being created. /// </summary> private IdentifierContract() : base(null, false) { } /// <summary> /// Returns an <see cref="Identifier"/> that has no URI fragment. /// Quietly returns the original <see cref="Identifier"/> if it is not /// a <see cref="UriIdentifier"/> or no fragment exists. /// </summary> /// <returns> /// A new <see cref="Identifier"/> instance if there was a /// fragment to remove, otherwise this same instance.. /// </returns> internal override Identifier TrimFragment() { Contract.Ensures(Contract.Result<Identifier>() != null); throw new NotImplementedException(); } /// <summary> /// Converts a given identifier to its secure equivalent. /// UriIdentifiers originally created with an implied HTTP scheme change to HTTPS. /// Discovery is made to require SSL for the entire resolution process. /// </summary> /// <param name="secureIdentifier">The newly created secure identifier. /// If the conversion fails, <paramref name="secureIdentifier"/> retains /// <i>this</i> identifiers identity, but will never discover any endpoints.</param> /// <returns> /// True if the secure conversion was successful. /// False if the Identifier was originally created with an explicit HTTP scheme. /// </returns> internal override bool TryRequireSsl(out Identifier secureIdentifier) { Contract.Ensures(Contract.ValueAtReturn(out secureIdentifier) != null); throw new NotImplementedException(); } } }
3d6a775dba8de4b29a267e9c48b654b3f4d4a3aa
C#
GediminasMasaitis/MHArmory
/MHArmory/ViewModels/SkillSelectorViewModel.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using MHArmory.Core; using MHArmory.Core.DataStructures; namespace MHArmory.ViewModels { public enum VisibilityMode { All, Selected, Unselected } public class SkillSelectorViewModel : ViewModelBase { private IEnumerable<SkillViewModel> skills; public IEnumerable<SkillViewModel> Skills { get { return skills; } set { SetValue(ref skills, value); } } private VisibilityMode visibilityMode = VisibilityMode.All; public bool VisibilityModeAll { set { if (value && visibilityMode != VisibilityMode.All) { visibilityMode = VisibilityMode.All; ComputeVisibility(); } } } public bool VisibilityModeSelected { set { if (value && visibilityMode != VisibilityMode.Selected) { visibilityMode = VisibilityMode.Selected; ComputeVisibility(); } } } public bool VisibilityModeUnselected { set { if (value && visibilityMode != VisibilityMode.Unselected) { visibilityMode = VisibilityMode.Unselected; ComputeVisibility(); } } } private string searchText; public string SearchText { get { return searchText; } set { if (SetValue(ref searchText, value)) { if (Skills != null) ComputeVisibility(); } } } private void ComputeVisibility() { foreach (SkillViewModel vm in Skills) ComputeVisibility(vm); } internal void ComputeVisibility(SkillViewModel skillViewModel) { if (visibilityMode == VisibilityMode.Selected) { if (skillViewModel.HasCheckedAbility == false) { skillViewModel.IsVisible = false; return; } } else if (visibilityMode == VisibilityMode.Unselected) { if (skillViewModel.HasCheckedAbility) { skillViewModel.IsVisible = false; return; } } skillViewModel.ApplySearchText(SearchStatement.Create(searchText)); } public ICommand CancelCommand { get; } public SkillSelectorViewModel() { CancelCommand = new AnonymousCommand(OnCancel); } private void OnCancel(object parameter) { if (parameter is CancellationCommandArgument cancellable) { if (string.IsNullOrWhiteSpace(SearchText) == false) { SearchText = string.Empty; cancellable.IsCancelled = true; } } } } }
52b2f320551e073897743cb73d16806d49e672ca
C#
johnholliday/structurizr-objects
/StructurizrObjects/StructurizrObjects/ComponentAttribute.cs
2.96875
3
using System; namespace StructurizrObjects { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ComponentAttribute : Attribute { public ComponentAttribute(string description, string technology, string type = "") { Description = description; Technology = technology; Type = type; } public string Description { get; } public string Technology { get; } public string Type { get; } } }
73aea1aa0a1b1ca8f0cf1bda1a9b145096de24b9
C#
sts-CAD-Software/PCB-Investigator-Scripts
/ASync-Folder/Highlight pins.cs
2.65625
3
//ASynchronous template //----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 29.04.2014 // Autor Fabio // // Example to highlight pins on top component layer with asynchronous script. //----------------------------------------------------------------------------------- //This script highlights pins on the top component level that are connected to the GND network. //It is executed at regular intervals to change the color of the pins to highlight them. //The script is executed asynchronously so as not to affect the performance of the application. //It also uses the UpdateView method to ensure that the changes are visible on the screen. //----------------------------------------------------------------------------------- using PCBI.Automation; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace PCBIScript { public class PScript : IPCBIScriptASync { public void Execute(PCBI.Automation.IPCBIWindow parent) { //do work here bool exampleColorReset = true; while (true) { Thread.Sleep(1000); if (isDisposed) break; //example work to highlight pins of gnd net IStep curStep = parent.GetCurrentStep(); if (curStep == null) return; ICMPLayer topLayer = curStep.GetCMPLayer(true); if (topLayer == null) continue; foreach (ICMPObject cmp in topLayer.GetAllLayerObjects()) { foreach (IPin pin in cmp.GetPinList()) { if (pin.GetNetNameOnIPin(cmp).ToLowerInvariant().Contains("gnd")) { if(exampleColorReset) pin.ResetPinColor(cmp); else pin.SetPinColor(System.Drawing.Color.Aqua, cmp); } } } exampleColorReset = !exampleColorReset; parent.UpdateView(); } } bool isDisposed = false; public void Dispose() { isDisposed = true; } } }
b5113fdea0d77a09bd77ed718cf209f2f2b64581
C#
rafaelcarlins/Teste_Softplan
/Softplan/Business/TaxaJuros.cs
2.609375
3
 using Newtonsoft.Json; using Softplan.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace Softplan.Business { public class TaxaJuros :ITaxaJuros { HttpClient client = new HttpClient(); public TaxaJuros() { client.BaseAddress = new Uri("https://localhost:44395/");//localhost client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } public async Task<decimal> RetornoTaxaJuros() { HttpResponseMessage response = await client.GetAsync("/api/taxajuros");//endereço para acessar if (response.IsSuccessStatusCode) { var dados = await response.Content.ReadAsStringAsync(); decimal ret = JsonConvert.DeserializeObject<decimal>(dados); return ret; } return 0; } } }
d44f0aab85b99fa3dd0e474ea6e72ee34eddaea2
C#
OlegFirumiants-Sela/SAR_Tech-interview-test
/InterviewTest/FirstQuestion/Rectangle.cs
3.4375
3
using System; using System.Collections.Generic; using System.Text; namespace FirstQuestion { class Rectangle : AbstractPolygon, IPolygon { double _width, _length; public Rectangle(double width, double length) { _width = width; _length = length; CalcArea(); CalcPerimeter(); } public void CalcArea() { _area = _width * _length; } public void CalcPerimeter() { _perimeter = 2 * (_width + _length); } } }
d46525e42a5be0bac3d21e85aa8541e12d337da8
C#
lynkfox/schoolExampleCode
/C Sharp Programing 2/FreeWeather/FreeWeather1/Controllers/WeatherController.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using FreeWeather1.Models; using System.Net.Http; using Newtonsoft.Json; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace FreeWeather1.Controllers { public class WeatherController : Controller { static HttpClient client = new HttpClient(); string apiKey = "af3beccb1675daada2e5840b10fffdf6"; // GET: /<controller>/ public IActionResult Index() { return View(); } [HttpPost] public IActionResult Index(Zip data) { int zipcode = data.zipCode; string response = GetWeather(zipcode.ToString()).GetAwaiter().GetResult(); // Deserialize the results. OpenWeatherMap openWeatherMap = JsonConvert.DeserializeObject<OpenWeatherMap>(response); /* Question for Class - Why Does the Deserialization not have a problem when we cut out various * properties of the classes created by the json? * * need more details on how this foreach loop below here is working. What is it doing? * * openWeatherMap.weather is an array - its going through the array... of strings. ah I got it. * * but still - DesearlizeObject is doing the heavy lifting here. It is what is taking the Json - because * jsons are always formated in the same manner - and taking the values and putting them in the proper class * properties... * * it just has a if property !exist clause, don't bother with that value and move on? */ string weatherDescription = ""; foreach (var weatherItem in openWeatherMap.weather) { if (!string.IsNullOrEmpty(weatherDescription)) weatherDescription += " and "; weatherDescription += weatherItem.weatherDescription; } var viewModel = new WeatherData { City = openWeatherMap.cityName, zipCode = zipcode, Desc = weatherDescription, Temp = openWeatherMap.main.temp.ToString() }; return View("LocalWeather", viewModel); } public async Task<string> GetWeather(string zipCode) { var requestParameters = new Dictionary<string, string>(); requestParameters.Add("zip", zipCode); string uri = GetUri(requestParameters); var response = await client.GetAsync(uri); string returnValue = ""; if (response.IsSuccessStatusCode) { returnValue = await response.Content.ReadAsStringAsync(); } return returnValue; } public string GetUri(Dictionary<string, string> requestParameters) { requestParameters.Add("units", "imperial"); requestParameters.Add("APPID", apiKey); var builder = new StringBuilder("http://api.openweathermap.org/data/2.5/weather"); bool firstParameter = true; /* Ok. This is the IMPORTANT loop - this is the loop thats reading the JSON into the dictionary * dataType. whats it doing? * * well, we have the First Parameter = true for the first run through. * Which we append to the string builder as True ... what does the ? "?" : "&" mean? * * then it adds the first part of the json (the name) to the Key of the dictionary (first string) sets an * = sign, then the seceond part of the Json - in this case after the : (is that what the above is doing?) * as the value. * * so we end up with a long string of Key = Value ... * * oh? does ? "?" : "&" mean replace ? with ? and : with &? so the string would build (and because * jsons are all formated the same way, and this is a deserializer built to interpret jsons) the string would * end up Key=Value&Key=Value ect.... with any ? remaining question marks (so unknown data remains unknown data?) * * * * no... none of that is right.... because requestParemeters at this point is just a dictionary with * zip, ##### * units, imperial * APPID, ###ourKey### * * so this is using the dictionary to build the URI... AH Thats what First Paremeter is for then! * * it sets the ? as the first thing built onto the string after the api.blah/blah/weather * * because it was true... so Builder((Boolean) ? "?" : "&") is a very complicated and interesting function * overload that takes a boolean, and sets the first value (?) if true and the second (after the ':'?) if false! * * and for a dictionary, remember Key is the first object in the dictionary, and Value is the second. */ foreach (var parameter in requestParameters) { builder.Append((firstParameter) ? "?" : "&"); builder.Append(parameter.Key); builder.Append("="); builder.Append(parameter.Value); firstParameter = false; } return builder.ToString(); } } }
c5c3a2bc966659dfa91d8c425d202d6a4fe051f5
C#
Yupdown/Project-Isometric
/Assets/Project-Isometric/IsometricGame/Item/ItemContainer.cs
3.046875
3
using System; namespace Isometric.Items { public class ItemContainer { private ItemStack _itemStack; public ItemStack itemStack { get { return _itemStack; } } public bool blank { get { return _itemStack == null; } } public event Action SignalItemChange; public ItemStack Apply(ItemStack itemStack) { ItemStack.Apply(ref _itemStack, ref itemStack); if (SignalItemChange != null) SignalItemChange(); return itemStack; } public void Apply(int value) { ItemStack.AddStack(ref _itemStack, value); if (SignalItemChange != null) SignalItemChange(); } } }
9dea818a76ded40013cc45563834d09dcab32e8b
C#
romulo-ribeiro/Exercism
/teams/padawan-2020-maringa/csharp/react/React.cs
3.40625
3
using System; using System.Collections.Generic; using System.Linq; public class Reactor { public InputCell CreateInputCell(int value) => new InputCell(value); public ComputeCell CreateComputeCell(IEnumerable<Cell> producers, Func<int[], int> compute) => new ComputeCell(producers, compute); } public abstract class Cell { private int _value; public int Value { get => _value; set { if (value == _value) return; _value = value; Changed?.Invoke(this, _value); } } public event EventHandler<int> Changed; } public class InputCell : Cell { public InputCell(int value) => Value = value; } public class ComputeCell : Cell { private readonly IEnumerable<Cell> _producers; private readonly Func<int[], int> _compute; public ComputeCell(IEnumerable<Cell> producers, Func<int[], int> compute) { _producers = producers; _compute = compute; foreach (var cell in _producers) { cell.Changed += ValueChanged; } Compute(); } private void ValueChanged(object sender, int newValue) => Compute(); private int Compute() => Value = _compute((from p in _producers select p.Value).ToArray()); }
f887d9dd1c543edb0f4088035887d13644447f8a
C#
NoumanMalik-grb/phamarchy-systeam
/phamarchy systeam/Controllers/SaleReturn1Controller.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using phamarchy_systeam.Models; using System.Web.Mvc; namespace phamarchy_systeam.Controllers { public class SaleReturn1Controller : Controller { Model1 db = new Model1(); public ActionResult SaleReturnCart() { return View(); } //public ActionResult Addtocart(int id) //{ // Product p = new Product(); // p.quantity = 5; // List<Product> Rlist = new List<Product>(); // Rlist.Add(db.Products.Where(x => x.Product_id == id).FirstOrDefault()); // Session["productReturn"] = Rlist; // return RedirectToAction("SaleReturnCart"); //} public ActionResult AddTocart(int id, int quantity) { List<Product> Rlist = new List<Product>(); if (Session["productReturn"] != null) { Rlist = (List<Product>)Session["productReturn"]; } bool ProductExsit = false; foreach (var item in Rlist) { if (id == item.Product_id) { ProductExsit = true; item.Rquantity++; } } if (ProductExsit == false) { Product pro = db.Products.Where(p => p.Product_id == id).FirstOrDefault(); Rlist.Add(pro); Rlist[0].Rquantity = quantity; } Session["productReturn"] = Rlist; return RedirectToAction("SaleReturnCart"); } } }
266127cf95b1fc5ae2dfd8b7e9877b621f479f56
C#
CappiJonas/Curso-de-L-gica-de-Programa-o
/Seção 6/Exercícios Propostos/Exercicios_Propostos/Exercicio_8/Program.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio_8 { class Program { static void Main(string[] args) { int N; string[] sexo; double[] altura; N = int.Parse(Console.ReadLine()); sexo = new string[N]; altura = new double[N]; for (int i = 0; i < N; i++) { string[] s = Console.ReadLine().Split(' '); altura[i] = double.Parse(s[0]); sexo[i] = s[1]; } double menorAltura = 10.0; for (int i = 0; i < N; i++) { if (menorAltura > altura[i]) { menorAltura = altura[i]; } } Console.WriteLine($"Menor Altura = {menorAltura}"); double maiorAltura = 0.0; for (int i = 0; i < N; i++) { if (maiorAltura < altura[i]) { maiorAltura = altura[i]; } } Console.WriteLine($"Maior Altura = {maiorAltura}"); int cont = 0; double somaAlturaMulheres = 0.0; double media = 0.0; for (int i = 0; i < N; i++) { if (sexo[i] == "F") { somaAlturaMulheres = somaAlturaMulheres + altura[i]; cont++; } } media = somaAlturaMulheres / cont; Console.WriteLine($"Média das alturas das mulheres = {media.ToString("F2")}"); int contHomem = 0; for (int i = 0; i < N; i++) { if (sexo[i] == "M") { contHomem++; } } Console.WriteLine($"Número de Homens = {contHomem}"); Console.ReadKey(); } } }
3693db5be8e8753aa18b30ad2696fb6d1f23db78
C#
lacerdaeduardo/SwStarship
/src/SwStarship.Core/Util/SwApiClient.cs
2.5625
3
using Microsoft.Extensions.Configuration; using RestSharp; using SwStarship.Core.Domain.Models; using SwStarship.Core.Generics; using SwStarship.Core.Interfaces; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; namespace SwStarship.Core.Util { public class SwApiClient : ISwApiClient { private readonly IConfiguration _configuration; private readonly IRestClient _restClient; private readonly string _starshipEndpoint; public SwApiClient(IConfiguration configuration, IRestClient restClient) { _configuration = configuration; _restClient = restClient; _starshipEndpoint = _configuration.GetSection("SwStarshipsEndpoint").Value; } public async Task<IEnumerable<Starship>> GetStarshipsAsync() { List<Starship> starships = new List<Starship>(); var starshipRequest = new RestRequest(_starshipEndpoint, DataFormat.Json); while (starshipRequest != null) { var getResponse = await _restClient.ExecuteGetAsync<PagedList<Starship>>(starshipRequest); if (!HttpStatusCode.OK.Equals(getResponse.StatusCode)) { break; } starships.AddRange(getResponse.Data.Results); starshipRequest = !string.IsNullOrEmpty(getResponse.Data.Next) ? new RestRequest(getResponse.Data.Next, DataFormat.Json) : null; } return starships; } } }
e040db36e2a90630e1f001307d47138572befc53
C#
gindyo/POS-WPF
/Register.UI/Models/BaseVM.cs
2.671875
3
using System; using System.ComponentModel; using System.Reflection; using System.Runtime.CompilerServices; using Interfaces.VMBased; namespace Register.UI.Models { public class BaseVM<T> : IBaseVM { public BaseVM() { } public BaseVM(T baseInstance) { Type type = typeof (T); PropertyInfo[] props = type.GetProperties(); foreach (PropertyInfo propertyInfo in props) { propertyInfo.SetValue(this, propertyInfo.GetValue(baseInstance)); } } public event PropertyChangedEventHandler PropertyChanged; public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } }
f366c19cdf484e70e89a9dd31ad852f1a5bdb639
C#
EdwardDobson/CUBER
/Assets/Scripts/Platforms/Rotate.cs
2.71875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum RotateDirection { None, Right, Left, } public class Rotate : MonoBehaviour { public float Speed; public RotateDirection dir; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { switch(dir) { case RotateDirection.Left: transform.Rotate(Vector3.forward, 45 * Time.deltaTime * Speed); break; case RotateDirection.Right: transform.Rotate(Vector3.back, 45 * Time.deltaTime * Speed); break; case RotateDirection.None: break; default: break; } } }
7d137daac10eb4f3a2e0146e4f49e59776a2b8e0
C#
Mozlite/aspnetcore
/Mozlite.Mvc/AdminMenus/MenuProviderFactory.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Caching.Memory; namespace Mozlite.Mvc.AdminMenus { /// <summary> /// 菜单提供者工厂实现类。 /// </summary> public class MenuProviderFactory : IMenuProviderFactory { private readonly IEnumerable<IMenuProvider> _providers; private readonly IMemoryCache _cache; /// <summary> /// 初始化类<see cref="MenuProviderFactory"/>。 /// </summary> /// <param name="providers">菜单提供者接口。</param> /// <param name="cache">缓存接口。</param> public MenuProviderFactory(IEnumerable<IMenuProvider> providers, IMemoryCache cache) { _providers = providers; _cache = cache; } /// <summary> /// 通过提供者名称获取菜单实例对象。 /// </summary> /// <param name="provider">提供者名称。</param> /// <returns>返回当前提供者名称的菜单实例对象。</returns> public IEnumerable<MenuItem> GetMenus(string provider) { return LoadMenus(provider).Values; } private IDictionary<string, MenuItem> LoadMenus(string provider) { return _cache.GetOrCreate($"memus[{provider}]", ctx => { ctx.SetAbsoluteExpiration(TimeSpan.FromMinutes(3)); var dic = new Dictionary<string, MenuItem>(StringComparer.OrdinalIgnoreCase); var providers = _providers.Where(p => string.Compare(p.Name, provider, StringComparison.OrdinalIgnoreCase) == 0); foreach (var menuProvider in providers) { AddProvider(dic, menuProvider); } return dic; }); } /// <summary> /// 获取当前选项。 /// </summary> /// <param name="provider">提供者名称。</param> /// <param name="name">当前菜单唯一Id。</param> /// <returns>返回当前菜单项。</returns> public MenuItem GetMenu(string provider, string name) { LoadMenus(provider).TryGetValue(name, out var item); return item; } private void AddProvider(IDictionary<string, MenuItem> dic, IMenuProvider provider) { var root = new MenuItem(); provider.Init(root); foreach (var menu in root) { if (dic.TryGetValue(menu.Name, out var item)) item.Merge(menu); else item = menu; AddSubMenus(dic, item); } } private void AddSubMenus(IDictionary<string, MenuItem> dic, MenuItem item) { dic[item.Name] = item; foreach (var it in item) { AddSubMenus(dic, it); } } /// <summary> /// 通过提供者名称获取菜单顶级实例对象。 /// </summary> /// <param name="provider">提供者名称。</param> /// <returns>返回当前提供者名称的菜单实例对象。</returns> public IEnumerable<MenuItem> GetRoots(string provider) { return GetMenus(provider) .Where(x => x.Level == 0) .OrderByDescending(x => x.Priority) .ToList(); } /// <summary> /// 属性菜单。 /// </summary> /// <param name="provider">菜单提供者。</param> public void Refresh(string provider) { _cache.Remove($"memus[{provider}]"); } } }
78bf4df9538f79d7e7cc4c7c114a2564f320147d
C#
renansalvino/MVCSenai
/McBonaldsMVC/Repositorios/ClienteRepository.cs
2.828125
3
using Microsoft.Win32; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; using System.Text.RegularExpressions; using System; using Hamburgueria_WebMVC.Models; namespace Hamburgueria.Repositories { public class ClienteRepository : BaseRepository { public static uint CONT = 0; private const string PATH = "Database/Cliente.csv"; private const string PATH_INDEX = "Database/Cliente_Id.csv"; private List<Cliente> clientes = new List<Cliente> (); public ClienteRepository() { if (!File.Exists(PATH_INDEX)){ File.Create(PATH_INDEX).Close(); } var ultimoIndice = File.ReadAllText(PATH_INDEX); uint indice = 0; uint.TryParse(ultimoIndice, out indice); CONT = indice; } public bool Inserir (Cliente cliente) { CONT++; File.WriteAllText(PATH_INDEX, CONT.ToString()); string linha = PrepararRegistroCSV (cliente); File.AppendAllText (PATH, linha); return true; } public bool Atualizar (Cliente cliente) { var clientesRecuperados = ObterRegistrosCSV (PATH); var clienteString = PrepararRegistroCSV (cliente); var linhaCliente = -1; var resultado = false; for (int i = 0; i < clientesRecuperados.Length; i++) { if (clienteString.Equals (clientesRecuperados[i])) { linhaCliente = i; resultado = true; } } if (linhaCliente >= 0) { clientesRecuperados[linhaCliente] = clienteString; File.WriteAllLines (PATH, clientesRecuperados); } return resultado; } public bool Apagar (ulong id) { var clientesRecuperados = ObterRegistrosCSV (PATH); var linhaCliente = -1; var resultado = false; for (int i = 0; i < clientesRecuperados.Length; i++) { if (id.Equals (clientesRecuperados[i])) { linhaCliente = i; resultado = true; } } if (linhaCliente >= 0) { clientesRecuperados[linhaCliente] = ""; try { File.WriteAllLines (PATH, clientesRecuperados); } catch(DirectoryNotFoundException ) { System.Console.WriteLine("Diretório não encontrado. Favor verificar."); } catch (PathTooLongException ) { System.Console.WriteLine("Nome do arquivo é muito grande."); } } return resultado; } public Cliente ObterPor (ulong id) { foreach (var item in ObterRegistrosCSV (PATH)) { if (id.Equals (ExtrairCampo (id.ToString(), item))) { return ConverterEmObjeto (item); } } return null; } public Cliente ObterPor (string email) { if (email != null) { foreach (var item in ObterRegistrosCSV (PATH)) { if (email.Equals (ExtrairCampo ("email", item))) { return ConverterEmObjeto (item); } } } return null; } public List<Cliente> ListarTodos () { var linhas = ObterRegistrosCSV (PATH); foreach (var item in linhas) { Cliente cliente = ConverterEmObjeto (item); this.clientes.Add (cliente); } return this.clientes; } private Cliente ConverterEmObjeto (string registro) { Cliente cliente = new Cliente(); System.Console.WriteLine("REGISTRO:" + registro); cliente.Id = ulong.Parse(ExtrairCampo("id", registro)); cliente.Nome = ExtrairCampo("nome", registro); cliente.Email = ExtrairCampo("email", registro); cliente.Senha = ExtrairCampo("senha", registro); cliente.Endereco = ExtrairCampo("endereco", registro); cliente.Telefone = ExtrairCampo("telefone", registro); cliente.DataNascimento = DateTime.Parse(ExtrairCampo("data_nascimento", registro)); return cliente; } private string PrepararRegistroCSV (Cliente cliente) { return $"id={CONT};nome={cliente.Nome};email={cliente.Email};senha={cliente.Senha};endereco={cliente.Endereco};telefone={cliente.Telefone};data_nascimento={cliente.DataNascimento}\n"; } } }
02365c4c93e92814fa944a306cebb3294ca6a796
C#
BerniceChua/PluggableAITutorial
/Assets/PluggableAI/TargetsAndArrayList.cs
2.734375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public static class TargetsAndArrayList { /*[HideInInspector]*/ public static List<GameObject> m_TargetsList = new List<GameObject>(); //// Use this for initialization //void Start () { //if (m_TargetsList == null) { // m_TargetsList = new ArrayList(); // } // } //// Update is called once per frame //void Update () { // //if (FindObjectOfType<Target>()) { // // return true; // //} //} public static void AddToArrayList(GameObject targetWithThisName) { // Add target to the ArrayList. m_TargetsList.Add(targetWithThisName); Debug.Log(targetWithThisName + " has been added to the List."); //Debug.Log("CountThingsInArrayList() = " + CountThingsInArrayList()); } public static void RemoveFromArrayList(GameObject targetWithThisName) { // Remove target from the ArrayList. m_TargetsList.Remove(targetWithThisName); Debug.Log(targetWithThisName + " has been removed from the List."); //Debug.Log("CountThingsInArrayList() = " + CountThingsInArrayList()); } public static int CountThingsInArrayList() { // Used for debugging Debug.Log("m_TargetsList.Count = " + m_TargetsList.Count); return m_TargetsList.Count; } public static void IterateThroughArrayList() { } public static GameObject GetNearestInArrayList() { GameObject nearest = m_TargetsList[0]; float dist = Mathf.Infinity; //foreach (GameObject target in m_TargetsList) { // if (target.transform.position.sqrMagnitude < nearest.transform.position.sqrMagnitude) { // nearest = target; // Debug.Log("nearest = " + nearest); // } //} if (CountThingsInArrayList() == 0) return null; else { for (int i = 0; i < m_TargetsList.Count; i++) { if (m_TargetsList[i].activeSelf == false) { continue; } float distanceBetween = Vector3.Distance(m_TargetsList[i].transform.position, nearest.transform.position); if (nearest == null || distanceBetween < dist) { nearest = m_TargetsList[i]; dist = distanceBetween; } if (m_TargetsList[i].transform.position.sqrMagnitude < nearest.transform.position.sqrMagnitude) { nearest = m_TargetsList[i]; Debug.Log("nearest = " + nearest); } } return nearest; } } }
905cc2a062c8939bbade8831c3c58e451d19d66a
C#
Gribbleshnibit8/CKAN-plugins
/Parts Pruner/FilePruner.cs
2.859375
3
using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Remoting.Messaging; using CKAN; using PartsPrunerPlugin; namespace PartsPruner { class FilePruner { /// <summary> /// Takes a .prnl file and determines if it is fully or partially pruned /// </summary> /// <param name="path"></param> /// <returns></returns> public bool CheckPruned(string path) { bool r = false; foreach (var line in LoadFilePaths(path)) { if (IsBlankOrComment(line)) continue; var fPath = Path.Combine(Main.Instance.CurrentInstance.GameData(), line); bool i = IsDirectoryPruned(fPath); if (i != r) r = i; } return r; } /// <summary> /// Determines if a folder contains all pruned files or pruned and unpruned /// </summary> /// <param name="path"></param> /// <returns></returns> public bool IsDirectoryPruned(string path) { if (Directory.Exists(path)) { var di = new DirectoryInfo(path); if (!di.Exists) return false; int fileCount = di.EnumerateFiles("*", SearchOption.AllDirectories).Count(); int pruneCount = di.EnumerateFiles("*.prune", SearchOption.AllDirectories).Count(); if (fileCount == pruneCount) return true; return false; } if (File.Exists(path + ".prune")) return true; return false; } /// <summary> /// Loads all lines from a given .prnl file /// </summary> /// <param name="file"></param> /// <returns></returns> private List<string> LoadFilePaths(string file) { var pathsInFile = new List<string>(); using (var r = new StreamReader(file)) { string line; while ((line = r.ReadLine()) != null) pathsInFile.Add(line); } return pathsInFile; } /// <summary> /// Checks if the given string starts with a # or is a blank line /// </summary> /// <param name="line"></param> /// <returns></returns> private bool IsBlankOrComment(string line) { if (line[0] == '#') return true; if (string.IsNullOrEmpty(line)) return true; return false; } #region Pruner /// <summary> /// Takes a list of file and directory paths and adds the .prune extension to all contained files /// </summary> /// <param name="filesList">List of file and directory paths</param> public void PruneFiles(IEnumerable<string> filesList) { foreach (var file in filesList) { foreach (var line in LoadFilePaths(file)) { if (IsBlankOrComment(line)) continue; var path = Path.Combine(Main.Instance.CurrentInstance.GameData(), line); if (File.Exists(path)) PruneFile(path); else if (Directory.Exists(path)) PruneDirectory(path); else PartPrunerUi.Instance.LogWarning("\"" + PartPrunerUi.GetGameDataPath(path) + "\" is not a file or a directory."); } } } private void PruneDirectory(string path) { try { PartPrunerUi.Instance.Log("Pruning files from " + PartPrunerUi.GetGameDataPath(path)); var files = Directory.GetFiles(path).ToList(); files.AddRange(Directory.GetDirectories(path)); foreach (var file in files) { if (File.Exists(file)) PruneFile(file); else if (Directory.Exists(file)) PruneDirectory(file); } } catch (IOException ex) { PartPrunerUi.Instance.LogError(ex.ToString()); } } private void PruneFile(string file) { try { File.Move(file, file + ".prune"); PartPrunerUi.Instance.Log("Pruned: " + PartPrunerUi.GetGameDataPath(file)); } catch (IOException ex) { PartPrunerUi.Instance.LogError(ex.ToString()); } } #endregion Pruner #region Unpruner /// <summary> /// Takes a list of file and directory paths and removes the .prune extension from all contained files /// </summary> /// <param name="filesList">List of file and directory paths</param> public void UnpruneFiles(IEnumerable<string> filesList) { foreach (var file in filesList) { foreach (var line in LoadFilePaths(file)) { var prunefile = Path.Combine(Main.Instance.CurrentInstance.GameData(), line + ".prune"); var path = Path.Combine(Main.Instance.CurrentInstance.GameData(), line); if (File.Exists((prunefile))) path += ".prune"; if (File.Exists(path)) UnpruneFile(path); else if (Directory.Exists(path)) UnpruneDirectory(path); else PartPrunerUi.Instance.LogWarning("\"" + PartPrunerUi.GetGameDataPath(path) + "\" is not a file or a directory."); } } } private void UnpruneDirectory(string path) { try { PartPrunerUi.Instance.Log("Unpruning files from " + PartPrunerUi.GetGameDataPath(path)); var files = Directory.GetFiles(path).ToList(); files.AddRange(Directory.GetDirectories(path)); foreach (var file in files) { if (File.Exists(file)) UnpruneFile(file); else if (Directory.Exists(file)) UnpruneDirectory(file); } } catch (IOException ex) { PartPrunerUi.Instance.LogError(ex.ToString()); } } private void UnpruneFile(string file) { try { var newFile = file.Replace(".prune", ""); File.Move(file, newFile); PartPrunerUi.Instance.Log("Unpruned: " + PartPrunerUi.GetGameDataPath(file)); } catch (IOException ex) { PartPrunerUi.Instance.LogError(ex.ToString()); } } #endregion Unpruner } }
c13cca448c3a77f06ce89948e3d63b70096f391a
C#
juan102/Parcial2
/Decorator/FastSSD.cs
2.671875
3
using System; using System.Collections.Generic; using System.Text; namespace Decorator { public class FastSSD : Decorador { private Computador ComputadorActual; public FastSSD(Computador computador) { this.ComputadorActual = computador; } public override decimal CalcularCosto() { return this.ComputadorActual.CalcularCosto() + 255.20M; } } }
8390aa56ce02b15748194e9213617d9ca6962933
C#
EricZhaoCherryTomato/ConnectFour
/ConnectFour/Game.cs
3.125
3
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; namespace ConnectFour { public class Game :IGame { private readonly IBoard _board; private readonly IPlayer _player; private readonly IJudge _judge; public Game(IBoard board, IPlayer player, IJudge judge) { _board = board; _player = player; _judge = judge; } public void Start() { var boardDimension = _board.InitBoard(); char[,] board = new char[boardDimension[0], boardDimension[1]];; var p1 = _player.Create(); p1.SetPlayerColor('y'); p1.SetPlayerName("Yellows"); var p2 = _player.Create(); p2.SetPlayerColor('r'); p2.SetPlayerName("Reds"); Console.Write(_board.PrintState(board)); do { if (GetMove(p1, board)) break; if (GetMove(p2, board)) break; } while (true); Console.ReadKey(true); } private bool GetMove(Player player, char[,] board) { var dropChoice = -1; do { try { Console.Write("\n"); Console.WriteLine(player.PlayerName + " Turn "); dropChoice = Convert.ToInt32(Console.ReadLine()); board = player.DropCoin(board, dropChoice - 1); Console.Write(_board.PrintState(board)); var win = _judge.CheckBoard(board, player); if (!win) return false; Console.Write("\n"); Console.WriteLine(player.PlayerName + " WINS !"); } catch { Console.Write("Invalid Move"); } } while (dropChoice < 0); return true; } } }
6fe05fbdaeaaea19f329b67e3d0ee5743bbf95a6
C#
jacksonh/manos
/src/Manos/Manos.Http/HttpParser.cs
2.53125
3
// // Based on http_parser.java: http://github.com/a2800276/http-parser.java // which is based on http_parser: http://github.com/ry/http-parser // // // Copyright 2009,2010 Ryan Dahl <ry@tinyclouds.org> // Copyright (C) 2010 Tim Becker // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // 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 System; using System.IO; using Manos.IO; namespace Manos.Http { public class HttpParser { private ParserType type; private int http_major; private int http_minor; private int status_code; private HttpMethod method; /* true = Upgrade header was present and the parser has exited because of that. * false = No upgrade header present. * Should be checked when http_parser_execute() returns in addition to * error checking. */ protected bool upgrade; public HttpParser () : this (ParserType.HTTP_BOTH) { } public HttpParser (ParserType type) { this.type = type; switch (type) { case ParserType.HTTP_REQUEST: this.state = State.start_req; break; case ParserType.HTTP_RESPONSE: this.state = State.start_res; break; case ParserType.HTTP_BOTH: this.state = State.start_res_or_res; break; default: throw new HttpException ("can't happen, invalid ParserType enum"); } } public bool Strict { get { return strict; } set { strict = value; } } public int Major { get { return http_major; } } public int Minor { get { return http_minor; } } public int StatusCode { get { return status_code; } } public HttpMethod HttpMethod { get { return method; } } public bool Upgrade { get { return upgrade; } } public bool KeepAlive { get { return http_should_keep_alive (); } } // // The state machine // State state; HState header_state; bool strict; int index; int flags; // TODO int nread; int content_length; /* * technically we could combine all of these (except for url_mark) into one * variable, saving stack space, but it seems more clear to have them * separated. */ int header_field_mark = -1; int header_value_mark = -1; int fragment_mark = -1; int query_string_mark = -1; int path_mark = -1; int url_mark = -1; static void p (object o) { Console.WriteLine (o); } /** Execute the parser with the currently available data contained in * the buffer. The buffers position() and limit() need to be set * correctly (obviously) and a will be updated approriately when the * method returns to reflect the consumed data. */ public void Execute (ParserSettings settings, ByteBuffer data) { int p = (int) data.Position; int p_err = p; // this is used for pretty printing errors. // In case the headers don't provide information about the content // length, `execute` needs to be called with an empty buffer to // indicate that all the data has been send be the client/server, // else there is no way of knowing the message is complete. int len = data.Length; if (0 == len) { if (State.body_identity_eof == state) settings.RaiseOnMessageComplete(this); } // in case the _previous_ call to the parser only has data to get to // the middle of certain fields, we need to update marks to point at // the beginning of the current buffer. switch (state) { case State.header_field: header_field_mark = p; break; case State.header_value: header_value_mark = p; break; case State.req_fragment: fragment_mark = p; url_mark = p; break; case State.req_query_string: query_string_mark = p; url_mark = p; break; case State.req_path: path_mark = p; // JACKSON ADDED, I assume java can fall through? url_mark = p; break; case State.req_host: case State.req_schema: case State.req_schema_slash: case State.req_schema_slash_slash: case State.req_port: case State.req_query_string_start: case State.req_fragment_start: url_mark = p; break; } // this is where the work gets done, traverse the available data... while (data.Length > 0) { p = (int) data.Position; int pe = (int) data.Length; byte ch = 0; // the current character to process. int c = -1; // utility variably used for up- and downcasing etc. int to_read = 0; // used to keep track of how much of body, etc. is left to read if(state != State.body_identity) ch = data.ReadByte (); if (parsing_header (state)) { ++nread; if (nread > HTTP_MAX_HEADER_SIZE) { settings.RaiseOnError (this, "possible buffer overflow", data, p_err); } } switch (state) { /* * this state is used after a 'Connection: close' message * the parser will error out if it reads another message */ case State.dead: settings.RaiseOnError (this, "Connection already closed", data, p_err); // JACKSON: Added this break break; case State.start_res_or_res: if (CR == ch || LF == ch){ break; } flags = 0; content_length = -1; settings.RaiseOnMessageBegin (this); if (H == ch) state = State.res_or_resp_H; else { type = ParserType.HTTP_REQUEST; method = start_req_method_assign (ch); if (HttpMethod.ERROR == method) settings.RaiseOnError (this, "invalid method", data, p_err); index = 1; state = State.req_method; } break; case State.res_or_resp_H: if (T == ch) { type = ParserType.HTTP_RESPONSE; state = State.res_HT; } else { if (E != ch) settings.RaiseOnError (this, "not E", data, p_err); type = ParserType.HTTP_REQUEST; method = HttpMethod.HTTP_HEAD; index = 2; state = State.req_method; } break; case State.start_res: flags = 0; content_length = -1; settings.RaiseOnMessageBegin (this); switch (ch) { case H: state = State.res_H; break; case CR: case LF: break; default: settings.RaiseOnError (this, "Not H or CR/LF", data, p_err); break; } break; case State.res_H: if (strict && T != ch) settings.RaiseOnError (this, "Not T", data, p_err); state = State.res_HT; break; case State.res_HT: if (strict && T != ch) settings.RaiseOnError (this, "Not T2", data, p_err); state = State.res_HTT; break; case State.res_HTT: if (strict && P != ch) settings.RaiseOnError (this, "Not P", data, p_err); state = State.res_HTTP; break; case State.res_HTTP: if (strict && SLASH != ch) settings.RaiseOnError (this, "Not '/'", data, p_err); state = State.res_first_http_major; break; case State.res_first_http_major: if (!isDigit (ch)) settings.RaiseOnError (this, "Not a digit", data, p_err); http_major = (int) ch - 0x30; state = State.res_http_major; break; /* major HTTP version or dot */ case State.res_http_major: if (DOT == ch) { state = State.res_first_http_minor; break; } if (!isDigit (ch)) settings.RaiseOnError(this, "Not a digit", data, p_err); http_major *= 10; http_major += (ch - 0x30); if (http_major > 999) settings.RaiseOnError(this, "invalid http major version: " + http_major, data, p_err); break; /* first digit of minor HTTP version */ case State.res_first_http_minor: if (!isDigit (ch)) settings.RaiseOnError (this, "Not a digit", data, p_err); http_minor = (int)ch - 0x30; state = State.res_http_minor; break; /* minor HTTP version or end of request line */ case State.res_http_minor: if (SPACE == ch) { state = State.res_first_status_code; break; } if (!isDigit (ch)) settings.RaiseOnError(this, "Not a digit", data, p_err); http_minor *= 10; http_minor += (ch - 0x30); if (http_minor > 999) settings.RaiseOnError(this, "invalid http minor version: " + http_minor, data, p_err); break; case State.res_first_status_code: if (!isDigit (ch)) { if (SPACE == ch) break; settings.RaiseOnError (this, "Not a digit (status code)", data, p_err); } status_code = (int)ch - 0x30; state = State.res_status_code; break; case State.res_status_code: if (!isDigit (ch)) { switch (ch) { case SPACE: state = State.res_status; break; case CR: state = State.res_line_almost_done; break; case LF: state = State.header_field_start; break; default: settings.RaiseOnError(this, "not a valid status code", data, p_err); break; } break; } status_code *= 10; status_code += (int)ch - 0x30; if (status_code > 999) settings.RaiseOnError(this, "ridiculous status code:"+status_code, data, p_err); break; case State.res_status: /* the human readable status. e.g. "NOT FOUND" * we are not humans so just ignore this * we are not men, we are devo. */ if (CR == ch) { state = State.res_line_almost_done; break; } if (LF == ch) { state = State.header_field_start; break; } break; case State.res_line_almost_done: if (strict && LF != ch) settings.RaiseOnError (this, "not LF", data, p_err); state = State.header_field_start; break; case State.start_req: if (CR==ch || LF == LF) break; flags = 0; content_length = -1; settings.RaiseOnMessageBegin (this); method = start_req_method_assign (ch); if (HttpMethod.ERROR == method) settings.RaiseOnError (this, "invalid method", data, p_err); index = 1; state = State.req_method; break; case State.req_method: if (0 == ch) settings.RaiseOnError( this, "NULL in method", data, p_err); byte [] arr = HttpMethodBytes.GetBytes (method); if (SPACE == ch && index == arr.Length) state = State.req_spaces_before_url; else if (arr[index] == ch) { // wuhu! } else if (HttpMethod.HTTP_CONNECT == method) { if (1 == index && H == ch) { method = HttpMethod.HTTP_CHECKOUT; } else if (2 == index && P == ch) { method = HttpMethod.HTTP_COPY; } } else if (HttpMethod.HTTP_MKCOL == method) { if (1 == index && O == ch) { method = HttpMethod.HTTP_MOVE; } else if (1 == index && E == ch) { method = HttpMethod.HTTP_MERGE; } else if (2 == index && A == ch) { method = HttpMethod.HTTP_MKACTIVITY; } } else if (1 == index && HttpMethod.HTTP_POST == method && R == ch) { method = HttpMethod.HTTP_PROPFIND; } else if (1 == index && HttpMethod.HTTP_POST == method && U == ch) { method = HttpMethod.HTTP_PUT; } else if (4 == index && HttpMethod.HTTP_PROPFIND == method && P == ch) { method = HttpMethod.HTTP_PROPPATCH; } else { settings.RaiseOnError (this, "Invalid HTTP method", data, p_err); } ++index; break; /*__________________URL__________________*/ case State.req_spaces_before_url: if (SPACE == ch) break; if (SLASH == ch) { url_mark = p; path_mark = p; state = State.req_path; break; } if (isAtoZ (ch)) { url_mark = p; state = State.req_schema; break; } settings.RaiseOnError (this, "Invalid something", data, p_err); break; case State.req_schema: if (isAtoZ (ch)) break; if (COLON == ch) { state = State.req_schema_slash; break; } else if (DOT == ch) { state = State.req_host; break; } settings.RaiseOnError (this, "invalid char in schema: "+ch, data, p_err); break; case State.req_schema_slash: if (strict && SLASH != ch) settings.RaiseOnError (this, "invalid char in schema, not /", data, p_err); state = State.req_schema_slash_slash; break; case State.req_schema_slash_slash: if (strict && SLASH != ch) settings.RaiseOnError(this, "invalid char in schema, not /", data, p_err); state = State.req_host; break; case State.req_host: if (isAtoZ (ch)) break; if (isDigit (ch) || DOT == ch || DASH == ch) break; switch (ch) { case COLON: state = State.req_port; break; case SLASH: path_mark = p; break; case SPACE: /* The request line looks like: * "GET http://foo.bar.com HTTP/1.1" * That is, there is no path. */ settings.RaiseOnUrl (this, data, url_mark, p-url_mark); url_mark = -1; state = State.req_http_start; break; default: settings.RaiseOnError(this, "host error in method line", data, p_err); break; } break; case State.req_port: if (isDigit (ch)) break; switch (ch) { case SLASH: path_mark = p; state = State.req_path; break; case SPACE: /* The request line looks like: * "GET http://foo.bar.com:1234 HTTP/1.1" * That is, there is no path. */ settings.RaiseOnUrl (this,data,url_mark,p-url_mark); url_mark = -1; state = State.req_http_start; break; default: settings.RaiseOnError (this, "invalid port", data, p_err); break; } break; case State.req_path: if (usual (ch)) break; switch (ch) { case SPACE: settings.RaiseOnUrl (this,data,url_mark, p-url_mark); url_mark = -1; settings.RaiseOnPath(this,data,path_mark, p-path_mark); path_mark = -1; state = State.req_http_start; break; case CR: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; settings.RaiseOnPath(this,data,path_mark, p-path_mark); path_mark = -1; http_minor = 9; state = State.res_line_almost_done; break; case LF: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; settings.RaiseOnPath(this,data,path_mark, p-path_mark); path_mark = -1; http_minor = 9; state = State.header_field_start; break; case QMARK: settings.RaiseOnPath(this,data,path_mark, p-path_mark); path_mark = -1; state = State.req_query_string_start; break; case HASH: settings.RaiseOnPath(this,data,path_mark, p-path_mark); path_mark = -1; state = State.req_fragment_start; break; default: settings.RaiseOnError(this, "unexpected char in path", data, p_err); break; } break; case State.req_query_string_start: if (usual(ch)) { query_string_mark = p; state = State.req_query_string; break; } switch (ch) { case QMARK: break; case SPACE: settings.RaiseOnUrl(this, data, url_mark, p-url_mark); url_mark = -1; state = State.req_http_start; break; case CR: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; http_minor = 9; state = State.res_line_almost_done; break; case LF: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; http_minor = 9; state = State.header_field_start; break; case HASH: state = State.req_fragment_start; break; default: settings.RaiseOnError(this, "unexpected char in path", data, p_err); break; } break; case State.req_query_string: if (usual(ch)) { break; } switch (ch) { case QMARK: break; // allow extra '?' in query string case SPACE: settings.RaiseOnUrl(this, data, url_mark, p-url_mark); url_mark = -1; settings.RaiseOnQueryString(this, data, query_string_mark, p-query_string_mark); query_string_mark = -1; state = State.req_http_start; break; case CR: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; settings.RaiseOnQueryString(this, data, query_string_mark, p-query_string_mark); query_string_mark = -1; http_minor = 9; state = State.res_line_almost_done; break; case LF: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; settings.RaiseOnQueryString(this, data, query_string_mark, p-query_string_mark); query_string_mark = -1; http_minor = 9; state = State.header_field_start; break; case HASH: settings.RaiseOnQueryString(this, data, query_string_mark, p-query_string_mark); query_string_mark = -1; state = State.req_fragment_start; break; default: settings.RaiseOnError(this, "unexpected char in path", data, p_err); break; } break; case State.req_fragment_start: if (usual(ch)) { fragment_mark = p; state = State.req_fragment; break; } switch (ch) { case SPACE: settings.RaiseOnUrl(this, data, url_mark, p-url_mark); url_mark = -1; state = State.req_http_start; break; case CR: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; http_minor = 9; state = State.res_line_almost_done; break; case LF: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; http_minor = 9; state = State.header_field_start; break; case QMARK: fragment_mark = p; state = State.req_fragment; break; case HASH: break; default: settings.RaiseOnError(this, "unexpected char in path", data, p_err); break; } break; case State.req_fragment: if (usual(ch)) { break; } switch (ch) { case SPACE: settings.RaiseOnUrl(this, data, url_mark, p-url_mark); url_mark = -1; settings.RaiseOnFragment(this, data, fragment_mark, p-fragment_mark); fragment_mark = -1; state = State.req_http_start; break; case CR: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; settings.RaiseOnFragment(this, data, query_string_mark, p-query_string_mark); fragment_mark = -1; http_minor = 9; state = State.res_line_almost_done; break; case LF: settings.RaiseOnUrl(this,data,url_mark, p-url_mark); url_mark = -1; settings.RaiseOnFragment(this, data, query_string_mark, p-query_string_mark); fragment_mark = -1; http_minor = 9; state = State.header_field_start; break; case QMARK: case HASH: break; default: settings.RaiseOnError(this, "unexpected char in path", data, p_err); break; } break; /******************* URL *******************/ /******************* HTTP 1.1 *******************/ case State.req_http_start: switch (ch) { case H: state = State.req_http_H; break; case SPACE: break; default: settings.RaiseOnError(this, "error in req_http_H", data, p_err); break; } break; case State.req_http_H: if (strict && T != ch) settings.RaiseOnError(this, "unexpected char", data, p_err); state = State.req_http_HT; break; case State.req_http_HT: if (strict && T != ch) settings.RaiseOnError(this, "unexpected char", data, p_err); state = State.req_http_HTT; break; case State.req_http_HTT: if (strict && P != ch) settings.RaiseOnError(this, "unexpected char", data, p_err); state = State.req_http_HTTP; break; case State.req_http_HTTP: if (strict && SLASH != ch) settings.RaiseOnError(this, "unexpected char", data, p_err); state = State.req_first_http_major; break; /* first digit of major HTTP version */ case State.req_first_http_major: if (!isDigit(ch)) settings.RaiseOnError(this, "non digit in http major", data, p_err); http_major = (int)ch - 0x30; state = State.req_http_major; break; /* major HTTP version or dot */ case State.req_http_major: if (DOT == ch) { state = State.req_first_http_minor; break; } if (!isDigit(ch)) settings.RaiseOnError(this, "non digit in http major", data, p_err); http_major *= 10; http_major += (int)ch - 0x30; if (http_major > 999) settings.RaiseOnError(this, "ridiculous http major", data, p_err); break; /* first digit of minor HTTP version */ case State.req_first_http_minor: if (!isDigit(ch)) settings.RaiseOnError(this, "non digit in http minor", data, p_err); http_minor = (int)ch - 0x30; state = State.req_http_minor; break; case State.req_http_minor: if (ch == CR) { state = State.req_line_almost_done; break; } if (ch == LF) { state = State.header_field_start; break; } /* XXX allow spaces after digit? */ if (!isDigit(ch)) settings.RaiseOnError(this, "non digit in http minor", data, p_err); http_minor *= 10; http_minor += (int)ch - 0x30; if (http_minor > 999) settings.RaiseOnError(this, "ridiculous http minor", data, p_err); break; /* end of request line */ case State.req_line_almost_done: { if (ch != LF) settings.RaiseOnError(this, "missing LF after request line", data, p_err); state = State.header_field_start; break; } /******************* HTTP 1.1 *******************/ /******************* Header *******************/ case State.header_field_start: { if (ch == CR) { state = State.headers_almost_done; break; } if (ch == LF) { /* they might be just sending \n instead of \r\n so this would be * the second \n to denote the end of headers*/ state = State.headers_almost_done; if (!headers_almost_done(ch, settings, data, p_err)) return; break; } c = upper(ch); if (c == 0) { settings.RaiseOnError(this, "invalid char in header", data, p_err); }; header_field_mark = p; index = 0; state = State.header_field; switch (c) { case C: header_state = HState.C; break; case P: header_state = HState.matching_proxy_connection; break; case T: header_state = HState.matching_transfer_encoding; break; case U: header_state = HState.matching_upgrade; break; default: header_state = HState.general; break; } break; } case State.header_field: { c = UPCASE[ch]; if (0 != c) { switch (header_state) { case HState.general: break; case HState.C: index++; header_state = (O == c ? HState.CO : HState.general); break; case HState.CO: index++; header_state = (N == c ? HState.CON : HState.general); break; case HState.CON: index++; switch (c) { case N: header_state = HState.matching_connection; break; case T: header_state = HState.matching_content_length; break; default: header_state = HState.general; break; } break; /* connection */ case HState.matching_connection: index++; if (index > CONNECTION.Length || c != CONNECTION[index]) { header_state = HState.general; } else if (index == CONNECTION.Length-1) { header_state = HState.connection; } break; /* proxy-connection */ case HState.matching_proxy_connection: index++; if (index > PROXY_CONNECTION.Length || c != PROXY_CONNECTION[index]) { header_state = HState.general; } else if (index == PROXY_CONNECTION.Length-1) { header_state = HState.connection; } break; /* content-length */ case HState.matching_content_length: index++; if (index > CONTENT_LENGTH.Length || c != CONTENT_LENGTH[index]) { header_state = HState.general; } else if (index == CONTENT_LENGTH.Length-1) { header_state = HState.content_length; } break; /* transfer-encoding */ case HState.matching_transfer_encoding: index++; if (index > TRANSFER_ENCODING.Length || c != TRANSFER_ENCODING[index]) { header_state = HState.general; } else if (index == TRANSFER_ENCODING.Length-1) { header_state = HState.transfer_encoding; } break; /* upgrade */ case HState.matching_upgrade: index++; if (index > UPGRADE.Length || c != UPGRADE[index]) { header_state = HState.general; } else if (index == UPGRADE.Length-1) { header_state = HState.upgrade; } break; case HState.connection: case HState.content_length: case HState.transfer_encoding: case HState. upgrade: if (SPACE != ch) header_state = HState.general; break; default: settings.RaiseOnError(this, "Unknown Header State", data, p_err); break; } // switch: header_state break; } // 0 != c if (COLON == ch) { settings.RaiseOnHeaderField(this, data, header_field_mark, p-header_field_mark); header_field_mark = -1; state = State.header_value_start; break; } if (CR == ch) { state = State.header_almost_done; settings.RaiseOnHeaderField(this, data, header_field_mark, p-header_field_mark); header_field_mark = -1; break; } if (ch == LF) { settings.RaiseOnHeaderField(this, data, header_field_mark, p-header_field_mark); header_field_mark = -1; state = State.header_field_start; break; } settings.RaiseOnError(this, "invalid header field", data, p_err); break; } case State.header_value_start: { if (SPACE == ch) break; header_value_mark = p; state = State.header_value; index = 0; c = UPCASE[ch]; if (c == 0) { if (CR == ch) { settings.RaiseOnHeaderValue(this, data, header_value_mark, p-header_value_mark); header_value_mark = -1; header_state = HState.general; state = State.header_almost_done; break; } if (LF == ch) { settings.RaiseOnHeaderValue(this, data, header_value_mark, p-header_value_mark); header_value_mark = -1; state = State.header_field_start; break; } header_state = HState.general; break; } switch (header_state) { case HState.upgrade: flags |= F_UPGRADE; header_state = HState.general; break; case HState.transfer_encoding: /* looking for 'Transfer-Encoding: chunked' */ if (C == c) { header_state = HState.matching_transfer_encoding_chunked; } else { header_state = HState.general; } break; case HState.content_length: if (!isDigit(ch)) { settings.RaiseOnError(this, "Content-Length not numeric", data, p_err); } content_length = (int)ch - 0x30; break; case HState.connection: /* looking for 'Connection: keep-alive' */ if (K == c) { header_state = HState.matching_connection_keep_alive; /* looking for 'Connection: close' */ } else if (C == c) { header_state = HState.matching_connection_close; } else { header_state = HState.general; } break; default: header_state = HState.general; break; } break; } // header value start case State.header_value: { c = UPCASE[ch]; if (c == 0) { if (CR == ch) { settings.RaiseOnHeaderValue(this, data, header_value_mark, p-header_value_mark); header_value_mark = -1; state = State.header_almost_done; break; } if (LF == ch) { settings.RaiseOnHeaderValue(this, data, header_value_mark, p-header_value_mark); header_value_mark = -1; if (!header_almost_done(ch)) { settings.RaiseOnError(this,"incorrect header ending, expection LF", data, p_err); } break; } break; } switch (header_state) { case HState.general: break; case HState.connection: case HState.transfer_encoding: settings.RaiseOnError(this, "Shouldn't be here", data, p_err); break; case HState.content_length: if (ch == ' ') break; if (!isDigit(ch)) settings.RaiseOnError(this, "Content-Length not numeric", data, p_err); content_length *= 10; content_length += (int)ch - 0x30; break; /* Transfer-Encoding: chunked */ case HState.matching_transfer_encoding_chunked: index++; if (index > CHUNKED.Length || c != CHUNKED[index]) { header_state = HState.general; } else if (index == CHUNKED.Length-1) { header_state = HState.transfer_encoding_chunked; } break; /* looking for 'Connection: keep-alive' */ case HState.matching_connection_keep_alive: index++; if (index > KEEP_ALIVE.Length || c != KEEP_ALIVE[index]) { header_state = HState.general; } else if (index == KEEP_ALIVE.Length-1) { header_state = HState.connection_keep_alive; } break; /* looking for 'Connection: close' */ case HState.matching_connection_close: index++; if (index > CLOSE.Length || c != CLOSE[index]) { header_state = HState.general; } else if (index == CLOSE.Length-1) { header_state = HState.connection_close; } break; case HState.transfer_encoding_chunked: case HState.connection_keep_alive: case HState.connection_close: if (SPACE != ch) header_state = HState.general; break; default: state = State.header_value; header_state = HState.general; break; } break; } // header_value case State.header_almost_done: if (!header_almost_done(ch)) settings.RaiseOnError(this,"incorrect header ending, expection LF", data, p_err); break; case State.headers_almost_done: if (!headers_almost_done(ch, settings, data, p_err)) return; break; /******************* Header *******************/ /******************* Body *******************/ case State.body_identity: to_read = min(pe, content_length); //TODO change to use buffer? if (to_read > 0) { settings.RaiseOnBody(this, data, p, to_read); data.Skip(to_read); content_length -= to_read; if (content_length == 0) { settings.RaiseOnMessageComplete(this); state = new_message(); } } break; case State.body_identity_eof: to_read = pe; // TODO change to use buffer ? if (to_read > 0) { settings.RaiseOnBody(this, data, p, to_read); data.Skip(to_read); } break; /******************* Body *******************/ /******************* Chunk *******************/ case State.chunk_size_start: if (0 == (flags & F_CHUNKED)) settings.RaiseOnError(this, "not chunked", data, p_err); c = UNHEX[ch]; if (c == -1) { settings.RaiseOnError(this, "invalid hex char in chunk content length", data, p_err); } content_length = c; state = State.chunk_size; break; case State.chunk_size: if (0 == (flags & F_CHUNKED)) settings.RaiseOnError(this, "not chunked", data, p_err); if (CR == ch) { state = State.chunk_size_almost_done; break; } c = UNHEX[ch]; if (c == -1) { if (SEMI == ch || SPACE == ch) { state = State.chunk_parameters; break; } settings.RaiseOnError(this, "invalid hex char in chunk content length", data, p_err); } content_length *= 16; content_length += c; break; case State.chunk_parameters: if (0 == (flags & F_CHUNKED)) settings.RaiseOnError(this, "not chunked", data, p_err); /* just ignore this shit. TODO check for overflow */ if (CR == ch) { state = State.chunk_size_almost_done; break; } break; case State.chunk_size_almost_done: if (0 == (flags & F_CHUNKED)) { settings.RaiseOnError(this, "not chunked", data, p_err); } if (strict && LF != ch) { settings.RaiseOnError(this, "expected LF at end of chunk size", data, p_err); } if (0 == content_length) { flags |= F_TRAILING; state = State.header_field_start; } else { state = State.chunk_data; } break; case State.chunk_data: { if (0 == (flags & F_CHUNKED)) { settings.RaiseOnError(this, "not chunked", data, p_err); } to_read = min(pe, content_length); if (to_read > 0) { settings.RaiseOnBody(this, data, p, to_read); data.Skip(to_read); } if (to_read == content_length) { state = State.chunk_data_almost_done; } content_length -= to_read; break; } case State.chunk_data_almost_done: if (0 == (flags & F_CHUNKED)) { settings.RaiseOnError(this, "not chunked", data, p_err); } if (strict && CR != ch) { settings.RaiseOnError(this, "chunk data terminated incorrectly, expected CR", data, p_err); } state = State.chunk_data_done; break; case State.chunk_data_done: if (0 == (flags & F_CHUNKED)) { settings.RaiseOnError(this, "not chunked", data, p_err); } if (strict && LF != ch) { settings.RaiseOnError(this, "chunk data terminated incorrectly, expected LF", data, p_err); } state = State.chunk_size_start; break; /******************* Chunk *******************/ default: settings.RaiseOnError(this, "unhandled state", data, p_err); break; } // switch } // while p = (int) data.Position; /* Reaching this point assumes that we only received part of a * message, inform the callbacks about the progress made so far*/ settings.RaiseOnHeaderField (this, data, header_field_mark, p-header_field_mark); settings.RaiseOnHeaderValue (this, data, header_value_mark, p-header_value_mark); settings.RaiseOnFragment (this, data, fragment_mark, p-fragment_mark); settings.RaiseOnQueryString (this, data, query_string_mark, p-query_string_mark); settings.RaiseOnPath (this, data, path_mark, p-path_mark); settings.RaiseOnUrl (this, data, url_mark, p-url_mark); } // execute /* If http_should_keep_alive() in the on_headers_complete or * on_message_complete callback returns true, then this will be should be * the last message on the connection. * If you are the server, respond with the "Connection: close" header. * If you are the client, close the connection. */ bool http_should_keep_alive() { if (http_major > 0 && http_minor > 0) { /* HTTP/1.1 */ if ( 0 != (flags & F_CONNECTION_CLOSE) ) { return false; } else { return true; } } else { /* HTTP/1.0 or earlier */ if ( 0 != (flags & F_CONNECTION_KEEP_ALIVE) ) { return true; } else { return false; } } } bool isDigit(int b) { if (b >= 0x30 && b <=0x39) { return true; } return false; } bool isAtoZ(int b) { byte c = lower(b); return (c>= 0x61 /*a*/ && c <= 0x7a /*z*/); } bool usual(int b) { //static const uint32_t usual[] = { // 0xffffdbfe, /* 1111 1111 1111 1111 1101 1011 1111 1110 */ // // /* ?>=< ;:98 7654 3210 /.-, +*)( '&%$ #"! */ // 0x7ffffff6, /* 0111 1111 1111 1111 1111 1111 1111 0110 */ // // /* _^]\ [ZYX WVUT SRQP ONML KJIH GFED CBA@ */ // 0xffffffff, /* 1111 1111 1111 1111 1111 1111 1111 1111 */ // // /* ~}| {zyx wvut srqp onml kjih gfed cba` */ // 0xffffffff, /* 1111 1111 1111 1111 1111 1111 1111 1111 */ // // 0xffffffff, /* 1111 1111 1111 1111 1111 1111 1111 1111 */ // 0xffffffff, /* 1111 1111 1111 1111 1111 1111 1111 1111 */ // 0xffffffff, /* 1111 1111 1111 1111 1111 1111 1111 1111 */ // 0xffffffff /* 1111 1111 1111 1111 1111 1111 1111 1111 */ //}; // //#define USUAL(c) (usual[c >> 5] & (1 << (c & 0x1f))) switch (b) { case NULL: case CR: case LF: case SPACE: case QMARK: case HASH: return false; } return true; } byte lower (int b) { return (byte)(b|0x20); } byte upper(int b) { char c = (char)(b); return (byte)Char.ToUpper (c); } HttpMethod start_req_method_assign(int c){ switch (c) { case C: return HttpMethod.HTTP_CONNECT; /* or COPY, CHECKOUT */ case D: return HttpMethod.HTTP_DELETE; case G: return HttpMethod.HTTP_GET; case H: return HttpMethod.HTTP_HEAD; case L: return HttpMethod.HTTP_LOCK; case M: return HttpMethod.HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE */ case O: return HttpMethod.HTTP_OPTIONS; case P: return HttpMethod.HTTP_POST; /* or PROPFIND, PROPPATH, PUT */ case R: return HttpMethod.HTTP_REPORT; case T: return HttpMethod.HTTP_TRACE; case U: return HttpMethod.HTTP_UNLOCK; } return HttpMethod.ERROR; // ugh. } bool header_almost_done(int ch) { if (strict && LF != ch) { return false; } state = State.header_field_start; // TODO java enums support some sort of bitflag mechanism !? switch (header_state) { case HState.connection_keep_alive: flags |= F_CONNECTION_KEEP_ALIVE; break; case HState.connection_close: flags |= F_CONNECTION_CLOSE; break; case HState.transfer_encoding_chunked: flags |= F_CHUNKED; break; default: break; } return true; } // Return true if we should continue processing bool headers_almost_done (int ch, ParserSettings settings, ByteBuffer data, int p_err) { if (strict && LF != ch) { settings.RaiseOnError (this, "header not properly completed", data, p_err); return false; } if (0 != (flags & F_TRAILING)) { /* End of a chunked request */ settings.RaiseOnHeadersComplete(this); settings.RaiseOnMessageComplete(this); state = new_message(); return true; } nread = 0; if (0 != (flags & F_UPGRADE) || HttpMethod.HTTP_CONNECT == method) upgrade = true; /* Here we call the headers_complete callback. This is somewhat * different than other callbacks because if the user returns 1, we * will interpret that as saying that this message has no body. This * is needed for the annoying case of recieving a response to a HEAD * request. */ /* (responses to HEAD request contain a CONTENT-LENGTH header * but no content) * * Consider what to do here: I don't like the idea of the callback * interface having a different contract in the case of HEAD * responses. The alternatives would be either to: * * a.) require the header_complete callback to implement a different * interface or * * b.) provide an overridden execute(bla, bla, bool * parsingHeader) implementation ... */ if (null != settings.OnHeadersComplete) { if (settings.RaiseOnHeadersComplete (this) == 1) flags |= F_SKIPBODY; } // Exit, the rest of the connect is in a different protocol. if (upgrade) { settings.RaiseOnMessageComplete(this); state = new_message (); return false; } if (0 != (flags & F_SKIPBODY)) { settings.RaiseOnMessageComplete(this); state = new_message(); } else if (0 != (flags & F_CHUNKED)) { /* chunked encoding - ignore Content-Length header */ state = State.chunk_size_start; } else { if (content_length == 0) { /* Content-Length header given but zero: Content-Length: 0\r\n */ settings.RaiseOnMessageComplete(this); state = new_message(); } else if (content_length > 0) { /* Content-Length header given and non-zero */ state = State.body_identity; } else { if (type == ParserType.HTTP_REQUEST || http_should_keep_alive()) { /* Assume content-length 0 - read the next */ settings.RaiseOnMessageComplete(this); state = new_message(); } else { /* Read body until EOF */ state = State.body_identity_eof; } } } return true; } // headers_almost_fone private static int min (int a, int b) { return a < b ? a : b; } /* probably not the best place to hide this ... */ public bool HTTP_PARSER_STRICT; State new_message() { if (HTTP_PARSER_STRICT){ return http_should_keep_alive() ? start_state() : State.dead; } else { return start_state(); } } State start_state() { return type == ParserType.HTTP_REQUEST ? State.start_req : State.start_res; } bool parsing_header(State state) { switch (state) { case State.chunk_size_start : case State.chunk_size : case State.chunk_size_almost_done : case State.chunk_parameters : case State.chunk_data : case State.chunk_data_almost_done : case State.chunk_data_done : case State.body_identity : case State.body_identity_eof : return false; } return (0==(flags & F_TRAILING)); } /* "Dial CONST for Constants" */ const int HTTP_MAX_HEADER_SIZE = 80 * 1024; const int F_CHUNKED = 1 << 0; const int F_CONNECTION_KEEP_ALIVE = 1 << 1; const int F_CONNECTION_CLOSE = 1 << 2; const int F_TRAILING = 1 << 3; const int F_UPGRADE = 1 << 4; const int F_SKIPBODY = 1 << 5; static readonly byte [] UPCASE = new byte [] { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x2d,0x00,0x2f, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37, 0x38,0x39,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57, 0x58,0x59,0x5a,0x00,0x00,0x00,0x00,0x5f, 0x00,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57, 0x58,0x59,0x5a,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, }; static readonly byte [] CONNECTION = new byte [] { 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x49, 0x4f, 0x4e, }; static readonly byte [] PROXY_CONNECTION = new byte [] { 0x50, 0x52, 0x4f, 0x58, 0x59, 0x2d, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x49, 0x4f, 0x4e, }; static readonly byte [] CONTENT_LENGTH = new byte [] { 0x43, 0x4f, 0x4e, 0x54, 0x45, 0x4e, 0x54, 0x2d, 0x4c, 0x45, 0x4e, 0x47, 0x54, 0x48, }; static readonly byte [] TRANSFER_ENCODING = new byte [] { 0x54, 0x52, 0x41, 0x4e, 0x53, 0x46, 0x45, 0x52, 0x2d, 0x45, 0x4e, 0x43, 0x4f, 0x44, 0x49, 0x4e, 0x47, }; static readonly byte [] UPGRADE = new byte [] { 0x55, 0x50, 0x47, 0x52, 0x41, 0x44, 0x45, }; static readonly byte [] CHUNKED = new byte [] { 0x43, 0x48, 0x55, 0x4e, 0x4b, 0x45, 0x44, }; static readonly byte [] KEEP_ALIVE = new byte [] { 0x4b, 0x45, 0x45, 0x50, 0x2d, 0x41, 0x4c, 0x49, 0x56, 0x45, }; static readonly byte [] CLOSE = new byte [] { 0x43, 0x4c, 0x4f, 0x53, 0x45, }; static readonly int [] UNHEX = new int [] { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; public const byte A = 0x41; public const byte B = 0x42; public const byte C = 0x43; public const byte D = 0x44; public const byte E = 0x45; public const byte F = 0x46; public const byte G = 0x47; public const byte H = 0x48; public const byte I = 0x49; public const byte J = 0x4a; public const byte K = 0x4b; public const byte L = 0x4c; public const byte M = 0x4d; public const byte N = 0x4e; public const byte O = 0x4f; public const byte P = 0x50; public const byte Q = 0x51; public const byte R = 0x52; public const byte S = 0x53; public const byte T = 0x54; public const byte U = 0x55; public const byte V = 0x56; public const byte W = 0x57; public const byte X = 0x58; public const byte Y = 0x59; public const byte Z = 0x5a; public const byte CR = 0x0d; public const byte LF = 0x0a; public const byte DOT = 0x2e; public const byte SPACE = 0x20; public const byte SEMI = 0x3b; public const byte COLON = 0x3a; public const byte HASH = 0x23; public const byte QMARK = 0x3f; public const byte SLASH = 0x2f; public const byte DASH = 0x2d; public const byte NULL = 0x00; } }
2678aea007a2705921b3c15673b1e41584a43e1b
C#
shopathome-engineering/message-queue
/Exceptions/MessageSerializationFailureException.cs
2.984375
3
using System; namespace ShopAtHome.MessageQueue.Exceptions { /// <summary> /// Indicates a failure in serializing or de-serializing a Message object /// </summary> public class MessageSerializationFailureException : Exception { /// <summary> /// Constructs a new MessageSerializationFailureException with the raw contents of the message that caused the failure /// </summary> /// <param name="rawBody"></param> /// <param name="innerException"></param> public MessageSerializationFailureException(byte[] rawBody, Exception innerException) : base(innerException.Message, innerException) { RawMessageBody = rawBody; } /// <summary> /// The raw binary contents of the message that caused the failure /// </summary> public byte[] RawMessageBody { get; } } }
64c44eaa51c4ac54cfe7072bc3933dfac218daf6
C#
ErickTejaxun/Usac-Forms
/Proyecto1/UsacForms/xForms/xForms/Form1.cs
2.6875
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 xForms.Clases; namespace xForms { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } public void metodo() { List<Objeto> lista = new List<Objeto>(); lista.Add(new Objeto()); lista.Add(new Objeto()); lista.Add(new Objeto()); lista.Add(new Objeto()); List<Objeto> lista2 = new List<Objeto>(); foreach (Objeto ob in lista) { lista2.Add(ob.Clonar()); } foreach (Objeto ob2 in lista2) { ob2.nombre = "erick tejaxun"; ob2.edad = 20; ob2.email = "jjj.@gmail.com"; } foreach (Objeto ob in lista) { Console.WriteLine(ob.nombre + "\t" + ob.edad + "\t" + ob.email); } foreach (Objeto ob in lista2) { Console.WriteLine(ob.nombre + "\t" + ob.edad + "\t" + ob.email); } } private void button1_Click_1(object sender, EventArgs e) { } } }
3046f315322987c0481ad50827302ce18126e3df
C#
navneetkaurbedi6/SwarajIP
/SwarajInsurancePortalDA/Common/CollectionHelper.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Text; using System.Reflection; using System.IO; using System.Web; namespace SwarajInsurancePortalDA.Common { public class CollectionHelper { /// <summary> /// Converts datatable to genric class /// </summary> /// <typeparam name="T"></typeparam> /// <param name="datatable"></param> /// <returns></returns> public static List<T> ConvertTo<T>(DataTable datatable) where T : new() { List<T> Temp = new List<T>(); try { List<string> columnsNames = new List<string>(); foreach (DataColumn DataColumn in datatable.Columns) columnsNames.Add(DataColumn.ColumnName); Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames)); return Temp; } catch { return Temp; } } public static T getObject<T>(DataRow row, List<string> columnsName) where T : new() { T obj = new T(); try { string columnname = ""; string value = ""; PropertyInfo[] Properties; Properties = typeof(T).GetProperties(); foreach (PropertyInfo objProperty in Properties) { columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower()); if (!string.IsNullOrEmpty(columnname)) { value = row[columnname].ToString(); if (!string.IsNullOrEmpty(value)) { if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null) { value = row[columnname].ToString().Replace("$", "").Replace(",", ""); objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null); } else { value = row[columnname].ToString().Replace("%", ""); if (objProperty.PropertyType == Type.GetType("System.Boolean")) // objProperty.SetValue(obj, Convert.ChangeType(Convert.ToBoolean(Convert.ToInt32(value)), Type.GetType(objProperty.PropertyType.ToString())), null); objProperty.SetValue(obj, Convert.ChangeType(Convert.ToBoolean(value), Type.GetType(objProperty.PropertyType.ToString())), null); else if (objProperty.CanWrite) objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null); } } } } } catch { //return obj; } return obj; } /// <summary> /// Convert Genric Class to DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection"></param> /// <returns></returns> public static DataTable ToDataTable<T>(IEnumerable<T> collection) { DataTable newDataTable = new DataTable(); Type impliedType = typeof(T); PropertyInfo[] _propInfo = impliedType.GetProperties(); foreach (PropertyInfo pi in _propInfo) newDataTable.Columns.Add(pi.Name, Nullable.GetUnderlyingType( pi.PropertyType) ?? pi.PropertyType); foreach (T item in collection) { DataRow newDataRow = newDataTable.NewRow(); newDataRow.BeginEdit(); foreach (PropertyInfo pi in _propInfo) { object piValue = pi.GetValue(item, null); newDataRow[pi.Name] = piValue == null ? DBNull.Value : piValue; } newDataRow.EndEdit(); newDataTable.Rows.Add(newDataRow); } return newDataTable; } /// <summary> /// To get the single object from datatable having single record /// </summary> /// <typeparam name="T"></typeparam> /// <param name="datatable"></param> /// <returns></returns> public static T ConvertToObject<T>(DataTable datatable) where T : new() { List<T> Temp = new List<T>(); try { List<string> columnsNames = new List<string>(); foreach (DataColumn DataColumn in datatable.Columns) columnsNames.Add(DataColumn.ColumnName); Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames)); return Temp.FirstOrDefault(); } catch { return Temp.FirstOrDefault(); } } /// <summary> /// Exception Handling /// </summary> /// <param name="ex"></param> public static void ExcepLog(Exception ex) { if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/LogInfo/"))) { System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/LogInfo/")); } string strPath = HttpContext.Current.Server.MapPath("~/LogInfo/info.txt"); if (!File.Exists(strPath)) { File.Create(strPath).Dispose(); } using (StreamWriter sw = File.AppendText(strPath)) { sw.WriteLine("=====Error Log =="); sw.WriteLine("===Start===" + DateTime.Now); sw.WriteLine("Error Message : " + ex.Message); sw.WriteLine("Stack Trace : " + ex.StackTrace); sw.WriteLine("===End=== " + DateTime.Now); sw.WriteLine(""); sw.WriteLine(""); } } } }
874f9af0fd034a3fcae1ea78b45ad5eec2ef64e0
C#
leonmeijer/mobile
/Phoebe/Data/SqlExtensions.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Toggl.Phoebe.Data.DataObjects; namespace Toggl.Phoebe.Data { /// <summary> /// This extension class contains everything that deals with raw SQL. /// </summary> public static class SqlExtensions { public static long? GetRemoteId<T> (this IDataStoreContext ctx, Guid id) where T : CommonData { var tbl = ctx.Connection.GetMapping<T> ().TableName; var q = String.Concat ("SELECT RemoteId FROM ", tbl, " WHERE Id=?"); try { var remoteId = ctx.Connection.ExecuteScalar<long> (q, id); if (remoteId == 0) { // Relation doesn't exist or RemoteId is set to zero return null; } return remoteId; } catch (NullReferenceException) { // This happens when the RemoteId of the relation is set to null return null; } } public static Guid GetLocalId<T> (this IDataStoreContext ctx, long remoteId) where T : CommonData { var tbl = ctx.Connection.GetMapping<T> ().TableName; var q = String.Concat ("SELECT Id FROM ", tbl, " WHERE RemoteId=?"); return ctx.Connection.ExecuteScalar<Guid> (q, remoteId); } public static List<string> GetTimeEntryTagNames (this IDataStoreContext ctx, Guid timeEntryId) { var tagTbl = ctx.Connection.GetMapping<TagData> ().TableName; var timeEntryTagTbl = ctx.Connection.GetMapping<TimeEntryTagData> ().TableName; var q = String.Concat ( "SELECT t.Name AS Value FROM ", tagTbl, " AS t ", "LEFT JOIN ", timeEntryTagTbl, " AS tet ON tet.TagId=t.Id ", "WHERE tet.DeletedAt IS NULL AND tet.TimeEntryId=?"); var res = ctx.Connection.Query<ColumnRow<string>> (q, timeEntryId); return res.Select (v => v.Value).ToList (); } public static Guid GetTagIdFromName (this IDataStoreContext ctx, Guid workspaceId, string name) { var con = ctx.Connection; var tagTbl = con.GetMapping (typeof (TagData)).TableName; var q = String.Concat ("SELECT Id AS Value FROM ", tagTbl, " WHERE WorkspaceId=? AND Name=?"); return con.ExecuteScalar<Guid> (q, workspaceId, name); } public static int GetProjectColorFromName (this IDataStoreContext ctx, Guid workspaceId, string name) { var con = ctx.Connection; var tagTbl = con.GetMapping (typeof (ProjectData)).TableName; var q = String.Concat ("SELECT Color AS Value FROM ", tagTbl, " WHERE WorkspaceId=? AND Name=?"); return con.ExecuteScalar<int> (q, workspaceId, name); } public async static Task<List<ProjectData>> GetUserAccessibleProjects (this IDataStore ds, Guid userId) { var projectTbl = await ds.GetTableNameAsync<ProjectData>(); var projectUserTbl = await ds.GetTableNameAsync<ProjectUserData>(); var q = String.Concat ( "SELECT p.* FROM ", projectTbl, " AS p ", "LEFT JOIN ", projectUserTbl, " AS pu ON pu.ProjectId = p.Id AND pu.UserId=? ", "WHERE p.DeletedAt IS NULL AND p.IsActive != 0 AND ", "(p.IsPrivate == 0 OR pu.UserId IS NOT NULL)", "ORDER BY p.Name "); return await ds.QueryAsync<ProjectData> (q, userId); } public async static Task<List<ProjectData>> GetMostUsedProjects (this IDataStore ds, Guid userId) { var timeEntryTbl = await ds.GetTableNameAsync<TimeEntryData>(); var projectTbl = await ds.GetTableNameAsync<ProjectData>(); var q = String.Concat ( "SELECT project.* ", "FROM ", timeEntryTbl, " AS entry INNER JOIN ", projectTbl, " AS project ON entry.ProjectId = project.Id ", "WHERE entry.ProjectId != '" + Guid.Empty + "'", "AND project.WorkspaceId != '" + Guid.Empty + "'", "AND project.WorkspaceId IS NOT NULL ", "GROUP BY entry.ProjectId ORDER BY COUNT(*) DESC" ); return await ds.QueryAsync<ProjectData> (q, userId); } public async static Task<long> CountUserAccessibleProjects (this IDataStore ds, Guid userId) { var projectTbl = await ds.GetTableNameAsync<ProjectData>(); var projectUserTbl = await ds.GetTableNameAsync<ProjectUserData>(); var q = String.Concat ( "SELECT COUNT(*) FROM ", projectTbl, " AS p ", "LEFT JOIN ", projectUserTbl, " AS pu ON pu.ProjectId = p.Id AND pu.UserId=? ", "WHERE p.DeletedAt IS NULL AND p.IsActive != 0 AND ", "(p.IsPrivate == 0 OR pu.UserId IS NOT NULL)"); return await ds.ExecuteScalarAsync<long> (q, userId); } public async static Task<List<TagData>> GetTimeEntryTags (this IDataStore ds, Guid timeEntryId) { /* TODO: Review why this query is not working. var tagTbl = await ds.GetTableNameAsync<TagData>(); var timeEntryTagTbl = await ds.GetTableNameAsync<TimeEntryTagData>(); var q = string.Concat ( "SELECT t.* FROM ", tagTbl, " AS t ", "INNER JOIN ", timeEntryTagTbl, " AS tet ON tet.TagId = t.Id ", "WHERE t.DeletedAt IS NULL AND tet.DeletedAt IS NULL ", "ORDER BY t.Name ", "AND tet.TimeEntryId=?"); */ var tags = await ds.Table<TagData> ().ToListAsync (); var tagRelations = await ds.Table<TimeEntryTagData> ().Where ((arg) => arg.TimeEntryId == timeEntryId).ToListAsync (); var tagList = tagRelations.Select (r => tags.FirstOrDefault (tag => tag.Id == r.TagId)); return tagList.ToList (); } public static Task ResetAllModificationTimes (this IDataStore ds) { return ds.ExecuteInTransactionAsync (ctx => { foreach (var type in SqliteDataStore.DiscoverDataObjectTypes()) { var con = ctx.Connection; var tbl = con.GetMapping (type).TableName; if (type.IsSubclassOf (typeof (CommonData))) { var q = String.Concat ( "UPDATE ", tbl, " SET ModifiedAt = ? ", "WHERE RemoteId IS NOT NULL AND DeletedAt IS NULL ", "AND (IsDirty = 0 OR RemoteRejected = 1)"); ctx.Connection.Execute (q, DateTime.MinValue); } } }); } public static int PurgeDatedTimeCorrections (this IDataStoreContext ctx, DateTime time) { var tbl = ctx.Connection.GetMapping<TimeCorrectionData> ().TableName; var q = String.Concat ("DELETE FROM ", tbl, " WHERE MeasuredAt < ?"); return ctx.Connection.Execute (q, time); } public async static Task<DateTime> GetDatesByDays (this IDataStore ds, DateTime initialDate, int daysToLoad) { var result = DateTime.MinValue; var teTable = await ds.GetTableNameAsync<TimeEntryData>(); var q = String.Concat ( "SELECT t.* FROM ", teTable, " AS t ", "WHERE t.DeletedAt IS NULL AND t.State > 0 AND t.StartTime < ? ", "GROUP BY t.StartTime"); var entries = await ds.QueryAsync<TimeEntryData> (q, initialDate); if (entries.Count > 0) { var dates = entries.Select (t => t.StartTime.Date).GroupBy (x => x.Date).Take (daysToLoad); result = dates.LastOrDefault ().Key; } return result; } private class ColumnRow<T> { public T Value { get; set; } } } }
e098fb84ead2f9b23c9513329c90c401174dc296
C#
sholev/SoftUni
/C#-WebDeveloper-3.0/C#-OOP-Basics-June-2016/Exercises/DefiningClasses/Person/Startup/Startup.cs
3.609375
4
namespace Person { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; class Startup { static void Main(string[] args) { ThirdProblemTest(); } private static void ThirdProblemTest() { var count = int.Parse(Console.ReadLine()); var persons = new List<Person>(); for (int i = 0; i < count; i++) { var parameters = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var name = parameters[0]; var age = int.Parse(parameters[1]); persons.Add(new Person(name, age)); } persons.Where(p => p.age > 30) .OrderBy(p => p.name) .ToList() .ForEach(Console.WriteLine); } private static void SecondProblemTest() { Type personType = typeof(Person); ConstructorInfo emptyCtor = personType.GetConstructor(new Type[] { }); ConstructorInfo ageCtor = personType.GetConstructor(new[] { typeof(int) }); ConstructorInfo nameAgeCtor = personType.GetConstructor(new[] { typeof(string), typeof(int) }); bool swapped = false; if (nameAgeCtor == null) { nameAgeCtor = personType.GetConstructor(new[] { typeof(int), typeof(string) }); swapped = true; } string name = Console.ReadLine(); int age = int.Parse(Console.ReadLine()); Person basePerson = (Person)emptyCtor.Invoke(new object[] { }); Person personWithAge = (Person)ageCtor.Invoke(new object[] { age }); Person personWithAgeAndName = swapped ? (Person)nameAgeCtor.Invoke(new object[] { age, name }) : (Person)nameAgeCtor.Invoke(new object[] { name, age }); Console.WriteLine($"{basePerson.name} {basePerson.age}"); Console.WriteLine($"{personWithAge.name} {personWithAge.age}"); Console.WriteLine($"{personWithAgeAndName.name} {personWithAgeAndName.age}"); } private static void FirstProblemTest() { Type personType = typeof(Person); FieldInfo[] fields = personType.GetFields(BindingFlags.Public | BindingFlags.Instance); Console.WriteLine(fields.Length); } } }
852363653e57864e6c57948af1f20619678a5554
C#
Yongfou/jo
/SocketServeur/Serveur/Serveur.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ServeurData; using System.Net.Sockets; using System.IO; using System.Threading; using System.Net; namespace Serveur { class Serveur { const string FICHIER = "..\\..\\..\\ListeClients.txt"; static Socket CaptureSocket; public static List<ClientData> _client; /// <summary> /// Auteur: Sébastien Paquet /// Description: Démare le serveur. /// </summary> /// <param name="args"></param> static void Main(string[] args) { StreamWriter EListClient = new StreamWriter(FICHIER); EListClient.WriteLine("",false); EListClient.Close(); Console.WriteLine("Startint serveur on " + Packet.PrendIP()); CaptureSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _client = new List<ClientData>(); IPEndPoint ip = new IPEndPoint(IPAddress.Parse(Packet.PrendIP()), 4242); CaptureSocket.Bind(ip); Thread capteThread = new Thread(CapteThread); capteThread.Start(); Thread pingpongThread = new Thread(new ThreadStart(CheckIfStillConnected)); pingpongThread.Start(); } // capte les clients qui essayent de se connecter. static void CapteThread() { for (;;) { CaptureSocket.Listen(0); _client.Add(new ClientData(CaptureSocket.Accept())); } } // recoit les information de chauqe client. public static void Data_Entrant(object cSocket) { Socket clientSocket = (Socket)cSocket; byte[] byBuffer; int iBytes; for (;;) { Thread.Sleep(20); try { byBuffer = new byte[clientSocket.SendBufferSize]; iBytes = clientSocket.Receive(byBuffer); if (iBytes > 0) { Packet packet = new Packet(byBuffer); DataAssignation(packet); } } catch (SocketException ex) { Console.WriteLine(" client disconnecter"); for (int i = 0; i < _client.Count; i++) { if(clientSocket.Connected == false) ((Socket)_client[i].clientSocket).Close(); _client.Remove(_client[i]); i--; } } //clientSocket.(); //foreach (ClientData cd in _client) //while(true) //{ // if (cSocket == cd.clientSocket) // //cd.clientThread.Join(); // _client.Remove(cd); // clientSocket.Close(); // //goto B; // return; //} if (_client.Count == 0) { Environment.Exit(0); } //CaptureSocket.Close(); } } //data assignation. public static void DataAssignation (Packet p) { switch (p.packetType) { case PacketType.Chat: foreach (ClientData c in _client) { c.clientSocket.Send(p.Tobytes()); } break; } } public static void CheckIfStillConnected() { /* Etant donné que la propriété .Connected d'une socket n'est pas * mise à jour lors de la déconnexion d'un client sans que l'on ait * prélablement essayé de lire ou d'écrire sur cette socket, cette méthode * parvient à déterminer si une socket cliente s'est déconnectée grce à la méthode * poll. On effectue un poll en lecture sur la socket, si le poll retourne vrai et que * le nombre de bytes disponible est 0, il s'agit d'une connexion terminée*/ while (true) { for (int i = 0; i < _client.Count; i++) { if (((Socket)_client[i].clientSocket).Poll(10, SelectMode.SelectRead) && ((Socket)_client[i].clientSocket).Available == 0) { Console.WriteLine("Client " + ((Socket)_client[i].clientSocket).GetHashCode() + " déconnecté"); ((Socket)_client[i].clientSocket).Close(); _client.Remove(_client[i]); i--; } } Thread.Sleep(1); } } } class ClientData { public Socket clientSocket; public Thread clientThread;// public string id; public ClientData( Socket clientSocket) { this.clientSocket = clientSocket; id = Guid.NewGuid().ToString(); clientThread = new Thread(Serveur.Data_Entrant); clientThread.Start(clientSocket); EnvoieRegistrationPacket(); } public void EnvoieRegistrationPacket() { Packet p = new Packet(PacketType.Registration, "serveur",""); p.Gdata.Add(id); clientSocket.Send(p.Tobytes()); } } }
d60484173c73447c30a258a573784e194347ba44
C#
kinnejs/Komodo_DevTeams
/DevTeamsProject/DevTeam.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DevTeamsProject { public enum TeamNam { Alpha = 1, Beta, Gamma } public class DevTeam { //try instead of having separate name and Id for developer in two different places, keep it in the developer class only. And create a property that calls a List<Developer> as the reference type instead. public List<Developer> ListofDevelopers{ get; set; } public string TeamName { get; set; } public bool License { get; set; } public DevTeam() { } public DevTeam(bool license, string teamName) { License = license; TeamName = teamName; } } }
02efe8e069651111d1eb824bd7ce8201fea496a6
C#
chrlemay/praktijksplitsing
/SyntraWestCSharpExercises/BuildingBlock3_Selectie/Opdracht03_07Portkosten.cs
3.125
3
using System; namespace SyntraWestCSharpExercises.BuildingBlock3_Selectie { public class Opdracht03_07Portkosten : ExerciseBase { public override void RunExercise() { string binnenBelgie, genormaliseerd; float gewicht, bedrag; Console.WriteLine("Versturen binnen België (y/n)"); binnenBelgie = Console.ReadLine(); Console.WriteLine("Genormaliseerd (y/n)"); genormaliseerd = Console.ReadLine(); Console.WriteLine("Hoeveel weegt je pakje:"); gewicht = float.Parse(Console.ReadLine()); if(binnenBelgie == "y") { if(genormaliseerd == "y") { if(gewicht > 50) { bedrag = -1; } else { bedrag = .7f; } } else { if(gewicht <= 100) { bedrag = 1.4f; } else if(gewicht <= 350) { bedrag = 2.1f; } else if(gewicht <= 1000) { bedrag = 3.5f; } else if(gewicht <=2000) { bedrag = 4.9f; } else { bedrag = -1; } } } else { if (genormaliseerd == "y") { if (gewicht > 50) { bedrag = -1; } else { bedrag = 1.07f; } } else { if (gewicht <= 100) { bedrag = 3.21f; } else if (gewicht <= 350) { bedrag = 6.42f; } else if (gewicht <= 1000) { bedrag = 10.7f; } else if (gewicht <= 2000) { bedrag = 21.4f; } else { bedrag = -1; } } } Console.WriteLine($"Binnen België {(binnenBelgie == "y" ? "Ja" : "Nee")}"); Console.WriteLine($"Genormaliseerd {(genormaliseerd == "y" ? "Ja" : "Nee")}"); Console.WriteLine($"Gewicht {gewicht}"); Console.WriteLine($"te betalen: {bedrag}"); } } }
2826e5eb3cc99e001899a9ed1a8150bdcd1c35e4
C#
j-ronnas/UnstableEcosystems
/Assets/SoundManager.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SoundManager : MonoBehaviour { AudioSource source; public static SoundManager instance; private void Awake() { instance = this; source = GetComponent<AudioSource>(); } public void SetSound(bool b) { source.mute = !b; } public void PlayPop() { if (!source.isPlaying) { source.Play(); } } }
81879af5b2a1a7152add24cf3adce441ba855088
C#
piekstra/MiscProjects
/C#/HackerRank/BalancedBrackets/ctci-balanced-brackets.cs
3.09375
3
using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Text; using System; class Solution { static void Main(string[] args) { int t = Convert.ToInt32(Console.ReadLine()); for (int tItr = 0; tItr < t; tItr++) { string expression = Console.ReadLine(); var bracketStack = new Stack<char>(); var balanced = true; foreach (var c in expression) { if (c.Equals('{') || c.Equals('(') || c.Equals('[')) { bracketStack.Push(c); } else if (bracketStack.Count == 0) { balanced = false; break; } else { if (c.Equals('}') && !bracketStack.Pop().Equals('{') || c.Equals(')') && !bracketStack.Pop().Equals('(') || c.Equals(']') && !bracketStack.Pop().Equals('[')) { balanced = false; break; } } } // Any leftovers means it's not balanced if (bracketStack.Count > 0) { balanced = false; } Console.WriteLine(balanced ? "YES" : "NO"); } } }
fba9ded90a8f0c2e3f128b285fff270dad81992d
C#
OsvaldoJ/BeetleX
/samples/Echo.Server/Program.cs
2.609375
3
using BeetleX; using BeetleX.EventArgs; using System; namespace Echo.Server { class Program : ServerHandlerBase { private static IServer server; public static void Main(string[] args) { server = SocketFactory.CreateTcpServer<Program>(); //server.Options.DefaultListen.CertificateFile = "text.pfx"; //server.Options.DefaultListen.SSL = true; //server.Options.DefaultListen.CertificatePassword = "123456"; server.Open(); Console.Write(server); Console.Read(); } public override void SessionReceive(IServer server, SessionReceiveEventArgs e) { string name = e.Stream.ToPipeStream().ReadLine(); Console.WriteLine(name); e.Session.Stream.ToPipeStream().WriteLine("hello " + name); e.Session.Stream.Flush(); base.SessionReceive(server, e); } } }
def8b0c34301cb93580dbcf0535aee179cf38856
C#
teodorro/Evolution1
/TestModel2/TestUpgrade/TestUpgradePoisonous.cs
2.578125
3
using System.Collections.Generic; using System.Linq; using Model; using Model.Upgrades; using Xunit; namespace TestModel.TestUpgrade { public class TestUpgradePoisonous { private IAnimal _victim; private void OnVictimChoose(object sender, VictimChooseEventArgs args) { if (AttackPossibilityChecker.Instance.CanAttack(args.Fight.Attacker, _victim)) args.Fight.Start(_victim); } [Fact] public void TestPoisonousSimple() { GameConstructor.Instance.ArrangeTwoAnimals( out var game, out var player1, new List<UpgradeSingle>() { new UpgradeCarnivorous() }, out var player2, new List<UpgradeSingle>() { new UpgradePoisonous() }); _victim = player2.Animals.First(); game.VictimChoose += OnVictimChoose; (player1.Animals.First().Upgrades.First(x => x.UpgradeType == UpgradeType.Carnivorous) as UpgradeCarnivorous).Use(); var phaseEx = new PhaseExtinction(new List<IPlayer>(){player1, player2}); phaseEx.StartExtinct(); Assert.Empty(player1.Animals); } [Fact] public void TestPoisonousNotDie() { GameConstructor.Instance.ArrangeTwoAnimals( out var game, out var player1, new List<UpgradeSingle>() , out var player2, new List<UpgradeSingle>() { new UpgradePoisonous() }); player1.TryFeedAnimalEvent += (sender, args) => args.Player.Feed(args.Animal); player2.TryFeedAnimalEvent += (sender, args) => args.Player.Feed(args.Animal); player1.TryFeed(player1.Animals.First()); player2.TryFeed(player2.Animals.First()); var phaseEx = new PhaseExtinction(new List<IPlayer>() { player1, player2 }); phaseEx.StartExtinct(); Assert.Single(player1.Animals); Assert.Single(player1.Animals); } } }
cddf431b45b5b921cbf7d3504cfc770c1fd0f539
C#
elinaach/assignments
/Branching/assignment2.cs
3.71875
4
using System; public class Branching { public static void Main(string[] args) { int dayNumber; Console.WriteLine("Please enter the number of the day:"); if (!Int32.TryParse(Console.ReadLine(), out dayNumber) || dayNumber < 1 || dayNumber > 7) { Console.WriteLine("Input is incorrect!"); return; } switch (dayNumber) { case 1: Console.WriteLine("It is a working day"); break; case 2: Console.WriteLine("It is a working day"); break; case 3: Console.WriteLine("It is a working day"); break; case 4: Console.WriteLine("It is a working day"); break; case 5: Console.WriteLine("It is a working day"); break; case 6: Console.WriteLine("It is holiday"); break; case 7: Console.WriteLine("It is holiday"); break; default: Console.WriteLine("Input is incorrect!!"); break; } } }
0f180ea08c8188b54dd2579d77f3bb8754fe397b
C#
mghall25/CSharp-Course-Practice-Projects
/ChallengeSimpleDarts/ChallengeSimpleDarts/Score.cs
3
3
using Darts; namespace ChallengeSimpleDarts { public static class Score { public static int CalcDartThrow(Dart dart) { int throwScore = dart.ThrowScore; // calc non-bullseye if (throwScore != 0) { if (dart.ThrowInRing == "inner") throwScore *= 3; else if (dart.ThrowInRing == "outer") throwScore *= 2; } else { //calc bullseye if (dart.ThrowInRing == "inner") throwScore = 50; else throwScore = 25; } return throwScore; } } }
9d735e60871602e841928905c1833db2416105b9
C#
debop/NFramework
/test/NFramework.Test/Validations/ValidatorToolFixture.cs
2.515625
3
using System; using NUnit.Framework; using SharpTestsEx; namespace NSoft.NFramework.Validations { [Microsoft.Silverlight.Testing.Tag("Validations")] [TestFixture] public class ValidatorToolFixture { [Test] public void GetValidatorTest() { var validator = ValidatorTool.GetValidator(typeof(Customer)); validator.Should().Not.Be.Null(); validator = ValidatorTool.GetValidator(typeof(User)); validator.Should().Not.Be.Null(); } [Test] public void GetValidatorOfTest() { var customer = new Customer(); var validator = ValidatorTool.GetValidatorOf(customer); validator.Should().Not.Be.Null(); var user = new User(); validator = ValidatorTool.GetValidatorOf(user); validator.Should().Not.Be.Null(); } [Test] public void CustomerValidatorTest() { var customer = new Customer() { Name = "배성혁", Company = "리얼웹", Discount = 12.5m, ZipCode = "135-010" }; var result = ValidatorTool.Validate(customer); result.IsValid.Should().Be.True(); result.Errors.Count.Should().Be(0); customer = new Customer() { Name = "", Company = "", Discount = 12.5m, ZipCode = "" }; result = ValidatorTool.Validate(customer); result.IsValid.Should().Be.False(); result.Errors.Count.Should().Be.GreaterThan(0); foreach(var failure in result.Errors) { Console.WriteLine(failure); } } [Test] public void UserValidatorTest() { var user = new User() { Id = "debop", Password = "123456abc1234", Name = "배성혁", LastAccessTime = DateTime.Today }; var result = ValidatorTool.Validate(user); result.IsValid.Should().Be.True(); result.Errors.Count.Should().Be(0); foreach(var failure in result.Errors) { Console.WriteLine(failure); } user = new User() { Id = "debop", Password = "123", Name = "배성혁", LastAccessTime = DateTime.Today.AddYears(1) }; result = ValidatorTool.Validate(user); result.IsValid.Should().Be.False(); result.Errors.Count.Should().Be.GreaterThan(0); foreach(var failure in result.Errors) { Console.WriteLine(failure); } } } }
869f0b0051d81fe913c9b2208aa2ea720f953fd9
C#
parzital/CSharp-4-Basic-Apps
/(Maths Game) Matematik Oyunu/Matematikoyunu/KayitAc.cs
2.640625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Matematikoyunu { public partial class KayitAc : Form { public KayitAc() { InitializeComponent(); } public Form1 form1; List<string> kayitlar = new List<string>(); private void listView1_DoubleClick(object sender, EventArgs e) { User user = new User(form1, Blok.blok1); Sonuc.form1 = form1; user.KayitAc(kayitlar[listView1.Items.IndexOf(listView1.SelectedItems[0])]); form1.Show(); this.Hide(); } private void KayitAc_Load(object sender, EventArgs e) { string dosya_yolu = "skor.txt"; if (File.Exists(dosya_yolu) == true) // dizindeki dosya var mı ? { FileStream fileStream = new FileStream(dosya_yolu, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fileStream); string satir; string[] bilgiler; string[] item = new string[10]; while ((satir = sr.ReadLine()) != null) { kayitlar.Add(satir); bilgiler = satir.Split('|'); item[0] = bilgiler[0]; item[1] = bilgiler.Length.ToString(); ListViewItem itm = new ListViewItem(item); listView1.Items.Add(itm); } sr.Close(); fileStream.Close(); } else MessageBox.Show("Hiçbir kayıt bulunamadi."); } } }
06b157af27f1c8b3ec9e9abd7751e507db3744ff
C#
werdnalt/TowerGame
/Assets/Scripts/MinionSpawner.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class MinionSpawner : MonoBehaviour { public Path path; public int owner; public Path.Direction pathTraversalDirection; public float timeBetweenGroupSpawns = 6f; public GameObject minion; public int groupSize = 5; private float timeOfLastGroupSpawn; private float timeBetweenMinionSpawns = 0.5f; private int minionsOfGroupSpawned = 0; private float timeOfLastMinionSpawn; // Start is called before the first frame update void Start() { if (!path) { Exception e = new Exception("Path missing in minion spawner"); throw e; } timeOfLastMinionSpawn = Time.time; } // Update is called once per frame void Update() { if (Time.time - timeOfLastGroupSpawn >= timeBetweenGroupSpawns && Time.time - timeOfLastMinionSpawn >= timeBetweenMinionSpawns) Spawn(); } private Vector3 SpawnPosition() { switch (pathTraversalDirection) { case Path.Direction.Forward: return new Vector3(path.waypoints[0].transform.position.x, path.waypoints[0].transform.position.y, -5f); case Path.Direction.Backward: return new Vector3(path.waypoints[path.waypoints.Count - 1].transform.position.x, path.waypoints[path.waypoints.Count - 1].transform.position.y, -5f); default: return Vector3.zero; } } void Spawn() { timeOfLastMinionSpawn = Time.time; Vector3 spawnPosition = SpawnPosition(); Minion m = GameObject.Instantiate(minion, spawnPosition, Quaternion.identity).GetComponent<Minion>(); m.SetPath(path, pathTraversalDirection, owner); // set minion to begin walking path minionsOfGroupSpawned++; if (minionsOfGroupSpawned == groupSize) { timeOfLastGroupSpawn = Time.time; minionsOfGroupSpawned = 0; } } }
013e472da21e29c9f18fc2adc3f1682b2126f67d
C#
changweihua/CLib
/Image/CImageEdge.cs
2.578125
3
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace CLib.CImage { #region 关于 /************************************************************************************* * CLR 版本: 4.0.30319.18034 * 类 名 称: CImageEdge * 机器名称: LUMIA800 * 命名空间: CLib.CImage * 文 件 名: CImageEdge * 创建时间: 2013/3/6 19:47:21 * 作 者: 常伟华 Changweihua * 版 权: CImageEdge说明:本代码版权归常伟华所有,使用时必须带上常伟华网站地址 All Rights Reserved (C) 2013 - 2014 * 签 名: To be or not, it is not a problem ! * 网 站: http://www.cmono.net * 邮 箱: changweihua@outlook.com * 唯一标识: 5d03e1b6-252e-4f4c-b147-9b7ffaae4949 * * 登录用户: Changweihua * 所 属 域: Lumia800 * 创建年份: 2013 * 修改时间: * 修 改 人: * ************************************************************************************/ #endregion /// <summary> /// 图像边缘检测 /// </summary> public class CImageEdge { //Roberts算子 // gx = f(i,j) - f(i+1,j) // gy = f(i+1,j) - f(i,j+1) // g(i,j) = abs(gx) + abs(gy) private Bitmap Roberts(Bitmap bmp) { Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height); LockBitmap lbmp = new LockBitmap(bmp); LockBitmap newlbmp = new LockBitmap(newbmp); lbmp.LockBits(); newlbmp.LockBits(); for (int i = 0; i < bmp.Width - 1; i++) { for (int j = 0; j < bmp.Height - 1; j++) { Color c1 = lbmp.GetPixel(i, j); Color c2 = lbmp.GetPixel(i + 1, j); Color c3 = lbmp.GetPixel(i, j + 1); Color c4 = lbmp.GetPixel(i + 1, j + 1); int r = Math.Abs(c1.R - c4.R) + Math.Abs(c2.R - c3.R); int g = Math.Abs(c1.G - c4.G) + Math.Abs(c2.G - c3.G); int b = Math.Abs(c1.B - c4.B) + Math.Abs(c2.B - c3.B); if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; newlbmp.SetPixel(i, j, Color.FromArgb(r, g, b)); } } lbmp.UnlockBits(); newlbmp.UnlockBits(); return newbmp; } //Sobel算子 // gx = f(i-1,j-1) + 2f(i-1,j) + f(i-1,j+1) - f(i+1,j-1) - 2f(i+1,j) - f(i+1,j+1) // gy = f(i-1,j-1) + 2f(i,j-1) + f(i+1,j-1) - f(i-1,j+1) - 2f(i,j+1) - f(i+1,j+1) // g(i,j) = gx + gy private Bitmap Sobel(Bitmap bmp) { Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height); LockBitmap lbmp = new LockBitmap(bmp); LockBitmap newlbmp = new LockBitmap(newbmp); lbmp.LockBits(); newlbmp.LockBits(); for (int i = 1; i < bmp.Width - 1; i++) { for (int j = 1; j < bmp.Height - 1; j++) { Color c1 = lbmp.GetPixel(i - 1, j - 1); Color c2 = lbmp.GetPixel(i, j - 1); Color c3 = lbmp.GetPixel(i + 1, j - 1); Color c4 = lbmp.GetPixel(i - 1, j); Color c6 = lbmp.GetPixel(i + 1, j); Color c7 = lbmp.GetPixel(i - 1, j + 1); Color c8 = lbmp.GetPixel(i, j + 1); Color c9 = lbmp.GetPixel(i + 1, j + 1); int r1 = c1.R + 2 * c4.R + c7.R - c3.R - 2 * c6.R - c9.R; int r2 = c1.R + 2 * c2.R + c3.R - c7.R - 2 * c8.R - c9.R; int g1 = c1.G + 2 * c4.G + c7.G - c3.G - 2 * c6.G - c9.G; int g2 = c1.G + 2 * c2.G + c3.G - c7.G - 2 * c8.G - c9.G; int b1 = c1.B + 2 * c4.B + c7.B - c3.B - 2 * c6.B - c9.B; int b2 = c1.B + 2 * c2.B + c3.B - c7.B - 2 * c8.B - c9.B; int r = Math.Abs(r1) + Math.Abs(r2); int g = Math.Abs(g1) + Math.Abs(g2); int b = Math.Abs(b1) + Math.Abs(b2); if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; newlbmp.SetPixel(i, j, Color.FromArgb(r, g, b)); //newlbmp.SetPixel(i, j, Color.FromArgb(r, r, r)); } } lbmp.UnlockBits(); newlbmp.UnlockBits(); return newbmp; } //拉普拉斯算子(四邻域) // g(i,j) = abs(4f(i,j) - f(i,j-1) - f(i,j+1) - f(i-1,j) - f(i+1,j)) private Bitmap Laplace4(Bitmap bmp) { Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height); LockBitmap lbmp = new LockBitmap(bmp); LockBitmap newlbmp = new LockBitmap(newbmp); lbmp.LockBits(); newlbmp.LockBits(); for (int i = 1; i < bmp.Width - 1; i++) { for (int j = 1; j < bmp.Height - 1; j++) { Color c2 = lbmp.GetPixel(i, j - 1); Color c4 = lbmp.GetPixel(i - 1, j); Color c5 = lbmp.GetPixel(i, j); Color c6 = lbmp.GetPixel(i + 1, j); Color c8 = lbmp.GetPixel(i, j + 1); int r = Math.Abs(4 * c5.R - c2.R - c4.R - c6.R - c8.R); int g = Math.Abs(4 * c5.G - c2.G - c4.G - c6.G - c8.G); int b = Math.Abs(4 * c5.B - c2.B - c4.B - c6.B - c8.B); if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; newlbmp.SetPixel(i, j, Color.FromArgb(r, g, b)); } } lbmp.UnlockBits(); newlbmp.UnlockBits(); return newbmp; } private Bitmap Laplace8(Bitmap bmp) { Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height); LockBitmap lbmp = new LockBitmap(bmp); LockBitmap newlbmp = new LockBitmap(newbmp); lbmp.LockBits(); newlbmp.LockBits(); for (int i = 1; i < bmp.Width - 1; i++) { for (int j = 1; j < bmp.Height - 1; j++) { Color c1 = lbmp.GetPixel(i - 1, j - 1); Color c2 = lbmp.GetPixel(i, j - 1); Color c3 = lbmp.GetPixel(i + 1, j - 1); Color c4 = lbmp.GetPixel(i - 1, j); Color c5 = lbmp.GetPixel(i, j); Color c6 = lbmp.GetPixel(i + 1, j); Color c7 = lbmp.GetPixel(i - 1, j + 1); Color c8 = lbmp.GetPixel(i, j + 1); Color c9 = lbmp.GetPixel(i + 1, j + 1); int r = Math.Abs(8 * c5.R - c1.R - c2.R - c3.R - c4.R - c6.R - c7.R - c8.R - c9.R); int g = Math.Abs(8 * c5.G - c1.G - c2.G - c3.G - c4.G - c6.G - c7.G - c8.G - c9.G); int b = Math.Abs(8 * c5.B - c1.B - c2.B - c3.B - c4.B - c6.B - c7.B - c8.B - c9.B); if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; newlbmp.SetPixel(i, j, Color.FromArgb(r, g, b)); } } lbmp.UnlockBits(); newlbmp.UnlockBits(); return newbmp; } //右下边缘抽出 // g(i,j) = abs(2f(i+1,j) + 2f(i,j+1) - 2f(i,j-1) - 2f(i-1,j)); private Bitmap RightBottomEdge(Bitmap bmp) { Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height); LockBitmap lbmp = new LockBitmap(bmp); LockBitmap newlbmp = new LockBitmap(newbmp); lbmp.LockBits(); newlbmp.LockBits(); for (int i = 1; i < bmp.Width - 1; i++) { for (int j = 1; j < bmp.Height - 1; j++) { Color c2 = lbmp.GetPixel(i, j - 1); Color c4 = lbmp.GetPixel(i - 1, j); Color c6 = lbmp.GetPixel(i + 1, j); Color c8 = lbmp.GetPixel(i, j + 1); int r = 2 * Math.Abs(c6.R + c8.R - c2.R - c4.R); int g = 2 * Math.Abs(c6.G + c8.G - c2.G - c4.G); int b = 2 * Math.Abs(c6.B + c8.B - c2.B - c4.B); if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; newlbmp.SetPixel(i, j, Color.FromArgb(r, g, b)); } } lbmp.UnlockBits(); newlbmp.UnlockBits(); return newbmp; } //Prewitt边缘检测样板算子(方向为右下) // g(i,j) = abs(f(i-1,j-1) + f(i,j-1) + f(i+1,j-1) + f(i-1,j) + f(i-1,j+1) - f(i+1,j) - f(i,j+1) - f(i+1,j+1) - 2f(i,j)) // // 右下 右上 // 1 1 1 1 -1 -1 // 1 -2 -1 1 -2 -1 // 1 -1 -1 1 1 1 // // 上 下 // -1 -1 -1 1 1 1 // 1 -2 1 1 -2 1 // 1 1 1 -1 -1 -1 private Bitmap Prewitt(Bitmap bmp) { Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height); LockBitmap lbmp = new LockBitmap(bmp); LockBitmap newlbmp = new LockBitmap(newbmp); lbmp.LockBits(); newlbmp.LockBits(); for (int i = 1; i < bmp.Width - 1; i++) { for (int j = 1; j < bmp.Height - 1; j++) { Color c1 = lbmp.GetPixel(i - 1, j - 1); Color c2 = lbmp.GetPixel(i, j - 1); Color c3 = lbmp.GetPixel(i + 1, j - 1); Color c4 = lbmp.GetPixel(i - 1, j); Color c5 = lbmp.GetPixel(i, j); Color c6 = lbmp.GetPixel(i + 1, j); Color c7 = lbmp.GetPixel(i - 1, j + 1); Color c8 = lbmp.GetPixel(i, j + 1); Color c9 = lbmp.GetPixel(i + 1, j + 1); int r = Math.Abs(c1.R + c2.R + c3.R + c4.R + c7.R - c6.R - c8.R - c9.R - 2 * c5.R); int g = Math.Abs(c1.G + c2.G + c3.G + c4.G + c7.G - c6.G - c8.G - c9.G - 2 * c5.R); int b = Math.Abs(c1.B + c2.B + c3.B + c4.B + c7.B - c6.B - c8.B - c9.B - 2 * c5.R); if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; newlbmp.SetPixel(i, j, Color.FromArgb(r, g, b)); } } lbmp.UnlockBits(); newlbmp.UnlockBits(); return newbmp; } //Robinson算子(这里使用第一个) //Robinson算子有八个样板,这里列出四个,剩余四个为下面四个的取反 // // 1 2 1 0 1 2 // 0 0 0 -1 0 1 // -1 -2 -1 -2 -1 0 // // -1 0 1 -2 -1 0 // -2 0 2 -1 0 1 // -1 0 1 0 -1 2 private Bitmap Robinson(Bitmap bmp) { Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height); LockBitmap lbmp = new LockBitmap(bmp); LockBitmap newlbmp = new LockBitmap(newbmp); lbmp.LockBits(); newlbmp.LockBits(); for (int i = 1; i < bmp.Width - 1; i++) { for (int j = 1; j < bmp.Height - 1; j++) { Color c1 = lbmp.GetPixel(i - 1, j - 1); Color c2 = lbmp.GetPixel(i, j - 1); Color c3 = lbmp.GetPixel(i + 1, j - 1); Color c7 = lbmp.GetPixel(i - 1, j + 1); Color c8 = lbmp.GetPixel(i, j + 1); Color c9 = lbmp.GetPixel(i + 1, j + 1); int r = Math.Abs(c1.R + 2 * c2.R + c3.R - c7.R - 2 * c8.R - c9.R); int g = Math.Abs(c1.G + 2 * c2.G + c3.G - c7.G - 2 * c8.G - c9.G); int b = Math.Abs(c1.B + 2 * c2.B + c3.B - c7.B - 2 * c8.B - c9.B); if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; newlbmp.SetPixel(i, j, Color.FromArgb(r, g, b)); } } lbmp.UnlockBits(); newlbmp.UnlockBits(); return newbmp; } //Kirsch算子(这里使用第一个) //Kirsch算子有8个边缘样板,与Prewitt边缘样板类似,这里列出一个 // // 5 5 5 // -3 0 -3 // -3 -3 -3 // private Bitmap Kirsch(Bitmap bmp) { Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height); LockBitmap lbmp = new LockBitmap(bmp); LockBitmap newlbmp = new LockBitmap(newbmp); lbmp.LockBits(); newlbmp.LockBits(); for (int i = 1; i < bmp.Width - 1; i++) { for (int j = 1; j < bmp.Height - 1; j++) { Color c1 = lbmp.GetPixel(i - 1, j - 1); Color c2 = lbmp.GetPixel(i, j - 1); Color c3 = lbmp.GetPixel(i + 1, j - 1); Color c4 = lbmp.GetPixel(i - 1, j); Color c6 = lbmp.GetPixel(i + 1, j); Color c7 = lbmp.GetPixel(i - 1, j + 1); Color c8 = lbmp.GetPixel(i, j + 1); Color c9 = lbmp.GetPixel(i + 1, j + 1); int r = Math.Abs(5 * (c1.R + c2.R + c3.R) - 3 * (c4.R + c6.R + c7.R + c8.R + c9.R)); int g = Math.Abs(5 * (c1.G + c2.G + c3.G) - 3 * (c4.G + c6.G + c7.G + c8.G + c9.G)); int b = Math.Abs(5 * (c1.B + c2.B + c3.B) - 3 * (c4.B + c6.B + c7.B + c8.B + c9.B)); if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; newlbmp.SetPixel(i, j, Color.FromArgb(r, g, b)); } } lbmp.UnlockBits(); newlbmp.UnlockBits(); return newbmp; } //Smoothed算子 // gx = f(i,j) - f(i+1,j) // gy = f(i+1,j) - f(i,j+1) // g(i,j) = abs(gx) + abs(gy) private Bitmap Smoothed(Bitmap bmp) { Bitmap newbmp = new Bitmap(bmp.Width, bmp.Height); LockBitmap lbmp = new LockBitmap(bmp); LockBitmap newlbmp = new LockBitmap(newbmp); lbmp.LockBits(); newlbmp.LockBits(); for (int i = 1; i < bmp.Width - 1; i++) { for (int j = 1; j < bmp.Height - 1; j++) { Color c1 = lbmp.GetPixel(i - 1, j - 1); Color c2 = lbmp.GetPixel(i, j - 1); Color c3 = lbmp.GetPixel(i + 1, j - 1); Color c4 = lbmp.GetPixel(i - 1, j); Color c6 = lbmp.GetPixel(i + 1, j); Color c7 = lbmp.GetPixel(i - 1, j + 1); Color c8 = lbmp.GetPixel(i, j + 1); Color c9 = lbmp.GetPixel(i + 1, j + 1); int r1 = c3.R + c6.R + c9.R - c1.R - c4.R - c7.R; int r2 = c1.R + c2.R + c3.R - c7.R - c8.R - c9.R; int g1 = c3.G + c6.G + c9.G - c1.G - c4.G - c7.G; int g2 = c1.G + c2.G + c3.G - c7.G - c8.G - c9.G; int b1 = c3.B + c6.B + c9.B - c1.B - c4.B - c7.B; int b2 = c1.B + c2.B + c3.B - c7.B - c8.B - c9.B; int r = Math.Abs(r1) + Math.Abs(r2); int g = Math.Abs(g1) + Math.Abs(g2); int b = Math.Abs(b1) + Math.Abs(b2); if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; newlbmp.SetPixel(i, j, Color.FromArgb(r, g, b)); //newlbmp.SetPixel(i, j, Color.FromArgb(r, r, r)); } } lbmp.UnlockBits(); newlbmp.UnlockBits(); return newbmp; } } }
40cb48a07a907394f2bed6fce38e0c63e6346900
C#
salileo/WallpaperManager
/WallpaperManager/TrayIcon.cs
2.59375
3
using System; using System.Drawing; using System.IO; using System.Windows; using System.Windows.Forms; using System.Windows.Resources; namespace WallpaperManager { class TrayIcon { private MainWindow parentWindow; private NotifyIcon trayIcon; private MenuItem openWindowMenuItem; private MenuItem changeWallpaperMenuItem; private MenuItem enablePPTMenuItem; private MenuItem disablePPTMenuItem; private MenuItem exitApplicationMenuItem; public TrayIcon(MainWindow parentWindow) { //create the tray icon and set the icon file this.trayIcon = new NotifyIcon(); StreamResourceInfo info = App.GetResourceStream(new Uri("/Icons/main.ico", UriKind.Relative)); this.trayIcon.Icon = new Icon(info.Stream); this.trayIcon.Visible = false; this.trayIcon.Text = "Wallpaper Manager"; this.trayIcon.BalloonTipTitle = "Wallpaper Manager"; this.trayIcon.BalloonTipText = "Wallpaper Manager"; //set the mouse handlers this.trayIcon.DoubleClick += new System.EventHandler(this.ChangeWallpaper); //setup the context menu ContextMenu menu = new ContextMenu(); this.trayIcon.ContextMenu = menu; this.openWindowMenuItem = new MenuItem("Open main window"); this.openWindowMenuItem.Click += new EventHandler(this.OpenMainWindow); menu.MenuItems.Add(this.openWindowMenuItem); this.changeWallpaperMenuItem = new MenuItem("Change wallpaper"); this.changeWallpaperMenuItem.Click += new EventHandler(this.ChangeWallpaper); menu.MenuItems.Add(this.changeWallpaperMenuItem); this.enablePPTMenuItem = new MenuItem("Enable presentation"); this.enablePPTMenuItem.Click += new EventHandler(this.EnablePresentation); menu.MenuItems.Add(this.enablePPTMenuItem); this.disablePPTMenuItem = new MenuItem("Disable presentation"); this.disablePPTMenuItem.Click += new EventHandler(this.DisablePresentation); menu.MenuItems.Add(this.disablePPTMenuItem); this.exitApplicationMenuItem = new MenuItem("Exit Application"); this.exitApplicationMenuItem.Click += new EventHandler(this.ExitApplication); menu.MenuItems.Add(this.exitApplicationMenuItem); //set the parent in the end after all initialization has succeeded this.parentWindow = parentWindow; this.parentWindow.PresentationModeChanged += ParentWindow_ModeChanged; this.UpdateBasedOnPresentationMode(); } /// <summary> /// Show/Hide the main app window /// </summary> public void UpdateMainWindow(bool show) { if (show) { this.parentWindow.Show(); this.parentWindow.WindowState = WindowState.Normal; this.openWindowMenuItem.Visible = false; //bug: item not selected if application starts minimized //m_parent.c_filelist.ScrollIntoView(m_parent.c_filelist.SelectedItem); } else { this.parentWindow.Hide(); this.openWindowMenuItem.Visible = true; } } /// <summary> /// Show/Hide the icon in tray /// </summary> public void UpdateTrayIcon(bool show) { this.trayIcon.Visible = show; } /// <summary> /// Update the context menu based on the presentation mode /// </summary> private void UpdateBasedOnPresentationMode() { bool enabled = Settings.Instance.InPresentationMode; bool imagePresent = !string.IsNullOrEmpty(Settings.Instance.PresentationImage); this.enablePPTMenuItem.Visible = !enabled && imagePresent; this.disablePPTMenuItem.Visible = enabled && imagePresent; this.changeWallpaperMenuItem.Visible = !enabled; } /// <summary> /// Sets the tool tip text /// </summary> public void SetToolText(string text) { string tooltip_text; text = Path.GetFileName(text); if (text.Length > 0) { tooltip_text = "Wallpaper: " + text; // if the length is too long, try to just use the file name if (tooltip_text.Length >= 64) { tooltip_text = text; } // if the length is still too long, truncate the file name if (tooltip_text.Length >= 64) { tooltip_text = text.Substring(0, 60) + "..."; } } else { tooltip_text = "Wallpaper Manager"; } this.trayIcon.Text = tooltip_text; this.trayIcon.BalloonTipText = text; if (this.trayIcon.Visible && !string.IsNullOrEmpty(text)) { this.trayIcon.ShowBalloonTip(10); } } /// <summary> /// Set the tool tip text to the loading state /// </summary> public void SetLoadingText() { string text = "Loading next image ..."; this.trayIcon.Text = text; this.trayIcon.BalloonTipText = text; if (this.trayIcon.Visible) { this.trayIcon.ShowBalloonTip(60); } } /// <summary> /// Handler for "enable presentation" menu item /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void EnablePresentation(object sender, EventArgs args) { this.parentWindow.SwitchPresentationMode(true); } /// <summary> /// Handler for "disable presentation" menu item /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void DisablePresentation(object sender, EventArgs args) { this.parentWindow.SwitchPresentationMode(false); } /// <summary> /// Handler for "change wallpaper" menu item /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void ChangeWallpaper(object sender, EventArgs args) { this.parentWindow.GotoNextImage(true); } /// <summary> /// Handler for "open main window" menu item /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OpenMainWindow(object sender, EventArgs args) { this.UpdateMainWindow(true); } /// <summary> /// Handler for "exit application" menu item /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void ExitApplication(object sender, EventArgs args) { this.parentWindow.ForceExitApp(); } /// <summary> /// Handler for action to take when presentation mode is changed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ParentWindow_ModeChanged(object sender, EventArgs e) { this.UpdateBasedOnPresentationMode(); } } }
d553fe86d8059ab747b790de0e893582d721f14c
C#
robrich/aspnet-dos-and-donts-for-highly-maintainable-code
/03. Action Filters/ActionFilters/Filters/HelloActionFiltersAttribute.cs
2.875
3
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace ActionFilters.Filters { public class HelloActionFiltersAttribute : ActionFilterAttribute { public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { // before regular method Console.WriteLine($"Before {context.HttpContext.Request.Path}"); Console.WriteLine($"Calling {context.ActionDescriptor.RouteValues["controller"]}.{context.ActionDescriptor.RouteValues["action"]}"); // do the regular method var result = await next(); // after regular method Console.WriteLine($"Finished calling {context.ActionDescriptor.RouteValues["controller"]}.{context.ActionDescriptor.RouteValues["action"]}"); } public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { // before view rendering string viewName = null; ViewResult view = context.Result as ViewResult; if (view != null) { viewName = view.ViewName; } if (string.IsNullOrEmpty(viewName)) { viewName = context.ActionDescriptor.RouteValues["action"]; } Console.WriteLine($"Rendering {viewName}"); // render the view var result = await next(); // after view rendering Console.WriteLine($"Finished rendering {viewName}"); Console.WriteLine($"After {context.HttpContext.Request.Path}"); } } }
c855fc8746a85fad94582b28de93cb4119d69d41
C#
YugoAnzai/Dunk-Line
/Assets/Scripts/Save/PlayerPrefsManager.cs
2.609375
3
using System.Collections.Generic; using UnityEngine; public enum SaveKey { HighScore = 0, LastScore = 1, } public class PlayerPrefsManager { private enum ValueType { INT, FLOAT, BOOL, STRING } private static Dictionary<SaveKey, string> keyNames; private static Dictionary<SaveKey, ValueType> keyTypes; [RuntimeInitializeOnLoadMethod] private static void SetupKeyNames() { keyNames = new Dictionary<SaveKey, string>(); keyTypes = new Dictionary<SaveKey, ValueType>(); // Setup names and types AddToDicts(SaveKey.HighScore, ValueType.INT); AddToDicts(SaveKey.LastScore, ValueType.INT); } private static void AddToDicts(SaveKey key, ValueType type) { AddToDicts(key, type, key.ToString()); } private static void AddToDicts(SaveKey key, ValueType type, string name) { keyTypes.Add(key, type); keyNames.Add(key, name); } public static string GetPrefSaveName(SaveKey key) { return keyNames[key]; } public static bool HasKey(SaveKey key) { return PlayerPrefs.HasKey(keyNames[key]); } public static void DeleteKey(SaveKey key) { PlayerPrefs.DeleteKey(keyNames[key]); } #region INT public static int GetInt(SaveKey key) { if (keyTypes[key] != ValueType.INT) { throw new PlayerPrefsException(keyNames[key] + " Does not store INT value."); } return PlayerPrefs.GetInt(keyNames[key]); } public static void SetInt(SaveKey key, int value) { if (keyTypes[key] != ValueType.INT) { throw new PlayerPrefsException(keyNames[key] + " Does not store INT value."); } PlayerPrefs.SetInt(keyNames[key], value); } #endregion #region BOOL public static bool GetBool(SaveKey key) { if (keyTypes[key] != ValueType.BOOL) { throw new PlayerPrefsException(keyNames[key] + " Does not store Bool value."); } return PlayerPrefs.GetInt(keyNames[key]) == 1 ? true : false; } public static void SetBool(SaveKey key, bool value) { if (keyTypes[key] != ValueType.BOOL) { throw new PlayerPrefsException(keyNames[key] + " Does not store Bool value."); } int integer = value ? 1 : 0; PlayerPrefs.SetInt(keyNames[key], integer); } #endregion #region FLOAT public static float GetFloat(SaveKey key) { if (keyTypes[key] != ValueType.FLOAT) { throw new PlayerPrefsException(keyNames[key] + " Does not store FLOAT value."); } return PlayerPrefs.GetFloat(keyNames[key]); } public static void SetFloat(SaveKey key, float value) { if (keyTypes[key] != ValueType.FLOAT) { throw new PlayerPrefsException(keyNames[key] + " Does not store FLOAT value."); } PlayerPrefs.SetFloat(keyNames[key], value); } #endregion #region STRING public static string GetString(SaveKey key) { if (keyTypes[key] != ValueType.STRING) { throw new PlayerPrefsException(keyNames[key] + " Does not store STRING value."); } return PlayerPrefs.GetString(keyNames[key]); } public static void SetString(SaveKey key, string value) { if (keyTypes[key] != ValueType.STRING) { throw new PlayerPrefsException(keyNames[key] + " Does not store STRING value."); } PlayerPrefs.SetString(keyNames[key], value); } #endregion #region RESET public static void ResetSave() { foreach(SaveKey key in keyNames.Keys) { DeleteKey(key); } } #endregion } [System.Serializable] public class PlayerPrefTypeException : System.Exception { public PlayerPrefTypeException() { } public PlayerPrefTypeException(string message) : base(message) { } public PlayerPrefTypeException(string message, System.Exception inner) : base(message, inner) { } protected PlayerPrefTypeException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } }
de31d375eee8e5d7e76c0b916ccd2677effe79a4
C#
jiangyimm/DonePad
/DonePadClient/MongoDb/MongoDbProvide.cs
2.828125
3
using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using DonePadClient.Config; namespace DonePadClient.MongoDb { public class MongoDbProvide { static MongoDbProvide() { Init(); } private static MongoClient _mongoClient; private static IMongoDatabase _db; private static bool _connected; private static void Init() { if (_connected) return; _mongoClient = new MongoClient(MongoDbConfigHelper.Config.ConnectionString); _db = _mongoClient.GetDatabase(MongoDbConfigHelper.Config.DataBaseName); _connected = true; } private static void CreateTables<T>() { try { _db.CreateCollection(nameof(T)); } catch (Exception e) { Console.WriteLine(e); } } public static void Insert<T>(T info) { var col = _db.GetCollection<T>(typeof(T).Name); col.InsertOne(info); } public static List<T> QueryList<T>(Expression<Func<T, bool>> expression) { var col = _db.GetCollection<T>(typeof(T).Name); return col.AsQueryable().Where(expression).ToList(); } public static List<T> QueryList<T>() { var col = _db.GetCollection<T>(typeof(T).Name); return col.AsQueryable().ToList(); } public static bool Delete<T>(Expression<Func<T, bool>> predicate) { var col = _db.GetCollection<T>(typeof(T).Name); var result = col.DeleteMany(predicate); return result != null && result.DeletedCount > 0; } public static bool Update<T>(FilterDefinition<T> f, UpdateDefinition<T> u) { var col = _db.GetCollection<T>(typeof(T).Name); var result = col.UpdateMany(f, u); return result != null && result.ModifiedCount > 0; } } }
1de20a994c30d77971ac687fe521a2d74e439cd0
C#
GuilhermeMatheus/alura-csharp-poo2
/src/06-ByteBank-Construtores/ContaCorrente.cs
3.46875
3
using System; namespace _06_ByteBank_Construtores { public class ContaCorrente { public static int NumeroDeContasCriadas { get; private set; } private int _numero; private int _agencia; private double _saldo; private Cliente _titular; public int Numero { get { return _numero; } set { if (value <= 0) { Console.WriteLine("Não é permitido número menor ou igual a 0"); return; } _numero = value; } } public int Agencia { get { return _agencia; } set { if (value <= 0) { Console.WriteLine("Não é permitido agencia menor ou igual a 0"); return; } _agencia = value; } } public double Saldo { get { return _saldo; } set { _saldo = value; } } public Cliente Titular { get { return _titular; } set { _titular = value; } } public ContaCorrente(int numero, int agencia) { Numero = numero; Agencia = agencia; NumeroDeContasCriadas++; } public void Deposita(double valor) { // devia ter feito um SetSaldo(GetSaldo() + saldo) // usar propriedades aqui é opcional mas eu sempre faço assim pra centralizar qualquer lógica Saldo += valor; } public bool Saca(double valor) { if (Saldo >= valor) { Saldo -= valor; return true; } return false; } public bool Transfere(double valor, ContaCorrente outraConta) { // Começamos assim, mas podemos fazer invocando o Saca // e ganhamos um DRY ? //if (this.saldo >= valor) //{ // this.saldo -= valor; // outraConta.Deposita(valor); // return true; //} bool saqueRealizado = Saca(valor); if (saqueRealizado) { outraConta.Deposita(valor); return true; } return false; } } }
7f07f9080bf23b583d007d7ae18854c12a1d0891
C#
Cinchoo/ChoETL
/src/ChoETL/Common/Dynamic/ChoDynamicClassFactory.cs
2.71875
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ChoETL { public class ChoDynamicClassFactory { private AppDomain _appDomain; private AssemblyBuilder _assemblyBuilder; private ModuleBuilder _moduleBuilder; private TypeBuilder _typeBuilder; private string _assemblyName; public ChoDynamicClassFactory() : this("ChoETL.Dynamic") { } public ChoDynamicClassFactory(string assemblyName) { _appDomain = Thread.GetDomain(); _assemblyName = assemblyName; } /// <summary> /// This is the normal entry point and just return the Type generated at runtime /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="properties"></param> /// <returns></returns> public Type CreateDynamicType<T>(string name, Dictionary<string, Type> properties, string[] keys = null) { var tb = CreateDynamicTypeBuilder<T>(name, properties, keys); #if !NETSTANDARD2_0 return tb.CreateType(); #else return tb.CreateTypeInfo(); #endif } /// <summary> /// Exposes a TypeBuilder that can be returned and created outside of the class /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="properties"></param> /// <returns></returns> public TypeBuilder CreateDynamicTypeBuilder<T>(string name, Dictionary<string, Type> properties, string[] keys = null) { if (_assemblyBuilder == null) { #if !NETSTANDARD2_0 _assemblyBuilder = _appDomain.DefineDynamicAssembly(new AssemblyName(_assemblyName), AssemblyBuilderAccess.RunAndSave); #else _assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(_assemblyName), AssemblyBuilderAccess.Run); #endif } //vital to ensure the namespace of the assembly is the same as the module name, else IL inspectors will fail if (_moduleBuilder == null) _moduleBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName + ".dll"); //typeof(T) is for the base class, can be omitted if not needed _typeBuilder = _moduleBuilder.DefineType(_assemblyName + "." + name, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.Serializable | TypeAttributes.BeforeFieldInit, typeof(T)); //various class based attributes for WCF and EF AddDataContractAttribute(); AddTableAttribute(name); AddDataServiceKeyAttribute(); //if there is a property on the base class and also in the dictionary, remove them from the dictionary var pis = typeof(T).GetProperties(); foreach (var pi in pis) { properties.Remove(pi.Name); } //get the OnPropertyChanged method from the base class var propertyChangedMethod = typeof(T).GetMethod("OnPropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic); CreateProperties(_typeBuilder, properties, propertyChangedMethod, keys); return _typeBuilder; } public void AddDataContractAttribute() { Type attrType = typeof(DataContractAttribute); _typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(attrType.GetConstructor(Type.EmptyTypes), new object[] { })); } public void AddTableAttribute(string name) { Type attrType = typeof(TableAttribute); _typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(attrType.GetConstructor(new[] { typeof(string) }), new object[] { name })); } public void AddDataServiceKeyAttribute() { //Type attrType = typeof(DataServiceKeyAttribute); //_typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(attrType.GetConstructor(new[] { typeof(string) }), // new object[] { "Id" })); } public void CreateProperties(TypeBuilder typeBuilder, Dictionary<string, Type> properties, MethodInfo raisePropertyChanged, string[] keys) { properties.ToList().ForEach(p => CreateFieldForType(p.Value, p.Key, raisePropertyChanged, keys)); } private void CreateFieldForType(Type type, String name, MethodInfo raisePropertyChanged, string[] keys) { FieldBuilder fieldBuilder = _typeBuilder.DefineField("_" + name.ToLowerInvariant(), type, FieldAttributes.Private); PropertyBuilder propertyBuilder = _typeBuilder.DefineProperty(name, PropertyAttributes.HasDefault, type, null); //add the various WCF and EF attributes to the property AddDataMemberAttribute(propertyBuilder); AddColumnAttribute(propertyBuilder); if (keys != null && keys.Contains(name)) AddKeyAttribute(propertyBuilder); MethodAttributes getterAndSetterAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;// | MethodAttributes.Virtual; //creates the Get Method for the property propertyBuilder.SetGetMethod(CreateGetMethod(getterAndSetterAttributes, name, type, fieldBuilder)); //creates the Set Method for the property and also adds the invocation of the property change propertyBuilder.SetSetMethod(CreateSetMethod(getterAndSetterAttributes, name, type, fieldBuilder, raisePropertyChanged)); } private void AddDataMemberAttribute(PropertyBuilder propertyBuilder) { Type attrType = typeof(DataMemberAttribute); var attr = new CustomAttributeBuilder(attrType.GetConstructor(Type.EmptyTypes), new object[] { }); propertyBuilder.SetCustomAttribute(attr); } private void AddColumnAttribute(PropertyBuilder propertyBuilder) { Type attrType = typeof(ColumnAttribute); var attr = new CustomAttributeBuilder(attrType.GetConstructor(Type.EmptyTypes), new object[] { }); propertyBuilder.SetCustomAttribute(attr); } private void AddKeyAttribute(PropertyBuilder propertyBuilder) { Type attrType = typeof(KeyAttribute); var attr = new CustomAttributeBuilder(attrType.GetConstructor(Type.EmptyTypes), new object[] { }); propertyBuilder.SetCustomAttribute(attr); } private MethodBuilder CreateGetMethod(MethodAttributes attr, string name, Type type, FieldBuilder fieldBuilder) { var getMethodBuilder = _typeBuilder.DefineMethod("get_" + name, attr, type, Type.EmptyTypes); var getMethodILGenerator = getMethodBuilder.GetILGenerator(); getMethodILGenerator.Emit(OpCodes.Ldarg_0); getMethodILGenerator.Emit(OpCodes.Ldfld, fieldBuilder); getMethodILGenerator.Emit(OpCodes.Ret); return getMethodBuilder; } private MethodBuilder CreateSetMethod(MethodAttributes attr, string name, Type type, FieldBuilder fieldBuilder, MethodInfo raisePropertyChanged) { var setMethodBuilder = _typeBuilder.DefineMethod("set_" + name, attr, null, new Type[] { type }); var setMethodILGenerator = setMethodBuilder.GetILGenerator(); setMethodILGenerator.Emit(OpCodes.Ldarg_0); setMethodILGenerator.Emit(OpCodes.Ldarg_1); setMethodILGenerator.Emit(OpCodes.Stfld, fieldBuilder); if (raisePropertyChanged != null) { setMethodILGenerator.Emit(OpCodes.Ldarg_0); setMethodILGenerator.Emit(OpCodes.Ldstr, name); setMethodILGenerator.EmitCall(OpCodes.Call, raisePropertyChanged, null); } setMethodILGenerator.Emit(OpCodes.Ret); return setMethodBuilder; } #if !NETSTANDARD2_0 public void SaveAssembly() { _assemblyBuilder.Save(_assemblyBuilder.GetName().Name + ".dll"); } #endif } }
2884b7986b1b583c67eefe7ca966bdab7e8b84b0
C#
IgnacioFigueroa/proyecto-grupo-03
/SimuladorHorario/SimuladorHorario/EventoPersonal.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimuladorHorario { [Serializable()] public class EventoPersonal:Evento { public string nombre { get; private set; } public string hora { get; private set; } public string fecha { get; private set; } public string sala { get; private set; } public TipoEvento tipo { get; private set; } public bool primerPeriodo = false; public EventoPersonal(string nombre, string hora, string fecha, string sala) : base(nombre, hora, fecha, sala,TipoEvento.PERS,true) { this.nombre = nombre; this.hora = hora; this.fecha = fecha; this.sala = sala; } public override string ToString() { string text = fecha.Replace(':','-') + " " +hora +" " + nombre; return text; } } }
a6ee07d6a2bf33bc8e7ab02e86b25bb54a000425
C#
Soucre/Working_git_vfs
/VfsInformationCustomerService 2010/Services/Crawler/Page.cs
2.96875
3
using System; using System.Collections.Generic; using System.Text; namespace VfsInformationFeedService.Crawler { public class Page { #region Constructor /// <summary> /// Default constructor. /// </summary> public Page() { } #endregion #region Private Instance Fields private int _size; private string _text; private string _url; private int _viewstateSize; #endregion #region Public Properties public int Size { get { return _size; } } public string Text { get { return _text; } set { _text = value; _size = value.Length; } } public string Url { get { return _url; } set { _url = value; } } public int ViewstateSize { get { return _viewstateSize; } set { _viewstateSize = value; } } #endregion public void CalculateViewstateSize() { int startingIndex = Text.IndexOf("id=\"__VIEWSTATE\""); if (startingIndex > -1) { int indexOfViewstateValueNode = Text.IndexOf("value=\"", startingIndex); int indexOfClosingQuotationMark = Text.IndexOf("\"", indexOfViewstateValueNode + 7); string viewstateValue = Text.Substring(indexOfViewstateValueNode + 7, indexOfClosingQuotationMark - (indexOfViewstateValueNode + 7)); ViewstateSize = viewstateValue.Length; } } } }
db3875985eca5646cc854a47dbaa1198fefa87d0
C#
YassineMarroun/CSharp-Basics2021
/Ejemplo17-List/Program.cs
3.71875
4
using System; using System.Collections.Generic; namespace Ejemplo17_List { /* * Ejemplo de uso de lista */ class Program { static void Main(string[] args) { // Creo la lista List<char> listaABC = new List<char>(); // Añadimos los elementos listaABC.Add('a'); listaABC.Add('b'); listaABC.Add('d'); listaABC.Add('d'); listaABC.Add('k'); listaABC.Add('e'); listaABC.Add('f'); // Eliminamos el elemento de la posición 3, una d que está duplicada listaABC.RemoveAt(3); // Falta la c, la inserto en su lugar listaABC.Insert(2, 'c'); // Elimino la k listaABC.Remove('k'); // Uso un bucle para recorrer la lista (no se eliminan) foreach (char letra in listaABC) { Console.WriteLine(letra); } } } }
407d4fd61232678c0185693e2e2d410b2cdf914e
C#
unixcrh/Motion
/Motion/ZForge.Motion.Core/CameraStatus.cs
2.890625
3
using System; using System.Collections.Generic; using System.Text; namespace ZForge.Motion.Core { public class CameraStatus { private int status; public const int STARTED = 0x01; public const int STOPPED = 0x02; public const int PAUSED = 0x04; public CameraStatus(int status) { this.status = status; } #region Properties public int Value { get { return this.status; } set { this.status = value; } } #endregion public void SetStatus(int s, bool set) { if (set) { this.Value = this.Value | s; } else { this.Value = this.Value & (~s); } } public bool IsStatusSet(int s) { return ((this.Value & s) != 0) ? true : false; } public static bool IsStatusSet(int status, int s) { return ((status & s) != 0) ? true : false; } } }
561a3b2c2e22625a5a878908dcef38fd1574310b
C#
StoQK/CSharp-II
/5. UsingClassesAndObjects/04. SurfaceOfTriangleCalculation/SurfaceOfTriangleCalculation.cs
4.5
4
//Write methods that calculate the surface of a triangle by given: //Side and an altitude to it; Three sides; //Two sides and an angle between them. Use System.Math. using System; namespace _04.SurfaceOfTriangleCalculation { class SurfaceOfTriangleCalculation { static double CalculateSurfaceOfTriangle(double side, double altitude) { double area = (side * altitude) / 2; return area; } static double CalculateSurfaceOfTriangle(double sideA, double sideB, double sideC) { double p = (sideA + sideB + sideC) / 2; double area = Math.Sqrt(p * (p - sideA) * (p - sideB) * (p - sideC)); return area; } static double CalculateSurfaceOfTriangle(double sideA, double sideB, int angle) { double area = (sideA * sideB * Math.Sin(Math.PI * angle / 180)) / 2; return area; } static void Main() { Console.WriteLine("Area (given a, ha) = {0:F2} ", CalculateSurfaceOfTriangle(6, 4)); Console.WriteLine("Area (given a,b,c) = {0:F2}", CalculateSurfaceOfTriangle(3, 4, 5.0)); Console.WriteLine("Area (given a, b, angle between them) = {0:F2}", CalculateSurfaceOfTriangle(2, 2, 60)); } } }
757e0c344cf0e7edf7e643d40fb1f12c00281fcf
C#
FilipeAndre-Silva/learning_csharp
/Tutorial C#/Variáveris/Program.cs
3.609375
4
using System; namespace Variáveris { class Program { static void Main(string[] args) { //Variáveis em C# string vazia; vazia = "Atribuindo valor"; Console.WriteLine(vazia); string nome_completo = "Filipe André da Silva"; Console.WriteLine(nome_completo); int idade = 23; Console.WriteLine(idade); int valor1 = 100; valor1 = 50; Console.Write("Valor alterado antes da exibição para:"); Console.WriteLine(valor1); const int vida = 1; Console.Write("Valor de costante não alteravel:"); Console.WriteLine(vida); double peso = 84.5D; Console.WriteLine(peso); float valor_float = 5.75F; Console.WriteLine(valor_float); long myNum = 15000000000L; Console.WriteLine(myNum); char letra = 'F'; Console.WriteLine(letra); bool vivo = true; Console.WriteLine(vivo); string outro_nome = "Concatenando"; Console.WriteLine(outro_nome + " Strings"); string nome = "Filipe "; string sobrenome = "André"; Console.WriteLine(nome + sobrenome); int x = 5; int y = 8; Console.Write("Resultado Operações matemáticas de soma:"); Console.WriteLine(x + y); int a = 1, b = 4, c = 7; Console.WriteLine(a + b + c); } } }
b4959bb66792a62fbc0d5f4a882bc5b41d56a46d
C#
gongjiaji/RecipeSlave
/Assets/Scripts/enemy/EnemyController.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyController : MonoBehaviour { public float hp; public int attack; public bool isDead; public GameObject[] loots; private GameObject player; public Vector2 dropRate; public Vector3 lootOffset; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag("Player"); } // Update is called once per frame void Update () { if(isDead) { Destroy(gameObject); DropLoot(); } } private void DropLoot() { // todo int a = Random.Range(0, 100); // no.0 ~ no.99 int i = -1; if(a < dropRate.x) { i = 0; }else if (a < dropRate.y) { i = 1; } else { i = 2; } StartCoroutine(DelayDropLoot()); Instantiate(loots[i], transform.position, transform.rotation); } // other script call this method. public void LoseHP(float damage) { hp -= damage; if(hp <= 0) { isDead = true; } } private void OnCollisionEnter2D(Collision2D collision) { if(collision.gameObject.CompareTag("Player")) { player.GetComponent<TakeDamage>().LoseHp(attack); } } private IEnumerator DelayDropLoot() { yield return new WaitForSeconds(0.5f); } }
d7b328706360692c611fe27ef6344b2ca3c5d9e8
C#
anycmd/anycmd
/src/Anycmd.Xacml/Runtime/Functions/BaseAtLeastOneMemberOf.cs
2.796875
3
using Anycmd.Xacml.Interfaces; using System; namespace Anycmd.Xacml.Runtime.Functions { /// <summary> /// BAse class for all the implementations of the AtLeastOneMemberOf&gt;type&lt; functions. /// </summary> public abstract class BaseAtLeastOneMemberOf : FunctionBase, ITypeSpecificFunction { #region IFunction Members /// <summary> /// Evaluates the function. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="args">The function arguments.</param> /// <returns>The result value of the function evaluation.</returns> public override EvaluationValue Evaluate( EvaluationContext context, params IFunctionParameter[] args ) { if (context == null) throw new ArgumentNullException("context"); if (args == null) throw new ArgumentNullException("args"); IFunction function = DataType.EqualFunction; foreach( object par1 in args[0].Elements ) { foreach( object par2 in args[1].Elements ) { EvaluationValue retVal = function.Evaluate( context, new EvaluationValue( par1, args[0].GetType( context ) ), new EvaluationValue( par2, args[1].GetType( context ) ) ); if( retVal.BoolValue ) { return EvaluationValue.True; } } } return EvaluationValue.False; } /// <summary> /// The data type of the return value. /// </summary> public override IDataType Returns { get{ return DataTypeDescriptor.Boolean; } } /// <summary> /// Defines the data types for the function arguments. /// </summary> public override IDataType[] Arguments { get { return new IDataType[]{ DataTypeDescriptor.Bag, DataTypeDescriptor.Bag }; } } /// <summary> /// Defines the data type for which the function was defined for. /// </summary> public abstract IDataType DataType { get; } #endregion } }
a360f346efc5e5c7b0084f7431a85346fd66c117
C#
PawelGerr/Thinktecture.Runtime.Extensions
/samples/Thinktecture.Runtime.Extensions.Benchmarking/Database/Name.cs
2.90625
3
using System; using System.ComponentModel.DataAnnotations; namespace Thinktecture.Database; [ValueObject] public sealed partial class Name { private readonly string _value; static partial void ValidateFactoryArguments(ref ValidationResult? validationResult, ref string value) { if (String.IsNullOrWhiteSpace(value)) { validationResult = new ValidationResult("Name cannot be empty."); return; } value = value.Trim(); if (value.Length < 2) validationResult = new ValidationResult("Name cannot be less than 2 characters."); } }
33db938c1e4cd91b85c86ca331930800fe9f7764
C#
gitter-badger/wham
/src/WarHub.Armoury.Model.BattleScribeXml/GuidMapping/GuidControllableBase.cs
2.59375
3
// WarHub licenses this file to you under the MIT license. // See LICENSE file in the project root for more information. namespace WarHub.Armoury.Model.BattleScribeXml.GuidMapping { using System; using System.Collections.Generic; using System.Xml.Serialization; public abstract class GuidControllableBase : IGuidControllable, INotifyGuidChanged, INotifyGuidListChanged { private GuidController _controller; /// <summary> /// Setting this property will subscribe controller to this object's events. /// </summary> [XmlIgnore] public GuidController Controller { get { return _controller; } private set { _controller = value; if (value == null) return; value.SubscribeGuidChanges(this); value.SubscribeGuidListChanges(this); } } /// <summary> /// Assigns controller to Controller. /// </summary> /// <param name="controller"></param> public virtual void Process(GuidController controller) { Controller = controller; } public event GuidChangedEventHandler GuidChanged; public event GuidListChangedEventHandler GuidListChanged; protected void TrySetAndRaise(ref List<Guid> guidList, List<Guid> newGuidList, Action<string> idSetter) { if (guidList == newGuidList) { return; } guidList = newGuidList; GuidListChanged?.Invoke(this, new GuidListChangedEventArgs(newGuidList, idSetter)); } protected void TrySetAndRaise(ref Guid guid, Guid newGuid, Action<string> idSetter) { if (guid == newGuid) { return; } guid = newGuid; GuidChanged?.Invoke(this, new GuidChangedEventArgs(newGuid, idSetter)); } } }
4042b9240b477caef3430f0dbb45c9c53713c9b6
C#
reiss-josh/wallrun
/Assets/SabreCSG/Scripts/Brushes/CompoundBrushes/TrimBrush.cs
2.515625
3
#if UNITY_EDITOR || RUNTIME_CSG using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Sabresaurus.SabreCSG { [ExecuteInEditMode] public class TrimBrush : CompoundBrush { /// <summary> /// The size of the trim. /// </summary> [SerializeField] float trimSize = 0.25f; /// <summary> /// Gets or sets the size of the trim. /// </summary> /// <value>The size of the trim.</value> public float TrimSize { get { return trimSize; } set { trimSize = value; } } /// <summary> /// Gets the beautiful name of the brush used in auto-generation of the hierarchy name. /// </summary> /// <value>The beautiful name of the brush.</value> public override string BeautifulBrushName { get { return "Trim Brush"; } } public override int BrushCount { get { // If the brush is too small for trims, just default to a single brush to not break things ok! return (localBounds.size.x > trimSize * 2.0f && localBounds.size.z > trimSize * 2.0f)?5:1; } } public override void UpdateVisibility () { } Polygon[] GeneratePolys(int index) { Polygon[] output = generatedBrushes[index].GetPolygons(); float xNorm = Mathf.Cos(index * Mathf.PI * 0.5f); float zNorm = -Mathf.Sin(index * Mathf.PI * 0.5f); Vector3 frontOuterTop = new Vector3( localBounds.center.x + (localBounds.size.x * 0.5f * xNorm) + (localBounds.size.x * 0.5f * zNorm), localBounds.max.y, localBounds.center.z + (localBounds.size.z * 0.5f * xNorm) + (localBounds.size.z * 0.5f * zNorm) ); Vector3 frontOuterBottom = frontOuterTop; frontOuterBottom.y = localBounds.min.y; Vector3 backOuterTop = new Vector3( localBounds.center.x + (localBounds.size.x * 0.5f * xNorm) + (localBounds.size.x * 0.5f * -zNorm), localBounds.max.y, localBounds.center.z + (localBounds.size.z * 0.5f * -xNorm) + (localBounds.size.z * 0.5f * zNorm) ); Vector3 backOuterBottom = backOuterTop; backOuterBottom.y = localBounds.min.y; Vector3 frontInnerTop = new Vector3( localBounds.center.x + ((localBounds.size.x - trimSize * 2.0f) * 0.5f * xNorm) + ((localBounds.size.x - trimSize * 2.0f) * 0.5f * zNorm), localBounds.max.y, localBounds.center.z + ((localBounds.size.z - trimSize * 2.0f) * 0.5f * xNorm) + ((localBounds.size.z - trimSize * 2.0f) * 0.5f * zNorm) ); Vector3 frontInnerBottom = frontInnerTop; frontInnerBottom.y = localBounds.min.y; Vector3 backInnerTop = new Vector3( localBounds.center.x + ((localBounds.size.x - trimSize * 2.0f) * 0.5f * xNorm) + ((localBounds.size.x - trimSize * 2.0f) * 0.5f * -zNorm), localBounds.max.y, localBounds.center.z + ((localBounds.size.z - trimSize * 2.0f) * 0.5f * -xNorm) + ((localBounds.size.z - trimSize * 2.0f) * 0.5f * zNorm) ); Vector3 backInnerBottom = backInnerTop; backInnerBottom.y = localBounds.min.y; // Outer Plane output[0].Vertices[0].Position = frontOuterTop; output[0].Vertices[1].Position = frontOuterBottom; output[0].Vertices[2].Position = backOuterBottom; output[0].Vertices[3].Position = backOuterTop; // Inner Plane output[1].Vertices[0].Position = frontInnerTop; output[1].Vertices[1].Position = backInnerTop; output[1].Vertices[2].Position = backInnerBottom; output[1].Vertices[3].Position = frontInnerBottom; // Top Plane output[2].Vertices[0].Position = frontInnerTop; output[2].Vertices[1].Position = frontOuterTop; output[2].Vertices[2].Position = backOuterTop; output[2].Vertices[3].Position = backInnerTop; // Bottom Plane output[3].Vertices[0].Position = frontOuterBottom; output[3].Vertices[1].Position = frontInnerBottom; output[3].Vertices[2].Position = backInnerBottom; output[3].Vertices[3].Position = backOuterBottom; // Front Plane output[4].Vertices[0].Position = frontInnerTop; output[4].Vertices[1].Position = frontInnerBottom; output[4].Vertices[2].Position = frontOuterBottom; output[4].Vertices[3].Position = frontOuterTop; // Back Plane output[5].Vertices[0].Position = backInnerBottom; output[5].Vertices[1].Position = backInnerTop; output[5].Vertices[2].Position = backOuterTop; output[5].Vertices[3].Position = backOuterBottom; for (int i = 0; i < 6; i++) { if (index % 2 == 1) Array.Reverse(output[i].Vertices); GenerateNormals(output[i]); GenerateUvCoordinates(output[i]); } return output; } /// <summary> /// Generates the UV coordinates for a <see cref="Polygon"/> automatically. /// </summary> /// <param name="polygon">The polygon to be updated.</param> private void GenerateUvCoordinates(Polygon polygon) { // stolen code from the surface editor "AutoUV". Vector3 planeNormal = polygon.Plane.normal; Quaternion cancellingRotation = Quaternion.Inverse(Quaternion.LookRotation(-planeNormal)); // Sets the UV at each point to the position on the plane for (int i = 0; i < polygon.Vertices.Length; i++) { Vector3 position = polygon.Vertices[i].Position; Vector2 uv = (cancellingRotation * position) * 0.5f; polygon.Vertices[i].UV = uv; } } private void GenerateNormals(Polygon polygon) { Plane plane = new Plane(polygon.Vertices[1].Position, polygon.Vertices[2].Position, polygon.Vertices[3].Position); foreach (Vertex vertex in polygon.Vertices) vertex.Normal = plane.normal; } public override void Invalidate (bool polygonsChanged) { base.Invalidate(polygonsChanged); for (int i = 0; i < BrushCount; i++) { generatedBrushes[i].Mode = this.Mode; generatedBrushes[i].IsNoCSG = this.IsNoCSG; generatedBrushes[i].IsVisible = this.IsVisible; generatedBrushes[i].HasCollision = this.HasCollision; } Vector3 baseSize; if (localBounds.size.x > trimSize * 2.0f && localBounds.size.z > trimSize * 2.0f) { float sizeX = localBounds.size.x - trimSize * 2.0f; float sizeZ = localBounds.size.z - trimSize * 2.0f; baseSize = new Vector3(sizeX, localBounds.size.y, sizeZ); // Build the trims here for (int i = 1; i < BrushCount; i++) { // Vector3 brushPos = localBounds.center; // brushPos.x += Mathf.Sin(i * Mathf.PI * 0.5f) * ((localBounds.size.x - trimSize) * 0.5f); // brushPos.z += Mathf.Cos(i * Mathf.PI * 0.5f) * ((localBounds.size.z - trimSize) * 0.5f); // generatedBrushes[i].transform.localPosition = brushPos; Vector3 brushSize = new Vector3(); if (i % 2 == 0) { brushSize.x = sizeX; brushSize.z = trimSize; } else { brushSize.x = trimSize; brushSize.z = sizeZ; } brushSize.y = localBounds.size.y; BrushUtility.Resize(generatedBrushes[i], brushSize); generatedBrushes[i].SetPolygons(GeneratePolys(i)); generatedBrushes[i].Invalidate(true); } } else { baseSize = localBounds.size; } generatedBrushes[0].transform.localPosition = localBounds.center; BrushUtility.Resize(generatedBrushes[0], baseSize); } } } #endif
1ff25f3dce24dc0789dd8fce5d4ce25a206ea259
C#
shendongnian/download4
/latest_version_download2/60642-11005636-28633286-4.cs
3.25
3
public class LambdaExpressionAttribute : Attribute { public LambdaExpression MyLambda { get; private set; } //ctor public LambdaExpressionAttribute(Type hostingType, string filterMethod) { MyLambda = (LambdaExpression)hostingType.GetField(filterMethod).GetValue(null); } } public class User { public bool IsAdministrator { get; set; } } public static class securityExpresions { public static readonly LambdaExpression IsAdministrator = (Expression<Predicate<User>>)(x => x.IsAdministrator); public static readonly LambdaExpression IsValid = (Expression<Predicate<User>>)(x => x != null); public static void CheckAccess(User user) { // only for this POC... never do this in shipping code System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); var method = stackTrace.GetFrame(1).GetMethod(); var filters = method.GetCustomAttributes(typeof(LambdaExpressionAttribute), true).OfType<LambdaExpressionAttribute>(); foreach (var filter in filters) { if ((bool)filter.MyLambda.Compile().DynamicInvoke(user) == false) { throw new UnauthorizedAccessException("user does not have access to: " + method.Name); } } } } public static class TheClass { [LambdaExpression(typeof(securityExpresions), "IsValid")] public static void ReadSomething(User user, object theThing) { securityExpresions.CheckAccess(user); Console.WriteLine("read something"); } [LambdaExpression(typeof(securityExpresions), "IsAdministrator")] public static void WriteSomething(User user, object theThing) { securityExpresions.CheckAccess(user); Console.WriteLine("wrote something"); } } static void Main(string[] args) { User u = new User(); try { TheClass.ReadSomething(u, new object()); TheClass.WriteSomething(u, new object()); } catch(Exception e) { Console.WriteLine(e); } }
72265be0a9af068f2fcbc2d2ce5b12d96c84eaa3
C#
MrDywar/cart-service
/src/CartService.Application/Repositories/ShoppingCartRepository.cs
2.671875
3
using CartService.Application.Services; using CartService.Domain.Entities; using Dapper; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CartService.Application.Repositories { public class ShoppingCartRepository : RepositoryBase, IShoppingCartRepository { public ShoppingCartRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } public async Task Add(ShoppingCart entity) { var sqlQuery = @"INSERT INTO ShoppingCart (CustomerId, CreatedOn, LatestUpdatedOn) VALUES (@CustomerId, @CreatedOn, @LatestUpdatedOn); SELECT SCOPE_IDENTITY()"; entity.Id = await Connection.ExecuteScalarAsync<long>(sqlQuery, entity, Transaction); } public async Task Delete(long id) { var sqlQuery = @"DELETE FROM ShoppingCart WHERE Id = @id"; await Connection.ExecuteAsync(sqlQuery, new { id }, Transaction); } public async Task DeleteByCustomerId(string customerId) { var sqlQuery = @"DELETE FROM ShoppingCart WHERE CustomerId = @customerId"; await Connection.ExecuteAsync(sqlQuery, new { customerId }, Transaction); } public async Task<ShoppingCart> GetByCustomerId(string customerId, bool includeItems = false) { if (!includeItems) { var sqlQuery = @"SELECT * FROM ShoppingCart WHERE CustomerId = @customerId"; var result = await Connection.QueryAsync<ShoppingCart>(sqlQuery, new { customerId }, Transaction); return result.FirstOrDefault(); } else { var sqlQuery = @" SELECT * FROM ShoppingCart c LEFT JOIN ShoppingCartItem ci on ci.ShoppingCartId = c.Id WHERE c.CustomerId = @customerId"; var cartItems = new List<ShoppingCartItem>(); var carts = await Connection.QueryAsync<ShoppingCart, ShoppingCartItem, ShoppingCart>( sqlQuery, (cart, cartItem) => { cartItems.Add(cartItem); return cart; }, param: new { customerId }, transaction: Transaction); var result = carts.FirstOrDefault(); if (result != null) { result.ShoppingCartItems = cartItems; } return result; } } public async Task<ShoppingCart> Get(long Id) { var sqlQuery = @"SELECT * FROM ShoppingCart WHERE Id = @Id"; var result = await Connection.QueryAsync<ShoppingCart>(sqlQuery, new { Id }, Transaction); return result.FirstOrDefault(); } public async Task Update(ShoppingCart entity) { var sqlQuery = @"UPDATE ShoppingCart SET LatestUpdatedOn = @LatestUpdatedOn WHERE Id = @Id"; await Connection.ExecuteAsync(sqlQuery, entity, Transaction); } } }
f9b0b4865bda21b26ca7798f25c747e332a6cc0a
C#
Anii92/ChatWindowsForms
/Business.Logic/LoginBusiness.cs
2.609375
3
using Common.Logic.Models; using DataAccess; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.Logic { public class LoginBusiness: ILoginBusiness { private Repository repository; public LoginBusiness() { this.repository = new Repository(); } public User Login(string userName, string password) { User user = this.repository.CheckUserAndPasswordForLogin(userName, password); if (user.Userid > 0) { this.SaveCurrentUser(user.Email); } return user; } private void SaveCurrentUser(string value) { Common.Logic.Configuration.SaveValueToAppConfig("currentUser", value); } } }
6a0fd730ae401b6c4e0c79c00ce295f8ea91b812
C#
mahal1234/InstituteMVC_Project
/InstituteMVC_Project/Controllers/SalaryController.cs
2.78125
3
using InstituteMVC_Project.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace InstituteMVC_Project.Controllers { public class SalaryController : Controller { // GET: Salary //object of the ADO.Net Model class to conect with the database for usinf the conceot of the crud InstituteDBEntities dataDB = new InstituteDBEntities(); //List Method is used to display tthe whole record from the database table public ActionResult DisplaySalary() { return View(dataDB.Salaries.ToList()); } // GET: Salary/Details/5 public ActionResult Details(int id) { return View(); } // GET: Salary/Create public ActionResult Create() { return View(); } // POST: Salary/Create //here is the coed to enter the record in the database table [HttpPost] public ActionResult Create([Bind(Exclude = "Id")]Salary StaffToPay) { if (!ModelState.IsValid) return View(); dataDB.Salaries.Add(StaffToPay); dataDB.SaveChanges(); //Response.Redirect("StudentAdmission",true); return RedirectToAction("DisplaySalary"); } // GET: Salary/Edit/5 //if we want to update the record then we must have to need the id to update public ActionResult Edit(int id) { var staffToPay = (from m in dataDB.Salaries where m.ID == id select m).First(); return View(staffToPay); } // POST: Salary/Edit/5 //after passign the id we can edit the details of the inserted record [HttpPost] public ActionResult Edit(Salary StaffToSalary) { var orignalRecord = (from m in dataDB.Salaries where m.ID == StaffToSalary.ID select m).First(); if (!ModelState.IsValid) return View(orignalRecord); dataDB.Entry(orignalRecord).CurrentValues.SetValues(StaffToSalary); dataDB.SaveChanges(); return RedirectToAction("DisplaySalary"); } // GET: Salary/Delete/5 //when we want to delete the record from the table then we must have to pass the id public ActionResult Delete(Salary StaffToDel) { var d = dataDB.Salaries.Where(x => x.ID == StaffToDel.ID).FirstOrDefault(); dataDB.Salaries.Remove(d); dataDB.SaveChanges(); return RedirectToAction("DisplaySalary"); } // POST: Salary/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } } }
9ce80a1b90de2410fb4cd8d3468724cf51fe4a36
C#
mati4ever/FPPG-CRM-v2
/UI CRM/AddTaskForm.cs
2.5625
3
using FPPG_CRM_v2; 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 UI_CRM { public partial class AddTaskForm : Form { ICaller callingForm; private PersonModel customer = new PersonModel(); public AddTaskForm(ICaller caller) { callingForm = caller; InitializeComponent(); InitializeList(); } public AddTaskForm(ICaller caller, PersonModel person) { callingForm = caller; InitializeComponent(); InitializeList(); customer_combobox.SelectedItem = person; customer_combobox.Text = person.RepresentByLastNameShort; } private void InitializeList() { customer_combobox.DataSource = null; customer_combobox.DataSource = GlobalConfig.Connection.GetPerson_All(); customer_combobox.DisplayMember = "RepresentByLastNameShort"; category_combobox.DataSource = null; category_combobox.DataSource = GlobalConfig.Connection.GetTaskCategory(); repetition_combobox.Items.Add("Brak"); repetition_combobox.Items.Add("Miesięczna"); repetition_combobox.Items.Add("Kwartalna"); repetition_combobox.Items.Add("Roczna"); repetition_combobox.Text = "Brak"; creationDate_textbox.Text = DateTime.Now.ToString("dd/MM/yyyy"); } private bool Validate() { if (customer_combobox.SelectedItem == null || category_combobox.SelectedItem == null || repetition_combobox.Text.Length ==0) { return false; } else { return true; } } private void cancel_button_Click(object sender, EventArgs e) { callingForm.LoadTaskListPanel(); } private void addTask_button_Click(object sender, EventArgs e) { DateTime date1; DateTime date2; if (DateTime.TryParseExact(creationDate_textbox.Text, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date1) && DateTime.TryParseExact(executionDate_textbox.Text, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date2)) { if (Validate()) { TaskModel task = new TaskModel(); task.Person = (PersonModel)customer_combobox.SelectedItem; task.DateOfCreation = date1; task.DateOfExecution = date2; task.Category = (string)category_combobox.SelectedItem; string note = note_textbox.Text; task.Note = GlobalConfig.Connection.ConvertNote(note); task.Repetition = GlobalConfig.Connection.ConverRepetition(repetition_combobox.Text); GlobalConfig.Connection.CreateTask(task); MessageBox.Show("Dodano zadanie"); callingForm.LoadTaskListPanel(); } else { MessageBox.Show("Wybierz klienta kategorię zadania i jego powtarzalność."); } } else { MessageBox.Show("Błędny format daty. Poprawny format: DD-MM-RRRR"); } } } }
fdd8f99e948b89a6071aa6852eac908237989174
C#
nikita262001/CinemaBuyTicket
/CinemaNick/CinemaNick/DataBase/AccountDB.cs
2.9375
3
using SQLite; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace CinemaNick { public class AccountDB { private List<Account> _startData = new List<Account> // стартовые аккаунты админов { new Account { Login ="Nick", Password = "Volk", Name = "Никита", Surname = "Волков", Patronymic = "Валерьевич", Admin = true, ImageLink =Device.RuntimePlatform == Device.Android ? "Shiro.jpg" : "Images/Shiro.jpg" }, new Account { Login ="Admin", Password = "Admin", Name = "(Пусто)", Surname = "(Пусто)", Patronymic = "(Пусто)", Admin = true, ImageLink =Device.RuntimePlatform == Device.Android ? "image10.jpg" : "Images/image10.jpg" }, }; readonly SQLiteAsyncConnection _database; public AccountDB(SQLiteAsyncConnection database) { _database = database; if (_database.Table<Account>().CountAsync().Result == 0) { IntializeData(_startData); } } private void IntializeData(IEnumerable<Account> startData) { _database.InsertAllAsync(startData); } public Task<List<Account>> GetItemsAsync() { return _database.Table<Account>().ToListAsync(); } public Task<int> SaveItemAsync(Account item) { return _database.InsertAsync(item); } public Task<int> EditItemAsync(Account item) { return _database.UpdateAsync(item); } public Task<int> DeleteItemAsync(Account item) { return _database.DeleteAsync(item); } public Task<Account> GetItemAsync(int id) { return _database.Table<Account>().Where(i => i.IdAccount == id).FirstOrDefaultAsync(); } } }
990d55c4018ec7c23d627cf2d71c6c8ab4a2e282
C#
chris24sahadeo/projects
/mopd_programming_exercise/LibraryApp/LibraryApp/Logic/BookActions.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using LibraryApp.Models; namespace LibraryApp.Logic { public class BookActions : IDisposable { private LibraryContext __db = new LibraryContext(); public bool AddBook(string book_id, string book_name, string edition, string year_published, string publisher_name, string genre_name, string cover_photo_path, string rating, string summary) { var book = new book(); book.book_id = book_id; book.book_name = book_name; book.edition = Convert.ToDecimal(edition); book.year_published = Convert.ToInt16(year_published); book.publisher_name = publisher_name; book.genre_name = genre_name; book.cover_photo_path = cover_photo_path; book.rating = Convert.ToDecimal(rating); book.summary = summary; __db.books.Add(book); __db.SaveChanges(); return true; } public bool UpdateBook(string old_id, string book_id, string book_name, string edition, string year_published, string publisher_name, string genre_name, string cover_photo_path, string rating, string summary) { var book = __db.books.Where(b => b.book_id == old_id).FirstOrDefault(); if(book != null) { book.book_id = book_id; book.book_name = book_name; book.edition = Convert.ToDecimal(edition); book.year_published = Convert.ToInt16(year_published); book.publisher_name = publisher_name; book.genre_name = genre_name; if (!string.IsNullOrEmpty(cover_photo_path)) { book.cover_photo_path = cover_photo_path; } book.rating = Convert.ToDecimal(rating); book.summary = summary; __db.Entry(book).State = System.Data.Entity.EntityState.Modified; __db.SaveChanges(); return true; } return true; } public void Dispose() { if(__db != null) { __db.Dispose(); __db = null; } } } }
19a0c174d1c96dbf3b2e8df01159a50c81fe229c
C#
RMSpratt/Design-Patterns-CSharp
/CommandPattern/Example/PlayerController.cs
2.859375
3
/* Class: PlayerController * Description: Invoker class to handle command requests and invoke them on the * receiver (Player) class. */ public class PlayerController { List<UserCommand> playerCommands; UserCommand lastCommand; public PlayerController() { playerCommands = new List<UserCommand> {}; lastCommand = new NoneCommand(); } public void AddCommand(UserCommand newCommand) { playerCommands.Add(newCommand); } public void DisableCommand(int commandIndex) { playerCommands[commandIndex] = new NoneCommand(); } public void InvokeCommand(int commandIndex) { playerCommands[commandIndex].Execute(); lastCommand = playerCommands[commandIndex]; } public void SetCommand(UserCommand newCommand, int index) { playerCommands[index] = newCommand; } public void UndoLastCommand() { lastCommand.Undo(); lastCommand = new NoneCommand(); } }
7eca226dbfa7aed7fac8710fe1db7ab325b9b0d0
C#
Kingefosa/QuickGenerate
/quickgenerate/complex/TitleGenerator.cs
3.4375
3
using System.Text; using QuickGenerate.Implementation; using QuickGenerate.Primitives; namespace QuickGenerate.Complex { public class TitleGenerator : Generator<string> { private readonly Generator<string>[] wordGenerators = new Generator<string>[] { new ChoiceGenerator<string>("I", "a", "of", "it", "the"), new CapitalizedWordGenerator(), new CapitalizedWordGenerator(), new CapitalizedWordGenerator() }; private readonly IntGenerator lengthGenerator; public TitleGenerator(int min, int max) { lengthGenerator = new IntGenerator(min, max); } public override string GetRandomValue() { var sb = new StringBuilder(); var sentenceLength = lengthGenerator.GetRandomValue(); var first = wordGenerators.PickOne().GetRandomValue().Capitalize(); sb.Append(first); sb.Append(" "); for(var i = 1; i < sentenceLength - 1; i ++) { var word = wordGenerators.PickOne().GetRandomValue(); sb.Append(word); sb.Append(" "); } var last = wordGenerators.PickOne().GetRandomValue(); sb.Append(last); return sb.ToString(); } } }
6ba339f64d50fdc7c732505e9513ea809e67b993
C#
BucurCosmin/HomeMonitor
/WebMonitor/Services/SensorsDataWeather.cs
2.96875
3
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebMonitor.Data; using WebMonitor.Models; namespace WebMonitor.Services { public class SensorsDataWeather : ISensorsDataWeather { private readonly ApplicationDbContext _context; public SensorsDataWeather(ApplicationDbContext context) { _context = context; } public void AddWeatherSensorData(WeatherData data) { MonitorData newdata = new MonitorData { Pressure = data.Pressure, Temperature = data.Temperature, Timestamp = DateTime.Now }; _context.SensorsData.Add(newdata); _context.SaveChanges(); } public WeatherData GetLastWeatherData() { MonitorData data=_context.SensorsData.Last<MonitorData>(); return new WeatherData { Temperature = data.Temperature, Pressure = data.Pressure }; } public async Task<WeatherDataViewModel> GetWeatherDataAsync(int hours) { DateTime timebegin = DateTime.Now.Subtract(new TimeSpan(hours, 0, 0)); IEnumerable<MonitorData> values= await _context.SensorsData.Where<MonitorData>(Data => Data.Timestamp > timebegin ).ToArrayAsync(); WeatherDataViewModel model = new WeatherDataViewModel(); model.WeatherDataPoints = values; return model; } } }
f2f4841c3b56a8c1f687ff2773d228f787dfc412
C#
auxo86/-
/清單式的內容/Controllers/HomeController.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using 清單式的內容.Models; namespace 清單式的內容.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { //DropDownBox ListBox //CheckBox RadioButton string[] ary1 = { "日本", "美國", "台灣", "韓國" }; ViewBag.ary1 = ary1; ViewBag.ary2 = new SelectList(ary1); ViewBag.ary3 = new SelectList(ary1, "台灣"); List<UserInfo> userlist = new List<UserInfo>() { new UserInfo(){ID=1, Name="Tony", Age=33}, new UserInfo(){ID=1, Name="Mary", Age=23}, new UserInfo(){ID=1, Name="John", Age=13} }; ViewBag.ary4 = new SelectList(userlist, "ID", "Name", userlist[0].ID); return View(); } } }
3529f9c5314e52fb49ee7602c95035f47c3b269a
C#
patschm/MOC20483C_01_2021
/Module_6/Serializers/Program.cs
3.046875
3
using Bogus; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; namespace Serializers { class Program { static void Main(string[] args) { JsonDemo(false); SerializeExercise(); DeserializeDemo(); Console.WriteLine("Done"); Console.ReadLine(); } private static void DeserializeDemo() { FileStream fs = File.OpenRead("E:\\people.xml"); XmlSerializer ser = new XmlSerializer(typeof(List<Person>)); var people = ser.Deserialize(fs) as List<Person>; foreach (Person p in people) { p.Introduce(); } } private static void SerializeExercise() { List<Person> people = CreatePeople(); //foreach(Person p in people) //{ // p.Introduce(); //} FileStream fs = File.Create("E:\\people.xml"); XmlSerializer ser = new XmlSerializer(typeof(List<Person>)); ser.Serialize(fs, people); fs.Close(); } private static List<Person> CreatePeople() { var faker = new Faker<Person>(); return faker .RuleFor(p=>p.ID, f=>f.IndexFaker) .RuleFor(p=>p.Age, f=>f.Random.Int(0, 123)) .RuleFor(p=>p.FirstName, f=>f.Name.FirstName()) .RuleFor(p=>p.LastName, f=>f.Name.LastName()) .Generate(1000) .ToList(); } private static void JsonDemo(bool read) { if (!read) { Person p = new Person { FirstName = "Joan", LastName = "Groen", Age = 34 }; //p.Introduce(); FileStream fs = File.Create("E:\\person.json"); StreamWriter writer = new StreamWriter(fs); JsonSerializer ser = new JsonSerializer(); ser.ContractResolver =new DefaultContractResolver { NamingStrategy = new KebabCaseNamingStrategy() }; ser.Serialize(writer, p); writer.Flush(); } else { FileStream fs = File.OpenRead("E:\\person.json"); StreamReader rdr = new StreamReader(fs); JsonSerializer ser = new JsonSerializer(); Person p = ser.Deserialize(rdr, typeof(Person)) as Person; p.Introduce(); } } } }
523cac0e38aec4e7ed49401d75baa829af9a9062
C#
delapiero/csharp-design-patterns
/Obserwator/ObserwatorB.cs
2.71875
3
using OxyPlot; using OxyPlot.Axes; using OxyPlot.Series; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Obserwator { public class ObserwatorB: IObserwator, INotifyPropertyChanged { public PlotModel Model { get; set; } public bool Aktywny { get; set; } public ObserwatorB() { Aktywny = true; } public void Aktualizuj(IObiektObserwowany o) { if (Aktywny) { Model = new PlotModel(); IList<double> wartosci = (o as Obserwowany).wartosci; CategoryAxis osx = new CategoryAxis(); LinearAxis osy = new LinearAxis(); ColumnSeries series = new ColumnSeries(); int size = wartosci.Count; for (int i = 0; i < size; ++i) { // dodanie wartosci series.Items.Add( new ColumnItem( wartosci.ElementAt(i), i )); // dodanie kolumny osx.Labels.Add(((char)(65 + i)).ToString()); } Model.Axes.Add(osx); Model.Axes.Add(osy); Model.Series.Clear(); Model.Series.Add(series); OnPropertyChanged("Model"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
c1bb61c34b40b7f7fe68308745a8eea7366ec4ab
C#
EugenMayer/mvvmcrossDAL
/Utils/ModelChangedEvent.cs
2.640625
3
using System; namespace Cirrious.CrossCore.MvvmCrossDAL { public delegate void ModelChangedEventHandler(object sender,ModelChangedEventArgs args); public enum ModelChangeOperation { Add, Update, Delete, DeleteAll } public class ModelChangedEventArgs: EventArgs { private object _newModel; private ModelChangeOperation _operation; public ModelChangedEventArgs(object newModel, ModelChangeOperation operation) { _newModel = newModel; _operation = operation; } public object NewModel { get { return _newModel; } } public ModelChangeOperation Operation { get { return _operation; } } } }
2440b2dd38cee540a32f695b1e0d0fdf62e15f32
C#
PALNI/MAgPIE
/Shared Library/Pipeline/CountingEnumerable.cs
3.015625
3
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; namespace ZondervanLibrary.SharedLibrary.Pipeline { public class CountingEnumerable<T> : IEnumerable<T> { private readonly IEnumerable<T> _enumerable; public CountingEnumerable(IEnumerable<T> enumerable) { Contract.Requires(enumerable != null); _enumerable = enumerable; } public Int32 Count { get; private set; } /// <inheritdoc/> public IEnumerator<T> GetEnumerator() { Count = 0; foreach (T item in _enumerable) { Count++; yield return item; } } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static class CountingEnumerable { public static CountingEnumerable<T> Wrap<T>(IEnumerable<T> enumerable) { return new CountingEnumerable<T>(enumerable); } } }
10b6ccf5d5e1d0b807c65abcdf29538c92f7276d
C#
nodoid/GridClick
/GridClick/GridClick/GridClickPage.cs
2.765625
3
using System; using System.Collections.Generic; using Xamarin.Forms; namespace GridClick { public class GridClickPage : ContentPage { public GridClickPage() { if (Device.OS == TargetPlatform.iOS) Padding = new Thickness(0, 20, 0, 0); BackgroundColor = Color.Green; CreateUI(); } void CreateUI() { var numbers = new List<string> { "ace", "2", "3","4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king" }; var hands = new List<string> { "spades", "hearts", "clubs", "diamonds" }; var cards = new List<string>(); foreach (var h in hands) { foreach (var n in numbers) cards.Add(string.Format("{0}_of_{1}.png", n, h)); } var gridStack = new StackLayout { Orientation = StackOrientation.Horizontal, WidthRequest = App.ScreenSize.Width, VerticalOptions = LayoutOptions.Start, Padding = new Thickness(0, -8, 0, 0) }; var grid = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand, Padding = new Thickness(6, 0, 6, 4), RowDefinitions = { new RowDefinition { Height = GridLength.Auto }, }, ColumnDefinitions = { new ColumnDefinition { Width = App.ScreenSize.Width * .3 }, new ColumnDefinition { Width = App.ScreenSize.Width * .3 }, new ColumnDefinition { Width = App.ScreenSize.Width * .3 }, } }; int left = 0, top = 0; foreach (var pl in cards) { var imgProduct = new CustomImage { Source = Device.OS == TargetPlatform.Windows ? "Assets/" + pl : pl, VerticalOptions = LayoutOptions.Start, WidthRequest = App.ScreenSize.Width * .27 }; imgProduct.SizeChanged += (object sender, EventArgs e) => { if (imgProduct.Height > 152) imgProduct.HeightRequest = Device.OS == TargetPlatform.iOS ? 130 : imgProduct.Height; if (imgProduct.Height < 130) imgProduct.HeightRequest = Device.OS == TargetPlatform.iOS ? 130 : 152; }; var lblText = new Label { Text = pl.Split('.')[0], TextColor = Color.Blue, HorizontalTextAlignment = TextAlignment.Center, FontSize = 14 }; var stack = new StackLayout { Orientation = StackOrientation.Vertical, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Start, WidthRequest = App.ScreenSize.Width * .33, HeightRequest = App.ScreenSize.Height * .3, BackgroundColor = Color.White, Spacing = 0.4, StyleId = lblText.Text, Children = { new StackLayout { VerticalOptions = LayoutOptions.CenterAndExpand, Children = { imgProduct, new StackLayout { Padding = new Thickness(0, -4, 0, 0), Children = { lblText } }, } } } }; var stackTap = new TapGestureRecognizer { NumberOfTapsRequired = 1, Command = new Command(async (t) => { await DisplayAlert("Clicked", "You've just clicked the " + stack.StyleId.Split('.')[0].Replace('_', ' '), "OK"); }) }; stack.GestureRecognizers.Add(stackTap); grid.Children.Add(stack, left, top); left++; if (left == 3) { left = 0; top++; grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); } } gridStack.Children.Add(new ScrollView { VerticalOptions = LayoutOptions.FillAndExpand, Content = grid }); Content = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand, Children = { gridStack } }; } } }
29aeda3899eaaa3d01e25f8cfbc9e18908b664e5
C#
shendongnian/download4
/first_version_download2/115954-8047688-17917947-2.cs
2.6875
3
public bool EndOfStream { get { if (this.stream == null) { __Error.ReaderClosed(); } if (this.charPos < this.charLen) { return false; } int num = this.ReadBuffer(); return num == 0; } }
a885f864fe8c35a891906c0b0dba619810e10d39
C#
dotnatcore/dotvuecore
/src/DotVueCore.SockJs/Route.cs
2.515625
3
using System.Text.RegularExpressions; namespace DotVueCore.SockJs { internal class Route { public Route(string method, int type, bool regex, string match, SessionHttpContextHandler handler) { Method = method; Type = type; if (regex) { RegEx = new Regex(match); } else { Raw = match; } Handler = handler; } public string Method { get; set; } public int Type { get; set; } public Regex RegEx { get; set; } public string Raw { get; set; } public SessionHttpContextHandler Handler { get; set; } } }
7eafcb06b7db01cb725c1d692c26d43f892c947f
C#
jjzhang166/tkSim
/Assets/scripts/ColliderToChildrens.cs
2.59375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ColliderToChildrens : MonoBehaviour { // Use this for initialization void Start () { // Iterate through all child objects of our Geometry object foreach (Transform childObject in transform) { // First we get the Mesh attached to the child object Mesh mesh = childObject.gameObject.GetComponent<MeshFilter>().mesh; // If we've found a mesh we can use it to add a collider if (mesh != null) { // Add a new MeshCollider to the child object MeshCollider meshCollider = childObject.gameObject.AddComponent<MeshCollider>(); // Finaly we set the Mesh in the MeshCollider meshCollider.sharedMesh = mesh; } } } // Update is called once per frame void Update () { } }
82664ab10613b04804dc08e98e6dd865f2973001
C#
OpenRIAServices/OpenRiaServices
/src/VisualStudio/Templates/CSharp/BusinessApplication/Assets/Resources/ApplicationResources.cs
2.546875
3
namespace $safeprojectname$ { using System; using System.ComponentModel; using System.Globalization; using System.Windows.Browser; /// <summary> /// Wraps access to the strongly-typed resource classes so that you can bind control properties to resource strings in XAML. /// </summary> public sealed class ApplicationResources { private static readonly ApplicationStrings applicationStrings = new ApplicationStrings(); private static readonly ErrorResources errorResources = new ErrorResources(); /// <summary> /// Gets the <see cref="ApplicationStrings"/>. /// </summary> public ApplicationStrings Strings { get { return applicationStrings; } } /// <summary> /// Gets the <see cref="ErrorResources"/>. /// </summary> public ErrorResources Errors { get { return errorResources; } } } }
ce6f4878e726ffcfef343e5a4bc9963acc3fe6d8
C#
masaru-b-cl/ngtnet2-fizzbuzz
/FizzBuzz.Test/FizzBuzzTest.cs
3.0625
3
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FizzBuzz.Test { [TestClass] public class FizzBuzzTest { private FizzBuzzer fizzBuzzer; [TestInitialize] public void SetUp() { fizzBuzzer = new FizzBuzzer(); } [TestMethod] public void 引数が正の数の場合文字列でその数を返す() { fizzBuzzer.Say(1).Is("1"); } [TestMethod] public void 引数が3の倍数の場合Fizzを返す() { fizzBuzzer.Say(3).Is("Fizz"); } } }
4e1eb202c4a355aafdd900e6c77200832a2e1766
C#
jeisonnunez/Portafolio-Proyectos
/LoginSystem/PresentacionWPF/Gestion/ModelTipoCambio/ModelTipoCambio.cs
2.578125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Vista.Clases_Basicas; namespace Vista.Gestion.ModelTipoCambio { public class ModelTipoCambio: INotifyPropertyChangeObservable,IDataErrorInfo { public string Error { get { return null; } } private string rateDate; private string currency; private string usd; private string selectedValueYear; private string selectedValueMonth; public string SelectedValueYear { get { return selectedValueYear; } set { if (value != selectedValueYear) { selectedValueYear = value; //notify the binding that my value has been changed OnPropertyChanged("SelectedValueYear"); } } } public string SelectedValueMonth { get { return selectedValueMonth; } set { if (value != selectedValueMonth) { selectedValueMonth = value; //notify the binding that my value has been changed OnPropertyChanged("SelectedValueMonth"); } } } public string RateDate { get { return rateDate; } set { if (value != rateDate) { rateDate = value; //notify the binding that my value has been changed OnPropertyChanged("RateDate"); } } } public string USD { get { return usd; } set { if (value != usd) { usd = value; //notify the binding that my value has been changed OnPropertyChanged("USD"); } } } public string Currency { get { return currency; } set { if (value != currency) { currency = value; //notify the binding that my value has been changed OnPropertyChanged("Currency"); } } } public string this[string name] { get { string result = null; switch (name) { case "Currency": if (string.IsNullOrWhiteSpace(Currency)) result = "Codigo de moneda no puede estar vacio"; else if (Currency.Length > 3) result = "Codigo de moneda no debe exceder la cantidad de caracteres de 3"; break; case "RateDate": if (string.IsNullOrWhiteSpace(RateDate)) result = "Fecha no puede estar vacio"; break; case "USD": if (string.IsNullOrWhiteSpace(USD)) { result = "Entrada invalidad"; } else if (ConvertToDecimal(USD) == false) result = "Entrada invalidad"; else if (NumericValidator(USD) == false) result = "Cantidad de enteros no debe exceder los 19 y decimales no debe exceder los 6 "; break; case "SelectedValueYear": if (string.IsNullOrWhiteSpace(SelectedValueYear)) { result = "Año no puede estar vacio"; } break; case "SelectedValueMonth": if (string.IsNullOrWhiteSpace(SelectedValueMonth)) { result = "Mes no puede estar vacio"; } break; } return result; } } private int userSign; public int UserSign { get => userSign; set => userSign = value; } } }
8be9c8be64aec36dae73cb7e09401871baa9344c
C#
alexjo24/Learning_C_Sharp
/Algorithms/SelectionSort/Program.cs
3.703125
4
using System; namespace Program { class Program { static void Main(string[] args) { Random rnd = new Random(); int Min = -100; int Max = 100; int[] randomArr = new int[Max]; for (int i = 0; i < Max; i++){ randomArr[i] = rnd.Next(Min,Max); } System.Console.WriteLine("\nArray to be sorted: "); foreach (int el in randomArr){ System.Console.Write(el + " "); } System.Console.WriteLine("\nSize of array: " + randomArr.Length); int[] sortedArr = SelectionSort.Run(randomArr); System.Console.WriteLine("\nSorted Array in Ascending order : "); foreach (int el in sortedArr){ System.Console.Write(el + " "); } } } }
fe4e0c17bb94f89e81dd5c3d4d46a676cee8afd3
C#
Komplementariteten/dotnet
/conture-detect/Image/BmpTypes.cs
2.59375
3
using System.Runtime.InteropServices; using System.Text; namespace Image { [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BmpFileHeader { public ushort BfType; public uint BfSize; public uint BfReserved; public uint BfOffBits; public override string ToString() { var sb = new StringBuilder(); sb.Append($"Type:\t\t {this.BfType}, 0x{this.BfType:X2}\n"); sb.Append($"Size:\t\t {this.BfSize}, 0x{this.BfSize:X2}\n"); sb.Append($"Reserved:\t {this.BfReserved}, 0x{this.BfReserved:X2}\n"); sb.Append($"Offset:\t\t {this.BfOffBits}, 0x{this.BfOffBits:X2}\n"); return sb.ToString(); } } public static class Consts { public static unsafe int BmpFileHeaderSize = sizeof(BmpFileHeader); public static unsafe int BmpFileInfoSize = sizeof(BmpFileInfo); public static unsafe int RGBASize = sizeof(RGBA); } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BmpFileInfo { public uint BiSize; public int BiWidth; public int BiHeight; public ushort BiPlanes; public ushort BiBitCount; public uint BiCompression; public uint BiSizeImage; public int BiXPelsPerMeter; public int BiYPelsPerMeter; public uint BiCrlUsed; public uint BiClrImportant; public override string ToString() { var sb = new StringBuilder(); sb.Append($"Size:\t\t {this.BiSize}, 0x{this.BiSize:X2}\n"); sb.Append($"Width:\t\t {this.BiWidth}, 0x{this.BiWidth:X2}\n"); sb.Append($"Height:\t\t {this.BiHeight}, 0x{this.BiHeight:X2}\n"); sb.Append($"Planes:\t\t {this.BiPlanes}, 0x{this.BiPlanes:X2}\n"); sb.Append($"BitCount:\t {this.BiBitCount}, 0x{this.BiBitCount:X2}\n"); sb.Append($"Compression:\t {this.BiCompression}, 0x{this.BiCompression:X2}\n"); sb.Append($"ImageSize:\t {this.BiSizeImage}, 0x{this.BiSizeImage:X2}\n"); sb.Append($"XPels:\t\t {this.BiXPelsPerMeter}, 0x{this.BiXPelsPerMeter:X2}\n"); sb.Append($"YPels:\t\t {this.BiYPelsPerMeter}, 0x{this.BiYPelsPerMeter:X2}\n"); sb.Append($"ColorTable:\t {this.BiCrlUsed}, 0x{this.BiCrlUsed:X2}\n"); sb.Append($"Import:\t\t {this.BiClrImportant}, 0x{this.BiClrImportant:X2}\n"); return sb.ToString(); } } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RGBA { public byte Blue; public byte Green; public byte Red; public byte Alpha; public override string ToString() { return $"r:{this.Red:X2}, g:{this.Green:X2}, b:{this.Blue:X2}, a:{this.Alpha:X2}"; } public void SetColor(int color) { this.Red = (byte)((color & 0xff0000) >> 16); this.Green = (byte)((color & 0xff00) >> 8); this.Blue = (byte)(color & 0xff); } } public readonly ref struct CBitmap { public readonly BmpFileHeader Head; public readonly BmpFileInfo Info; public readonly RGBA[] Pixel; public int AbsWidth => Math.Abs(this.Info.BiWidth); public int AbsHeight => Math.Abs(this.Info.BiHeight); public CBitmap(BmpFileHeader header, BmpFileInfo info, RGBA[] rgba) { this.Head = header; this.Info = info; this.Pixel = rgba; } public override string ToString() { var sb = new StringBuilder(); foreach (var p in this.Pixel) { sb.AppendLine(p.ToString()); } return sb.ToString(); } public void DrawHorizontalLine(int row, int startX, int endX, int color) { var offset = (row * this.AbsWidth) + startX; var length = endX - startX; for (int i = 0; i < length; i++) { this.Pixel[offset + i].SetColor(color); } } public void DrawVerticalLine(int x, int startY, int endY, int color) { var length = endY - startY; var offset = (startY * this.AbsWidth); for (int i = 0; i < length; i++) { var index = (i * this.AbsWidth) + offset + x; this.Pixel[index].SetColor(color); } } public unsafe void Save(string path) { Span<BmpFileHeader> head = stackalloc BmpFileHeader[1]; head[0] = this.Head; var headBytes = MemoryMarshal.AsBytes<BmpFileHeader>(head); Span<BmpFileInfo> info = stackalloc BmpFileInfo[1]; info[0] = this.Info; var infoBytes = MemoryMarshal.AsBytes<BmpFileInfo>(info); Span<RGBA> rgb = stackalloc RGBA[this.Pixel.Length]; for (int i = 0; i < this.Pixel.Length; i++) { rgb[i] = this.Pixel[i]; } var rgbBytes = MemoryMarshal.AsBytes<RGBA>(rgb); Span<byte> bytes = stackalloc byte[(int)this.Head.BfSize]; headBytes.CopyTo(bytes.Slice(0)); infoBytes.CopyTo(bytes.Slice(Consts.BmpFileHeaderSize)); rgbBytes.CopyTo(bytes.Slice((int)this.Head.BfOffBits)); File.WriteAllBytes(path, bytes.ToArray()); } } }
dbd6c11125a00f5de1a76d9ec0278eca847f25b6
C#
Engin-Boot/modularity-c-AleenaSaleem
/TelCo.ColorCoder/ColorCode.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Drawing; namespace Telco.ColorCoder { class ColorCode { internal static Color[] colorMapMajor; internal static Color[] colorMapMinor; internal class ColorPair { internal Color majorColor; internal Color minorColor; public override string ToString() { return string.Format("MajorColor:{0}, MinorColor:{1}", majorColor.Name, minorColor.Name); } } static ColorCode() { colorMapMajor = new Color[] { Color.White, Color.Red, Color.Black, Color.Yellow, Color.Violet }; colorMapMinor = new Color[] { Color.Blue, Color.Orange, Color.Green, Color.Brown, Color.SlateGray }; } } }
2237586a8c800ad9b2ac9c050bdc835c47f63c0f
C#
Peter-Georgiev/Programming.Fundamentals
/ArraysAndMethods-Exercises/04.NthDigit/NthDigit.cs
3.96875
4
using System; class NthDigit { static void Main() { int readInteger = int.Parse(Console.ReadLine()); int index = int.Parse(Console.ReadLine()); byte result = FindNthDigit(readInteger, index); PrintNthDigit(result); } static byte FindNthDigit(long readInteger, int index) { long result = 0; while (index > 0) { result = readInteger % 10; readInteger /= 10; index--; } return (byte)result; } static void PrintNthDigit(byte result ) { Console.WriteLine(result); } }
4a500b48a23297af18e5c70fdfc01ee281033e15
C#
konolga/bowling-game
/ServerAPI/Controllers/UsersController.cs
2.5625
3
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ServerAPI.Data; using ServerAPI.Infrastructure; using System.Collections.Generic; using Microsoft.Extensions.Logging; namespace ServerAPI.Controllers { [ApiController] [Route("api/[controller]")] public class UsersController : ControllerBase { private readonly IUsersRepo _repo; private readonly ILogger<UsersController> _logger; public UsersController(IUsersRepo repo, ILogger<UsersController> logger) { _repo = repo; _logger = logger; } [HttpPost] public async Task<IActionResult> CreateUser([FromForm] string username) { var user = await _repo.GetUserByUsername(username); if (user == null) { user = new User() {Username = username}; await _repo.CreateUser(user); }; return Ok(user); } [HttpPut("{id}")] public async Task<IActionResult> UpdateUser([FromForm] User user, int id) { if (await _repo.UpdateUser(user)) return Ok(); return BadRequest($"Updating user id {id} failed on save"); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteUser(string id) { await _repo.DeleteUser(id); return NoContent(); } } }
9f2d0f1e9d1ecf63e23b46cab5bb3f58b505b70b
C#
devsinsight/santex.league
/Santex.League.Repository/Repository.cs
2.8125
3
using Microsoft.EntityFrameworkCore; using Santex.League.Domain.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Santex.League.Repository { public class Repository<T> : IRepository<T> where T : class { private DbContext _context; public DbSet<T> dbSet; public Repository(DbContext context) { _context = context; dbSet = context.Set<T>(); } public async Task Create(params T[] items) { foreach (T item in items) await _context.Set<T>().AddAsync(item); } public Task Update(params T[] items) { foreach (T item in items) _context.Set<T>().Update(item); return Task.CompletedTask; } public Task Remove(params T[] items) { foreach (T item in items) _context.Set<T>().Remove(item); return Task.CompletedTask; } public virtual IList<T> GetAll(params Expression<Func<T, object>>[] navigationProperties) { IQueryable<T> dbQuery = dbSet; foreach (Expression<Func<T, object>> navigationProperty in navigationProperties) dbQuery = dbQuery.Include(navigationProperty); return dbQuery.ToList<T>(); } public virtual IList<T> GetList(Expression<Func<T, bool>> where, params Expression<Func<T, object>>[] navigationProperties) { IQueryable<T> dbQuery = dbSet; foreach (Expression<Func<T, object>> navigationProperty in navigationProperties) dbQuery = dbQuery.Include(navigationProperty); dbQuery = dbQuery.Where(where); return dbQuery.ToList<T>(); } public virtual T GetSingle(Func<T, bool> where, params Expression<Func<T, object>>[] navigationProperties) { IQueryable<T> dbQuery = dbSet; foreach (Expression<Func<T, object>> navigationProperty in navigationProperties) dbQuery = dbQuery.Include(navigationProperty); return dbQuery.FirstOrDefault(where); } } }
375148b0655a939f8e336e30b7cfae9fdbdb8d5e
C#
NaylonBrando/engdemrg-ders-3-dot-net-core
/OOP2/Customer.cs
2.65625
3
using System; using System.Collections.Generic; using System.Text; namespace OOP2 { class Customer { //Classlarda özellik ve operasyon tutarız. //Özellik tututlan yerde operasyon tutulmamalı, operasyon tutulan yerde özellik tutulmamalı. //Özellik tutulan Classlar varlıktır. public int Id { get; set; } public string CustomerNo { get; set; } //Not: eğer veri sayısal işleme tabi tutmayacaksanız, string tutmak daha iyidir //Farklı sistemlerle veri uyumsuzluğu olmasın diye böyle tutarız! //Bir nesnede bir değeri kullanmak zorunda gibi görmüyorsam, o nesneye ait görmüyorsam soyutlama hatası yapmısız deriz. //public string TcNo { get; set; } //public string Name { get; set; } //public string Surname { get; set; } //public string CompanyName { get; set; } //public string VergiNo { get; set; } //gerçek ve tüzel müşterileri birbirinin yerine kullanmamalıyız. //gidipte müsteritipi diye de özellik koymak da hatalıdır! //Bu dediklerimiz SOLID yazılım geliştirme prensiplerinden gelir } }
5a438d59a224eb15fed87da505d64717716b99a9
C#
marcosdosea/CatalogarPatrimonio
/Codigo/CatalogarPatrimonio/Service/DialogoServicoService.cs
2.65625
3
using Core; using Core.DTO; using Core.Service; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Service { public class DialogoservicoService : IDialogoservicoService { private readonly CatalogarPatrimonioContext _context; public DialogoservicoService(CatalogarPatrimonioContext context) { _context = context; } public int Inserir(Dialogoservico dialogoServico) { _context.Add(dialogoServico); _context.SaveChanges(); return dialogoServico.Id; } public void Editar(Dialogoservico dialogoServico) { _context.Update(dialogoServico); _context.SaveChanges(); } public void Remover(int idDialogoServico) { var _dialogoServico = _context.Dialogoservico.Find(idDialogoServico); _context.Dialogoservico.Remove(_dialogoServico); _context.SaveChanges(); } public int GetNumeroDialogo() { return _context.Dialogoservico.Count(); } private IQueryable<Dialogoservico> GetQuery() { IQueryable<Dialogoservico> tb_dialogoServico = _context.Dialogoservico; var query = from dialogoServico in tb_dialogoServico select dialogoServico; return query; } public IEnumerable<Dialogoservico> ObterPorNome(string mensagem) { IEnumerable<Dialogoservico> dialogoServico = GetQuery() .Where(dialogoServicoModel => dialogoServicoModel.Mensagem. StartsWith(mensagem)); // seria melhor idpessoa? return dialogoServico; } public IEnumerable<Dialogoservico> ObterTodos() { return GetQuery(); } public Dialogoservico Obter(int idDialogoServico) { IEnumerable<Dialogoservico> dialogoServico = GetQuery().Where(dialogoServicoModel => dialogoServicoModel.Id.Equals(idDialogoServico)); return dialogoServico.ElementAtOrDefault(0); } } }