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
508dd4e2d457db842c5bba3c683fc7d2e588b521
C#
HanseSecure/Projects-MS-SQL-Server-DBA
/MailOutExcel/ExcelBiblio/CWorkbook.cs
3.0625
3
using System; namespace ExcelBiblio { public class CWorkbook : IDisposable { protected dynamic __workbook; protected CWorkbook() { } public CWorkbook(dynamic workbook) { this.__workbook = workbook; } ~CWorkbook() { Dispose(); } public void Dispose() { if (__workbook != null) { __workbook.Close(true); __workbook = null; } } public void SaveAs(string path) { this.__workbook.SaveAs(path); } public void Save() { this.__workbook.Save(); } public ProfiCreditWorksheet ActiveSheet { get { return new ProfiCreditWorksheet(this.__workbook.ActiveSheet); } } public class ProfiCreditWorksheet { protected dynamic __worksheet; protected ProfiCreditWorksheet() { } public ProfiCreditWorksheet(dynamic worksheet) { this.__worksheet = worksheet; } public object GetCells(int row, int col) { return this.__worksheet.Cells[row, col].Value; } public void SetCells(int row, int col, object val) { this.__worksheet.Cells[row, col].Value = val; } public void RowDelete(int row) { this.__worksheet.Rows(row).Delete(); } } } }
78a3941829780486ddfd1bfd3ba321ede9fc903a
C#
PJATK-EPG-SNM/S18620_Prace_Domowe
/Praca_Domowa_01/Assets/Scripts/Rotation.cs
2.625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotation : MonoBehaviour { bool started; // Start is called before the first frame update void Start() { StartCoroutine(Move()); } // Update is called once per frame public float speed; public bool left; void Update() { if ((left == true) && (started == true)) { transform.Rotate(Vector3.forward * speed * Time.deltaTime); } else { transform.Rotate(Vector3.back * speed * Time.deltaTime); } } IEnumerator Move() { started = false; yield return new WaitForSeconds(0.9f); started = true; } }
b76372c9e6a04027374fcfbf6d9b13205c56b9df
C#
dogasp/Projets
/FinCoursApp code source/FinCoursAppV2/FinCoursAppV2/Graphe.xaml.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microcharts; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SkiaSharp; namespace FinCoursAppV2 { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Graphe : ContentPage { Random r = new Random(); List<ChartEntry> entries; public Graphe (IDictionary<string, TimeSpan> Others_Total, List<Date> Dates) { InitializeComponent (); var Daily_Total = Others_Total.ToDictionary(entry => entry.Key, entry => entry.Value); //copie du dictionnaire des jours suivants TimeSpan EndingDay = new TimeSpan(); //calcul des temps de la journée DateTime Current = DateTime.Now; if (Current.DayOfWeek != DayOfWeek.Saturday && Current.DayOfWeek != DayOfWeek.Sunday && 18 >= Current.Hour && Current.Hour >= 8) { foreach (Date ToTest in Dates) { if (ToTest.day == Current.DayOfWeek && ToTest.start < Current.TimeOfDay && ToTest.end.TimeOfDay > Current.TimeOfDay) { TimeSpan gap = ToTest.end.TimeOfDay - Current.TimeOfDay; Daily_Total[ToTest.matter] += gap; EndingDay += gap; } else if (ToTest.day == Current.DayOfWeek && ToTest.date.TimeOfDay > Current.TimeOfDay) { Daily_Total[ToTest.matter] += ToTest.duration; EndingDay += ToTest.duration; } } } entries = new List<ChartEntry>(); foreach (KeyValuePair<string, TimeSpan> entry in Daily_Total) { entries.Add( new ChartEntry((float)entry.Value.TotalHours) { Label = entry.Key, ValueLabel = entry.Value.ToString(@"hh\:mm\:ss"), Color = SKColor.Parse(String.Format("#{0:X6}", r.Next(0x1000000))) } ); } entries.Sort((x, y) => y.ValueLabel.CompareTo(x.ValueLabel)); Create_Chart(entries); Device.StartTimer(TimeSpan.FromMilliseconds(900), () => { Daily_Total = Others_Total.ToDictionary(entry => entry.Key, entry => entry.Value); //copie du dictionnaire des jours suivants EndingDay = new TimeSpan(); //calcul des temps de la journée Current = DateTime.Now; if (Current.DayOfWeek != DayOfWeek.Saturday && Current.DayOfWeek != DayOfWeek.Sunday && 18 >= Current.Hour && Current.Hour >= 8) { foreach (Date ToTest in Dates) { if (ToTest.day == Current.DayOfWeek && ToTest.start < Current.TimeOfDay && ToTest.end.TimeOfDay > Current.TimeOfDay) { TimeSpan gap = ToTest.end.TimeOfDay - Current.TimeOfDay; Daily_Total[ToTest.matter] += gap; EndingDay += gap; } else if (ToTest.day == Current.DayOfWeek && ToTest.date.TimeOfDay > Current.TimeOfDay) { Daily_Total[ToTest.matter] += ToTest.duration; EndingDay += ToTest.duration; } } } if (DateTime.Now.Second == 0) { entries = new List<ChartEntry>(); foreach (KeyValuePair<string, TimeSpan> entry in Daily_Total) { entries.Add( new ChartEntry((float)entry.Value.TotalHours) { Label = entry.Key, ValueLabel = entry.Value.ToString(@"hh\:mm\:ss"), Color = SKColor.Parse(String.Format("#{0:X6}", r.Next(0x1000000))) } ); } entries.Sort((x, y) => y.ValueLabel.CompareTo(x.ValueLabel)); Create_Chart(entries); } return true; }); } private void Create_Chart(List<ChartEntry> entries) { chartView.Chart = new DonutChart() { Entries = entries, HoleRadius = .5f, LabelTextSize = 35 }; } private async void NavigateButton_OnClicked(object sender, EventArgs e) { await Navigation.PopAsync(); } } }
3b68a6557a60a85408a7be55861e8b94d933179c
C#
rev3r/ProperHelloWorld
/tests/FunctionalTests/DisplayHelloWorld.cs
2.78125
3
using System; using System.IO; using ConsoleApp; using Xunit; namespace FunctionalTests { public class DisplayHelloWorld { [Fact] public void Invokation_DisplaysHelloWorld() { using (var sw = new StringWriter()) { Console.SetOut(sw); Program.Main(); var expected = string.Format("Hello World!" + Environment.NewLine); Assert.Equal(expected, sw.ToString()); } } } }
72ada04afef3a6590e4f0f9aaa1447369fd55328
C#
TobiasSjoholm1995/Csharp_Practice
/FacadePattern/CarFacade.cs
3.21875
3
using System; namespace FacadePattern { public class CarFacade { private Engine engine; private SubEngine subEngine; private Body body; private Tires tires; public CarFacade() { tires = new Tires(); subEngine = new SubEngine(); body = new Body(); // Handle the injection, in some cases these dependencies and injection are complexed. // So handling everything in the facade makes it easer for client. engine = new Engine(subEngine); } public void CreateCompleteCar() { Console.WriteLine("********** Creating Car **********\n"); tires.SetTires(); engine.SetEngine(); body.SetBody(); Console.WriteLine("\n********** Car complete **********"); } } }
bfd5e15537584a0e5325a2de427ee912616d8db6
C#
IchanskijOleg/FirstStepGit
/ConAppIteaLes6/ConAppIteaLes6/Adress.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConAppIteaLes6 { class Adress { /*private string index; private string country; private string street; private string house; private string apartment;*/ public string Index { get; } public string Country { get; } public string Street { get; } public string House { get; } public string Apartment { get; } public Adress(string index, string country, string street, string house, string apartment) { Index = index; Country = country; Street = street; House = house; Apartment = apartment; } public void PrintAdress() { Console.WriteLine("Індекс {0}, місто {1}, вулиця {2}, будинок {3}, квартира {4}", Index, Country, Street, House, Apartment); } } }
4544d87225d6f2248974ecbd9ef1af78a4c0d953
C#
BryanTai/ggj2021
/Assets/Scripts/Interactable.cs
2.765625
3
using UnityEngine; using UnityEngine.AI; /* This component is for all objects that the player can interact with such as enemies, items etc. It is meant to be used as a base class. */ //[RequireComponent(typeof(ColorOnHover))] public class Interactable : MonoBehaviour { public float radius = 1f; public Transform interactionTransform; public Transform player; // Reference to the player transform public bool hasInteracted = false; // Have we already interacted with the object? private void Awake() { player = GameObject.Find("Player").transform; } void Update () { /* float distance = Vector3.Distance(player.position, interactionTransform.position); // If we haven't already interacted and the player is close enough if (!hasInteracted && distance <= radius) { // Interact with the object hasInteracted = true; Interact(); } */ } // This method is meant to be overwritten public virtual void Interact () { Debug.Log("Interacting with " + transform.name); } void OnDrawGizmosSelected () { if (interactionTransform == null) interactionTransform = transform; Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(interactionTransform.position, radius); } }
d8475c2f6b9415b873949d2255a3038fe964b1df
C#
particleinabox/dscs
/ParticleInaBox/DataStructures/LinkedList.cs
3.4375
3
using System; using System.Text; namespace ParticleInaBox { namespace DataStructures { public class LinkedList<T> where T : IComparable { private LinkedListNode<T> _head = null; public LinkedListNode<T> Head { get { return _head; } } public Int32 Length { get { var _iterator = _head; var count = 0; while (_iterator != null) { count++; _iterator = _iterator.Next; } return count; } } public void Insert(T item) { if (_head == null) _head = new LinkedListNode<T>(item); else { _head = new LinkedListNode<T>(item, _head); _head.Next.previous = _head; } } public void InsertAfter(T item1, T item2) { var insertAfterNode = SearchNodes(item1); if (insertAfterNode == null) throw new ItemNotFoundException(item1); var node = new LinkedListNode<T>(item2, insertAfterNode.Next, insertAfterNode); insertAfterNode.Next.previous = node; insertAfterNode.next = node; } public void Remove(T item) { LinkedListNode<T> node = SearchNodes(item); if (node == null) throw new ItemNotFoundException(item); else { if (node == _head) { _head = node.Next; if (_head != null) _head.previous = null; } else { node.Previous.next = node.Next; if (node.Next != null) node.Next.previous = node.Previous; } } } public bool Contains(T item) { return SearchNodes(item) != null ? true : false; } private LinkedListNode<T> SearchNodes(T item) { var iterator = _head; while (iterator != null) if (iterator.Value.CompareTo(item) == 0) return iterator; else iterator = iterator.Next; return iterator; } public void Reverse() { var node = _head; var prev = node.previous; while (node != null) { var next = node.Next; node.next = prev; node.previous = next; prev = node; node = next; } _head = prev; } public void ReverseRecursiveWay() { if (_head != null) ReverseRecursive(_head); } private void ReverseRecursive(LinkedListNode<T> _node) { if (_node != null) { _head = _node; ReverseRecursive(_node.Next); if (_node.Next != null) _node.Next.next = _node; _node.previous = _node.Next; _node.next = null; } } public override string ToString() { if (_head != null) { var start = _head; var stackString = new StringBuilder(); stackString.Append(_head.Value); while ((start = start.Next) != null) { stackString.AppendFormat(" -> {0} ", start.Value); } return stackString.ToString(); } return null; } } } }
a2438f0f799cfcea8756beed51f0192b2244253f
C#
pecolynx/Ginger
/Ginger/main/Models/FileCreationEventArgs.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ginger.Models.Io { /// <summary> /// ファイル生成 /// </summary> public class FileCreationEventArgs : EventArgs { /// <summary> /// Initializes a new instance of the <see cref="FileCreationEventArgs"/> class. /// パス情報を指定して、FileCreationEventArgs クラスのインスタンスを生成、初期化します。 /// </summary> /// <param name="fullpath">パス情報</param> public FileCreationEventArgs(string fullpath) { this.FullPath = fullpath; } /// <summary> /// 生成されたファイルへのフルパスを取得します。 /// </summary> public string FullPath { get; private set; } } }
d78a59b2e586e307d07687d44c743e045ba3b977
C#
qkmaxware/Geometry
/Geometry/src/Geometry/Primitives/Cube.cs
2.859375
3
using System.Collections.Generic; namespace Qkmaxware.Geometry.Primitives { /// <summary> /// Cubic mesh /// </summary> public class Cube : ParameterizedMesh { private static Vec3[] cubeCoordinates = new Vec3[]{ new Vec3(-0.5,-0.5,0.5), new Vec3(-0.5,0.5,0.5), new Vec3(-0.5,-0.5,-0.5), new Vec3(-0.5,0.5,-0.5), new Vec3(0.5,-0.5,0.5), new Vec3(0.5,0.5,0.5), new Vec3(0.5,-0.5,-0.5), new Vec3(0.5,0.5,-0.5), }; private static int[] cubeFaces = new int[]{ 3,2,0, 7,6,2, 5,4,6, 1,0,4, 2,6,4, 7,3,1, 1,3,0, 3,7,2, 7,5,6, 5,1,4, 0,2,4, 5,7,1 }; protected override IMesh Generate() { List<Triangle> tris = new List<Triangle>(); for(int i = 0; i < cubeFaces.Length; i+=3) { tris.Add( new Triangle( size * cubeCoordinates[cubeFaces[i]] + centre, size * cubeCoordinates[cubeFaces[i + 1]] + centre, size * cubeCoordinates[cubeFaces[i + 2]] + centre ) ); } return new ListMesh(tris); } double size; public double Size { get => size; set { size = value; Rebuild(); } } Vec3 centre; public Vec3 Centre { get => centre; set { centre = value; Rebuild(); } } /// <summary> /// Create a cube /// </summary> /// <param name="size">size of the cube</param> /// <param name="centre">centre of the cube</param> public Cube (double size, Vec3 centre) { this.size = size; this.centre = centre; Rebuild(); } } }
f23b7b64365385ca6edf9fb628f6ddf2e00a0e23
C#
janwiesemann/WPF-Translate
/src/WPF-Translate/IO/ResourceDictionaryFile.cs
2.71875
3
using System.Collections.Generic; using System.Diagnostics; namespace de.LandauSoftware.WPFTranslate.IO { /// <summary> /// Stellt ein WPF-Ressource-File dar. /// </summary> [DebuggerDisplay("{FileName} {Entrys.Count}")] public class ResourceDictionaryFile { /// <summary> /// Erstellt eine neue Instanz eines ResourceDictionaryFiles /// </summary> /// <param name="fileName">Dateiname</param> public ResourceDictionaryFile(string fileName, IResourceFileReader reader) { FileName = fileName; Reader = reader; } /// <summary> /// Ruft eine Liste aller Einträge ab /// </summary> public List<DictionaryRawEntry> Entrys { get; } = new List<DictionaryRawEntry>(); /// <summary> /// Ruft den Dateinamen ab /// </summary> public string FileName { get; } /// <summary> /// Ruft alle MergedDictionaries ab /// </summary> public List<MergedDictionary> MergedDictionaries { get; } = new List<MergedDictionary>(); /// <summary> /// Eine Sammlung aller zusätzlichen Namespaces /// </summary> public List<DictionaryNamespace> Namespaces { get; } = new List<DictionaryNamespace>(); public IResourceFileReader Reader { get; } /// <summary> /// Settings für die Datei /// </summary> public XAMLSettings Settings { get; set; } /// <summary> /// X:Class /// </summary> public string XClass { get; set; } /// <summary> /// Entfernt alle String-Ressourcen (DictionaryStringEntry) aus den Einträgen /// </summary> public void RemoveAllStringRessoueces() { for (int i = Entrys.Count - 1; i >= 0; i--) { if (Entrys[i] is DictionaryStringEntry) Entrys.RemoveAt(i); } } } }
4d577dec1ffc06424bff400de214e9cfea56c1fd
C#
IvanBitunjac/OOM-Seminar-app
/OOM Seminar/ConcreteMediator.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOM_Seminar { public class ConcreteMediator : IMediator { List<User> users = new List<User>(); User sender; public List<User> Users { get { return this.users; } } public User Sender { get { return this.sender; } set { this.sender = value; } } //Sends message to all active users public void SendMessage(string message) { if (message == "") return; foreach(User user in users) { if(user.Equals(sender) || !user.IsActive()) { continue; } else { user.ReceivedMessage = sender.Message; } } } //Automatically adds reference to mediator to added users public void AddUsers(User user) { user.MediatorRef = this; users.Add(user); } } }
e3d02e91fe16097dfc490f98dd2cfec0ffd0dc7d
C#
vacatrin/simple-shopping-cart
/simple-shopping-cart-source/Controllers/ShoppingListController.cs
2.71875
3
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web.Http; using Newtonsoft.Json; using simple_shopping_cart_source.Models; namespace simple_shopping_cart_source.Controllers { public class ShoppingListController : ApiController { #region Region creating a mock shopping list, before implementing the database public static List<ShoppingList> shoppingLists = new List<ShoppingList> { new ShoppingList() { Id = 0, Name = "Groceries", Items = { new Item { Id = 0, Checked = false, Name = "Milk", ShoppingListId = 0}, new Item { Id = 1, Checked = false, Name = "Tomatoes", ShoppingListId = 0 }, new Item { Id = 2, Checked = false, Name = "Bread", ShoppingListId = 0 } } }, new ShoppingList() { Id = 1, Name = "Tools", Items = { new Item { Name = "Wrench" }, new Item { Name = "Bolts" }, new Item { Name = "Nuts" } } } }; #endregion // GET: api/ShoppingList?id=5 public IHttpActionResult Get(int id) { ShoppingList result = shoppingLists.FirstOrDefault(s => s.Id == id); if (result == null) { return NotFound(); } return Ok(result); } // POST: api/ShoppingList public IEnumerable Post([FromBody]ShoppingList newList) { newList.Id = shoppingLists.Count; shoppingLists.Add(newList); return shoppingLists; } } }
44805e7c4103f1551a81bfa648149b8eeb16cd87
C#
ekutsenko-softheme/clouduri
/CloudUri.DAL.Tests/Database/DbExceptionTests.cs
2.546875
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using CloudUri.DAL.Database; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CloudUri.DAL.Tests.Database { /// <summary> /// Tests the <see cref="DbException"/> class /// </summary> [TestClass] public class DbExceptionTests { /// <summary> /// Tests the first constructor /// </summary> [TestMethod] public void Constructor1Test() { const string message = "Message"; DbException dbException = new DbException(message); Assert.AreEqual(message, dbException.Message); Assert.IsNull(dbException.InnerException); Assert.IsNull(dbException.Params); Assert.IsNull(dbException.StoredProcedureName); } /// <summary> /// Tests the second constructor /// </summary> [TestMethod] public void Constructor2Test() { const string message = "Message"; InvalidOperationException exception = new InvalidOperationException(); DbException dbException = new DbException(message, exception); Assert.AreEqual(message, dbException.Message); Assert.AreEqual(exception, dbException.InnerException); Assert.IsNull(dbException.Params); Assert.IsNull(dbException.StoredProcedureName); } /// <summary> /// Tests the third constructor /// </summary> [TestMethod] public void Constructor3Test() { const string message = "Message"; const string sp = "storedprocedure"; InvalidOperationException exception = new InvalidOperationException(); DbException dbException = new DbException(message, exception, sp); Assert.AreEqual(message, dbException.Message); Assert.AreEqual(exception, dbException.InnerException); Assert.IsNull(dbException.Params); Assert.AreEqual(sp, dbException.StoredProcedureName); } /// <summary> /// Tests the fourth constructor /// </summary> [TestMethod] public void Constructor4Test() { const string message = "Message"; const string sp = "storedprocedure"; InvalidOperationException exception = new InvalidOperationException(); ICollection<DbParam> @params = new Collection<DbParam>(); DbException dbException = new DbException(message, exception, sp, @params); Assert.AreEqual(message, dbException.Message); Assert.AreEqual(exception, dbException.InnerException); Assert.AreEqual(@params, dbException.Params); Assert.AreEqual(sp, dbException.StoredProcedureName); } /// <summary> /// Tests the tostring() method /// </summary> [TestMethod] public void ToStringTest() { const string message = "Message"; const string sp = "storedprocedure"; InvalidOperationException exception = new InvalidOperationException(); ICollection<DbParam> @params = new Collection<DbParam> { new DbParam { Direction = ParameterDirection.Output, Name = "@", Size = 4, Type = SqlDbType.Money, Value = 123 } }; DbException dbException = new DbException(message, exception, sp, @params); const string expectedTostring = "Stored procedure: storedprocedure, params: Name: @, Value: 123, Type: Money, Direction: Output, Size: 4, exception: CloudUri.DAL.Database.DbException: Message ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.\r\n --- End of inner exception stack trace ---"; Assert.AreEqual(expectedTostring, dbException.ToString()); } /// <summary> /// Tests the tostring() method /// </summary> [TestMethod] public void ToStringWithNullParamsTest() { const string message = "Message"; const string sp = "storedprocedure"; InvalidOperationException exception = new InvalidOperationException(); DbException dbException = new DbException(message, exception, sp); const string expectedTostring = "Stored procedure: storedprocedure, params: , exception: CloudUri.DAL.Database.DbException: Message ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.\r\n --- End of inner exception stack trace ---"; Assert.AreEqual(expectedTostring, dbException.ToString()); } } }
456da24fc2da3a00226e797a84b2a2b9b970ee5a
C#
cang2016/RMS
/Logging/Appender/IAppenderAttacher.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RMS.Logging { /// <summary> /// 要添加的附加器接口. /// </summary> public interface IAppenderAttachable { /// <summary> /// 添加一个附加器. /// </summary> /// <param name="appender">要添加的附加器.</param> /// <remarks> /// <para> /// 添加一个指定的附加器,允许选择添加一个不存在的附加器 /// </para> /// </remarks> void AddAppender(IAppender appender); /// <summary> /// 获取所在添加的附加器. /// </summary> /// <value> /// 一个附加器集合. /// </value> /// <remarks> /// <para> /// 一个附加器集合. /// 如果不存在,则返回一个空集合. /// </para> /// </remarks> AppenderCollection Appenders { get; } /// <summary> /// 返回指定名称的附加器. /// </summary> /// <param name="name">指定要获取的名附加器名称.</param> /// <returns> IAppender GetAppender(string name); /// <summary> /// 删除所有的附加器. /// </summary> /// <remarks> /// <para> /// 删除并关闭所有的附加器 /// </para> /// </remarks> void RemoveAllAppenders(); /// <summary> /// 删除从附加器列表中指定的附加器. /// </summary> /// <param name="appender">要删除的附加器.</param> /// <returns>从列表中删除的附加器.</returns> /// <remarks> /// <para> IAppender RemoveAppender(IAppender appender); /// <summary> /// 删除从附加器列表中指定名称的附加器. /// </summary> /// <param name="name">指定要删除的附加器的名称.</param> /// <returns>从列表中删除的附加器</returns> /// <remarks> /// <para> IAppender RemoveAppender(string name); } }
f3ad5d7ed9ffee26dc6696de6029ea0ff726dee9
C#
Educational-Repos/Lemma
/Lemma/GeeUI/Views/ImageView.cs
2.578125
3
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace GeeUI.Views { public class ImageView : View { public Texture2D Texture; public override Rectangle BoundBox { get { return new Rectangle(RealX, RealY, (int)ScaledImageSize.X, (int)ScaledImageSize.Y); } } public Vector2 ScaleVector { get { return new Vector2(Width / (float)Texture.Width, Height / (float)Texture.Height); } set { Width.Value = (int)(Texture.Width * value.X); Height.Value = (int)(Texture.Height * value.Y); } } public Vector2 ScaledImageSize { get { return new Vector2(Width * ScaleVector.X, Height * ScaleVector.Y); } } public ImageView(GeeUIMain GeeUI, View rootView, Texture2D texture) : base(GeeUI, rootView) { Texture = texture; Width.Value = texture.Width; Height.Value = texture.Height; } public override void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(Texture, AbsolutePosition, null, Color.White * EffectiveOpacity, 0f, Vector2.Zero, ScaleVector, SpriteEffects.None, 0f); base.Draw(spriteBatch); } } }
e1f4fc8d8820c306681aaeda3983d11bab080702
C#
jboullion/BetaBrew
/BetaBrew.Web/Serialization/CustomerMapper.cs
2.71875
3
using BetaBrew.Data.Models; using BetaBrew.Web.ViewModels; namespace BetaBrew.Web.Serialization { public static class CustomerMapper { /// <summary> /// Serialize Customer Data Model to a Customer View Model /// </summary> /// <param name="customer"></param> /// <returns></returns> public static CustomerModel SerializeCustomer(Customer customer) { return new CustomerModel { Id = customer.Id, CreatedOn = customer.CreatedOn, UpdatedOn = customer.UpdatedOn, FirstName = customer.FirstName, LastName = customer.LastName, PrimaryAddress = MapCustomerAddress(customer.PrimaryAddress) }; } /// <summary> /// Serialize Customer View Model to a Customer Data Model /// </summary> /// <param name="customer"></param> /// <returns></returns> public static Customer SerializeCustomer(CustomerModel customer) { return new Customer { Id = customer.Id, CreatedOn = customer.CreatedOn, UpdatedOn = customer.UpdatedOn, FirstName = customer.FirstName, LastName = customer.LastName, PrimaryAddress = MapCustomerAddressModel(customer.PrimaryAddress) }; } /// <summary> /// Map a CustomerAddress data model into a CustomerAddress view model /// </summary> /// <param name="address"></param> /// <returns></returns> public static CustomerAddressModel MapCustomerAddress(CustomerAddress address) { return new CustomerAddressModel { Id = address.Id, AddressLine1 = address.AddressLine1, AddressLine2 = address.AddressLine2, City = address.City, State = address.State, PostalCode = address.PostalCode, Country = address.Country, CreatedOn = address.CreatedOn, UpdatedOn = address.UpdatedOn }; } /// <summary> /// Map a CustomerAddress view model into a CustomerAddress data model /// </summary> /// <param name="address"></param> /// <returns></returns> public static CustomerAddress MapCustomerAddressModel(CustomerAddressModel address) { return new CustomerAddress { Id = address.Id, AddressLine1 = address.AddressLine1, AddressLine2 = address.AddressLine2, City = address.City, State = address.State, PostalCode = address.PostalCode, Country = address.Country, CreatedOn = address.CreatedOn, UpdatedOn = address.UpdatedOn }; } } }
289cf24e71e2fb4e2e853cd8913b4a277b396217
C#
shendongnian/download4
/code11/1959017-59551102-212251326-2.cs
2.875
3
public virtual void SetCredentials( string email, string plainTextPassword) { EMail = email; SetPassword(plainTextPassword); } public virtual void SetPassword(string plainTextPassword) { HashedPassword = _passwordHasher.HashPassword( EMail, plainTextPassword); }
41b073783727dbd7fd4df7733e8cb9c0322cba6c
C#
shendongnian/download4
/first_version_download2/216158-16814361-41355537-2.cs
3.453125
3
Console.WriteLine("Enter your Name"); Console.WriteLine("Enter your Pswrd"); string name = Console.ReadLine(); string pswrd = Console.ReadLine(); string[] names = "James,John,Jude".Split(Convert.ToChar(",")); string[] passes = "Pass1, Word2, Password3".Split(Convert.ToChar(",")); for (int i = 0; i<names.Length, i++) { if (names[i] == name && passes[i] == pswrd) { Console.WriteLine("You are logged in"); } else { Console.WriteLine("Incorrect name or pswrd"); } }
20cad2e8ab9be4518d0b65bdaa6a9d04b8542fe2
C#
art-Tests/Cli-pipeline-sample
/Cli.Model/DataModelHelper.cs
2.578125
3
using System; using System.Threading; namespace Cli.Model { public static class DataModelHelper { public static bool ProcessPhase1(DataModel data) { if (data == null || data.Stage != DataModelStageEnum.INIT) return false; Console.Error.WriteLine($"[P1][{DateTime.Now}] data({data.SerialNO}) start..."); Thread.Sleep(1000); data.Stage = DataModelStageEnum.PHASE1_COMPLETE; Console.Error.WriteLine($"[P1][{DateTime.Now}] data({data.SerialNO}) end..."); return true; } public static bool ProcessPhase2(DataModel data) { if (data == null || data.Stage != DataModelStageEnum.PHASE1_COMPLETE) return false; Console.Error.WriteLine($"[P2][{DateTime.Now}] data({data.SerialNO}) start..."); Thread.Sleep(1500); data.Stage = DataModelStageEnum.PHASE2_COMPLETE; Console.Error.WriteLine($"[P2][{DateTime.Now}] data({data.SerialNO}) end..."); return true; } public static bool ProcessPhase3(DataModel data) { if (data == null || data.Stage != DataModelStageEnum.PHASE2_COMPLETE) return false; Console.Error.WriteLine($"[P3][{DateTime.Now}] data({data.SerialNO}) start..."); Thread.Sleep(2000); data.Stage = DataModelStageEnum.PHASE3_COMPLETE; Console.Error.WriteLine($"[P3][{DateTime.Now}] data({data.SerialNO}) end..."); return true; } } }
5ae1ee32d4c2e9d0292450088cf3d1df92aa760b
C#
redd20/Click-world
/Idle click world/Assets/LevelGen.cs
2.59375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LevelGen : MonoBehaviour { #region Variables [SerializeField] public GameObject[] Land; // [SerializedField] is an UnityEditor Window mod that puts droppable fields in private int LandArrayLocation = 0; private int Randomizer; [SerializeField] public int KingdomSize; int[,] LandGridSize; [SerializeField] Camera playerCamera; #endregion // Start is called before the first frame update void Start() { Instantiate<GameObject>(Land[0], new Vector3(this.transform.position.x, this.transform.position.y), this.transform.rotation); // This places the castle at 0,0,0 in the map PositiveXMapBuild(); // This function builds the map in the positive X direction this.transform.position = new Vector3(-1, 0, 0); // this resets the map building object to the negative side after the first half of the build NegativeXMapBuild(); // This builds the map to the Negative X direction playerCamera.transform.position = new Vector3(4, 4, -4); //Sets up initial camera postion Destroy(this.gameObject); // removes map builder from memory } private void NegativeXMapBuild() { for (int i = 0; i < KingdomSize; i++) { RandomizerFunction(); for (int e = 0; e <= KingdomSize; e++) { RandomizerFunction(); Instantiate<GameObject>(Land[Randomizer], new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z + e), this.transform.rotation); RandomizerFunction(); if (this.transform.position.z - e != 0 || this.transform.position.z + e != 0) { Instantiate<GameObject>(Land[Randomizer], new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z - e), this.transform.rotation); } } this.transform.position = new Vector3(this.transform.position.x - 1, this.transform.position.y, this.transform.position.z); } } private void PositiveXMapBuild() { for (int i = 1; i <= KingdomSize + 1; i++) { RandomizerFunction(); if (this.transform.position.x > 0) { Instantiate<GameObject>(Land[Randomizer], new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z), this.transform.rotation); } for (int e = 1; e <= KingdomSize; e++) { RandomizerFunction(); Instantiate<GameObject>(Land[Randomizer], new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z + e), this.transform.rotation); RandomizerFunction(); if (this.transform.position.x + e > 0) { Instantiate<GameObject>(Land[Randomizer], new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z - e), this.transform.rotation); } } this.transform.position = new Vector3(this.transform.position.x + 1, this.transform.position.y, this.transform.position.z); } } // Update is called once per frame void Update() { } // This Function provides a random number based on the size of the Land Array which offers flexibility in the randomly generated level public void RandomizerFunction() { Randomizer = Random.Range(1, Land.Length); } }
6d9fb62a22bad847636f411f2e37cb0d95eea0a0
C#
ptychan/MOBA
/Assets/Scripts/TargetingSystem.cs
2.5625
3
using System.Collections.Generic; using System.Linq; using UnityEngine; public class TargetingSystem : MonoBehaviour { List<Health> targetInRange = new List<Health>(); Health targetHealth; Team team; private void Start() { team = GetComponent<Team>(); } public void UpdateTarget() { targetInRange.RemoveAll(x => !x.IsAlive()); if (!targetHealth || !targetHealth.IsAlive()) { var closestTargetHealth = targetInRange .OrderBy(x => (x.transform.position - transform.position).sqrMagnitude) .FirstOrDefault(); targetHealth = closestTargetHealth; } } public Health GetCurrentTarget() { return targetHealth; } private void OnTriggerEnter(Collider other) { var otherTeam = other.GetComponentInParent<Team>(); if (otherTeam == null || otherTeam.faction == team.faction) return; targetInRange.Add(other.GetComponentInParent<Health>()); Debug.Log("[TargetingSystem] Adding target: " + other.name); } private void OnTriggerExit(Collider other) { var otherHealth = other.GetComponentInParent<Health>(); targetInRange.Remove(otherHealth); Debug.Log("[TargetingSystem] Removing target: " + other.name); // If my current target just left, stop targeting it if (otherHealth == targetHealth) { targetHealth = null; } } }
02e39a5b6b99ef2c13dafb1c5a392749a52ea522
C#
ewertonews/EwsChat
/EwsChat.Data/ChatUserRespository.cs
2.8125
3
using EwsChat.Data.Exceptions; using EwsChat.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EwsChat.Data { public class ChatUserRespository : IChatUserRespository { private readonly HashSet<ChatUser> chatUsers; public ChatUserRespository() { chatUsers = new HashSet<ChatUser>(); } public async Task AddUserAsync(ChatUser user) { await Task.Run(() => { var possibleExistentUser = chatUsers.FirstOrDefault(u => u.NickName == user.NickName); if (possibleExistentUser != null) { throw new UserAlreadyExistsException("There is already a user registered with the given NickName"); } if (user.UserId == null) { user.UserId = Guid.NewGuid().ToString(); } chatUsers.Add(user); }); } public async Task<IEnumerable<ChatUser>> GetUsersOfRoomAsync(int roomId) { //TODO:throw RoomNotFoundException when invalid room; return await Task.Run(() => { return chatUsers.Where(u => u.ActiveRoomId == roomId); }); } public async Task<IEnumerable<ChatUser>> GetAllUsersAsync() { return await Task.Run(() => { return chatUsers; }); } public async Task<ChatUser> GetUserByIdAsync(string userId) { var searchedUser = await Task.Run(() => { return chatUsers.FirstOrDefault(u => u.UserId == userId); }); if(searchedUser == null) { throw new UserNotFoundException("There is no user registered with given user id"); } return searchedUser; } public async Task<ChatUser> UpdateUserAsync(ChatUser updatedUser) { var userToRemove = await GetUserByIdAsync(updatedUser.UserId); chatUsers.Remove(userToRemove); chatUsers.Add(updatedUser); return updatedUser; } public async Task RemoveUserAsync(string userId) { var userToRemove = await GetUserByIdAsync(userId); if (userToRemove == null) { throw new UserNotFoundException("There is no user registered with given user id."); } chatUsers.Remove(userToRemove); } } }
5e985ac4b123c80523ec6191938c538b5ff91655
C#
shendongnian/download4
/first_version_download2/192936-14734778-35584438-2.cs
2.796875
3
Array.Sort(properties, (pi1, pi2) => { if (pi1.DeclaringType.IsSubclassOf(pi2.DeclaringType)) return 1; else if (pi2.DeclaringType.IsSubclassOf(pi1.DeclaringType)) return -1; else return 0; });
437e81c3d465a5aed194b9c36aa079a6c25daf23
C#
minhchan11/Coin_calculation
/Objects/Coin.cs
3.203125
3
using System; using System.Collections.Generic; namespace CoinApp.Objects { public class Coin { public string ConvertToCoins(int cents) { string coinResult = ""; //quarters int quarters = cents/25; if (quarters > 0) { coinResult += quarters.ToString() + " quarter(s) "; } cents %= 25; //dimes int dime = cents/10; if (dime > 0) { coinResult += dime.ToString() + " dime(s) "; } cents %= 10; //nickels int nickels = cents/5; if (nickels > 0) { coinResult += nickels.ToString() + " nickel(s) "; } cents %= 5; if (cents > 0) { coinResult += cents.ToString() + " pennie(s)"; } return coinResult; } } } // public List<string> Change() // { // int total = _amount; // if( (total > 0) & (total < 100) ) // { // Random Random = new Random(); // int quanQuar = total / 25; // int quarters = Random.Next(0, quanQuar); // string quarterStr = quarters.ToString() + " quarter(s)"; // _coinList.Add(quarterStr); // int dimeQuan = (total - (quarters * 25)) / 10; // int dimes = Random.Next(0, dimeQuan); // string dimeStr = dimes.ToString() + " Dime(s)"; // _coinList.Add(dimeStr); // int nickelQuan = (total - (quarters * 25) - (dimes * 10)) / 5; // int nickels = Random.Next(0, nickelQuan); // string nickelStr = nickels.ToString() + " Nickel(s)"; // _coinList.Add(nickelStr); // int pennyQuan = (total - (quarters * 25) - (dimes * 10) - (nickels * 5)) / 1; // string pennyStr = pennyQuan.ToString() + " pennie(s)"; // _coinList.Add(pennyStr); // } // return _coinList; // } // }
45b6e8a0f9bc5950cd53241069a189c9404c8853
C#
ninjapretzel/zsharp2
/Behaviours/Animation/StretchNSquash.cs
2.890625
3
using UnityEngine; using System.Collections; ///Uses two osciallators to animate the scaling of a transform. ///Basically automates the 'stretch n squash' animation. public class StretchNSquash : MonoBehaviour { public Oscillator horizontal = new Oscillator(0.3f, 1.5f, 1.0f); public Oscillator vertical = new Oscillator(0.3f, 1.5f, 2.0f); Vector3 baseScale; void Start() { baseScale = transform.localScale; } void Update() { horizontal.Update(); vertical.Update(); Vector3 scale = baseScale; scale.y *= vertical.value; scale.x *= horizontal.value; scale.z *= horizontal.value; transform.localScale = scale; } }
cabe93ab19bee8724fe69c1c5a1b018e51f93b6d
C#
chris01k/RecipeHandling
/RecipeHandling/View/FoodPlanView.cs
2.828125
3
using Jamie.Model; using System; namespace Jamie.View { public class FoodPlanView { //Variables private FoodPlanItemSet _FoodPlanItems; private RecipeSet _Recipes; //Constructors public FoodPlanView(FoodPlanItemSet FoodPlanItems, RecipeSet Recipes) { _FoodPlanItems = FoodPlanItems; _Recipes = Recipes; } //Properties public FoodPlanItemSet FoodPlanItems { get { return _FoodPlanItems; } } //Readonly public RecipeSet Recipes { get { return _Recipes; } } //Readonly //Methods public void Menu() { int HowManyItemsInSet = FoodPlanItems.Count; if (HowManyItemsInSet > 0) FoodPlanItems.SelectItem(HowManyItemsInSet - 1); string MenuInput = ""; while (MenuInput != "Q") { ViewSet(); Console.WriteLine(); Console.WriteLine("\nFoodPlanItem Menü"); Console.WriteLine("---------\nSelected FoodplanItem: {0}\n", FoodPlanItems.SelectedItem); Console.WriteLine("A Add FoodplanItem"); Console.WriteLine("D Delete Selected FoodplanItem"); Console.WriteLine("S Select FoodplanItem"); Console.WriteLine("V View Set"); Console.WriteLine("--------------------"); Console.WriteLine("Q Quit"); Console.WriteLine(); Console.Write("Ihre Eingabe:"); MenuInput = Console.ReadLine().ToUpper(); switch (MenuInput) { case "A": //AddItem(); FoodPlanItem newItem = NewPopulatedObject(); if ((newItem != null) && !FoodPlanItems.AddItem(newItem)) { Console.WriteLine("Fehler: Food Plan Eintrag konnte nicht angelegt werden"); Console.ReadLine(); } break; case "D": //DeleteSelectedItem(); break; case "S": SelectItem(); break; case "V": break; default: Console.WriteLine(); break; } } }// --> View public FoodPlanItem NewPopulatedObject() { DateTime InputDate; float InputFloat; string InputString; FoodPlanItem ReturnItem; ReturnItem = new FoodPlanItem(); do { Console.Write("Date of Preparation: "); InputString = Console.ReadLine(); } while (!DateTime.TryParse(InputString, out InputDate)); ReturnItem.DateToStartPreparation = InputDate; do { Console.Write("Date to Consume: "); InputString = Console.ReadLine(); } while (!DateTime.TryParse(InputString, out InputDate)); ReturnItem.DateToConsume = InputDate; do { Console.Write("Date to Consume: "); InputString = Console.ReadLine(); } while (!float.TryParse(InputString, out InputFloat)); ReturnItem.TotalPortions = InputFloat; /* do { Console.Write("Date of Preparation : "); InputString = Console.ReadLine(); try { DateTime.Parse(InputString); } catch { continue; } break; } while (true); do { Console.Write("Date to Consume : "); InputString = Console.ReadLine(); try { ReturnItem.DateToConsume = DateTime.Parse(InputString); } catch { continue; } break; } while (true); do { Console.Write("Total Portions : "); InputString = Console.ReadLine(); try { ReturnItem.TotalPortions = float.Parse(InputString); } catch { continue; } break; } while (true); */ Console.WriteLine(Recipes.ToString()); ReturnItem.PlannedRecipe = ListHelper.ChangeRecipeField("Recipe: "); return ReturnItem; }// --> View public FoodPlanItem SelectItem() { int ParsedIntValue; long SelectedID; string InputString; do { Console.Write("FoodPlan ID:"); InputString = Console.ReadLine(); } while (!int.TryParse(InputString, out ParsedIntValue)); SelectedID = ParsedIntValue; return FoodPlanItems.SelectItemByID(SelectedID); } public void ViewSet() { Console.WriteLine(FoodPlanItems.ToString()); }// --> View } }
9340271a5d5e9646d4896b091ed4dfba7b3b13be
C#
MariiaRev/PM_HomeWorks
/HomeWork3/Library/ERPReports/Product.cs
2.875
3
 namespace Library.ERPReports { public class Product { public string Id { get; } public string Brand { get; } public string Model { get; } public decimal Price { get; } public Product(string id, string brand, string model, decimal price) { Id = id; Brand = brand; Model = model; Price = price; } public override string ToString() { return $" {Id, 4} {Brand, 15} {Model, 15} {Price, 10}"; } } }
ddaaea91af6337385117ded902aeb86b1df98e4b
C#
awilliams2112/social-loans
/SocialLoans/SocialLoans/DAL/Repositories/DisclosureRepository.cs
2.546875
3
using DAL.Models; using DAL.Repositories.Interfaces; using System; using System.Collections.Generic; using System.Text; using System.Linq.Expressions; using System.Linq; namespace DAL.Repositories { public interface IDisclosureRepository : IRepository<Disclosure> { DisclosureTemplate GetTemplateByTypeId(int disclosureTypeId); } public class DisclosureRepository : Repository<Disclosure>, IDisclosureRepository { ApplicationDbContext context; public DisclosureRepository(ApplicationDbContext context) : base(context) { this.context = context; } public DisclosureTemplate GetTemplateByTypeId(int disclosureTypeId) { return this.context.DisclosureTemplates.FirstOrDefault(t => t.DisclosureTemplateTypeId == disclosureTypeId && t.IsCurrent); } } }
67e6746ef4f23c297294bf2e0f03c298762dac72
C#
mk-prg-net/mk-prg-net.lib
/mko.Newton/LispVelocitiesArray.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using E = mko.Euklid; namespace mko.Newton.Vector { public class Velocities : MeasuredValuesVector<MeasuredValueV, MeasuredValueV.UnitV> { public Velocities(Velocities v) : base(v) { } public Velocities(int countValues) : base(countValues) { } public Velocities(MeasuredValueV.UnitV unit, int countValues) : base(unit, countValues) { } public Velocities(MeasuredValueV.UnitV unit, params double[] values) : base(unit, values) { } public Velocities(MeasuredValueV.UnitV unit, E.Vector Vector) : base(unit, Vector) { } public Velocities(MeasuredValueV.UnitV unit, params MeasuredValueV[] values) : base(unit, values) { } /// <summary> /// Einheit von V als Quotient Einheit Weg/Einheit Zeit /// </summary> public Tuple<Distance.UnitS, MeasuredValueT.UnitT> UnitAsQuotient { get { return MeasuredValueV.GetVelocityUnitAsQuotient(Unit); } } /// <summary> /// Vectoraddition von Geschwindigkeiten /// </summary> /// <param name="v1"></param> /// <param name="v2"></param> public static Velocities operator +(Velocities v1, Velocities v2) { if (v1.Unit == v2.Unit) return new Velocities(v1.Unit, v1.Vector + v2.Vector); else return new Velocities(v1.BaseUnit, v1.VectorInBaseUnit + v2.VectorInBaseUnit); } /// <summary> /// Integration des Weges über der Zeit /// </summary> /// <param name="dv">Momentangeschwindigkeit</param> /// <param name="dt">Zeitintervall</param> /// <returns>Weg in der Einheit, die im Zähler der Einheit von dv steht</returns> public static Distances operator *(Velocities dv, MeasuredValueT dt) { var q = MeasuredValueV.GetVelocityUnitAsQuotient(dv.Unit); return new Distances(q.Item1, dv.Vector * dt.ConvertTo(q.Item2)); } public static Distances operator *(MeasuredValueT dt, Velocities dv) { return dv * dt; } /// <summary> /// Differenzenqutient der Geschwindigkeit über der Zeit /// </summary> /// <param name="dv">Momentangeschwindigkeit</param> /// <param name="dt">Zeitintervall</param> /// <returns></returns> public static Accelerations operator /(Velocities dv, MeasuredValueT dt) { var q = dv.UnitAsQuotient; return new Accelerations(MeasuredValueAcc.CreateUnit(q.Item1, dt.Unit), dv.Vector * (1/dt.ConvertTo(q.Item2))); } } }
fae748c10ab0afdf638e2c58142c07b6ec361ca9
C#
SynI20N/BridgeRace
/Assets/Code/Extensions.cs
2.515625
3
using UnityEngine; public static class Extensions { public static Vector3 RandomPointInCollider(Collider collider) { Bounds bounds = collider.bounds; Vector3 result = new Vector3( Random.Range(bounds.min.x, bounds.max.x), Random.Range(bounds.min.y, bounds.max.y), Random.Range(bounds.min.z, bounds.max.z) ); return collider.ClosestPoint(result); } }
7ba7ceca2530e6d76df34f3aff4ecf9208948967
C#
GitBulk/Tam.Framework
/Core/Tam.Util/ObjectDumper.cs
3.03125
3
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Tam.Util { public class ObjectDumper { const string OBJECT_DUMPER_FILE_NAME = "ObjectDumper_{0}.txt"; const string DATE_PATTERN_4Y_2M_2D = "yyyyMMdd"; private static string CreatedTime = ""; private static object LockObject = new object(); private static string FolderPath = ""; public ObjectDumper(string folderPath) { if (string.IsNullOrWhiteSpace(folderPath)) { throw new NullOrEmptyArgumentException("FolderPath"); } FolderPath = folderPath; } public void Print(object target, int index = 0) { CreatedTime = DateTime.Now.ToString(DATE_PATTERN_4Y_2M_2D); //string filePath = string.Format(Logger.Folder_Log_Name + "\\" + OBJECT_DUMPER_FILE_NAME, CreatedTime); string filePath = Path.GetFullPath(string.Format(FolderPath + "\\" + OBJECT_DUMPER_FILE_NAME, CreatedTime)); if (DirectoryHerlper.CreateDirectory(FolderPath) == false) { return; } var properties = from property in target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) select new { Name = property.Name, Value = property.GetValue(target, null) }; var builder = new StringBuilder(); builder.AppendLine("Date/Time: " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString()); if (index > 0) { builder.AppendLine("STT = " + index); } foreach (var property in properties) { builder .Append(property.Name) .Append(" = ") .Append(property.Value) .AppendLine(); } builder.AppendLine(); builder.AppendLine("================================================="); //set up a filestream var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write); //set up a streamwriter for adding text StreamWriter sw = new StreamWriter(fs); lock (LockObject) { //find the end of the underlying filestream sw.BaseStream.Seek(0, SeekOrigin.End); //add the text sw.WriteLine(builder.ToString()); //add the text to the underlying filestream sw.Flush(); //close the writer sw.Close(); } } public void Print(object target) { Print(target, 0); } } }
d9dd7dde46337e57b552441bdaa1e6595b651cba
C#
johndward01/10_CSharp_Loops
/Iteration_Statements_Exercise_2/Iteration_Statements_Exercise__2/Program.cs
4.03125
4
using System; using System.Collections.Generic; namespace Iteration_Statements_Exercise__2 { class Program { static void Main(string[] args) { //var list = new List<int>() { 1, 2, 3 }; //An example collection to play around with using Loops ////for loop example ---> type (for) and hit Tab twice //for (int i = 0; i < list.Count; i++) //{ // Console.WriteLine(list[i]); //} ////foreach loop example ---> type (foreach) and hit Tab twice //foreach (var item in list) //{ // Console.WriteLine(item); //} ////while loop example ---> type (while) and hit Tab twice //var index = 0; //while (index < list.Count) //{ // Console.WriteLine(list[index]); // index++; //} ////do-while loop example ---> type (do) and hit Tab twice //do //{ // Console.WriteLine(list[index]); // index++; //} while (index < list.Count); //-------------------------------------------------------------------------------------------------------------------------------- var numbers = new List<int>(); int x = 0; //The do-while loop executes the code first then checks the conditional //Use a do-while loop if you need to execute code at least once do { x++; numbers.Add(x); } while (x < 100); //The while loop checks the conditional first //Use a while loop if you don't know how long to loop for //Executes code 0 or more times while (x < 200) { x++; numbers.Add(x); } Console.WriteLine("Increase:"); //The foreach loop is used for iterating through a collection //Use a foreach loop if you need to go through everything in the collection from beginning to end foreach (var number in numbers) { Console.WriteLine(number); } Console.WriteLine(); Console.WriteLine("Decrease:"); Console.WriteLine(); //The for loop is used for iterating through a collection a specific number of times //A for loop is more flexible than a foreach loop and allows you to iterate in many different ways for (int i = 199; i <= numbers.Count && i >= 0; i--) { Console.WriteLine(numbers[i]); } Console.WriteLine(); //Console.WriteLine(numbers.Count); //This While loop asks the user for a number and tells you if it's an even number or an odd number //uncomment this code to run it //int numInteger; //double numDouble; //bool conditional = true; //while (conditional) //{ // Console.WriteLine("please enter a number"); // var userInput = Console.ReadLine(); // if (int.TryParse(userInput, out numInteger)) // { // if (numInteger % 2 == 0) // { // Console.WriteLine("This is an even number"); // conditional = false; // } // else // { // Console.WriteLine("This is an odd number"); // conditional = false; // } // } // else if (double.TryParse(userInput, out numDouble)) // { // if (numDouble % 2 == 0) // { // Console.WriteLine("This is an even number"); // conditional = false; // } // else // { // Console.WriteLine("This is an even number"); // conditional = false; // } // } // else // { // Console.WriteLine("Please enter a valid number"); // Console.WriteLine(); // } //} } } }
19fa6a67d6cb5ef845c843732d1b36e327c20f7f
C#
axelnyberg/OnlineLibraryWebServer
/Library_BL/Author.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace Library_BL { public class Author { private int _Aid, _BirthYear; private string _FirstName, _LastName; public Author(string firstname, string lastnamne, int birthyear) { this._FirstName = firstname; this._LastName = lastnamne; this._BirthYear = birthyear; } public Author() { } public string FirstName { get { return _FirstName; } set { _FirstName = value; } } public string LastName { get { return _LastName; } set { _LastName = value; } } public int Aid { get { return _Aid; } set { _Aid = value; } } public int BirthYear { get { return _BirthYear; } set { _BirthYear = value; } } public int save() { SqlConnection con = new SqlConnection(Settings.ConnectionString); SqlCommand cmd; int retVal = -1; bool existing; if (this._Aid == 0) { existing = false; cmd = new SqlCommand("INSERT INTO AUTHOR (FirstName, LastName, BirthYear) VALUES ('" + this._FirstName + "','" + this._LastName + "'," + this._BirthYear + "); SELECT SCOPE_IDENTITY()", con); } else { existing = true; cmd = new SqlCommand("UPDATE AUTHOR set FirstName='" + this.FirstName + "', LastName='" + this.LastName + "', BirthYear=" + this.BirthYear + " WHERE Aid=" + this.Aid, con); } try { con.Open(); if (!existing) { retVal = cmd.ExecuteNonQuery(); } else { retVal = -1; cmd.ExecuteScalar(); } } catch (Exception er) { throw er; } finally { con.Close(); } return retVal; } public static List<Author> getAll() { List<Author> results = new List<Author>(); SqlConnection con = new SqlConnection(Settings.ConnectionString); SqlCommand cmd = new SqlCommand("SELECT * FROM AUTHOR", con); try { con.Open(); SqlDataReader dar = cmd.ExecuteReader(); while (dar.Read()) { Author newAuthor = new Author(); newAuthor.Aid = (int)dar["Aid"]; newAuthor.BirthYear = (dar["BirthYear"] == DBNull.Value) ? 0 : Convert.ToInt32(dar["BirthYear"].ToString()); newAuthor.FirstName = dar["FirstName"] as string; newAuthor.LastName = dar["LastName"] as string; results.Add(newAuthor); } } catch (Exception er) { throw er; } finally { con.Close(); } return results; } public static Author getByAid(int aid) { Author newAuthor = null; SqlConnection con = new SqlConnection(Settings.ConnectionString); SqlCommand cmd = new SqlCommand("SELECT * FROM AUTHOR WHERE Aid=@Aid", con); SqlParameter paramAid = new SqlParameter("Aid", SqlDbType.Int); paramAid.Value = aid; cmd.Parameters.Add(paramAid); try { con.Open(); SqlDataReader dar = cmd.ExecuteReader(); if (dar.Read()) { newAuthor = new Author(); newAuthor.Aid = (int)dar["Aid"]; newAuthor.BirthYear = (dar["BirthYear"] == DBNull.Value) ? 0 : Convert.ToInt32(dar["BirthYear"].ToString()); newAuthor.FirstName = dar["FirstName"] as string; newAuthor.LastName = dar["LastName"] as string; } } catch (Exception er) { throw er; } finally { con.Close(); } return newAuthor; } public static string GetBookISBN(int id) { Library_BL.Author author = Library_BL.Author.getByAid(id); string queryGetBooks = "select * from BOOK_AUTHOR where Aid=" + id; SqlConnection con = new SqlConnection(Settings.ConnectionString); SqlCommand cmd = new SqlCommand(queryGetBooks, con); List<string> isbnList = new List<string>(); try { con.Open(); SqlDataReader dar = cmd.ExecuteReader(); while (dar.Read()) { string isbn = Convert.ToString( dar["ISBN"]); isbnList.Add(isbn); } } catch (Exception er) { throw er; } finally { con.Close(); } int antalBocker = isbnList.Count(); string query=""; for(int i = 0 ; i < antalBocker; i++) { if (i != 0) query += ", "; query += "'" + isbnList[i] + "'"; } return query; } public static void DeleteFromBookAuthor(string isbnBooks) { SqlConnection con = new SqlConnection(Settings.ConnectionString); SqlCommand cmd = new SqlCommand("Delete from BOOK_AUTHOR where ISBN IN (" + isbnBooks + ")", con); try { con.Open(); SqlDataReader dar = cmd.ExecuteReader(); } catch (Exception er) { throw er; } finally { con.Close(); } } public static void DeleteFromCopy(string isbnBooks) { SqlConnection con = new SqlConnection(Settings.ConnectionString); SqlCommand cmd = new SqlCommand("Delete from COPY where ISBN IN (" + isbnBooks + ")", con); try { con.Open(); SqlDataReader dar = cmd.ExecuteReader(); } catch (Exception er) { throw er; } finally { con.Close(); } } public static void DeleteFromBook(string isbnBooks) { SqlConnection con = new SqlConnection(Settings.ConnectionString); SqlCommand cmd = new SqlCommand("Delete from BOOK Where ISBN IN (" + isbnBooks + ")", con); try { con.Open(); SqlDataReader dar = cmd.ExecuteReader(); } catch (Exception er) { throw er; } finally { con.Close(); } } public static void DeleteAuthor(int id) { SqlConnection con = new SqlConnection(Settings.ConnectionString); SqlCommand cmd = new SqlCommand("Delete from AUTHOR Where Aid="+id, con); string books = GetBookISBN(id); if (books == "") { try { con.Open(); SqlDataReader dar = cmd.ExecuteReader(); } catch (Exception er) { throw er; } finally { con.Close(); } } else { DeleteFromBookAuthor(books); DeleteFromCopy(books); DeleteFromBook(books); DeleteAuthor(id); } } public static List<Author> search(string query) { string SQL = "SELECT * FROM AUTHOR WHERE FirstName LIKE '%" + query + "%' OR LastName LIKE '%" + query + "%'"; List<Author> results = new List<Author>(); SqlConnection con = new SqlConnection(Library_BL.Settings.ConnectionString); SqlCommand cmd = new SqlCommand(SQL, con); try { con.Open(); SqlDataReader dar = cmd.ExecuteReader(); while (dar.Read()) { Author newAuthor = new Author(); newAuthor.Aid = (int)dar["Aid"]; newAuthor.BirthYear = (dar["BirthYear"] == DBNull.Value) ? 0 : Convert.ToInt32(dar["BirthYear"].ToString()); newAuthor.FirstName = dar["FirstName"] as string; newAuthor.LastName = dar["LastName"] as string; results.Add(newAuthor); } } catch (Exception er) { throw er; } finally { con.Close(); } return results; } public static List<Author> getBookDetails(string isbn) { List<Author> result = new List<Author>(); SqlConnection con = new SqlConnection(Settings.ConnectionString); SqlCommand cmd; cmd = new SqlCommand("SELECT Aid from BOOK_AUTHOR WHERE ISBN ='" + isbn + "'", con); try { con.Open(); SqlDataReader dar = cmd.ExecuteReader(); while (dar.Read()) { Author newAuthor = new Author(); newAuthor.Aid = (int)dar["Aid"]; result.Add(newAuthor); } } catch (Exception er) { throw er; } finally { con.Close(); } return result; } } }
156ca597536439a82ac480a72119ba84a3e62d8e
C#
cristianagrigoriu/OOP
/UsersExam/ExamTakingStudentUser.cs
3.046875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UsersExam { internal class ExamTakingStudentUser : User, IExamDelegate { private IDisplayInfo df; public void TakeExam(int option, string name) { ConcreteDisplayFactory c = new ConcreteDisplayFactory(); df = c.CreateDisplay(option); PrepareForExam(name); GoToExam(name); ReceiveGrade(name); } private void ReceiveGrade(string name) { df.DisplayInfo("Student " + name + " receives grade for exam."); } private void GoToExam(string name) { df.DisplayInfo("Student " + name + " is currently taking the exam."); } private void PrepareForExam(string name) { df.DisplayInfo("Student " + name + " is preparing for exam."); } } }
0986f05f56075fbf35fc1c1427e446e8beab0f9f
C#
xiongwjw/wjwlib
/wjw.helper/wjw.helper.core/Encrypts/Md5.cs
3.015625
3
using System; using System.IO; using System.Linq; using System.Text; namespace wjw.helper.Encrypts { public class MD5 { public static string CaculateStringMd5(string str,bool removeSeperater=true) { try { var md5 = System.Security.Cryptography.MD5.Create(); string result = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(str))); if (removeSeperater) result = result.Replace("-", ""); return result; } catch { return string.Empty; } } public static string CaculateFileMd5(string path, bool removeSeperater = true) { try { using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { var md5Provider = System.Security.Cryptography.MD5.Create(); byte[] hash_byte = md5Provider.ComputeHash(file); string result = System.BitConverter.ToString(hash_byte); if(removeSeperater) result = result.Replace("-", ""); return result; } } catch { return string.Empty; } } } }
f27eb3712b463a209e9c077af349cfa264225343
C#
joe1545134/UnityLockStepDemo
/LockStepDemo/Server/LockStepDemo/ServiceFrameWork/Database/ICursor.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CDatabase { /// <summary> /// 数据集读取游标接口类 /// </summary> public interface ICursor { /// <summary> /// 读取数据集中的下一条数据 /// </summary> /// <returns>True:读取下一条数据成功,False:读取下一条数据失败</returns> bool MoveToNext(); /// <summary> /// 获取数据集的字段数量 /// </summary> /// <returns>字段数量</returns> int FieldCount(); /// <summary> /// 关闭数据集 /// </summary> void Close(); /// <summary> /// 得到指定字段的数据类型 /// </summary> /// <param name="i">指定字段索引</param> /// <returns>数据类型名称</returns> string GetDataTypeName(int i); /// <summary> /// 得到指定字段名称 /// </summary> /// <param name="i">指定字段的索引</param> /// <returns>字段名称</returns> string GetName(int i); /// <summary> /// 判断指定字段值是否为NULL /// </summary> /// <param name="i">指定字段的索引</param> /// <returns>True:字段值为NULL,False:字段值不为NULL</returns> bool IsDBNull(int i); /// <summary> /// 通过指定字段名称获取对应索引值 /// </summary> /// <param name="field">指定字段名称</param> /// <returns>字段索引值</returns> int GetFieldIndex(string field); /// <summary> /// 通过指定字段索引获取DateTime类型字段的值 /// </summary> /// <param name="i">指定字段索引</param> /// <returns>字段值</returns> DateTime GetDateTime(int i); /// <summary> /// 通过指定字段名称获取DateTime类型字段的值 /// </summary> /// <param name="column">指定字段名称</param> /// <returns>字段值</returns> DateTime GetDateTime(string column); /// <summary> /// 通过指定字段索引获取Int类型字段的值 /// </summary> /// <param name="i">指定字段索引</param> /// <returns>字段值</returns> int GetInt(int i); /// <summary> /// 通过指定字段名称获取Int类型字段的值 /// </summary> /// <param name="column">指定字段名称</param> /// <returns>字段值</returns> int GetInt(string column); /// <summary> /// 通过指定字段索引获取String类型字段的值 /// </summary> /// <param name="i">指定字段索引</param> /// <returns>字段值</returns> string GetString(int i); /// <summary> /// 通过指定字段名称获取String类型字段的值 /// </summary> /// <param name="column">指定字段名称</param> /// <returns>字段值</returns> string GetString(string column); /// <summary> /// 通过指定字段索引获取Double类型字段的值 /// </summary> /// <param name="i">指定字段索引</param> /// <returns>字段值</returns> double GetDouble(int i); /// <summary> /// 通过指定字段名称获取Double类型字段的值 /// </summary> /// <param name="column">指定字段名称</param> /// <returns>字段值</returns> double GetDouble(string column); } }
744052c1dc92f1d2e31783d65b3faa9288016c69
C#
quickCloverCrew/basketstats
/NBASpider/Out/CSVFileWriter.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace NBASpider.Out { class CSVFileWriter { string fileName; public CSVFileWriter(string fileName) { this.fileName = fileName; } // TODO: пока тупо так, потом нормально сделаю public void Write(string data) { try { FileStream fs = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8); sw.Write(data); sw.Close(); } catch (IOException fe) { string sDir = Directory.GetCurrentDirectory(); string s = Path.Combine(sDir, fileName); Console.WriteLine("Error on file {0}", s); Console.WriteLine(fe.Message); } } } }
3a89420c5511831779348cb12675e3cc0a1c258b
C#
borislavvp/RMS-Users-Microservice
/Users.Service/Common/Interfaces/IRequestResult.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Users.Service.Common.Interfaces { /// <summary> /// Represents the object responsible for keeping the result of an authentication request /// </summary> public interface IRequestResult { /// <summary> /// The reason that the action failed. /// </summary> string FailureReason { get; } /// <summary> /// Indication whether the action succeed. /// </summary> bool IsSuccess { get; } } /// <summary> /// Represents the object responsible for keeping the result of an authentication request with additional data property /// </summary> public interface IRequestResult<T> { /// <summary> /// The data which is passed when the result is successfull /// </summary> T Data { get;} /// <summary> /// The reason that the action failed. /// </summary> string FailureReason { get; } /// <summary> /// Indication whether the action succeed. /// </summary> bool IsSuccess { get; } } }
10f53c25dd90f7402750db1a36c81ed8be7b1643
C#
hofmannzhu/bwjs
/BWJS.Client.Monitor/ProcessMonitor.cs
2.84375
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BWJS.Client.Monitor { public class ProcessMonitor { static IntPtr intPtr0 = new IntPtr(0); private static Process[] MyProcesses; /// <summary> /// 监控进程,发现没有直接启动 /// </summary> /// <param name="processName"></param> /// <param name="file"></param> public static void MonitorProcess(string processName, string file) { MyProcesses = Process.GetProcessesByName(processName);//需要监控的程序名,该方法带出该程序所有用到的进程 if (MyProcesses.Count() == 0) Run(file); else if (MyProcesses.Count() > 1 || MyProcesses.Count(o => o.MainWindowHandle != intPtr0) != 1) { foreach (Process myprocess in MyProcesses) { myprocess.Kill(); } Run(file); } } static void Run(string file) { if (File.Exists(file)) { RunCmd2(file, ""); } } /// <summary> /// 运行cmd命令 /// 不显示命令窗口 /// </summary> /// <param name="cmdExe">指定应用程序的完整路径</param> /// <param name="cmdStr">执行命令行参数</param> static bool RunCmd2(string cmdExe, string cmdStr) { bool result = false; try { using (Process myPro = new Process()) { myPro.StartInfo.FileName = "cmd.exe"; myPro.StartInfo.UseShellExecute = false; myPro.StartInfo.RedirectStandardInput = true; myPro.StartInfo.RedirectStandardOutput = true; myPro.StartInfo.RedirectStandardError = true; myPro.StartInfo.CreateNoWindow = true; myPro.Start(); //如果调用程序路径中有空格时,cmd命令执行失败,可以用双引号括起来 ,在这里两个引号表示一个引号(转义) string str = string.Format(@"""{0}"" {1} {2}", cmdExe, cmdStr, "&exit"); myPro.StandardInput.WriteLine(str); myPro.StandardInput.AutoFlush = true; myPro.WaitForExit(); result = true; } } catch { } return result; } } }
79e2ab2db7edcf2114718e96a503b51584177891
C#
cjhnim/daily-kata
/WordWrap/day_6/WordWrap/WordWrap/WordWrapper.cs
3.375
3
using System; namespace WordWrap { public class WordWrapper { public WordWrapper() { } public string DoWrap(string input, int col) { if (string.IsNullOrEmpty(input) || col == 0) return ""; if (input.Length > col) return input.Substring(0, col).Trim() + "--" + input.Substring(col, input.Length- col).Trim(); else return input; } } }
1acc7b0654fd5a49c1de87601422fb9f07c2bb96
C#
azum23/ACM
/ACM.BLTest/CustomerRepositoryTest.cs
2.734375
3
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using ACM.BL; namespace ACM.BLTest { [TestClass] public class CustomerRepositoryTest { [TestMethod] public void CustomerRepositoryRetrieveTest() { // Arrange var customerRepository = new CustomerRepository(); var excepted = new Customer(1) { EmailAddress = "a@amail.com", FirstName = "Alex", LastName = "Znamensky" }; excepted.AddressList.Add(new Address() { AddressType = 1, StreetLine1 = "Kirova", StreetLine2 = "39/1", City = "Arzamas", State = "NN", Country = "Ru", PostalCode = "607220" }); excepted.AddressList.Add(new Address() { AddressType = 2, StreetLine1 = "Zelenaya", StreetLine2 = "32/1", City = "Arzamas", State = "NN", Country = "Ru", PostalCode = "607220" }); // Act var actual = customerRepository.Retrieve(1); Assert.AreEqual(excepted.CustomerId, actual.CustomerId); Assert.AreEqual(excepted.EmailAddress, actual.EmailAddress); Assert.AreEqual(excepted.FirstName, actual.FirstName); Assert.AreEqual(excepted.LastName, actual.LastName); for (int i = 0; i < 1; i++) { Assert.AreEqual(excepted.AddressList[i].AddressType, actual.AddressList[i].AddressType); Assert.AreEqual(excepted.AddressList[i].StreetLine1, actual.AddressList[i].StreetLine1); Assert.AreEqual(excepted.AddressList[i].StreetLine2, actual.AddressList[i].StreetLine2); Assert.AreEqual(excepted.AddressList[i].State, actual.AddressList[i].State); Assert.AreEqual(excepted.AddressList[i].Country, actual.AddressList[i].Country); Assert.AreEqual(excepted.AddressList[i].PostalCode, actual.AddressList[i].PostalCode); } } } }
0a702d00b0fe9325d1e8e5301fe0849bac7b3577
C#
bjornhandersson/HilbertIndex
/Bson.HilbertIndex/Envelope.cs
2.875
3
using System; namespace Bson.HilbertIndex { public class Envelope { public Envelope(double minX, double maxX, double minY, double maxY) { MinX = minX; MaxX = maxX; MinY = minY; MaxY = maxY; } public double MinX { get; } public double MaxX { get; } public double MinY { get; } public double MaxY { get; } public Envelope Expand(Coordinate position) => Expand(position.X, position.Y); public Envelope Expand(double x, double y) => new Envelope( x < MinX ? x : MinX, x > MaxX ? x : MaxX, y < MinY ? y : MinY, y > MaxY ? y : MaxY ); } }
8a491ad1c8961a0979609356873bb460b968f749
C#
Piirtaa/Decoratid
/Storidioms/StoreOf/StoreOfExactlyDecoration.cs
2.71875
3
using Decoratid.Core.Decorating; using Decoratid.Core.Identifying; using Decoratid.Core.Storing; using Decoratid.Storidioms.ItemValidating; using System.Collections.Generic; using Decoratid.Extensions; using CuttingEdge.Conditions; using Decoratid.Core.Logical; namespace Decoratid.Storidioms.StoreOf { #region IStore Of Exactly Constructs /// <summary> /// a store of items that are of type T (exact match, no derived types) /// </summary> /// <typeparam name="T"></typeparam> public interface IStoreOfExactly<T> : IStore, IValidatingStore where T : IHasId { T GetById(object id); new List<T> GetAll(); } #endregion /// <summary> /// Turns a store into a "storeOf". decorates a store such that the only items that can be stored within the store are of type TItem /// </summary> /// <typeparam name="T"></typeparam> public sealed class StoreOfExactlyDecoration<T> : ValidatingDecoration, IStoreOfExactly<T> where T : IHasId { #region Declarations private readonly object _stateLock = new object(); #endregion #region Ctor public StoreOfExactlyDecoration(IStore decorated) : base(decorated, IsExactlyOfValidator.New<T>()) { } #endregion #region IDecoratedStore public override IDecorationOf<IStore> ApplyThisDecorationTo(IStore store) { return new StoreOfExactlyDecoration<T>(store); } #endregion #region IStoreOfExactly public new List<T> GetAll() { return base.GetAll().ConvertListTo<T, IHasId>(); } public T GetById(object id) { var item = this.Get(StoredObjectId.New(typeof(T), id)); if (item == null) return default(T); return (T)item; } #endregion } public static class StoreOfExactlyDecorationExtensions { /// <summary> /// constrains the store to operate on items of exactly T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="decorated"></param> /// <returns></returns> public static StoreOfExactlyDecoration<T> IsExactlyOf<T>(this IStore decorated) where T : IHasId { Condition.Requires(decorated).IsNotNull(); return new StoreOfExactlyDecoration<T>(decorated); } } }
13115d37023fc3953935666eae0f36d2ca066516
C#
iNeverSleeeeep/NPOI-For-Unity
/NPOI.SS.Formula.Functions/Days360.cs
2.609375
3
using NPOI.SS.Formula.Eval; using NPOI.SS.UserModel; using System; namespace NPOI.SS.Formula.Functions { public class Days360 : Var2or3ArgFunction { public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { double value; try { double d = NumericFunction.SingleOperandEvaluate(arg0, srcRowIndex, srcColumnIndex); double d2 = NumericFunction.SingleOperandEvaluate(arg1, srcRowIndex, srcColumnIndex); value = Evaluate(d, d2); } catch (EvaluationException ex) { return ex.GetErrorEval(); } return new NumberEval(value); } public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1, ValueEval arg2) { double value; try { double d = NumericFunction.SingleOperandEvaluate(arg0, srcRowIndex, srcColumnIndex); double d2 = NumericFunction.SingleOperandEvaluate(arg1, srcRowIndex, srcColumnIndex); ValueEval singleValue = OperandResolver.GetSingleValue(arg2, srcRowIndex, srcColumnIndex); OperandResolver.CoerceValueToBoolean(singleValue, stringsAreBlanks: false); value = Evaluate(d, d2); } catch (EvaluationException ex) { return ex.GetErrorEval(); } return new NumberEval(value); } private double Evaluate(double d0, double d1) { DateTime startingDate = GetStartingDate(d0); DateTime endingDateAccordingToStartingDate = GetEndingDateAccordingToStartingDate(d1, startingDate); long num = startingDate.Month * 30 + startingDate.Day; long num2 = (endingDateAccordingToStartingDate.Year - startingDate.Year) * 360 + endingDateAccordingToStartingDate.Month * 30 + endingDateAccordingToStartingDate.Day; return (double)(num2 - num); } private DateTime GetDate(double date) { return DateUtil.GetJavaDate(date); } private DateTime GetStartingDate(double date) { DateTime dateTime = GetDate(date); if (IsLastDayOfMonth(dateTime)) { dateTime = new DateTime(dateTime.Year, dateTime.Month, 30, dateTime.Hour, dateTime.Minute, dateTime.Second); } return dateTime; } private DateTime GetEndingDateAccordingToStartingDate(double date, DateTime startingDate) { DateTime dateTime = DateUtil.GetJavaDate(date, use1904windowing: false); if (IsLastDayOfMonth(dateTime) && startingDate.Day < 30) { dateTime = GetFirstDayOfNextMonth(dateTime); } return dateTime; } private bool IsLastDayOfMonth(DateTime date) { return date.AddDays(1.0).Month != date.Month; } private DateTime GetFirstDayOfNextMonth(DateTime date) { return (date.Month < 12) ? new DateTime(date.Year, date.Month + 1, 1, date.Hour, date.Minute, date.Second) : new DateTime(date.Year + 1, 1, 1, date.Hour, date.Minute, date.Second); } } }
b7f7fa73d02a41b95022c34a28f07870668d8335
C#
Linathimqalo/SimpleCalculator
/SimpleCalculator/Subtract.cs
3.21875
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 SimpleCalculator { public partial class Subtract : Form { public Subtract() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { this.Close(); Form1 form1 = new Form1(); form1.Show(); } private void button1_Click(object sender, EventArgs e) { try { double a = Convert.ToDouble(textBox1.Text); double b = Convert.ToDouble(textBox2.Text); string ans = (a - b).ToString(); textBox1.Clear(); textBox2.Clear(); MessageBox.Show("The total is: " + ans); } catch { MessageBox.Show("Invaild!"); } } } }
5356eb5050d9f947b3b90f3cff8dd2f1fb71b4e9
C#
propheel/Projects
/pkgik3dgame/.svn/pristine/4f/4f6c0be9320d1b2b8b8ab27c17d8b34d13bdb224.svn-base
2.71875
3
#region Using Statements using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace WarGame { /// <summary> /// This is a class representing a game object bounding box /// </summary> public class Bbox : Microsoft.Xna.Framework.DrawableGameComponent { /// <summary> /// Scene in which the bounding box appears /// </summary> MainScene scene; /// <summary> /// Game object which owns the bounding box /// </summary> GameObject owner; /// <summary> /// Initial bounding box and bounding box after transformations /// </summary> BoundingBox baseBox, realBox; /// <summary> /// Color of the bounding box /// </summary> Color color = Color.Yellow; /// <summary> /// Array of indices used to draw the bounding box /// </summary> short[] index = new short[] { 3, 2, 0, 1, 4, 5, 6, 2, 7, 3, 4 }; /// <summary> /// Values used to draw the bounding box /// </summary> RasterizerState WIREFRAME_RASTERIZER_STATE = new RasterizerState() { CullMode = CullMode.None, FillMode = FillMode.WireFrame }; RasterizerState SOLID_RASTERIZER_STATE = new RasterizerState() { CullMode = CullMode.None, FillMode = FillMode.Solid }; #region Getters and Setters public BoundingBox RealBox { get { return realBox; } } public BoundingBox BaseBox { get { return baseBox; } } #endregion /// <summary> /// Constructor of the bounding box /// </summary> /// <param name="_owner">Game object which owns the bounding box</param> /// <param name="_game">Game which the bounding box i set in</param> public Bbox(GameObject _owner, WarGame _game, MainScene _scene) : base(_game) { scene = _scene; owner = _owner; baseBox = (BoundingBox)_owner.GameObjectModel.Tag; Visible = false; DrawOrder = (int)WarGame.DrawingOrder.GameObject; } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { RecalculateBoundingBox(); base.Update(gameTime); } /// <summary> /// Enables the bounding box self-drawing /// </summary> /// <param name="gameTime">Snapshot of time</param> public override void Draw(GameTime gameTime) { List<VertexPositionColor> vertices = new List<VertexPositionColor>(); Vector3[] vectors = realBox.GetCorners(); for (int i = 0; i < 8; i++) vertices.Add(new VertexPositionColor(vectors[i], color)); ((WarGame)base.Game).GraphicsDevice.RasterizerState = WIREFRAME_RASTERIZER_STATE; foreach (EffectPass p in ((WarGame)base.Game).Effect.CurrentTechnique.Passes) { p.Apply(); ((WarGame)base.Game).GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, vertices.ToArray(), 0, vertices.Count, index, 0, index.Length - 2); } ((WarGame)base.Game).GraphicsDevice.RasterizerState = SOLID_RASTERIZER_STATE; base.Draw(gameTime); } /// <summary> /// Bounding box destructor /// </summary> public void Destroy() { scene.SceneComponents.Remove(this); Visible = Enabled = false; Dispose(); } public void RecalculateBoundingBox() { List<Vector3> corners = new List<Vector3>(); foreach (Vector3 corner in (baseBox.GetCorners())) { corners.Add(Vector3.Transform(corner, owner.CurrentWorld)); } realBox = BoundingBox.CreateFromPoints(corners); } } }
05c210ab9ae9f8bf442eb0b47e26050413a049c6
C#
MaSander/C-_Exercicios
/bases/Orientaçao Objeto/metodos/Senai.Metodos.Exc5/classe/Triangulo.cs
3.078125
3
namespace Senai.Metodos.Exc5.classe { public class Triangulo { // atributo public float ladoA, ladoB, ladoC; public bool Valido() { if (ladoA < (ladoB + ladoC) && ladoB < (ladoA + ladoC) && ladoC < (ladoA + ladoB)) { return true; } else { return false; } } public string Tipo() { if (ladoA == ladoB && ladoA == ladoC) { return "equilatero"; } else if (ladoA == ladoB || ladoA == ladoC || ladoB == ladoC) { return "isóceles"; }else return "escaleno"; } } }
faf6971fcf5c737b2bc8461034790134ef76e298
C#
ethanCun/.Net-
/Image-Upload/Image-Upload/Tool/WebBase.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Image_Upload.Tool { public class WebBase { /// <summary> /// 得到当前网站的根地址 /// </summary> /// <returns></returns> public static string GetRootPath() { // 是否为SSL认证站点 string secure = HttpContext.Current.Request.ServerVariables["HTTPS"]; string httpProtocol = (secure == "on" ? "https://" : "http://"); // 服务器名称 string serverName = HttpContext.Current.Request.ServerVariables["Server_Name"]; string port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"]; // 应用服务名称 string applicationName = HttpContext.Current.Request.ApplicationPath; return httpProtocol + serverName + (port.Length > 0 ? ":" + port : string.Empty) + applicationName; } } }
b25d5e9b594717c01022a3f3d725dd397ed212af
C#
jenzy/Advent-of-Code
/src/advent-of-code-2018/Days/Day14.cs
3.546875
4
using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace AdventOfCode.Y2018.Days { /* --- Day 14: Chocolate Charts --- You finally have a chance to look at all of the produce moving around. Chocolate, cinnamon, mint, chili peppers, nutmeg, vanilla... the Elves must be growing these plants to make hot chocolate! As you realize this, you hear a conversation in the distance. When you go to investigate, you discover two Elves in what appears to be a makeshift underground kitchen/laboratory. The Elves are trying to come up with the ultimate hot chocolate recipe; they're even maintaining a scoreboard which tracks the quality score (0-9) of each recipe. Only two recipes are on the board: the first recipe got a score of 3, the second, 7. Each of the two Elves has a current recipe: the first Elf starts with the first recipe, and the second Elf starts with the second recipe. To create new recipes, the two Elves combine their current recipes. This creates new recipes from the digits of the sum of the current recipes' scores. With the current recipes' scores of 3 and 7, their sum is 10, and so two new recipes would be created: the first with score 1 and the second with score 0. If the current recipes' scores were 2 and 3, the sum, 5, would only create one recipe (with a score of 5) with its single digit. The new recipes are added to the end of the scoreboard in the order they are created. So, after the first round, the scoreboard is 3, 7, 1, 0. After all new recipes are added to the scoreboard, each Elf picks a new current recipe. To do this, the Elf steps forward through the scoreboard a number of recipes equal to 1 plus the score of their current recipe. So, after the first round, the first Elf moves forward 1 + 3 = 4 times, while the second Elf moves forward 1 + 7 = 8 times. If they run out of recipes, they loop back around to the beginning. After the first round, both Elves happen to loop around until they land on the same recipe that they had in the beginning; in general, they will move to different recipes. Drawing the first Elf as parentheses and the second Elf as square brackets, they continue this process: (3)[7] (3)[7] 1 0 3 7 1 [0](1) 0 3 7 1 0 [1] 0 (1) (3) 7 1 0 1 0 [1] 2 3 7 1 0 (1) 0 1 2 [4] 3 7 1 [0] 1 0 (1) 2 4 5 3 7 1 0 [1] 0 1 2 (4) 5 1 3 (7) 1 0 1 0 [1] 2 4 5 1 5 3 7 1 0 1 0 1 2 [4](5) 1 5 8 3 (7) 1 0 1 0 1 2 4 5 1 5 8 [9] 3 7 1 0 1 0 1 [2] 4 (5) 1 5 8 9 1 6 3 7 1 0 1 0 1 2 4 5 [1] 5 8 9 1 (6) 7 3 7 1 0 (1) 0 1 2 4 5 1 5 [8] 9 1 6 7 7 3 7 [1] 0 1 0 (1) 2 4 5 1 5 8 9 1 6 7 7 9 3 7 1 0 [1] 0 1 2 (4) 5 1 5 8 9 1 6 7 7 9 2 The Elves think their skill will improve after making a few recipes (your puzzle input). However, that could take ages; you can speed this up considerably by identifying the scores of the ten recipes after that. For example: If the Elves think their skill will improve after making 9 recipes, the scores of the ten recipes after the first nine on the scoreboard would be 5158916779 (highlighted in the last line of the diagram). After 5 recipes, the scores of the next ten would be 0124515891. After 18 recipes, the scores of the next ten would be 9251071085. After 2018 recipes, the scores of the next ten would be 5941429882. What are the scores of the ten recipes immediately after the number of recipes in your puzzle input? --- Part Two --- As it turns out, you got the Elves' plan backwards. They actually want to know how many recipes appear on the scoreboard to the left of the first recipes whose scores are the digits from your puzzle input. 51589 first appears after 9 recipes. 01245 first appears after 5 recipes. 92510 first appears after 18 recipes. 59414 first appears after 2018 recipes. How many recipes appear on the scoreboard to the left of the score sequence in your puzzle input? */ public class Day14 : DayBase { public override object Part1() { int skip = int.Parse(Input); var recipes = new List<int> { 3, 7 }; int elf1 = 0, elf2 = 1; while (recipes.Count < skip + 10) { int combined = recipes[elf1] + recipes[elf2]; int new1 = combined / 10, new2 = combined % 10; if (new1 > 0) recipes.Add(new1); recipes.Add(new2); elf1 = (elf1 + recipes[elf1] + 1) % recipes.Count; elf2 = (elf2 + recipes[elf2] + 1) % recipes.Count; } return string.Join("", recipes.Skip(skip).Take(10)); } public override object Part2() { int target = int.Parse(Input), targetMod = (int)Math.Pow(10, Input.Length); var recipes = new List<int> { 3, 7 }; int elf1 = 0, elf2 = 1, num = 37; while (num != target) { int combined = recipes[elf1] + recipes[elf2]; int new1 = combined / 10, new2 = combined % 10; if (new1 > 0) { num = AddRecipe(new1); if (num == target) break; } num = AddRecipe(new2); elf1 = (elf1 + recipes[elf1] + 1) % recipes.Count; elf2 = (elf2 + recipes[elf2] + 1) % recipes.Count; } return recipes.Count - Input.Length; int AddRecipe(int recipe) { recipes.Add(recipe); return (num * 10 + recipe) % targetMod; } } [Fact] public static void Test() { var day = Program.CreateInstance(14); Assert.Equal("4138145721", day.Part1().ToString()); Assert.Equal(20276284, day.Part2()); } } }
750d47d3302e42782afe3ad47816143c1c07daf7
C#
lunarcloud/vr-game-GGJ-2019
/VR Global Game Jam 2019/Assets/Scripts/Generation/Generators/AlienNameGenerator.cs
2.625
3
public static class AlienNameGenerator { private static readonly string[] Start = { "Aaa", "Aby", "Aca", "Alk", "Ara", "Axo", "Bab", "Bar", "Bor", "Bru", "Byn", "Cal", "Cel", "Cha", "Col", "Cy", "Dae", "Dee", "Dra", "Dys", "El-", "Exo", "Ew", "Fer", "For", "Gal", "G'k", "Gor", "Hal", "Hoo", "Hyk", "Ico", "Ish", "Jen", "J'n", "Kal", "Kiv", "K't", "Lax", "Log", "Ly-", "Mac", "Mar", "Mel", "Mug", "Naa", "Neb", "Nih", "Ogr", "Osi", "Paa", "Pen", "Pri", "Pyr", "Qua", "Rea", "Rob", "Sak", "Sco", "Shi", "Sir", "S'p", "Sul", "Tal", "Ter", "Thr", "Tra", "Tus", "Ul-", "Uni", "Vaa", "Vin", "Vyr", "Wal", "Xan", "Xen", "Yeh", "Yuu", "Zeb", "Zoq" }; private static readonly string[] Middle = { "maz", "orm", "dro", "rit", "som", "dal", "tar", "ach", "uri", "ard", "lib", "zar", "lon", "noc", "'n", "led", "gon", "tur", "thr", "ton", string.Empty }; private static readonly string[] End = { "ite", "of", "ent", "an", "ish", "on", "ite", "ot", "yn", "er", string.Empty }; public static string Create(int seed) { // Build random number generator for name var rand = new Generator(seed); // Select indexes var iStart = (int)(rand.NextUint() % Start.Length); var iMiddle = (int)(rand.NextUint() % Middle.Length); var iEnd = (int)(rand.NextUint() % End.Length); // Combine name return Start[iStart] + Middle[iMiddle] + End[iEnd]; } }
dbf6ec1b8f01ce2215621325607cbac5e91d8496
C#
shendongnian/download4
/code8/1430605-38955633-124945150-2.cs
2.625
3
public PartialViewResult Search(string query) { var result = db.Users.Where(u => u.UserName.ToLower().Contains(query.ToLower())).ToList(); return PartialView("_UsersResult", result); }
c3367cea7f4b6775d63f1fba26e2134ed5852a75
C#
Quixotic7/RCSGQuake1MapImporter
/Assets/Plugins/RealtimeCSG/Editor/Thirdparty/Q1MapImporter/MapImporter.cs
2.640625
3
#if UNITY_EDITOR || RUNTIME_CSG using System; using System.Globalization; using System.IO; using System.Linq; namespace RealtimeCSG.Quake1Importer { /// <summary> /// Importer for Quake 1 Map Format (*.map) format. /// </summary> /// <remarks>Originally created by Henry de Jongh for SabreCSG.</remarks> public class MapImporter { // If true the Textures axis from the Valve map will be used to attempt to align the textures. // this is kindof buggy atm and doesn't work well for angled surfaces. public bool adjustTexturesForValve = false; /// <summary> /// Imports the specified Quake 1 Map Format file. /// </summary> /// <param name="path">The file path.</param> /// <returns>A <see cref="MapWorld"/> containing the imported world data.</returns> public MapWorld Import(string path) { // create a new world. MapWorld world = new MapWorld(); world.mapName = Path.GetFileNameWithoutExtension(path); // open the file for reading. we use streams for additional performance. // it's faster than File.ReadAllLines() as that requires two iterations. using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) using (StreamReader reader = new StreamReader(stream)) { // read all the lines from the file. int depth = 0; string line; bool justEnteredClosure = false; bool valveFormat = false; string key; object value; MapBrush brush = null; MapEntity entity = null; while (!reader.EndOfStream) { line = reader.ReadLine().Trim(); //UnityEngine.Debug.Log("Line = " + line); if (line.Length == 0) continue; // skip comments. if (line[0] == '/') continue; // parse closures and keep track of them. if (line[0] == '{') { depth++; justEnteredClosure = true; //UnityEngine.Debug.Log($"Entered Closure Depth = {depth}"); continue; } if (line[0] == '}') { depth--; //UnityEngine.Debug.Log($"Exited Closure Depth = {depth}"); continue; } // parse entity. if (depth == 1) { // create a new entity and add it to the world. if (justEnteredClosure) { entity = new MapEntity(); world.Entities.Add(entity); } // parse entity properties. if (TryParsekeyValue(line, out key, out value)) { switch (key) { case "mapversion": var version = (int)value; if(version == 220) { valveFormat = true; world.valveFormat = adjustTexturesForValve; } //UnityEngine.Debug.Log($"mapversion = {version}"); break; case "classname": entity.ClassName = (string)value; //UnityEngine.Debug.Log($"Classname = {entity.ClassName}"); break; case "_tb_type": entity.tbType = (string)value; break; case "_tb_name": entity.tbName = (string)value; break; case "_tb_id": entity.tbId = (int)value; break; case "_tb_layer": entity.tbLayer = (int)value; break; case "_tb_layer_sort_index": entity.tbLayerSortIndex = (int)value; break; case "_tb_group": entity.tbGroup = (int)value; break; } } } // parse entity brush. if (depth == 2) { // create a new brush and add it to the entity. if (justEnteredClosure) { brush = new MapBrush(); entity.Brushes.Add(brush); } // parse brush sides. MapBrushSide mapBrushSide; if (TryParseBrushSide(line, out mapBrushSide, valveFormat)) { brush.Sides.Add(mapBrushSide); } } justEnteredClosure = false; } } return world; } /// <summary> /// Tries to parse a key value line. /// </summary> /// <param name="line">The line (e.g. '"editorversion" "400"').</param> /// <param name="key">The key that was found.</param> /// <param name="value">The value that was found.</param> /// <returns>True if successful else false.</returns> private bool TryParsekeyValue(string line, out string key, out object value) { key = ""; value = null; if (!line.Contains('"')) return false; int idx = line.IndexOf('"', 1); key = line.Substring(1, idx - 1); string rawvalue = line.Substring(idx + 3, line.Length - idx - 4); if (rawvalue.Length == 0) return false; int vi; float vf; // detect floating point value. if (rawvalue.Contains('.') && float.TryParse(rawvalue, out vf)) { value = vf; return true; } // detect integer value. else if (Int32.TryParse(rawvalue, out vi)) { value = vi; return true; } // probably a string value. else { value = rawvalue; return true; } } /// <summary> /// Tries the parse a brush side line. /// </summary> /// <param name="line">The line to be parsed.</param> /// <param name="mapBrushSide">The map brush side or null.</param> /// <returns>True if successful else false.</returns> private bool TryParseBrushSide(string line, out MapBrushSide mapBrushSide, bool valveFormat) { if (valveFormat) return TryParseBrushSideValve(line, out mapBrushSide); mapBrushSide = new MapBrushSide(); // detect brush side definition. if (line[0] == '(') { string[] values = line.Replace("(", "").Replace(")", "").Replace(" ", " ").Replace(" ", " ").Trim().Split(' '); if (values.Length != 15) return false; try { MapVector3 p1 = new MapVector3(float.Parse(values[0], CultureInfo.InvariantCulture), float.Parse(values[1], CultureInfo.InvariantCulture), float.Parse(values[2], CultureInfo.InvariantCulture)); MapVector3 p2 = new MapVector3(float.Parse(values[3], CultureInfo.InvariantCulture), float.Parse(values[4], CultureInfo.InvariantCulture), float.Parse(values[5], CultureInfo.InvariantCulture)); MapVector3 p3 = new MapVector3(float.Parse(values[6], CultureInfo.InvariantCulture), float.Parse(values[7], CultureInfo.InvariantCulture), float.Parse(values[8], CultureInfo.InvariantCulture)); mapBrushSide.Plane = new MapPlane(p1, p2, p3); mapBrushSide.Material = values[9]; mapBrushSide.Offset = new MapVector2(float.Parse(values[10], CultureInfo.InvariantCulture), float.Parse(values[11], CultureInfo.InvariantCulture)); mapBrushSide.Rotation = float.Parse(values[12], CultureInfo.InvariantCulture); mapBrushSide.Scale = new MapVector2(float.Parse(values[13], CultureInfo.InvariantCulture), float.Parse(values[14], CultureInfo.InvariantCulture)); } catch (Exception) { throw new Exception("Encountered invalid brush side. The format of the map file must be slightly different, please open an issue on github if you think you did everything right."); } return true; } return false; } private bool TryParseBrushSideValve(string line, out MapBrushSide mapBrushSide) { mapBrushSide = new MapBrushSide(); // detect brush side definition. if (line[0] == '(') { string[] values = line.Replace("(", "").Replace(")", "").Replace("[", "").Replace("]", "").Replace(" ", " ").Replace(" ", " ").Trim().Split(' '); //UnityEngine.Debug.Log($"Values Length = {values.Length}"); if (values.Length != 21) return false; try { MapVector3 p1 = new MapVector3(float.Parse(values[0], CultureInfo.InvariantCulture), float.Parse(values[1], CultureInfo.InvariantCulture), float.Parse(values[2], CultureInfo.InvariantCulture)); MapVector3 p2 = new MapVector3(float.Parse(values[3], CultureInfo.InvariantCulture), float.Parse(values[4], CultureInfo.InvariantCulture), float.Parse(values[5], CultureInfo.InvariantCulture)); MapVector3 p3 = new MapVector3(float.Parse(values[6], CultureInfo.InvariantCulture), float.Parse(values[7], CultureInfo.InvariantCulture), float.Parse(values[8], CultureInfo.InvariantCulture)); mapBrushSide.Plane = new MapPlane(p1, p2, p3); mapBrushSide.Material = values[9]; mapBrushSide.t1 = new MapVector3(float.Parse(values[10], CultureInfo.InvariantCulture), float.Parse(values[11], CultureInfo.InvariantCulture), float.Parse(values[12], CultureInfo.InvariantCulture)); mapBrushSide.t2 = new MapVector3(float.Parse(values[14], CultureInfo.InvariantCulture), float.Parse(values[15], CultureInfo.InvariantCulture), float.Parse(values[16], CultureInfo.InvariantCulture)); mapBrushSide.Offset = new MapVector2(float.Parse(values[13], CultureInfo.InvariantCulture), float.Parse(values[17], CultureInfo.InvariantCulture)); mapBrushSide.Rotation = float.Parse(values[18], CultureInfo.InvariantCulture); mapBrushSide.Scale = new MapVector2(float.Parse(values[19], CultureInfo.InvariantCulture), float.Parse(values[20], CultureInfo.InvariantCulture)); } catch (Exception) { throw new Exception("Encountered invalid brush side. The format of the map file must be slightly different, please open an issue on github if you think you did everything right."); } return true; } return false; } } } #endif
248c4cf0af23383808a0e700cb58a1311e0bbfda
C#
PlumpMath/DesignPatternApp-1
/DesignPatternApp/Observer.cs
3.78125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternApp { /// <summary> /// This is an interface which attached and detached observers and /// notify it's observers when state changes. /// </summary> public interface Isubject { void Attach(IObserver observer); void Dettach(IObserver observer); void Notify(); } public interface IObserver { void NotifyPartPurchased(); } /// <summary> /// This class Implement ISubject interface and provide implementation to attach/dettach observers /// When inventory state value updated notify this change to all its registered observers. /// </summary> public class PartSubject : Isubject { List<IObserver> observers = new List<IObserver>(); private int _partStock; public int PartStock { get { return _partStock; } set { if(value > _partStock) { Notify(); } _partStock = value; } } public void Attach(IObserver observer) { observers.Add(observer); } public void Dettach(IObserver observer) { observers.Remove(observer); } public void Notify() { //Notify to observers that value of part stock has been changed. observers.ForEach(p => p.NotifyPartPurchased()); } } /// <summary> /// This class get notified when part stock has been updated /// </summary> public class PartObserver : IObserver { public string Name = string.Empty; public PartObserver(string name) { Name = name; } public void NotifyPartPurchased() { Console.WriteLine("Hey {0}, New Part has been purchased", Name); } } }
ae2cf0d406876a932ab042d031458c1a9229dc6c
C#
wujiaze/Test
/CsharpTest/C#Test/委托测试/DelTest/DelTest/Program.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DelTest { class Program { static void Main(string[] args) { DelClass.MyMed(sdf,1); Console.Read(); } private static bool sdf(int num, uint id) { Console.WriteLine(num + " / "+id); return true; } } }
fcbaf652b3c875a72df2c4d54791bdb50d01f91a
C#
edwinreg011/Coding-Dojo
/c#/oop/human/Program.cs
3.09375
3
using System; using human.Models; namespace human { class Program { static void Main(string[] args) { Human you = new Human("Carl"); Console.WriteLine(you.Name); Console.WriteLine($"Strength:{you.Strength}"); Console.WriteLine($"Intelligence:{you.Intelligence}"); Console.WriteLine($"Dexterity:{you.Dexterity}"); Console.WriteLine($"Health:{you.Health}"); Human me = new Human("Edwin", 10, 3, 5,30); Console.WriteLine(me.Name); Console.WriteLine($"Strength:{me.Strength}"); Console.WriteLine($"Intelligence:{me.Intelligence}"); Console.WriteLine($"Dexterity:{me.Dexterity}"); Console.WriteLine($"Health:{me.Health}"); me.Attack(you); } } }
88a70e06cd98ca114cd93340bf0688a0d5f170ac
C#
aangairbender/2d_rpg_from_scratch
/RPG.Math/Shape.cs
2.734375
3
namespace RPG.Math { public abstract class Shape { private BoundingBox _boundingBox; private bool _boundingBoxNeedRecalc = true; public BoundingBox BoundingBox { get { if (_boundingBoxNeedRecalc) { _boundingBox = CalculateBoundingBox(); _boundingBoxNeedRecalc = false; } return _boundingBox; } } protected abstract BoundingBox CalculateBoundingBox(); public abstract void ApplyTransform(Matrix transform); public abstract Shape Clone(); } }
591f82185581da44ccd8d87ee76f7af5eb0af064
C#
carvinchen/OwnCloudClient
/OwnCloudClient/MyWebClient.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; namespace OwnCloudClient { public class MyWebClient : WebClient { /// <summary> /// Time in milliseconds /// </summary> public int Timeout{ get; private set; } public MyWebClient() { this.Timeout = 60000; } /// <param name="timeout_ms">Set the connection timeout in milliseconds. Defaults to 60,000</param> public MyWebClient(int timeout_ms) { this.Timeout = timeout_ms; } protected override WebRequest GetWebRequest(Uri address) { var result = base.GetWebRequest(address); result.Timeout = this.Timeout; return result; } } }
bb90cd0ed41a0187907b524ba3c4dd999c9f468e
C#
dotnet/dotnet-api-docs
/snippets/csharp/System.Drawing/ColorConverter/Overview/form1.cs
2.6875
3
using System.Drawing; using System; using System.Windows.Forms; public class Form1: System.Windows.Forms.Form { #region " Windows Form Designer generated code " public Form1() : base() { //This call is required by the Windows Form Designer. InitializeComponent(); //Add any initialization after the InitializeComponent() call } //Form overrides dispose to clean up the component list. protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough] private void InitializeComponent() { // // Form1 // this.ClientSize = new System.Drawing.Size(292, 266); this.Name = "Form1"; this.Text = "Form1"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint); } #endregion // The following code example demonstrates how to use the // PointConverter.ConvertFromString and the Point.op_Subtraction // methods. This example is designed to be used with Windows // Forms. Paste this code into a form and call the // ShowPointConverter method when handling the form's Paint // event, passing e as PaintEventArgs. //<snippet1> private void ShowPointConverter(PaintEventArgs e) { // Create the PointConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Point)); Point point1 = (Point) converter.ConvertFromString("200, 200"); // Use the subtraction operator to get a second point. Point point2 = point1 - new Size(190, 190); // Draw a line between the two points. e.Graphics.DrawLine(Pens.Black, point1, point2); } //</snippet1> // The following code example demonstrates how to use the // ColorConverter.ConvertToString method. This example // is designed to be used with Windows Forms. Paste this code // into a form and call the ShowColorConverter method when // handling the form's Paint event, passing e as PaintEventArgs. //<snippet2> private void ShowColorConverter(PaintEventArgs e) { Color myColor = Color.PaleVioletRed; // Create the ColorConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(myColor); string colorAsString = converter.ConvertToString(Color.PaleVioletRed); e.Graphics.DrawString(colorAsString, this.Font, Brushes.PaleVioletRed, 50.0F, 50.0F); } //</snippet2> // The following code example demonstrates how to use the // ConvertToInvariantString and ConvertToString methods. // This example is designed to be used with Windows Forms. // Paste this code into a form and call the ShowFontStringConversion // method when handling the form's Paint event, passing e // as PaintEventArgs. //<snippet3> private void ShowFontStringConversion(PaintEventArgs e) { // Create the FontConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Font)); Font font1 = (Font) converter.ConvertFromString("Arial, 12pt"); string fontName1 = converter.ConvertToInvariantString(font1); string fontName2 = converter.ConvertToString(font1); e.Graphics.DrawString(fontName1, font1, Brushes.Red, 10, 10); e.Graphics.DrawString(fontName2, font1, Brushes.Blue, 10, 30); } //</snippet3> private void Form1_Paint(object sender, PaintEventArgs e) { ShowFontStringConversion(e); ShowPointConverter(e); ShowColorConverter(e); } [STAThread] public static void Main() { Application.Run(new Form1()); } }
8dffe970cae1e8c3915333803e6c0786c728b190
C#
DgoNeves/AdventOfCode
/2019/day3/day3.linq
3.1875
3
<Query Kind="Program" /> void Main() { var input = File.ReadAllText(@"/input.txt"); var firstWirePath = input.Split('\n')[0]; var secondWirePath = input.Split('\n')[1]; var firstWireName = "Wire_1"; var secondWireName = "Wire_2"; var dic = new Dictionary<Point, string>(); var pointsFirstWireTook = FollowSteps(dic, firstWirePath, firstWireName); var pointsSecondWireTook = FollowSteps(dic, secondWirePath, secondWireName); // Part 1 pointsSecondWireTook .Where(x => x.Value.Contains(firstWireName) && x.Value.Contains(secondWireName)) .Select(x => Math.Abs(x.Key.X) + Math.Abs(x.Key.Y)) .OrderBy(x => x) .First() .Dump(); // Part 2 var result = pointsSecondWireTook .Where(x => x.Value.Contains(firstWireName) && x.Value.Contains(secondWireName)) .Select(x => int.Parse(x.Value.Split(new char[] {':', ','})[1]) + int.Parse(x.Value.Split(new char[] {':', ','})[3])) .First() .Dump(); } Dictionary<Point, string> FollowSteps(Dictionary<Point, string> dic,string stepText, string shipName) { var steps = stepText.Split(','); var startingPoint = new Point(0,0); var totalStepsTaken = 0; foreach (var step in steps) { var direction = step.First(); var number = int.Parse(step.Substring(1)); var nextPoints = Point.GetPoints(startingPoint, direction, number); startingPoint = nextPoints.Last(); foreach (var point in nextPoints) { totalStepsTaken++; if(!dic.ContainsKey(point)) dic.Add(point,$"{shipName}:{totalStepsTaken}"); else { dic[point] += $",{shipName}:{totalStepsTaken}"; } } } return dic; } class Point { public int X { get; set; } public int Y { get; set; } public Point(int x, int y) { this.X = x; this.Y = y; } public static List<Point> GetPoints(Point startingPoint, char dir, int steps) { if(dir == 'R') { return Enumerable.Range(1, steps) .Select(i => new Point(startingPoint.X + i ,startingPoint.Y)).ToList(); } if (dir == 'L') { return Enumerable.Range(1, steps) .Select(i => new Point(startingPoint.X -i , startingPoint.Y)).ToList(); } if (dir == 'U') { return Enumerable.Range(1, steps) .Select(i => new Point(startingPoint.X, startingPoint.Y + i)).ToList(); } if (dir == 'D') { return Enumerable.Range(1, steps) .Select(i => new Point(startingPoint.X, startingPoint.Y - i)).ToList(); } throw new Exception("Wrong direction!"); } public override int GetHashCode() { return this.X.GetHashCode() + this.Y.GetHashCode(); } public override bool Equals(object obj) { if(obj is Point p) return p.X == this.X && p.Y == this.Y; return base.Equals(obj); } } // Define other methods and classes here
21757fef08bcfa7e8f6fdffeee8d90a8c55566ca
C#
phr00t/bepuphysics2
/BepuPhysics/PositionLastTimestepper.cs
2.859375
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using BepuUtilities; namespace BepuPhysics { /// <summary> /// Updates the simulation in the order of: sleeper -> integrate velocities and update body bounding boxes -> collision detection -> solver -> integrate body poses -> data structure optimization. /// </summary> public class PositionLastTimestepper : ITimestepper { /// <summary> /// Fires after the sleeper completes and before bodies are integrated. /// </summary> public event TimestepperStageHandler Slept; /// <summary> /// Fires after bodies have had their velocities and bounding boxes updated, but before collision detection begins. /// </summary> public event TimestepperStageHandler BeforeCollisionDetection; /// <summary> /// Fires after all collisions have been identified, but before constraints are solved. /// </summary> public event TimestepperStageHandler CollisionsDetected; /// <summary> /// Fires after the solver executes and before body poses are integrated. /// </summary> public event TimestepperStageHandler ConstraintsSolved; /// <summary> /// Fires after bodies have their poses integrated and before data structures are incrementally optimized. /// </summary> public event TimestepperStageHandler PosesIntegrated; public void Timestep(Simulation simulation, float dt, IThreadDispatcher threadDispatcher = null) { simulation.Sleep(threadDispatcher); Slept?.Invoke(dt, threadDispatcher); simulation.IntegrateVelocitiesBoundsAndInertias(dt, threadDispatcher); BeforeCollisionDetection?.Invoke(dt, threadDispatcher); simulation.CollisionDetection(dt, threadDispatcher); CollisionsDetected?.Invoke(dt, threadDispatcher); simulation.Solve(dt, threadDispatcher); ConstraintsSolved?.Invoke(dt, threadDispatcher); simulation.IntegratePoses(dt, threadDispatcher); PosesIntegrated?.Invoke(dt, threadDispatcher); simulation.IncrementallyOptimizeDataStructures(threadDispatcher); } } }
7a856e90861c56232196cae31b2f98c0904c9c61
C#
tk-yoshimura/TensorShader
/TensorShader/Links/TrinaryArithmetric/Clamp.cs
2.6875
3
using static TensorShader.VariableNode; namespace TensorShader { public partial class Field { /// <summary>Clamp</summary> public static Field Clamp(Field x, Field xmin, Field xmax) { Field y = new(); Link link = new Links.TrinaryArithmetric.Clamp(x, xmin, xmax, y); link.Forward(); return y; } } } namespace TensorShader.Links.TrinaryArithmetric { /// <summary>Clamp</summary> internal class Clamp : TrinaryArithmetric { /// <summary>コンストラクタ</summary> public Clamp(Field infield1, Field infield2, Field infield3, Field outfield) : base(infield1, infield2, infield3, outfield) { } /// <summary>順伝搬</summary> public override void Forward() { Y.AssignValue(Clamp(X1.Value, X2.Value, X3.Value)); } /// <summary>逆伝搬</summary> public override void Backward() { if (Y.Grad is null) { return; } if (X1.EnableBackprop) { X1.AddGrad(Y.Grad * LessThanOrEqual(X2.Value, X1.Value) * LessThanOrEqual(X1.Value, X3.Value)); } if (X2.EnableBackprop) { X2.AddGrad(Y.Grad * GreaterThan(X2.Value, X1.Value)); } if (X3.EnableBackprop) { X3.AddGrad(Y.Grad * GreaterThan(X1.Value, X3.Value)); } } } }
b7360386f1e8a41d27bbe3c4e807139fe786d37b
C#
MatthiasSchilder/DotSpatial
/Source/Core/DotSpatial.Controls/Docking/IDockManager.cs
2.53125
3
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel.Composition; namespace DotSpatial.Controls.Docking { /// <summary> /// An interface that allows plugins to add controls which are managed by the application as forms or docking panels. /// </summary> [InheritedExport] public interface IDockManager { #region Events /// <summary> /// Occurs when the active panel is changed, meaning a difference panel is activated. /// </summary> event EventHandler<DockablePanelEventArgs> ActivePanelChanged; /// <summary> /// Occurs after a panel is added. /// </summary> event EventHandler<DockablePanelEventArgs> PanelAdded; /// <summary> /// Occurs when a panel is closed, which means the panel can still be activated or removed. /// </summary> event EventHandler<DockablePanelEventArgs> PanelClosed; /// <summary> /// Occurs when a panel is hidden. /// </summary> event EventHandler<DockablePanelEventArgs> PanelHidden; /// <summary> /// Occurs after a panel is removed. /// </summary> event EventHandler<DockablePanelEventArgs> PanelRemoved; #endregion #region Methods /// <summary> /// Adds the specified panel. /// </summary> /// <param name="panel"> /// The panel. /// </param> void Add(DockablePanel panel); /// <summary> /// Hides the panel. A subsequent call to SelectPanel will show this panel in the same place it was when hidden. /// </summary> /// <param name="key">The key.</param> void HidePanel(string key); /// <summary> /// Removes the specified panel. /// </summary> /// <param name="key"> /// The key. /// </param> void Remove(string key); /// <summary> /// Resets the layout of the dock panels to a developer specified location. /// </summary> void ResetLayout(); /// <summary> /// Activates and selects the panel. /// </summary> /// <param name="key"> /// The key. /// </param> void SelectPanel(string key); /// <summary> /// Shows the panel but does not select it. /// </summary> /// <param name="key">The key.</param> void ShowPanel(string key); #endregion } }
4808ce7ea89be73ce504bd9620030b8eebaab624
C#
przemyslawzaworski/Unity3D-C-programming
/AssetBundle/AssetBundleManager.cs
2.53125
3
using UnityEngine; public class AssetBundleManager : MonoBehaviour { // structure for storing prefab data struct Data { public AssetBundle Bundle; public GameObject Instance; } // container Data _Container; // load prefab to memory Data LoadAssetInstance(string path, string address) { AssetBundle bundle = AssetBundle.LoadFromFile(path); GameObject instance = Instantiate(bundle.LoadAsset<GameObject>(address)); Data data = new Data(); data.Bundle = bundle; data.Instance = instance; return data; } // unload prefab from memory void UnloadAssetInstance (Data data) { Destroy(data.Instance); data.Bundle.Unload(true); Resources.UnloadUnusedAssets(); } // example usage: void Update() { if (Input.GetKeyDown(KeyCode.O)) { _Container = LoadAssetInstance("D:\\Mods\\test_group_assets_all_7226dcfc3174ecd7d6182fefc9cc0273.bundle", "Assets/Prefabs/Sphere.prefab"); } if (Input.GetKeyDown(KeyCode.P)) { UnloadAssetInstance(_Container); } } }
217e1bfda28a6349f2f00ce2d7541577fadb857b
C#
mathusummut/Ablaze.Net
/Ablaze.UI/System/Windows.Forms/UserListBox.cs
2.796875
3
using System.Collections.Generic; using System.ComponentModel; using System.Drawing; namespace System.Windows.Forms { /// <summary> /// An interactive list box supporting 'Add New...', and move up and move down arrow buttons. /// </summary> [ToolboxItem(true)] [ToolboxItemFilter("System.Windows.Forms")] [DesignTimeVisible(true)] [DesignerCategory("CommonControls")] [DefaultEvent(nameof(ItemAdded))] [Description("An interactive list box supporting 'Add New...', and move up and move down arrow buttons.")] [DisplayName(nameof(UserListBox))] public class UserListBox : UserControl { private ListBox listBox; private StyledArrowButton upButton, downButton; private SplitContainer SplitContainer; private int defaultButtonWidth = 45, minButtonWidth = 16; private bool removeDuplicates, showDirections = true; /// <summary> /// A delegate representing a method called when an item was added or removed. /// </summary> /// <param name="items">A new list of all iems in the list box.</param> public delegate void ItemsChangedEventHandler(string[] items); /// <summary> /// A delegate representing a method called when an item has beem moved up or moved down. /// </summary> /// <param name="upperItem">The first (starting from top) item whose order was changed.</param> /// <param name="lowerItem">The botton (starting from top) item whose order was changed.</param> /// <param name="upperItemIndex">The index of upperItem (the index of lowerItem is upperItem + 1).</param> public delegate void ItemOrderChangedEventHandler(string upperItem, string lowerItem, int upperItemIndex); /// <summary> /// Fired when an item was added or removed. /// </summary> [Description("Fired when an item was added or removed.")] public event ItemsChangedEventHandler ItemsChanged; /// <summary> /// Fired when an item was added. /// </summary> [Description("Fired when an item was added.")] public event Action<string> ItemAdded; /// <summary> /// Fired when an item was removed. /// </summary> [Description("Fired when an item was removed.")] public event Action<string> ItemRemoved; /// <summary> /// Fired when an item has beem moved up or moved down. /// </summary> [Description("Fired when an item has beem moved up or moved down.")] public event ItemOrderChangedEventHandler ItemOrderChanged; /// <summary> /// The add item prompt text. /// </summary> public string PromptText = "Add Entry:"; /// <summary> /// The add item prompt caption. /// </summary> public string PromptTitle = "Add"; /// <summary> /// The add item prompt button text. /// </summary> public string PromptButton = "Add"; /// <summary> /// Gets a list of all items in the list. /// </summary> [Browsable(false)] public string[] Items { get { string[] items = new string[listBox.Items.Count - 1]; for (int i = 0; i < listBox.Items.Count - 1; i++) items[i] = listBox.Items[i].ToString(); return items; } } /// <summary> /// Whether to remove or keep duplicates in the list. /// </summary> [Description("Whether to remove or keep duplicates in the list.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public bool RemoveDuplicates { get { return removeDuplicates; } set { removeDuplicates = value; if (removeDuplicates) { string[] currentElements = Items; List<string> newList = new List<string>(); foreach (string str in currentElements) { if (!newList.Contains(str)) newList.Add(str); } listBox.Items.Clear(); foreach (string s in newList) listBox.Items.Add(s); listBox.Items.Add("Add New..."); } } } /// <summary> /// The minimum arrow button widths. /// </summary> [Description("The minimum arrow button widths.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public int MinButtonWidth { get { return minButtonWidth; } set { minButtonWidth = value; if (showDirections) SplitContainer.Panel2MinSize = value; } } /// <summary> /// Whether to show the move up and down arrow buttons. /// </summary> [Description("Whether to show the move up and down arrow buttons.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public bool ShowDirectionButtons { get { return showDirections; } set { if (value == showDirections) return; showDirections = value; if (value) { SplitContainer.Panel2.Controls.Add(upButton); SplitContainer.Panel2.Controls.Add(downButton); } else { SplitContainer.Panel2.Controls.Remove(upButton); SplitContainer.Panel2.Controls.Remove(downButton); } OnResize(null); } } /// <summary> /// The ListBox control. /// </summary> [Description("The ListBox control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public ListBox ListBox { get { return listBox; } } /// <summary> /// The up arrow button control. /// </summary> [Description("The up arrow button control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public StyledArrowButton UpButton { get { return upButton; } } /// <summary> /// The down arrow button control. /// </summary> [Description("The down arrow button control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public StyledArrowButton DownButton { get { return downButton; } } /// <summary> /// Gets or sets whether to trim trailing spaces to user input. /// </summary> [Description("Gets or sets whether to trim trailing spaces to user input.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public bool TrimSpaces { get; set; } /// <summary> /// Gets or sets the default button width, which is overriden when the splitter is resized. /// </summary> [Description("Gets or sets the default button width, which is overriden when the splitter is resized.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public int DefaultButtonWidth { get { return defaultButtonWidth; } set { if (value == defaultButtonWidth) return; defaultButtonWidth = value; OnResize(null); } } /// <summary> /// Initializes an empty list box. /// </summary> public UserListBox() : this(true, null) { } /// <summary> /// Initializes a list box, spcifying whether to show the move up and down arrow buttons. /// </summary> /// <param name="showButtons">Whether to show the move up and down arrow buttons.</param> public UserListBox(bool showButtons) : this(showButtons, null) { } /// <summary> /// Initializes a list box with the specified initial items. /// </summary> /// <param name="items">The items to add to the list box.</param> public UserListBox(params string[] items) : this(true, items) { } /// <summary> /// Initializes a list box with the specified initial items. /// </summary> /// <param name="showButtons">Whether to show the move up and down arrow buttons.</param> /// <param name="items">The items to add to the list box (can be null).</param> public UserListBox(bool showButtons, params string[] items) { TrimSpaces = true; listBox = new ListBox(); SplitContainer = new SplitContainer(); downButton = new StyledArrowButton(); upButton = new StyledArrowButton(); SplitContainer.Panel1.SuspendLayout(); SplitContainer.Panel2.SuspendLayout(); SplitContainer.SuspendLayout(); SuspendLayout(); listBox.BorderStyle = BorderStyle.None; listBox.Dock = DockStyle.Fill; listBox.Font = new Font("Calibri Light", 12F, FontStyle.Regular, GraphicsUnit.Point, 0); listBox.FormattingEnabled = true; listBox.IntegralHeight = false; listBox.ItemHeight = 19; if (!(items == null || items.Length == 0)) listBox.Items.AddRange(items); listBox.Items.Add("Add New..."); listBox.Location = Point.Empty; listBox.Name = nameof(ListBox); listBox.ScrollAlwaysVisible = true; listBox.Size = new Size(320, 356); listBox.TabIndex = 0; listBox.SelectedIndexChanged += ListBox_SelectedIndexChanged; listBox.MouseDown += ListBox_MouseUp; SplitContainer.Dock = DockStyle.Fill; SplitContainer.Location = Point.Empty; SplitContainer.Name = nameof(SplitContainer); SplitContainer.Panel1.Controls.Add(listBox); SplitContainer.Size = new Size(382, 356); SplitContainer.SplitterDistance = 320; SplitContainer.SplitterWidth = 4; SplitContainer.TabIndex = 3; SplitContainer.SplitterMoved += SplitContainer_SplitterMoved; downButton.BackColor = BackColor; downButton.BackgroundImageLayout = ImageLayout.Stretch; downButton.Dock = DockStyle.Bottom; downButton.Location = new Point(0, 295); downButton.Name = nameof(DownButton); downButton.Rotation = 180F; downButton.Size = new Size(61, 61); downButton.TabIndex = 2; downButton.Click += button2_Click; upButton.BackColor = BackColor; upButton.BackgroundImageLayout = ImageLayout.Stretch; upButton.Dock = DockStyle.Top; upButton.Location = Point.Empty; upButton.Name = nameof(UpButton); upButton.Size = new Size(61, 61); upButton.TabIndex = 1; upButton.Click += button1_Click; Controls.Add(SplitContainer); Name = nameof(UserListBox); Size = new Size(382, 356); this.showDirections = showButtons; if (showButtons) { SplitContainer.Panel2.Controls.Add(upButton); SplitContainer.Panel2.Controls.Add(downButton); } SplitContainer.Panel1.ResumeLayout(false); SplitContainer.Panel2.ResumeLayout(false); SplitContainer.ResumeLayout(false); ResumeLayout(false); } /// <summary> /// Called when the list box is resized. /// </summary> protected override void OnResize(EventArgs e) { if (e != null) base.OnResize(e); if (showDirections) { SplitContainer.Panel2MinSize = minButtonWidth; upButton.Height = Math.Min(upButton.Width, ClientSize.Height / 2); downButton.Height = Math.Min(upButton.Width, ClientSize.Height / 2); if (SplitContainer.Panel1MinSize <= Width) SplitContainer.SplitterDistance = ClientSize.Width - (defaultButtonWidth + SplitContainer.SplitterWidth); } else { SplitContainer.Panel2MinSize = 0; if (SplitContainer.Panel1MinSize <= Width) SplitContainer.SplitterDistance = ClientSize.Width; } } private void SplitContainer_SplitterMoved(object sender, SplitterEventArgs e) { if (showDirections) { upButton.Height = Math.Min(upButton.Width, ClientSize.Height / 2); downButton.Height = Math.Min(upButton.Width, ClientSize.Height / 2); } } private void ListBox_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right && !(listBox.SelectedIndex == -1 || listBox.SelectedIndex == listBox.Items.Count - 1)) { string item = listBox.Items[listBox.SelectedIndex].ToString(); listBox.Items.RemoveAt(listBox.SelectedIndex); Action<string> itemRemoved = ItemRemoved; if (itemRemoved != null) itemRemoved(item); ItemsChangedEventHandler itemsChanged = ItemsChanged; if (itemsChanged != null) itemsChanged(Items); } } private void ListBox_SelectedIndexChanged(object sender, EventArgs e) { if (listBox.SelectedIndex == listBox.Items.Count - 1) ShowAddItemPrompt(); } /// <summary> /// Shows a new item prompt to the user and adds the item if the user accepts. /// </summary> protected virtual void ShowAddItemPrompt() { TextDialog dialog = new TextDialog(PromptText, PromptTitle, PromptButton); if (MessageLoop.ShowDialog(dialog) == DialogResult.OK) AddItem(dialog.Input); } /// <summary> /// Adds the specified item to list box. /// </summary> /// <param name="item">The item to add.</param> public void AddItem(string item) { if (item == null) item = string.Empty; if (TrimSpaces) item = item.Trim(); if (item.Length == 0) return; string[] items = Items; if (removeDuplicates && Contains(items, item)) return; listBox.Items.Insert(listBox.Items.Count - 1, item); Action<string> itemAdded = ItemAdded; if (itemAdded != null) itemAdded(item); ItemsChangedEventHandler itemsChanged = ItemsChanged; if (itemsChanged != null) itemsChanged(Items); } /// <summary> /// Gets whether the specified array contains the specified element. /// </summary> /// <typeparam name="T">The type of the array.</typeparam> /// <param name="array">The array to search for the item into.</param> /// <param name="element">The item to search for in the array.</param> public static bool Contains<T>(T[] array, T element) { if (array == null) return false; for (int i = 0; i < array.Length; i++) { if (array[i] == null) { if (element == null) return true; } else if (array[i].Equals(element)) return true; } return false; } private void button1_Click(object sender, EventArgs e) { int index = listBox.SelectedIndex; if (index <= 0 || index == listBox.Items.Count - 1) return; string belowItem = listBox.Items[index].ToString(); string upperItem = listBox.Items[index - 1].ToString(); listBox.Items[index] = upperItem; index--; listBox.Items[index] = belowItem; listBox.SelectedIndex = index; ItemOrderChangedEventHandler itemOrderChanged = ItemOrderChanged; if (itemOrderChanged != null) itemOrderChanged(belowItem, upperItem, index); } private void button2_Click(object sender, EventArgs e) { int index = listBox.SelectedIndex; if (index == -1 || index >= listBox.Items.Count - 2) return; string belowItem = listBox.Items[index].ToString(); string upperItem = listBox.Items[index + 1].ToString(); listBox.Items[index] = upperItem; listBox.Items[index + 1] = belowItem; listBox.SelectedIndex = index + 1; ItemOrderChangedEventHandler itemOrderChanged = ItemOrderChanged; if (itemOrderChanged != null) itemOrderChanged(upperItem, belowItem, index); } } }
43afc4ee7d36682ff6c37ca279fa616021ccc6dc
C#
Clepcidre/TriEngine
/TriDevs.TriEngine/Rectangle.cs
3.359375
3
/* Rectangle.cs * * Copyright © 2013 by Adam Hellberg, Sijmen Schoon and Preston Shumway. * * 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; namespace TriDevs.TriEngine { /// <summary> /// A rectangle representing an area in 2D space. /// </summary> public struct Rectangle : IEquatable<Rectangle> { /// <summary> /// The X position of this rectangle, in screen pixels. /// </summary> public readonly int X; /// <summary> /// The Y position of this rectangle, in screen pixels. /// </summary> public readonly int Y; /// <summary> /// The width of this rectangle in pixels. /// </summary> public readonly int Width; /// <summary> /// The height of this rectangle in pixels. /// </summary> public readonly int Height; /// <summary> /// Optional color of this rectangle, if it is to be drawn onto the screen. /// </summary> public readonly Color Color; /// <summary> /// Initializes a new <see cref="Rectangle" /> with position and size based on two /// point objects. /// </summary> /// <param name="position">The point to get position from.</param> /// <param name="size">The point to get width and height from.</param> /// <param name="color">Color of this rectangle, set to null for default color of black.</param> public Rectangle(Point<int> position, Point<int> size, Color? color = null) : this(position.X, position.Y, size.X, size.Y, color) { } /// <summary> /// Initializes a new rectangle with specified position and size. /// </summary> /// <param name="x">X-position of this rectangle, in screen pixels.</param> /// <param name="y">Y-position of this rectangle, in screen pixels.</param> /// <param name="width">Width of this rectangle, in pixels.</param> /// <param name="height">Height of this rectangle, in pixels.</param> /// <param name="color">Color of this rectangle, set to null for default color of black.</param> public Rectangle(int x, int y, int width, int height, Color? color = null) { X = x; Y = y; Width = width; Height = height; Color = color.HasValue ? color.Value : Color.Black; } /// <summary> /// Returns whether this rectangle is intersecting with another rectangle. /// </summary> /// <param name="other">Rectangle to check against.</param> /// <returns>True if this rectangle is intersecting with the other rectangle, false otherwise.</returns> public bool Intersects(Rectangle other) { if (Equals(other)) return true; if (X >= other.X && (X + Width) <= (other.X + other.Width)) return true; if (X < other.X && (X + Width) >= other.X) return true; if (Y >= other.Y && (Y + Height) <= (other.Y + other.Height)) return true; if (Y < other.Y && (Y + Height) >= other.Y) return true; return false; } public bool Equals(Rectangle other) { return X == other.X && Y == other.Y && Width == other.Width && Height == other.Height; } } }
7ef94747b4dd7505be033fb0bdd9ed8d5af5ee0a
C#
jackbrown109/procedural-generation
/Assets/Resources/Scripts/Pathfinding/Heap.cs
3.421875
3
using UnityEngine; using System.Collections; using System; public class Heap<T> where T : IHeapItem<T> { T[] items; int currentItemCount; // Amount of items currently in the heap //================================================================================= // Constructor for the Heap class //================================================================================= public Heap(int maxHeapSize) { items = new T[maxHeapSize]; } //================================================================================= // Function used to add new items to the heap //================================================================================= public void Add(T item) { item.HeapIndex = currentItemCount; items[currentItemCount] = item; // puts new item at the end of the array SortUp(item); // jump to SortUp function to check whether it's position in the array needs changing currentItemCount++; // increase currentItemCount by 1 } //================================================================================= // Removes the first item from the heap //================================================================================= public T RemoveFirst() { T firstItem = items[0]; currentItemCount--; // decrease currentItemCount by 1 items[0] = items[currentItemCount]; //takes item at the end of the heap and put it in the first position items[0].HeapIndex = 0; SortDown(items[0]); // jumps to sort down function return firstItem; } //================================================================================= // Used if the priority of an item needs to be changed due to a node in pathfinding // openSet having a change in fCost due to a new path to it. //================================================================================= public void UpdateItem(T item) { SortUp(item); // SortUp called, priority will only increase, so SortDown not necessary } //================================================================================= // Accessor to the number of items currently in the heap //================================================================================= public int Count { get { return currentItemCount; } } //================================================================================= // Checks if the heap contains a specific item //================================================================================= public bool Contains(T item) { return Equals(items[item.HeapIndex], item); } //================================================================================= // Checks parent against its children to see whether it needs to be moved down. //================================================================================= void SortDown(T item) { while (true) { int childIndexLeft = item.HeapIndex * 2 + 1; int childIndexRight = item.HeapIndex * 2 + 2; int swapIndex = 0; // If the parent item has a left child if (childIndexLeft < currentItemCount) { swapIndex = childIndexLeft; // Sets swapIndex to childIndexLeft by default // If the parent item also has a right child if (childIndexRight < currentItemCount) { // Check to see which of the child indicies, left or right is higher (higher one becomes swapIndex) if (items[childIndexLeft].CompareTo(items[childIndexRight]) < 0) { swapIndex = childIndexRight; // Sets swapIndex to childIndexRight if it's higher } } // Checks if parent has lower priority than it's highest priority child if (item.CompareTo(items[swapIndex]) < 0) { Swap(item, items[swapIndex]); // jumps to Swap function to swap the parent with it's child } // If parent's priority is higher, return else { return; } } // If parent has no children, return else { return; } } } //================================================================================= // Compares items with their parent, to see whether it has a higher priority. // The parentIndex will equal -1 if the item has a lower priority, 0 if it has the // same priority, or 1 if it has a higher priority. //================================================================================= void SortUp(T item) { // Calculates parent index to compare item to it's parent int parentIndex = (item.HeapIndex - 1) / 2; while (true) { T parentItem = items[parentIndex]; // If the item has a higher priority than parent item, item needs to be swapped with parent if (item.CompareTo(parentItem) > 0) { Swap(item, parentItem); //Jumps to Swap function to swap item with parent item } // Once item is no longer of a higher priority, break out of the loop else { break; } // Otherwise continue calculating the parent index and comparing item to its new parent parentIndex = (item.HeapIndex - 1) / 2; } } //================================================================================= // Swap function is used to swap item with its parent //================================================================================= void Swap(T itemA, T itemB) { items[itemA.HeapIndex] = itemB; items[itemB.HeapIndex] = itemA; int itemAIndex = itemA.HeapIndex; itemA.HeapIndex = itemB.HeapIndex; itemB.HeapIndex = itemAIndex; } } //================================================================================= // Interface used so items can keep track of their index in the heap, and allows // items to be compared to others to sort priority in the heap. //================================================================================= public interface IHeapItem<T> : IComparable<T> { int HeapIndex { get; set; } }
fc7937d912c9388d3f12e77acb3c32f8f931f116
C#
shendongnian/download4
/code1/106235-3514865-7330556-2.cs
3.078125
3
public static object ConvertCustomDate(string input, string inputFormat) { Date dt= DateTime.ParseExact(input, inputFormat, CultureInfo.CurrentCulture); return new { Month=dt.ToString("MMMM"), Year=dt.ToString("yyyy") }; }
1d258f369d83b6da9fc24afb0bac74b6d7639068
C#
riesaexe/WikiPicDownload
/Win_Equip/Form1.cs
2.703125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Win_Equip { using System.IO; using System.Net; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void txtSavePath_Click(object sender, EventArgs e) { FolderBrowserDialog folder = new FolderBrowserDialog(); if (folder.ShowDialog() == DialogResult.OK) { this.txtSavePath.Text = folder.SelectedPath; } if (this.txtSavePath.Text != "E:/WikiPic/") { this.txtSavePath.Text += @"\"; } } private void btnDownload_Click(object sender, EventArgs e) { string savePath = txtSavePath.Text.Trim(); string requestUrl = "http://file.fgowiki.fgowiki.com/fgo/card/equip/"; int min = Convert.ToInt32(txtMin.Text.Trim()); int max = Convert.ToInt32(txtMax.Text.Trim()); if (string.IsNullOrEmpty(savePath)) { MessageBox.Show("请选择保存路径"); return; } //匿名委托 System.Threading.Thread th = new System.Threading.Thread(() => { ProcessDownload(savePath, requestUrl, min, max); }); th.IsBackground = true; th.Start(); } #region 执行下载操作 - void ProcessDownload(string savePath, string requestUrl, int min, int max) /// <summary> /// 执行下载操作 /// </summary> /// <param name="savePath">图片保存的路径</param> /// <param name="requestUrl">请求图片的url地址</param> /// <param name="min">礼装编号最小值</param> /// <param name="max">礼装编号最大值</param> private void ProcessDownload(string savePath, string requestUrl, int min, int max) { for (int i = min; i <= max; i++) { string fileName = i.ToString("000"); string tmpFileName = fileName; string tmpRequestUrl = requestUrl; string tmpSavePath = savePath; tmpFileName += "A.png";//002A.png tmpRequestUrl += tmpFileName; tmpSavePath += tmpFileName; WebRequest request = WebRequest.Create(tmpRequestUrl); if (!Directory.Exists(savePath))//不存在则创建 { Directory.CreateDirectory(savePath); } try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { using (Stream stream = response.GetResponseStream() , fsStream = new FileStream(tmpSavePath, FileMode.Create)) { stream.CopyTo(fsStream);//数据流.CopyTo(目标流) } } } } catch (WebException ex) { continue; } } MessageBox.Show("下载完成!"); } #endregion } }
6bd708660c4323fba7772aa7346543f3326c018a
C#
sahil-tandon/IS7024-BandItFinal
/BandIt/WcfService1/WcfService1/JSONGenerator.cs
2.921875
3
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Xml.Serialization; namespace WcfService1 { public class JSONGenerator { /* Method to Generate the BANDS JSON and return the serialized String to the UI. */ public static string generateBandJSON() { BandsCollection bands = DeserializeBandSchema(); if (bands != null) { return JsonConvert.SerializeObject(bands); } else { return ""; } } /* Method to Generate the BAND NAMES JSON and return the serialized String to the UI. */ public static string generateBandNames() { BandsCollection bands = DeserializeBandSchema(); List<string> bandNames = new List<string>(); foreach (BandJSON band in bands.band) { bandNames.Add(band.BandName); } return JsonConvert.SerializeObject(bandNames); } /* Method to Generate the SONG NAMES JSON and return the serialized String to the UI. */ public static string generateSongNames() { BandsCollection bands = DeserializeBandSchema(); List<string> songNames = new List<string>(); foreach (BandJSON band in bands.band) { foreach (Songs song in band.Songs) { songNames.Add(song.SongName); } } return JsonConvert.SerializeObject(songNames); } /* Method to Generate the SONGS JSON and return the serialized String to the UI. */ public static string generateSongJSON() { BandsCollection bands = DeserializeBandSchema(); if (bands != null) { List<Songs> songs = new List<Songs>(); foreach (BandJSON band in bands.band) { foreach (Songs song in band.Songs) { Songs songDetails = new Songs { BandName = band.BandName, SongName = song.SongName, Rating = song.Rating, Duration = song.Duration }; songs.Add(songDetails); } } return JsonConvert.SerializeObject(songs); } else { return ""; } } /* Utility Method to deserialize the bands XML Schema and return a c# object */ public static BandsCollection DeserializeBandSchema() { BandsCollection bands = null; XmlSerializer serializer = new XmlSerializer(typeof(BandsCollection)); WebClient client = new WebClient(); Uri uri = HttpContext.Current.Request.Url; String host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; Stream stream = client.OpenRead(host + "/BandSchema.xml"); StreamReader reader = new StreamReader(stream); bands = (BandsCollection)serializer.Deserialize(reader); reader.Close(); return bands; } /* Method to Generate the current time using Google Timezon API */ public static string generateTimeString() { DateTime currentDateTime = GetTimeService.GetLocalDateTime(39.1347212, -84.51388365493398, DateTime.UtcNow); String time = (currentDateTime.TimeOfDay.Hours).ToString() + ":" + (currentDateTime.TimeOfDay.Minutes).ToString(); return JsonConvert.SerializeObject(time); } } }
889f44ce08bc5a1877261ca208e6b3bf3a23f73d
C#
genrys/Light-is-Rescue
/Project/Roll a Ball/Assets/Scripts/CollectableObjects/Rotator.cs
2.6875
3
using UnityEngine; using System.Collections; public class Rotator : MonoBehaviour { private GameObject displayManager; private int lastPointsByCollect; private string nameOfGround; public Transform pickParticle; public Color objectColor; public Vector3 rotationDirection; public float speedOfObject; public int pointsByCollect; public string playerTag; private void Start() { Initialize(); } private void Update() { ColorOfObject(); RotatingObject(); } /// <summary> /// Check collision with other object /// </summary> /// <param name="other"></param> private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag(playerTag)) { Instantiate(pickParticle, transform.position, transform.rotation); displayManager.GetComponent<DisplayTextManager>().SetCount(pointsByCollect); DeactivateObject(); } } /// <summary> /// Deactivate object in hirearchy /// </summary> private void DeactivateObject() { gameObject.SetActive(false); } /// <summary> /// Set charachters an object by parameters /// </summary> /// <param name="objColor"></param> /// <param name="pointsForCollect"></param> public void SetCharactersOfObject(Color objColor, int pointsForCollect) { objectColor = objColor; gameObject.GetComponent<Renderer>().material.color = objectColor; pointsByCollect = pointsForCollect; lastPointsByCollect = pointsByCollect; } /// <summary> /// Rotating an object every frame /// </summary> private void RotatingObject() { transform.Rotate(rotationDirection * speedOfObject * Time.deltaTime); } /// <summary> /// Set color if it will be change /// </summary> private void ColorOfObject() { if (gameObject.GetComponent<Renderer>().material.color.Equals(Color.red)) pointsByCollect = 5; else pointsByCollect = lastPointsByCollect; gameObject.GetComponent<Renderer>().material.color = objectColor; } /// <summary> /// Initializing all variables /// </summary> private void Initialize() { nameOfGround = "Ground"; playerTag = "Player"; displayManager = GameObject.Find(nameOfGround); } }
3a1de175e2f6fa36a9ed1de0fd89946fe3ed5090
C#
TenchuHawke/TheWallC
/Models/User.cs
2.796875
3
using System.ComponentModel.DataAnnotations; namespace TheWall.Models { public abstract class BaseEntity {} public class User : BaseEntity { [Key] public int UId { get; set; } [Required] [MinLength (2)] public string FirstName { get; set; } [Required] [MinLength (2)] public string LastName { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Required] public string Password { get; set; } // public System.DateTime Birthday { get; set; } // public System.DateTime HireDate { get; set; } public System.DateTime CreatedAt { get; set; } public System.DateTime UpdatedAt { get; set; } } public class UserValidation : User { [Required (ErrorMessage = "First Name is required.")] [MinLength (2, ErrorMessage = "First Name must be at least 2 characters.")] public new string FirstName { get; set; } [Required (ErrorMessage = "Last Name is required.")] [MinLength (2, ErrorMessage = "Last Name must be at least 2 characters.")] public new string LastName { get; set; } [Required (ErrorMessage = "E-mail address is required.")] [MinLength (6)] [EmailAddress (ErrorMessage = "E-mail address is not valid.")] public new string Email { get; set; } // [Required( ErrorMessage = "Username is required.")] // [MinLength (2)( ErrorMessage = "Username must be at least 2 characters.")] // public new string Username { get; set; } [Required (ErrorMessage = "Password is required.")] [MinLength (8, ErrorMessage = "Password must be at least 8 characters long")] // [RegularExpression("(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9])$", ErrorMessage = "Your Password must contain a Number, a lower Case Letter, and a Capitol Letter.")] public new string Password { get; set; } [Required (ErrorMessage = "Password Confirmation is required.")] [Compare ("Password", ErrorMessage = "Password and Password Confirmation must match")] public string PasswordConfirm { get; set; } // public System.DateTime Birthday { get; set; } // public System.DateTime HireDate { get; set; } public new System.DateTime CreatedAt { get; set; } public new System.DateTime UpdatedAt { get; set; } } }
f2812bc2a6084dcecdf0d7b10060c0597e6907f9
C#
iain-neirfeno/CSharpWebAppExample
/CalculatedTriangleRepo/TriangleRepo.cs
2.96875
3
using System.Linq; using Triangles.Model; using Triangles.TriangleByPosition; using Triangles.TriangleByVertices; namespace CalculatedTriangleRepo { public class TriangleRepo: ITriangleByPositionRepo, ITiangeByVerticesRepo { private readonly int _triangleSideLength; private readonly int _numberOfColumns; private readonly int _numberOfRows; public TriangleRepo(int numberOfRows, int numberOfColumns, int triangleSideLength) { _numberOfRows = numberOfRows; _numberOfColumns = numberOfColumns; _triangleSideLength = triangleSideLength; } public Triangle FindTriangleByRowAndColumn(char row, int column) { var rowIndex = GetRowIndex(row); if (!IsValidLocation(rowIndex, column)) return null; var inversionFactor = (column - 1) % 2; var topLeftVertex = FindTopLeftVertex(rowIndex, column); var bottomRightVertex = FindBottomRightVertex(topLeftVertex); var remainingVertex = FindRemainingVertex(topLeftVertex, inversionFactor); return new Triangle( topLeftVertex, bottomRightVertex, remainingVertex, column, row ); } public Triangle FindTriangleByVertices(int v1X, int v1Y, int v2X, int v2Y, int v3X, int v3Y) { if (!(IsValidVertex(v1X, v1Y) && IsValidVertex(v2X, v2Y) && IsValidVertex(v3X, v3Y))) return null; var vertices = new[] {new Vertex(v1X, v1Y), new Vertex(v2X, v2Y), new Vertex(v3X, v3Y)}; var topLeftVertex = FindTopLeftVertex(vertices); var topRightVertex = FindTopRightVertex(vertices, topLeftVertex); var bottomRightVertex = FindBottomRightVertex(vertices, topLeftVertex); var bottomLeftVertex = FindBottomLeftVertex(vertices, topLeftVertex); if (!AllVerticesPresent(topRightVertex, bottomLeftVertex, bottomRightVertex)) return null; var row = (char) ('A' + topLeftVertex.Y / _triangleSideLength); var column = topLeftVertex.X / (_triangleSideLength / 2) + 1 + (topRightVertex != null ? 1 : 0); return new Triangle(vertices[0], vertices[1], vertices[2], column, row); } private bool AllVerticesPresent(Vertex topRightVertex, Vertex bottomLeftVertex, Vertex bottomRightVertex) { return bottomRightVertex != null && (topRightVertex != null || bottomLeftVertex != null); } private Vertex FindBottomLeftVertex(Vertex[] vertices, Vertex topLeftVertex) { return vertices.FirstOrDefault(v => v.X == topLeftVertex.X && v.Y == topLeftVertex.Y + _triangleSideLength); } private Vertex FindTopRightVertex(Vertex[] vertices, Vertex topLeftVertex) { return vertices.FirstOrDefault(v => v.X == topLeftVertex.X + _triangleSideLength && v.Y == topLeftVertex.Y); } private Vertex FindBottomRightVertex(Vertex[] vertices, Vertex topLeftVertex) { return vertices.FirstOrDefault(v => v.X == topLeftVertex.X + _triangleSideLength && v.Y == topLeftVertex.Y + _triangleSideLength); } private Vertex FindTopLeftVertex(Vertex[] vertices) { return vertices.OrderBy(v => v.X * _triangleSideLength * (_numberOfColumns / 2) + v.Y).First(); } private bool IsValidLocation(int row, int column) { return column > 0 && row > 0 && column <= _numberOfColumns && row <= _numberOfRows; } private Vertex FindTopLeftVertex(int row, int column) { return new Vertex((column - 1) / 2 * _triangleSideLength, (row - 1) * _triangleSideLength); } private Vertex FindBottomRightVertex(Vertex topLeftVertex) { return new Vertex( topLeftVertex.X + _triangleSideLength, topLeftVertex.Y + _triangleSideLength); } private Vertex FindRemainingVertex(Vertex topLeftVertex, int inversionFactor) { return new Vertex( topLeftVertex.X + inversionFactor * _triangleSideLength, topLeftVertex.Y + _triangleSideLength - inversionFactor * _triangleSideLength); } private static int GetRowIndex(char row) { return row - 'A' + 1; } private bool IsValidVertex(int x, int y) { return x % _triangleSideLength == 0 && y % _triangleSideLength == 0 && x >= 0 && x <= _triangleSideLength * (_numberOfColumns / 2) && y >= 0 && y <= _triangleSideLength * _numberOfRows; } } }
d8b0cf546fb41561e55ab5c56e9a3f95e35ffa72
C#
csuffyy/Z.ExtensionMethods
/System.Drawing.Color/System.Drawing.ColorTranslator/Color.ToHtml.cs
2.921875
3
// Copyright (c) 2014 Jonathan Magnan (http://zzzportal.com) // All rights reserved. // Licensed under MIT License (MIT) // License can be found here: https://zextensionmethods.codeplex.com/license using System; using System.Drawing; public static partial class ColorExtension { /// <summary> /// Translates the specified structure to an HTML string color representation. /// </summary> /// <param name="c">The structure to translate.</param> /// <returns>The string that represents the HTML color.</returns> public static String ToHtml(this Color c) { return ColorTranslator.ToHtml(c); } }
cb2627428d84119d6ddaaede13755be6bde8d903
C#
vdabar/Frutinet
/src/Frutinet.Common/Domain/AggregateRoot.cs
2.5625
3
using Frutinet.Common.Events; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Frutinet.Common.Domain { public abstract class AggregateRoot : IAggregateRoot { public Guid Id { get; protected set; } public ICollection<IEvent> Events { get; protected set; } = new List<IEvent>(); protected AggregateRoot() { Id = Guid.Empty; } protected AggregateRoot(Guid id) { if (id == Guid.Empty) id = Guid.NewGuid(); Id = id; } protected void AddEvent(IEvent @event) { Events.Add(@event); } } }
e8c9e2f4f5376d024308c9b5de16dc143d15e492
C#
JamesTryand/OpenIDE
/Languages/CSharp/CSharp/Crawlers/Struct.cs
2.671875
3
using System; namespace CSharp.Crawlers { public class Struct : ICodeReference { public string Type { get; private set; } public string File { get; private set; } public string Signature { get { return string.Format("{0}.{1}", Namespace, Name); } } public string Namespace { get; private set; } public string Name { get; private set; } public int Offset { get; private set; } public int Line { get; private set; } public int Column { get; private set; } public Struct(string file, string ns, string name, int offset, int line, int column) { File = file; Namespace = ns; Name = name; Offset = offset; Line = line; Column = column; } } }
3d1b2f449c197eea90ef12d2f81af55d85517be3
C#
JohnSoares/nerd-store
/src/NerdStore.Catalog.Data/Repository/ProductRepository.cs
2.6875
3
using Microsoft.EntityFrameworkCore; using NerdStore.Catalog.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NerdStore.Catalog.Data.Repository { public class ProductRepository : Repository<Product>, IProductRepository { public ProductRepository(CatalogContext context) : base(context) { } public async Task<IEnumerable<Product>> GetByCategory(int code) { return await _context.Products.AsNoTracking() .Include(p => p.Category) .Where(c => c.Category.Code == code).ToListAsync(); } public async Task<IEnumerable<Category>> GetCategories() { return await _context.Categories.AsNoTracking().ToListAsync(); } public void Add(Category category) { _context.Categories.Add(category); } public void Update(Category category) { _context.Categories.Update(category); } } }
113c0cafd1714b3447a439e4e945465f7ef1e1c5
C#
ercJuL/Wpf_github_hosts
/WPF_Best_Hosts/Behaviour/WebSpeedComparer.cs
2.71875
3
using System; using System.Collections; using WPF_Best_Hosts.Lib; namespace WPF_Best_Hosts.Behaviour { public class WebSpeedComparer : IComparer { public int Compare(object x, object y) { var xNum = Utils.InverseHumanReadableByteCount((string) x); var yNum = Utils.InverseHumanReadableByteCount((string) y); var result = xNum - yNum; return result == 0 ? 0 : (int) (Math.Abs(result) / result); } } }
9e795b9f90cd71d46ab1b35c65b0de9404e9bbbf
C#
ByteDev/ByteDev.Nuget.Nuspec
/src/ByteDev.Nuget.Nuspec/NuspecMetaData.cs
2.59375
3
using System; using System.Collections.Generic; namespace ByteDev.Nuget.Nuspec { /// <summary> /// Represents metadata within the nuspec manifest. /// </summary> public class NuspecMetaData { /// <summary> /// Specifies the minimum version of the NuGet client that can install this package, enforced /// by nuget.exe and the Visual Studio Package Manager /// </summary> public string MinClientVersion { get; internal set; } #region Mandatory /// <summary> /// Mandatory. The case-insensitive package identifier, which must be unique across nuget.org or whatever /// gallery the package resides in. /// </summary> public string Id { get; internal set; } /// <summary> /// Mandatory. The version of the package, following the major.minor.patch pattern. /// Version numbers may include a pre-release suffix. /// </summary> public string Version { get; internal set; } /// <summary> /// Mandatory. A description of the package for UI display. /// </summary> public string Description { get; internal set; } /// <summary> /// Mandatory. Collection of packages authors, matching the profile names on nuget.org. /// </summary> public IEnumerable<string> Authors { get; internal set; } #endregion #region Optional /// <summary> /// Collection of the package creators using profile names on nuget.org. /// This is often the same list as in authors, and is ignored when uploading the package to nuget.org. /// </summary> public IEnumerable<string> Owners { get; internal set; } /// <summary> /// A URL for the package's home page, often shown in UI displays as well as nuget.org. /// </summary> public Uri ProjectUrl { get; internal set; } /// <summary> /// License file. /// </summary> public NuspecLicense License { get; internal set; } /// <summary> /// It is a path to an image file within the package, often shown in UIs like /// nuget.org as the package icon. /// </summary> public string Icon { get; internal set; } /// <summary> /// Specifys whether the client must prompt the consumer to accept the package license /// before installing the package. /// </summary> public bool RequireLicenseAcceptance { get; internal set; } /// <summary> /// Specifying whether the package is be marked as a development-only-dependency, which prevents /// the package from being included as a dependency in other packages. /// </summary> public bool DevelopmentDependency { get; internal set; } /// <summary> /// A description of the changes made in this release of the package, often used in UI like /// the Updates tab of the Visual Studio Package Manager in place of the package description. /// </summary> public string ReleaseNotes { get; internal set; } /// <summary> /// Copyright details for the package. /// </summary> public string Copyright { get; internal set; } /// <summary> /// The locale ID for the package. /// </summary> public string Language { get; internal set; } /// <summary> /// Collection of tags (keywords) that describe the package and aid discoverability of packages /// through search and filtering. /// </summary> public IEnumerable<string> Tags { get; internal set; } /// <summary> /// Details the repository that built the .nupkg. /// </summary> public NuspecRepository Repository { get; internal set; } /// <summary> /// A human-friendly title of the package which may be used in some UI displays. /// (nuget.org and the Package Manager in Visual Studio do not show title) /// </summary> public string Title { get; internal set; } /// <summary> /// Package dependencies. /// </summary> public NuspecDependencies Dependencies { get; internal set; } /// <summary> /// Package types. /// </summary> public IEnumerable<NuspecPackageType> PackageTypes { get; internal set; } /// <summary> /// Framework assembly references. /// </summary> public IEnumerable<NuspecFrameworkAssembly> FrameworkAssemblies { get; internal set; } /// <summary> /// Assembly references. Used by projects using packages.config to explicitly specify the assemblies that /// the target project should reference when using the package. /// </summary> public NuspecReferences References { get; internal set; } /// <summary> /// Content files that define what files to include or exclude. /// </summary> public IEnumerable<NuspecContentFile> ContentFiles { get; internal set; } #endregion } }
62ae6984943aa196754e95e0e6158fe05a1be81d
C#
MattiaPezzanoAiv/CSharp_BehaviourTree
/BT/DecoratorNodes/Conditionals/IntCondition.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BT.Decorators { public class IntCondition : BaseConditionEvaluator<int> { protected override bool IsEqual(int obj1, int obj2) { return obj1 == obj2; } protected override bool IsGreater(int obj1, int obj2) { return obj1 > obj2; } protected override bool IsLess(int obj1, int obj2) { return obj1 < obj2; } protected override bool IsGreaterEqual(int obj1, int obj2) { return obj1 >= obj2; } protected override bool IsLessEqual(int obj1, int obj2) { return obj1 <= obj2; } protected override bool IsNotEqual(int obj1, int obj2) { return obj1 != obj2; } } }
eaf86d9272bb62c5df3d133bae824e923259d335
C#
amittyyy/Coding_Questions_Answers
/SequentiallyBounded .cs
2.8125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Test { public partial class SequentiallyBounded : Form { public SequentiallyBounded() { InitializeComponent(); } private void SequentiallyBounded_Load(object sender, EventArgs e) { } static int isSequentially(int[] a) { int val = 0; for(int i=0; i<a.Length; i++) { if (a[i]< 0) { return 0; } else if (a[i] >= val) { val = a[i]; } } return 1; } } }
5dad7ee88aa0e3e1abccda6df905f40887774764
C#
MaximZinevych/codewars
/codewars-project/codewars-project/Task_02.cs
3.625
4
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace codewars_project { /* Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. Your task is to write a function that takes a string and return a new string with all vowels removed. For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!". Note: for this kata y isn't considered a vowel. */ class Task_02 { public static string Disemvowel(string str) { return Regex.Replace(str, "[aeiou]", "", RegexOptions.IgnoreCase); ; } } }
0162754808ae0dea68a04e9251b30523acc8d2e0
C#
lucafilippodangelo/OOP-Patterns-Refresh
/FlyweightStructuralPattern/AlienFactory.cs
2.5625
3
using System; using System.Collections.Generic; using System.Text; namespace FlyweightStructuralPattern { //LDFLY003 public class AlienFactory { private Dictionary<int, IAlien> list = new Dictionary<int, IAlien>(); public void SaveAlien(int index, IAlien alien) { list.Add(index, alien); } public IAlien GetAlien(int index) { return list[index]; } } }
ecbe3ac1731cbf32d23b992af2330b853f64f0d1
C#
suresh-kok/BTC
/Travel_Request_System/Travel_Request_System_EF/Mail/SendMail.cs
2.75
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Linq.Expressions; using System.Net; using System.Net.Mail; using System.Reflection; using System.Text; namespace Travel_Request_System_EF.Mail { public class SendMail { public List<string> ToAddresses; public string MailBody; public string MailSubject; public List<MailAttachment> MailAttachments; public void Send() { string host = ConfigurationManager.AppSettings["SMTPHost"]; string fromAddress = ConfigurationManager.AppSettings["SMTPFrom"]; string smtpUname = ConfigurationManager.AppSettings["SMTPUname"]; string smtpPass = ConfigurationManager.AppSettings["SMTPPass"]; try { MailMessage mail = new MailMessage { Body = MailBody, IsBodyHtml = true, SubjectEncoding = Encoding.UTF8, Priority = MailPriority.Normal }; foreach (var item in ToAddresses) { mail.To.Add(new MailAddress(item)); } mail.From = new MailAddress(fromAddress); mail.Subject = MailSubject; foreach (MailAttachment ma in MailAttachments) { mail.Attachments.Add(ma.File); } SmtpClient smtp = new SmtpClient { Host = host, Credentials = new NetworkCredential(smtpUname, smtpPass), EnableSsl = false }; smtp.Send(mail); } catch (Exception ex) { StringBuilder sb = new StringBuilder(1024); sb.Append("\nTo:" + string.Join(", ", ToAddresses.ToArray())); sb.Append("\nbody:" + MailBody); sb.Append("\nsubject:" + MailSubject); sb.Append("\nfromAddress:" + fromAddress); sb.Append("\nHosting:" + host); throw new Exception(sb.ToString(), ex); } } public string ListToString<T>(List<T> inputList, params Expression<Func<T, object>>[] fxns) { return GetMyTable(inputList, fxns); } public static string GetMyTable<T>(IEnumerable<T> list, params Expression<Func<T, object>>[] fxns) { StringBuilder sb = new StringBuilder(); sb.Append("<TABLE>\n"); sb.Append("<TR>\n"); foreach (var fxn in fxns) { sb.Append("<TH>"); sb.Append(GetName(fxn)); sb.Append("</TH>"); } sb.Append("</TR> <!-- HEADER -->\n"); foreach (var item in list) { sb.Append("<TR>\n"); foreach (var fxn in fxns) { sb.Append("<TD>"); sb.Append(fxn.Compile()(item)); sb.Append("</TD>"); } sb.Append("</TR>\n"); } sb.Append("</TABLE>"); return sb.ToString(); } private static string GetName<T>(Expression<Func<T, object>> expr) { var member = expr.Body as MemberExpression; if (member != null) { return GetName2(member); } var unary = expr.Body as UnaryExpression; if (unary != null) { return GetName2((MemberExpression)unary.Operand); } return "?+?"; } private static string GetName2(MemberExpression member) { var fieldInfo = member.Member as FieldInfo; if (fieldInfo != null) { var d = fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute; if (d != null) { return d.Description; } return fieldInfo.Name; } var propertInfo = member.Member as PropertyInfo; if (propertInfo != null) { var d = propertInfo.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute; if (d != null) { return d.Description; } return propertInfo.Name; } return "?-?"; } } }
59b60f0e0e7088bcc2a5e8d78b53599b4a0aa70b
C#
nikolagsiderov/APPartment
/APPartment.Infrastructure/Tools/CollectionExtensions.cs
2.515625
3
using APPartment.ORM.Framework.Declarations; using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.Linq; namespace APPartment.Infrastructure.Tools { public static class CollectionExtensions { public static List<SelectListItem> ToSelectList<T>(this List<T> collection) where T : IBaseObject, new() { var selectList = new List<SelectListItem>(); foreach (var item in collection) { selectList.Add(new SelectListItem() { Text = item.Name, Value = item.ID.ToString() }); } return selectList; } public static List<SelectListItem> ToLookupSelectList<T>(this List<T> collection) where T : ILookupObject, new() { var selectList = new List<SelectListItem>(); foreach (var item in collection) { selectList.Add(new SelectListItem() { Text = item.Name, Value = item.ID.ToString() }); } return selectList; } public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property) { return items.GroupBy(property).Select(x => x.First()); } } }
a8c84dd3021a2452337f2a2099a54c423c6c07cd
C#
SalviMaruf/Movie_Rental_Store
/WebApplication1/WebApplication1/Models/MinNumberOfMovies.cs
2.90625
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace WebApplication1.Models { public class MinNumberOfMovies:ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var movie = (Movie) validationContext.ObjectInstance; if(movie.NumberOfItemsInStock>=1 && movie.NumberOfItemsInStock<=20) return ValidationResult.Success; else { return new ValidationResult("The field NumberInStock must be between 1 and 20"); } } } }
f8403631a6e81a7e64dee36745b5eb78ad089739
C#
umbersar/ToyDB
/ToyDB/REPL.cs
2.71875
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ToyDB { public static class REPL { const string prompt = "ToyDB>"; const string ToyDB = @" _____ ____ ____ |_ _|__ _ _| _ \| __ ) | |/ _ \| | | | | | | _ \ | | (_) | |_| | |_| | |_) | |_|\___/ \__, |____/|____/ |___/ "; public static void Start(TextReader tIn, TextWriter tOut) { //create the env variable in outer scope so that it persists after executing a line of code and we can use a IDENT later Environment_AST env = Environment_AST.NewEnvironment_AST(); while (true) { tOut.Write(prompt); string line = tIn.ReadLine(); if (string.IsNullOrEmpty(line)) break; Lexer lex = new Lexer(line); #region MyRegion //var tok = lex.NextToken(); //while (tok.Type != TokenHelper.TokenType.EOF) { // tOut.WriteLine(tok); // tok = lex.NextToken(); //} #endregion Parser p = new Parser(lex); SQLBatch program = p.ParseSQLBatch(); if (p.Errors().Count != 0) { printParserError(tOut, p.Errors()); continue; } //tOut.WriteLine(program.ToString()); //tOut.WriteLine(); Object_AST evaluated = Evaluator.Eval(program, env); if (evaluated != null) { tOut.WriteLine(evaluated.Inspect()); } } } private static void printParserError(TextWriter tOut, List<string> errors) { tOut.WriteLine(ToyDB); tOut.WriteLine("Woops! We ran into some monkey business here!"); tOut.WriteLine(" parser errors:"); foreach (var msg in errors) { tOut.WriteLine("\t" + msg); } } } }
570b71ceef2d8a1af681fb1614505f83b1862a89
C#
guillermaster/SocialRequirements
/SocialRequirements.Domain/BusinessLogic/Requirement/IRequirementBusiness.cs
2.765625
3
using System.Collections.Generic; using SocialRequirements.Domain.DTO.General; using SocialRequirements.Domain.DTO.Requirement; namespace SocialRequirements.Domain.BusinessLogic.Requirement { public interface IRequirementBusiness { /// <summary> /// Specified whether a company has requirements or not /// </summary> /// <param name="companyId">Company identifier</param> /// <returns>True when the company has at least one requirements, otherwise returns false.</returns> bool HaveRequirements(long companyId); /// <summary> /// Adds a new requirement to the database /// </summary> /// <param name="companyId">Company identifier</param> /// <param name="projectId">Project identifier</param> /// <param name="title">Requirement title</param> /// <param name="description">Requirement description</param> /// <param name="hashtags">Hashtags for the requirement</param> /// <param name="priorityId">Requirement Priority ID</param> /// <param name="username">Creation username</param> /// <returns>Requirement DTO with data of the newly created requirement</returns> RequirementDto Add(long companyId, long projectId, string title, string description, string[] hashtags, int priorityId, string username); /// <summary> /// Adds a like to the specified requirement /// </summary> /// <param name="companyId">Company identifier</param> /// <param name="projectId">Project identifier</param> /// <param name="requirementId">Requirement ID</param> /// <param name="username">Username who gave the like</param> void Like(long companyId, long projectId, long requirementId, string username); /// <summary> /// Adds a like to the specified requirement /// </summary> /// <param name="companyId">Company identifier</param> /// <param name="projectId">Project identifier</param> /// <param name="requirementId">Requirement ID</param> /// <param name="username">Username who gave the dislike</param> void Dislike(long companyId, long projectId, long requirementId, string username); /// <summary> /// Query requirements by user from all of his projects and companies /// </summary> /// <param name="username">Username related to the requirements</param> /// <param name="statusId">Filter by this status (optional)</param> /// <param name="developmentStatusId">Filter by this development status (optional)</param> /// <returns>List of requirements</returns> List<RequirementDto> GetList(string username, int? statusId = null, int? developmentStatusId = null); /// <summary> /// Query requirements by hashtag and user from all of his projects and companies /// </summary> /// <param name="hashtag">Hashtag of requirements to look for</param> /// <param name="username">Username related to the requirements</param> /// <returns>List of requirements</returns> List<RequirementDto> GetListByHashtag(string hashtag, string username); /// <summary> /// Query approved requirements by user from all of his projects and companies /// </summary> /// <param name="username">Username related to the requirements</param> /// <returns>List of requirements</returns> List<RequirementDto> GetListApproved(string username); /// <summary> /// Query rejected requirements by user from all of his projects and companies /// </summary> /// <param name="username">Username related to the requirements</param> /// <returns>List of requirements</returns> List<RequirementDto> GetListRejected(string username); /// <summary> /// Query requirements with pending approval by user from all of his projects and companies /// </summary> /// <param name="username">Username related to the requirements</param> /// <returns>List of requirements</returns> List<RequirementDto> GetListPending(string username); /// <summary> /// Query draft requirements by user from all of his projects and companies /// </summary> /// <param name="username">Username related to the requirements</param> /// <returns>List of requirements</returns> List<RequirementDto> GetListDraft(string username); /// <summary> /// Query approved requirements pending development, filtered by user from all of his projects and companies /// </summary> /// <param name="username">Username related to the requirements</param> /// <returns>List of requirements</returns> List<RequirementDto> GetListPendingDevelopment(string username); /// <summary> /// Query approved requirements under development, filtered by user from all of his projects and companies /// </summary> /// <param name="username">Username related to the requirements</param> /// <returns>List of requirements</returns> List<RequirementDto> GetListUnderDevelopment(string username); /// <summary> /// Query approved requirements under testing stage, filtered by user from all of his projects and companies /// </summary> /// <param name="username">Username related to the requirements</param> /// <returns>List of requirements</returns> List<RequirementDto> GetListUnderTesting(string username); /// <summary> /// Query approved requirements that have been deployed, filtered by user from all of his projects and companies /// </summary> /// <param name="username">Username related to the requirements</param> /// <returns>List of requirements</returns> List<RequirementDto> GetListDeployed(string username); /// <summary> /// Returns requirement data matching criteria specified by input params /// </summary> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <returns>Requirement</returns> RequirementDto Get(long companyId, long projectId, long requirementId); /// <summary> /// Sets a requirement as approved /// </summary> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <param name="username">User who approves the requirement</param> void Approve(long companyId, long projectId, long requirementId, string username); /// <summary> /// Sets a requirement as under development /// </summary> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <param name="username">User who updates the requirement status</param> void SetUnderDevelopment(long companyId, long projectId, long requirementId, string username); /// <summary> /// Sets a requirement as under testing stage /// </summary> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <param name="username">User who updates the requirement status</param> void SetUnderTesting(long companyId, long projectId, long requirementId, string username); /// <summary> /// Sets a requirement as deployed /// </summary> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <param name="username">User who updates the requirement status</param> void SetDeployed(long companyId, long projectId, long requirementId, string username); /// <summary> /// Sets a requirement as rejected /// </summary> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <param name="username">User who rejects the requirement</param> void Reject(long companyId, long projectId, long requirementId, string username); /// <summary> /// Updates the title and description for the specified requirement /// </summary> /// <param name="title">Requirement title</param> /// <param name="description">Description title</param> /// <param name="newProjectId">Project ID (to move the requirement to another project)</param> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <param name="priorityId">Requirement Priority ID</param> /// <param name="username">User that triggered the update</param> void Update(string title, string description, long newProjectId, long companyId, long projectId, long requirementId, int priorityId, string username); /// <summary> /// Submits a requirement for its aproval /// </summary> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <param name="username">User that submitted the requirement</param> void SubmitForApproval(long companyId, long projectId, long requirementId, string username); /// <summary> /// Uploads a file to the DB server as part of the lastest requirement version record /// </summary> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <param name="fileName">File name</param> /// <param name="fileContent">File content in bytes</param> /// <param name="username">Modification username</param> void UploadAttachment(long companyId, long projectId, long requirementId, string fileName, byte[] fileContent, string username); /// <summary> /// Uploads a file to the DB server as part of a specific requirement version record /// </summary> /// <param name="companyId">Company ID</param> /// <param name="projectId">Project ID</param> /// <param name="requirementId">Requirement ID</param> /// <param name="requirementVersionId">Requirement version ID</param> /// <param name="fileName">File name</param> /// <param name="fileContent">File content in bytes</param> /// <param name="username">Modification username</param> void UploadAttachment(long companyId, long projectId, long requirementId, long requirementVersionId, string fileName, byte[] fileContent, string username); byte[] GetAttachment(long companyId, long projectId, long requirementId, long? requirementVersionId = null); string GetAttachmentTitle(long companyId, long projectId, long requirementId, long? requirementVersionId = null); /// <summary> /// Search for requirements matching the text /// </summary> /// <param name="text">Search criteria</param> /// <returns>List of requirements as search results</returns> List<SearchResultDto> SearchRequirement(string text); } }
0e3943e4d5ee947a626887cbac258224e6f52cb7
C#
derekhubbard/StoreFront
/Inventory.Tests/WorthCalculatorRule/AlchemyWorthCalculatorRuleTests.cs
2.734375
3
using FluentAssertions; using NUnit.Framework; using StoreFront.Inventory.WorthCalculatorRule; namespace StoreFront.Inventory.Tests.WorthCalculatorRule { [TestFixture] public class AlchemyWorthCalculatorRuleTests { [Test] public void Calculate_PositiveShelfLife_ShouldReduceWorthByTwo() { // arrange var rule = new AlchemyWorthCalculatorRule(); const int shelfLife = 10; const int originalWorth = 10; // act int newWorth = rule.Calculate(shelfLife, originalWorth); // assert newWorth.Should().Be(originalWorth - 2); } [Test] public void Calculate_NegativeShelfLife_ShouldReduceWorthByFour() { // arrange var rule = new AlchemyWorthCalculatorRule(); const int shelfLife = -10; const int originalWorth = 10; // act int newWorth = rule.Calculate(shelfLife, originalWorth); // assert newWorth.Should().Be(originalWorth - 4); } [Test] public void Calculate_WhenDecreasingWorth_ShouldNeverDecreaseWorthBelowZero() { // arrange var rule = new AlchemyWorthCalculatorRule(); const int shelfLife = 10; const int originalWorth = 0; // act int newWorth = rule.Calculate(shelfLife, originalWorth); // assert newWorth.Should().Be(originalWorth); } } }
e059dfeac13db15c8200b042196c33b23844527a
C#
rajeevyadav/corefx
/src/Common/perf/PerfRunner/PerfRunner.cs
2.671875
3
using System.IO; using System.Reflection; using System.Collections.Generic; using Microsoft.Xunit.Performance.Api; public class PerfHarness { public static void Main(string[] args) { using (XunitPerformanceHarness harness = new XunitPerformanceHarness(args)) { foreach(var testName in GetTestAssemblies()) { harness.RunBenchmarks(GetTestAssembly(testName)); } } } private static string GetTestAssembly(string testName) { // Assume test assemblies are colocated/restored next to the PerfHarness. return Path.Combine( Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), testName); } private static IEnumerable<string> GetTestAssemblies() { return Directory.EnumerateFiles(".", "*.Performance.Tests.dll"); } }
1a85eca6619d46154685dc141589c273ff425245
C#
MichaelLoder/WeatherTestApp
/BLL/WeatherFacade.cs
2.59375
3
using System; using System.Collections.Generic; using System.Text; using BLL.Interfaces; using BO; using System.Linq; using BLL.WeatherRules; namespace BLL { public class WeatherFacade : IWeatherFacade { private readonly IWeatherAggregatorFactory _weatherAggregatorFactory; private readonly IAggeratorClient _aggeratorClient; private readonly ICacheFacade<TempUnits, List<AggeratorResult>> _tempCacheFacade; private readonly ICacheFacade<WindUnits, List<AggeratorResult>> _windCacheFacade; private readonly IWeatherRule _rule; public WeatherFacade(IWeatherAggregatorFactory weatherAggregatorFactory, IAggeratorClient aggeratorClient, ICacheFacade<TempUnits, List<AggeratorResult>> tempCacheFacade, ICacheFacade<WindUnits, List<AggeratorResult>> windCacheFacade, IWeatherRule rule ) { _weatherAggregatorFactory = weatherAggregatorFactory; _aggeratorClient = aggeratorClient; _tempCacheFacade = tempCacheFacade; _windCacheFacade = windCacheFacade; _rule = rule; } public WeatherResult GetWeatherResult(WeatherRequest request) { //refactor to extension method - error checking var choosenWindUnit = (WindUnits) Enum.Parse(typeof(WindUnits), request.WindUnit); var choosenTempUnit = (TempUnits) Enum.Parse(typeof(TempUnits), request.TempUnit); // get list of every api we need to call var aggregators = _weatherAggregatorFactory.GetWeatherAggregator(choosenTempUnit, choosenWindUnit, _aggeratorClient); var results = new List<AggeratorResult>(); // loop[ through each api foreach (var weatherAggregator in aggregators) { results.Add(weatherAggregator.GetWeatherResult(request.Location, choosenTempUnit, choosenWindUnit).Result); } // get previous queries of temperature var cachedTemp = _tempCacheFacade.Get(choosenTempUnit); // get previous queries of wind speeds var cahceWind = _windCacheFacade.Get(choosenWindUnit); // add only the results we are interested in cahceWind.Add(results.First(x => x.WindUnits == choosenWindUnit)); cachedTemp.Add(results.First(x => x.TempUnitChoosen == choosenTempUnit)); // add results to cache _tempCacheFacade.Add(choosenTempUnit, cachedTemp); _windCacheFacade.Add(choosenWindUnit, cahceWind); // return the result after processing them through rules return _rule.ProcessAnyRule(new WeatherResult() { AverageTemp = cachedTemp.CalculateTempAverage(choosenTempUnit), AverageWindSpeed = cahceWind.CalculateWindAverage(choosenWindUnit), Location = request.Location, WindUnits = choosenWindUnit, TempUnitChoosen = choosenTempUnit }); } } }
4c2bdefcc221dc34dcab312367278b4c9e634310
C#
DevFojo/leetcode
/LeetCode/Solution20.cs
3.359375
3
using System.Collections.Generic; namespace LeetCode { public class Solution20 { public bool IsValid(string s) { var stack = new Stack<char>(); var parentheses = new Dictionary<char, bool> { {'(', false}, {'{', false}, {'[', false}, {')', true}, {'}', true}, {']', true} }; foreach (var c in s) { if (parentheses[c]) { if (stack.Count == 0) { return false; } var last = stack.Pop(); if (!closes(c, last)) { return false; } } else { stack.Push(c); } } return stack.Count == 0; } private bool closes(char c, char o) { return o == '[' && c == ']' || o == '{' && c == '}' || o == '(' && c == ')'; } } }
de60ea0f52b38e3c6e691b2f949aed867da2571b
C#
GuiOttoni/Security.Framework
/Security.Framework/Utils/Base64Url.cs
3.25
3
using System; using System.Collections.Generic; using System.Text; namespace Security.Framework.Utils { /// <summary> /// Static Class to Encode and Decode Base64 Urls. /// </summary> public static class Base64Url { #region .: Base URL 64 Utilities :. /// <summary> /// Create an encoding based on the Jwt Specification. /// </summary> /// <param name="input"></param> /// <returns></returns> public static String Base64UrlEncode(byte[] data) { /* Variable Declaration Area */ String answer = Convert.ToBase64String(data); /* Remove any trailing '='s */ answer = answer.Split('=')[0x00]; /* 62nd Char of Encoding */ answer = answer.Replace('+', '-'); /* 63rd Char of Encoding */ answer = answer.Replace('/', '_'); return answer; } /// <summary> /// Decode data, according to the Jwt Specification. /// </summary> /// <param name="data">Data to be decoded.</param> /// <returns>A byte array with data decodd.</returns> public static byte[] Base64UrlDecode(String data) { /* Variable Declaration Area */ String answer = data; /* 62nd Char of Encoding */ answer = answer.Replace('-', '+'); /* 63rd Char of Encoding */ answer = answer.Replace('_', '/'); /* Padding with trailing '='s */ switch (answer.Length % 0x04) { /* No padding chars needed */ case 0: break; /* Including 2 padding chars */ case 2: answer += "=="; break; /* Including 1 padding char */ case 3: answer += "="; break; default: throw new System.Exception("The base64URL informed is invalid."); } /* .Net Standard Decoder */ return Convert.FromBase64String(answer); } #endregion } }
2e78c5334aa9ca5ea085fd8c4897a4cb31eb7ea6
C#
vjkrammes/Tracker
/Tracker/ViewModels/QAViewModel.cs
2.71875
3
using System.Windows.Media; using Tracker.Infrastructure; namespace Tracker.ViewModels { public class QAViewModel : ViewModelBase { #region Properties private string _question; public string Question { get => _question; set => SetProperty(ref _question, value); } private string _answer; public string Answer { get => _answer; set => SetProperty(ref _answer, value); } private bool _answerRequired; public bool AnswerRequired { get => _answerRequired; set => SetProperty(ref _answerRequired, value); } private SolidColorBrush _borderBrush; public SolidColorBrush BorderBrush { get => _borderBrush; set => SetProperty(ref _borderBrush, value); } #endregion #region Command Methods public override bool OkCanExecute() => AnswerRequired ? !string.IsNullOrEmpty(Answer) : true; #endregion public QAViewModel() { BorderBrush = Brushes.Black; } } }
2c4b4e2aeb13d4a8a0a16b8e65cc5ea505eca96c
C#
bronxc/Unscrambler
/Unscrambler/Features/MethodFeatures/CalliReplace.cs
2.53125
3
using System.Collections.Generic; using AsmResolver.DotNet; using AsmResolver.PE.DotNet.Cil; namespace Unscrambler.Features.MethodFeatures { public class CalliReplace : IMethodFeature { private int _count; public void Process( MethodDefinition method ) { var instr = method.CilMethodBody.Instructions; for ( int i = 0; i < instr.Count; i++ ) { if ( instr[i].OpCode != CilOpCodes.Ldftn || instr[i + 1].OpCode != CilOpCodes.Calli ) continue; // Change ldftn to call and remove the calli opcode instr[i].OpCode = CilOpCodes.Call; instr[i + 1].OpCode = CilOpCodes.Nop; _count++; } } public IEnumerable<Summary> GetSummary() { if ( _count > 0 ) yield return new Summary( $"Replaced {_count} Calli implementations", Logger.LogType.Success ); } } }
19eefdae348ab5c7e827181b70d445bacd8c56ab
C#
riggea/2048bot
/2048/2048/Src/EvaluatorStrategy.cs
3.234375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _2048 { class EvaluatorStrategy : Strategy { private PositionEvaluator evaluator; public EvaluatorStrategy(PositionEvaluator evaluator) { this.evaluator = evaluator; } public Direction getDirection(GameBoard board) { double bestScore = -1; Direction bestDirection = Direction.None; foreach (Direction tryDirection in (Direction[])Enum.GetValues(typeof(Direction))) { if (tryDirection == Direction.None) continue; GameBoard newBoard = board.move(tryDirection); if (newBoard.Equals(board)) continue; double newScore = evaluator.score(newBoard); if (newScore > bestScore) { bestScore = newScore; bestDirection = tryDirection; } } return bestDirection; } } }
b6ccc24427c9addbab8820032ec5e621bef839d6
C#
tchao-oo/amex-icepicker
/AmexIcePicker/Amex.IcePicker/Xml/Serialization.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.IO; namespace Amex.IcePicker.Xml { public class Serialization { public static object Deserialize(string xml, Type objType) { XmlSerializer xmlSerializer = new XmlSerializer(objType); using (StringReader stringReader = new StringReader(xml)) return xmlSerializer.Deserialize(stringReader); } public static object DeserializeFromFile(string filename, Type objType) { XmlSerializer xmlSerializer = new XmlSerializer(objType); using (FileStream fs = new FileStream(filename, FileMode.Open)) return xmlSerializer.Deserialize(fs); } public static string Serialize(Object obj, Type objType) { XmlSerializer xmlSerializer = new XmlSerializer(objType); using (StringWriter stringWriter = new StringWriter()) { xmlSerializer.Serialize(stringWriter, obj); return stringWriter.ToString(); } } } }
3454a953e5a1a9b9357a8d4ca422e2f1cbdb02bd
C#
wumh0622/SSF_GameJam
/Assets/Scripts/BackGroundScolling.cs
2.703125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BackGroundScolling : MonoBehaviour { public static BackGroundScolling instance; [SerializeField] GameObject[] backGround; [SerializeField] float gap; void Awake() { if (instance == null) { instance = this; } } public void Scolling(float speed) { for (int i = 0; i < backGround.Length; i++) { backGround[i].transform.position = new Vector3( backGround[i].transform.position.x - Time.deltaTime * speed, backGround[i].transform.position.y, backGround[i].transform.position.z); if(backGround[i].transform.position.x < -gap) { backGround[i].transform.position = new Vector3(backGround[i].transform.position.x + gap * 3, backGround[i].transform.position.y, backGround[i].transform.position.z); } } } }
6c026b46e8a704a2cf292a96d3aea2b89f4f193d
C#
mcknell/Stile
/source/Stile/Types/Expressions/Printing/ExpressionParsers/BlockExpressionParser.cs
2.515625
3
#region License info... // Stile for .NET, Copyright 2011-2013 by Mark Knell // Licensed under the MIT License found at the top directory of the Stile project on GitHub #endregion #region using... using System.Linq; using System.Linq.Expressions; #endregion namespace Stile.Types.Expressions.Printing.ExpressionParsers { public class BlockExpressionParser : ExpressionParser<BlockExpression> { public BlockExpressionParser(BlockExpression expression, IPrintStrategy printStrategy) : base(expression, printStrategy) {} protected override void Parse(BlockExpression expression) { Append(Format.OpenBlock); AppendSequence(Format.StatementSeparator, expression.Expressions.ToArray()); Append(Format.CloseBlock); } } }
d575840e39ef52e9d2e899c1bd941e76ab229b3e
C#
Teodor92/University
/CSharp/01. CSharpIntroduction/05. DivisionCheckerAdvanced/Program.cs
3.78125
4
namespace _05.DivisionCheckerAdvanced { using System.Text; using Homework.Common; /// <summary> /// Prints all the numbers divisible by 3,4 and 9 within a given range. /// </summary> public class Program { private const string IntervalStartPromt = "Please enter the start of the interval"; private const string IntervalEndPromt = "Please enter the end of the interval"; private const string DivisorChousePromt = "Please chouse a divisor - 3, 4 or 9."; private const string InvalidDivisorPromt = "Divisor is invalid. Please try again."; internal static void Main(string[] args) { var intervalStart = ConsoleInputHelper.SafeRead<int>(IntervalStartPromt); var intervalEnd = ConsoleInputHelper.SafeRead<int>(IntervalEndPromt); while (true) { var divisor = ConsoleInputHelper.SafeRead<int>(DivisorChousePromt); var isDivisorValid = divisor == 3 || divisor == 4 || divisor == 9; if (!isDivisorValid) { ConsoleOutputHelper.WriteMessage(InvalidDivisorPromt, ConsoleMessageType.Error); } else { var numbers = GetAllDivisableNumbers(intervalStart, intervalEnd, divisor); ConsoleOutputHelper.WriteMessage(numbers, ConsoleMessageType.Success); break; } } } private static string GetAllDivisableNumbers(int intervalsStart, int intervalEnd, int divisor) { var output = new StringBuilder(); for (int i = intervalsStart; i < intervalEnd; i++) { if (i % divisor == 0) { output.AppendFormat("{0} ", i); } } return output.ToString().Trim(); } } }