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
26a1af93557abfbd3704841e2c4a7d621948fff9
C#
magerate/Geometries
/src/Cession.Geometries/Rect.cs
3.296875
3
using System; namespace Cession.Geometries { public struct Rect : IEquatable<Rect> { public static readonly Rect Empty = new Rect (0, 0, 0, 0); private double _x; private double _y; private double _width; private double _height; public Point Location { get{ return new Point (_x, _y); } } public double X { get { return _x; } set { _x = value; } } public double Left { get { return _x; } } public double Y { get { return _y; } set { _y = value; } } public double Bottom { get { return _y + _height; } } public double Width { get { return _width; } set { _width = value; } } public Size Size { get{ return new Size (_width, _height); } } public double Right { get { return _x + _width; } } public double Height { get { return _height; } set { _height = value; } } public double Top { get { return _y; } } public Point Center { get{ return new Point (_x + _width / 2, _y + Height / 2); } } public Point LeftBottom { get { return new Point (this.Left, this.Bottom); } } public Point RightBottom { get { return new Point (this.Right, this.Bottom); } } public Point LeftTop { get { return new Point (this.Left, this.Top); } } public Point RightTop { get { return new Point (this.Right, this.Top); } } public Rect (double x, double y, double width, double height) { if (width < 0) throw new ArgumentException (); if (height < 0) throw new ArgumentException (); _x = x; _y = y; _width = width; _height = height; } public Rect (Point location, Size size) : this (location.X, location.Y, size.Width, size.Height) { } public bool Contains (Point point) { return point.X >= _x && point.X <= _x + _width && point.Y >= _y && point.Y <= _y + _height; } public bool Contains (Rect rect) { return rect.Left >= Left && rect.Right <= Right && rect.Top >= Top && rect.Bottom <= Bottom; } public bool Equals (Rect rect) { return this._x == rect._x && this._y == rect._y && this._width == rect._width && this._height == rect._height; } public override bool Equals (object obj) { if (null == obj || !(obj is Rect)) return false; return Equals ((Rect)obj); } public override int GetHashCode () { return _x.GetHashCode () ^ _y.GetHashCode () ^ _width.GetHashCode () ^ _height.GetHashCode (); } public static bool operator == (Rect left, Rect right) { return left.Equals (right); } public static bool operator != (Rect left, Rect right) { return !left.Equals (right); } public void Offset (double x, double y) { this._x += x; this._y += y; } public void Offset (Vector vector) { this.Offset (vector.X, vector.Y); } public void Inflate (double width, double height) { this._x -= width; this._y -= height; this._width += 2 * width; this._height += 2 * height; } public Rect Union (Rect rect) { if (this == Empty) return rect; if (rect == Empty) return this; var left = Math.Min (this.Left, rect.Left); var top = Math.Min (this.Top, rect.Top); var right = Math.Max (this.Right, rect.Right); var bottom = Math.Max (this.Bottom, rect.Bottom); return Rect.FromLTRB (left, top, right, bottom); } public Rect? Intersects (Rect rect) { var left = Math.Max (this.Left, rect.Left); var right = Math.Min (this.Right, rect.Right); var top = Math.Max (this.Top, rect.Top); var bottom = Math.Min (this.Bottom, rect.Bottom); if (left <= right && top <= bottom) return Rect.FromLTRB (left, top, right, bottom); return null; } public override string ToString () { return string.Format ("{0},{1},{2},{3}", _x.ToString (), _y.ToString (), _width.ToString (), _height.ToString ()); } public static Rect FromLTRB (double left, double top, double right, double bottom) { return new Rect (left, top, right - left, bottom - top); } public static Rect FromPoints (Point p1, Point p2) { return FromLTRB (Math.Min (p1.X, p2.X), Math.Min (p1.Y, p2.Y), Math.Max (p1.X, p2.X), Math.Max (p1.Y, p2.Y)); } } }
1fc6a11428e278b1dce80e6ef2fe63599b8be61e
C#
agaddampalli/Algorithms
/Chapter 16 - Strings/ZigZagConversion.linq
3.046875
3
<Query Kind="Program" /> void Main() { Convert("PAYPALISHIRING", 4).Dump(); } public string Convert(string s, int numRows) { if(numRows <= 1) { return s; } var temp = new StringBuilder[numRows]; for (int i = 0; i < numRows; i++) { temp[i] = new StringBuilder(); } var currentRow = 0; var isDownward = false; for (int i = 0; i < s.Length; i++) { temp[currentRow].Append(s[i]); if(currentRow == 0 || currentRow == numRows -1) { isDownward = !isDownward; } currentRow += isDownward ? 1 : -1; } return temp.Aggregate((x,y) => x.Append(y)).ToString(); }
2c633f83cad508db80a1c2f7df511bbd63890b5e
C#
muaddibco/Wist
/Wist.Common/Wist.Core/PerformanceCounters/IntegerCounter.cs
2.515625
3
using System.Diagnostics; namespace Wist.Core.PerformanceCounters { [CounterType(CounterType = PerformanceCounterType.NumberOfItems64)] public class IntegerCounter : PerformanceCounterBase { //public IntegerCounter(string categoryName, string counterName, string instanceName, bool readOnly = false) : // base(categoryName, counterName, instanceName, PerformanceCounterType.NumberOfItems64, readOnly) //{ //} public long Decrement() { return _counter.Decrement(); } public long Increment() { return _counter.Increment(); } public long IncrementBy(long value) { return _counter.IncrementBy((long)value); } public long DecrementBy(long value) { return _counter.RawValue -= value; } } }
815983efea3be026b9dc5dad5934bc744c8f5a82
C#
mrcretu/.NET-MVC
/DataAccess/DataAccess/Configurations/PostConfiguration.cs
2.734375
3
using System; using DataAccess.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace DataAccess.Configurations { public class PostConfiguration : IEntityTypeConfiguration<Post> { public void Configure(EntityTypeBuilder<Post> builder) { builder.ToTable("Posts"); builder.HasKey(p => p.Id); builder.Property(p => p.Id).HasMaxLength(50); builder.Property(p => p.AddedDate).IsRequired().HasDefaultValue(DateTime.Now); builder.Property(p => p.Content).IsRequired().HasMaxLength(1000); builder.HasOne(p => p.User).WithMany(u => u.Posts).HasForeignKey(p => p.UserId); builder.Property(u => u.Id).HasMaxLength(50); } } }
41129aaaef6c354da42fd919d4fbf8028b122736
C#
VeritasCarpeDiem/Double-Linked-List
/Program.cs
3.015625
3
using System; namespace Double_Linked_List { class Program { static void Main() { DoublyLinkedList<int> list = new DoublyLinkedList<int>(); list.AddFirst(1); list.AddLast(2); list.AddLast(3); list.PrintForwards(); list.AddFirst(0); list.PrintForwards(); Console.WriteLine(list.RemoveFirst()); list.PrintForwards(); list.RemoveLast(); list.PrintForwards(); list.AddLast(3); Console.WriteLine( list.Remove(2)); list.PrintForwards(); list.PrintBackwards(); //Extensions.PrintEnumerable(list); list.PrintEnumerable(); list.PrintEnumerableBackwards(); //Extensions.PrintEnumerableBackwards(list); ////////////////////////// //Next Week: //Circular Linked List //Recursion //Unique Ptrs } } }
b2114a77e3c8e33a3a295509c4071bab7ec11832
C#
thankshelp/oopLab2
/lab2/Point.cs
3.046875
3
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using System.Windows.Shapes; namespace lab2 { public class Point2D { private double x, y; public Point2D() { x = 0; y = 0; } public double Getx() { return x; } public double Gety() { return y; } public void SetX(double x) { this.x = x; } public void SetY(double y) { this.y = y; } public void moveX(double mx) { this.x += mx; } public void moveY(double my) { this.y += my; } } }
36beac218aa05349f2cb2cfd2e4fc39c2d8bd816
C#
hapikit/hapikit.net
/src/Hapikit.net/Parser/Context.cs
2.625
3
using System; using System.Linq; using System.Collections.Generic; namespace Hapikit { public class Context { public object Subject { get; private set; } public VocabTerm TermMap { get; private set; } public string LastProperty { get; set; } public Context(object subject, VocabTerm term) { Subject = subject; TermMap = term; } public override string ToString() { return $"{Subject?.GetType().Name} : {TermMap?.Term}"; } } }
c738f28030cd43f34b9ce88d8b62832fac2daa39
C#
bde0x1/BoardGame
/BoardGame/InGameInformationForms/PropertyCard.cs
2.75
3
using BoardGame.Domain_Model; using System; using System.Windows.Forms; namespace BoardGame { public partial class PropertyCard : Form { public string FieldName { get; set; } public int FieldValue { get; set; } public int FieldFinishedValue { get; set; } public int FieldBuildingTurns { get; set; } private Cards m_Cards; private Player m_Player; public PropertyCard(Player player, Cards card) { InitializeComponent(); ButtonTip.SetToolTip(Cancel, "Nem veszem meg"); ButtonTip.SetToolTip(Ok, "Lelet megvásárlása"); this.m_Player = player; this.m_Cards = card; Random randomCard = new Random(); int randomCardNumber = randomCard.Next(0, m_Cards.PropertyCards.Count); PlayerOrRobotName.Text = player.Name; for (int i = 0; i < m_Cards.PropertyCards.Count; i++) { if (i == randomCardNumber) { CardText.Text = "Gratulálok! Felfedeztél egy " + m_Cards.PropertyCards[i].PropertyName + "-t."; TurnText.Text = "A feltárásának idelye: " + m_Cards.PropertyCards[i].BuildingTurns + " kör."; FinishedValue.Text = "Ammennyiben elvégezted " + m_Cards.PropertyCards[i].PropertyFinishedValue + "$-t kapsz."; Price.Text = m_Cards.PropertyCards[i].PropertyValue + "$"; if (player.Balance >= m_Cards.PropertyCards[i].PropertyValue) { FieldFinishedValue = m_Cards.PropertyCards[i].PropertyFinishedValue; FieldValue = m_Cards.PropertyCards[i].PropertyValue; FieldName = m_Cards.PropertyCards[i].PropertyName; FieldBuildingTurns = m_Cards.PropertyCards[i].BuildingTurns; m_Player.MyPropertyCards.Add(m_Cards.PropertyCards[i]); m_Cards.PropertyCards.RemoveAt(i); } else { MessageBox.Show("Sajnáljuk nincs elég Pénezd!", "Bank", MessageBoxButtons.OK); Ok.Enabled = false; } } } } private void Ok_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; this.Close(); } private void Cancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; this.Close(); } } }
5cce7732d0f43d4a0b223fca71e2340087e733d8
C#
drowhunter/Steam-Library-Manager
/Source/Steam Library Manager/Framework/SteamIDConvert.cs
2.71875
3
using System; using System.Globalization; using System.Text.RegularExpressions; /* SteamID-NET * https://github.com/NachoReplay/SteamID-NET * GNU General Public License v3.0 * https://github.com/NachoReplay/SteamID-NET/blob/master/LICENSE */ namespace Steam_Library_Manager.Framework { /// <summary> /// Auth type enumeration, From SourcePawn's Clients.inc /// </summary> public enum AuthIdType { /// <summary> /// The game-specific auth string as returned from the engine /// </summary> AuthId_Engine = 0, // The following are only available on games that support Steam authentication. /// <summary> /// Steam2 rendered format, ex "STEAM_1:1:4153990" /// </summary> AuthId_Steam2, /// <summary> /// Steam3 rendered format, ex "U:1:8307981" /// </summary> AuthId_Steam3, /// <summary> /// A SteamID64 (uint64) as a String, ex "76561197968573709" /// </summary> AuthId_SteamID64, }; /// <summary> /// SteamID Regex constents /// </summary> public static class SteamIDRegex { /// <summary> /// SteamID2 Regex /// </summary> public const string Steam2Regex = "^STEAM_0:[0-1]:([0-9]{1,10})$"; /// <summary> /// SteamID32 Regex /// </summary> public const string Steam32Regex = "^U:1:([0-9]{1,10})$"; /// <summary> /// SteamID64 Regex /// </summary> public const string Steam64Regex = "^7656119([0-9]{10})$"; } /// <summary> /// SteamId converting class. /// </summary> public static class SteamIDConvert { /// <summary> /// Converts a <see cref="AuthIdType.AuthId_Steam3"/> to a <see cref="AuthIdType.AuthId_Steam2"/> format. /// </summary> /// <param name="input">String input of AuthId_Steam3</param> /// <returns>Returns the SteamID2(STEAM_0:1:000000) string.</returns> public static string Steam32ToSteam2(string input) { if (!Regex.IsMatch(input, SteamIDRegex.Steam32Regex)) { return string.Empty; } long steam64 = Steam32ToSteam64(input); return Steam64ToSteam2(steam64); } /// <summary> /// Converts a <see cref="AuthIdType.AuthId_Steam2"/> to a <see cref="AuthIdType.AuthId_Steam3"/> /// </summary> /// <param name="input"></param> /// <returns></returns> public static string Steam2ToSteam32(string input) { if (!Regex.IsMatch(input, SteamIDRegex.Steam2Regex)) { return string.Empty; } long steam64 = Steam2ToSteam64(input); return Steam64ToSteam32(steam64); } /// <summary> /// Converts our <see cref="AuthIdType.AuthId_Steam3"/> to the <see cref="AuthIdType.AuthId_SteamID64"/> format. /// </summary> /// <param name="input">AuthId_Steam3</param> /// <returns>Returns the SteamID64(76561197960265728) in long type</returns> public static long Steam32ToSteam64(string input) { long steam32 = Convert.ToInt64(input.Substring(4)); if (steam32 < 1L || !Regex.IsMatch("U:1:" + steam32.ToString(CultureInfo.InvariantCulture), "^U:1:([0-9]{1,10})$")) { return 0; } return steam32 + 76561197960265728L; } /// <summary> /// Converts a <see cref="AuthIdType.AuthId_SteamID64"/> to a <see cref="AuthIdType.AuthId_Steam2"/> /// </summary> /// <param name="communityId">SteamID64(76561197960265728)</param> /// <returns>String.empty if error, else the string SteamID2(STEAM_0:1:000000)</returns> public static string Steam64ToSteam2(long communityId) { if (communityId < 76561197960265729L || !Regex.IsMatch(communityId.ToString(CultureInfo.InvariantCulture), "^7656119([0-9]{10})$")) return string.Empty; communityId -= 76561197960265728L; long num = communityId % 2L; communityId -= num; string input = string.Format("STEAM_0:{0}:{1}", num, (communityId / 2L)); if (!Regex.IsMatch(input, "^STEAM_0:[0-1]:([0-9]{1,10})$")) { return string.Empty; } return input; } /// <summary> /// Converts a <see cref="AuthIdType.AuthId_Steam2"/> to a <see cref="AuthIdType.AuthId_SteamID64"/> /// </summary> /// <param name="accountId"></param> /// <returns>Retruns a <see cref="AuthIdType.AuthId_SteamID64"/></returns> public static long Steam2ToSteam64(string accountId) { if (!Regex.IsMatch(accountId, "^STEAM_0:[0-1]:([0-9]{1,10})$")) { return 0; } return 76561197960265728L + Convert.ToInt64(accountId.Substring(10)) * 2L + Convert.ToInt64(accountId.Substring(8, 1)); } /// <summary> /// Converts a <see cref="AuthIdType.AuthId_SteamID64"/> to a <see cref="AuthIdType.AuthId_Steam3"/> /// </summary> /// <param name="communityId"></param> /// <returns>Returns a <see cref="AuthIdType.AuthId_Steam3"/> string</returns> public static string Steam64ToSteam32(long communityId) { if (communityId < 76561197960265729L || !Regex.IsMatch(communityId.ToString(CultureInfo.InvariantCulture), "^7656119([0-9]{10})$")) { return string.Empty; } return string.Format("U:1:{0}", communityId - 76561197960265728L); } } /// <summary> /// Here we have our engine object for conversion, manipulation, and identification of ID. /// </summary> public class SteamID_Engine { /// <summary> /// The SteamID we are working with. /// </summary> public string WorkingID { get; private set; } /// <summary> /// The current working steamid <see cref="AuthIdType"/> if <see cref="AuthIdType.AuthId_Engine"/> is set that means that the ID is NOT a valid account ID. /// </summary> public AuthIdType AuthType { private set; get; } /// <summary> /// The <see cref="AuthIdType.AuthId_Steam2"/> equivalent of the <see cref="WorkingID"/> /// </summary> public string Steam2 { private set; get; } /// <summary> /// The <see cref="AuthIdType.AuthId_Steam3"/> equivalent of <see cref="WorkingID"/> /// </summary> public string Steam32 { private set; get; } /// <summary> /// The <see cref="AuthIdType.AuthId_SteamID64"/> equivalent of <see cref="WorkingID"/> /// </summary> public long Steam64 { private set; get; } /// <summary> /// Sets our objects steamid refrence to work with. <see cref="WorkingID"/> /// </summary> /// <param name="ID">An id to work with.</param> public SteamID_Engine(string ID) { WorkingID = ID; if (Regex.IsMatch(WorkingID, SteamIDRegex.Steam2Regex)) { AuthType = AuthIdType.AuthId_Steam2; Steam2 = WorkingID; Steam32 = SteamIDConvert.Steam2ToSteam32(WorkingID); Steam64 = SteamIDConvert.Steam2ToSteam64(WorkingID); } else if (Regex.IsMatch(WorkingID, SteamIDRegex.Steam32Regex)) { AuthType = AuthIdType.AuthId_Steam3; Steam2 = SteamIDConvert.Steam32ToSteam2(WorkingID); Steam32 = WorkingID; Steam64 = SteamIDConvert.Steam32ToSteam64(WorkingID); } else if (Regex.IsMatch(WorkingID, SteamIDRegex.Steam64Regex)) { AuthType = AuthIdType.AuthId_SteamID64; Steam2 = SteamIDConvert.Steam64ToSteam2(Int64.Parse(WorkingID)); Steam32 = SteamIDConvert.Steam64ToSteam32(Int64.Parse(WorkingID)); Steam64 = Int64.Parse(WorkingID); } else { AuthType = AuthIdType.AuthId_Engine; } } /// <summary> /// Returns the string representation of the current <see cref="WorkingID"/> /// </summary> /// <returns></returns> public string AuthType_string() { if (AuthType == AuthIdType.AuthId_Steam2) { return "SteamID2"; } else if (AuthType == AuthIdType.AuthId_Steam3) { return "SteamID32"; } else if (AuthType == AuthIdType.AuthId_SteamID64) { return "SteamID64"; } else if (AuthType == AuthIdType.AuthId_Engine) { return "Engine ID"; } else { return string.Empty; } } } }
78b8f22f6228c5697aba1e88c38055b07de756c6
C#
fescastro/ACAI
/Acai.Api/Persistence/Contexts/AppDbContext.cs
2.625
3
using Microsoft.EntityFrameworkCore; using Acai.Api.Domain.Models; namespace Acai.Api.Persistence.Contexts { //Classe resposável por mapear os models do dominio para tabelas public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options){ } public DbSet<Pedido> Pedidos {get; set;} public DbSet<Tamanho> Tamanhos {get; set;} public DbSet<Sabor> Sabores {get; set;} public DbSet<Adicional> Adicionals {get; set;} public DbSet<PedidoAdicional> PedidosAdicionais {get; set;} protected override void OnModelCreating(ModelBuilder builder){ base.OnModelCreating(builder); ModelBuilderPedido(builder); ModelBuilderTamanho(builder); ModelBuilderSabor(builder); ModelBuilderAdicional(builder); ModelBuilderPedidoAdicional(builder); } private void ModelBuilderPedido(ModelBuilder builder){ builder.Entity<Pedido>().ToTable("Pedido"); builder.Entity<Pedido>().HasKey(p => p.Id); builder.Entity<Pedido>().Property(p => p.Id).IsRequired(); builder.Entity<Pedido>().Property(p => p.Cliente).IsRequired().HasMaxLength(30); builder.Entity<Pedido>().Property(p => p.ValorTotalPedido).HasColumnType("decimal(5,3)").IsRequired(); builder.Entity<Pedido>().HasOne<Tamanho>(p => p.Tamanho).WithMany(p => p.Pedidos).HasForeignKey(p => p.TamanhoId); builder.Entity<Pedido>().HasOne<Sabor>(p => p.Sabor).WithMany(p => p.Pedidos).HasForeignKey(p => p.SaborId); } private void ModelBuilderTamanho(ModelBuilder builder){ builder.Entity<Tamanho>().ToTable("Tamanho"); builder.Entity<Tamanho>().HasKey(p => p.Id); builder.Entity<Tamanho>().Property(p => p.Id).IsRequired(); builder.Entity<Tamanho>().Property(p => p.Descricao).IsRequired().HasMaxLength(30); builder.Entity<Tamanho>().Property(p => p.Ml).IsRequired().HasMaxLength(6); builder.Entity<Tamanho>().Property(p => p.TempoMinutos).IsRequired(); builder.Entity<Tamanho>().Property(p => p.Valor).HasColumnType("decimal(5,3)").IsRequired(); } private void ModelBuilderSabor(ModelBuilder builder){ builder.Entity<Sabor>().ToTable("Sabor"); builder.Entity<Sabor>().HasKey(p => p.Id); builder.Entity<Sabor>().Property(p => p.Id).IsRequired(); builder.Entity<Sabor>().Property(p => p.Descricao).IsRequired().HasMaxLength(30); builder.Entity<Sabor>().Property(p => p.TempoMinutos).IsRequired(); } private void ModelBuilderAdicional(ModelBuilder builder){ builder.Entity<Adicional>().ToTable("Adicional"); builder.Entity<Adicional>().HasKey(p => p.Id); builder.Entity<Adicional>().Property(p => p.Id).IsRequired(); builder.Entity<Adicional>().Property(p => p.Descricao).IsRequired().HasMaxLength(30); builder.Entity<Adicional>().Property(p => p.TempoMinutos).IsRequired(); builder.Entity<Adicional>().Property(p => p.Valor).HasColumnType("decimal(5,3)").IsRequired(); } private void ModelBuilderPedidoAdicional(ModelBuilder builder){ builder.Entity<PedidoAdicional>().ToTable("Pedido_Adicional"); builder.Entity<PedidoAdicional>().HasKey(p => new {p.AdicionalId, p.PedidoId}); builder.Entity<PedidoAdicional>().Property(p => p.AdicionalId).IsRequired(); builder.Entity<PedidoAdicional>().Property(p => p.PedidoId).IsRequired(); builder.Entity<PedidoAdicional>().HasOne(p => p.Pedido).WithMany(p => p.pedidoAdicionals).HasForeignKey(p => p.PedidoId); builder.Entity<PedidoAdicional>().HasOne(p => p.Adicional).WithMany(p => p.pedidoAdicionals).HasForeignKey(p => p.AdicionalId); } } }
f146cc64431a5c9b9ea5a4cb4ae2550d800b01cf
C#
A-Larkins/Temple_Book_Store
/Bookstore/BookLibrary/Student.cs
3.0625
3
/* * Andrew Larkins * 09/21/20 * Student class to store info. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BookLibrary { public class Student { String id; String name; String address; String phoneNum; String campus; public Student(String id, String name, String address, String phoneNum, String campus) { id = this.Id; name = this.Name; address = this.Address; phoneNum = this.PhoneNum; campus = this.Campus; } public Student() { } public string Id { get => id; set => id = value; } public string Name { get => name; set => name = value; } public string Address { get => address; set => address = value; } public string PhoneNum { get => phoneNum; set => phoneNum = value; } public string Campus { get => campus; set => campus = value; } } }
fd7945b3291e6824bb66b46fe631010560af49a8
C#
Vael-hub/BlazorTutorial
/CustomerManagement.Models/ClientContact.cs
2.640625
3
using System; using System.ComponentModel.DataAnnotations; namespace BusinessManagement.Models { public class ClientContact { public int ContactId { get; set; } /// <summary> /// Prénom du client /// </summary> public string FirstName { get; set; } /// <summary> /// Nom du client /// </summary> public string LastName { get; set; } /// <summary> /// Numéro de téléphone /// </summary> [DataType(DataType.PhoneNumber)] public string PhoneNumber { get; set; } /// <summary> /// Mail de contact /// </summary> [EmailAddress(ErrorMessage = "L'adresse mail n'est pas valide")] public string Mail { get; set; } /// <summary> /// Société du contact /// </summary> public Society Society { get; set; } } }
77373d8b0ec09dabe3b7800a386360d079533010
C#
AlexShkor/cqrs-pocker-app-example
/src/Poker/Platform/Settings/SettingsMapper.cs
3.1875
3
using System; using System.Reflection; namespace Poker.Platform.Settings { /// <summary> /// Maps application settings to your custom type or to existing instance of object /// SettingsMapper read <appSettings /> right from your *.config file /// </summary> public static class SettingsMapper { /// <summary> /// Map application settings to instance of specified type /// </summary> public static TObject Map<TObject>() where TObject : class, new() { var instance = Activator.CreateInstance(typeof(TObject)); Map(typeof(TObject), instance); return (TObject)instance; } /// <summary> /// Map application settings to existing object instance /// </summary> public static void Map<TObject>(TObject instance) where TObject : class, new() { Map(typeof(TObject), instance); } /// <summary> /// Map application settings to instance of specified type /// </summary> public static Object Map(Type type, string prefix = null) { var instance = Activator.CreateInstance(type); Map(type, instance, prefix); return instance; } /// <summary> /// Map application settings to existing object instance /// </summary> public static void Map(Object instance, string prefix = null) { Map(instance.GetType(), instance, prefix); } /// <summary> /// Map application settings to your custom type or to existing instance of object /// null i /// </summary> private static void Map(Type type, Object instance, string prefix = null) { // Create object instance if not specified if (instance == null) throw new ArgumentNullException("instance"); // Get all the public properties of the type PropertyInfo[] propertyInfos = type.GetProperties(); foreach (var propertyInfo in propertyInfos) { Object[] propertyAttributes = propertyInfo.GetCustomAttributes(typeof(SettingsPropertyAttribute), true); if (propertyAttributes.Length == 0) continue; Object[] prefixAttributes = propertyInfo.GetCustomAttributes(typeof(SettingsPrefixAttribute), true); if (prefixAttributes.Length == 1) { prefix = ((SettingsPrefixAttribute)prefixAttributes[0]).Prefix; } ApplySettingsProperty(instance, propertyInfo, (SettingsPropertyAttribute)propertyAttributes[0], prefix); } } private static void ApplySettingsProperty(Object instance, PropertyInfo propertyInfo, SettingsPropertyAttribute attribute, string prefix = null) { // If key was not specified we assuming that this is inner object if (!attribute.IsKeySpecified) { var innerObj = Map(propertyInfo.PropertyType, prefix); propertyInfo.SetValue(instance, innerObj, null); return; } // Reading settings from <appSettings /> var key = String.IsNullOrEmpty(prefix) ? attribute.Key : String.Format("{0}.{1}", prefix, attribute.Key); var value = System.Configuration.ConfigurationManager.AppSettings[key]; Object convertedValue = null; // If this is Boolean if (propertyInfo.PropertyType == typeof(Boolean)) { if (String.Compare(value, "true", true) == 0 || String.Compare(value, "yes", true) == 0) convertedValue = true; else if (String.Compare(value, "false", true) == 0 || String.Compare(value, "no", true) == 0) convertedValue = false; else throw new Exception(String.Format("Cannot convert from '{0}' to Boolean. Value can be 'true' or 'false'.", value)); } // Otherwise we are using System.Convert else { convertedValue = Convert.ChangeType(value, propertyInfo.PropertyType); } propertyInfo.SetValue(instance, convertedValue, null); } } }
de6cec6fc3e6d84f98295b916882809ea3b4a995
C#
warappa/XamlCSS
/XamlCSS.XamarinForms/ComponentModel/EnumTypeConverter.cs
2.546875
3
using System; using System.Globalization; using Xamarin.Forms; namespace XamlCSS.ComponentModel { public class EnumTypeConverter<Tout> : TypeConverter { public override bool CanConvertFrom(Type sourceType) { return sourceType == typeof(string); } public override object ConvertFrom(CultureInfo culture, object o) { return Enum.Parse(typeof(Tout), o as string, true); } public override object ConvertFrom(object o) { return Enum.Parse(typeof(Tout), o as string, true); } public override object ConvertFromInvariantString(string value) { return Enum.Parse(typeof(Tout), value, true); } } }
00eee06296918535276b1f69923bce8eb0f580db
C#
aakesh001/ongoing
/Pavani/ConsolDemo/DataTransformationEngine 20180320/DataTransformationEngine/DataStore/DataObject.cs
2.9375
3
using System; using System.Data; using System.Collections.Generic; using AppConfigurations; namespace DataStore { //Base DataObject class for the transformation engine //Contains a DataTable to hold the data //Trying out a MetaInfo to store properties of column (may not be needed) public class DataObject { protected DataTable dataTable = new DataTable(); protected List<DataObjectColumnMetaInfo> metaInfo = new List<DataObjectColumnMetaInfo>(); protected String SOURCE_FIELD_NAME = "sourceFieldName"; protected String SOURCE_FIELD_NAME_1 = "sourceFieldName1"; protected String SOURCE_FIELD_NAME_2 = "sourceFieldName2"; protected String TARGET_FIELD_NAME = "targetFieldName"; protected String VALUE = "value"; protected String SOURCE_FORMAT = "sourceFormat"; protected String TARGET_FORMAT = "targetFormat"; protected String DEFAULT_ACTION = "defaultAction"; protected String LOOKUP_TABLE = "lookupTable"; protected String SEPARATOR = "separator"; /// <summary> /// Creating a new DataObject with a Name /// </summary> /// <param name="tableName"></param> public DataObject(String tableName) { dataTable = new DataTable(tableName); initializeMetaInfo(); } /// <summary> /// Creating a new DataObject using a DataTable /// </summary> /// <param name="dTbl"></param> public DataObject(DataTable dTbl) { dataTable = dTbl; dataTable.TableName = "Default"; initializeMetaInfo(); } /// <summary> /// Initializing MetaInfo /// </summary> private void initializeMetaInfo() { for (int column = 0; column < dataTable.Columns.Count; column++) { DataObjectColumnMetaInfo columnMetaInfo = new DataObjectColumnMetaInfo(); columnMetaInfo.columnName = dataTable.Columns[column].ColumnName; metaInfo.Add(columnMetaInfo); } } /// <summary> /// Getting the DataTable /// </summary> public DataTable Data { get { return dataTable; } } //Adding a new column, no type defined, no data protected void AddColumn(String columnName) { //Add Column to DataTable DataColumn dataColumn = new DataColumn(columnName); dataTable.Columns.Add(dataColumn); //Add Column Meta Info DataObjectColumnMetaInfo columnMetaInfo = new DataObjectColumnMetaInfo(); columnMetaInfo.columnName = columnName; metaInfo.Add(columnMetaInfo); } public void Map(MapSet mapSet, LookupTableSet lookupTableSet) { foreach (Map map in mapSet.Maps) { Console.WriteLine("Performing :" + map.Action + "\tAdding : " + map.GetParameter(TARGET_FIELD_NAME)); //REMOVE //TODO: Validate - Target Field Name must be present on the map parameters switch (map.Action) { case "copy": Copy(map.GetParameter(SOURCE_FIELD_NAME), map.Parameters[TARGET_FIELD_NAME], map.Parameters[VALUE]); break; case "assign": Assign(map.GetParameter(TARGET_FIELD_NAME), map.GetParameter(VALUE)); break; case "lookup": Lookup(map.GetParameter(SOURCE_FIELD_NAME), map.GetParameter(TARGET_FIELD_NAME), lookupTableSet.LookupTables[map.GetParameter(LOOKUP_TABLE)], map.GetParameter(DEFAULT_ACTION), map.GetParameter(VALUE)); break; case "formatDate": FormatDate(map.GetParameter(SOURCE_FIELD_NAME), map.GetParameter(TARGET_FIELD_NAME), map.GetParameter(SOURCE_FORMAT), map.GetParameter(TARGET_FORMAT)); break; case "concat": Concat(map.GetParameter(SOURCE_FIELD_NAME_1), map.GetParameter(SOURCE_FIELD_NAME_2), map.GetParameter(TARGET_FIELD_NAME), map.GetParameter(VALUE)); break; } } } ///<summary> ///Copy field to target, assign a default value if source feld is unavailable or null. ///</summary> public void Copy(String sourceFieldName, String targetFieldName, String value) { DataColumn newColumn = new DataColumn(targetFieldName); if (dataTable.Columns.Contains(sourceFieldName)) { String expression = "IIF([" + sourceFieldName + "]<>'', [" + sourceFieldName + "], \'" + value + "\')"; newColumn.Expression = expression; dataTable.Columns.Add(newColumn); } else { Assign(targetFieldName, value); } } ///<summary> ///Assign a value to target field. ///</summary> public void Assign(String targetFieldName, String value) { DataColumn newColumn = new DataColumn(targetFieldName); String expression = "\'" + value + "\'"; newColumn.Expression = expression;//TODO: Handling XML escape sequences, and \ " ' on value. dataTable.Columns.Add(newColumn); } ///<summary> ///Lookup a table to derive target field value from source. ///</summary> /// defaultAction: /// copy - Copies the source field into the target field if the lookup /// yields no result. /// assign - Assigns the value in <value> if specified if lookup returns /// no result.Sets null if <value> is missing. /// null - Assigns null value to target.This is the default, if default /// is not specified. public void Lookup(String sourceFieldName, String targetFieldName, LookupTable lookupTable, String defaultAction, String value) { AddColumn(targetFieldName); for (int row = 0; row < dataTable.Rows.Count; row++) { String defaultValue = String.Empty; switch (defaultAction) { case "copy": defaultValue = dataTable.Rows[row][sourceFieldName].ToString(); break; case "value": defaultValue = value; break; default: break; } dataTable.Rows[row][targetFieldName] = lookupTable.Lookup(dataTable.Rows[row][sourceFieldName].ToString(), defaultValue); } } public void Concat(String sourceFieldName1, String sourceFieldName2, String targetFieldName, String seprator) { DataColumn newColumn = new DataColumn(targetFieldName); String expression = "[" + sourceFieldName1 + "] + \' \' + [" + sourceFieldName2 + "]"; newColumn.Expression = expression; dataTable.Columns.Add(newColumn); } public void FormatDate(String sourceFieldName, String targetFieldName, String sourceDateFormat, String targetDateFormat) { String sourceFieldValue = String.Empty; String targetFieldValue = String.Empty; String ccyy = String.Empty; String MM = String.Empty; String dd = String.Empty; if (sourceDateFormat == targetDateFormat) { Copy(sourceFieldName, targetFieldName, ""); return; } else { AddColumn(targetFieldName); for (int row = 0; row < dataTable.Rows.Count; row++) { sourceFieldValue = dataTable.Rows[row][sourceFieldName].ToString() + " "; switch (sourceDateFormat) { case "ccyyMMdd": ccyy = sourceFieldValue.Substring(0, 4); MM = sourceFieldValue.Substring(4, 2); dd = sourceFieldValue.Substring(6, 2); break; case "ccyy-MM-dd": ccyy = sourceFieldValue.Substring(0, 4); MM = sourceFieldValue.Substring(5, 2); dd = sourceFieldValue.Substring(8, 2); break; case "MM/dd/ccyy": case "MM-dd-ccyy": ccyy = sourceFieldValue.Substring(6, 4); MM = sourceFieldValue.Substring(0, 2); dd = sourceFieldValue.Substring(3, 2); break; case "dd/MM/ccyy": case "dd-MM-ccyy": ccyy = sourceFieldValue.Substring(6, 4); MM = sourceFieldValue.Substring(3, 2); dd = sourceFieldValue.Substring(0, 2); break; default: //TODO: Action on bad source date format break; } switch (targetDateFormat) { case "ccyyMMdd": targetFieldValue = ccyy + MM + dd; break; case "ccyy-MM-dd": targetFieldValue = ccyy + "-" + MM + "-" + dd; break; case "MM/dd/ccyy": targetFieldValue = MM + "/" + dd + "/" + ccyy; break; case "MM-dd-ccyy": targetFieldValue = MM + "-" + dd + "-" + ccyy; break; case "dd/MM/ccyy": targetFieldValue = dd + "/" + MM + "/" + ccyy; break; case "dd-MM-ccyy": targetFieldValue = dd + "-" + MM + "-" + ccyy; break; default: //TODO: Action on bad source date format break; } dataTable.Rows[row][targetFieldName] = targetFieldValue; } } } public void FormatDateDeprecated(String sourceFieldName, String targetFieldName, String sourceDateFormat, String targetDateFormat) { int ccyyPosition = 0; int MMPosition = 0; int ddPosition = 0; switch (sourceDateFormat) { case "ccyyMMdd": ccyyPosition = 0; MMPosition = 4; ddPosition = 6; break; case "ccyy-MM-dd": ccyyPosition = 0; MMPosition = 5; ddPosition = 8; break; case "MM/dd/ccyy": case "MM-dd-ccyy": ccyyPosition = 6; MMPosition = 0; ddPosition = 3; break; case "dd/MM/ccyy": case "dd-MM-ccyy": ccyyPosition = 6; MMPosition = 3; ddPosition = 0; break; } String expression = "\'\'"; switch (targetDateFormat) { case "ccyyMMdd": expression = "SUBSTRING([" + sourceFieldName + "]+\' \'," + ccyyPosition + ",4) + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + MMPosition + ",2) + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + ddPosition + ",2)"; break; case "ccyy-MM-dd": expression = "SUBSTRING([" + sourceFieldName + "]+\' \'," + ccyyPosition + ",4) + \'-\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + MMPosition + ",2) + \'-\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + ddPosition + ",2)"; break; case "MM/dd/ccyy": expression = "SUBSTRING([" + sourceFieldName + "]+\' \'," + MMPosition + ",2) + \'\\\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + ddPosition + ",2) + \'\\\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + ccyyPosition + ",4)"; break; case "MM-dd-ccyy": expression = "SUBSTRING([" + sourceFieldName + "]+\' \'," + MMPosition + ",2) + \'-\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + ddPosition + ",2) + \'-\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + ccyyPosition + ",4)"; break; case "dd/MM/ccyy": expression = "SUBSTRING([" + sourceFieldName + "]+\' \'," + ddPosition + ",2) + \'\\\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + MMPosition + ",2) + \'\\\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + ccyyPosition + ",4)"; break; case "dd-MM-ccyy": expression = "SUBSTRING([" + sourceFieldName + "]+\' \'," + ddPosition + ",2) + \'-\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + MMPosition + ",2) + \'-\' + " + "SUBSTRING([" + sourceFieldName + "]+\' \'," + ccyyPosition + ",4)"; break; default: //TODO: Action on bad source date format break; } Console.WriteLine(expression); DataColumn newColumn = new DataColumn(targetFieldName); newColumn.Expression = expression; try { dataTable.Columns.Add(newColumn); } catch (ArgumentOutOfRangeException argOutOfRange){ Console.WriteLine(argOutOfRange); } } public virtual void Transform() { } } }
e22ab02473a27be1b4f900a507c2c9eb0703979f
C#
javierpuntonet/Alexa.NET.SkillFlow.Interpreter
/Alexa.NET.SkillFlow.Interpreter.Tests/GoToTests.cs
2.6875
3
using System; using System.Collections.Generic; using System.Text; using Alexa.NET.SkillFlow.Instructions; using Alexa.NET.SkillFlow.Interpreter; using Xunit; namespace Alexa.NET.SkillFlow.Tests { public class GoToTests { [Fact] public void CorrectlyIdentifiesText() { var interpreter = new GoToInterpreter(); var context = new SkillFlowInterpretationContext(new SkillFlowInterpretationOptions()); context.Components.Push(new SceneInstructions()); Assert.True(interpreter.CanInterpret("->", context)); } [Fact] public void CorrectlyIdentifiesReturn() { var interpreter = new GoToInterpreter(); var context = new SkillFlowInterpretationContext(new SkillFlowInterpretationOptions()); context.Components.Push(new SceneInstructions()); Assert.True(interpreter.CanInterpret("<->", context)); } [Fact] public void CorrectlyIdentifiesFalseText() { var interpreter = new GoToInterpreter(); Assert.False(interpreter.CanInterpret("=>", new SkillFlowInterpretationContext(new SkillFlowInterpretationOptions()))); } [Fact] public void CreatesComponentCorrectly() { var interpreter = new GoToInterpreter(); var result = interpreter.Interpret("-> test", new SkillFlowInterpretationContext(new SkillFlowInterpretationOptions())); var instruction = Assert.IsType<GoTo>(result.Component); Assert.Equal("test",instruction.SceneName); } [Fact] public void CreatesAndReturnComponentCorrectly() { var interpreter = new GoToInterpreter(); var result = interpreter.Interpret("<-> test this thing", new SkillFlowInterpretationContext(new SkillFlowInterpretationOptions())); var gtar = Assert.IsType<GoToAndReturn>(result.Component); Assert.Equal("test this thing", gtar.SceneName); } [Fact] public void AddsCorrectly() { var instruction = new GoTo("test"); var instructions = new SceneInstructions(); instructions.Add(instruction); var result = Assert.Single(instructions.Instructions); Assert.Equal(instruction,result); } [Fact] public void AddsAndReturnCorrectly() { var instruction = new GoToAndReturn(); var instructions = new SceneInstructions(); instructions.Add(instruction); var result = Assert.Single(instructions.Instructions); Assert.Equal(instruction, result); } } }
6000d127852d681fd50c5b697dc808dc5a945d38
C#
SureshKaushik/Algorithms
/DSAlgorithms/LinkedListOperations.cs
3.65625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DSAlgorithms { public class LinkedListOperations { public void CountLinkedList() { Node head = new Node(); Node second = new Node(); Node third = new Node(); head.Data = 1; head.Next = second; second.Data = 2; second.Next = third; third.Data = 3; third.Next = null; // Find total cound of linked list Node current = head; int count = 0; while (current != null) { current = current.Next; Console.WriteLine(current); count++; } } // Find the middle of linked list // Search from liked list // Check whether it contains or not } public class Node { public int Data { get; set; } public Node Next { get; set; } } }
237364b83c4f312a8d00b2b76943931206d445dd
C#
Kuhpik/Design-patterns
/Assets/Behavioral/Memento/RPGCharacter.cs
3.21875
3
using UnityEngine; namespace Kuhpik.DesignPatterns.Behavioral.Memento { public class RPGCharacter { public readonly string Name; //SnapshotManager class can't read private fields int _health; Vector2 _position; public RPGCharacter(string name, int health, Vector2 position) { Name = name; _health = health; _position = position; } public void GetDamage(int damage) { _health -= damage; } public void Move(Vector2 dir) { _position += dir; } public void SetHealth(int health) { _health = health; } public void SetPosition(Vector2 position) { _position = position; } public void PrintState() { Debug.Log($"Character {Name} is on position {_position} and has {_health}"); } public ISnapshot SaveState() { return new RPGCharacterSnapshot(this, _health, _position); } } }
c94349cecf7012dad4fee9f3d09882e06e1b74bb
C#
SoftingIndustrial/OPC-Classic-SDK
/development/NET/src/client/ClientAddressSpaceElement.cs
2.640625
3
using System; using Softing.OPCToolbox.Client; using System.Runtime.InteropServices; using Softing.OPCToolbox; using Softing.OPCToolbox.OTB; namespace Softing.OPCToolbox.Client { /// <summary> /// <para>Represents an element in an OPC Server's address space.</para> /// <para> /// The elements in an OPC Server's address space have different signification depending on the OPC specification supported by the OPC Server. /// <br></br>The address space of an <b>Data Access Server</b> contains all the data sources and data sinks made available by that <b>Data Access Server.</b> /// <br></br>It can be a structure of any depth(hierarchical) or it can be flat. /// <br></br> In the flat adress space there are no nodes and all the leaves are on the same level. /// <br></br>A hierarchical presentation of the server address space would behave much like a file system, where the directories /// are the branches or paths, and the files represent the leaves or items. /// For example, a server could present a control system by showing all the control networks, then all of the devices /// on a selected network, and then all of the classes of data within a device, then all of the data items of that class. /// In a hierachical adress space, nodes can be used as structuring means.The nodes can for example represent devices in an installation; /// leaves are available at the nodes,representing data sinks(e.g.controllers) and data sources(e.g.temperature sensors). /// These can be setpoints and measured variables of a device. /// </para> /// <para>The address space of an <b>Alarms and Events Server</b> is always hierarchical and is used for topographic organization of events. /// The nodes of the address space describe areas in which events may occur(e.g. room).The leaves describe events sources. /// Several events can be available at one event source (e.g monitoring of the temperature value and the temperature sensor). /// </para> /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/doc/*' /// /> [Serializable] public class AddressSpaceElement : IDisposable { #region // Public Constructors //----------------------------- /// <summary> /// Initializes a new instance of the <see cref="AddressSpaceElement"/> class with /// the value indicated by an element name and an element handle. /// </summary> /// <param name="aType">The type of the address space element</param> /// <param name="aName">A name for the address space element.</param> /// <param name="aQualifiedName">The qualified name for the address space element.</param> /// <param name="aHandle">A handle for the address space element.</param> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/constructor[@name="AddressSpaceElement"]/doc/*' /// /> public AddressSpaceElement( EnumAddressSpaceElementType aType, string aName, string aQualifiedName, uint aHandle) { m_type = aType; m_name = aName; m_qName = aQualifiedName; m_objectElementHandle = aHandle; } /// <summary> /// The <see cref="AddressSpaceElement">AddressSpaceElement</see> class destructor. /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/method[@name="Finalize"]/doc/*' /// /> ~AddressSpaceElement() { Dispose(); } /// <summary> /// Releases the resources used by the <see cref="AddressSpaceElement"/> object. /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/method[@name="Dispose"]/doc/*' /// /> public void Dispose() { if (m_objectElementHandle != 0) { OTBFunctions.OTCReleaseAddressSpaceElement(m_objectElementHandle, 0); } } //- #endregion #region //Protected Attributes //---------------------------- internal uint m_objectElementHandle = 0; /// <summary> /// A name for an element within the server's address space. /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/field[@name="m_name"]/doc/*' /// /> protected string m_name = string.Empty; /// <summary> /// A qualified name for an element within the server's address space. /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/field[@name="m_qName"]/doc/*' /// /> protected string m_qName = string.Empty; /// <summary> /// The type of the addrerss space element as retrieved from the server /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/field[@name="m_type"]/doc/*' /// /> protected EnumAddressSpaceElementType m_type = EnumAddressSpaceElementType.LEAF; //- #endregion #region //Public Properties //------------------------- ///<summary> ///Gets the handle of an <see cref="AddressSpaceElement"/> in the server's adress space. ///</summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/property[@name="Handle"]/doc/*' /// /> public uint Handle { get { return m_objectElementHandle; } } /// <summary> /// Gets or sets the name of an <see cref="AddressSpaceElement"/> within the server's adress space. /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/property[@name="Name"]/doc/*' /// /> public virtual string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// Gets or sets the qualified name of an <see cref="AddressSpaceElement"/> within the server's address space. /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/property[@name="QualifiedName"]/doc/*' /// /> public virtual string QualifiedName { get { return m_qName; } set { m_qName = value; } } /// <summary> /// Gets the type of an <see cref="AddressSpaceElement"/> within the server's address space. /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/property[@name="IsBranch"]/doc/*' /// /> public bool IsBranch { get { return (m_type & EnumAddressSpaceElementType.BRANCH) != 0; } } /// <summary> /// Gets the type of an <see cref="AddressSpaceElement"/> within the server's address space. /// </summary> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="AddressSpaceElement"]/property[@name="IsLeaf"]/doc/*' /// /> public bool IsLeaf { get { return (m_type & EnumAddressSpaceElementType.LEAF) != 0; } } //- #endregion } // end AddressSpaceElement } // end Softing.OPCToolbox.Client
36385f9498d23c642880ffe832a5be058f976706
C#
IlhamInsankamil/MiniProject
/BuahSayur/BuahSayur.ViewModel/DeliveryOrderHeaderViewModel.cs
2.53125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuahSayur.ViewModel { public class DeliveryOrderHeaderViewModel { // Header public int Id { get; set; } [DisplayName("Username")] public string Customer_Username { get; set; } public string Reference { get; set; } [DisplayName("Selling Date"), DisplayFormat(DataFormatString = "{0:ddd, dd/MM/yyyy}")] public DateTime SellingDate { get; set; } [DisplayName("Shipping Date"), DisplayFormat(DataFormatString = "{0:ddd, dd/MM/yyyy}")] public DateTime ShippingDate { get; set; } public string SellingDateString { get { return SellingDate.ToString("ddd, dd/MM/yyyy"); } } public bool IsSent { get; set; } public bool IsReturned { get; set; } // Detail public List<DeliveryOrderDetailViewModel> DeliveryDetails { get; set; } } public class SellingResult { private bool _Success = true; public bool Success { get { return _Success; } set { _Success = value; } } public string Reference { get; set; } public decimal Total { get; set; } } }
1ce03f9f0eef4cb9e0d8b129753961ca698e02a3
C#
RustamjonUsmonov/hashtable
/hashTable/hashTable/Program.cs
3.203125
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace hashTable { class ThisTable { static Hashtable userInfoHash; } class Program { static void Main(string[] args) { var userInfoHash = new Hashtable(); //Добавление for (int i = 0; i < 10; i++) { userInfoHash.Add(i,"user"+i); } //удаление if (userInfoHash.ContainsKey(0)) { userInfoHash.Remove(0); } //замена if (userInfoHash.ContainsKey(1)) { userInfoHash[1]="replaced"; } //вывод foreach (DictionaryEntry entry in userInfoHash) { Console.WriteLine("Key:"+entry.Key+"/Value:"+entry.Value); } Console.ReadKey(); } } } //******************************************очередь с приоритетом //using System; //using System.Text; //namespace PriorityQueue //{ // class Elem // { // public int Task { get; set; } // public int Priority { get; set; } // public override string ToString() // { // return $"{Priority}:{Task}"; // } // } // class PriorityQueue // { // public int Capacity { get; private set; } // private Elem[] data; // private Elem[] oldData; // public PriorityQueue(Elem[] inputData) // { // Capacity = inputData.Length; // oldData = new Elem[Capacity + 1]; // data = new Elem[2 * Capacity]; // for (int i = 0; i < Capacity; i++) // { // oldData[i] = inputData[i]; // data[Capacity + i] = inputData[i]; // } // FillQueue(); // } // private void FillQueue() // { // for (int k = Capacity - 1; k > 0; k--) // { // if (data[2 * k].Priority > data[2 * k + 1].Priority) // data[k] = data[2 * k]; // else // data[k] = data[2 * k + 1]; // } // } // public PriorityQueue AddElem(Elem elem) // { // var newData = oldData; // newData[oldData.Length - 1] = elem; // return new PriorityQueue(newData); // } // public PriorityQueue GetElem(int n) // { // oldData[n] = null; // var newData = new Elem[oldData.Length - 2]; // int k = 0; // for (var i = 0; i < oldData.Length - 1; i++) // { // if (oldData[i] != null) // { // newData[k] = oldData[i]; // k++; // } // } // return new PriorityQueue(newData); // } // public override string ToString() // { // StringBuilder sb = new StringBuilder(); // for (int k = 1; k < 2 * Capacity; k++) // { // sb.AppendLine($"{k} -- {data[k]}"); // } // return sb.ToString(); // } // } // class Program // { // static void Main(string[] args) // { // Elem[] data = { new Elem { Priority = 1, Task = 1 }, // new Elem { Priority = 2, Task = 2 }, // new Elem { Priority = -1, Task = -1 }, // new Elem { Priority = 4, Task = 4 }, // new Elem { Priority = 5, Task = 5 }, // new Elem { Priority = 5, Task = 6 }, // new Elem { Priority = 3, Task = 7 }, // new Elem { Priority = 4, Task = 8 }}; // PriorityQueue queue = new PriorityQueue(data); // Console.WriteLine(queue); // Console.WriteLine(queue.AddElem(new Elem { Priority = 5, Task = 2 })); // Console.WriteLine(queue.GetElem(4)); // Console.ReadKey(); // } // } //}
056d7fb3976abab94ee39617b4c3375433c04e0d
C#
derfy/yasb
/Yasb.Wireup/ExampleMessage.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Yasb.Common.Messaging; using System.Threading; namespace Yasb.Wireup { [Serializable] public class ExampleMessage2 : ExampleMessage { public ExampleMessage2(int number, string name) : base(number, name) { } } [Serializable] public class ExampleMessage : IMessage { public ExampleMessage(int number, string name) { Number = number; Name = name; } public int Number { get; set; } public string Name { get; set; } } public class ExampleMessageHandler : IHandleMessages<ExampleMessage>, IHandleMessages<ExampleMessage2> { private static int _readCount = 0; public static int ReadCount { get { return _readCount; } } public void Handle(ExampleMessage message) { // Console.WriteLine(string.Format("Handler 1 : {0} {1}", message.Name, message.Number)); Interlocked.Increment(ref _readCount); } public void Handle(ExampleMessage2 message) { //Console.WriteLine(string.Format("Handler 2 {0} {1}", message.Name, message.Number)); //Thread.Sleep(2000); // throw new Exception("bu bu"); Interlocked.Increment(ref _readCount); } } public class ErrorMessage : IMessage { public int Number { get; private set; } public string Name { get; private set; } public ErrorMessage(int number, string name) { Number = number; Name = name; } } }
1c97d5b2219ca648341fc2cab10ea07286b7ed9f
C#
alessiogiordano/Damiera
/Assets/Scripts/Classes/Player.cs
2.703125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player { private int _score; public int score { get => _score; } public void AddScore(int ammount) { _score += Mathf.Abs(ammount); } public PlayerColor color { get; } public Player(PlayerColor color) { this._score = 0; this.color = color; } }
4edb828fa9a9d49daea2b281821c9dae341e1c14
C#
ormikopo1988/design-patterns-csharp-dotnet
/StatePattern/ExamplesForHumans/LowerCase.cs
3
3
using System; namespace StatePattern.ExamplesForHumans { public class LowerCase : IWritingState { public void Write(string words) { Console.WriteLine(words.ToLower()); } } }
2e5cf444b3cc83f8a161381e45fcff59131c83b6
C#
selganor74/chess-sharp
/chess.core/Game/IPiece.cs
2.828125
3
using System.Collections.Generic; namespace chess.core.Game { public interface IPiece { Position Position { get; set; } Kind Kind { get; set; } Color Color { get; set; } Color OpponentsColor { get; } BoardState Board { get; set; } List<Move> ValidMoves(); void Move(Move move); bool IsOpponentOf(IPiece other); bool IsEmptyHouse(); // Creates a perfecto copy of the Piece, //excluding so the piece must be replaced into the board. IPiece Clone(); } }
ba74ef1d8e0dbec218cdf1159e441d27f145236f
C#
AmitHadas/advanced2
/ImageService/ImageService/Commands/CloseGuiCommand.cs
2.671875
3
using ImageService.Commands; using ImageService.Server; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace ImageService.Commands { /// <summary> /// Class CloseGuiCommand. /// </summary> /// <seealso cref="ImageService.Commands.ICommand" /> class CloseGuiCommand : ICommand { /// <summary> /// The m image server /// </summary> private ImageServer m_imageServer; /// <summary> /// Initializes a new instance of the <see cref="CloseGuiCommand"/> class. /// </summary> /// <param name="imageServer">The image server.</param> public CloseGuiCommand(ImageServer imageServer) { m_imageServer = imageServer; } /// <summary> /// Executes the specified arguments. /// </summary> /// <param name="args">The arguments.</param> /// <param name="result">if set to <c>true</c> [result].</param> /// <returns>System.String.</returns> public string Execute(string[] args, out bool result) { result = true; return ""; } } }
2c6d56588c4152c3819077061b7939e5e5d244ba
C#
georgelevinson/DesignPatterns
/Adapter/AdapterDI.cs
3.59375
4
using System; using System.Collections.Generic; using System.Text; namespace Adapter { public interface ICommand { void Execute(); } class SaveCommand : ICommand { public void Execute() { Console.WriteLine("Saving a file"); } } class OpenCommand : ICommand { public void Execute() { Console.WriteLine("Opening a file"); } } public class Button { private ICommand _command; private string _name; public Button(ICommand command, string name) { if (command == null) throw new ArgumentNullException(); _command = command; _name = name; } public void Click() { _command.Execute(); } public void PrintMe() { Console.WriteLine($"I'm a button called {_name}"); } } public class Editor { private IEnumerable<Button> _buttons; public IEnumerable<Button> Buttons => _buttons; public Editor(IEnumerable<Button> buttons) { if (buttons == null) throw new ArgumentNullException(); _buttons = buttons; } public void ClickAll() { foreach (var btn in _buttons) btn.Click(); } } }
e85f48cffd31fecc57a27e2c9991be0db323e0ff
C#
noisynoise/Chaskis
/Chaskis/GenericIrcBot/IrcBot.cs
2.53125
3
// Copyright Seth Hendrick 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file ../../LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) using System; using System.Collections.Generic; using SethCS.Basic; using SethCS.Exceptions; namespace ChaskisCore { public class IrcBot : IDisposable { // -------- Fields -------- /// <summary> /// Version in the form of a string. /// </summary> public const string VersionString = "0.0.1"; /// <summary> /// Semantic Version of the bot. /// </summary> public static readonly SemanticVersion Version = SemanticVersion.Parse( VersionString ); /// <summary> /// The irc config. /// </summary> private readonly IIrcConfig ircConfig; /// <summary> /// The line configs to use. /// </summary> private readonly IList<IIrcHandler> ircHandlers; /// <summary> /// The IRC Connection. /// </summary> private readonly IConnection ircConnection; // -------- Constructor -------- /// <summary> /// Constructor. /// </summary> /// <param name="ircConfig">The irc config object to use. This will be cloned after being passed in.</param> /// <param name="ircHandlers">The line configs to be used in this bot.</param> /// <param name="infoLogEvent">The event to do if we want to log information.</param> /// <param name="errorLogEvent">The event to do if an error occurrs.</param> public IrcBot( IIrcConfig ircConfig, IList<IIrcHandler> ircHandlers, Action<string> infoLogEvent, Action<string> errorLogEvent ) { ArgumentChecker.IsNotNull( ircConfig, nameof( ircConfig ) ); ArgumentChecker.IsNotNull( ircHandlers, nameof( ircHandlers ) ); this.ircConfig = ircConfig.Clone(); this.IrcConfig = new ReadOnlyIrcConfig( this.ircConfig ); this.ircHandlers = ircHandlers; IrcConnection connection = new IrcConnection( ircConfig ); connection.ReadEvent = delegate( string line ) { foreach( IIrcHandler config in this.ircHandlers ) { config.HandleEvent( line, this.ircConfig, connection ); } }; connection.InfoLogEvent = infoLogEvent; connection.ErrorLogEvent = errorLogEvent; this.ircConnection = connection; } // -------- Properties -------- /// <summary> /// Read-only reference to the irc config object. /// </summary> public IIrcConfig IrcConfig { get; private set; } // -------- Functions ------- /// <summary> /// Starts the IRC Connection. No-op if already started. /// </summary> public void Start() { if( this.ircConnection.IsConnected == false ) { this.ircConnection.Connect(); } } /// <summary> /// Stops the IRC Connection. /// </summary> public void Dispose() { if( this.ircConnection.IsConnected ) { try { this.ircConnection.SendPart( this.IrcConfig.QuitMessage ); } finally { this.ircConnection.Disconnect(); } } } } }
0c2215ba8c046e6af6b5ad11b4c12202b95861fb
C#
thomasvt/glyphedit
/GlyphEdit/GlyphEdit.Model/Manipulation/DocumentManipulationScope.cs
2.890625
3
using System; namespace GlyphEdit.Model.Manipulation { /// <summary> /// Scope wihtin document changes (will) form a single reversable operation on the undo stack. /// </summary> public class DocumentManipulationScope { private readonly DocumentManipulator _documentManipulator; private readonly Document _document; private readonly RestorePoint _restorePoint; internal DocumentManipulationScope(DocumentManipulator documentManipulator, Document document) { _documentManipulator = documentManipulator; _document = document; _restorePoint = new RestorePoint(); } public LayerEditAccess GetLayerEditAccess(Guid layerId) { var layer = _document.GetLayer(layerId); if (!_restorePoint.HasPreviousStateFor(layerId)) _restorePoint.StorePreviousState(layer); return new LayerEditAccess(layer); } public void Commit() { foreach (var layerId in _restorePoint.GetAllPreviousStateLayerIds()) { _restorePoint.StoreNewState(_document.GetLayer(layerId)); } // add a restorepoint, for the currently committed changes. _documentManipulator.AddRestorePoint(_restorePoint); } /// <summary> /// Undoes all changes done in this editscope. You may continue to use the scope after this, and draw something else. /// </summary> public void Revert() { _restorePoint.Undo(_document); _restorePoint.Clear(); } } }
4708dcfe335887cd587f013b3a0aacfcf11eff4a
C#
Mateusz-Peplinski/Loqui
/src/design/Design.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace Loqui { class Design { /// <summary> /// This Function is called to invert the colour of contorls and set background image based on "bool darkMode"; /// </summary> public void ChangeDisplayMode(Form form, bool darkMode, string lightModeBackground, string darkModeBackground) { if (darkMode) { // Set image to dark version Image backgroundImage = new Bitmap(darkModeBackground); form.BackgroundImage = backgroundImage; // goes through all control items and inverts them foreach (Control item in form.Controls) { if (item.BackColor != Color.Transparent) { item.BackColor = Color.Black; } item.ForeColor = Color.White; } } else { // Set image to light version Image backgroundImage = new Bitmap(lightModeBackground); form.BackgroundImage = backgroundImage; // goes through all control items and inverts them foreach (Control item in form.Controls) { if (item.BackColor != Color.Transparent) { item.BackColor = Color.White; } item.ForeColor = Color.Black; } } } // This function contorls colour mode public void ButtonColour(Button button, bool onLeave, bool checkedDarkMode) { // If checkbox clicked dark mode begins if (checkedDarkMode) { // If mouse hovers over button change if (!onLeave) { button.BackColor = Color.FromArgb(80, 80, 80); } if (onLeave) { button.BackColor = Color.Black; } } } } }
1944422268a1fc44bb7072015171c2b29a89b13a
C#
ZurabKV/SnakeProject
/ConsoleApp7/CreaturesFolder/Snake.cs
2.8125
3
using ConsoleApp7.CreaturesFolder; using ConsoleApp7.Entities; using ConsoleApp7.UserInterface; using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp7 { class Snake : Creature, IMovable { public static int score = 0; public static int stepsMade = 0; public override char shape => 'O'; public override ConsoleColor CreatureColor => ConsoleColor.Magenta; public static void IfWasKilled(ref Snake snake, ref Food food, ref Enemy enemy) { bool SnakeTouchedWall = snake.x == 0 || snake.y == 0 || snake.x == PlayGround.width - 1 || snake.y == PlayGround.hight - 1; bool SnakeTouchedEnemy = snake.x == enemy.x && snake.y == enemy.y; if (SnakeTouchedEnemy||SnakeTouchedWall) { ExecutePostDeathAction(ref snake, ref food, ref enemy); } } public void Move(ConsoleKeyInfo key) { switch (key.Key) { case ConsoleKey.LeftArrow: x--; break; case ConsoleKey.RightArrow: x++; break; case ConsoleKey.UpArrow: y--; break; case ConsoleKey.DownArrow: y++; break; } stepsMade++; } public static void ExecutePostDeathAction(ref Snake snake, ref Food food, ref Enemy enemy) { snake = new Snake(); food = new Food(); enemy = new Enemy(); UI.gameover.Print(); Console.ReadKey(); score = 0; stepsMade = 0; } } }
d2488998f6219ba0a56cbe783bc3d56b48f852be
C#
mfloriani/sfas21
/Assets/Scripts/FiniteStateMachine.cs
2.625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FiniteStateMachine { private FSMState _currentState; public FiniteStateMachine() { } public void Start(FSMState initialState) { ChangeState(initialState); } public void Update() { _currentState.Update(); } public void ChangeState(FSMState newState) { if(_currentState != null) _currentState.Exit(); _currentState = newState; _currentState.Enter(); } public System.Type GetCurrentStateType() { return _currentState.GetType(); } }
86ecd5479de102a5945c469f39c278953045b4c7
C#
horikuss20/Apprentice
/Scripts/WaterTrigger.cs
2.75
3
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(BoxCollider))] public class WaterTrigger : MonoBehaviour { //BoxCollider for the water GameObject BoxCollider boxCollider; //CharacterController for the character CharacterController controller; //Vector for the top and right side of the collider Vector3 boundsMax; //Vector for the bottom and left side of the collider Vector3 boundsMin; //Vector for the player's position once in the trigger Vector3 playerPos; //The vector to offset the player's position once in the trigger Vector3 offset; //The length of the dolphin to push into the water float dolphinLengthOffset; private void Awake() { //Find the BoxCollider of the dolphin to know how much to offset the position //bounds.extents gets half the size of the Bounds, so multiply it by 2 to get the //true length of the dolphin dolphinLengthOffset = GameObject.Find("DolphinFunctionality"). GetComponent<BoxCollider>().bounds.extents.z * 2; //Find the CharacterController in order to move the player controller = GameObject.Find("PlayerFunctionality"). GetComponent<CharacterController>(); } void Start() { //Get the BoxCollider from the GameObject and set the max and min //bounds in world space boxCollider = GetComponent<BoxCollider>(); boundsMax = boxCollider.bounds.max; boundsMin = boxCollider.bounds.min; } private void OnTriggerEnter(Collider other) { ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Set playerPos, determine what side the player enters the trigger from, // // set the offset depending on what side the player enters the trigger, and // // use controller to move the player completely into the water // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// if (other.tag == "Player") { //Set playerPos playerPos = other.transform.position; //if the player enters the trigger from the top if (playerPos.y >= boundsMax.y) { //set the offset's y to the top part of the trigger, adding the dolphin's length offset = new Vector3(playerPos.x, boundsMax.y + dolphinLengthOffset, playerPos.z); //move the player based on the offset calculated controller.Move(playerPos - offset); //since the player is entering from the top, rotate it to look down other.transform.rotation = Quaternion.LookRotation(Vector3.down); } //if the player enters the trigger from the bottom if (playerPos.y <= boundsMin.y) { //set the offset's y to the bottom part of the trigger, subtracting the dolphin's length offset = new Vector3(playerPos.x, boundsMin.y - dolphinLengthOffset, playerPos.z); //move the player based on the offset calculated controller.Move(playerPos - offset); //since the player is entering from the bottom, rotate it to look up other.transform.rotation = Quaternion.LookRotation(Vector3.up); } //if the player enters the trigger from the left if (playerPos.x <= boundsMin.x) { //set the offset's x to the left part of the trigger, subtracting the dolphin's length offset = new Vector3(boundsMin.x - dolphinLengthOffset, playerPos.y, playerPos.z); //move the player based on the offset calculated controller.Move(playerPos - offset); } //if the player enters the trigger from the right if (playerPos.x >= boundsMax.x) { //set the offset's x to the right part of the trigger, adding the dolphin's length offset = new Vector3(boundsMax.x + dolphinLengthOffset, playerPos.y, playerPos.z); //move the player based on the offset calculated controller.Move(playerPos - offset); } } } }
4c6a399ae742865fecec5dc6f2e5064dcd15f65f
C#
Merchello/Merchello
/src/Merchello.Core/Gateways/GatewayProviderBase.cs
2.59375
3
namespace Merchello.Core.Gateways { using System; using System.Collections.Generic; using Models; using Services; using Umbraco.Core; using Umbraco.Core.Cache; /// <summary> /// Defines the GatewayBase /// </summary> public abstract class GatewayProviderBase : IProvider { #region Fields /// <summary> /// The gateway provider settings. /// </summary> private readonly IGatewayProviderSettings _gatewayProviderSettings; /// <summary> /// The gateway provider service. /// </summary> private readonly IGatewayProviderService _gatewayProviderService; /// <summary> /// The runtime cache. /// </summary> private readonly IRuntimeCacheProvider _runtimeCache; #endregion /// <summary> /// Initializes a new instance of the <see cref="GatewayProviderBase"/> class. /// </summary> /// <param name="gatewayProviderService">The <see cref="IGatewayProviderService"/></param> /// <param name="gatewayProviderSettings">The <see cref="IGatewayProviderSettings"/></param> /// <param name="runtimeCacheProvider">Umbraco's <see cref="IRuntimeCacheProvider"/></param> protected GatewayProviderBase(IGatewayProviderService gatewayProviderService, IGatewayProviderSettings gatewayProviderSettings, IRuntimeCacheProvider runtimeCacheProvider) { Mandate.ParameterNotNull(gatewayProviderService, "gatewayProviderService"); Mandate.ParameterNotNull(gatewayProviderSettings, "gatewayProvider"); Mandate.ParameterNotNull(runtimeCacheProvider, "runtimeCacheProvider"); _gatewayProviderService = gatewayProviderService; _gatewayProviderSettings = gatewayProviderSettings; _runtimeCache = runtimeCacheProvider; } /// <summary> /// Gets the unique Key that will be used /// </summary> public Guid Key { get { return _gatewayProviderSettings.Key; } } /// <summary> /// Gets the <see cref="IGatewayProviderService"/> /// </summary> public IGatewayProviderService GatewayProviderService { get { return _gatewayProviderService; } } /// <summary> /// Gets the <see cref="IGatewayProviderSettings"/> /// </summary> public virtual IGatewayProviderSettings GatewayProviderSettings { get { return _gatewayProviderSettings; } } /// <summary> /// Gets the ExtendedData collection from the <see cref="IGatewayProviderSettings"/> /// </summary> public virtual ExtendedDataCollection ExtendedData { get { return _gatewayProviderSettings.ExtendedData; } } /// <summary> /// Gets a value indicating whether or not this provider is "activated" /// </summary> public virtual bool Activated { get { return _gatewayProviderSettings.Activated; } } /// <summary> /// Gets the RuntimeCache /// </summary> /// <returns></returns> protected IRuntimeCacheProvider RuntimeCache { get { return _runtimeCache; } } /// <summary> /// Returns a collection of all possible gateway methods associated with this provider /// </summary> /// <returns>A collection of <see cref="IGatewayResource"/></returns> public abstract IEnumerable<IGatewayResource> ListResourcesOffered(); } }
bd7f443db2367038f904b6e8cf563769e9bb4c1f
C#
Sigf/GameJam_1-31
/src/Assets/Scripts/Controllers/enemyStats.cs
2.625
3
using UnityEngine; using System.Collections; public class enemyStats : MonoBehaviour { public Ability _ability; public float hp; public bool isInvulnerable; private SpriteRenderer _sr; private bool onHitCD; private float hitCD = 0.1f; private float hitTime = 0.0f; // Use this for initialization void Start () { _sr = gameObject.GetComponent<SpriteRenderer>(); onHitCD = false; } // Update is called once per frame void Update () { if(isInvulnerable){ return; } if(onHitCD){ _sr.color = new Color(1.0f, 0.0f, 0.0f); if(Time.time - hitTime >= hitCD){ onHitCD = false; _sr.color = new Color(1.0f, 1.0f, 1.0f, 1.0f); } } } public void ProcessHit(Ability hit){ if(isInvulnerable){ return; } Debug.Log ("Hit by " + hit.GetType() + " and took " + hit.getDamage() + " Damage"); if(!onHitCD){ hp -= hit.getDamage (); onHitCD = true; hitTime = Time.time; if(hp <= 0){ Destroy (gameObject); } } } }
1c71bc4bf978258ad19f05535576a433008cfbea
C#
eleon88/csharp-workbook
/01Week/1.1/1.1/Program.cs
3.71875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1._1 { class Program { static void Main(string[] args) { Console.WriteLine("Enter a number"); int number1 = int.Parse(Console.ReadLine()); Console.WriteLine("Enter a second number"); int number2 = int.Parse(Console.ReadLine()); int result = number1 + number2; Console.WriteLine("\n The result is " + result); Console.WriteLine("\n please enter a number in yards to convert into inches"); int yards = int.Parse(Console.ReadLine()); int inches = yards * 36; Console.WriteLine("\n" + yards + " yards = " + inches + " inches"); bool people = true; bool f = false; decimal num = 13; Console.WriteLine("\n People = " + people + " f = " + f + " num = " + num * num); Console.ReadLine(); } } }
b7f30ffb77fee95d1192358dee15581ce3e1c7af
C#
polykhel/BizPerms
/G4.BizPermit.Dal/QuarterData.cs
2.578125
3
using G4.BizPermit.Entities; using System; using System.Collections.Generic; using System.Linq; namespace G4.BizPermit.Dal { public class QuarterData { public static List<Quarter> ListAll() { using (DB context = new DB()) { return context.Quarters.ToList(); } } public static bool Add(Quarter obj) { using (DB context = new DB()) { obj.CreatedDate = DateTime.Now; context.Quarters.Add(obj); try { context.SaveChanges(); } catch { return false; } return true; } } public static bool Delete(int id) { using (DB context = new DB()) { Quarter obj = context.Quarters.Where(o => o.Id == id).SingleOrDefault(); context.Quarters.Remove(obj); try { context.SaveChanges(); } catch { return false; } return true; } } public static bool Edit(Quarter obj) { using (DB context = new DB()) { Quarter _obj = context.Quarters.Where(o => o.Id == obj.Id).SingleOrDefault(); _obj.Name = obj.Name; _obj.IsActive = obj.IsActive; _obj.CreatedBy = obj.CreatedBy; try { context.SaveChanges(); } catch { return false; } return true; } } public static Quarter GetById(int id) { using (DB context = new DB()) { Quarter obj = context.Quarters.Where(o => o.Id == id).SingleOrDefault(); return obj; } } } }
769b8f32f1ae345d438571bc2fc47067eb84ad93
C#
sakapon/AtCoder-Contests
/CSharp/PAST/PAST202005/H.cs
3.234375
3
using System; using System.Linq; class H { static int[] Read() => Console.ReadLine().Split().Select(int.Parse).ToArray(); static void Main() { var h = Read(); int n = h[0], l = h[1]; var x = Read().ToHashSet(); var t = Read(); var dp = Enumerable.Repeat(1 << 30, l).Prepend(0).ToArray(); for (int i = 0; i < l; i++) { if (dp[i] == 1 << 30) continue; if (x.Contains(i)) dp[i] += t[2]; dp[i + 1] = Math.Min(dp[i + 1], dp[i] + t[0]); if (i + 2 <= l) dp[i + 2] = Math.Min(dp[i + 2], dp[i] + t[0] + t[1]); else dp[l] = Math.Min(dp[l], dp[i] + (t[0] + t[1]) / 2); if (i + 4 <= l) dp[i + 4] = Math.Min(dp[i + 4], dp[i] + t[0] + 3 * t[1]); else dp[l] = Math.Min(dp[l], dp[i] + (t[0] + t[1]) / 2 + (l - i - 1) * t[1]); } Console.WriteLine(dp[l]); } }
5bb56ae6b1fabbd08427617b15679f857897a609
C#
Svengali/legba_old
/src/libs/Entity/Entity.cs
2.53125
3
using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis; using System.Diagnostics.Tracing; using lib.Net; using Validation; namespace ent { public enum EntityId : ulong { Invalid = 0, } /* public partial class ComHealth : Component { public float Health => m_health; } public partial class Entity { private int m_testVal = 10; public int TestVal => m_testVal; public Optional<T> Com<T>() where T : class { var name = typeof(T).Name; Component com = null; var hasCom = m_coms.TryGetValue( name, out com ); return com as T; } Optional<T> IEntity.Com<T>() { Requires.ValidState( typeof(T).IsInterface, $"{typeof(T).Name} must be an interface" ); var comOpt = Com<T>(); var com = comOpt.Value; return com; } public Entity MutCom<T>(Func<T> fn) where T : Component { var name = typeof(T).Name; Component com = null; var hasCom = m_coms.TryGetValue( name, out com ); if( hasCom ) { var newCom = fn(); var newComs = m_coms.SetItem( name, newCom ); return with( comsOpt: newComs ); } else { // TODO LOG return this; } } */ public partial class Component<T> { } public partial class ComponentWithCfg<T, TCFG> : Component<T> { } } namespace mmo { public enum Com { Invalid, Physical, Health, Connection, } public class ComponentWithCfg<TCFG> : ent.ComponentWithCfg<Com, TCFG> { } public class ComHealthCfg : lib.Config { } public class ComHealth : ComponentWithCfg<ComHealthCfg> { } public class Entity : ent.Entity<Com> { } } public class Amazing { } // Interesting. But not totally sure its necessary public partial class Mut<T> { private T t; public Mut(ref T newT) { t = newT; } public void mut(Func<T> fn) { t = fn(); } }
bf7c440e3b50a1205feb31a6ebb84b3b4ba4604c
C#
SJDavies2020/Review_11_12_2018
/Review_1/Form1.cs
2.71875
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 Review_1 { public partial class frmReview : Form { Double MyResult = 0; public frmReview() { InitializeComponent(); } private void btnCalc_Click(object sender, EventArgs e) { MyResult = (Convert.ToDouble(txtVal1.Text) + Convert.ToDouble(txtVal2.Text)) / 2; lblResult.Text = Convert.ToString(MyResult); } } }
e3fe7f489388ee03452312feb1a9959e1122a372
C#
gabsot22/beverage-collection-key
/cis237-assignment1/Program.cs
3.34375
3
// Author: David Barnes // Class: CIS 237 // Assignment: 1 using System; namespace cis237_assignment1 { class Program { static void Main(string[] args) { // Set Console Window Size Console.BufferHeight = Int16.MaxValue - 1; Console.WindowHeight = 40; Console.WindowWidth = 120; // Set a constant for the size of the collection const int beverageCollectionSize = 4000; // Set a constant for the path to the CSV File const string pathToCSVFile = "../../../datafiles/beverage_list.csv"; // Create an instance of the UserInterface class UserInterface userInterface = new UserInterface(); // Create an instance of the BeverageCollection class BeverageCollection beverageCollection = new BeverageCollection(beverageCollectionSize); // Create an instance of the CSVProcessor class CSVProcessor csvProcessor = new CSVProcessor(); // Display the Welcome Message to the user userInterface.DisplayWelcomeGreeting(); // Display the Menu and get the response. Store the response in the choice integer // This is the 'primer' run of displaying and getting. int choice = userInterface.DisplayMenuAndGetResponse(); // While the choice is not exit program while (choice != 5) { switch (choice) { case 1: // Load the CSV File bool success = csvProcessor.ImportCSV(beverageCollection, pathToCSVFile); if (success) { // Display Success Message userInterface.DisplayImportSuccess(); } else { // Display Fail Message userInterface.DisplayImportError(); } break; case 2: // Print Entire List Of Items string allItemsString = beverageCollection.ToString(); if (!String.IsNullOrWhiteSpace(allItemsString)) { // Display all of the items userInterface.DisplayAllItems(allItemsString); } else { // Display error message for all items userInterface.DisplayAllItemsError(); } break; case 3: // Search For An Item string searchQuery = userInterface.GetSearchQuery(); string itemInformation = beverageCollection.FindById(searchQuery); if (itemInformation != null) { userInterface.DisplayItemFound(itemInformation); } else { userInterface.DisplayItemFoundError(); } break; case 4: // Add A New Item To The List string[] newItemInformation = userInterface.GetNewItemInformation(); if (beverageCollection.FindById(newItemInformation[0]) == null) { beverageCollection.AddNewItem( newItemInformation[0], newItemInformation[1], newItemInformation[2], decimal.Parse(newItemInformation[3]), (newItemInformation[4] == "True") ); userInterface.DisplayAddWineItemSuccess(); } else { userInterface.DisplayItemAlreadyExistsError(); } break; } // Get the new choice of what to do from the user choice = userInterface.DisplayMenuAndGetResponse(); } } } }
32c9241f67762ca2221b5d8fcffffc28566c01d7
C#
VincentH-Net/QuickCross
/Examples/CloudAuction/CloudAuction.ws/QuickCross/Templates/_APPNAME_Navigator.cs
2.53125
3
#if TEMPLATE // To add a navigator class: in the Visual Studio Package Manager Console (menu View | Other Windows), enter "Install-Mvvm". Alternatively: copy this file, then in the copy remove the enclosing #if TEMPLATE ... #endif lines and replace CloudAuction with the application name. using System; using Windows.UI.Xaml.Controls; using CloudAuction.Shared; namespace CloudAuction { class CloudAuctionNavigator : ICloudAuctionNavigator { private static readonly Lazy<CloudAuctionNavigator> lazy = new Lazy<CloudAuctionNavigator>(() => new CloudAuctionNavigator()); public static CloudAuctionNavigator Instance { get { return lazy.Value; } } private CloudAuctionNavigator() { } public Frame NavigationContext { get; set; } private void Navigate(Type sourcePageType) { if (NavigationContext == null || NavigationContext.CurrentSourcePageType == sourcePageType) return; NavigationContext.Navigate(sourcePageType); } /* TODO: For each view, add a method to navigate to that view like this: public void NavigateTo_VIEWNAME_View() { Navigate(typeof(_VIEWNAME_View)); } * Note that the New-View command adds the above code automatically (see http://github.com/MacawNL/QuickCross#new-view). */ } } #endif // TEMPLATE
8ceba1285e28e4c680aa2472d7d23b41090d1372
C#
retinio/eav-model
/src/EVA.Infrastructure.Data/Repositories/Repository.cs
2.734375
3
using System; using System.Threading.Tasks; using EVA.Domain.Abstractions; using EVA.Domain.Abstractions.Entity; using EVA.Infrastructure.Data.Context; using Microsoft.EntityFrameworkCore; namespace EVA.Infrastructure.Data.Repositories { public abstract class Repository<T> : IRepository<T> where T : DomainEntity, IAggregate { protected EvaContext Context { get; private set; } protected Repository(EvaContext context) { Context = context ?? throw new ArgumentNullException(nameof(context)); } public virtual async Task<T> AddAsync(T aggregate) { var dbEntityEntry = await Context.Set<T>() .AddAsync(aggregate); return dbEntityEntry.Entity; } public virtual async Task<T> UpdateAsync(T aggregate) { aggregate.ModifiedDateTime = DateTimeOffset.UtcNow; var dbEntityEntry = Context.Entry(aggregate); dbEntityEntry.State = EntityState.Modified; return dbEntityEntry.Entity; } public virtual async Task<bool> DeleteAsync(T aggregate) { Context.Set<T>().Remove(aggregate); return true; } } }
00979f0a8744b5dddc34b4d12ece73cd159a9bb2
C#
dmytrokulak/Epok
/sw/tests/Epok.Integration.Tests/TestHelper.cs
2.6875
3
using System; using System.Linq; namespace Epok.Integration.Tests { internal static class TestHelper { internal static T RandomEnumValue<T>(T excluding, bool includeDefault = false) where T : Enum { return Enum.GetValues(typeof(T)).OfType<T>() .First(v => (includeDefault || Convert.ToInt32(v) != 0) && !v.Equals(excluding)); } } }
bd5bc39b66a3df21cda27aebfe6f48ab396799d0
C#
HHUBBSolucionessss/HSFit
/GYM/Formularios/Usuarios/frmUsuarios.cs
2.515625
3
using System; using System.Data; using System.Windows.Forms; namespace GYM.Formularios { public partial class frmUsuarios : Form { string id; #region Instancia private static frmUsuarios frmInstancia; public static frmUsuarios Instancia { get { if (frmInstancia == null) frmInstancia = new frmUsuarios(); else if (frmInstancia.IsDisposed) frmInstancia = new frmUsuarios(); return frmInstancia; } set { frmInstancia = value; } } #endregion public frmUsuarios() { InitializeComponent(); } public void CargarUsuarios() { dgvUsuarios.Rows.Clear(); string sql = "SELECT * FROM usuarios WHERE eliminado=0 ORDER BY nivel DESC"; DataTable dt = Clases.ConexionBD.EjecutarConsultaSelect(sql); foreach (DataRow dr in dt.Rows) { int nivel = Convert.ToInt32(dr["nivel"]); string niv; if (nivel == 3) niv = "Administrador"; else if (nivel == 2) niv = "Encargado"; else niv = "Asistente"; dgvUsuarios.Rows.Add(new object[] { dr["id"], dr["userName"], niv }); } } private void EliminarUsuario(string id) { string sql = "UPDATE usuarios SET eliminado=1 WHERE id='" + id + "'"; Clases.ConexionBD.EjecutarConsultaSelect(sql); dgvUsuarios.Rows.RemoveAt(dgvUsuarios.CurrentRow.Index); } private void frmUsuarios_Load(object sender, EventArgs e) { CargarUsuarios(); } private void btnNuevo_Click(object sender, EventArgs e) { (new frmNuevoUsuario(this)).ShowDialog(this); } private void btnEditar_Click(object sender, EventArgs e) { (new frmEditarUsuario(this, id)).ShowDialog(this); } private void btnEliminar_Click(object sender, EventArgs e) { if (dgvUsuarios.CurrentRow != null) { if (frmMain.id.ToString() != id) { EliminarUsuario(id); } } } private void dgvUsuarios_RowEnter(object sender, DataGridViewCellEventArgs e) { try { id = dgvUsuarios[0, e.RowIndex].Value.ToString(); } catch { } } } }
c165ec189506a262bdaf2c17e7100fbc0a1f7525
C#
BorianKrustev/School
/2 Programming Fundamentals/Homework/5-Arrays/Homework/3.FoldAndSum/Program.cs
3.515625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _3.FoldAndSum { class Program { static void Main(string[] args) { int[] arr = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); int a = arr.Length / 4; int[] left = arr.Take(a).ToArray(); int[] mid = arr.Skip(a).Take(a * 2).ToArray(); int[] right = arr.Skip(a * 3).ToArray(); Array.Reverse(left); Array.Reverse(right); List<int> midAndLeftList = new List<int>(); midAndLeftList.AddRange(left); midAndLeftList.AddRange(right); int[] leftAndRigt = midAndLeftList.ToArray(); int[] arrToPrint = new int[mid.Length]; for (int i = 0; i < mid.Length; i++) { arrToPrint[i] = leftAndRigt[i] + mid[i]; } Console.WriteLine($"{string.Join(" ", arrToPrint)}"); //int[] arr = Console.ReadLine() // .Split(' ') // .Select(int.Parse) // .ToArray(); // //int skip = arr.Length / 4; //int[] left = new int[skip]; //int[] mid = new int[skip * 2]; //int[] right = new int[skip]; // //for (int i = 0; i < left.Length; i++) //{ // left[i] = arr[i]; //} //for (int i = skip; i < arr.Length - skip; i++) //{ // mid[i - skip] = arr[i]; //} //for (int i = arr.Length - 1; i >= skip * 3; i--) //{ // right[i - skip * 3] = arr[i]; //} // //int[] leftAndRigt = new int[skip * 2]; // //Array.Reverse(left); //Array.Reverse(right); //for (int i = 0; i < left.Length; i++) //{ // leftAndRigt[i] = left[i]; //} //for (int i = 0; i < right.Length; i++) //{ // leftAndRigt[i + skip] = right[i]; //} // //for (int i = 0; i < mid.Length; i++) //{ // mid[i] += leftAndRigt[i]; //} // //Console.WriteLine($"{string.Join(" ", mid)}"); } } }
0983e653abc7dc47f80fa5ce16b6c64e221bf402
C#
Kuinran/CS-inventory-project
/CS project/SQL_Instructions.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using MySql.Data; using MySql.Data.MySqlClient; namespace CS_project { static class SQL_Instructions { public static MySql.Data.MySqlClient.MySqlConnection SQL_Connect(String serverLoc, String username, String dbname, String port, String password) { MySql.Data.MySqlClient.MySqlConnection conn = null; string connstr = String.Format("server={0};user={1};database={2};port={3};password={4}", serverLoc, username, dbname, port, password); try { conn = new MySql.Data.MySqlClient.MySqlConnection(connstr); conn.Open(); } catch (MySql.Data.MySqlClient.MySqlException ex) { Debug.Write(ex); return null; } return conn; } public static void SQL_Disconnect(MySql.Data.MySqlClient.MySqlConnection conn) { conn.Close(); } } }
cce9a87e7045ebb9eb37af243f6f3f63ec530e29
C#
klosejay/Gisoft.Map
/OpenSourceProjects/Gisoft.NetTopologySuite/Algorithm/RayCrossingCounter.cs
3.25
3
using Gisoft.GeoAPI.Geometries; namespace Gisoft.NetTopologySuite.Algorithm { ///<summary> /// Counts the number of segments crossed by a horizontal ray extending to the right /// from a given point, in an incremental fashion. /// <para>This can be used to determine whether a point lies in a <see cref="IPolygonal"/> geometry.</para> /// <para>The class determines the situation where the point lies exactly on a segment.</para> /// <para>When being used for Point-In-Polygon determination, this case allows short-circuiting the evaluation.</para> /// </summary> /// <remarks> /// This class handles polygonal geometries with any number of shells and holes. /// The orientation of the shell and hole rings is unimportant. /// In order to compute a correct location for a given polygonal geometry, /// it is essential that <b>all</b> segments are counted which /// <list type="Bullet"> /// <item>touch the ray</item> /// <item>lie in in any ring which may contain the point</item> /// </list> /// <para> /// The only exception is when the point-on-segment situation is detected, in which /// case no further processing is required. /// The implication of the above rule is that segments which can be a priori determined to <i>not</i> touch the ray /// (i.e. by a test of their bounding box or Y-extent) do not need to be counted. This allows for optimization by indexing. /// </para> /// <para> /// This implementation uses the extended-precision orientation test, /// to provide maximum robustness and consistency within /// other algorithms. /// </para> /// </remarks> /// <author>Martin Davis</author> public class RayCrossingCounter { ///<summary> /// Determines the <see cref="Gisoft.GeoAPI.Geometries.Location"/> of a point in a ring. /// This method is an exemplar of how to use this class. ///</summary> /// <param name="p">The point to test</param> /// <param name="ring">An array of Coordinates forming a ring</param> /// <returns>The location of the point in the ring</returns> public static Location LocatePointInRing(Coordinate p, Coordinate[] ring) { var counter = new RayCrossingCounter(p); for (int i = 1; i < ring.Length; i++) { var p1 = ring[i]; var p2 = ring[i - 1]; counter.CountSegment(p1, p2); if (counter.IsOnSegment) return counter.Location; } return counter.Location; } /// <summary> /// Determines the <see cref="Gisoft.GeoAPI.Geometries.Location"/> of a point in a ring. /// </summary> /// <param name="p">The point to test</param> /// <param name="ring">A coordinate sequence forming a ring</param> /// <returns>The location of the point in the ring</returns> public static Location LocatePointInRing(Coordinate p, ICoordinateSequence ring) { var counter = new RayCrossingCounter(p); var p1 = new Coordinate(); var p2 = new Coordinate(); int count = ring.Count; for (var i = 1; i < count; i++) { ring.GetCoordinate(i, p1); ring.GetCoordinate(i - 1, p2); counter.CountSegment(p1, p2); if (counter.IsOnSegment) return counter.Location; } return counter.Location; } private readonly Coordinate _p; private int _crossingCount; // true if the test point lies on an input segment private bool _isPointOnSegment; public RayCrossingCounter(Coordinate p) { _p = p; } ///<summary> /// Counts a segment ///</summary> /// <param name="p1">An endpoint of the segment</param> /// <param name="p2">Another endpoint of the segment</param> public void CountSegment(Coordinate p1, Coordinate p2) { /* * For each segment, check if it crosses * a horizontal ray running from the test point in the positive x direction. */ // check if the segment is strictly to the left of the test point if (p1.X < _p.X && p2.X < _p.X) return; // check if the point is equal to the current ring vertex if (_p.X == p2.X && _p.Y == p2.Y) { _isPointOnSegment = true; return; } /* * For horizontal segments, check if the point is on the segment. * Otherwise, horizontal segments are not counted. */ if (p1.Y == _p.Y && p2.Y == _p.Y) { double minx = p1.X; double maxx = p2.X; if (minx > maxx) { minx = p2.X; maxx = p1.X; } if (_p.X >= minx && _p.X <= maxx) { _isPointOnSegment = true; } return; } /* * Evaluate all non-horizontal segments which cross a horizontal ray to the * right of the test pt. To avoid double-counting shared vertices, we use the * convention that * <ul> * <li>an upward edge includes its starting endpoint, and excludes its * final endpoint * <li>a downward edge excludes its starting endpoint, and includes its * final endpoint * </ul> */ if (((p1.Y > _p.Y) && (p2.Y <= _p.Y)) || ((p2.Y > _p.Y) && (p1.Y <= _p.Y))) { var orient = Orientation.Index(p1, p2, _p); if (orient == OrientationIndex.Collinear) { _isPointOnSegment = true; return; } // Re-orient the result if needed to ensure effective segment direction is upwards if (p2.Y < p1.Y) { orient = Orientation.ReOrient(orient); } // The upward segment crosses the ray if the test point lies to the left (CCW) of the segment. if (orient == OrientationIndex.Left) { _crossingCount++; } } } ///<summary> /// Reports whether the point lies exactly on one of the supplied segments. /// </summary> /// <remarks> /// This method may be called at any time as segments are processed. If the result of this method is <c>true</c>, /// no further segments need be supplied, since the result will never change again. /// </remarks> public bool IsOnSegment { get { return _isPointOnSegment; } } /// <summary> /// Gets the <see cref="Gisoft.GeoAPI.Geometries.Location"/> of the point relative to the ring, polygon /// or multipolygon from which the processed segments were provided. /// </summary> /// <remarks> /// This property only determines the correct location /// if <b>all</b> relevant segments have been processed. /// </remarks> public Location Location { get { if (_isPointOnSegment) return Location.Boundary; // The point is in the interior of the ring if the number of X-crossings is // odd. if ((_crossingCount%2) == 1) { return Location.Interior; } return Location.Exterior; } } /// <summary> /// Tests whether the point lies in or on /// the ring, polygon or multipolygon from which the processed /// segments were provided. /// </summary> /// <remarks> /// This property only determines the correct location /// if <b>all</b> relevant segments have been processed /// </remarks> public bool IsPointInPolygon { get { return Location != Location.Exterior; } } } }
2be5ff89efecec8376bd2cab1b38ce5e21bc5fb2
C#
ufcpp/UfcppSample
/Chapters/Resource/ByRef/RefReassignment/RefReassingmentMax.cs
3.5
4
namespace ByRef.RefReassignment.RefReassingmentMax { using System; class Program { static ref int RefMaxOld(int[] array) { if (array.Length == 0) throw new InvalidOperationException(); // これまでこんな感じでインデックスで持って、 var maxIndex = 0; for (int i = 1; i < array.Length; i++) { // 毎度毎度、配列のインデックス アクセスするようなコードを書くことがたまに。 if (array[maxIndex] < array[i]) { array[maxIndex] = array[i]; maxIndex = i; } } return ref array[maxIndex]; } static ref int RefMax(int[] array) { if (array.Length == 0) throw new InvalidOperationException(); // それを、こんな風に参照ローカル変数に変えて、 ref var max = ref array[0]; for (int i = 1; i < array.Length; i++) { // ref 再代入で済ませるように。 ref var x = ref array[i]; if (max < x) max = ref x; } return ref max; } } }
606d1e59f24a94ea0cbf0effddb9c84c1186b582
C#
mustafasariel/EFDemoSabahSabah
/Demo5/EF/Mapping/CustomerMapping.cs
2.53125
3
using Demo5.Entity; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Demo5.EF.Mapping { public class CustomerMapping:EntityTypeConfiguration<Customer> { public CustomerMapping() { this.HasKey(t => t.CustomerId); this.Property(t => t.CustomerName).HasMaxLength(30).IsUnicode(false).HasColumnName("CustomerName"); this.Property(t => t.CustomerLastname).HasMaxLength(30).IsUnicode(false).HasColumnName("CustomerLastName"); this.ToTable("msa.Customers"); } } }
7c2d4bc0dc85c3439cf4c3ff519e6f5e99128161
C#
willschipp/simple-db-rest-api-dotnet
/simple-db-rest-api/Controllers/TodoController.cs
2.75
3
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using System.Linq; using TodoApi.Models; namespace TodoApi.Controllers { [Route("api/[controller]")] public class TodoController : Controller { private readonly TodoContext _context; public TodoController(TodoContext context) { _context = context; if (_context.TodoItems.Count() == 0) { _context.TodoItems.Add(new TodoItem { Name = "Item1" }); _context.SaveChanges(); } } [HttpGet] public IEnumerable<TodoItem> GetAll() { return _context.TodoItems.ToList(); } } }
69a968817f4db0b72a1744f96bd003a328a9fdb8
C#
baba-s/UniSequenceTask
/Scripts/ISequenceTask.cs
3.296875
3
using System; using System.Collections; namespace Kogane { /// <summary> /// タスクのインターフェイス /// </summary> public interface ISequenceTask : IEnumerable { /// <summary> /// タスクを追加します /// </summary> void Add( string text, Action<Action> task ); /// <summary> /// タスクを実行します /// </summary> void Play( string text, Action onCompleted ); } /// <summary> /// ISequenceTask 型の拡張メソッドを管理するクラス /// </summary> public static class ISequenceTaskExt { /// <summary> /// タスクを追加します /// </summary> public static void Add( this ISequenceTask self, Action<Action> task ) { self.Add( string.Empty, task ); } /// <summary> /// タスクを実行します /// </summary> public static void Play( this ISequenceTask self ) { self.Play( onCompleted: null ); } /// <summary> /// タスクを実行します /// </summary> public static void Play( this ISequenceTask self, Action onCompleted ) { self.Play( string.Empty, onCompleted ); } /// <summary> /// タスクを実行します /// </summary> public static void Play( this ISequenceTask self, string text ) { self.Play( text, null ); } } }
8959cc9a9474a8f43da0ef3acdebea01a00bf397
C#
AllFi/Assistant
/Plugins/MusicPlugin/MusicProviders/MusicProvider.cs
2.625
3
 namespace MusicPlugin.MusicProviders { public abstract class MusicProvider { public abstract string Name { get; } public abstract void TurnOn( string musicRequest ); public abstract void TurnOff(); public abstract void Play(); public abstract void Pause(); public abstract void Next(); public abstract void Previous(); public abstract string WhoIsIt(); public abstract bool IsPlaying(); } }
0d9755e80cebcceb9202c73f084474fd98e3fce8
C#
Sunkatta/My-HW-Projects-At-Uni
/I-st Course/STD1A-LusianManolov-1701681009-H8/AverageNumber/Program.cs
3.9375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AverageNumber { class Program { static void Main(string[] args) { int number; int sum = 0; int br = 0; do { Console.Write("Enter a number between 1 and 255 (when you are ready enter 0):"); number = int.Parse(Console.ReadLine()); if (number % 2 == 0 && number >= 1 && number <= 255) { sum += number; br++; } } while (number != 0); if (sum == 0) { Console.WriteLine("There are no even numbers between 1 and 255!"); } else { Console.WriteLine("The average sum of the even numbers is: " + (double)sum / br) ; } } } }
2f3e88c7cd6b766e14b4e3477d88a90681be39a8
C#
biagianina/JSONClasses
/Range.Tests/OneOrMoreTests.cs
3.015625
3
using System; using Xunit; namespace Classes.Tests { public class OneOrMoreTests { [Fact] public void ReturnsFalseAndEmptyForEmptyString() { var a = new OneOrMore( new Range('0', '9')); Assert.False(a.Match("").Success()); Assert.Equal("", a.Match("").RemainingText()); } [Fact] public void ReturnsTrueAndEmptyForThreeMatchesString() { var a = new OneOrMore( new Range('0', '9')); Assert.True(a.Match("123").Success()); Assert.Equal("", a.Match("123").RemainingText()); } [Fact] public void ReturnsTrueAndRemainingForTwoMatchesString() { var a = new OneOrMore( new Range('0', '9')); Assert.True(a.Match("12a").Success()); Assert.Equal("a", a.Match("12a").RemainingText()); } [Fact] public void ReturnsFalseAndTextForNoMatchesString() { var a = new OneOrMore( new Range('0', '9')); Assert.False(a.Match("bc").Success()); Assert.Equal("bc", a.Match("bc").RemainingText()); } } }
4e758f7e98ff664939d7c8597564e3850f30ecc9
C#
libla/Mapping
/Mapping/MySQL.cs
2.546875
3
using System; using System.Data; using System.Data.Common; using System.Text; using System.Threading; using System.Threading.Tasks; using MySql.Data.MySqlClient; namespace Mapping { public class MySQL : DataSource { private static int total = 0; private readonly string host; private readonly int port; private readonly string username; private readonly string password; private readonly string database; public MySQL(string host, int port, string username, string password, string database) : this( host, port, username, password, database, null) { } public MySQL( string host, int port, string username, string password, string database, Func<Type, string, string> mapping) : base(mapping) { Interlocked.Increment(ref total); this.host = host; this.port = port; this.username = username; this.password = password; this.database = database; } protected override void Dispose(bool disposing) { if (Interlocked.Decrement(ref total) == 0) MySqlConnection.ClearAllPools(); } protected override async Task<DbConnection> CreateConnection() { MySqlConnection connection = new MySqlConnection(string.Format( "Data Source = {0};Port = {1};Username = {2};Password = \"{3}\";CharSet = utf8mb4;", host, port, username, password.Replace("\"", "\"\""))); if (Token == null) await connection.OpenAsync(); else await connection.OpenAsync(Token.Value); TimeSpan timezone = TimeZoneInfo.Local.BaseUtcOffset; string sql = string.Format("SET time_zone = '{1}:{2:00}';CREATE DATABASE IF NOT EXISTS {0};USE {0};", database, (timezone.Hours >= 0 ? "+" : "") + timezone.Hours.ToString(), Math.Abs(timezone.Minutes)); DataSource.Command command; using (Parameters parameters = CreateParameters()) command = CreateCommand(sql, parameters); if (Token.HasValue) await command.Execute(connection, Token.Value); else await command.Execute(connection); return connection; } protected override void CloseConnection(DbConnection connection) { MySqlConnection mysql = connection as MySqlConnection; if (mysql != null) mysql.CloseAsync(); else connection.Close(); } protected override Parameters CreateParameters() { return new Command(); } protected override DataSource.Command CreateCommand(string sql, Parameters parameters) { Command command = (Command)parameters; command.Retain(); command.command.CommandText = sql; return command; } protected override async Task<bool> IsTableExist(DbConnection connection, DataTable.Define define) { MySqlCommand exist = new MySqlCommand(string.Format( "SELECT count(TABLE_NAME) as result FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}';", database, NameMapping(define)), (MySqlConnection)connection); try { using (var reader = Token == null ? await exist.ExecuteReaderAsync() : await exist.ExecuteReaderAsync(Token.Value)) { if (Token == null ? await reader.ReadAsync() : await reader.ReadAsync(Token.Value)) return reader.GetInt32(0) != 0; return false; } } finally { exist.Dispose(); } } protected override async Task BeginTransaction(DbConnection connection, Isolation level) { string str; switch (level) { case Isolation.Repeatable: str = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;BEGIN;"; break; case Isolation.Lock: str = "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;BEGIN;"; break; default: str = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;BEGIN;"; break; } MySqlCommand command = new MySqlCommand(str, (MySqlConnection)connection); try { if (Token == null) await command.ExecuteNonQueryAsync(); else await command.ExecuteNonQueryAsync(Token.Value); } finally { command.Dispose(); } } protected override async Task CommitTransaction(DbConnection connection) { MySqlCommand command = new MySqlCommand("COMMIT;", (MySqlConnection)connection); try { if (Token == null) await command.ExecuteNonQueryAsync(); else await command.ExecuteNonQueryAsync(Token.Value); } finally { command.Dispose(); } } protected override async Task RollbackTransaction(DbConnection connection) { MySqlCommand command = new MySqlCommand("ROLLBACK;", (MySqlConnection)connection); try { if (Token == null) await command.ExecuteNonQueryAsync(); else await command.ExecuteNonQueryAsync(Token.Value); } finally { command.Dispose(); } } protected override void LimitCount(StringBuilder builder, uint count) { builder.Append(" LIMIT "); builder.Append(count); } protected override void InsertOrUpdate( StringBuilder builder, Parameters parameters, DataTable.Define define, DataTable.Reader reader) { using (Buffer columns = Acquire(), values = Acquire()) { int index = 0; for (int i = 0; i < define.Columns.Count; ++i) { DataTable.Column column = define.Columns[i]; switch (column.type) { case DataTable.Type.Bool: { bool? result = null; if (!reader.Get(i, ref result)) continue; if (index != 0) values.buffer.Append(", "); if (result == null) values.buffer.Append("NULL"); else ToString(result.Value, values.buffer); } break; case DataTable.Type.Int: { int? result = null; if (!reader.Get(i, ref result)) continue; if (index != 0) values.buffer.Append(", "); if (result == null) values.buffer.Append("NULL"); else ToString(result.Value, values.buffer); } break; case DataTable.Type.UInt: { uint? result = null; if (!reader.Get(i, ref result)) continue; if (index != 0) values.buffer.Append(", "); if (result == null) values.buffer.Append("NULL"); else ToString(result.Value, values.buffer); } break; case DataTable.Type.Long: { long? result = null; if (!reader.Get(i, ref result)) continue; if (index != 0) values.buffer.Append(", "); if (result == null) values.buffer.Append("NULL"); else ToString(result.Value, values.buffer); } break; case DataTable.Type.ULong: { ulong? result = null; if (!reader.Get(i, ref result)) continue; if (index != 0) values.buffer.Append(", "); if (result == null) values.buffer.Append("NULL"); else ToString(result.Value, values.buffer); } break; case DataTable.Type.Double: { double? result = null; if (!reader.Get(i, ref result)) continue; if (index != 0) values.buffer.Append(", "); if (result == null) values.buffer.Append("NULL"); else ToString(result.Value, values.buffer); } break; case DataTable.Type.String: { string result = null; if (!reader.Get(i, ref result) || result == null) continue; if (index != 0) values.buffer.Append(", "); if (result == null) values.buffer.Append("NULL"); else ToString(result, values.buffer); } break; case DataTable.Type.DateTime: { DateTime? result = null; if (!reader.Get(i, ref result)) continue; if (index != 0) values.buffer.Append(", "); if (result == null) values.buffer.Append("NULL"); else ToString(result.Value, values.buffer); } break; case DataTable.Type.Bytes: { byte[] result = null; if (!reader.Get(i, ref result) || result == null) continue; if (index != 0) values.buffer.Append(", "); if (result == null) { values.buffer.Append("NULL"); } else { int count = parameters.Count; values.buffer.Append(Placeholder(count)); parameters.Add(count, result); } } break; } if (index != 0) columns.buffer.Append(", "); columns.buffer.Append(EscapeColumn(column)); ++index; } builder.AppendFormat("REPLACE INTO {0} ({1}) VALUES ({2});", EscapeTable(NameMapping(define)), columns.buffer.ToString(), values.buffer.ToString()); } } protected override string ColumnType(DataTable.Column column) { string notnull = column.key ? "" : (column.notnull ? " NOT NULL" : " NULL"); switch (column.type) { case DataTable.Type.Bool: return "tinyint(1)" + notnull; case DataTable.Type.Int: return "int(32)" + notnull; case DataTable.Type.UInt: return "int(32) UNSIGNED" + notnull; case DataTable.Type.Long: return "bigint" + notnull; case DataTable.Type.ULong: return "bigint UNSIGNED" + notnull; case DataTable.Type.Double: return "double" + notnull; case DataTable.Type.String: return (column.key || column.index ? "varchar(255) CHARACTER SET latin1" : "longtext CHARACTER SET utf8mb4") + notnull; case DataTable.Type.DateTime: return "timestamp" + notnull + " DEFAULT CURRENT_TIMESTAMP"; case DataTable.Type.Bytes: return (column.key || column.index ? "varbinary(255)" : "longblob") + notnull; default: throw new ArgumentOutOfRangeException(nameof(column)); } } protected override string EscapeTable(string s) { return '`' + s + '`'; } protected override string EscapeColumn(DataTable.Column column) { return '`' + column.name + '`'; } protected override string Placeholder(int index) { return "?p" + index; } protected override void ToString(bool b, StringBuilder builder) { builder.Append(b ? "1" : "0"); } protected override void ToString(int i, StringBuilder builder) { builder.Append(i); } protected override void ToString(uint u, StringBuilder builder) { builder.Append(u); } protected override void ToString(long l, StringBuilder builder) { builder.Append(l); } protected override void ToString(ulong u, StringBuilder builder) { builder.Append(u); } protected override void ToString(double d, StringBuilder builder) { builder.Append(d); } private static readonly char[] escapes = {'\\', '\''}; protected override void ToString(string s, StringBuilder builder) { builder.Append('\''); int start = 0; while (true) { int index = s.IndexOfAny(escapes, start); if (index < 0) index = s.Length; builder.Append(s, start, index - start); if (index == s.Length) break; builder.Append('\\'); builder.Append(s[index]); start = index + 1; } builder.Append('\''); } protected override void ToString(DateTime d, StringBuilder builder) { if (d.Kind == DateTimeKind.Utc) d = d.ToLocalTime(); builder.AppendFormat("'{0:yyyy-MM-dd HH:mm:ss}.{1:000}'", d, d.Millisecond); } protected override uint? ReadUInt(DbDataReader reader, int index) { if (reader.IsDBNull(index)) return null; return ((MySqlDataReader)reader).GetUInt32(index); } protected override ulong? ReadULong(DbDataReader reader, int index) { if (reader.IsDBNull(index)) return null; return ((MySqlDataReader)reader).GetUInt64(index); } protected override DateTime? ReadDateTime(DbDataReader reader, int index) { if (reader.IsDBNull(index)) return null; DateTime datetime = ((MySqlDataReader)reader).GetDateTime(index); if (datetime.Kind == DateTimeKind.Utc) return datetime.ToLocalTime(); else if (datetime.Kind == DateTimeKind.Local) return datetime; else return datetime.ToUniversalTime().ToLocalTime(); } private new class Command : Parameters, DataSource.Command { public readonly MySqlCommand command; private int refcount; public Command() { command = new MySqlCommand(); refcount = 1; } public void Dispose() { if (Interlocked.Decrement(ref refcount) == 0) command.Dispose(); } public void Retain() { Interlocked.Increment(ref refcount); } public void Add(int index, bool b) { MySqlParameter parameter = new MySqlParameter { DbType = DbType.Int32, Value = b ? 1 : 0, }; command.Parameters["p" + index] = parameter; } public void Add(int index, int i) { MySqlParameter parameter = new MySqlParameter { DbType = DbType.Int32, Value = i, }; command.Parameters["p" + index] = parameter; } public void Add(int index, uint u) { MySqlParameter parameter = new MySqlParameter { DbType = DbType.UInt32, Value = u, }; command.Parameters["p" + index] = parameter; } public void Add(int index, long l) { MySqlParameter parameter = new MySqlParameter { DbType = DbType.Int64, Value = l, }; command.Parameters["p" + index] = parameter; } public void Add(int index, ulong u) { MySqlParameter parameter = new MySqlParameter { DbType = DbType.UInt64, Value = u, }; command.Parameters["p" + index] = parameter; } public void Add(int index, double d) { MySqlParameter parameter = new MySqlParameter { DbType = DbType.Double, Value = d, }; command.Parameters["p" + index] = parameter; } public void Add(int index, string s) { MySqlParameter parameter = new MySqlParameter { DbType = DbType.String, Value = s, }; command.Parameters["p" + index] = parameter; } public void Add(int index, byte[] bytes) { MySqlParameter parameter = new MySqlParameter { DbType = DbType.Binary, Value = bytes, }; command.Parameters["p" + index] = parameter; } public int Count { get { return command.Parameters.Count; } } public async Task Execute(DbConnection connection) { try { command.Connection = (MySqlConnection)connection; await command.ExecuteNonQueryAsync(); } catch (MySqlException e) { if (e.Number == (int)MySqlErrorCode.LockDeadlock) throw new LockException(e); throw; } } public async Task Execute(DbConnection connection, CancellationToken token) { try { command.Connection = (MySqlConnection)connection; await command.ExecuteNonQueryAsync(token); } catch (MySqlException e) { if (e.Number == (int)MySqlErrorCode.LockDeadlock) throw new LockException(e); throw; } } public async Task<DbDataReader> Query(DbConnection connection) { try { command.Connection = (MySqlConnection)connection; return await command.ExecuteReaderAsync(); } catch (MySqlException e) { switch (e.Number) { case (int)MySqlErrorCode.LockDeadlock: throw new LockException(e); case (int)MySqlErrorCode.LockWaitTimeout: throw new TimeoutException(e.Message, e); default: throw; } } } public async Task<DbDataReader> Query(DbConnection connection, CancellationToken token) { try { command.Connection = (MySqlConnection)connection; return await command.ExecuteReaderAsync(token); } catch (MySqlException e) { if (e.Number == (int)MySqlErrorCode.LockDeadlock) throw new LockException(e); throw; } } } } }
22056953a88f24a6a93f41ba7373e42e8af3185b
C#
JustCallMeAD/CoreSystem
/CoreSystem/Sys/DateTimeExtensions.cs
3.65625
4
using System; public static class DateTimeExtensions { /// <summary> /// Converts a DateTime to the last day of it's financial year. /// </summary> /// <param name="dt"></param> /// <returns></returns> public static DateTime ToLastDayOfFinancialYear(this DateTime dt) { return new DateTime((dt.Month > 6) ? dt.Year + 1 : dt.Year, 6, 30, 12, 0, 0, 0, dt.Kind); } /// <summary> /// For a given date, e.g. 2013-04-18, returns 2013-04-18 23:59:59. /// </summary> /// <param name="dt"></param> /// <returns>A datetime that includes the last second of the day</returns> public static DateTime ToEndDateTime(this DateTime dt) { if (dt > DateTime.MinValue) { return new DateTime(dt.Year, dt.Month, dt.Day, 23, 59, 59); } return dt; } /// <summary> /// Converts datetime to simple xyz ago string for display. /// </summary> /// <param name="dt">Input datetime.</param> /// <returns>Examples: "{0} day{1} ago" OR "{0} hour{1} ago" OR "{0} mins ago"</returns> public static string ToSimpleAgoString(this DateTime dt) { var ts = DateTime.Now - dt; var mins = ts.TotalMinutes; var hours = ts.TotalHours; var days = ts.TotalDays; if (days > 0) { return string.Format("{0} day{1} ago", (int)days, (days > 1 ? "s" : "")); } if (hours > 0) { return string.Format("{0} hour{1} ago", (int)hours, (hours > 1 ? "s" : "")); } if (mins > 0) { return string.Format("{0} mins ago", (int)mins); } return string.Empty; } /// <summary> /// Get's the time portion like "6:27pm" or "1:30am". /// </summary> /// <param name="dt">Input datetime.</param> /// <returns></returns> public static string GetTwelveHourTime(this DateTime dt) { return dt.ToString("h:mmtt").ToLower(); } /// <summary> /// Get day of month English suffix - e.g. 1 = "st", 3 = "rd", 5 = "th", 22 = "nd". /// </summary> /// <param name="dt">Input datetime.</param> /// <returns>Suffix string.</returns> public static string GetDaySuffix(this DateTime dt) { switch (dt.Day) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } } public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); /// <summary> /// To JavaScript milliseconds since unix epoch. Great for making Date instances in JavaScript from a .NET DateTime on backend. /// </summary> /// <param name="dt"></param> /// <returns></returns> public static double ToJavaScriptMilliseconds(this DateTime dt) { return dt.ToUniversalTime().Subtract(UnixEpoch).TotalMilliseconds; } }
e5744d727689396cf88283fa97fc458895348948
C#
vassildinev/CSharp-Part-2
/09.CSharp-2-Exam-Preparation/OTHER_EXAM_PROBLEMS/KukataIsDancing/KukataIsDancing/KukataIsDancing.cs
3.796875
4
using System; class KukataIsDancing { const int size = 3; static void Main() { //INPUT, SOLUTION & OUTPUT int numberOfDances = int.Parse(Console.ReadLine()); int[,] matrix = new int[size, size]; FillMatrix(matrix); for (int i = 0; i < numberOfDances; i++) { int kukataRow = 1; int kukataCol = 1; int kukataDir = 0; string dance = Console.ReadLine(); foreach (char cmd in dance) { MoveKukata(cmd, ref kukataRow, ref kukataCol, ref kukataDir); } if (matrix[kukataRow, kukataCol] == 0) { Console.WriteLine("RED"); } else if (matrix[kukataRow, kukataCol] == 1) { Console.WriteLine("BLUE"); } else if (matrix[kukataRow, kukataCol] == 2) { Console.WriteLine("GREEN"); } } } private static void FillMatrix(int[,] matrix) { // 0 = red // 1 = blue // 2 = green matrix[0, 0] = 0; matrix[0, 1] = 1; matrix[0, 2] = 0; matrix[1, 0] = 1; matrix[1, 1] = 2; matrix[1, 2] = 1; matrix[2, 0] = 0; matrix[2, 1] = 1; matrix[2, 2] = 0; } static void MoveKukata(char c, ref int kukataRow, ref int kukataCol, ref int kukataDir) { // rotation if (c == 'R') { kukataDir++; if (kukataDir == 4) { kukataDir = 0; } } if (c == 'L') { kukataDir--; if (kukataDir == -1) { kukataDir = 3; } } // forward movement if (c == 'W') { if (kukataDir == 0) { kukataCol++; if (kukataCol == 3) { kukataCol = 0; } } if (kukataDir == 1) { kukataRow++; if (kukataRow == 3) { kukataRow = 0; } } if (kukataDir == 2) { kukataCol--; if (kukataCol == -1) { kukataCol = size - 1; } } if (kukataDir == 3) { kukataRow--; if (kukataRow == -1) { kukataRow = size - 1; } } } } }
f9c87c152cb94d97f73f8529dfa8a499bdc61e1a
C#
GalinaSazonova/2semester
/05.03.14/1/ParseTree/Operand.cs
3.03125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParseTree { /// <summary> /// Class for operands. /// </summary> public class Operand : ParseTreeNode { public Operand(string expr) { this.Value = expr; } public string Value { get; set; } public override int Calculate() { return Convert.ToInt32(Value); } public override string ToPrint() { return this.Value; } } }
6b5904d114069ea7ca766a7a7f7c849d1ce778e1
C#
Thebirate/uplink.net
/uplink.NET/uplink.NET/Services/UploadQueueService.cs
2.640625
3
using SQLite; using SQLitePCL; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using uplink.NET.Interfaces; using uplink.NET.Models; namespace uplink.NET.Services { public class UploadQueueService : IUploadQueueService { SQLiteAsyncConnection _connection; CancellationToken _uploadCancelToken; Task _uploadTask; readonly string _databasePath; public UploadQueueService() { _databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "uplinkNET.db"); } public UploadQueueService(string databasePath) { _databasePath = databasePath; } public bool UploadInProgress { get { return _uploadTask != null && ( _uploadTask.Status == TaskStatus.Running || _uploadTask.Status == TaskStatus.WaitingToRun); } } private async Task InitAsync() { if (_connection == null) { _connection = new SQLiteAsyncConnection(_databasePath); await _connection.CreateTableAsync<UploadQueueEntry>(); } } public async Task AddObjectToUploadQueue(string bucketName, string key, string accessGrant, byte[] objectData, string identifier = null) { await InitAsync(); var entry = new UploadQueueEntry(); entry.AccessGrant = accessGrant; entry.Identifier = string.IsNullOrWhiteSpace(identifier) ? Guid.NewGuid().ToString() : identifier; entry.BucketName = bucketName; entry.Key = key; entry.Bytes = objectData; await _connection.InsertAsync(entry); } public async Task CancelUploadAsync(string key) { await InitAsync(); await _connection.Table<UploadQueueEntry>().DeleteAsync(e => e.Key == key); } public Task<List<UploadOperation>> GetAwaitingUploadsAsync() { throw new NotImplementedException(); } public void ProcessQueueInBackground() { if (_uploadTask == null || _uploadTask.Status != TaskStatus.Running) { if (_uploadTask != null) _uploadTask.Dispose(); CancellationTokenSource source = new CancellationTokenSource(); _uploadCancelToken = source.Token; _uploadTask = Task.Factory.StartNew(() => DoUploadAsync(_uploadCancelToken), _uploadCancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default); } } private async Task DoUploadAsync(CancellationToken token) { await InitAsync(); try { while (!token.IsCancellationRequested) { var toUpload = await _connection.Table<UploadQueueEntry>().FirstAsync(); try { var access = new Access(toUpload.AccessGrant); var bucketService = new BucketService(access); var bucket = await bucketService.GetBucketAsync(toUpload.BucketName); var objectService = new ObjectService(access); var upload = await objectService.UploadObjectAsync(bucket, toUpload.Key, new UploadOptions(), toUpload.Bytes, false); await upload.StartUploadAsync(); if (upload.Completed) { await _connection.Table<UploadQueueEntry>().DeleteAsync(e => e.Id == toUpload.Id); } else { //ToDo: Error handling } } catch (Exception ex) { } } } catch { } //That's ok, nothing more to do. } } }
7d86ee806f604e5e388bf56e10620dda5662b562
C#
alittlesail/VSIX-ALittleScript
/Guess/ALittleScriptGuessClass.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ALittle { public class ALittleScriptGuessClass : ALittleScriptGuess { // 命名域和类名 public string namespace_name = ""; public string class_name = ""; // 类本身定义的模板列表 public List<ABnfGuess> template_list = new List<ABnfGuess>(); // 填充后的模板实例 public Dictionary<string, ABnfGuess> template_map = new Dictionary<string, ABnfGuess>(); // 如果是using定义出来的,那么就有这个值 public string using_name; public ALittleScriptClassDecElement class_dec; // 是否是原生类 public bool is_native = false; public ALittleScriptGuessClass(string p_namespace_name, string p_class_name , ALittleScriptClassDecElement p_class_dec, string p_using_name, bool p_is_const, bool p_is_native) { is_register = ALittleScriptUtility.IsRegister(p_class_dec); namespace_name = p_namespace_name; class_name = p_class_name; class_dec = p_class_dec; using_name = p_using_name; is_const = p_is_const; is_native = p_is_native; } public override ABnfElement GetElement() { return class_dec; } public override bool NeedReplace() { if (template_list.Count == 0) return false; foreach (var pair in template_map) { if (pair.Value.NeedReplace()) return true; } return false; } public override ABnfGuess ReplaceTemplate(Dictionary<string, ABnfGuess> fill_map) { var new_guess = Clone() as ALittleScriptGuessClass; foreach (var pair in template_map) { var guess = pair.Value.ReplaceTemplate(fill_map); if (guess == null) return null; if (guess != pair.Value) { var replace = pair.Value.ReplaceTemplate(fill_map); if (replace == null) return null; new_guess.template_map.Add(pair.Key, replace); } } return new_guess; } public override ABnfGuess Clone() { var guess = new ALittleScriptGuessClass(namespace_name, class_name, class_dec, using_name, is_const, is_native); guess.template_list.AddRange(template_list); foreach (var pair in template_map) guess.template_map.Add(pair.Key, pair.Value); guess.UpdateValue(); return guess; } public override void UpdateValue() { value = ""; if (is_const) value += "const "; if (is_native) value += "native "; value += namespace_name + "." + class_name; List<string> name_list = new List<string>(); foreach (var template in template_list) { if (template_map.TryGetValue(template.GetValueWithoutConst(), out ABnfGuess impl)) { if (template.is_const && !impl.is_const) { impl = impl.Clone(); impl.is_const = true; impl.UpdateValue(); } name_list.Add(impl.GetValue()); } else name_list.Add(template.GetValue()); } if (name_list.Count > 0) value += "<" + string.Join(",", name_list) + ">"; } public override bool IsChanged() { foreach (var guess in template_list) { if (guess.IsChanged()) return true; } foreach (var pair in template_map) { if (pair.Value.IsChanged()) return true; } return ALittleScriptIndex.inst.GetGuessTypeList(class_dec) == null; } } }
f28381784c96f3fec04b9bd3c66a9bc6e42f367f
C#
Titaniumstein/PodiatryApplication
/View/Events/EventListener.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace View.Events { public class EventListener<TMessage> : IEventListener<TMessage> { private readonly EventOrchestrator<TMessage> orchestrator; public EventListener(EventOrchestrator<TMessage> orchestrator) { this.orchestrator = orchestrator; } public event Action<TMessage> MessageReceived { add { orchestrator.MessageReceived += value; } remove { orchestrator.MessageReceived -= value; } } } }
82e91988f0e4f351736f141c68a24bda3db43365
C#
trixtur/CsBot
/src/CsBot/Command/RssFeedCommand.cs
2.796875
3
using System; using System.Linq; using System.Net; using System.ServiceModel.Syndication; using System.Xml; namespace CsBot.Command { class RssFeedCommand { readonly CommandHandler handler; SyndicationFeed feed; int count; Users Users { get => handler.Users; } string Addresser { get => handler.Addresser; } IrcBotService IrcBotService { get => handler.IrcBotService; } public RssFeedCommand(CommandHandler handler) { this.handler = handler; } public void GetNext() { var feed = Users[Addresser].Feed; var feedCount = Users[Addresser].FeedCount; if (feed == null) { handler.Say($"You must use {IrcBotService.Settings.CommandStart}getfeeds before trying to list them."); return; } if (feedCount >= feed.Items.Count() || feedCount < 0) { feedCount = 0; handler.Say("Reached max, starting over."); } for (; feedCount < feed.Items.Count(); feedCount++) { var item = feed.Items.ElementAt(feedCount); handler.Say($"Item {feedCount + 1} of {feed.Items.Count()}: {item.Title.Text.Trim()}"); count++; if (count == 4) break; } Users[Addresser].FeedCount = ++feedCount; } public void GetMore(string command, int endCommand) { feed = Users[Addresser].Feed; if (feed == null) { handler.Say($"You must use {IrcBotService.Settings.CommandStart}getfeeds before trying to get more information."); return; } if (command.Length == endCommand + 1 || !int.TryParse(command.Substring(endCommand + 2).Trim().ToLower(), out var feedNumber)) { handler.Say($"Usage: {IrcBotService.Settings.CommandStart}getmore # (Where # is an item from the rss feed)"); } else { feedNumber--; if (feedNumber < 0 || feedNumber > feed.Items.Count()) { handler.Say($"Number is not in the right range. Must be from 1 to {feed.Items.Count()}."); } else { count = 0; handler.Say($"Links for {feed.Items.ElementAt(feedNumber).Title.Text}(Max 4):"); foreach (var link in feed.Items.ElementAt(feedNumber).Links) { handler.Say(link.Uri.ToString().Trim()); count++; if (count == 4) return; } } } } public void GetFeeds(string command, int endCommand) { XmlReader rssReader; if (command.Length == endCommand + 1) { rssReader = XmlReader.Create("http://rss.news.yahoo.com/rss/topstories#"); } else { try { var request = (HttpWebRequest)WebRequest.Create(command.Substring(endCommand + 2).Trim().ToLower()); request.AllowAutoRedirect = true; var response = (HttpWebResponse)request.GetResponse(); rssReader = XmlReader.Create(response.GetResponseStream()); } catch (Exception e) { handler.Say($"Usage: {IrcBotService.Settings.CommandStart}getfeeds http://<rsssite>/rss/<rssfeed#>"); Console.WriteLine(e.Message); return; } } try { feed = SyndicationFeed.Load(rssReader); handler.Users[Addresser].Feed = feed; rssReader.Close(); count = 0; Users[Addresser].FeedCount = 4; handler.Say($"Items 1 through 4 of {feed.Items.Count()} items."); foreach (var item in feed.Items) { handler.Say(item.Title.Text.Trim()); count++; if (count == 4) return; } } catch (Exception e) { handler.Say("Received invalid feed data."); Console.WriteLine(e.Message); } } } }
f73414adf90cdfe8a55d06210940c404d6764d5a
C#
Campbell20/GameHog
/GameHog/Models/Store.cs
2.578125
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace GameHog.Models { public class Store { //Store's unique identification number in the table public int Id { get; set; } //Store name (such as GameStop, EB Games, etc) public string StoreName { get; set; } //building, mall, etc name public string LocationName { get; set; } //Store's Physical Address (later tied into Google Maps for easy searching by customer) public string StorePhysicalStreet { get; set; } public string StorePhysicalCity { get; set; } public string StorePhysicalState { get; set; } public string StorePhysicalZipCode { get; set; } //Store's hours of operation [DataType(DataType.MultilineText)] public string StoreHours { get; set; } //Is this the customer's home location? public bool IsHomeStore { get; set; } #region MailingAddress /// <summary> /// Removed mailing address from this model, because it's backend (district manager infromation that the customer doersn't need at this time.) /// </summary> ////Is theere a different mailing address? If so, check block //public bool IsStoreMailingDifferent { get; set; } ////The Store's mailing address if there is one //public int MailingStreetNumber { get; set; } //public string MailingStreetName { get; set; } ////street identifer (such as St., Dr., Ave., Ln., etc, etc) //public int MailingStreetIdentifier { get; set; } //// suite number if there is one //public int MailingStreetSecondaryIdentifier { get; set; } ////Store's City Name //public string MailingCity { get; set; } ////Store's State //public string MailingState { get; set; } ////Store's Zipcode //public int MailingZipCode { get; set; } #endregion } }
d1c1d68c42cf9b2ce59e8af7c5559338865e0dca
C#
planettelex/Bloom
/Shared/Bloom.Data/Repositories/ArtistRepository.cs
2.90625
3
using System; using System.Collections.Generic; using System.Data.Linq; using System.Linq; using Bloom.Data.Interfaces; using Bloom.Domain.Models; namespace Bloom.Data.Repositories { /// <summary> /// Access methods for artist data. /// </summary> public class ArtistRepository : IArtistRepository { /// <summary> /// Initializes a new instance of the <see cref="ArtistRepository" /> class. /// </summary> /// <param name="roleRepository">The role repository.</param> /// <param name="photoRespository">The photo respository.</param> /// <param name="personRepository">The person repository.</param> public ArtistRepository(IRoleRepository roleRepository, IPhotoRespository photoRespository, IPersonRepository personRepository) { _roleRepository = roleRepository; _photoRespository = photoRespository; _personRepository = personRepository; } private readonly IRoleRepository _roleRepository; private readonly IPhotoRespository _photoRespository; private readonly IPersonRepository _personRepository; /// <summary> /// Gets the artist. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="artistId">The artist identifier.</param> public Artist GetArtist(IDataSource dataSource, Guid artistId) { if (!dataSource.IsConnected()) return null; var artistTable = ArtistTable(dataSource); if (artistTable == null) return null; var artistQuery = from a in artistTable where a.Id == artistId select a; var artist = artistQuery.SingleOrDefault(); if (artist == null) return null; var photoTable = PhotoTable(dataSource); var artistPhotoTable = ArtistPhotoTable(dataSource); var photosQuery = from ap in artistPhotoTable join photo in photoTable on ap.PhotoId equals photo.Id where ap.ArtistId == artistId orderby ap.Priority select photo; artist.Photos = photosQuery.ToList(); var artistMemberTable = ArtistMemberTable(dataSource); var membersQuery = from member in artistMemberTable where member.ArtistId == artistId orderby member.Priority select member; artist.Members = membersQuery.ToList(); if (artist.Members == null) return artist; var artistMemberRoleTable = ArtistMemberRoleTable(dataSource); var personTable = PersonTable(dataSource); var roleTable = RoleTable(dataSource); foreach (var artistMember in artist.Members) { var am = artistMember; var personQuery = from person in personTable where person.Id == am.PersonId select person; artistMember.Person = personQuery.SingleOrDefault(); var rolesQuery = from amr in artistMemberRoleTable join role in roleTable on amr.RoleId equals role.Id where amr.ArtistMemberId == am.Id orderby role.Name select role; artistMember.Roles = rolesQuery.ToList(); } return artist; } /// <summary> /// Finds all artists with the given name. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="artistName">An artist name.</param> public List<Artist> FindArtist(IDataSource dataSource, string artistName) { if (!dataSource.IsConnected()) return null; var artistTable = ArtistTable(dataSource); if (artistTable == null) return null; var artistQuery = from a in artistTable where a.Name.ToLower() == artistName.ToLower() select a; var results = artistQuery.ToList(); return !results.Any() ? null : results; } /// <summary> /// Lists the artists. /// </summary> /// <param name="dataSource">The data source.</param> public List<Artist> ListArtists(IDataSource dataSource) { if (!dataSource.IsConnected()) return null; var artistTable = ArtistTable(dataSource); if (artistTable == null) return null; var photoTable = PhotoTable(dataSource); var artistPhotoTable = ArtistPhotoTable(dataSource); var artistsQuery = from a in artistTable from artistPhoto in artistPhotoTable.Where(ap => ap.ArtistId == a.Id && ap.Priority == 1).DefaultIfEmpty() from photo in photoTable.Where(p => artistPhoto.PhotoId == p.Id).DefaultIfEmpty() orderby a.Name select new { Artist = a, ProfileImage = photo }; var results = artistsQuery.ToList(); var artists = new List<Artist>(); foreach (var result in results) { var artist = result.Artist; artist.ProfileImage = result.ProfileImage; artists.Add(artist); } return artists; } /// <summary> /// Adds an artist. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="artist">The artist.</param> public void AddArtist(IDataSource dataSource, Artist artist) { if (!dataSource.IsConnected()) return; var artistTable = ArtistTable(dataSource); if (artistTable == null) return; artistTable.InsertOnSubmit(artist); dataSource.Save(); } /// <summary> /// Adds an artist member. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="member">The artist member.</param> public void AddArtistMember(IDataSource dataSource, ArtistMember member) { if (!dataSource.IsConnected()) return; if (!_personRepository.PersonExists(dataSource, member.PersonId)) _personRepository.AddPerson(dataSource, member.Person); var artistMemberTable = ArtistMemberTable(dataSource); if (artistMemberTable == null) return; artistMemberTable.InsertOnSubmit(member); dataSource.Save(); } /// <summary> /// Deletes an artist member. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="member">The artist member.</param> public void DeleteArtistMember(IDataSource dataSource, ArtistMember member) { if (!dataSource.IsConnected()) return; var artistMemberTable = ArtistMemberTable(dataSource); if (artistMemberTable == null) return; if (member.Roles != null && member.Roles.Any()) foreach (var role in member.Roles) DeleteArtistMemberRole(dataSource, member, role); artistMemberTable.DeleteOnSubmit(member); dataSource.Save(); } /// <summary> /// Adds an artist member role. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="member">The member.</param> /// <param name="role">The role.</param> public void AddArtistMemberRole(IDataSource dataSource, ArtistMember member, Role role) { if (!dataSource.IsConnected()) return; if (!_roleRepository.RoleExists(dataSource, role.Id)) _roleRepository.AddRole(dataSource, role); var artistMemberRoleTable = ArtistMemberRoleTable(dataSource); if (artistMemberRoleTable == null) return; var artistMemberRole = ArtistMemberRole.Create(member, role); artistMemberRoleTable.InsertOnSubmit(artistMemberRole); dataSource.Save(); } /// <summary> /// Deletes an artist member role. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="member">The member.</param> /// <param name="role">The role.</param> public void DeleteArtistMemberRole(IDataSource dataSource, ArtistMember member, Role role) { if (!dataSource.IsConnected()) return; var artistMemberRoleTable = ArtistMemberRoleTable(dataSource); if (artistMemberRoleTable == null) return; var artistMemberRoleQuery = from amr in artistMemberRoleTable where amr.ArtistMemberId == member.Id && amr.RoleId == role.Id select amr; var artistMemberRole = artistMemberRoleQuery.SingleOrDefault(); if (artistMemberRole == null) return; artistMemberRoleTable.DeleteOnSubmit(artistMemberRole); dataSource.Save(); } /// <summary> /// Adds an artist photo. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="artist">An artist.</param> /// <param name="photo">The photo.</param> /// <param name="priority">The priority.</param> public void AddArtistPhoto(IDataSource dataSource, Artist artist, Photo photo, int priority) { if (!dataSource.IsConnected() || photo == null) return; if (!_photoRespository.PhotoExists(dataSource, photo.Id)) _photoRespository.AddPhoto(dataSource, photo); var artistPhotoTable = ArtistPhotoTable(dataSource); if (artistPhotoTable == null) return; var artistPhoto = ArtistPhoto.Create(artist, photo, priority); artistPhotoTable.InsertOnSubmit(artistPhoto); dataSource.Save(); } /// <summary> /// Deletes the artist photo. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="artist">The artist.</param> /// <param name="photo">The photo.</param> public void DeleteArtistPhoto(IDataSource dataSource, Artist artist, Photo photo) { if (!dataSource.IsConnected() || photo == null) return; var artistPhotoTable = ArtistPhotoTable(dataSource); if (artistPhotoTable == null) return; var artistPhotoQuery = from ap in artistPhotoTable where ap.ArtistId == artist.Id && ap.PhotoId == photo.Id select ap; var personPhoto = artistPhotoQuery.SingleOrDefault(); if (personPhoto == null) return; artistPhotoTable.DeleteOnSubmit(personPhoto); dataSource.Save(); } /// <summary> /// Deletes an artist. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="artist">The artist.</param> public void DeleteArtist(IDataSource dataSource, Artist artist) { if (!dataSource.IsConnected()) return; var artistTable = ArtistTable(dataSource); if (artistTable == null) return; var artistReferenceTable = ArtistReferenceTable(dataSource); var artistReferencesQuery = from ar in artistReferenceTable where ar.ArtistId == artist.Id select ar; artistReferenceTable.DeleteAllOnSubmit(artistReferencesQuery.AsEnumerable()); dataSource.Save(); var artistPhotoTable = ArtistPhotoTable(dataSource); var artistPhotosQuery = from ap in artistPhotoTable where ap.ArtistId == artist.Id select ap; artistPhotoTable.DeleteAllOnSubmit(artistPhotosQuery.AsEnumerable()); dataSource.Save(); var artistMemberTable = ArtistMemberTable(dataSource); var artistMembersQuery = from am in artistMemberTable where am.ArtistId == artist.Id select am; var members = artistMembersQuery.ToList(); foreach (var member in members) { var m = member; var artistMemberRoleTable = ArtistMemberRoleTable(dataSource); var artistMemberRolesQuery = from amr in artistMemberRoleTable where amr.ArtistMemberId == m.Id select amr; artistMemberRoleTable.DeleteAllOnSubmit(artistMemberRolesQuery.AsEnumerable()); dataSource.Save(); artistMemberTable.DeleteOnSubmit(member); dataSource.Save(); } artistTable.DeleteOnSubmit(artist); dataSource.Save(); } #region Tables private static Table<Artist> ArtistTable(IDataSource dataSource) { return dataSource?.Context.GetTable<Artist>(); } private static Table<ArtistPhoto> ArtistPhotoTable(IDataSource dataSource) { return dataSource?.Context.GetTable<ArtistPhoto>(); } private static Table<ArtistReference> ArtistReferenceTable(IDataSource dataSource) { return dataSource?.Context.GetTable<ArtistReference>(); } private static Table<ArtistMember> ArtistMemberTable(IDataSource dataSource) { return dataSource?.Context.GetTable<ArtistMember>(); } private static Table<ArtistMemberRole> ArtistMemberRoleTable(IDataSource dataSource) { return dataSource?.Context.GetTable<ArtistMemberRole>(); } private static Table<Role> RoleTable(IDataSource dataSource) { return dataSource?.Context.GetTable<Role>(); } private static Table<Person> PersonTable(IDataSource dataSource) { return dataSource?.Context.GetTable<Person>(); } private static IEnumerable<Photo> PhotoTable(IDataSource dataSource) { return dataSource?.Context.GetTable<Photo>(); } #endregion } }
887df78787e259305b9609b4d895e549b2292148
C#
radtek/vprint
/PTFReports/PTFReportsLib/Extentions/IListEx.cs
2.65625
3
/*************************************************** // Copyright (c) Premium Tax Free 2012 /***************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace PTF.Reports { public static class IListEx { /// <summary> /// Returns any or all or collection /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="funct"></param> /// <returns></returns> public static IEnumerable<T> Where<T>(this IList list, Func<T, bool> funct = null) { Debug.Assert(list != null); lock (((ICollection)list).SyncRoot) { foreach (T value in list) if (funct == null || funct(value)) yield return value; } } } }
7c4025502f83871df6c4722d95143c7dd2c0d72e
C#
mstarski/file-manager
/FileManager/DataModels/MyDirectory.cs
3.390625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; /// <summary> /// MyDirectory Class represents system directories /// </summary> namespace FileManager.DataModels { public class MyDirectory : IDiscElement { public string Path { get; set; } public string Name { get; set; } public MyDirectory(string name, string path) { Path = path; Name = name; } public int GetElementCount() { return GetSubElements().Count; } /// <summary> /// Gets child files and directories and adds them to a List of IDiscElement elements /// </summary> /// <returns></returns> public List<IDiscElement> GetSubElements() { List<IDiscElement> result = new List<IDiscElement>(); DirectoryInfo d = new DirectoryInfo(this.Path); try { FileInfo[] fs = d.GetFiles(); DirectoryInfo[] dirs = d.GetDirectories(); foreach (DirectoryInfo dir in dirs) { MyDirectory directory = new MyDirectory(dir.Name, dir.FullName); result.Add(directory); } foreach (FileInfo file in fs) { MyFile myfile = new MyFile(file.Name, file.FullName, file.Length); result.Add(myfile); } return result; } catch(Exception e) { //Exception handler MessageBox.Show(e.ToString()); return null; } } public DateTime GetCreationDate() { return Directory.GetCreationTime(Path); } public string GetDescription() { return Path + " liczba elementów: " + GetElementCount(); } } }
179d620eadc162762ad31854059c9eb677019854
C#
scbj/musixx
/Musixx.Shared/ApplicationSettingsHelper.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace Musixx.Shared { public static class ApplicationSettingsHelper { public static object ReadResetSettingsValue(string key) { object value = ReadSettingsValue(key); if (value != null) ApplicationData.Current.LocalSettings.Values.Remove(key); return value; } public static object ReadSettingsValue(string key) { if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(key)) return null; return ApplicationData.Current.LocalSettings.Values[key]; } public static void SaveSettingsValue(string key, object value) { if (ApplicationData.Current.LocalSettings.Values.ContainsKey(key)) ApplicationData.Current.LocalSettings.Values.Add(key, value); else ApplicationData.Current.LocalSettings.Values[key] = value; } } }
5839fdb821c85c6b623f937afc16eb707e3a5da2
C#
DanteDercksen/GADE6112_POE_19014267_Task1
/Tile.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GADE6112_POE_19014267 { abstract class Tile { public enum TileType { HERO, ENEMY, GOBLIN, WEAPON}; protected int x; protected int y; public int X { get { return x; } } public int Y { get { return y; } } public Tile(int x, int y) { x = X; y = Y; } } }
f55e10af397ad23246018d02b237a7462c449487
C#
saglag/LJPcalc
/src/LJPmath/Constants.cs
2.640625
3
using System; using System.Collections.Generic; using System.Text; namespace LJPmath { public static class Constants { // Boltzmann constant = 1.38064852e-23 (m^2 * kg) / (s^2 * K) public const double zeroCinK = 273.15; public const double boltzmann = 1.38064852e-23; // Elementary charge = 1.602176634e-19 (cm * g * s) public const double e = 1.602176634e-19; // Avogadro constant = 6.02214076e23 (no units) public const double Nav = 6.02214076e23; // Gas Constant public const double R = Nav * boltzmann; // Faraday constant (C / mol) public const double F = e * Nav; } }
75ed631974e349f3aee55b7fe6433ba1c2f1da52
C#
MartinNikolovMarinov/CSharp_DSA
/SoftUni/DataStructures/04.Trees/Homework/TraverseAndSaveDirectory/MyFile.cs
2.890625
3
namespace TraverseAndSaveDirectory { public class MyFile { public int Size { get; set; } public string Name { get; set; } public MyFile(string name, int size) { this.Name = name; this.Size = size; } } }
900a1a6f87f6d2b2e7af918c5daa91e07c1a323d
C#
sedc-codecademy/sedc6-csharp
/src/Advanced05/Advanced05/Extensions.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Advanced05 { static class Extensions { public static void PrintCollection<T>(this IEnumerable<T> collection) { foreach (var item in collection) { Console.WriteLine(item); } } public static void PrintItem<T>(this T item) { Console.WriteLine(item); } } }
698cabfccc23d4c5a1bd84ab39bb089311a7cc16
C#
peachpiecompiler/peachpie
/src/Peachpie.Runtime/Collections/ValueList`1.cs
3.109375
3
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Pchp.Core.Collections { /// <summary> /// <see cref="IList{T}"/> implementation as a value type. /// </summary> [DebuggerDisplay("{typeof(T).FullName,nq}[{_count}]")] public struct ValueList<T> : IList<T> { int _count; T[] _array; /// <summary> /// Gets new empty list. /// </summary> public static ValueList<T> Empty => new ValueList<T>(0); // no alloc public ValueList(IEnumerable<T> collection) { _count = 0; _array = null; AddRange(collection); } public ValueList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); _count = 0; _array = capacity <= 0 ? Array.Empty<T>() : new T[capacity]; } public T this[int index] { get { return index >= 0 && index < _count ? _array[index] : throw new ArgumentOutOfRangeException(nameof(index)); } set { if (index >= 0 && index < _count) { _array[index] = value; } else { throw new ArgumentOutOfRangeException(nameof(index)); } } } public int Count { get => _count; internal set { if (value < 0 || value > Capacity) throw new ArgumentOutOfRangeException(nameof(value)); _count = value; } } public bool IsReadOnly => false; private int Capacity { get { return _array != null ? _array.Length : 0; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } if (value == 0) { _array = Array.Empty<T>(); } else if (_array == null || _array.Length == 0) { _array = new T[value]; } else { Array.Resize(ref _array, value); } } } private void EnsureCapacity(int capacity) { if (Capacity < capacity) { Capacity = Math.Max(capacity, Capacity * 2); } } public void Add(T item) { EnsureCapacity(_count + 1); _array[_count++] = item; } public void AddRange(IEnumerable<T> enumerable) { if (enumerable is ICollection col) { EnsureCapacity(Count + col.Count); col.CopyTo(_array, _count); _count += col.Count; } else if (enumerable != null) { foreach (var item in enumerable) { Add(item); } } } public void AddRange(T[] array) => AddRange(array, 0, array.Length); public void AddRange(T[] array, int start, int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } EnsureCapacity(Count + count); Array.Copy(array, start, _array, _count, count); _count += count; } public void Clear() { if (_count != 0) { Array.Clear(_array, 0, _count); _count = 0; } } public bool Contains(T item) => IndexOf(item) >= 0; public void CopyTo(T[] array, int arrayIndex) { if (_count != 0) { Array.Copy(_array, 0, array, arrayIndex, _count); } } public int IndexOf(T item) => _array != null ? Array.IndexOf(_array, item, 0, _count) : -1; public void Insert(int index, T item) { if (index > Count || index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } EnsureCapacity(_count + 1); // make space for the new item at _array[index] var toBeMoved = Count - index; if (toBeMoved > 0) { Array.Copy(_array, index, _array, index + 1, toBeMoved); } // _count++; _array[index] = item; } public bool Remove(T item) { var index = IndexOf(item); if (index >= 0) { RemoveAt(index); return true; } else { return false; } } public void RemoveAt(int index) { if (index < 0 || index >= _count) { throw new ArgumentOutOfRangeException(nameof(index)); } _array[index] = default(T); Array.Copy(_array, index + 1, _array, index, --_count - index); } /// <summary> /// Alias to <see cref="Add(T)"/>. /// </summary> public void Push(T item) => this.Add(item); /// <summary> /// Pops an element from the end of collection. /// </summary> /// <returns>The last element.</returns> public T Pop() { if (_count > 0) { return _array[--_count]; } else { throw new InvalidOperationException(); } } public ValueEnumerator GetEnumerator() => new ValueEnumerator(ref this); IEnumerator<T> IEnumerable<T>.GetEnumerator() { var count = _count; var array = _array; for (int i = 0; i < count; i++) { yield return array[i]; } } IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator(); /// <summary> /// Returns a collection of items with duplicit <c>key</c> (according to provided <paramref name="keySelector"/>. /// </summary> /// <typeparam name="TKey">Type of the key to be checned.</typeparam> /// <param name="keySelector">Gets the key to be used for the duplicity check.</param> /// <param name="predicate">Optional. Where predicate.</param> /// <returns>Set of duplicit items.</returns> public IReadOnlyList<T> SelectDuplicities<TKey>(Func<T, TKey> keySelector, Predicate<T> predicate = null) { if (this.Count <= 1) { return Array.Empty<T>(); } if (keySelector == null) { throw new ArgumentNullException(nameof(keySelector)); } var set = new HashSet<TKey>(); var duplicities = new ValueList<T>(); foreach (var item in this) { if (predicate != null && !predicate(item)) { continue; } if (set.Add(keySelector(item))) { // ok } else { duplicities.Add(item); } } // return duplicities.AsReadOnly(); } /// <summary> /// Gets a readonly collection of the elements. /// Note the collection may reference the underlying array, so any changes will be reflected in both returned list and this list as well. /// </summary> public IReadOnlyList<T> AsReadOnly() { if (_count == 0) { return Array.Empty<T>(); } Debug.Assert(_array != null); if (_count == _array.Length) { return _array; } return new ArraySegmentClass(_array, _count); } /// <summary> /// Gets array with the elements. /// Note the array may reference the underlying array, so any changes will be reflected in both returned list and this list as well. /// </summary> public T[] ToArray() { if (_count == 0) { return Array.Empty<T>(); } Debug.Assert(_array != null); if (_count == _array.Length) { return _array; } return _array.AsSpan(0, _count).ToArray(); } public Span<T> AsSpan() { if (_count == 0) { return Span<T>.Empty; } Debug.Assert(_array != null); return _array.AsSpan(0, _count); } internal void GetArraySegment(out T[] array, out int count) { count = _count; array = _array ?? Array.Empty<T>(); } internal void GetArraySegment(int capacity, out T[] array, out int count) { EnsureCapacity(capacity); GetArraySegment(out array, out count); } public struct ValueEnumerator { readonly T[] _array; readonly int _count; int index; internal ValueEnumerator(ref ValueList<T> list) { _array = list._array; _count = list._count; index = -1; } public bool MoveNext() => ++index < _count; public T Current => _array[index]; } sealed class ArraySegmentClass : IReadOnlyList<T> { readonly T[] _array; readonly int _count; public ArraySegmentClass(T[] array, int count) { _array = array ?? throw new ArgumentNullException(nameof(array)); _count = count; } public T this[int index] => _array[index]; public int Count => _count; public IEnumerator<T> GetEnumerator() { for (int i = 0; i < _count; i++) { yield return _array[i]; } } IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator(); } } }
7b1069526efaa53cd2edd2d138eedd7584a59b6d
C#
fjesualdo/Testes
/Console/models/NewStudent.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Console { public class ListNewStudent : List<NewStudentt> { public ListNewStudent() { } // Create a data source by using a collection initializer. public static ListNewStudent GetListStudent() { ListNewStudent students = new ListNewStudent() { new NewStudentt {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, 60}}, new NewStudentt {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}}, new NewStudentt {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}}, new NewStudentt {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}}, new NewStudentt {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}}, new NewStudentt {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}}, new NewStudentt {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}}, new NewStudentt {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}}, new NewStudentt {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}}, new NewStudentt {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}}, new NewStudentt {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 60}}, new NewStudentt {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91}} }; return students; } } public class NewStudentt { public string First { get; set; } public string Last { get; set; } public int ID { get; set; } public List<int> Scores; public override string ToString() { //return string.Format("ID: {0,2} / NOME: {1, -15} / PREÇO: {2,10}", this.Id.ToString(), this.Nome, this.Preco.ToString("F2", CultureInfo.InvariantCulture)); return string.Format("ID: {0,3} / FIRST: {1,-20} / LAST: {2,-20} / SCORE: {3,-20}", ID > 0 ? ID.ToString() : "---", First, Last, String.Join(",", Scores)); } } }
88901f137866fd99bccda91cfd473bd0c974e6ba
C#
BorislavD/Arrays-and-Lists-CSharp
/CamelsBack.cs
3.609375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CamelsBack { class CamelsBack { static void Main(string[] args) { List<int> list = Console.ReadLine().Split().Select(int.Parse).ToList(); int n = int.Parse(Console.ReadLine()); int counter = 0; if (list.Count == n) { Console.WriteLine("already stable: {0}", string.Join(" ", list)); return; } else { while (list.Count > n) { list.RemoveAt(0); list.RemoveAt(list.Count - 1); counter++; } } Console.WriteLine("{0} rounds", counter); Console.WriteLine("remaining: {0}", string.Join(" ", list)); } } }
d882de15cb04f4a650fdec6cdb47f6eaa702fbc4
C#
ajabotomey/DialoguePrototype
/Assets/DialogueSystem/Scripts/ParseEmojis.cs
3.109375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Text; public static class ParseEmojis { public static string Parse(string text) { char[] separators = { '(', ')' }; // Go through and detect parenthesis and make substrings string[] textChunks = text.Split(separators); // Find all chunks that start with \\ for (int i = 0; i < textChunks.Length; i++) { if (textChunks[i].Contains("\\")) { string emoji = ConvertToUnicode(textChunks[i]); textChunks[i] = emoji; } } string result = ""; // Reform the string for (int i = 0; i < textChunks.Length; i++) { result += textChunks[i]; } return result; } private static string ConvertToUnicode(string iconUnicode) { // Remove the "\\u" iconUnicode = iconUnicode.Substring(3); int unicode = int.Parse(iconUnicode, System.Globalization.NumberStyles.HexNumber); string result = char.ConvertFromUtf32(unicode); return result; } }
b9a8bc793bba39955173a8107f5faaa7120c8f69
C#
AngelDimitrov52/Software-University
/2.C# Fundamentals/Homeworks and labs/09.RegularExtresion/RegularExpresionExe/05.NetherRealms/Program.cs
3.484375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace _05.NetherRealms { class Program { static void Main(string[] args) { string[] demons = Console.ReadLine() .Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); string pattern = @"[\+,\-\*\/0-9\.]"; Regex regexHelt = new Regex(pattern); string patternpower = @"(\-|\+)*([0-9]+\.)*[0-9]+"; Regex regexPower = new Regex(patternpower); Dictionary<string, List<double>> demonsDic = new Dictionary<string, List<double>>(); foreach (var demonName in demons) { var matchDemon = regexHelt.Replace(demonName, ""); int helt = 0; foreach (var digit in matchDemon) { helt += digit; } List<double> valueList = new List<double>(); valueList.Add(helt); demonsDic.Add(demonName, valueList); double dimige = 0; MatchCollection matchnums = regexPower.Matches(demonName); foreach (Match item in matchnums) { dimige += double.Parse(item.ToString()); } string pattern1 = @"\*"; Regex regex1 = new Regex(pattern1); MatchCollection poilideleno = regex1.Matches(demonName); foreach (Match item in poilideleno) { dimige *= 2; } string pattern2 = @"\/"; Regex regex2 = new Regex(pattern2); MatchCollection poilideleno2 = regex2.Matches(demonName); foreach (Match item in poilideleno2) { dimige /= 2; } demonsDic[demonName].Add(dimige); } foreach (var item in demonsDic.OrderBy(k => k.Key)) { Console.WriteLine($"{item.Key} - {item.Value[0]} health, {item.Value[1]:f2} damage"); } } } }
ca7329b20274c5732535acacd3afad8e2f265f71
C#
lvetskov/Telerik_Academy_Homework_Projects
/OOP/exam/Furniture/FurnitureManufacturer/Models/Table.cs
3.453125
3
namespace FurnitureManufacturer.Models { using FurnitureManufacturer.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Table : Furniture, ITable { private decimal length; private decimal width; private decimal area; public Table(string model, MaterialType material, decimal price, decimal height, decimal length, decimal width) : base(model, material, price, height) { this.Length = length; this.Width = width; this.Area = this.Length * this.Width; } public decimal Length { get { return this.length; } private set { if (value <= Furniture.zeroOrNullValue) { throw new ArgumentOutOfRangeException("The table's length cannot be less or equal to 0."); } this.length = value; } } public decimal Width { get { return this.width; } private set { if (value <= Furniture.zeroOrNullValue) { throw new ArgumentOutOfRangeException("The table's width cannot be less or equal to 0."); } this.width = value; } } public decimal Area { get { return this.area; } private set { this.area = value; } } } }
ccdd564515fe9541a05bfa722806d68bb75386c3
C#
eshohag/ASP.Net-MVC5-Apps
/UniversityRegistrationProcess/UniversityRegistrationProcess/Gateway/SemesterGateway.cs
2.890625
3
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using UniversityRegistrationProcess.Models; namespace UniversityRegistrationProcess.Gateway { public class SemesterGateway:CommonGateway { public List<Semester> GetAllSemesters() { Query = "SELECT * FROM Semester"; Command = new SqlCommand(Query, Connection); Connection.Open(); Reader = Command.ExecuteReader(); List<Semester> SemesterList = new List<Semester>(); while (Reader.Read()) { Semester aSemester = new Semester(); aSemester.SemesterId = Convert.ToInt32(Reader["SemesterId"]); aSemester.Name = Reader["Name"].ToString(); SemesterList.Add(aSemester); } Reader.Close(); Connection.Close(); return SemesterList; } } }
275b39905479e6acce108b38ff1191dc5c866e08
C#
shendongnian/download4
/first_version_download2/407875-35614865-111690470-2.cs
2.859375
3
string status = string.Empty; Thread thread = new System.Threading.Thread(() => { status = Download(downloadKit, patchTitle); }); thread.Start(); thread.Join(); //no point in looping here, if the thread finished, it has already assigned the //value it is going to assign to the status variable if (status == "Done") { //do what needs to be done } else { //uh oh, handle the failure here }
79e18a2a3fcc00799689c82c74541de059b15106
C#
ThomasH94/BreakoutMania
/Assets/_Project/Scripts/Scoring Systems/LivesManager.cs
2.625
3
using BrickBreak.EventManagement; using BrickBreak.GameManagement; using BrickBreak.Singletons; using TMPro; using UnityEngine; namespace BrickBreak.GameManagement { public class LivesManager : Singleton<LivesManager> { [SerializeField] private TextMeshProUGUI livesText = null; [SerializeField] private bool infiniteLives = false; public int Lives { get; private set; } public int startingLives = 3; [SerializeField] private SceneController _sceneController; private void Start() { Lives = startingLives; UpdateLivesText(); } private void OnEnable() { EventManager.StartListening("Lose Life", LoseLife); } private void OnDisable() { EventManager.StopListening("Lose Life", LoseLife); } private void UpdateLivesText() { livesText.text = infiniteLives ? "∞" : $"Lives: {Lives.ToString()}"; } // Lives will always have a default amount sent in based on the levels objective to add // an extra layer of challenge with no way to gain additional lives private void LoseLife() { if (infiniteLives) return; Lives--; if (Lives <= 0) { GameplayManager.Instance.LevelCompleted(false); } else { UpdateLivesText(); } } public void GainLives(int amount) { Lives += amount; UpdateLivesText(); } } }
7d9555e6a01cf80883441bb203064be908dc39d4
C#
DamirAinullin/RedisSessionProvider
/RedisSessionProviderUnitTests/RedisSessionStateItemCollectionTests/SingleThreadedTests.cs
2.515625
3
namespace RedisSessionProviderUnitTests.RedisSessionStateItemCollectionTests { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Moq; using RedisSessionProvider; using RedisSessionProvider.Serialization; [TestFixture] public class SingleThreadedTests { private RedisSessionStateItemCollection items; private RedisJSONSerializer srsly; [SetUp] public void OnBeforeTestExecute() { srsly = new RedisJSONSerializer(); this.items = new RedisSessionStateItemCollection( new Dictionary<string, byte[]> { { "a", Encoding.UTF8.GetBytes(srsly.SerializeOne("a", "x")) }, { "b", Encoding.UTF8.GetBytes(srsly.SerializeOne("b", "y")) }, { "c", Encoding.UTF8.GetBytes(srsly.SerializeOne("c", "z")) } }, "fakeCollection"); } [Test] public void RedisItemsCollectionConstructorTest() { Assert.AreEqual("x", (string)this.items["a"]); Assert.AreEqual("y", (string)this.items["b"]); Assert.AreEqual("z", (string)this.items["c"]); } [Test] public void RedisItemsCollectionAddTest() { this.items["something"] = "a thing"; this.items["foo"] = "bar"; this.items["lucas"] = "uses venmo"; Assert.AreEqual("a thing", this.items["something"]); Assert.AreEqual("bar", this.items["foo"]); Assert.AreEqual("uses venmo", this.items["lucas"]); Assert.Throws<NotImplementedException>( () => { var x = this.items[3]; }); } [Test] public void RedisItemsCollectionRemoveTest() { Assert.AreEqual("x", (string)this.items["a"]); Assert.AreEqual("y", (string)this.items["b"]); Assert.AreEqual("z", (string)this.items["c"]); this.items.Remove("a"); Assert.IsNull(this.items["a"]); this.items["something"] = "a thing"; this.items["foo"] = "bar"; this.items["lucas"] = "uses venmo"; Assert.AreEqual("y", (string)this.items["b"]); Assert.AreEqual("z", (string)this.items["c"]); Assert.AreEqual("a thing", this.items["something"]); Assert.AreEqual("bar", this.items["foo"]); Assert.AreEqual("uses venmo", this.items["lucas"]); this.items.Remove("foo"); Assert.IsNull(this.items["foo"]); Assert.AreEqual("y", (string)this.items["b"]); Assert.AreEqual("z", (string)this.items["c"]); Assert.AreEqual("a thing", this.items["something"]); Assert.AreEqual("uses venmo", this.items["lucas"]); Assert.AreEqual(4, this.items.Count); this.items["empty"] = null; Assert.AreEqual(4, this.items.Count); } [Test] public void RedisItemsEnumeratorTest() { foreach(KeyValuePair<string, object> val in this.items) { Assert.Contains(val.Value, new string[] { "x", "y", "z" }); } this.items["something"] = "a thing"; this.items["foo"] = "bar"; this.items["lucas"] = "uses venmo"; foreach (KeyValuePair<string, object> val in this.items) { Assert.Contains(val.Value, new string[] { "x", "y", "z", "a thing", "bar", "uses venmo" }); } } [Test] public void RedisItemsChangedObjsEnumeratorTest() { List<KeyValuePair<string, string>> changedObjs = new List<KeyValuePair<string, string>>(); foreach (KeyValuePair<string, string> val in this.items.GetChangedObjectsEnumerator()) { changedObjs.Add(val); } Assert.AreEqual(0, changedObjs.Count); this.items["something"] = "a thing"; this.items["foo"] = "bar"; this.items["lucas"] = "uses venmo"; foreach (KeyValuePair<string, string> val in this.items.GetChangedObjectsEnumerator()) { changedObjs.Add(val); } Assert.AreEqual(3, changedObjs.Count); foreach(KeyValuePair<string, string> val in changedObjs) { Assert.Contains( this.srsly.DeserializeOne(val.Value), new string[] { "a thing", "bar", "uses venmo" }); } this.items["a"] = "not x"; changedObjs.Clear(); foreach (KeyValuePair<string, string> val in this.items.GetChangedObjectsEnumerator()) { changedObjs.Add(val); } // since we got all the new changed objects in the previous call to GetChangedObjectsEnumerator, // this call should only return "a", "not x" Assert.AreEqual(1, changedObjs.Count); Assert.AreEqual(changedObjs[0].Key, "a"); Assert.AreEqual( this.srsly.DeserializeOne(changedObjs[0].Value), "not x"); } [Test] public void AddRemoveAndGetEnumeratorTest() { // test that nothing has changed since the stuff we added was in the constructor, // so in real usage that would be coming from Redis and thus be the default state int numChanged = 0; foreach (KeyValuePair<string, string> val in this.items.GetChangedObjectsEnumerator()) { numChanged++; } Assert.AreEqual(0, numChanged); // test assigning a value to something new this.items["a"] = "not x"; numChanged = 0; foreach (KeyValuePair<string, string> val in this.items.GetChangedObjectsEnumerator()) { numChanged++; Assert.AreEqual( val.Key, "a"); Assert.AreEqual( this.srsly.DeserializeOne(val.Value), "not x"); } Assert.AreEqual(1, numChanged); // test assigning a value to something else then assigning it back. In such a case, // we don't want it to come back from the enumerator because it has not really // changed from the initial state so why bother redis about it? this.items["a"] = "x"; this.items["a"] = "not x"; numChanged = 0; foreach (KeyValuePair<string, string> val in this.items.GetChangedObjectsEnumerator()) { numChanged++; } Assert.AreEqual(0, numChanged); // test creating a new value and then removing it will do nothing this.items["new"] = "m"; this.items["new"] = null; numChanged = 0; foreach (KeyValuePair<string, string> val in this.items.GetChangedObjectsEnumerator()) { numChanged++; } Assert.AreEqual(0, numChanged); // test creating a new value, then getting the changed objects enumerator (which resets // the initial state) then removing the new value then getting the changed objects // again results in two enumerators that return 1 element each this.items["new"] = "m"; numChanged = 0; foreach (KeyValuePair<string, string> val in this.items.GetChangedObjectsEnumerator()) { numChanged++; Assert.AreEqual( val.Key, "new"); Assert.AreEqual( this.srsly.DeserializeOne(val.Value), "m"); } Assert.AreEqual(1, numChanged); this.items["new"] = null; numChanged = 0; foreach (KeyValuePair<string, string> val in this.items.GetChangedObjectsEnumerator()) { numChanged++; Assert.AreEqual( val.Key, "new"); Assert.IsNull(val.Value); } Assert.AreEqual(1, numChanged); } [Test] public void AddRemoveAndDirtyCheckReferenceTypesTest() { // add a list to session this.items["refType"] = new List<string>(); // get a reference to it List<string> myList = this.items["refType"] as List<string>; // alternatively, make a list List<int> myOtherList = new List<int>(); // add it to session this.items["otherRefType"] = myOtherList; bool listCameBack = false; bool otherListCameBack = false; // test that these come back from the enumerator foreach(KeyValuePair<string, string> changed in this.items.GetChangedObjectsEnumerator()) { if(changed.Key == "refType" && changed.Value == srsly.SerializeOne(changed.Key, myList)) { listCameBack = true; } else if (changed.Key == "otherRefType" && changed.Value == srsly.SerializeOne(changed.Key, myOtherList)) { otherListCameBack = true; } } Assert.IsTrue(listCameBack, "failed to return string list"); Assert.IsTrue(otherListCameBack, "failed to return int list"); // test that if we get the changed objects again, they won't come back listCameBack = false; otherListCameBack = false; foreach (KeyValuePair<string, string> changed in this.items.GetChangedObjectsEnumerator()) { if(changed.Key == "refType") { listCameBack = true; } else if(changed.Key == "otherRefType") { otherListCameBack = true; } } Assert.IsFalse(listCameBack, "incorrectly returned string list"); Assert.IsFalse(otherListCameBack, "incorrectly returned int list"); // now let's modify a list myOtherList.Add(1); otherListCameBack = false; foreach (KeyValuePair<string, string> changed in this.items.GetChangedObjectsEnumerator()) { if(changed.Key == "otherRefType" && changed.Value == srsly.SerializeOne(changed.Key, myOtherList)) { otherListCameBack = true; } } Assert.IsTrue(otherListCameBack, "list that was modified not returned when it should have been"); // ok, let's see if modifying the list, then undoing that modification results // in it being returned (it shouldn't) myList.Add("a"); myList.Clear(); listCameBack = false; foreach (KeyValuePair<string, string> changed in this.items.GetChangedObjectsEnumerator()) { if (changed.Key == "refType" && changed.Value == srsly.SerializeOne(changed.Key, myList)) { listCameBack = true; } } Assert.IsFalse(listCameBack, "list that was modified then reset should not come back"); } } }
3f9843deaf9ccc828764db85cda9714a65086003
C#
BastienPerdriau/HelpFileMarkdownBuilder
/Sources/HelpFileMarkdownBuilder/Language.cs
3.125
3
using HelpFileMarkdownBuilder.Base; using HelpFileMarkdownBuilder.CSharp.Builder; using System; using System.Linq; namespace HelpFileMarkdownBuilder { /// <summary> /// Languages to build help files /// </summary> public abstract class Language : Enumeration { /// <summary> /// C# /// </summary> public static CSharpLanguage CSharp => new CSharpLanguage(0); /// <summary> /// Short name /// </summary> public abstract string ShortName { get; } /// <summary> /// Full name /// </summary> public abstract string FullName { get; } /// <summary> /// Builder /// </summary> internal abstract Builder Builder { get; } /// <summary> /// Constructor /// </summary> /// <param name="key">Key</param> protected Language(int key) : base(key) { } /// <summary> /// Gets a language by it short name /// </summary> /// <param name="shortName">Short name</param> /// <returns>Language</returns> public static Language FromShortName(string shortName) { return List<Language>().Single(l => string.Equals(l.ShortName, shortName, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Gets a language by it full name /// </summary> /// <param name="fullName">Full name</param> /// <returns>Language</returns> public static Language FromFullName(string fullName) { return List<Language>().Single(l => string.Equals(l.FullName, fullName, StringComparison.OrdinalIgnoreCase)); } } }
254823e2a4b82f1e73ca6f3903846ac35e90b3d3
C#
level2player/LiteCache
/src/LiteCache/LiteCache.cs
2.6875
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Timers; namespace Lsy.core.LiteCache { public class LiteCache<T> { Dictionary<string, T> globalDictionary = new Dictionary<string, T> (); /// <summary> /// 缓存数据集合,值copy /// </summary> /// <typeparam name="string">缓存Key</typeparam> /// <typeparam name="T">缓存数据类型</typeparam> /// <returns></returns> public Dictionary<string, T> GlobalDictionary { get { try { cacheLock.EnterReadLock (); return new Dictionary<string, T> (globalDictionary); } finally { cacheLock.ExitReadLock (); } } } private System.Timers.Timer expiredTimer; /// <summary> /// 缓存保存时间 /// </summary> /// <value></value> public int LiveTime { get; private set; } /// <summary> /// 检查间隔时间 /// </summary> /// <value></value> public int CheckTime { get; private set; } /// <summary> /// 缓存名称 /// </summary> /// <value></value> public string CacheName { get; private set; } /// <summary> /// 集合行数量 /// </summary> /// <value></value> public int Count { get { return GlobalDictionary.Count (); } } /// <summary> /// 读写锁 /// </summary> /// <returns></returns> private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim (); /// <summary> /// 构造函数 /// </summary> /// <param name="liveTime">数据生存周期,单位秒</param> /// <param name="checkTime">检查数据周期,单位秒</param> /// <param name="cacheName">缓存文件名称,不需要输入后缀名</param> public LiteCache (int liveTime, int checkTime, string cacheName) { LiveTime = liveTime; CheckTime = checkTime; CacheName = cacheName; RegisterTimeCheck (); InitLoadLocData (); } ~LiteCache () { if (cacheLock != null) cacheLock.Dispose (); } /// <summary> /// 从本地dat文件拉数据刷新到缓存中 /// </summary> private void InitLoadLocData () { cacheLock.EnterReadLock (); try { var dic = Utility.DeserializeCache<T> (CacheName); // Console.WriteLine ("dic.count=" + dic.Count ()); if (dic?.Count > 0) { globalDictionary = dic; } } catch (System.Exception) { } finally { cacheLock.ExitReadLock (); } } /// <summary> /// 添加缓存值 /// </summary> /// <param name="value">数据</param> /// <returns>guid(唯一标识);是否成功</returns> public (string, bool) AddValue (T value) { var guid = $"{System.Guid.NewGuid().ToString()}|{System.DateTime.Now.AddSeconds(LiveTime)}"; var tmp_dic = new Dictionary<string, T> () { { guid, value } }; cacheLock.EnterWriteLock (); try { if (Utility.SaveCache (tmp_dic, CacheName)) { globalDictionary.Add (guid, value); } } catch (System.Exception e) { throw e; } finally { cacheLock.ExitWriteLock (); } return (guid, true); } /// <summary> /// 批量添加数据 /// </summary> /// <param name="dataList">新增加的数据</param> /// <returns>添加条数;添加结果</returns> public (int, bool) AddValue (IList<T> dataList) { int count = 0; if (dataList == null || dataList.Count == 0) return (count, false); var tmp_dic = new Dictionary<string, T> (); foreach (var item in dataList) { var guid = $"{System.Guid.NewGuid().ToString()}|{System.DateTime.Now.AddSeconds(LiveTime)}"; tmp_dic.Add (guid, item); count++; } cacheLock.EnterWriteLock (); try { if (Utility.SaveCache (tmp_dic, CacheName)) { foreach (var item in tmp_dic) { globalDictionary.Add (item.Key, item.Value); } } } catch (System.Exception e) { throw e; } finally { cacheLock.ExitWriteLock (); } return (count, true); } /// <summary> /// 异步添加缓存值 /// </summary> /// <param name="value">数据</param> /// <returns>guid(唯一标识);是否成功</returns> public async Task<(string, bool)> AsynAddValue (T value) { return await Task.Run (() => { return AddValue (value); }); } /// <summary> /// 异步批量添加缓存值 /// </summary> /// <returns></returns> public async Task<(int, bool)> AsynAddValue (List<T> dataList) { return await Task.Run (() => { return AddValue (dataList); }); } /// <summary> /// 取缓存值 /// </summary> /// <param name="guid">guid(唯一标识)</param> /// <returns>数据值;是否成功</returns> public (T, bool) GetValue (string guid) { if (string.IsNullOrEmpty (guid)) return (default (T), false); T result = default (T); cacheLock.EnterReadLock (); try { if (globalDictionary.TryGetValue (guid, out result)) { return (result, true); } else { var dic = Utility.DeserializeCache<T> (CacheName); if (dic?.Count > 0) { if (dic.TryGetValue (guid, out result)) return (result, true); } return (default (T), false); } } catch (System.Exception) { return (result, false); } finally { cacheLock.ExitReadLock (); } } /// <summary> /// 异步取缓存值 /// </summary> /// <param name="guid">guid(唯一标识)</param> /// <returns>数据值;是否成功</returns> public async Task<(T, bool)> AsynGetValue (string guid) { return await Task.Run (() => { return GetValue (guid); }); } /// <summary> /// 更新缓存值 /// </summary> /// <param name="guid">guid(委托编号)</param> /// <param name="value">需要更新的值</param> /// <returns>是否更新成功</returns> public bool UpdateValue (string guid, T value) { if (string.IsNullOrEmpty (guid)) return false; if (globalDictionary.TryGetValue (guid, out var result)) { globalDictionary[guid] = value; cacheLock.EnterWriteLock (); try { return Utility.SaveCache (globalDictionary, CacheName, FileMode.Create); } catch (System.Exception e) { return false; } finally { cacheLock.ExitWriteLock (); } } else { return false; } } /// <summary> /// 异步更新缓存值 /// </summary> /// <param name="guid">guid(委托编号)</param> /// <param name="value">需要更新的值</param> /// <returns>是否更新成功</returns> public async Task<bool> AsynUpdateValue (string guid, T value) { return await Task.Run (() => { return UpdateValue (guid, value); }); } /// <summary> /// 删除缓存值 /// </summary> /// <param name="guid">guid(唯一标识)</param> /// <returns>是否成功</returns> public bool DeleteValue (string guid) { if (string.IsNullOrEmpty (guid)) return false; cacheLock.EnterWriteLock (); if (globalDictionary.Remove (guid)) { try { return Utility.SaveCache (globalDictionary, CacheName, FileMode.Create); } catch (System.Exception ex) { throw ex; } finally { cacheLock.ExitWriteLock (); } } cacheLock.EnterWriteLock (); return false; } /// <summary> /// 异步删除缓存值 /// </summary> /// <param name="guid">guid(唯一标识)</param> /// <returns>是否成功</returns> public async Task<bool> AsynDeleteValue (string guid) { return await Task.Run (() => { return DeleteValue (guid); }); } /// <summary> /// 删除集合数据,并且删除本地缓存 /// </summary> /// <returns>删除结果</returns> public bool Flush () { if (globalDictionary?.Count () > 0) { cacheLock.EnterWriteLock (); globalDictionary.Clear (); try { return Utility.SaveCache (globalDictionary, CacheName, FileMode.Create); } catch (System.Exception ex) { throw ex; } finally { cacheLock.ExitWriteLock (); } } return false; } #region 私有方法 private void RegisterTimeCheck () { expiredTimer = new System.Timers.Timer (CheckTime * 1000); expiredTimer.Elapsed += OnTimedEvent; expiredTimer.AutoReset = true; expiredTimer.Enabled = true; } private void OnTimedEvent (Object source, ElapsedEventArgs e) { List<string> clear_list = new List<string> (); foreach (string keyColl in globalDictionary.Keys) { var key_dt = Utility.GetEndSubString (keyColl, '|'); if (string.IsNullOrEmpty (key_dt)) continue; var data_dt = Convert.ToDateTime (key_dt); if (data_dt >= DateTime.Now) continue; if (Utility.TimeSecondsDiff (data_dt, DateTime.Now) >= 0) clear_list.Add (keyColl); } bool isClear = false; foreach (string keyColl in clear_list) { isClear = globalDictionary.Remove (keyColl); //Console.WriteLine ($"Key:{keyColl} is expired"); } if (isClear) { cacheLock.EnterWriteLock (); try { Utility.SaveCache (globalDictionary, CacheName, FileMode.Create); } catch (System.Exception ex) { Console.WriteLine ("save cache error,info=", ex.Message); //throw ex; } finally { cacheLock.ExitWriteLock (); } } } #endregion } }
95b1ac60bf35cf4f3fa56301e5bbdf575ef5b4ee
C#
bubdm/Pyro
/Library/Language/RhoLang/Parser/RhoAstFactory.cs
2.625
3
namespace Pyro.RhoLang.Parser { using System.Collections.Generic; using Language; using Lexer; /// <inheritdoc /> /// <summary> /// Make RhoAstNodes with various arguments. /// Required because C# doesn't allow template types to /// take parameters for constructors. /// Also, because Enums in C# can only derive from System.Enum. /// </summary> public class RhoAstFactory : IAstFactory<RhoToken, RhoAstNode, ERhoAst> { public void AddChild(RhoAstNode parent, RhoAstNode node) => parent.Children.Add(node); public RhoAstNode New(RhoToken t) => new RhoAstNode(ERhoAst.TokenType, t); public RhoAstNode New(ERhoAst e, RhoToken t) => new RhoAstNode(e, t); public RhoAstNode New(ERhoAst t) => new RhoAstNode(t); public IList<RhoAstNode> GetChildren(RhoAstNode node) => node.Children; } }
9763a05dad009022dadd454d71165ae9f1752822
C#
benny502/2OG
/2og_logic_pack/2og_logic_pack/Logic.cs
2.9375
3
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace _2og_logic_pack { class Logic { //文本数 private int _count; public int count { get { return _count; } } private int _txtEntry; public int txtEntry { get { return _txtEntry;} } //索引入口 private int _Entry; public int Entry { get { return _Entry; } } // 文本指针 public int[] pointers { get; set; } //数据长度 private int _length; public int length { get { return _length; } } private byte[] _data; public byte[] data { set { _data = value; _length = data.Length; } get { return _data; } } //文本开始位置 public int start { get { return pointers[0] + txtEntry; } } //文本结束位置 public int end { get { return pointers[pointers.Length - 1] + txtEntry; } } public Logic(string path) { // TODO: Complete member initialization if (!File.Exists(path)) throw new Exception("未检测到对应的原文件"); FileHelper helper = new FileHelper(path); data = helper.GetBytes(); _count = getCount(); pointers = getPointers(); } public int getCount() { using (BinaryReader reader = FileHelper.GetMemoryReader(data)) { reader.BaseStream.Seek(0x40, SeekOrigin.Begin); int l1 = FileHelper.SwapEndian(reader.ReadInt32()); reader.BaseStream.Seek(0x50, SeekOrigin.Begin); int l2 = FileHelper.SwapEndian(reader.ReadInt32()); return l1 + l2; } } public int[] getPointers() { using (BinaryReader reader = FileHelper.GetMemoryReader(data)) { reader.BaseStream.Seek(0x3C, SeekOrigin.Begin); _Entry = FileHelper.SwapEndian(reader.ReadInt32()); reader.BaseStream.Seek(0x4C, SeekOrigin.Begin); _txtEntry = FileHelper.SwapEndian(reader.ReadInt32()); reader.BaseStream.Seek(_Entry, SeekOrigin.Begin); int[] pointers = new int[_count]; for (int i = 0; i < _count; i++) { pointers[i] = FileHelper.SwapEndian(reader.ReadInt32()); } return pointers; } } public void Import(string[] strs, Dictionary<string, string> tbl) { using (BinaryWriter writer = FileHelper.GetMemoryWriter(data)) { byte[] buffer = new byte[end - start]; writer.Seek(start, SeekOrigin.Begin); writer.Write(buffer); writer.Flush(); writer.Seek(start, SeekOrigin.Begin); FileHelper helper = new FileHelper(); for (int i = 0; i < strs.Length; ++i) { pointers[i] = Convert.ToInt32(writer.BaseStream.Position) - _txtEntry; writer.Write(helper.Trans(strs[i], tbl)); byte zero = 0; writer.Write(zero); } writer.Flush(); } } public void UpdatePointers() { using (BinaryWriter writer = FileHelper.GetMemoryWriter(data)) { writer.BaseStream.Seek(_Entry, SeekOrigin.Begin); foreach (var pointer in pointers) { writer.Write(FileHelper.SwapEndian(pointer)); } writer.Flush(); } } public void WriteToBin(string path) { FileHelper helper = new FileHelper(); helper.Write(path, data); } } }
65e6a0bd94a3e0ec75277e5b65cdfbe323bdb574
C#
4373/timesheet
/TimeSheet/UsrUI/MyTextBox.cs
2.796875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TimeSheet.UsrUI { public partial class MyTextBox : UserControl { //[Description("通过设置字体大小来调节行高")] //[DefaultValue(12)] //public int FontSize { get; set{ this.textBox1.Font= new Font (} // ; } public MyTextBox() { InitializeComponent(); } public void SetText(string text) { this.textBox1.Text = text; } public void Clear() { this.textBox1.Text=string.Empty; } public event Action<string> OnMyTextChange; public string GetText() { return this.textBox1.Text; } protected override void OnPaint(PaintEventArgs e) { this.Height = 23; this.textBox1.Width = this.Width; this.textBox1.Height = this.Height-5; //GDI+绘图 e.Graphics.DrawLine(new Pen(Brushes.Black,2), new Point(0, this.Height), new Point(this.Width, this.Height)); this.textBox1.BackColor = this.BackColor; } public void textBox1_TextChanged(object sender, EventArgs e) { if (OnMyTextChange!=null) { OnMyTextChange(this.textBox1.Text); } } } }
43ef520b0e49059e24139309d45f936a9ef5058a
C#
shendongnian/download4
/code9/1520511-47837289-173829147-1.cs
4.03125
4
class Program { static void Main(String[] args) { // By using extension methods if ( "Hello world".ContainsAll(StringComparison.CurrentCultureIgnoreCase, "Hello", "world") ) Console.WriteLine("Found everything by using an extension method!"); else Console.WriteLine("I didn't"); // By using a single method if ( ContainsAll("Hello world", StringComparison.CurrentCultureIgnoreCase, "Hello", "world") ) Console.WriteLine("Found everything by using an ad hoc procedure!"); else Console.WriteLine("I didn't"); } private static Boolean ContainsAll(String str, StringComparison comparisonType, params String[] values) { return values.All(s => s.Equals(s, comparisonType)); } } // Extension method for your convenience internal static class Extensiones { public static Boolean ContainsAll(this String str, StringComparison comparisonType, params String[] values) { return values.All(s => s.Equals(s, comparisonType)); } }
069f72c40a7eccecd2c20f1e9398ef5844f5394d
C#
datvm/Training-WebMonitor
/WebMonitor.ServiceCore/WebMonitorService.cs
2.515625
3
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using WebMonitor.ServiceCore.Services; namespace WebMonitor.ServiceCore { public class WebMonitorService : IDisposable { private CancellationTokenSource cts; public void Start() { this.cts = new CancellationTokenSource(); Task.Run(DoServiceWork); } private async Task DoServiceWork() { while (!cts.IsCancellationRequested) { try { IMonitorService monitorService = null; var delay = await monitorService.PerformMonitorAsync(); await Task.Delay(delay); } catch (Exception ex) { Trace.TraceError(ex.ToString()); await Task.Delay(1000); } } } public void Dispose() { this.cts.Cancel(); } } }
63bc1e8f0d0d1164d8368105e45782c154d099a6
C#
WokeGames/transcendance
/Scripts/CSharp/Biomes.cs
2.53125
3
using Godot; using Godot.Collections; using System.Collections.Generic; using System; using System.Linq; using System.Text; using System.Threading.Tasks; using Array = Godot.Collections.Array; namespace RogueCity.Scripts.CSharp { public class Biomes : Node2D { public GroundTileScript[] tiles; [Export] public int size = 0; public Biomes () { tiles = new GroundTileScript[1]; } public override void _Ready() { var biomes = GetChildren(); Array[] tilesTemp = new Array[biomes.Count]; int index = 0; int count = 0; foreach (var b in biomes.OfType<Node2D>()) { tilesTemp[index] = b.GetChildren(); count += tilesTemp[index].Count; index++; } tiles = new GroundTileScript[count]; index = 0; foreach (var gts in tilesTemp.OfType<GroundTileScript>()) { tiles[index] = gts; } size = tiles.Count(); GD.Print(size); } // // Called every frame. 'delta' is the elapsed time since the previous frame. // public override void _Process(float delta) // { // // } } }
e1846c77c56950c56be2a6b13a617d39b628d8d1
C#
thinhpham/thp.aws.library
/Thp.Aws.Utility/CryptographyUtility.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; namespace Thp.Har.Utility { public static class CryptographyUtility { #region Hash public static string ComputeHash(string value) { return ComputeHash(value, false); } public static string ComputeHash(string value, bool returnFriendlyString) { string result = String.Empty; if (!string.IsNullOrEmpty(value)) { HashAlgorithm hashAlgorithm = new SHA512CryptoServiceProvider(); byte[] bytesToHash = UnicodeEncoding.ASCII.GetBytes(value); byte[] hashedBytes = hashAlgorithm.ComputeHash(bytesToHash); if (hashedBytes != null) { if (returnFriendlyString) { for (int i = 0; i < hashedBytes.Length; i++) { result += string.Format("{0:X2}", hashedBytes[i]); } } else { result = Convert.ToBase64String(hashedBytes); } } } return result; } public static string CreatePassword(string plainString) { // Convert the string password value to a byte array byte[] plainData = UnicodeEncoding.ASCII.GetBytes(plainString); // Create a 4-byte salt using a cryptographically secure random number generator byte[] saltData = new byte[4]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(saltData); // Append the salt to the end of the password byte[] saltPlusPasswordData = new byte[plainData.Length + saltData.Length]; Array.Copy(plainData, 0, saltPlusPasswordData, 0, plainData.Length); Array.Copy(saltData, 0, saltPlusPasswordData, plainData.Length, saltData.Length); // Create a new SHA instance and compute the hash HashAlgorithm hashAlgorithm = new SHA512CryptoServiceProvider(); byte[] hashData = hashAlgorithm.ComputeHash(saltPlusPasswordData); // Add salt bytes onto end of the password hash for storage byte[] hashPlusSaltData = new byte[hashData.Length + saltData.Length]; Array.Copy(hashData, 0, hashPlusSaltData, 0, hashData.Length); Array.Copy(saltData, 0, hashPlusSaltData, hashData.Length, saltData.Length); // Return the string data return Convert.ToBase64String(hashPlusSaltData); } public static bool ComparePassword(string plainString, string passwordString) { bool result = false; try { // First, pluck the four-byte salt off of the end of the hash byte[] saltData = new byte[4]; byte[] hashPlusSaltData = Convert.FromBase64String(passwordString); Array.Copy(hashPlusSaltData, hashPlusSaltData.Length - saltData.Length, saltData, 0, saltData.Length); // Convert Password to bytes byte[] plainData = UnicodeEncoding.ASCII.GetBytes(plainString); // Append the salt to the end of the password byte[] saltedPasswordData = new byte[plainData.Length + saltData.Length]; Array.Copy(plainData, 0, saltedPasswordData, 0, plainData.Length); Array.Copy(saltData, 0, saltedPasswordData, plainData.Length, saltData.Length); // Create a new SHA instance and compute the hash HashAlgorithm hashAlgorithm = new SHA512CryptoServiceProvider(); byte[] newHashData = hashAlgorithm.ComputeHash(saltedPasswordData); // Tack salt bytes onto end of the password hash for comparison byte[] newHashPlusSaltData = new byte[newHashData.Length + saltData.Length]; Array.Copy(newHashData, 0, newHashPlusSaltData, 0, newHashData.Length); Array.Copy(saltData, 0, newHashPlusSaltData, newHashData.Length, saltData.Length); // Compare and return result = (Convert.ToBase64String(hashPlusSaltData).Equals(Convert.ToBase64String(newHashPlusSaltData))); } catch { result = false; } return result; } #endregion #region Encryption public static string EncryptString(string plaintext, byte[] key, bool useHexString) { // The default AES key size under the .NET framework is 256. The following // call will create an AES crypto provider and create a random initialization // vector and key. The crypto mode defaults to CBC ensuring the proper chaining // of data to mitigate repetition of cipher text blocks. string ciphertext = ""; RijndaelManaged rij = new RijndaelManaged(); //Create an AES encryptor from the AES instance. ICryptoTransform aesencrypt = rij.CreateEncryptor(key, rij.IV); //Create crypto stream set to read and do an AES encryption transform on incoming bytes. MemoryStream ms = new MemoryStream(); CryptoStream cipherstream = new CryptoStream(ms, aesencrypt, CryptoStreamMode.Write); // Encrypt byte[] bytearrayinput = UnicodeEncoding.ASCII.GetBytes(plaintext); cipherstream.Write(bytearrayinput, 0, bytearrayinput.Length); cipherstream.FlushFinalBlock(); cipherstream.Close(); // Create a byte array to store our encrypted value plus IV ms.Flush(); byte[] encryptedValueWithIV = new byte[rij.IV.Length + ms.ToArray().Length]; Array.Copy(rij.IV, encryptedValueWithIV, rij.IV.Length); Array.Copy(ms.ToArray(), 0, encryptedValueWithIV, rij.IV.Length, ms.ToArray().Length); // Return encrypted string if (useHexString) { ciphertext = ByteArrayToHexString(encryptedValueWithIV); } else { ciphertext = Convert.ToBase64String(encryptedValueWithIV); } ms.Close(); return ciphertext; } public static string DecryptString(string ciphertext, byte[] key, bool useHexString) { // The default AES key size under the .NET framework is 256. The following // call will create an AES crypto provider and create a random initialization // vector and key. The crypto mode defaults to CBC ensuring the proper chaining // of data to mitigate repetition of cipher text blocks. string decryptedtext = ""; RijndaelManaged rij = new RijndaelManaged(); //Because the input string is passed in as a Base64 encoded value we decode prior writing to //the decryptor stream. byte[] encryptedValueWithIV = null; if (useHexString) { encryptedValueWithIV = HexStringToByteArray(ciphertext); } else { encryptedValueWithIV = Convert.FromBase64String(ciphertext); } byte[] iv = new byte[16]; byte[] encrypted = new byte[encryptedValueWithIV.Length - 16]; Array.Copy(encryptedValueWithIV, iv, 16); Array.Copy(encryptedValueWithIV, iv.Length, encrypted, 0, encrypted.Length); //Create an AES decryptor from the AES instance. ICryptoTransform aesdecrypt = rij.CreateDecryptor(key, iv); //Create a memorystream to which we'll decrypt our input string MemoryStream ms = new MemoryStream(); CryptoStream ecs = new CryptoStream(ms, aesdecrypt, CryptoStreamMode.Write); ecs.Write(encrypted, 0, encrypted.Length); ecs.FlushFinalBlock(); ecs.Close(); // Return decrypted string ms.Flush(); decryptedtext = UnicodeEncoding.ASCII.GetString(ms.ToArray()); ms.Close(); return decryptedtext; } #endregion #region Helper Methods public static string GenerateHMAC(string input, string secret) { // Instantiate the HMAC class HMACSHA256 hmac = new HMACSHA256(); try { // We pass in a user supplied password to generate a strong key to be used in our HMAC // since people tend to use weak and potentially dictionary values for keys. // Using the PasswordDerivedBytes helps to mitigate the risk of dictionary attacks // on our HMAC key // In the current implementation, regardless of the salt passed to the PasswordDeriveBytes // constructor the same derived password will be generated. PasswordDeriveBytes pdb = new PasswordDeriveBytes(secret, null); byte[] pbytes = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }); hmac.Key = pbytes; } catch (Exception e) { Console.Error.WriteLine(e.ToString()); } return UnicodeEncoding.ASCII.GetString(hmac.ComputeHash(UnicodeEncoding.ASCII.GetBytes(input))); } public static int GenerateRandomNumber() { // Create a secure RNG class and a byte array to hold the random data RNGCryptoServiceProvider secureRandom = new RNGCryptoServiceProvider(); byte[] randBytes = new byte[4]; // Generate 4 bytes of secure random number data and convert to 4-byte integer secureRandom.GetNonZeroBytes(randBytes); return (BitConverter.ToInt32(randBytes, 0)); } public static byte[] GenerateRandomSalt(int length) { // Create a buffer byte[] randBytes; if (length >= 1) { randBytes = new byte[length]; } else { randBytes = new byte[1]; } // Create a new RNGCryptoServiceProvider. RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider(); rand.GetBytes(randBytes); // return the bytes. return randBytes; } public static string GenerateRandomKey(int length) { byte[] buff = new byte[length]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(buff); StringBuilder sb = new StringBuilder(length * 2); for (int i = 0; i < buff.Length; i++) { sb.Append(string.Format("{0:X2}", buff[i])); } return sb.ToString(); } public static string GetHexRepresentation(string val) { if (string.IsNullOrEmpty(val)) return null; byte[] buff = UnicodeEncoding.ASCII.GetBytes(val); StringBuilder sb = new StringBuilder(buff.Length * 2); for (int i = 0; i < buff.Length; i++) { sb.Append(string.Format("{0:X2}", buff[i])); } return sb.ToString(); } public static string ByteArrayToHexString(byte[] val) { StringBuilder sb = new StringBuilder(val.Length * 2); for (int i = 0; i < val.Length; i++) { sb.Append(string.Format("{0:X2}", val[i])); } return sb.ToString(); } public static byte[] HexStringToByteArray(string val) { int numchars = val.Length; byte[] bytes = new byte[numchars / 2]; for (int i = 0; i < numchars; i += 2) { try { bytes[i / 2] = Convert.ToByte(val.Substring(i, 2), 16); } catch { bytes[i / 2] = 0; } } return bytes; } public static void ClearBytes(byte[] buffer) { // Check arguments. if (buffer == null) { throw new ArgumentException("Buffer"); } // Set each byte in the buffer to 0. for (int x = 0; x <= buffer.Length - 1; x++) { buffer[x] = 0; } } public static string GenerateASPNET20MachineKey() { string key64byte = GenerateRandomKey(64); string key32byte = GenerateRandomKey(32); StringBuilder aspnet20machinekey = new StringBuilder(); aspnet20machinekey.AppendFormat("<machineKey validationKey=\"{0}\" decryptionKey=\"{1}\" validation=\"SHA1\" decryption=\"AES\" />", key64byte, key32byte); return aspnet20machinekey.ToString(); } public static string GenerateASPNET11MachineKey() { string key64byte = GenerateRandomKey(64); string key24byte = GenerateRandomKey(24); StringBuilder aspnet11machinekey = new StringBuilder(); aspnet11machinekey.AppendFormat("<machineKey validationKey=\"{0}\" decryptionKey=\"{1}\" validation=\"SHA1\" />", key64byte, key24byte); return aspnet11machinekey.ToString(); } #endregion } }
6bd17b47144f412ec7ada1f25111a177c0453678
C#
DomideAdrian/Tema_Restaurant
/ClientApp/Restaurant/WriteMessage.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Restaurant { class WriteMessage { public string WeldPhrase(string flag, List<string> weldWord) { string message = flag + ";"; foreach(var element in weldWord) { message = message + element + ";"; } return message; } } }
8a140afad377ae8ab16ce03168fad73454f2a1af
C#
linekerpablo/TesteWTime
/TesteWTime.Infra/Repositories/UrlsRepository.cs
2.53125
3
using TesteWTime.Domain.Entities; using System.Collections.Generic; using TesteWTime.Domain.Interfaces; using System.Linq; using System.Data.SqlClient; using System.Text; using Newtonsoft.Json.Linq; using System; using Newtonsoft.Json; namespace TesteWTime.Infra.Repositories { public class UrlsRepository : RepositoryBase<Urls>, IUrlsRepository { #region Methods public Urls GetByUrlId(Int64 urlid) { return Db.Urlss.Where(p => p.UrlId.Equals(urlid)).FirstOrDefault(); } public Urls GetByHits(Byte hits) { return Db.Urlss.Where(p => p.Hits.Equals(hits)).FirstOrDefault(); } public Urls GetByUrl(String url) { return Db.Urlss.Where(p => p.Url.Equals(url)).FirstOrDefault(); } public Urls GetByShortUrl(String shorturl) { return Db.Urlss.Where(p => p.ShortUrl.Equals(shorturl)).FirstOrDefault(); } public bool ValidatedRequiredFields() { return false; } public string GetStats() { //Create the command SqlCommand objCmd = new SqlCommand(); //Open the connection StringBuilder commandSql = new StringBuilder(@"select sum(hits) as hits, count(UrlId) as urlCount, (select top 10 * from Urls order by Hits desc for json auto) as topUrls from urls for json auto"); objCmd.CommandText = commandSql.ToString(); objCmd.Connection = new SqlConnection { ConnectionString = Utilities.Utilities.ConnectionString }; objCmd.Connection.Open(); SqlDataReader sqlDataReader = objCmd.ExecuteReader(); string json = null; while (sqlDataReader.Read()) { json = sqlDataReader.GetValue(0).ToString(); } objCmd.Connection.Close(); return json; } #endregion } }
a395498409f8428909450a0b8eeee44e498570e0
C#
shendongnian/download4
/first_version_download2/80354-5198495-11081426-2.cs
3.09375
3
internal class ParseXML { public static xsdClass ToClass<xsdClass>(XElement ResponseXML) { return deserialize<xsdClass>(ResponseXML.ToString(SaveOptions.DisableFormatting)); } private static result deserialize<result>(string XML) { using (TextReader textReader = new StringReader(XML)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(result)); return (result) xmlSerializer.Deserialize(textReader); } } }
43ea7922a07a88699e312c1364dbff0e18305683
C#
audinowho/RogueElements
/RogueElements/MapGen/Rooms/RoomGenBump.cs
2.5625
3
// <copyright file="RoomGenBump.cs" company="Audino"> // Copyright (c) Audino // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System; using System.Collections.Generic; namespace RogueElements { /// <summary> /// Generates a rectangular room with the specified width and height, and with the tiles at the perimeter randomly blocked. /// </summary> /// <typeparam name="T"></typeparam> [Serializable] public class RoomGenBump<T> : PermissiveRoomGen<T>, ISizedRoomGen where T : ITiledGenContext { public RoomGenBump() { } public RoomGenBump(RandRange width, RandRange height, RandRange bumpPercent) { this.Width = width; this.Height = height; this.BumpPercent = bumpPercent; } protected RoomGenBump(RoomGenBump<T> other) { this.Width = other.Width; this.Height = other.Height; this.BumpPercent = other.BumpPercent; } /// <summary> /// Width of the room. /// </summary> public RandRange Width { get; set; } /// <summary> /// Height of the room. /// </summary> public RandRange Height { get; set; } /// <summary> /// Chance of a block tile at the room's perimeter. /// </summary> public RandRange BumpPercent { get; set; } public override RoomGen<T> Copy() => new RoomGenBump<T>(this); public override Loc ProposeSize(IRandom rand) { return new Loc(this.Width.Pick(rand), this.Height.Pick(rand)); } public override void DrawOnMap(T map) { // add peturbations if (this.Draw.Size.X > 2 && this.Draw.Size.Y > 2) { int tlTotal = (this.Draw.Size.X - 1) / 2 * this.BumpPercent.Pick(map.Rand) / 100; int blTotal = (this.Draw.Size.X - 1) / 2 * this.BumpPercent.Pick(map.Rand) / 100; int trTotal = (this.Draw.Size.X - 1) / 2 * this.BumpPercent.Pick(map.Rand) / 100; int brTotal = (this.Draw.Size.X - 1) / 2 * this.BumpPercent.Pick(map.Rand) / 100; int ltTotal = (this.Draw.Size.Y - 1) / 2 * this.BumpPercent.Pick(map.Rand) / 100; int rtTotal = (this.Draw.Size.Y - 1) / 2 * this.BumpPercent.Pick(map.Rand) / 100; int lbTotal = (this.Draw.Size.Y - 1) / 2 * this.BumpPercent.Pick(map.Rand) / 100; int rbTotal = (this.Draw.Size.Y - 1) / 2 * this.BumpPercent.Pick(map.Rand) / 100; for (int x = 0; x < this.Draw.Size.X; x++) { for (int y = 0; y < this.Draw.Size.Y; y++) { if ((y != 0 || (x >= tlTotal && x < this.Draw.Size.X - trTotal)) && (y != this.Draw.Size.Y - 1 || (x >= blTotal && x < this.Draw.Size.X - brTotal)) && (x != 0 || (y >= ltTotal && y < this.Draw.Size.Y - lbTotal)) && (x != this.Draw.Size.X - 1 || (y >= rtTotal && y < this.Draw.Size.Y - rbTotal))) map.SetTile(new Loc(this.Draw.X + x, this.Draw.Y + y), map.RoomTerrain.Copy()); } } } else { for (int x = 0; x < this.Draw.Size.X; x++) { for (int y = 0; y < this.Draw.Size.Y; y++) map.SetTile(new Loc(this.Draw.X + x, this.Draw.Y + y), map.RoomTerrain.Copy()); } } // fulfill existing borders since this room doesn't cover the entire square this.FulfillRoomBorders(map, false); // hall restrictions this.SetRoomBorders(map); } public override string ToString() { return string.Format("{0}: {1}x{2}", this.GetType().GetFormattedTypeName(), this.Width, this.Height); } } }
d8a6bc775b9de868a31793f6d234e94cbd6f5a27
C#
MichalTichy/aGrader
/CAC/TestResult.cs
2.671875
3
#region using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using aGrader.Mathematic; using aGrader.Properties; #endregion namespace aGrader { public class TestResultArgs : EventArgs { public TestResult Result { get; set; } } public class TestResult { private List<string> _errors; private List<string> _outputs; private List<object> _expectedOutputs; private List<int> _badOutputs=new List<int>(); private Queue<string> _realOutputs; public ReadOnlyCollection<string> Errors { get { return _errors.AsReadOnly(); } } public ReadOnlyCollection<string> Outputs { get { return _outputs.AsReadOnly(); } } public int CorrectOutputsCount => _errors.Count == 0 ? _expectedOutputs.Count - _badOutputs.Count : 0; public int WrongOutputsCount => _errors.Count == 0 ? _badOutputs.Count : _expectedOutputs.Count; public ReadOnlyCollection<object> ExpectedOutputs { get { return _expectedOutputs.AsReadOnly(); } } public ReadOnlyCollection<int> BadOutputs { get { return _badOutputs.AsReadOnly(); } } public readonly string FileName; public bool? IsOk { get; private set; } public readonly double ProcessorTime; public readonly TestProtocol Protocol; public TestResult() { _errors=new List<string>(); } public TestResult(string fileName, TestProtocol protocol, List<string> outputs, List<string> errors, double procesorTime) { FileName = fileName; Protocol = protocol; _outputs = outputs; _errors = errors; _expectedOutputs=new List<object>(); _expectedOutputs.AddRange(protocol.Outputs); ProcessorTime = procesorTime; EvaluateResults(); } private void EvaluateResults() { _realOutputs=new Queue<string>(_outputs); foreach (dynamic expectedOutput in _expectedOutputs) { var realOutput = _realOutputs.Dequeue(); if (string.IsNullOrEmpty(realOutput) || !CompareRealAndExpectedOutput(realOutput,expectedOutput)) { _badOutputs.Add(_outputs.Count-_realOutputs.Count-1); //add id of last deleted item } } IsOk = (_errors == null || _errors.Count == 0) && (_badOutputs == null || _badOutputs.Count == 0); } private bool CompareRealAndExpectedOutput(string realOutput, TextData expectedOutput) { return realOutput == expectedOutput.Data; } private bool CompareRealAndExpectedOutput(string realOutput, NumberData expectedOutput) { //removes formating realOutput = realOutput.Replace('.', ','); NumberFormatInfo numberFormats = CultureInfo.CurrentCulture.NumberFormat; if (expectedOutput.ToString().Contains(numberFormats.PositiveInfinitySymbol) || expectedOutput.ToString().Contains(numberFormats.NegativeInfinitySymbol)) return false; try { return Math.Abs(decimal.Parse(realOutput) - decimal.Parse(expectedOutput.ToString())) <= (decimal)Protocol.MaximumDeviation; } catch (Exception) { _errors.Add(string.Format(Resources.TestResult_CannotConvertNumber, realOutput)); ExceptionsLog.LogException($"Cannot convert {realOutput} to number."); return false; } } private bool CompareRealAndExpectedOutput(string realOutput, NumberMatchingConditionsData expectedOutput) { //removes formating realOutput = realOutput.Replace('.', ','); var value = decimal.Parse(realOutput); return expectedOutput.Conditions.All(condition => new BooleanExpresion(condition, value).Evaluate()); } private bool CompareRealAndExpectedOutput(string realOutput, FileHashData data) { return realOutput == data.ToString(); } private bool CompareRealAndExpectedOutput(string realOutput, LineFromTextFileData data) { return realOutput == data.ToString(); } private bool CompareRealAndExpectedOutput(string realOutput, ErrorData expectedOutput) { return false; } public void AddErrors(string error, bool insertAtTheBegining=false) { if (string.IsNullOrEmpty(error)) return; if (insertAtTheBegining) { _errors.InsertRange(0,error.Split('\n')); } else { _errors.AddRange(error.Split('\n')); } IsOk = (_errors == null || _errors.Count == 0) && (_badOutputs == null || _badOutputs.Count == 0); } } }
2db595ad792919e4e3c1864a2a57b0b96fd38562
C#
TS-Patterns/identify-valid-objects-and-design-low-level-design-sundeep-a-s
/Assignment-Day 4/VisitorPattern/VisitorPattern/DocumentConverters/PdfConverter.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VisitorPattern.interfaces; using VisitorPattern.Models; namespace VisitorPattern.DocumentConverters { public class PdfConverter:IDocumentConverter { public void Convert(Paragraph paragraph) { Console.WriteLine("Convert paragraph to PDF"); } public void Convert(Header header) { Console.WriteLine("Convert header to PDF"); } public void Convert(Footer footer) { Console.WriteLine("Convert footer to PDF"); } public void Convert(HyperLink hyperLink) { Console.WriteLine("Convert html to PDF"); } } }
e599b8e5208246ef4fe7a02a8b020eca3661be3d
C#
azniv/Snakes
/WindowsFormsApp13/Snake.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApp13 { public class Snake { string direction = "right"; string nextDirection = "right"; delegate string Directions(EventArgs e); // В лист записываем сегменты змейкм List<Figure> snake = new List<Figure>() { new Figure(7,5), new Figure(6,5), new Figure(5,5) }; Figure head = new Figure(); Figure newHead = new Figure(); // Создаем новую голову и добавляем ее к началу змейки, // чтобы передвинуть змейку в текущем направлении public void Move(Fruits fruit) { head = snake[0]; direction = nextDirection; if (direction == "right") { newHead = new Figure(head.Col + 1, head.Row); } else if (direction == "down") { newHead = new Figure(head.Col, head.Row + 1); } else if (direction == "left") { newHead = new Figure(head.Col - 1, head.Row); } else if (direction == "up") { newHead = new Figure(head.Col, head.Row - 1); } // Если врезались, то конец игры if (CheckCollision()) { GameOver(); return; } snake.Insert(0, newHead); //если съели фрукт, то увеличиваем очки if (newHead.Equal(fruit)) { Game.score++; fruit.Move(); } else { snake.RemoveAt(snake.Count - 1); } } // Задаем следующее направление движения змейки на основе нажатой клавиши public void SetDirection(string newDirection) { if (direction == "up" && newDirection == "down") { return; } else if (direction == "right" && newDirection == "left") { return; } else if (direction == "down" && newDirection == "up") { return; } else if (direction == "left" && newDirection == "right") { return; } nextDirection = newDirection; } // Рисуем квадрат для каждого сегмента тела змейки public void DrawSnake(Graphics graphics) { foreach (var s in snake) { s.DrawSquare(graphics); } } public void Restart() { direction = "right"; nextDirection = "right"; snake.Clear(); snake.Add(new Figure(7, 5)); snake.Add(new Figure(6, 5)); snake.Add(new Figure(5, 5)); Game.score = 0; } // Проверяем, не столкнулась ли змейка со стеной или собственным телом public bool CheckCollision() { var leftCollision = (newHead.Col < 1); var topCollision = (newHead.Row < 1); var rightCollision = (newHead.Col == Game.widthInBlocks); var bottomCollision = (newHead.Row == Game.heightInBlocks); var wallCollision = leftCollision || topCollision || rightCollision || bottomCollision; var selfCollision = false; foreach (var s in snake) { if (newHead.Equal(s)) selfCollision = true; } return wallCollision || selfCollision; } //Конец игры public void GameOver() { var result = MessageBox.Show("Вы проиграли :( \nНажмите ОК, чтобы начать заново ", "", MessageBoxButtons.OK); if (result == DialogResult.OK) { Restart(); return; } } } } //22,24,5,7,8,17
8dbe3d1d0fef06324ba30b97544d0deae69b94ac
C#
shendongnian/download4
/code4/657767-15680626-38208135-2.cs
2.75
3
List<Item> items = new List<Item>(); items.Add(new Item() { Id = 1, ParentId = 0 }); items.Add(new Item() { Id = 2, ParentId = 0 }); items.Add(new Item() { Id = 3, ParentId = 0 }); items.Add(new Item() { Id = 4, ParentId = 1 }); items.Add(new Item() { Id = 5, ParentId = 1 }); items.Add(new Item() { Id = 6, ParentId = 4 }); items.RemoveAll(input => items.Count(item => item.Id == input.ParentId) > 0); //those who remain // item with Id = 1 // item with Id = 2 // item with Id = 3
aaa5c0c1d12c2ec94d7c26926bc844e94f3b85ac
C#
sls1j/ExploreItGame
/ExploreItGame/Program.cs
2.703125
3
using System; using ExploreItGame.Nouns; using ExploreItGame.Verbs; using SDL2; namespace Hello { class Program { static void Main(string[] args) { if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0) { Console.WriteLine("Unable to initialize SDL. Error: {0}", SDL.SDL_GetError()); } else { var window = IntPtr.Zero; window = SDL.SDL_CreateWindow("Glummyl", SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, 1024, 800, SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE ); if (window == IntPtr.Zero) { Console.WriteLine("Unable to create a window. SDL. Error: {0}", SDL.SDL_GetError()); } else { IntPtr renderer = SDL.SDL_CreateRenderer(window, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED); SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG); GameState state = new GameState() { running = true }; state.grid = CollisionVerbs.GetGridBuilder(state.everything); SceneVerb.InitScene(renderer, state); const int frameRate = 60; const int frameDelay = 1000 / frameRate; while (state.running) { uint frameStart = SDL.SDL_GetTicks(); state.lastTime = state.time; state.time = (int)frameStart; InputVerbs.Execute(state.input); HeroVerbs.Update(state); Physics.Execute(state); SceneVerb.DrawScene(renderer, state); uint frameTime = SDL.SDL_GetTicks() - frameStart; if (frameDelay > frameTime) { uint delay = frameDelay - frameTime; SDL.SDL_Delay(delay); } if (state.input.isQuit) state.running = false; } } SDL.SDL_DestroyWindow(window); SDL.SDL_Quit(); } } } }