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
5fe1027dedd5bb24c309c84c0d6894d6b3b376de
C#
tdcoish/OGK_ChessSoftware
/OGK_Chess/Assets/Scripts/Board/DT_BD.cs
2.734375
3
/************************************************************************************* The board we play on. *************************************************************************************/ using UnityEngine; public static class PieceInfo{ public static uint _white = 1<<1; public static uint _black = 1<<2; public static uint _knight = 1<<3; public static uint _bishop = 1<<4; public static uint _rook = 1<<5; public static uint _queen = 1<<6; public static uint _king = 1<<7; public static uint _pawn = 1<<8; public static uint _noType = 1<<9; } public struct DT_BD { public DT_BD(int size = 8){ _Squares = new DT_SQ[8,8]; for(int y=0; y<8; y++){ for(int x=0; x<8; x++){ _Squares[x,y]._pos.x = x; _Squares[x,y]._pos.y = y; if((x+y)%2 == 1){ // if even then black, if odd then white _Squares[x,y]._COL = SQUARE_COLOUR.WHITE; }else{ _Squares[x,y]._COL = SQUARE_COLOUR.BLACK; } } } } public DT_SQ[,] _Squares; } public enum SQUARE_COLOUR{WHITE, BLACK}; public struct DT_SQ { public SQUARE_COLOUR _COL; public Vector2Int _pos; // Weird. This is the info for the piece on the square. Poor way of doing things. public uint _uInfo; }
1c9fd56fb74cdb0c02e20c1f8f2a427058435623
C#
mathiasuy/webservice
/Logica/LTipoTraslado.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EntidadesCompartidas; using ExcepcionesPersonalizadas; using Persistencia; namespace Logica { public class LTipoTraslado { //Buscar public static TipoTrasladoType BuscarTipoTraslado(int id) { TipoTrasladoType iva = PTipoTraslado.BuscarTipoTraslado(id); if (iva == null) { throw new ExcepcionesPersonalizadas.Logica("No se encontraron tipos de traslado con ese identificador"); } return iva; } //Alta public static void AltaTipoTraslado(TipoTrasladoType i) { ValidarTipoTraslado(i); int retorno = PTipoTraslado.AltaTipoTraslado(i); if (retorno == -1) { throw new ExcepcionesPersonalizadas.Logica("No se pudo dar de alta el tipo de traslado, ya hay uno con el mismo identificador"); } } //Baja public static void BajaTipoTraslado(int id) { int retorno = PTipoTraslado.BajaTipoTraslado(id); if (retorno == -1) { throw new ExcepcionesPersonalizadas.Logica("No se encontró un tipo de traslado con ese identificador"); } } //Modificar public static void ModificarTipoTraslado(TipoTrasladoType i) { ValidarTipoTraslado(i); int retorno = PTipoTraslado.ModificarTipoTraslado(i); if (retorno == -1) { throw new ExcepcionesPersonalizadas.Logica("No se encontró un tipo de traslado con ese identificador"); } } public static List<TipoTrasladoType> ListarTipoTraslado() { List<TipoTrasladoType> lista = PTipoTraslado.ListarTipoTraslado(); if (lista == null) { throw new ExcepcionesPersonalizadas.Logica("No se han encontrado tipos de traslado para listar"); } return lista; } //Listar public static void ValidarTipoTraslado(TipoTrasladoType i) { if (i == null) { throw new ExcepcionesPersonalizadas.Logica("No es un tipo de traslado válido"); } if (string.IsNullOrEmpty(i.Id.ToString()) || string.IsNullOrWhiteSpace(i.Id.ToString())) { throw new ExcepcionesPersonalizadas.Logica("Debe indicar un identificador"); } if (string.IsNullOrWhiteSpace(i.Nombre) || string.IsNullOrEmpty(i.Nombre)) { throw new ExcepcionesPersonalizadas.Logica("Debe indicar un Nombre"); } } } }
35623721ab235d453bd1e7c1b63c29846310ee51
C#
Noah-Garrett/csharp-exercises
/video-basics/Program.cs
3.453125
3
using System; namespace videobasics { class MainClass { public static void Main(string[] args) { string myString = "My \"so-called\" life"; string myString2 = "what if i need a \nnew line"; string myString3 = @"Go to your c:\ drive"; string myString4 = string.Format("{1} = {0}", "First", "Second"); string myString5 = string.Format("{0:C}", 123.45); string mystring6 = string.Format("{0:N}", 123456789); string mystring7 = string.Format("Percentage: {0:P}", .123); string myString8 = string.Format("Phone Number: {0:(###) ###-####}", 1234567890); string myString9 = "that summer we tok threes across the board"; //myString9 = myString.Substring(6,14); //myString9 = myString.ToUpper(); //myString9 = myString.Replace(" ", "--"); //myString9 = myString.Remove(6, 14); myString9 = string.Format("Length before: {0} -- length after: {1}", myString.Length, myString.Trim().Length); string myString10 = ""; for (int i = 0; i<100; i++) { myString10 += "--" + i.ToString(); } Console.WriteLine(myString); Console.WriteLine(myString2); Console.WriteLine(myString3); Console.WriteLine(myString4); Console.WriteLine(myString5); Console.WriteLine(mystring6); Console.WriteLine(mystring7); Console.WriteLine(myString8); Console.WriteLine(myString9); Console.ReadLine(); } } }
31f1b4960516d19f0137235a3540707af18043fe
C#
OlufemiFowosire-zz/PluralsightDesignPatternsPracticeCodes
/Patterns/TemplateMethod/TemplateMethod/TemplateMethod.Test/ColdVeggiePizzaServicePrepare.cs
2.640625
3
using System; using System.Collections.Generic; using System.Text; using Xunit; using Xunit.Abstractions; namespace TemplateMethod.Test { public class ColdVeggiePizzaServicePrepare { private readonly ITestOutputHelper output; public ColdVeggiePizzaServicePrepare(ITestOutputHelper output) { this.output = output; } [Fact] public void ReturnsAColdPizzaVeggie() { var logger = new LoggerAdapter(); var service = new ColdVeggiePizzaService(logger); var coldVeggiePizza = service.Prepare(); Assert.NotNull(coldVeggiePizza); output.WriteLine(logger.Dump()); } } }
c1f6d54dfd3fdd59e28b6cd4bd07f1f49c2180af
C#
kallDun/Google-Hash-Code
/Google Hash Code/Models/Car.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Google_Hash_Code { class Car { public List<Street> streets; public Street street_now; public int time_to_intersection; public Car(List<Street> street) { this.streets = street; street_now = street.First(); } } }
1ca486ad12b94498db0ac7e506cc8cd8cd9b4fe0
C#
jalex/VisioAutomation
/VisioAutomation_2010/VisioAutomation/Shapes/UserDefinedCellHelper.cs
2.5625
3
using System.Collections.Generic; using System.Linq; using VisioAutomation.Exceptions; using VisioAutomation.Extensions; using VisioAutomation.ShapeSheet; using IVisio = Microsoft.Office.Interop.Visio; namespace VisioAutomation.Shapes { public static class UserDefinedCellHelper { private static readonly short _udcell_section = ShapeSheet.SrcConstants.UserDefCellPrompt.Section; private static string GetRowName(string name) { return "User." + name; } public static void Delete(IVisio.Shape shape, string name) { if (shape == null) { throw new System.ArgumentNullException(nameof(shape)); } if (name == null) { throw new System.ArgumentNullException(nameof(name)); } UserDefinedCellHelper.CheckValidName(name); string full_prop_name = UserDefinedCellHelper.GetRowName(name); short row = shape.CellsU[full_prop_name].Row; shape.DeleteRow(_udcell_section, row); } public static void Set(IVisio.Shape shape, string name, string value, string prompt) { var cells = new UserDefinedCellCells(); cells.Value = value; cells.Prompt = prompt; cells.EncodeValues(); Set(shape, name, cells); } public static void Set(IVisio.Shape shape, string name, UserDefinedCellCells cells) { if (shape == null) { throw new System.ArgumentNullException(nameof(shape)); } if (cells == null) { throw new System.ArgumentNullException(nameof(cells)); } UserDefinedCellHelper.CheckValidName(name); if (UserDefinedCellHelper.Contains(shape, name)) { // The user-defined cell already exists string full_prop_name = UserDefinedCellHelper.GetRowName(name); if (cells.Value.HasValue) { string value_cell_name = full_prop_name; var cell = shape.CellsU[value_cell_name]; cell.FormulaU = cells.Value.Value; } if (cells.Prompt.HasValue) { string prompt_cell_name = full_prop_name + ".Prompt"; var cell = shape.CellsU[prompt_cell_name]; cell.FormulaU = cells.Prompt.Value; } } else { // The user-defined cell doesn't already exist short row = shape.AddNamedRow(_udcell_section, name, (short)IVisio.VisRowIndices.visRowUser); var src_value = new ShapeSheet.Src(_udcell_section, row, (short)IVisio.VisCellIndices.visUserValue); var src_prompt = new ShapeSheet.Src(_udcell_section, row, (short)IVisio.VisCellIndices.visUserPrompt); var writer = new VisioAutomation.ShapeSheet.Writers.SrcWriter(); if (cells.Value.HasValue) { writer.SetFormula(src_value, cells.Value.Value); } if (cells.Prompt.HasValue) { writer.SetFormula(src_prompt, cells.Prompt.Value); } writer.Commit(shape); } } public static Dictionary<string, UserDefinedCellCells> GetDictionary(IVisio.Shape shape, ShapeSheet.CellValueType type) { if (shape == null) { throw new System.ArgumentNullException(nameof(shape)); } var prop_count = UserDefinedCellHelper.GetCount(shape); if (prop_count < 1) { return new Dictionary<string, UserDefinedCellCells>(0); } var prop_names = UserDefinedCellHelper.GetNames(shape); if (prop_names.Count != prop_count) { throw new InternalAssertionException("Unexpected number of prop names"); } var shape_data = UserDefinedCellCells.GetCells(shape, type); var dic = new Dictionary<string,UserDefinedCellCells>(prop_count); for (int i = 0; i < prop_count; i++) { dic[prop_names[i]] = shape_data[i]; } return dic; } public static List<Dictionary<string, UserDefinedCellCells>> GetDictionary(IVisio.Page page, IList<IVisio.Shape> shapes, ShapeSheet.CellValueType type) { if (page == null) { throw new System.ArgumentNullException(nameof(page)); } if (shapes == null) { throw new System.ArgumentNullException(nameof(shapes)); } var shapeids = shapes.Select(s => s.ID).ToList(); var list_list_customprops = UserDefinedCellCells.GetCells(page,shapeids, CellValueType.Formula); var list_dic_customprops = new List<Dictionary<string, UserDefinedCellCells>>(shapeids.Count); for (int shape_index = 0; shape_index < shapes.Count; shape_index++) { var shape = shapes[shape_index]; var list_customprops = list_list_customprops[shape_index]; var prop_names = UserDefinedCellHelper.GetNames(shape); var dic_customprops = new Dictionary<string, UserDefinedCellCells>(list_customprops.Count); list_dic_customprops.Add(dic_customprops); for (int i = 0; i < list_customprops.Count ; i++) { var prop_name = prop_names[i]; dic_customprops[prop_name] = list_customprops[i]; } } return list_dic_customprops; } /// <summary> /// Get the number of user-defined cells for the shape. /// </summary> /// <param name="shape"></param> /// <returns></returns> public static int GetCount(IVisio.Shape shape) { if (shape == null) { throw new System.ArgumentNullException(nameof(shape)); } // If the User Property section does not exist then return zero immediately if (0 == shape.SectionExists[_udcell_section, (short)IVisio.VisExistsFlags.visExistsAnywhere]) { return 0; } var section = shape.Section[_udcell_section]; if (section == null) { string msg = string.Format("Could not find the user-defined section for shape {0}", shape.NameU); throw new InternalAssertionException(msg); } int row_count = section.Shape.RowCount[_udcell_section]; return row_count; } /// <summary> /// Returns all the Names of the user-defined cells /// </summary> /// <remarks> /// names of user defined cells are not queryable get GetResults & GetFormulas /// </remarks> /// <param name="shape"></param> /// <returns></returns> public static List<string> GetNames(IVisio.Shape shape) { if (shape == null) { throw new System.ArgumentNullException(nameof(shape)); } int user_prop_row_count = UserDefinedCellHelper.GetCount(shape); if (user_prop_row_count < 1) { return new List<string>(0); } var prop_names = new List<string>(user_prop_row_count); var prop_section = shape.Section[UserDefinedCellHelper._udcell_section]; var query_names = prop_section.ToEnumerable().Select(row => row.NameU); prop_names.AddRange(query_names); if (user_prop_row_count != prop_names.Count) { throw new InternalAssertionException("Unexpected number of user-defined-cell names"); } return prop_names; } public static bool IsValidName(string name) { if (name == null) { return false; } if (name.Length < 1) { return false; } const string space = " "; const string tab = "\t"; const string carriage_return = "\r"; const string line_feed = "\n"; if (name.Contains(space) || name.Contains(tab) || name.Contains(carriage_return) || name.Contains(line_feed)) { return false; } return true; } public static void CheckValidName(string name) { if (!UserDefinedCellHelper.IsValidName(name)) { string msg = string.Format("Invalid Name for User-Defined Cell: \"{0}\"", name); throw new System.ArgumentException(msg); } } public static bool Contains(IVisio.Shape shape, string name) { if (shape == null) { throw new System.ArgumentNullException(nameof(shape)); } if (name == null) { throw new System.ArgumentNullException(nameof(name)); } UserDefinedCellHelper.CheckValidName(name); string full_prop_name = UserDefinedCellHelper.GetRowName(name); var exists = (short)IVisio.VisExistsFlags.visExistsAnywhere; return 0 != (shape.CellExistsU[full_prop_name, exists]); } } }
137a4e6745a8d708a844f2ac0f325758e5955d5d
C#
asyade/RaidBot
/RaidBot.Protocol/messages/game/inventory/items/ObjectAddedMessage.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using RaidBot.Protocol.Types; using RaidBot.Protocol.Messages; using RaidBot.Common.IO; namespace Raidbot.Protocol.Messages { public class ObjectAddedMessage : NetworkMessage { public const uint Id = 3025; public override uint MessageId { get { return Id; } } public ObjectItem Object { get; set; } public byte Origin { get; set; } public ObjectAddedMessage() {} public ObjectAddedMessage InitObjectAddedMessage(ObjectItem Object, byte Origin) { this.Object = Object; this.Origin = Origin; return (this); } public override void Serialize(ICustomDataWriter writer) { this.Object.Serialize(writer); writer.WriteByte(this.Origin); } public override void Deserialize(ICustomDataReader reader) { this.Object = new ObjectItem(); this.Object.Deserialize(reader); this.Origin = reader.ReadByte(); } } }
8541a3bcdb4900d6e75721b9c98b673808d84f03
C#
Saihar1sh/battle-tank-game
/Assets/Scripts/Camera/CameraSwitch.cs
2.515625
3
using UnityEngine; using UnityEngine.UI; public class CameraSwitch : MonoBehaviour { [SerializeField] private GameObject cam , cam3rdPerson; [SerializeField] private Button switchCamBtn; private int count = 0; private void Awake() { switchCamBtn.onClick.AddListener(SwitchCam); } private void Start() { cam.SetActive(true); cam3rdPerson.SetActive(false); } private void Update() { if (Input.GetKeyDown(KeyCode.V) && count >= 0) { SwitchCam(); } } private void SwitchCam() { count++; Camera(count); } private void Camera(int _count) { switch (_count) { case 1: cam.SetActive(false); cam3rdPerson.SetActive(true); break; case 2: cam3rdPerson.SetActive(false); cam.SetActive(true); count = 0; break; } } }
d78fbe3ce52b2d161b0e201011217979ff95d25b
C#
zachtodd99/STEPS-Student-Teacher-Educational-Process-Supplement
/Assets/_scripts/stats.cs
2.71875
3
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class stats : MonoBehaviour { public GameObject statPrefab; // Use this for initialization void Start () { User user = GameObject.Find("User").GetComponent<User>(); user.saveUserData(); GameObject.Find("Total Score").GetComponent<Text>().text = "Total Points: " + user.getTotalPointsOverall(); if(user.quizRecord.Count == 0) { gameObject.active = false; } // TODO: change this to add a new gameobject for each stat for(int x = 0; x<user.quizRecord.Count;x++) { GameObject newStat = Instantiate(statPrefab,transform.parent); newStat.GetComponent<Text>().text = "Quiz: " + user.quizRecord[x].quizName + "\nTimes Taken: " + user.quizRecord[x].timesTaken + "\nAverage Percentage Correct: " + Math.Floor(10000 * user.quizRecord[x].averagePercentageCorrect)/100 + "%" + "\nHigh Score: " + user.quizRecord[x].highScore + "\n\n"; newStat.transform.SetSiblingIndex(transform.GetSiblingIndex() + x + 1); } } }
0a816bd0da3498b290a9f739c23b3ffc77a85f36
C#
maziesmith/WebServices
/Week4/WcfInClass1/WcfInClass1/WcfInClass1/ContactManager.svc.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace WcfInClass1 { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging. public class ContactManager : IContactManager { public string GetData(int value) { return string.Format("You entered: {0}", value); } public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite == null) { throw new ArgumentNullException("composite"); } if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; } public int GetNumberOfContacts() { return 5; } public ContactInformation GetClientInformation(string lastName) { if (lastName == "Gagnon") { ContactInformation myContact = new ContactInformation(); myContact.FirstName = "Jason"; myContact.LastName = "Gagnon"; myContact.PhoneNumber = "555-1212"; myContact.FaxNumber = "111-1212"; myContact.EmailAddress = "test@gmail.com"; return myContact; } else { ContactInformation newContact = new ContactInformation(); newContact.FirstName = ""; newContact.LastName = ""; newContact.PhoneNumber = ""; newContact.FaxNumber = ""; newContact.EmailAddress = ""; return newContact; } } } }
1c149460006fc7984c9534afeac19f8eac199b72
C#
marcdacz/interpreter
/Code/Interpreter.Models/Collections/VariableCollection.cs
3.03125
3
using System; namespace Interpreter.Models.Collections { public class VariableCollection : BaseScopedValueCollection<object> { private VariableTypes GetVariableType(string name) { VariableTypes type = VariableTypes.Unknown; if (name.StartsWith("local", StringComparison.InvariantCultureIgnoreCase)) { type = VariableTypes.Local; } else if (name.StartsWith("global", StringComparison.InvariantCultureIgnoreCase)) { type = VariableTypes.Global; } else if (name.StartsWith("sys", StringComparison.InvariantCultureIgnoreCase)) { type = VariableTypes.System; } return type; } public override ScopedValue GetScopeKeyOf(string name) { ScopedValue variableKey = null; if (GetVariableType(name) == VariableTypes.Local) { if (Scopes.Count() > 0) { variableKey = new ScopedValue(Scopes.PeekCurrent(), name); } } else { variableKey = new ScopedValue("global", name); } return variableKey; } public override void Add(string name, object value) { var variableType = GetVariableType(name); if (variableType != VariableTypes.Unknown) { base.Add(name, value); } else { throw new FormatException($"Incorrect variable format for {name}. Allowed prefixes: local or global."); } } } }
b3988d382a35c5dd4cd42394a167788148fe5fa5
C#
nickky2010/C-Sharp-HW7
/HW7_5/Program.cs
3.015625
3
// Задание 5 //Создать структуру, которая должна содержать следующие элементы: //поля для хранения фамилии, даты рождения, даты поступления, диагноза, //свойство для определения продолжительности пребывания в больнице в днях, //метод для определения возраста.Для описания последнего поля необходимо создать перечисление //(например, пусть diagnoz это перечисление с константами Грипп, Ангина, Пневмония, тогда поле с диагнозом должно быть описано так: //diagnoz bolezn;). //Разработать программу, которая выполняет следующие действия: //  Формирует массив структур. //  Выводит информацию о пациентах с заданным диагнозом. //Перед выводом пользователю предлагается возможность выбора формата вывода: // если пользователь нажмет клавишу Home, будет выводиться фамилия и возраст, // а если End – фамилия, дата поступления и год рождения. // Дополнительная опция: Выбор диагноза должен осуществляться посредством горизонтального светового меню. //  Выводит информацию о пациентах в виде: // Грипп // ╔═══╦═══════╦═══════════════════════════════════════╦═══════╗ // ║ № ║Фамилия║Продолжительность пребывания в больнице║Возраст║ // ╠═══╬═══════╬═══════════════════════════════════════╬═══════╣ // ║ 1 ║Иванов ║ 5 ║ 15 ║ // ║ 2 ║Петров ║ 12 ║ 35 ║ // ╚═══╩═══════╩═══════════════════════════════════════╩═══════╝ // Ангина // ╔═══╦═══════╦═══════════════════════════════════════╦═══════╗ // ║ № ║Фамилия║Продолжительность пребывания в больнице║Возраст║ // ╠═══╬═══════╬═══════════════════════════════════════╬═══════╣ // ║ 1 ║Сидоров║ 3 ║ 28 ║ // ║ 2 ║Дибров ║ 15 ║ 43 ║ // ╚═══╩═══════╩═══════════════════════════════════════╩═══════╝ //И т.д. //Если информации по какому-то диагнозу нет, выводится заголовок с диагнозом и вместо таблицы фраза «больные не обнаружены». //Информация в каждой таблице должна быть отсортирована по продолжительности пребывания в больнице. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HW7_5.Extend; namespace HW7_5 { class Program { static void Main(string[] args) { try { Hospital[] hospital = { new Hospital ("Иванов",new DateTime(2000,2,8), new DateTime(2018,10,8), Diagnoz.Ангина), new Hospital ("Петров",new DateTime(1966,5,16), new DateTime(2018,9,18), Diagnoz.Ангина), new Hospital ("Сидоров",new DateTime(2008,1,28), new DateTime(2018,8,28), Diagnoz.Пневмония), new Hospital ("Дибров",new DateTime(2000,7,4), new DateTime(2018,9,15), Diagnoz.Пневмония), new Hospital ("Пупкин",new DateTime(2000,12,9), new DateTime(2018,10,3), Diagnoz.Грипп), new Hospital ("Попкин",new DateTime(2000,3,7), new DateTime(2018,10,1), Diagnoz.Грипп), }; Table[] table = { new TableOrdinary ("", new Table.Column("№", 3), new Table.Column("Фамилия", 15), new Table.Column("Продолжительность пребывания в больнице"), new Table.Column("Возраст")), new TableHome ("", new Table.Column("№", 3), new Table.Column("Фамилия", 15), new Table.Column("Возраст")), new TableEnd ("", new Table.Column("№", 3), new Table.Column("Фамилия", 15), new Table.Column("Дата поступления"), new Table.Column("Год рождения")) }; Console.WriteLine(); string[] diagnozy = Enum.GetNames(typeof(Diagnoz)); Menu menu = new Menu(diagnozy, hospital, table); menu.Show(); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine("Ошибка! Задан неправильный формат дат! " + ex.Message); } catch (InvalidCastException ex) { Console.WriteLine("Ошибка! Задан неправильный формат таблицы!\n" + ex.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
92a98100aeec11992486542135da495ae307e5aa
C#
Joelx/Schlangenwettkampf_Forms
/Schlangenwettkampf_Forms/Form1.cs
2.609375
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 Schlangenwettkampf_Forms { public partial class Welt : Form { public Welt() { InitializeComponent(); } private Bitmap Bm; private Graphics Gr; private Random Rand = new Random(); private List<Schlange> _schlangen = new List<Schlange>(); private Vektor _dimensionen; private System.Windows.Forms.Timer _heartbeat; private const int MIN = 10; // Frei gewähltes min und max private const int MAX = 15; // Für Anzahl und Länge der Schlangen. private const int PIXEL_SCALE = 10; private const int INTERVAL = 100; // 500ms private void detektiere_kollision(Schlange jaeger) { Vektor kopfPos = jaeger.get_kopf().get_position(); using (Brush brush = new SolidBrush(Color.Gray)) { for (int i = 0; i < _dimensionen.y; i++) { for (int j = 0; j < _dimensionen.x; j++) { if ((i > 0 && j > 0) && (i != (_dimensionen.y-1)) && (j != (_dimensionen.x-1))) continue; Gr.FillRectangle(brush, j * PIXEL_SCALE, i * PIXEL_SCALE, 10, 10); // Zeichne Segment } } } foreach (var beute in _schlangen.ToList()) { if (beute == jaeger) continue; else { foreach (var segment in beute.get_segmente()) { Vektor segPos = segment.get_position(); if (kopfPos.x == segPos.x && kopfPos.y == segPos.y) { Console.WriteLine("Kollision!"); if (ist_jaeger_groesser_beute(jaeger, beute)) { Console.WriteLine("fresse!"); using (Brush brush = new SolidBrush(Color.FromArgb(100, 255, 0, 0))) { Gr.FillRectangle(brush, kopfPos.x * PIXEL_SCALE, kopfPos.y * PIXEL_SCALE, 30, 30); // Zeichne Segment Refresh(); System.Threading.Thread.Sleep(2000); } jaeger.fresse(beute); _schlangen.Remove(beute); } else { Console.WriteLine("Beute war zu groß!"); } } } } } } private void update(object sender, EventArgs e) { Gr.Clear(Color.White); foreach (var schlange in this._schlangen.ToList()) { Vektor pos = new Vektor(0, 0); Vektor vorgaenger = new Vektor(0, 0); List<ABeweglich> segments = schlange.get_segmente(); foreach (var segment in segments) { Color color = segment.Color; pos = segment.get_position(); // Hole aktuelle Segmentposition using (Brush brush = new SolidBrush(color)) { Gr.FillRectangle(brush, pos.x * PIXEL_SCALE, pos.y * PIXEL_SCALE, 10, 10); // Zeichne Segment } segment.bewege(vorgaenger, Rand, segments); // Bewege aktuelles Segment dort hin, wo das letzte Segment war if (segment.IstTot) { _schlangen.Remove(schlange); continue; } vorgaenger = pos; // Aktuelles Segment wird zum Vorgaenger fuer das nachste Segment. } detektiere_kollision(schlange); } Refresh(); } public void generiere_schlangen() { // Generiere zufällige Anzahl an Schlangen, sowie deren Länge. Random r = new Random(); int r_anzahl = r.Next(MIN, MAX); for (int i = 0; i < r_anzahl; i++) { int r_laenge = r.Next(MIN, 16); // Ebenso frei gewählt. // Generiere Startposition. Vektor startpos = new Vektor(MAX + 5, i*6+10); this._schlangen.Add(new Schlange(r_laenge, _dimensionen, startpos)); } } private static bool ist_jaeger_groesser_beute(Schlange jaeger, Schlange beute) { if (jaeger.get_laenge() > beute.get_laenge()) return true; else return false; } public void starte_timer() { this._heartbeat = new System.Windows.Forms.Timer(); this._heartbeat.Interval = (INTERVAL); this._heartbeat.Tick += new EventHandler(update); this._heartbeat.Enabled = true; this._heartbeat.Start(); } // Make a bitmap to display. private void Form1_Load(object sender, EventArgs e) { Console.WriteLine("test!"); FormBorderStyle = FormBorderStyle.FixedDialog; MinimizeBox = false; MaximizeBox = false; DoubleBuffered = true; // Set at design time: // StartPosition = FormStartPosition.CenterScreen; Bm = new Bitmap(ClientSize.Width, ClientSize.Height); Gr = Graphics.FromImage(Bm); BackgroundImage = Bm; this._dimensionen = new Vektor(ClientSize.Width/PIXEL_SCALE, ClientSize.Height/PIXEL_SCALE); // Console.WriteLine(ClientSize.Height); generiere_schlangen(); starte_timer(); } private void Form1_MouseClick(object sender, EventArgs e) { var groessteSchlange = _schlangen.OrderByDescending(item => item.get_laenge()).First(); // Ermittle groesste Schlange int laenge = groessteSchlange.get_laenge(); int low = (int)Math.Floor(laenge / 2.0f); int high = (int)Math.Ceiling(laenge / 2.0f); List<ABeweglich> segmente = groessteSchlange.get_segmente(); this._schlangen.Remove(groessteSchlange); this._schlangen.Add(new Schlange(high, _dimensionen, segmente[0].get_position())); this._schlangen.Add(new Schlange(low, _dimensionen, segmente[high].get_position())); } } }
bbd15aa47736a21d976d496a9ab2d80cc751ec3b
C#
KirillOsenkov/AspNetCore-Tooling
/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/StringExtensions.cs
2.734375
3
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting { internal static class StringExtensions { public static int? GetFirstNonWhitespaceOffset(this string line) { if (line is null) { throw new ArgumentNullException(nameof(line)); } for (var i = 0; i < line.Length; i++) { if (!char.IsWhiteSpace(line[i])) { return i; } } return null; } public static int? GetLastNonWhitespaceOffset(this string line) { if (line is null) { throw new ArgumentNullException(nameof(line)); } for (var i = line.Length - 1; i >= 0; i--) { if (!char.IsWhiteSpace(line[i])) { return i; } } return null; } public static string GetLeadingWhitespace(this string lineText) { if (lineText is null) { throw new ArgumentNullException(nameof(lineText)); } var firstOffset = lineText.GetFirstNonWhitespaceOffset(); return firstOffset.HasValue ? lineText.Substring(0, firstOffset.Value) : lineText; } public static string GetTrailingWhitespace(this string lineText) { if (lineText is null) { throw new ArgumentNullException(nameof(lineText)); } var lastOffset = lineText.GetLastNonWhitespaceOffset(); return lastOffset.HasValue ? lineText.Substring(lastOffset.Value) : lineText; } } }
4e7e87c60f93d5a3f2498319329f9c24c8126636
C#
ectuser/Object-Oriented-Programming
/SpaceStrategy/SpaceStrategy/Form1 Parts/Registry.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SpaceStrategy { public partial class Form1 { // REGISTRY public static Random rnd = new Random(); public static List<Resource> resourceTypes = new List<Resource>(new Resource[] { new Wood(), new Stone(), new Food() }); public static List<Building> buildingTypes = new List<Building>(new Building[] { new Sawmill(1, new Colony("example")), new Quarry(2, new Colony("example")), new Pasture(3, new Colony("example")) }); } public struct ResourceInt { public Resource Type { get; set; } public int Number { get; set; } public ResourceInt(Resource type, int number) { Type = type; Number = number; } } }
0acec7cac521474278ba25240dacb555133362cb
C#
SmitaJShetty/Betting-Problem
/totebettinproblem/GameRunner.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.ObjectModel; namespace ToteBettinProblem { public class GameRunner { public Collection<IGame> GamesSet { set; get; } public Collection<Bet> BetList { set; get; } public Result Reslt { get; set; } public GameRunner(Collection<IGame> GSet) { GamesSet = GSet; } public ICollection<Dividend> RunAllGames() { List<Dividend> _divs= new List<Dividend>(); foreach (IGame _g in GamesSet) { _divs.AddRange(_g.CalculateDividends(BetList,Reslt,_g.GetRule())); } return _divs; } } }
225cd74358bc31698707f36122e2af8f05242d98
C#
humamAbedrabbo/BarjeesGameWindows
/Elements/Cell.cs
3.046875
3
using Barjees.Common; using Barjees.Shapes; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Barjees.Elements { /// <summary> /// Board cell class /// </summary> public sealed class Cell : VisualGameObject { /// <summary> /// Returns the player occupying the cell /// </summary> public Player Owner { get { if (OccupiedBy.Count() == 0) return null; else return OccupiedBy[0].Owner; } } /// <summary> /// Returns list of pawns occupying the cell /// </summary> private List<Pawn> occupiedBy; /// <summary> /// Returns list of pawns occupying the cell /// </summary> public List<Pawn> OccupiedBy { get { return occupiedBy; } set { occupiedBy = value; } } /// <summary> /// True if the cell is highlighted /// </summary> private bool isHighlighted; /// <summary> /// True if the cell is highlighted /// </summary> public bool IsHighlighted { get { return isHighlighted; } set { isHighlighted = value; } } /// <summary> /// Sets the cell as horizontal cell /// </summary> private bool isHorizontal = true; /// <summary> /// Returns or sets cell horizontal state /// </summary> public bool IsHorizontal { get { return isHorizontal; } set { isHorizontal = value; } } /// <summary> /// Returns or sets cell vertical state /// </summary> public bool IsVertical { get { return !IsHorizontal; } set { IsHorizontal = !value; } } /// <summary> /// Cell bound /// </summary> private GRectangle bound; /// <summary> /// Cell bound /// </summary> public GRectangle Bound { get { return bound; } set { bound = value; OnPropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("Bound")); } } /// <summary> /// The cell global ID (1-96) /// </summary> private int globalID; /// <summary> /// The cell global ID (1-96) /// </summary> public int GlobalID { get { return globalID; } set { globalID = value; } } /// <summary> /// Checks if the cell is a shield cell /// </summary> private bool isShield; /// <summary> /// Checks if the cell is a shield cell /// </summary> public bool IsShield { get { return isShield; } set { isShield = value; } } /// <summary> /// Checks if the cell is a banj cell /// </summary> private bool isBanj; /// <summary> /// Checks if the cell is a banj cell /// </summary> public bool IsBanj { get { return isBanj; } set { isBanj = value; } } /// <summary> /// Default constructor /// </summary> public Cell() { Bound = new GRectangle(); IsHighlighted = false; OccupiedBy = new List<Pawn>(); IsShield = false; IsBanj = false; } /// <summary> /// Checks if the pawn can move to cell /// </summary> /// <param name="pawn"></param> /// <returns></returns> public bool CanAddPawn(Pawn pawn) { return (OccupiedBy.Count() == 0 || OccupiedBy[0].Owner.ID == pawn.Owner.ID || !IsShield); } /// <summary> /// Add pawn to the cell occupants /// </summary> /// <param name="pawn"></param> public void AddPawn(Pawn pawn) { if(CanAddPawn(pawn)) { if (GlobalID == 97 || GlobalID == 98) pawn.IsAchieved = true; KillOpponentPawns(pawn); OccupiedBy.Add(pawn); Update(); } } /// <summary> /// Remove pawn from the occupied pawns /// </summary> /// <param name="pawn"></param> public void RemovePawn(Pawn pawn) { if (OccupiedBy.Count > 0 && OccupiedBy[0].Owner.ID == pawn.Owner.ID) { OccupiedBy.RemoveAll(x => x.ID == pawn.ID); Update(); } } /// <summary> /// Update cell status /// </summary> public override void Update() { base.Update(); if(OccupiedBy != null) { int hw = (int)((Bound.R.Width - (OccupiedBy.Count() * Pawn.SIZE)) / (OccupiedBy.Count() + 1)); int hh = (int)(Bound.R.Height - Pawn.SIZE) / 2; int vw = (int)(Bound.R.Width - Pawn.SIZE) / 2; int vh = (int)((Bound.R.Height - (OccupiedBy.Count() * Pawn.SIZE)) / (OccupiedBy.Count() + 1)); if (IsHorizontal) { for (int i = 0; i < OccupiedBy.Count(); i++) { OccupiedBy[i].Bound.SetRect(new System.Drawing.Rectangle( Bound.R.Left + hw + (i * (Pawn.SIZE + hw)), Bound.R.Top + hh, Pawn.SIZE, Pawn.SIZE )); } } else { for (int i = 0; i < OccupiedBy.Count(); i++) { OccupiedBy[i].Bound.SetRect(new System.Drawing.Rectangle( Bound.R.Left + vw, Bound.R.Top + vh + (i * (Pawn.SIZE + vh)), Pawn.SIZE, Pawn.SIZE )); } } } // GameApp.Instance.Update(); } /// <summary> /// Kill the opponent pawns occupying the cell /// </summary> /// <param name="pawn"></param> private void KillOpponentPawns(Pawn pawn) { if (OccupiedBy == null || OccupiedBy.Count == 0) return; if(OccupiedBy[0].Owner.ID != pawn.Owner.ID) { foreach(Pawn p in OccupiedBy) { p.Kill(); } OccupiedBy.Clear(); } } /// <summary> /// Render the cell /// </summary> /// <param name="g"></param> public override void Render(System.Drawing.Graphics g) { if (GlobalID == 97 || GlobalID == 98) { if (IsHighlighted) { g.FillRectangle(System.Drawing.Brushes.Silver, Bound); } } else { if (IsHighlighted) { g.FillRectangle(System.Drawing.Brushes.Silver, Bound); } Bound.Draw(g); DrawShield(g); DrawBanj(g); } } /// <summary> /// Render the Banj line /// </summary> /// <param name="g"></param> private void DrawBanj(Graphics g) { if(IsBanj) { g.DrawLine(Pens.Black, Bound.R.Left, Bound.R.Top, Bound.R.Right, Bound.R.Bottom); } } /// <summary> /// Render the shield lines /// </summary> /// <param name="g"></param> private void DrawShield(System.Drawing.Graphics g) { if(IsShield) { g.DrawLine(Pens.Black, Bound.R.Left, Bound.R.Top, Bound.R.Right, Bound.R.Bottom); g.DrawLine(Pens.Black, Bound.R.Right, Bound.R.Top, Bound.R.Left, Bound.R.Bottom); } } /// <summary> /// Fires on bound changed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if(e.PropertyName == "Bound") { } } } }
24128d8627ec481d654763b66d38927e610b23e6
C#
KatySpielberg/Tic-Tac-Toe-in-WINFORM-
/WinForm_TicTacToe/WinForm_TicTacToe/Form1.cs
3
3
using System; using System.Windows.Forms; /// <summary> /// https://www.youtube.com/watch?v=p3gYVcggQOU&t=32s /// </summary> /// https://www.youtube.com/watch?v=mRg4FNvxjjo namespace WinForm_TicTacToe { public partial class Form1 : Form { bool turnX = true; // false will be = turn of O int turn_count = 0; public Form1() { InitializeComponent(); } private void newGameToolStripMenuItem_Click(object sender, EventArgs e) { turnX = true; turn_count = 0; foreach (Control c in Controls) { try { Button b = (Button)c; b.Enabled = true; b.Text = ""; } catch { } } } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("by Katy, 21/10/19", "Tic Tac Toe Info"); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void btn_Click(object sender, EventArgs e) { Button b = (Button)sender; if (turnX) b.Text = "X"; else b.Text = "O"; turnX = !turnX; b.Enabled = false; turn_count++; CheckForWinner(); } private void CheckForWinner() { bool isWinner = false; // Horizontal Win if ((A1.Text == A2.Text) && (A2.Text == A3.Text) && (!A1.Enabled)) isWinner = true; else if ((B1.Text == B2.Text) && (B2.Text == B3.Text) && (!B1.Enabled)) isWinner = true; else if ((C1.Text == C2.Text) && (C2.Text == C3.Text) && (!C1.Enabled)) isWinner = true; // Vertical Win if ((A1.Text == B1.Text) && (B1.Text == C1.Text) && (!A1.Enabled)) isWinner = true; else if ((A2.Text == B2.Text) && (B2.Text == C2.Text) && (!A2.Enabled)) isWinner = true; else if ((A3.Text == B3.Text) && (B3.Text == C3.Text) && (!A3.Enabled)) isWinner = true; // Diagonal Win if ((A1.Text == B2.Text) && (B2.Text == C3.Text) && (!A1.Enabled)) isWinner = true; else if ((A3.Text == B2.Text) && (B2.Text == C1.Text) && (!A3.Enabled)) isWinner = true; if (isWinner) { disableButtons(); string winner = ""; if (turnX) { winner = "O"; o_win_count.Text = (Int32.Parse(o_win_count.Text) + 1).ToString(); } else { winner = "X"; x_win_count.Text = (Int32.Parse(x_win_count.Text) + 1).ToString(); } MessageBox.Show(winner + " Wins!", "Cool!"); } else { if (turn_count == 9) { draw_count.Text = (Int32.Parse(draw_count.Text) + 1).ToString(); MessageBox.Show("Draw!", "Bummer!"); // ничья } } } private void disableButtons() { try { foreach (Control c in Controls) { Button b = (Button)c; b.Enabled = false; } } catch { } } private void btn_enter(object sender, EventArgs e) { Button b = (Button)sender; if (b.Enabled) { if (turnX) b.Text = "X"; else b.Text = "O"; } } private void btn_leave(object sender, EventArgs e) { Button B = (Button)sender; if (B.Enabled) { B.Text = ""; } } private void resetWinCountToolStripMenuItem_Click(object sender, EventArgs e) { x_win_count.Text = "0"; o_win_count.Text = "0"; draw_count.Text = "0"; } } }
d8ac44d9b14c84f52c93a74aacc531c9ca185aeb
C#
jeromeb85/Yis
/Source/CSharp/Yis/Framework/Data/Database/Paramhelper.cs
2.59375
3
using Oracle.ManagedDataAccess.Client; using System; using System.Data; using System.Data.Odbc; using System.Data.SqlClient; namespace Yis.Framework.Data.Database { public sealed class DbDataParamHelper { private DbDataParamHelper() { } public static IDataParameter BuildDataParameter(IDbConnection connection, DbType dataType, string parameterName, object value) { IDataParameter param = default(IDataParameter); switch (connection.GetType().FullName.ToUpper()) { case "SYSTEM.DATA.SQLCLIENT.SQLCONNECTION": param = new SqlParameter(); parameterName = parameterName.Replace(":", "@"); break; case "SYSTEM.DATA.ORACLECLIENT.ORACLECONNECTION": param = new OracleParameter(); parameterName = parameterName.Replace("@", ":"); break; case "SYSTEM.DATA.ODBC": param = new OdbcParameter(); break; default: throw new InvalidOperationException("Ce DataProvider n'est pas connu par le framework"); } param.DbType = dataType; //if (connection.GetType().FullName.ToUpper() == "SYSTEM.DATA.ORACLECLIENT.ORACLECONNECTION") //{ // switch (dataType) // { // case DbType.String: // param.DbType = (DbType) OracleType.VarChar; // break; // case DbType.Int16: // param.DbType = (DbType) OracleType.Int16; // break; // case DbType.Int32: // param.DbType = (DbType) OracleType.Int32; // break; // case DbType.DateTime: // param.DbType = (DbType) OracleType.DateTime; // break; // case DbType.Double: // param.DbType = (DbType) OracleType.Double; // break; // } //} param.Value = value ?? DBNull.Value; param.ParameterName = parameterName; return param; } } }
fd157d132fd5eb6325b1b5ed15eee6c8347ebc19
C#
r-net11/Rubezh
/Projects/Common/OpcDaServer/OpcDaServer/OpcDaItemBase.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OpcFoundation { /// <summary> /// Тег или директория OPC DA сервера /// </summary> public abstract class OpcDaItemBase { public OpcDaItemBase() { _items = new List<OpcDaItemBase>(); } #region Fields And Properties protected List<OpcDaItemBase> _items; /// <summary> /// Наименование корневой директории тегов /// </summary> public const string RootDirectory = @"."; /// <summary> /// Разделитель для сегментов пути к тегу /// </summary> public const string Spliter = @"\"; /// <summary> /// /// </summary> public abstract bool IsDirectory { get; } protected OpcDaDirectory _directory; /// <summary> /// Директория содержащая данный тег или директорию /// </summary> public OpcDaDirectory Directory { get { return _directory; } } #endregion #region Methods #endregion } }
6df6ae2f0905a215ea58fc0218dd58f9d8004a2f
C#
AATerekhov/CuttingSheet
/RandomlyCuttingSheet/Helper.cs
3.15625
3
using System; using System.Collections.Generic; using System.Linq; using Tekla.Structures.Geometry3d; namespace RandomlyCuttingSheet { class Helper { public static IOrderedEnumerable<RandomlyPlate> SortingFCNR(IOrderedEnumerable<RandomlyPlate> orderByPlateList, int widthMainPlate) { List<Room> rooms = new List<Room>(); rooms.Add(new Room(1, 0, widthMainPlate)); bool columAdd = false; foreach (var item in orderByPlateList) { if (rooms.First().Count == 0) { item.TypeSurface = 1; rooms.First().Add( item); } else { //нахождение наилучшего столбца item.BestColumn = -1; item.TypeSurface = 0; int typeSurface; foreach (var room in rooms) { if (room.CapacityCheck(item,out typeSurface)) { if (item.BestColumn == -1) { item.BestColumn = room.Number; item.TypeSurface = typeSurface; } else if ((rooms[item.BestColumn - 1].FullnessFloor < room.FullnessFloor) && (typeSurface == 1) && (item.TypeSurface == typeSurface)) { item.BestColumn = room.Number; } else if ((rooms[item.BestColumn - 1].FullnessCeiling < room.FullnessCeiling) && (typeSurface == 2) && (item.TypeSurface == typeSurface)) { item.BestColumn = room.Number; } } } //размещение в столбце или создание нового foreach (var room in rooms) { if (room.Number == item.BestColumn) { room.Add(item); break; } else { if ((room.Number) != rooms.Count) { continue; } else { columAdd = true; break; } } } //создание нового столбца if (columAdd) { rooms.Add(new Room(rooms.Last().Number + 1,rooms.Last().Displacement(), widthMainPlate)); item.TypeSurface = 1; rooms.Last().Add(item); columAdd = false; } } } return orderByPlateList; } /// <summary> /// Определение пересекаются ли многоугольники. /// </summary> /// <param name="pointListOne"></param> /// <param name="pointListTwo"></param> /// <returns></returns> public static bool GetIntersectionPlate(List<Point> pointListOne, List<Point> pointListTwo) { var intersectionPlate = false; List<LineSegment> segmentListOne = TransformationOfPointsInLineSegment(pointListOne); List<LineSegment> segmentListTwo = TransformationOfPointsInLineSegment(pointListTwo); foreach (var item in segmentListOne) { foreach (var segmentTwo in segmentListTwo) { intersectionPlate = IntersectionSegmentToSegment(item, segmentTwo); if (intersectionPlate) { break; } } if (intersectionPlate) { break; } } return intersectionPlate; } /// <summary> /// Из списка точек возвращает список отрезков. /// </summary> /// <param name="pointList"></param> /// <returns></returns> public static List<LineSegment> TransformationOfPointsInLineSegment(List<Point> pointList) { List<LineSegment> segmentList = new List<LineSegment>(); var i = 1; foreach (var point in pointList) { if (i != pointList.Count()) { segmentList.Add(new LineSegment(point,pointList[i])); } else { segmentList.Add(new LineSegment(point, pointList[0])); break; } i++; } return segmentList; } /// <summary> /// Определение пересекаются ли отрезки. /// возвращает bool. /// </summary> /// <param name="segmentOne"></param> /// <param name="segmentTwo"></param> /// <returns></returns> public static bool IntersectionSegmentToSegment(LineSegment segmentOne, LineSegment segmentTwo) { Vector vectorOne = new Vector(segmentOne.Point2.X - segmentOne.Point1.X, segmentOne.Point2.Y - segmentOne.Point1.Y, segmentOne.Point2.Z - segmentOne.Point1.Z); Vector vectorTwo = new Vector(segmentTwo.Point2.X - segmentTwo.Point1.X, segmentTwo.Point2.Y - segmentTwo.Point1.Y, segmentTwo.Point2.Z - segmentTwo.Point1.Z); Vector vectorZ = vectorOne.Cross(vectorTwo); GeometricPlane planeOne = new GeometricPlane(segmentOne.Point1, vectorOne, vectorZ); GeometricPlane planeTwo = new GeometricPlane(segmentTwo.Point1,vectorTwo,vectorZ); bool conditionOne; bool conditionTwo; var pointIntersectionOne = Intersection.LineSegmentToPlane(segmentOne, planeTwo); var pointIntersectionTwo = Intersection.LineSegmentToPlane(segmentTwo,planeOne); if (pointIntersectionOne == null) { conditionOne = false; } else { conditionOne = true; } if (pointIntersectionTwo == null) { conditionTwo = false; } else { conditionTwo = true; } if (conditionOne && conditionTwo) { return true; } else { return false; } } } }
aa34846d34ded41297cbf95faad4e86aef1e8d80
C#
JavierRoviraltaTerron/MedicalAppointmentManager
/WebAPI/Controllers/AppointmentController.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MedicalAppointmentManager.BusinessLogic.Interfaces; using MedicalAppointmentManager.BusinessLogic.Models; namespace MedicalAppointmentManager.WebAPI.Controllers { //[Route("api/[controller]")] [Route("[controller]")] [ApiController] public class AppointmentController : ControllerBase { public IAppointmentService _appointmentService; public AppointmentController(IAppointmentService appointmentService) { _appointmentService = appointmentService; } // GET: api/Appointment [HttpGet] public IEnumerable<AppointmentDTO> Get() { var lstAppointments = _appointmentService.Get(false); return lstAppointments; } // GET: api/Appointment/5 [HttpGet("{id}", Name = "Get")] public AppointmentDTO Get(int id) { var appointment = _appointmentService.Get(id); return appointment; } // POST: api/Appointment [HttpPost] public void Add([FromBody] AppointmentDTO appointment) { if (appointment != null) { _appointmentService.Add(appointment); } } //// PUT: api/Appointment/5 //[HttpPut("{id}")] //public void Put([FromBody] AppointmentDTO appointment) //{ //} // POST: api/Appointment/Update [Route("Update")] [HttpPost] public void Update([FromBody] AppointmentDTO appointment) { if (appointment != null) { _appointmentService.Update(appointment); } } // DELETE: api/Appointment/5 [HttpDelete("{id}")] public void Remove(int id) { _appointmentService.Remove(id); } } }
bcc86fbe50a3cdfdf6e12ca7c434e38c3d1b02ed
C#
ztepsic/MedOrd
/src/MedOrd/MedOrd.DomainModel/MedicalCase.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MedOrd.DomainModel.Enumerations; namespace MedOrd.DomainModel { public class MedicalCase : PersistentObject { #region Members /// <summary> /// Dohvaca ili postavlja naziv medicinskog slucaja /// </summary> public string Title { get; set; } /// <summary> /// Dohvaca ili postavlja datum /// </summary> public DateTime Date { get; set; } /// <summary> /// Dijagnoza /// </summary> private readonly Diagnosis diagnosis; /// <summary> /// Dohvaca dijagnozu /// </summary> public Diagnosis Diagnosis { get { return diagnosis; } } #endregion #region Constructors and Init /// <summary> /// Konstruktor /// </summary> /// <param name="title">naziv medicinskog slucaja</param> /// /// <param name="diagnosis">dijagnoza</param> public MedicalCase(string title, Diagnosis diagnosis) { Title = title; this.diagnosis = diagnosis; } #endregion #region Methods public override string ToString() { return Title; } #endregion } }
518f841836e107ec5803aa93b508bd34ee2e32cc
C#
HarunDilukaHeshan/KnBPrototype01
/Knb.App.Simulator.Shared/GameData/CardPack.cs
3.171875
3
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Knb.App.Simulator.GameData { public class CardPack : IEnumerable<Card> { protected Card[] Cards { get; } public int Count { get { return Cards.Length; } } public CardPack(Card[] cards) { var cardsList = new List<Card>(); foreach (var card in cards) cardsList.Add(new Card(card.SuitName, card.CardName)); Cards = cardsList.ToArray(); } public IEnumerator<Card> GetEnumerator() { return new CardPackEnumerator(Cards); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } public Card this[int index] { get => Cards[index]; } } public class CardPackEnumerator : IEnumerator<Card> { protected Card[] Cards { get; set; } protected Card CurrentCard { get; set; } public Card Current { get { return CurrentCard; } } object IEnumerator.Current { get { return Current; } } protected long Position { get; set; } = -1; public CardPackEnumerator(Card[] cards) { Cards = cards; } public void Dispose() { Cards = new Card[0]; } public bool MoveNext() { Position++; var canMove = Position < Cards.Length; if (canMove) CurrentCard = Cards[Position]; return canMove; } public void Reset() { Position = -1; CurrentCard = null; } } }
11683c14fb1b163b8fbaf88e2e34b7d130e2cabb
C#
krishna5816/RestaurantSystem
/ManifacturedMenuitems/Menufactured_partial.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using CustomControls; using System.Drawing; namespace RestaurantSystem.ManifacturedMenuitems { public partial class List { #region groub_by_itm public class RItemviwer { public int id { get; set; } public string name { get; set; } public decimal qty { get; set; } public string unit { get; set; } public ListViewItem getLV() { return new ListViewItem(new string[] { name, qty.ToString("0.##"), unit }); } } List<RItemviwer> rItemviwers; private void GroupByItem(List<int> billsid) { rItemviwers = new List<RItemviwer>(); betterListView1.AddColumns(new string[] { "Item", "Qty", "Unit", }); decimal total = 0; var billitems = db.billitems.Where(o => billsid.Contains(o.bill_id.Value)).ToList(); foreach (var billitem in billitems) { if (rItemviwers.Count(o => o.id == billitem.item_id) == 0) { var viwer = new RItemviwer() { id = billitem.item_id.Value, name = billitem.menuitem.name, unit=billitem.menuitem.unit, qty = billitem.qty.Value }; rItemviwers.Add(viwer); } else { var viwer = rItemviwers.First(o => o.id == billitem.item_id); viwer.qty += billitem.qty.Value; } } foreach (var viwer in rItemviwers) { betterListView1.Items.Add(viwer.getLV()); } } #endregion #region public class RCategoryViwer { public int Id { get; set; } public string name { get; set; } public decimal amount { get; set; } public decimal total { get; set; } } public void GroupByCategory(List<int> bills) { decimal nettotal = 0; betterListView1.AddColumns(new string[] { "Category", "Total Qty", "Net Total" }); var billitems = db.billitems.Where(o => bills.Contains(o.bill_id.Value)).Join(db.menuitems, o => o.item_id, p => p.id, (o, p) => new { o.qty, o.nettotal, p.category_id }).Join(db.categories, o => o.category_id, p => p.id, (o, p) => new { p.id, o.qty, p.name, o.nettotal }).GroupBy(o => o.id).Select(o => new RCategoryViwer() { Id = o.Key, amount = o.Sum(x => x.qty).Value, total = o.Sum(x => x.nettotal), name = o.FirstOrDefault(x => x.id == o.Key).name }).ToList(); foreach (var bi in billitems) { betterListView1.Add(new string[] { bi.name, bi.amount.ToString("0.###"), bi.total.ToString("0.##") }); } betterListView1.Add(new ListViewItem(new string[] { "Total", billitems.Sum(o => o.amount).ToString("0.###"), billitems.Sum(o => o.total).ToString("0.##") }) { BackColor = Color.Blue, ForeColor = Color.White }); } #endregion } }
28e8c7256e08921313395936a6bf16de99ed4884
C#
shendongnian/download4
/first_version_download2/535476-50182303-172739255-4.cs
3.1875
3
// Assign the game objects manually from the Unity interface via drag and drop. That is why public. Public GameObject[] ParticleSystems; Private String[] YourEmotions; float activationDuration = 15f; // Your code to retrieve the txt value and assign to 'YourEmotions' array. Have the order match the order of the equivalent game object. Then when you need the particle system, active it by calling StartParticularParticleSystem and passing in the string identifier of the one you want to use. // ... Public Void StartParticularParticleSystem(string Emotion) { for(int i = 0; i < ParticleSystems.Count; i++) { if(Emotion == YourEmotions[i]) { StartCoroutine(MyCoroutine(ParticleSystems[i])); } } } IEnumerator MyCoroutine (GameObject ObjectToActivate) { ObjectToActivate.SetActive(True); yield return new WaitForSeconds(activationDuration); ObjectToActivate.SetActive(False); }
01a51cd728a59b4edacf735a381a42483bb39146
C#
goozgk/Free-Snipping-Tool
/Free Snipping Tool/Operations/Shortcuts.cs
2.515625
3
using System; using System.Windows.Forms; using System.Runtime.InteropServices; class Shortcuts { public static string[] keys = { "PrintScreen", "Home", "End", "PageUp", "PageDown", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12" }; public static string[] Modifiers = { "Windows", "Shift", "Control", "Alt" }; public const int HOTKEY_ID = 31197; public const int WM_HOTKEY = 0x0312; private enum KeyModifiers { None = 0, Alt = 1, Control = 2, Shift = 4, Windows = 8 } [DllImport("user32.dll", SetLastError = true)] private static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk); [DllImport("user32.dll", SetLastError = true)] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); public static void ApplyHotKey(IntPtr handle, string Key, string Modfiers) { RemoveHotKey(handle); KeyModifiers modfierkey = (KeyModifiers)Enum.Parse(typeof(KeyModifiers), Modfiers); RegisterHotKey(handle, HOTKEY_ID, modfierkey, TypesConvertor.ConvertStringToKey(Key)); } public static void RemoveHotKey(IntPtr handle) { UnregisterHotKey(handle, HOTKEY_ID); } }
3695a10c77cd93e91204515329d0f7ace80cf152
C#
Bpoe/WakeOnLan
/WakeOnLanCmdlet/Extensions.cs
3.796875
4
//----------------------------------------------------------------------- // <copyright file="Extensions.cs"> // Copyright // </copyright> //----------------------------------------------------------------------- namespace Poesoft { using System.Collections.Generic; using System.Globalization; /// <summary> /// Class for extension methods /// </summary> public static class Extensions { /// <summary> /// Splits a string into substrings of the specified length /// </summary> /// <param name="value">The string to split</param> /// <param name="length">The length of the substrings to split the string into</param> /// <returns>The string split into substrings of the specified length</returns> public static string[] SplitByLength(this string value, int length) { var splitString = new string[value.Length / length]; var x = 0; for (var i = 0; i < value.Length / length; i++) { splitString[i] = value.Substring(x, length); x += length; } return splitString; } /// <summary> /// Removes the specified characters from the string /// </summary> /// <param name="value">The string to remove characters from</param> /// <param name="chars">The characters to remove</param> /// <returns>A copy of the string with the specified characters removed</returns> public static string RemoveCharacters(this string value, IEnumerable<char> chars) { var s = value; foreach (var c in chars) { s = value.Replace(c.ToString(CultureInfo.InvariantCulture), string.Empty); } return s; } /// <summary> /// Sets a value to the element at the specified position in the multidimensional System.Array. The indexes are specified as an array of 32-bit integers. /// </summary> /// <typeparam name="T">The type of the elements in the System.Array</typeparam> /// <param name="array">The System.Array to set the value of.</param> /// <param name="value">The new value for the specified element.</param> /// <param name="startIndex">A 32-bit integer that represents the start position of the System.Array elements to set.</param> /// <param name="length">A 32-bit integer that represents the number of System.Array elements to set.</param> public static void SetValues<T>(this T[] array, T value, int startIndex, int length) { for (var i = 0; i < length; i++) { array[startIndex + i] = value; } } } }
e887308dea73ef9e0942b3bf58a0ff7998423a46
C#
catahoc/ClimatePicking
/srv/ClimatePicking.DataRetriever/LoadLonLatScript.cs
2.5625
3
using System; using System.Data.Entity; using System.Linq; using ClimatePicking.Domain; namespace ClimatePicking.DataRetriever { public class LoadLonLatScript { public static void Do() { var countries = CountryRecord.Retrieve(); using (var context = new ClimateContext()) { var dbCountries = context.Countries.Include(x => x.Cities).ToList(); var joined = countries.Join(dbCountries, x => x.name, x => x.Name, (dto, db) => new {dto, db}); foreach (var pair in joined) { if (pair.dto.latlng != null && pair.dto.latlng.Length == 2) { foreach (var city in pair.db.Cities) { city.Lat = pair.dto.latlng[0]; city.Lon = pair.dto.latlng[1]; } } } context.SaveChanges(); } } } }
4a038d60fbc1901dc8532a2ad5cc52c930d6fe2f
C#
ap0llo/mddocs
/src/MdDocs.ApiReference.Test/Model/XmlDocs/XmlDocsReaderTest.cs
2.640625
3
using System; using System.Linq; using System.Xml.Linq; using Grynwald.MdDocs.ApiReference.Model; using Grynwald.MdDocs.ApiReference.Model.XmlDocs; using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace Grynwald.MdDocs.ApiReference.Test.Model.XmlDocs { public class XmlDocsReaderTest { private static ListElement ReadList(XDocument document) { var xmlDocsReader = new XmlDocsReader(NullLogger.Instance, document, Array.Empty<TypeId>()); var members = xmlDocsReader.Read(); Assert.Single(members); Assert.Single(members.Single().Summary.Elements); var element = members.Single().Summary.Elements.Single(); Assert.IsType<ListElement>(element); var list = (ListElement)element; return list; } private static XDocument GetDocumentFromListXml(string listXml) { return XDocument.Parse($@"<?xml version=""1.0""?> <doc> <assembly> <name>AssemblyName</name> </assembly> <members> <member name=""T:TypeName""> <summary> {listXml} </summary> </member> </members> </doc>"); } private static XDocument GetDocumentFromListItemXml(string listItemXml) { return GetDocumentFromListXml( $@"<list type=""bullet""> <item> {listItemXml} </item> </list>" ); } [Theory] [InlineData(@"<list></list>", ListType.None, false, 0)] [InlineData(@"<list type=""bullet""></list>", ListType.Bullet, false, 0)] [InlineData(@"<list type=""number""></list>", ListType.Number, false, 0)] [InlineData(@"<list type=""table""></list>", ListType.Table, false, 0)] [InlineData( @"<list type=""bullet""> <item> <description>description</description> </item> </list>", ListType.Bullet, false, 1)] [InlineData( @"<list type=""bullet""> <item> <description>description</description> </item> <item> <description>description</description> </item> </list>", ListType.Bullet, false, 2)] [InlineData( @"<list type=""bullet""> <listheader> <description>description</description> </listheader> <item> <description>description</description> </item> </list>", ListType.Bullet, true, 1)] public void Lists_are_parsed_correctly(string xml, ListType expectedListType, bool expectHeader, int expectedNumberOfListItems) { // ARRANGE var document = GetDocumentFromListXml(xml); // ACT var list = ReadList(document); // ASSERT Assert.Equal(expectedListType, list.Type); if (expectHeader) Assert.NotNull(list.ListHeader); else Assert.Null(list.ListHeader); Assert.Equal(expectedNumberOfListItems, list.Items.Count); } [Theory] [InlineData("")] [InlineData("<someElement></someElement>")] [InlineData("<term></term>")] public void Invalid_list_items_are_ignored(string xml) { // ARRANGE var document = GetDocumentFromListItemXml(xml); // ACT var list = ReadList(document); // ASSERT Assert.Empty(list.Items); } [Theory] [InlineData("<description>TestDescription</description>", false, true)] [InlineData("<term>TestTerm</term><description>TestDescription</description>", true, true)] public void List_items_are_parsed_correctly(string xml, bool expectTerm, bool expectDescription) { // ARRANGE var document = GetDocumentFromListItemXml(xml); // ACT var list = ReadList(document); // ASSERT Assert.Single(list.Items); var listItem = list.Items.Single(); Assert.NotNull(listItem.Term); if (expectTerm) Assert.False(listItem.Term.IsEmpty); else Assert.True(listItem.Term.IsEmpty); if (expectDescription) Assert.NotNull(listItem.Description); else Assert.Null(listItem.Description); } [Fact] public void ReadTextBlock_returns_the_expected_elements_01() { var xml = @" <para> Similar pages are also generated for interfaces, structs and enums </para> "; ReadTextBlock_returns_the_expected_elements( xml, new TextElement("Similar pages are also generated for interfaces, structs and enums") ); } [Fact] public void ReadTextBlock_returns_the_expected_elements_02() { var xml = @" <para> <see cref=""T:DemoProject.DemoStruct"" /> </para> "; ReadTextBlock_returns_the_expected_elements( xml, new SeeElement(MemberId.Parse("T:DemoProject.DemoStruct", Array.Empty<TypeId>())) ); } [Fact] public void ReadTextBlock_returns_the_expected_elements_03() { var xml = @" <para> Similar pages are also generated for interfaces, structs (see <see cref=""T:DemoProject.DemoStruct""/>) and enums </para> "; ReadTextBlock_returns_the_expected_elements( xml, new TextElement("Similar pages are also generated for interfaces, structs (see "), new SeeElement(MemberId.Parse("T:DemoProject.DemoStruct", Array.Empty<TypeId>())), new TextElement(") and enums") ); } [Fact] public void ReadTextBlock_returns_the_expected_elements_04() { var xml = @"<para>Lorem ipsum dolor sit amet.</para>"; ReadTextBlock_returns_the_expected_elements( xml, new TextElement("Lorem ipsum dolor sit amet.") ); } [Fact] public void ReadTextBlock_returns_the_expected_elements_05() { var xml = @"<para><see cref=""T:DemoProject.DemoClass"" /></para>"; ReadTextBlock_returns_the_expected_elements( xml, new SeeElement(MemberId.Parse("T:DemoProject.DemoClass", Array.Empty<TypeId>())) ); } [Fact] public void ReadTextBlock_returns_the_expected_elements_06() { var xml = @"<para><see cref=""T:DemoProject.DemoClass"">Lorem ipsum dolor sit amet.</see></para>"; ReadTextBlock_returns_the_expected_elements( xml, new SeeElement( MemberId.Parse("T:DemoProject.DemoClass", Array.Empty<TypeId>()), new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit amet.") })) ); } private void ReadTextBlock_returns_the_expected_elements(string xml, params Element[] expectedElements) { // ARRANGE var sut = new XmlDocsReader(NullLogger.Instance, new XDocument(), Array.Empty<TypeId>()); var expected = new TextBlock(expectedElements); // ACT var actual = sut.ReadTextBlock(XElement.Parse(xml)); // ASSERT Assert.Equal(expected, actual); } [Fact] public void ReadTextBlock_correctly_reads_see_elements_01() { var xml = @"<see cref=""T:SomeNamespace.SomeClass"" />"; var expected = new SeeElement(MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>())); ReadTextBlock_correctly_reads_see_elements(xml, expected); } [Fact] public void ReadTextBlock_correctly_reads_see_elements_02() { var xml = @"<see cref=""T:SomeNamespace.SomeClass"">Lorem ipsum dolor sit amet.</see>"; var expected = new SeeElement( MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()), new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit amet.") })); ReadTextBlock_correctly_reads_see_elements(xml, expected); } [Fact] public void ReadTextBlock_correctly_reads_see_elements_03() { var xml = @"<see href=""http://example.com"" />"; var expected = new SeeElement(new Uri("http://example.com")); ReadTextBlock_correctly_reads_see_elements(xml, expected); } [Fact] public void ReadTextBlock_correctly_reads_see_elements_04() { var xml = @"<see href=""http://example.com"">Lorem ipsum dolor sit amet.</see>"; var expected = new SeeElement( new Uri("http://example.com"), new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit amet.") })); ReadTextBlock_correctly_reads_see_elements(xml, expected); } [Fact] public void ReadTextBlock_correctly_reads_see_elements_05() { var xml = @"<see href=""http://example.com"" cref=""T:SomeNamespace.SomeClass"" />"; var expected = new SeeElement(MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>())); ReadTextBlock_correctly_reads_see_elements(xml, expected); } [Fact] public void ReadTextBlock_correctly_reads_see_elements_06() { var xml = @"<see href=""http://example.com"" cref=""T:SomeNamespace.SomeClass"">Lorem ipsum dolor sit amet.</see>"; var expected = new SeeElement( MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()), new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit amet.") })); ReadTextBlock_correctly_reads_see_elements(xml, expected); } private void ReadTextBlock_correctly_reads_see_elements(string xml, SeeElement expected) { // ARRANGE xml = $@"<para>{xml}</para>"; var sut = new XmlDocsReader(NullLogger.Instance, new XDocument(), Array.Empty<TypeId>()); // ACT var textBlock = sut.ReadTextBlock(XElement.Parse(xml)); // ASSERT var element = Assert.Single(textBlock.Elements); var seeElement = Assert.IsType<SeeElement>(element); Assert.Equal(expected, seeElement); } [Fact] public void ReadMemberContent_correctly_parses_seealso_elements_01() { var xml = @"<seealso cref=""T:SomeNamespace.SomeClass"" />"; var expected = new SeeAlsoElement(MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>())); ReadMemberContent_correctly_parses_seealso_elements(xml, expected); } [Fact] public void ReadMemberContent_correctly_parses_seealso_elements_02() { var xml = @"<seealso cref=""T:SomeNamespace.SomeClass"">Lorem ipsum dolor sit ament.</seealso>"; var expected = new SeeAlsoElement( MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()), new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit ament.") })); ReadMemberContent_correctly_parses_seealso_elements(xml, expected); } [Fact] public void ReadMemberContent_correctly_parses_seealso_elements_03() { var xml = @"<seealso href=""http://example.com"" />"; var expected = new SeeAlsoElement(new Uri("http://example.com")); ReadMemberContent_correctly_parses_seealso_elements(xml, expected); } [Fact] public void ReadMemberContent_correctly_parses_seealso_elements_04() { var xml = @"<seealso href=""http://example.com"">Lorem ipsum dolor sit ament.</seealso>"; var expected = new SeeAlsoElement( new Uri("http://example.com"), new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit ament.") })); ReadMemberContent_correctly_parses_seealso_elements(xml, expected); } [Fact] public void ReadMemberContent_correctly_parses_seealso_elements_05() { var xml = @"<seealso cref=""T:SomeNamespace.SomeClass"" href=""http://example.com"" />"; var expected = new SeeAlsoElement(MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>())); ReadMemberContent_correctly_parses_seealso_elements(xml, expected); } [Fact] public void ReadMemberContent_correctly_parses_seealso_elements_06() { var xml = @"<seealso cref=""T:SomeNamespace.SomeClass"" href=""http://example.com"">Lorem ipsum dolor sit ament.</seealso>"; var expected = new SeeAlsoElement( MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()), new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit ament.") })); ReadMemberContent_correctly_parses_seealso_elements(xml, expected); } private void ReadMemberContent_correctly_parses_seealso_elements(string xml, SeeAlsoElement expected) { // ARRANGE xml = $@"<container>{xml}</container>"; var sut = new XmlDocsReader(NullLogger.Instance, new XDocument(), Array.Empty<TypeId>()); var memberElement = new MemberElement(MemberId.Parse("T:DemoProject.DemoClass", Array.Empty<TypeId>())); // ACT sut.ReadMemberContent(XElement.Parse(xml), memberElement); // ASSERT var actual = Assert.Single(memberElement.SeeAlso); Assert.Equal(expected, actual); } } }
3e433d9c7c4802d2b07cf3752a6129c02019b073
C#
stpersam/BDDPrufung
/XUnitTestProject2/SpecFlowFeature1Steps.cs
3.125
3
using System; using TechTalk.SpecFlow; using Xunit; namespace XUnitTestProject2 { [Binding] public class SpecFlowFeature1Steps { double pi; [Given(@"the first number is (.*)")] public void GivenTheFirstNumberIs(double p0) { pi = p0; } [When(@"the sinus is calculated")] public void WhenTheSinusIsCalculated() { Math.Sin(pi); } [When(@"the cosinus is calculated")] public void WhenTheCosinusIsCalculated() { Math.Cos(pi); } [When(@"the tangens is calculated")] public void WhenTheTangensIsCalculated() { Math.Tan(pi); } [Then(@"the result should be (.*)")] public void ThenTheResultShouldBe(int p0) { var expected = p0; var actual = pi; Assert.Equal(expected, actual); } } }
3966f6865a9b48beb8f9e5049634ad6bd3d09cd3
C#
benvaro/MDI_Demo
/MDI_Demo/Parent.cs
2.6875
3
using System; using System.Windows.Forms; namespace MDI_Demo { public partial class Parent : Form { public Parent() { InitializeComponent(); } private int id = 0; public int COUNT_ITEMS => 8; public ToolStripItemCollection WindowDropDownItems => windowToolStripMenuItem.DropDownItems; private void newToolStripMenuItem_Click(object sender, EventArgs e) { var child = new Child(); child.MdiParent = this; child.Text = $"Child {++id}"; if (windowToolStripMenuItem.DropDownItems.Count == COUNT_ITEMS - 1) { var separator = new ToolStripSeparator(); windowToolStripMenuItem.DropDownItems.Add(separator); } var item = new ToolStripMenuItem(child.Text, null, new EventHandler((o, s) => { child.Activate(); })); windowToolStripMenuItem.DropDownItems.Add(item); child.Show(); } private void cascadeToolStripMenuItem_Click(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.Cascade); } private void horizontalToolStripMenuItem_Click(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.TileHorizontal); } private void verticalToolStripMenuItem_Click(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.TileVertical); } private void minimizeAllToolStripMenuItem_Click(object sender, EventArgs e) { foreach (var item in this.MdiChildren) { item.WindowState = FormWindowState.Minimized; } } } }
10104f59d3a208690539728cc933cc7580237a2e
C#
shendongnian/download4
/code3/542175-12568763-29602084-2.cs
3.1875
3
delegate void T2(); static void Main(string[] args) { T2 Thread = new T2(Work); while (true) { IAsyncResult result = Thread.BeginInvoke(null, null); //OTHER WORK TO DO Thread.EndInvoke(result); } } static void Work() { //WORK TO DO }
f4ca98c51b070a6a9a96d11b2e8072231cae49a9
C#
EladHarizy/fluffy-octo-robot
/src/Lib/Lib.DataTypes/Email.cs
3.0625
3
using System.Collections.Generic; using System.Text.RegularExpressions; using Lib.Exceptions; namespace Lib.DataTypes { public class Email { private const string regex = @"^(?=[A-Z0-9][A-Z0-9@._%+-]{5,253}$)[A-Z0-9._%+-]{1,64}@(?:(?=[A-Z0-9-]{1,63}\.)[A-Z0-9]+(?:-[A-Z0-9]+)*\.){1,8}[A-Z]{2,63}$"; private readonly string email; public Email(string email) { if (!Regex.Match(email, regex, RegexOptions.IgnoreCase).Success) { throw new InvalidEmailException(email); } this.email = email.ToLower(); } public override bool Equals(object obj) { return obj is Email email && this.email == email.email; } public override int GetHashCode() { return 848330207 + EqualityComparer<string>.Default.GetHashCode(email); } public override string ToString() { return email; } public static bool operator ==(Email email1, Email email2) { return email1 is null ? email2 is null : email1.Equals(email2); } public static bool operator !=(Email email1, Email email2) { return !(email1 == email2); } public static implicit operator Email(string email) { return new Email(email); } public static implicit operator string(Email email) { return email.email; } } }
3a4dc4c0243b7427c338609991393177f9636b00
C#
dsuz/unity-game-dev1-2nd-term-2020
/Assets/Scripts/MoveObjectCurveToPlayer.cs
2.796875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// まっすぐ下に移動し、プレイヤーに近づいたらその方向に曲げるように動かすコンポーネント /// </summary> [RequireComponent(typeof(Rigidbody2D))] public class MoveObjectCurveToPlayer : MonoBehaviour { /// <summary>移動速度</summary> [SerializeField] float m_speed = 1f; /// <summary>プレイヤーよりどれくらい上で動きを変化するか</summary> [SerializeField] float m_playerOffsetY = 5f; /// <summary>カーブする時にかける力</summary> [SerializeField] float m_chasingPower = 1f; Rigidbody2D m_rb; GameObject m_player; /// <summary>曲がる方向</summary> float m_x = 0f; void Start() { // まずまっすぐ下に移動させる m_rb = GetComponent<Rigidbody2D>(); m_rb.velocity = Vector2.down * m_speed; m_player = GameObject.FindGameObjectWithTag("Player"); } void Update() { // プレイヤーがいない時は何もしない if (m_player) { // プレイヤーとある程度近づいたら if (this.transform.position.y - m_player.transform.position.y < m_playerOffsetY) { // 左右どちらに曲がるか判定する if (m_x == 0) { m_x = (m_player.transform.position.x > this.transform.position.x) ? 1 : -1; // m_x = 1 => 右方向、m_x = -1 => 左方向を「三項演算子」を使って計算している } // カーブする m_rb.AddForce(m_x * Vector2.right * m_chasingPower); } } } }
efb8953b0c8a3c0aed6718f33522d959052b0257
C#
semenow94/CS-Algoritms-and-Structures
/HW2-2/Program.cs
3.9375
4
using System; namespace HW2_2 { //Требуется написать функцию бинарного поиска, посчитать его асимптотическую сложность и проверить работоспособность функции. //O(n)=log(n) class Program { static void Main() { Console.WriteLine("Имеем отсортированный массив из 20 элементов"); Random random = new Random(); int[] array = new int[20]; for(int i=0; i<20; i++) { array[i] = random.Next(1, 20); } Array.Sort(array); for(int i = 0; i < 20; i++) { Console.Write(array[i] + " "); } Console.WriteLine(); Console.WriteLine("Ищем элемент со значением 10"); int index = BinarySearch(array, 10); if (index >= 0) Console.WriteLine("Это элемент с индексом "+index); else Console.WriteLine("Такого элемента нет в массиве"); } public static int BinarySearch(int[] inputArray, int searchValue) { int min = 0; int max = inputArray.Length - 1; while (min <= max) { int mid = (min + max) / 2; if (searchValue == inputArray[mid]) { return mid; } else if (searchValue < inputArray[mid]) { max = mid - 1; } else { min = mid + 1; } } return -1; } } }
a7ab5a10d3486c0de0f80a04bcc6c8cd15800f5d
C#
RichardBradley/MMEd
/MMEd/Ad3ds/FaceListChunk.cs
2.859375
3
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace MMEd.Ad3ds { class FaceListChunk : Chunk { public override void Deserialise(Stream xiInStream, int xiLength) { BinaryReader lReader = new BinaryReader(xiInStream); int lCount = (int)lReader.ReadUInt16(); for (int ii = 0; ii < lCount; ++ii) { Face lFace; lFace.Vertex1 = lReader.ReadUInt16(); lFace.Vertex2 = lReader.ReadUInt16(); lFace.Vertex3 = lReader.ReadUInt16(); lReader.ReadUInt16(); // these are flags, but we ignore them mFaces.Add(lFace); } } public override void AddChild(Chunk xiChild) { throw new Exception("The method or operation is not implemented."); } public override string ToString() { return base.ToString() + " count: " + mFaces.Count; } public override int Length { get { return 6 + 2 + (mFaces.Count * 8); } } public override void Serialise(Stream xiOutStream) { BinaryWriter lWriter = new BinaryWriter(xiOutStream); lWriter.Write(FACE_LIST); lWriter.Write(Length); lWriter.Write((ushort)mFaces.Count); foreach (Face lFace in mFaces) { lWriter.Write(lFace.Vertex1); lWriter.Write(lFace.Vertex2); lWriter.Write(lFace.Vertex3); lWriter.Write((ushort)0x002); // this seems to work } } public void AddFace(Face xiFace) { mFaces.Add(xiFace); } List<Face> mFaces = new List<Face>(); } }
881a275e1bd588d42309d98331913461aba37d58
C#
kurtosmate/DesignPatterns
/DesignPatterns/Command/Command.cs
2.875
3
namespace DesignPatterns.Command { /// <summary> /// The 'Command' abstract class /// </summary> abstract class Command { protected Adder receiver; // Constructor public Command(Adder receiver) { this.receiver = receiver; } public abstract int Execute(int original); public abstract int Undo(); } }
a710239abe4cd53630b8ebbc108f1a1c689c70c9
C#
mvppet/Community
/CommunityClassLibraryTests/CommunityClassLibrary/Generic/BasicPositionSteps.cs
2.90625
3
using CommunityClassLibrary.Locations; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using TechTalk.SpecFlow; namespace CommunityTests.CommunityClassLibrary.Generic { [Binding] public class BasicPositionSteps { BasicPosition bp; [Given(@"I have a new position object")] public void GivenIHaveANewPositionObject() { bp = new BasicPosition(); } [Given(@"I have a new position object at \((.*), (.*)\)")] public void GivenIHaveANewPositionObjectAt(double x, double y) { bp = new BasicPosition(x,y); } [Then(@"the coordinates should be \((.*), (.*)\)")] public void ThenTheCoordinatesShouldBe(double x, double y) { Assert.AreEqual(x, bp.Value.X); Assert.AreEqual(y, bp.Value.Y); } [Then(@"the string value should be ""(.*)""")] public void ThenTheStringValueShouldBe(string stringValue) { Assert.AreEqual(stringValue, bp.StringValue); } } }
1b64a226a131083fb544868e5cad0b79aad1b5c4
C#
shawn718/KraceGennedy
/KraceGennedy/Controllers/NotificationController.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using KraceGennedy.Interfaces; using KraceGennedy.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace KraceGennedy.Controllers { [Route("api/notification")] public class NotificationController : Controller { public IUserRepositoriesInterface _userRepositoriesInterface { get; } public IWeatherRepositoryInterface _weatherRepositoryInterface { get; } public NotificationController(IUserRepositoriesInterface UserRepositoriesInterface, IWeatherRepositoryInterface weatherRepositoryInterface) { this._userRepositoriesInterface = UserRepositoriesInterface; this._weatherRepositoryInterface = weatherRepositoryInterface; } // GET: api/<controller> [HttpPost] [Route("schedule")] [AllowAnonymous] public IEnumerable<string> GenerateSchedule() { try { //Fetch all Employees var employees = _userRepositoriesInterface.GetEmployees(); //Check db for todays schedule if(employees != null) { //iniialize current date var currentDate = DateTime.Now.Date; //Figure out which day it is var dayOfWeek = DateTime.Now.DayOfWeek.ToString(); if (dayOfWeek == "Sunday") { int numOfDays = 6; //loop through each employees foreach (var emp in employees) { //start schedule check loop for (int i = 1; i <= numOfDays;) { //check if employees hrs were already scheduled for this day var hasSchedule = _userRepositoriesInterface. GetEmpScheduleByID(emp.EmployeeId, currentDate); //if user has no scheduled hrs for selected day generate schedule if (hasSchedule.EmployeeID != null && hasSchedule.EmployeeID != "" && dayOfWeek != "Sunday" && dayOfWeek != "Saturday") { Schedule schedule = new Schedule(); schedule.Day = currentDate.ToString(); schedule.EmployeeID = emp.EmployeeId; //Aquire weather data for users city for currentdate var empWeather = _weatherRepositoryInterface.GetWeatherDataByCityIDAndDate( emp.CityID, currentDate); //determine schedule schedule.Day = determineSchedule(empWeather.WeatherDesc, emp.Position.PositionName, emp.FullName); //store schedule _userRepositoriesInterface.CreateEmployeeSchedule(schedule); } //Checks if email was already sent var emailSent = _userRepositoriesInterface.CheckEmailSent(hasSchedule.ID); if (!emailSent) { //send email } //Increment for loop i = i + 1; //move on to the next day currentDate = currentDate.AddDays(1); } } } else if (dayOfWeek == "Monday") { //Initialize counter int numOfDays = 5; //loop through each employees foreach (var emp in employees) { //start schedule check loop for (int i = 1; i <= numOfDays;) { //check if employees hrs were already scheduled for this day var hasSchedule = _userRepositoriesInterface. GetEmpScheduleByID(emp.EmployeeId, currentDate); //if user has no scheduled hrs for selected day generate schedule if (hasSchedule.EmployeeID != null && hasSchedule.EmployeeID != "" && dayOfWeek != "Sunday" && dayOfWeek != "Saturday") { Schedule schedule = new Schedule(); schedule.Day = currentDate.ToString(); schedule.EmployeeID = emp.EmployeeId; //Aquire weather data for users city for currentdate var empWeather = _weatherRepositoryInterface.GetWeatherDataByCityIDAndDate( emp.CityID, currentDate); //determine schedule schedule.Day = determineSchedule(empWeather.WeatherDesc, emp.Position.PositionName, emp.FullName); //store schedule _userRepositoriesInterface.CreateEmployeeSchedule(schedule); } //Checks if email was already sent var emailSent = _userRepositoriesInterface.CheckEmailSent(hasSchedule.ID); if (!emailSent) { //send email } //Increment for loop i = i + 1; //move on to the next day currentDate = currentDate.AddDays(1); } } } else if (dayOfWeek == "Tuesday") { //Initialize counter int numOfDays = 4; //loop through each employees foreach (var emp in employees) { //start schedule check loop for (int i = 1; i <= numOfDays;) { //check if employees hrs were already scheduled for this day var hasSchedule = _userRepositoriesInterface. GetEmpScheduleByID(emp.EmployeeId, currentDate); //if user has no scheduled hrs for selected day generate schedule if (hasSchedule.EmployeeID != null && hasSchedule.EmployeeID != "" && dayOfWeek != "Sunday" && dayOfWeek != "Saturday") { Schedule schedule = new Schedule(); schedule.Day = currentDate.ToString(); schedule.EmployeeID = emp.EmployeeId; //Aquire weather data for users city for currentdate var empWeather = _weatherRepositoryInterface.GetWeatherDataByCityIDAndDate( emp.CityID, currentDate); //determine schedule schedule.Day = determineSchedule(empWeather.WeatherDesc, emp.Position.PositionName, emp.FullName); //store schedule _userRepositoriesInterface.CreateEmployeeSchedule(schedule); } //Checks if email was already sent var emailSent = _userRepositoriesInterface.CheckEmailSent(hasSchedule.ID); if (!emailSent) { //send email } //Increment for loop i = i + 1; //move on to the next day currentDate = currentDate.AddDays(1); } } } else if (dayOfWeek == "Wednesday") { //Initialize counter int numOfDays = 3; //loop through each employees foreach (var emp in employees) { //start schedule check loop for (int i = 1; i <= numOfDays;) { //check if employees hrs were already scheduled for this day var hasSchedule = _userRepositoriesInterface. GetEmpScheduleByID(emp.EmployeeId, currentDate); //if user has no scheduled hrs for selected day generate schedule if (hasSchedule.EmployeeID != null && hasSchedule.EmployeeID != "" && dayOfWeek != "Sunday" && dayOfWeek != "Saturday") { Schedule schedule = new Schedule(); schedule.Day = currentDate.ToString(); schedule.EmployeeID = emp.EmployeeId; //Aquire weather data for users city for currentdate var empWeather = _weatherRepositoryInterface.GetWeatherDataByCityIDAndDate( emp.CityID, currentDate); //determine schedule schedule.Day = determineSchedule(empWeather.WeatherDesc, emp.Position.PositionName, emp.FullName); //store schedule _userRepositoriesInterface.CreateEmployeeSchedule(schedule); } //Checks if email was already sent var emailSent = _userRepositoriesInterface.CheckEmailSent(hasSchedule.ID); if (!emailSent) { //send email } //Increment for loop i = i + 1; //move on to the next day currentDate = currentDate.AddDays(1); } } } else if (dayOfWeek == "Thursday") { //Initialize counter int numOfDsays = 2; //loop through each employees foreach (var emp in employees) { //start schedule check loop for (int i = 1; i <= numOfDsays;) { //check if employees hrs were already scheduled for this day var hasSchedule = _userRepositoriesInterface. GetEmpScheduleByID(emp.EmployeeId, currentDate); //if user has no scheduled hrs for selected day generate schedule if (hasSchedule.EmployeeID != null && hasSchedule.EmployeeID != "" && dayOfWeek != "Sunday" && dayOfWeek != "Saturday") { Schedule schedule = new Schedule(); schedule.Day = currentDate.ToString(); schedule.EmployeeID = emp.EmployeeId; //Aquire weather data for users city for currentdate var empWeather = _weatherRepositoryInterface.GetWeatherDataByCityIDAndDate( emp.CityID, currentDate); //determine schedule schedule.Day = determineSchedule(empWeather.WeatherDesc, emp.Position.PositionName, emp.FullName); //store schedule _userRepositoriesInterface.CreateEmployeeSchedule(schedule); } //Checks if email was already sent var emailSent = _userRepositoriesInterface.CheckEmailSent(hasSchedule.ID); if (!emailSent) { //send email } //Increment for loop i = i + 1; //move on to the next day currentDate = currentDate.AddDays(1); } } } else if (dayOfWeek == "Friday" || dayOfWeek == "Saturday") { currentDate = currentDate.AddDays(1); } } } catch (Exception ex) { throw ex; } return new string[] { "value1", "value2" }; } private string determineSchedule(string weatherDesc, string positionName, string FullName) { if (weatherDesc == "") { return "to be decided"; } else if (weatherDesc.ToLower().Contains("rain") && positionName.Contains("IT")) { return "Good day " + FullName + ". You are working remotely today."; } else if (weatherDesc.ToLower().Contains("rain") && !positionName.Contains("IT")) { return "Good day " + FullName + ". You are scheduled to only work for 4 hours today."; } else if (weatherDesc.ToLower().Contains("sun")) { return "Good day " + FullName + ". You are scheduled to work for 8 hours today."; } return "to be decided"; } // GET api/<controller>/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/<controller> [HttpPost] public void Post([FromBody]string value) { } // PUT api/<controller>/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/<controller>/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
58adec9385c2b22aba5257c52f8dac5e0b23f926
C#
samuelhegner/Flocking_Unity2D
/Flocking Simulation 2D/Assets/Shapes/Scripts/Runtime/Microtypes/RectPivot.cs
2.578125
3
using UnityEngine; // Shapes © Freya Holmér - https://twitter.com/FreyaHolmer/ // Website & Documentation - https://acegikmo.com/shapes/ namespace Shapes { public enum RectPivot { Corner, Center } public static class RectPivotExtensions { public static Rect GetRect( this RectPivot pivot, Vector2 size ) => pivot.GetRect( size.x, size.y ); public static Rect GetRect( this RectPivot pivot, float w, float h ) => pivot == RectPivot.Corner ? new Rect( 0, 0, w, h ) : new Rect( -w / 2, -h / 2, w, h ); } }
961db073d877b3a06bb0a345b92062ebc975145e
C#
OtherCannon/baja-lang
/compiler/Program.cs
3
3
using System; using LLVMSharp; namespace Baja { class Program { public static Properties BuildProps; static void Main(string[] args) { // Create a new Properties container BuildProps = new Properties(); // Check for arguments. If none given, check for a BajaProject.toml if (args.Length == 0) { // TODO: Add a method to check for BajaProject.toml throw new ArgumentException("Error: No arguments given."); } // Debug check for all commands /* for (int i = 0; i < args.Length; i++) { Console.WriteLine(args[i]); } */ // Switch of First Command switch(args[0]) { case "build": for (int i = 1; i < args.Length; i++) { switch (args[i]) { case "-Warn": // Do a quick check for a number after -Warn if (args.Length < i + 1) { throw new ArgumentException("Error: Value required for -Warn level"); } string WarnNumber = args[i + 1]; int WarnNum = Convert.ToInt32(WarnNumber); BuildProps.WarnLevel = WarnNum; i++; break; case "-Opt": // Do a quick check for a number after -Opt if (args.Length < i + 1) { throw new ArgumentException("Error: Value required for -Opt level"); } string OptNumber = args[i + 1]; int OptNum = Convert.ToInt32(OptNumber); BuildProps.OptLevel = OptNum; i++; break; case "-Name": // Do a quick check for a number after -Name if (args.Length < i + 1) { throw new ArgumentException("Error: Value required for -Name"); } string NameValue = args[i + 1]; BuildProps.Name = NameValue; i++; break; default: if (args[i].EndsWith(".baja")) { Console.WriteLine("Baja file detected! File: {0}", args[i]); } else { Console.WriteLine("Error: Invalid argument for build command."); } break; } } break; default: string CurrentInput = args[0]; Console.WriteLine("Error: Invalid argument: {0}", CurrentInput); break; } Console.WriteLine("WarnLevel: {0}", BuildProps.WarnLevel); Console.WriteLine("OptLevel: {0}", BuildProps.OptLevel); Console.WriteLine("Project Name: {0}", BuildProps.Name); } } }
10291b88f877dfa1203393655f560ba568cae6f1
C#
jordoin/nute
/Armlet/OpenSpace/ArmletServer/Server/HonorLogic/ArmletList.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using NetworkLevel.WCFServices; using PillInterfaces; namespace HonorLogic { internal class ArmletList { private readonly Dictionary<int, Armlet> _armlets = new Dictionary<int, Armlet>(); private readonly object _syncRoot = new object(); private bool IsRegistered(byte armletId) { return _armlets.ContainsKey(armletId); } public bool CreateIfNeeded(byte armletId, Func<byte, Armlet> creator) { lock (_syncRoot) { if (IsRegistered(armletId)) { return false; } _armlets.Add(armletId, creator(armletId)); return true; } } public void UpdateArmlet(PlayerUpdate playerStatusUpdate) { var armlet = _armlets[playerStatusUpdate.ArmletID]; armlet.Update(playerStatusUpdate); } public IEnumerable<IArmletInfo> Get() { lock (_syncRoot) { return _armlets.Values; } } public List<AStoredData> GetDataToStore() { lock (_syncRoot) { return _armlets.Select(a => new AStoredData { Id = a.Value.Id, Name = a.Value.Name.Replace('\n', ' '), Regen = a.Value.Regen }).ToList(); } } /* public void Remove(byte id) { lock (_syncRoot) { if (_armlets.ContainsKey(id)) { _armlets.Remove(id); } } } */ public IArmletInfo[] GetAll() { lock (_syncRoot) { return _armlets.Select(a => a.Value).Cast<IArmletInfo>().ToArray(); } } public IArmletInfo GetById(byte armletId) { lock (_syncRoot) { return _armlets[armletId]; } } } }
eab24e220ca21cf4f4bda0b1320c0773a406bf4c
C#
KillerMaker/ComprasWinForm
/ComprasWinForm/Modelos/CSolicitud.cs
2.78125
3
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ComprasWinForm.Modelos { class CSolicitud : CEntidad { public readonly int? id; public readonly int empleado; public readonly DateTime fecha; public readonly int articulo; public readonly int cantidad; public readonly int unidadMedida; public readonly int estado; public CSolicitud(int id) => this.id = id; public CSolicitud(int? id, int empleado,DateTime fecha,int articulo,int cantidad,int unidadMedida,int estado) { this.id = id; this.empleado = empleado; this.fecha = fecha; this.articulo = articulo; this.cantidad = cantidad; this.unidadMedida = unidadMedida; this.estado = estado; } public async override Task<int> Delete() => await ExecuteCommand($"UPDATE SOLICITUD SET ESTADO =2 WHERE ID ={id}"); public async override Task<int> Insert() => await ExecuteCommand(@"INSERT INTO SOLICITUD VALUES (@EMPLEADO,@FECHA,@ARTICULO,@CANTIDAD,@UNIDAD_MEDIDA,@ESTADO)", GetParameters()); public async override Task<int> Update() => await ExecuteCommand(@"UPDATE SOLICITUD SET EMPLEADO = @EMPLEADO, FECHA = @FECHA, ARTICULO = @ARTICULO, CANTIDAD=@CANTIDAD, UNIDAD_MEDIDA = @UNIDAD_MEDIDA, ESTADO =@ESTADO WHERE ID =@ID",GetParameters()); public async static Task<DataTable> Select(string searchString = null) { string query = "SELECT * FROM VISTA_SOLICITUD" + searchString; using (SqlConnection con = new SqlConnection(stringConnection)) { using (SqlDataReader reader = await ExecuteReader(query, con)) { DataTable table = new DataTable(); table.Columns.Add("Id"); table.Columns.Add("Empleado"); table.Columns.Add("Fecha"); table.Columns.Add("Articulo"); table.Columns.Add("Cantidad"); table.Columns.Add("Unidad de Medida"); table.Columns.Add("Estado"); while (await reader.ReadAsync()) { table.Rows.Add(new string[] { reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString(), reader[4].ToString(), reader[5].ToString(), reader[6].ToString(), }); } return table; } } } public override List<SqlParameter> GetParameters() { SqlParameter id = new SqlParameter("@ID", this.id); SqlParameter empleado = new SqlParameter("@EMPLEADO", this.empleado); SqlParameter fecha = new SqlParameter("@FECHA", this.fecha); SqlParameter articulo = new SqlParameter("@ARTICULO", this.articulo); SqlParameter estado = new SqlParameter("@ESTADO", this.estado); SqlParameter cantidad = new SqlParameter("@CANTIDAD", this.cantidad); SqlParameter unidadMedida = new SqlParameter("@UNIDAD_MEDIDA", this.unidadMedida); id.DbType = DbType.Int32; empleado.DbType = DbType.Int32; estado.DbType = DbType.Int32; articulo.DbType = DbType.String; fecha.DbType = DbType.Date; cantidad.DbType = DbType.Int32; unidadMedida.DbType = DbType.Int32; return (this.id.HasValue) ? new List<SqlParameter>() { id, empleado, articulo, fecha, estado,cantidad,unidadMedida } : new List<SqlParameter>() { empleado, articulo, fecha, estado, cantidad, unidadMedida }; } } }
32efb600efc5cf9d5a32720af6c8c75c28e65f7c
C#
RadSt/WPF-App-For-Ref
/VisualPacker/Models/Container.cs
2.953125
3
using System; using System.Collections.Generic; using System.Windows.Media.Media3D; namespace VisualPacker.Models { public class Container : ICloneable { private int priority; //приоритет загрузки private String color; //Цвет предмета при отображении на схеме укладки (в HTML формате) public Container() { Count = 1; DirLength = "a"; DirWidth = "a"; DirHeight = "a"; priority = 1; Order = 0; PressLength = 10000; PressWidth = 10000; PressHeight = 10000; } //параметры контейнера public int Length { get; set; } //длина public int Width { get; set; } //ширина public virtual int Height { get; set; } //высота public int Count { get; set; } //количество контейнеров в данном объекте(Если kind=box то 1, для комбинированных объектов может быть больше одного) public string Kind { get; set; } //box - обыкновенный прямоугольный ящик с тремя линейными размерами,cyl - цилинлр (бочка или кега) определяемая диамтром и высотой (пример ниже) public string ShipToName { get; set; } //Название ящика - не более 1000 симовлов public string ShipmentId { get; set; } //Название ящика - не более 1000 симовлов public string Name { get; set; } //Название ящика - не более 1000 симовлов public string ShortName { get; set; } //Название ящика - не более 1000 симовлов public string ContainerType { get; set; } public double Mass { get; set; } //массa public double Price { get; set; } //Стоимость public bool IsChecked { get; set; } //Стоимость public string DirLength { get; set; } public string DirWidth { get; set; } public string DirHeight { get; set; } /* Ограничение на ориентацию ящика в транспортном средстве Данный раздел определяет вдоль каких направлений могут быть ориентированы линейные размеры ящика - a - вдоль любого направления --> - x - ТОЛЬКО вдоль направления X (вдоль длины ТС) --> - у - ТОЛЬКО вдоль направления Y (вдоль ширины ТС) --> - z - ТОЛЬКО вдоль направления Z (вдоль высоты ТС) --> В частности, для того чтобы ящик не кантовался при укладке надо указать значение z для параметра height.*/ public int Order { get; set; } /* Порядок загрузки. Если в списке ящиков есть ящики с разным порядком, то сначала будут загужены ящики с порядком 0, затем с порядком 1, и т.п. Данная функциональность используется в случае, когда ТС загружается или разгруажается в нескольких точках. В этом случае алгоритм предложит такую схему укладки, при которой сначала можно загрузить ящики порядка 0, затем, в следующей точке, дозагрузить к ним ящики порядка 1 и так далее */ public string GroupName { get; set; } //Название группы public int GroupId { get; set; } //Иденттификатор группы, должен быть одним и тем же для всех ящиков комплекта /* Группы предмета. --> В некоторых случаях, определенные наборы ящиков определяют некий комплект. Например, когда перевозится мебель в разобранном состоянии, все составные части одного предмета мебели составлют комплект (или группу). При это в каждой ТС должно быть обязатльно загружено целое число комплектов. То есть недопустимо, чтобы часть составных частей одного предмета медели вошли в одно ТС, а часть в другое. Для того чтобы алгоритм вычислят схему укладки, в кторой все ящики одного коплекта обязательно входят в одно ТС, для ящиков такого типа надо определить параметры группы <group>*/ public int GroupQuantity { get; set; } /* Количество ящиков такого типа в комлекте Например, в комплект шкафа могут входить 3 одинкаовых ящика "полки", при этом количество самих комплектов может быть больше 1, например, 4. Тогда данное значение должно быть равно 3, а параметр quantity (полное количество ящиков) 3*4=12 */ public double PressLength { get; set; } //Допустимое давление на яшик, если его длина ориентирована вертикально. public double PressWidth { get; set; } //Допустимое давление на яшик, если его ширина ориентирована вертикально. public double PressHeight { get; set; } // Допустимое давление на яшик, если его высота ориентирована вертикально. /*Допустимое давление на яшик сверху, если он ориентирован указанным линейным размером вертикально. Когда ящик хрупкий, и нельзя чтобы на него было поставлено много тяжелых ящиков, надо этим параметром ограничивать максимально допустимое давление. Однако, подбирая наиболее удачное и оптимальное положение ящика, алгоритм может переворачивать его. И для разных ориентаций ящика, может быть указано разное ограничение. <!-- Если параметр не указан - ограничение отсутсвует. */ public int FragilityLength { get; set; } //хрупкость ящика, если его длина ориентирована вертикально. public int FragilityWidth { get; set; } //хрупкость ящика, если его ширина ориентирована вертикально. public int FragilityHeight { get; set; } //хрупкость ящика, если его высота ориентирована вертикально. /* Хрупкость ящика: --> - 0 - означает, что ящик не имеет ограничений по хрупкости (установки на него сверху других предметов), - 1 - означает, что никакие ящики не могут быть установлены сверху данного ящика, - N>1 -означает, что не более чем (N-1) ящиков такого же ти могут быть установлены сверху данного ящика.*/ public int Freezable { get; set; } /* Замерзаемость ящика (морозостоякость) --> В некоторых случаях, когда речь идет о перевозки продуктов, в зимнее время года, определенные ящики надо ставить подальше от двери, чтобы они не замерзли. Этот параметр определяет требования к установке ящика подальше от двери, 0 - нет ограничение на установку, 1 - ящик чуствителен к морозу. */ public int PalQuantity { get; set; } /* Количество ящиков на паллете. --> Парамерт определяет количество ящков такого типа на паллетах, хранящихся на складе. Данный параметр используется в методе рядной загрузки, когда мы должны укалдывать ящики последовательно, причем каждый раз использовать такое кочлиество, которое кратное количеству ящиков на паллете. Это надо для того, чтобы гузчики последовательног гурзили паллеты поступающие со склада, а не откладывали с них ящики "на потом". Замечание: этот параметр никак не связан с укладкой ящиков на паллетах. */ public int Level { get; set; } /* Уровень укладки. Это свойство является альтернативой всяким максимальным давлениеям на грань и определяет какие предметы могут быть сверху каких. Предметы 0-вого уровня могут быть в любом месте и допускают установку сверху любых предметов. На предметы уровня N можно ставить только предметы уровня N и выше. */ public int Quantity { get; set; }// Количество предметов такого типа в заказе на расчет public int Only4Bottom { get; set; } public Point3D FirstPoint { get; set; } //положение левого нижнего угла public virtual int Priority { get { return priority; } set { priority = value; } } public virtual string PriorityString { get { if (Priority == 0) { return "Срочный"; } return "Обычный"; } set { if (value == null) throw new ArgumentNullException("value"); PriorityString = value; } } public String Color { get { if (color == null) { return "Blue"; } return color.Replace("#", "").Replace("%", ""); } set { color = value; } } public virtual int Area { get { return Length*Width; } } public double Volume { get { return Length*Width*Height; } } public String Vgh { get { return Length + "x" + Width + "x" + Height; } } public bool AreSame01(Container container) { if ((Length <= container.Length & Length >= 0.8 * container.Length) & (Width <= container.Width & Width >= 0.8 * container.Width)) return true; return false; } public bool IsSuitableLength(double maxLength) { if (Length <= maxLength | (Width <= maxLength & DirLength != "y")) return true; return false; } public bool IsSuitableWidth(double maxWidth) { if (Length >= Width) { if ((Length <= maxWidth & Length > maxWidth - 100 & DirLength != "y") | (Width <= maxWidth & Width > maxWidth - 100 & DirLength != "x")) return true; return false; } if ((Length <= maxWidth & Length > maxWidth - 100 & DirLength != "x") | (Width <= maxWidth & Width > maxWidth - 100 & DirLength != "y")) return true; return false; } public virtual void ToContainerList(List<Container> tempList) { tempList.Add(this); } public virtual void RotateH() { int temp = Length; Length = Width; Width = temp; } public virtual object Clone() { Container container = new Container { Count = Count, Length = Length, Width = Width, Height = Height, Priority = Priority, Kind = Kind, Name = Name, ShipToName = ShipToName, ShipmentId = ShipmentId, ContainerType = ContainerType, Mass = Mass, Price = Price, DirLength = DirLength, DirWidth = DirWidth, DirHeight = DirHeight, Order = Order, GroupName = GroupName, GroupId = GroupId, GroupQuantity = GroupQuantity, PressLength = PressLength, PressWidth = PressWidth, PressHeight = PressHeight, FragilityLength = FragilityLength, FragilityWidth = FragilityWidth, FragilityHeight = FragilityHeight, Freezable = Freezable, Level = Level, Color = Color, Quantity = Quantity, Only4Bottom = Only4Bottom, FirstPoint = new Point3D(FirstPoint.X, FirstPoint.Y, FirstPoint.Z), IsChecked = IsChecked }; return container; } } }
7ca63bc4d1cffbbc78238b0bfd0aa2d0ce271e97
C#
tolchev/Budget
/WpfObjectView/Views/DetailFrameItems/DetailFrameItemContainer.cs
2.625
3
using System.Collections.Generic; using System.Reflection; using System.Windows; using System.Windows.Data; namespace WpfObjectView.Views.DetailFrameItems { class DetailFrameItemContainer { readonly List<BindingExpressionBase> bindingExpressions; readonly DetailFrameItemFactory itemFactory; public DetailFrameItemContainer() { bindingExpressions = new List<BindingExpressionBase>(); itemFactory = new DetailFrameItemFactory(); } public DetailFrameItemBase Create(PropertyInfo info, object viewModel) { Binding binding = new Binding(); binding.Path = new PropertyPath(info.Name); binding.Mode = info.CanWrite ? BindingMode.TwoWay : BindingMode.OneWay; binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit; DetailFrameItemBase item = itemFactory.Create(info, viewModel); bindingExpressions.Add(item.SetBindingExpression(binding)); return item; } public void Update() { foreach (var be in bindingExpressions) { be.UpdateSource(); } } public void Clear() { bindingExpressions.Clear(); } } }
13b74ab991aac4ffc6853a6693ddb4709c099b32
C#
sametcem/csharp
/Task10/Controllers/StudentsController.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Task10.Models; namespace Task10.Controllers { public class StudentsController : Controller { List<Student> lst; public StudentsController() { lst = new List<Student>() { new Student {IdStudent = 1,FirstName = "Louis",LastName = "Tyson",Address = "Ankara",IndexNumber = "s17181",StudyName = "Computer Science"}, new Student { IdStudent = 2, FirstName = "Jack", LastName = "Jones", Address = "Istanbul", IndexNumber = "s17182", StudyName = "Media Art" }, new Student { IdStudent = 3, FirstName = "Frey", LastName = "Mark", Address = "Izmir", IndexNumber = "s17183", StudyName = "Database" } }; } public IActionResult Index() { //ViewBag.Message = "Dude,its simple."; return View(lst); } public ActionResult Delete(int? i) { var st = lst.Find(c => c.IdStudent == i); lst.Remove(st); return View("Index", lst); } public ActionResult Add() { var std = new Student() { IdStudent = 4, FirstName = "Smith", LastName = "Jordan", Address = "Karaman", IndexNumber = "s17184", StudyName = "Computer Science" }; lst.Add(std); return View("Index", lst); } } }
587e3f4af3f2d4ca7ac80cd4b95ad08385fb30c5
C#
hirotk/Algorithm
/AlgorithmTest/BinarySearchTest.cs
2.953125
3
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Algorithm; namespace AlgorithmTest { [TestClass] public class BinarySearchTest { static int[] a = { -2, 0, 2, 3, 5, 7, 11, 11, 13, 17, 19, 23}; [TestMethod] public void IndexOfTest() { int expected = -1; int actual = BinarySearch.IndexOf(a, -3); Assert.AreEqual(expected, actual); expected = 0; actual = BinarySearch.IndexOf(a, -2); Assert.AreEqual(expected, actual); expected = 6; actual = BinarySearch.IndexOf(a, 11); Assert.AreEqual(expected, actual); expected = 11; actual = BinarySearch.IndexOf(a, 23); Assert.AreEqual(expected, actual); expected = -1; actual = BinarySearch.IndexOf(a, 24); Assert.AreEqual(expected, actual); } [TestMethod] public void IndexOfRecTest() { int expected = -1; int actual = BinarySearch.IndexOf(a, -3); Assert.AreEqual(expected, actual); expected = 0; actual = BinarySearch.IndexOf(a, -2); Assert.AreEqual(expected, actual); expected = 6; actual = BinarySearch.IndexOf(a, 11); Assert.AreEqual(expected, actual); expected = 11; actual = BinarySearch.IndexOf(a, 23); Assert.AreEqual(expected, actual); expected = -1; actual = BinarySearch.IndexOf(a, 24); Assert.AreEqual(expected, actual); } } }
c072cf0e0e7a685cdce10238f2184f1f9c56ddff
C#
beetee2/BlackJackMVC
/Blackjack/Models/Card.cs
3.328125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Diagnostics; namespace Blackjack { public class Card { private string[] suits = {"club", "diamond", "heart", "spade"}; private List<string> letters = new List<string> { "j", "q", "k"}; private List<string> numbers = Enumerable.Range(1, 10).ToList().ConvertAll<string>(i => i.ToString()); public string suit { get; set; } public string value { get; set; } public Card() { // ugly way to help initialize random constructor with differnt seed System.Threading.Thread.Sleep(1); Random rnd = new Random(DateTime.Now.Millisecond); List<string> values = numbers.Union(letters).ToList<string>(); this.suit = suits[rnd.Next(suits.Length - 1)]; this.value = values[rnd.Next(values.Count - 1)]; } public string getImageName(bool back) { if (back) { return "b1fv.gif"; } return string.Format("{0}{1}.gif", this.suit.Substring(0,1), this.value.ToString()); } public string getAltName() { return string.Format("{0} of {1}s", this.getIntValue(), this.suit); } public int getIntValue() { try { return int.Parse(this.value); } catch (System.FormatException) { return 10; } } } }
3a7bdab8cd440610815675c64c8d677740703321
C#
flovo89/Logger
/Logger/Logger.Common.Base/Prism/DelegateLogger.cs
2.75
3
using System; using Microsoft.Practices.Prism.Logging; namespace Logger.Common.Prism { public sealed class DelegateLogger : ILoggerFacade { #region Instance Constructor/Destructor public DelegateLogger (Action<string, Category, Priority> loggingDelegate) { if (loggingDelegate == null) { throw new ArgumentNullException(nameof(loggingDelegate)); } this.LoggingDelegate = loggingDelegate; } #endregion #region Instance Properties/Indexer private Action<string, Category, Priority> LoggingDelegate { get; } #endregion #region Interface: ILoggerFacade public void Log (string message, Category category, Priority priority) { this.LoggingDelegate(message, category, priority); } #endregion } }
aed2c083bc4b41a5933119cc26d8fc57a7d3724e
C#
ap0llo/mddocs
/src/MdDocs.ApiReference/Model/_Extensions/TypeReferenceExtensions.cs
2.859375
3
using System.Collections.Generic; using System.Linq; using Mono.Cecil; namespace Grynwald.MdDocs.ApiReference.Model { /// <summary> /// Extension methods for <see cref="TypeReference"/>. /// </summary> internal static class TypeReferenceExtensions { /// <summary> /// Gets the <see cref="MemberId"/> for the specified type. /// </summary> public static MemberId ToMemberId(this TypeReference typeReference) => typeReference.ToTypeId(); /// <summary> /// Gets the <see cref="TypeId"/> for the specified type. /// </summary> public static TypeId ToTypeId(this TypeReference typeReference) => typeReference.ToTypeId(Enumerable.Empty<TypeReference>()); private static TypeId ToTypeId(this TypeReference typeReference, IEnumerable<TypeReference> genericTypeArguments) { // generic instance type: a generic type with type arguments // does not necessarily mean the type arguments are real types // they can still be type parameters if (typeReference is GenericInstanceType genericInstanceType) { return GetGenericTypeInstanceId(genericInstanceType); } // handle a type with type parameters but explicitly specified type arguments // this can happen when converting generic nested types // e.g. // for the type OuterClass<string>.NestedClass<int>, the structure looks like this // NestedClass: // Type Arguments: string, int // Type Parameters: <None> // DeclaringType: OuterClass // OuterClass: // Type Arguments: <None> // Type Parameters: 1 else if (typeReference.HasGenericParameters && genericTypeArguments.Any()) { return GetGenericTypeInstanceId(typeReference, genericTypeArguments); } // Unbound generic type, e.g. // class Foo<T> // { } else if (typeReference.HasGenericParameters) { return GetGenericTypeId(typeReference); } // type is an generic parameter, e.g. the "T" in // class Foo<T> // { } else if (typeReference is GenericParameter genericParameter) { // parameter is declared at the method level if (genericParameter.DeclaringMethod != null) { var index = genericParameter.DeclaringMethod.GenericParameters.IndexOf(genericParameter); return new GenericTypeParameterId(GenericTypeParameterId.MemberKind.Method, index, genericParameter.Name); } // parameter is declared at the type-level else { var index = genericParameter.DeclaringType.GenericParameters.IndexOf(genericParameter); return new GenericTypeParameterId(GenericTypeParameterId.MemberKind.Type, index, genericParameter.Name); } } // type is an array type else if (typeReference is ArrayType arrayType) { return new ArrayTypeId(arrayType.ElementType.ToTypeId(), arrayType.Dimensions.Count); } // reference type ('ref', 'out' and 'in' parameters) else if (typeReference is ByReferenceType byReferenceType) { return new ByReferenceTypeId(byReferenceType.ElementType.ToTypeId()); } // type is a "normal", non-generic type else { // nested type if (typeReference.IsNested) { return new SimpleTypeId(typeReference.DeclaringType.ToTypeId(), typeReference.Name); } // top-level / non-nested type else { return new SimpleTypeId(new NamespaceId(typeReference.Namespace), typeReference.Name); } } } private static TypeId GetGenericTypeInstanceId(GenericInstanceType typeReference) { return GetGenericTypeInstanceId(typeReference, typeReference.GenericArguments); } private static TypeId GetGenericTypeInstanceId(TypeReference typeReference, IEnumerable<TypeReference> genericTypeArguments) { if (typeReference.IsNested) { // Handling of nested generic types: // For e.g. the type 'OuterClass<string>.NestedClass<int>', the type reference looks like this // // NestedClass`1: // Type Arguments: string, int // Type Parameters: <None> // DeclaringType ──────────┐ // │ // OuterClass`1: <──────────┘ // Type Arguments: <None> // Type Parameters: 1 // // In that case, get the required arguments for the declaring type and construct a type id for it // The remaining type arguments are used to build the type id for the current type // If *all* the arguments are required for the declaring type, return a non-generic type. // This is valid when a non-generic type is nested inside a generic type, e.g. 'OuterClass<string>.InnerClass' // var myTypeArgs = genericTypeArguments.Skip(typeReference.DeclaringType.GenericParameters.Count).ToArray(); var declaringTypeArgs = genericTypeArguments.Take(typeReference.DeclaringType.GenericParameters.Count); var declaringTypeId = typeReference.DeclaringType.ToTypeId(declaringTypeArgs); // for nested generic instance types, the type has all the type arguments // including the arguments for the declaring types if (myTypeArgs.Length == 0) { return new SimpleTypeId(declaringTypeId, typeReference.Name); } else { // remove the number of type parameters from the name var name = typeReference.Name.Substring(0, typeReference.Name.LastIndexOf('`')); var typeArguments = myTypeArgs .Select(x => x.ToTypeId()) .ToArray(); return new GenericTypeInstanceId( declaringTypeId, name, typeArguments); } } else { // remove the number of type parameters from the name var name = typeReference.Name.Substring(0, typeReference.Name.LastIndexOf('`')); var typeArguments = genericTypeArguments .Select(x => x.ToTypeId()) .ToArray(); return new GenericTypeInstanceId( new NamespaceId(typeReference.Namespace), name, typeArguments); } } private static TypeId GetGenericTypeId(TypeReference typeReference) { // if the type is nested and has generic parameters, // no all parameters are parameters of the type but might also be parameters // of the declaring type, // e.g. // // class Class1<T> // { // class Class2 // { // } // } // // In this case, Class2 would also have a generic type parameter // if (typeReference.IsNested) { // get the id of the declaring type var declaringType = typeReference.DeclaringType.ToTypeId(); // determine which type parameter are the type's parameters // and which parameters are parameters of the declaring types var declaringTypeGenericParamters = typeReference.DeclaringType .GenericParameters .Select(x => x.Name) .ToArray(); var genericParameters = typeReference .GenericParameters .Select(x => x.Name) .Except(declaringTypeGenericParamters) .ToArray(); // if all type parameters are declared in the declaring type, // return a non-generic type if (genericParameters.Length == 0) { return new SimpleTypeId(declaringType, typeReference.Name); } else { // remove the number of type parameters from the name var name = typeReference.Name.Substring(0, typeReference.Name.LastIndexOf('`')); return new GenericTypeId(declaringType, name, genericParameters.Length, genericParameters); } } else { // remove the number of type parameters from the name var name = typeReference.Name.Substring(0, typeReference.Name.LastIndexOf('`')); // get the names of the type parameters // so the GenericTypeId's DisplayName matches // the definition var typeParameterNames = typeReference.GenericParameters.Select(x => x.Name).ToArray(); return new GenericTypeId(new NamespaceId(typeReference.Namespace), name, typeReference.GenericParameters.Count, typeParameterNames); } } } }
56a1d0b7c7e38250f9179f2f5c41e1d5f2ff0de1
C#
subbudatta/csv
/Test/ArgumentsTest.cs
2.53125
3
using NUnit.Framework; using System; using System.IO; namespace DevOps.Tests.CSVConverter { [TestFixture] public class ArgumentsTest { private static string assemblyPath = System.Reflection.Assembly.GetAssembly(typeof(ArgumentsTest)).Location; private static string assemblyDir = Path.GetDirectoryName(assemblyPath); private static string xmlfileDir = Path.GetFullPath( Path.Combine(assemblyDir, @"..\..\..\Examples\HelloWorld\CSVTestInputs") ); private static DirectoryInfo outputDirectory = new DirectoryInfo(Path.GetFullPath( Path.Combine(assemblyDir, @"..\..\..\Examples\HelloWorld\CSVTestInputs\Output") )); private static DirectoryInfo WrongoutputDirectory = new DirectoryInfo(Path.GetFullPath( Path.Combine(assemblyDir, @"..\..\..\Examples\HelloWorld\CSVTestInputs") )); private static DirectoryInfo FixedoutputDirectory = new DirectoryInfo(Path.GetFullPath( Path.Combine(assemblyDir, @"..\..\..\Examples\HelloWorld\CSVTestInputs\fixedOutput") )); private static string WrongxmlfileDir = Path.GetFullPath( Path.Combine(assemblyDir, @"..\..\..\Examples\HelloWorld\CSVTestInput") ); public DevOps.CSVConverter.Arguments TestObject; public DevOps.CSVConverter.Program TestMainFuncObject; //private static string xmlDirectory = @"D:\resultxmls"; //private static string outputDirectory = @"D:\resultxmls"; private static string[] validArguments = { "--xmlFileDirectory", xmlfileDir, "--OutputDirectory", outputDirectory.FullName }; private static string[] inValidArguments = { "--xmlDirectory", xmlfileDir, "--OutputDirectory", outputDirectory.FullName }; private static string[] inValidArguments2 = { "--xmlDirectory", xmlfileDir, "--OutputDirector", outputDirectory.FullName }; private static string[] wrongArguments = { "--xmlFileDirectory", WrongxmlfileDir, "--OutputDirectory", outputDirectory.FullName }; [SetUp] public void TestSetup() { Console.WriteLine("TestSetup goes here"); if (!Directory.Exists(outputDirectory.FullName)) { Directory.CreateDirectory(outputDirectory.FullName); } TestObject = new DevOps.CSVConverter.Arguments(); TestMainFuncObject = new DevOps.CSVConverter.Program(); } [Test] public void TestThatWithValidArgumentsTheParsePasses() { bool returnValue = TestObject.Parse(validArguments); Assert.AreEqual(true, returnValue, "Expected different input"); } [Test] public void TestThatWithInvalidArgumentsTheParseFails() { bool returnValue = TestObject.Parse(inValidArguments); Assert.AreEqual(false, returnValue, "Expected different input"); } [Test] public void TestThatWithInvalidOutputArgumentsTheParseFails() { bool returnValue = TestObject.Parse(inValidArguments2); Assert.AreEqual(false, returnValue, "Expected different input"); } // TODO: Tests which calls exe and checks the ouput //This Test will pass and creates a Folder (Output) and stores the output in that folder [Test] public void TestThatWithValidArgumentsToTheMainMethodTheTestPasses() { int returnValue = DevOps.CSVConverter.Program.Main(validArguments); Assert.AreEqual(0, returnValue, "Expected different input"); } //This test wont create the Output Folder since invalid arument are passesd and the test returns -1 [Test] public void TestThatWithInValidArgumentsToTheMainMethodTheTestPasses() { int returnValue = DevOps.CSVConverter.Program.Main(inValidArguments); Assert.AreEqual(-1, returnValue, "Expected different input"); } //This tests output will be -1 since wrong path of the xml file is passed [Test] public void TestWithWrongXMLFilePathTheOutputWillBeMINUSONE() { int returnValue = DevOps.CSVConverter.Program.Main(wrongArguments); Assert.AreEqual(-1, returnValue, "Expected different input"); } //This Test Will Return 0 if the folder path passed contains required output [Test] public void TestThatReturnsZEROIfOutputFileisGenerated() { int returnValue = DevOps.CSVConverter.Program.CheckOutputGenerated((FixedoutputDirectory.FullName+"\\ConsolidatedResults.csv")); Assert.AreEqual(0, returnValue, "Expected different input"); } //This Test Will Return -1 if the folder path passed does not contains required output [Test] public void TestThatReturnsMINUSONEIfOutputFileisNotGenerated() { int returnValue = DevOps.CSVConverter.Program.CheckOutputGenerated((WrongoutputDirectory.FullName +"\\ConsolidatedResults.csv")); Assert.AreEqual(-1, returnValue, "Expected different input"); } [TearDown] public void TestTearDown() { Console.WriteLine("TestSetup teardown here"); if (!Directory.Exists(outputDirectory.FullName)) { Directory.CreateDirectory(outputDirectory.FullName); } TestObject = null; } } }
643a80e4c7448f1919a40d2469c9b47d503978a1
C#
BMerlo/JDynamic
/Assets/_Scripts/JsonDynamic.cs
3.078125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class JsonDynamic : MonoBehaviour { //need these strings to load and handle data string path = null; string textAsset = null; [SerializeField] UIBuilder uiBuilderRef; List<string> headersList = new List<string>(); List<string> memberList = new List<string>(); public List<List<string>> ListofLists = new List<List<string>>(); void Awake() { //in awake so I'm sure that the info is ready when called from UI Builder //read the file path = Application.dataPath + "/StreamingAssets/JsonChallenge.json"; //make it a string textAsset = System.IO.File.ReadAllText(path); //splitting file for better handling string[] txtArray = textAsset.Split(char.Parse("["), char.Parse("]")); //getting headers for table HeaderListFiller(txtArray); // Parsing Data for each member MemberListFiller(txtArray); //Filling up list of lists to handle info before showing it ListOfListsFiller(); } private void HeaderListFiller(string[] txtArray) { //in 1 is the data that I need for this string[] headers = txtArray[1].Split(char.Parse("\"")); //then it's added to a list for (int i = 0; i < headers.Length - 1; i++) { if (i % 2 != 0) { headersList.Add(headers[i]); } } } private void MemberListFiller(string[] txtArray) { //in 3 is the data that I need for this string[] dataArray = txtArray[3].Split(char.Parse("{"), char.Parse("}")); //then it's added to a list for (int i = 0; i < dataArray.Length - 1; i++) { if (i % 2 != 0) { memberList.Add(dataArray[i]); } } } private void ListOfListsFiller() { for (int i = 0; i < memberList.Count; i++) { ListofLists.Add(new List<string>()); string[] InfoMiembro = memberList[i].Split(char.Parse(",")); for (int j = 0; j < headersList.Count; j++) { //I need to clean it a little bit before passing to UI Builder string[] ListALimpiar = InfoMiembro[j].Split(char.Parse(":")); //I don't care about the attribute, so I'll just keep the data string ListaLimpia = ListALimpiar[1].Replace("\"", string.Empty); ListofLists.ElementAt(i).Add(ListaLimpia); } } } private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } } //methods to create UI and keep things tidy public int GetNumberOfMembers() { return memberList.Count; } public int GetNumberOfAttributes() { return headersList.Count; } public string GetNthAttributeName(int number) { return headersList.ElementAt(number); } public string GetNthAttribute(int member, int attribute) { return ListofLists.ElementAt(member).ElementAt(attribute); } //methods to handle data updates public void UpdateJsonFile() { textAsset = System.IO.File.ReadAllText(path); UpdateLists(); } public void UpdateLists() { headersList.Clear(); memberList.Clear(); ListofLists.Clear(); string[] txtArray = textAsset.Split(char.Parse("["), char.Parse("]")); HeaderListFiller(txtArray); MemberListFiller(txtArray); ListOfListsFiller(); } }
fb52e880e57fbd01961ed05f9d0137b87e931521
C#
amd-9/simple-api
/GeoHelper/GeoHelper.cs
2.8125
3
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; namespace GeoHelper { public class GeoHelper { private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILogger<GeoHelper> _logger; private readonly HttpClient _httpClient; public GeoHelper() { //_httpContextAccessor = httpContextAccessor; //_logger = logger; _httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(5) }; } public async Task<GeoInfo> GetGeoInfo(string ip) { //var ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress; var key = "8a8c1cec23d2627b7c93a50c657be2f7"; try { var response = await _httpClient.GetAsync($"http://api.ipstack.com/{ip}?access_key={key}&output=json&legacy=1"); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<GeoInfo>(json); } } catch (Exception ex) { //_logger.LogError(ex, "Failed to retrieve geo info for ip '{0}'", ip); } return null; } } }
b3cf7d168ef345e8d3e2c14d5bf9fc995a91d88d
C#
wujpkimo/TranningCsharp
/Lession2/ConsoleApp3/Program.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp3 { internal class Program { private static void Main(string[] args) { int[] v4 = new int[] { 4,44,444 }; int sum = 0; //for (int i = 0; i < v4.Length; i++) //{ // Console.WriteLine(v4[i]); //} for (int i = 1; i <= 1000; i++) { if (v4[0] == i || v4[1] == i || v4[2] == i) continue; sum += i; Console.WriteLine("i={0},sum={1}", i, sum); } } } }
bbeb2e301b375bc4b2c997d32881d071592d9858
C#
larielrary/IT-DDP
/LR2/LR2/Controllers/DiaryNoteController.cs
2.71875
3
using ClassLibrary; using ClassLibrary.Repository; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; namespace MeteorologicalDiaryServer.Controllers { [Route("api/[controller]")] [ApiController] public class DiaryNoteController : ControllerBase { private readonly IRepository<DiaryNote> _repository; public DiaryNoteController() { _repository = new Repository<DiaryNote>("diary.json"); } [HttpGet] public ActionResult<IEnumerable<DiaryNote>> Get() { return _repository.GetAll().ToList(); } [HttpGet("{id}")] public ActionResult<DiaryNote> Get(int id) { return _repository.GetById(id); } [HttpPut] public ActionResult Put(DiaryNote note) { _repository.Update(note); return Ok(note); } [HttpPost] public ActionResult Post(DiaryNote note) { _repository.Create(note); return Ok(note); } [HttpDelete("{id}")] public ActionResult Delete(int id) { _repository.Delete(id); return Ok(); } } }
c31101195a08f2f0f5694964195883d826ee9dd5
C#
NickUsov/asp-hw-2
/Controllers/HomeController.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApplication3.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } public ActionResult Calc(double a, double b, string action) { ViewBag.a = a; ViewBag.b = b; ViewBag.action = action; switch (action) { case "+": { ViewBag.result = a + b; } break; case "-": { ViewBag.result = a - b; } break; case "*": { ViewBag.result = a * b; } break; case "/": { ViewBag.result = a / b; } break; default: ViewBag.result = ""; break; } return View(); } } }
053a266f6e6a47d1c75eb7ef75d9f147d9e0cdae
C#
themultiv3rs3/samples
/CS/App_Code/SqlServerPdfLiteSessionProvider.cs
2.625
3
using System; using System.Data; using System.Data.SqlClient; using System.Web; using RadPdf.Lite; // Not in use by default // Uncomment the approprate line in CustomPdfIntegrationProvider.cs public class SqlServerPdfLiteSessionProvider : PdfLiteSessionProvider { /* This class assumes a SQL Server table called "sessions": CREATE TABLE [dbo].[sessions]( [id] [varchar](255) COLLATE Latin1_General_CS_AS NOT NULL, [value] [varbinary](max) NOT NULL, CONSTRAINT [PK_sessions] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] */ private readonly SqlConnection _connection; // This example uses an a simple SQL Server database for sessions public SqlServerPdfLiteSessionProvider(string connectionString) : base() { _connection = new SqlConnection(connectionString); _connection.Open(); } public override string AddSession(PdfLiteSession session) { // Generate a session key using RAD PDF's default generator. // Your own generator can be used here instead. string key = GenerateKey(); using (SqlCommand command = _connection.CreateCommand()) { command.CommandText = "INSERT INTO sessions (id, value) VALUES (@id, @value)"; command.Parameters.Add("@id", SqlDbType.VarChar, 255).Value = key; command.Parameters.Add("@value", SqlDbType.VarBinary, -1).Value = session.Serialize(); command.ExecuteNonQuery(); } return key; } public override PdfLiteSession GetSession(string key) { using (SqlCommand command = _connection.CreateCommand()) { command.CommandText = "SELECT value FROM sessions WHERE id = @id"; command.Parameters.Add("@id", SqlDbType.VarChar, 255).Value = key; using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { byte[] data = (byte[])reader.GetValue(0); return PdfLiteSession.Deserialize(data); } else { return null; } } } } }
81aea16575d164cd061dff1c39b3bf9ffc841fb9
C#
ritschard/HomePLC_GUI
/Model/TriggerEngine.cs
2.625
3
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Xml; namespace HomePLC.Model { public class TriggerEngine : BindingList<BaseTrigger> { private List<BaseTrigger> fTriggerList; public void Save(string filename) { XmlDocument doc = new XmlDocument(); XmlElement element = doc.CreateElement("triggers"); doc.AppendChild(element); foreach (BaseTrigger s in this) { XmlElement e = doc.CreateElement("trigger"); XmlAttribute a = doc.CreateAttribute("ID"); a.Value = s.ID.ToString(); e.Attributes.Append(a); s.Save(e); doc.DocumentElement.AppendChild(e); } doc.Save(filename); } public TriggerEngine() { fTriggerList = new List<BaseTrigger>(); } public List<BaseTrigger> Triggers { get { return fTriggerList; } } } }
54f3436cc86b1decd4d440d5a60908d02ef3d510
C#
mariapsz/SeleniumTests-CS
/CarrefourTests/PropertiesCollection.cs
3.15625
3
using OpenQA.Selenium; using System; using System.Collections.Generic; namespace CarrefourTests { class PropertiesCollection { public static IWebDriver driver { get; set; } public static List<Product> addedProductsList = new List<Product>(); public static void showAddedProductsList() { foreach (Product p in addedProductsList) { Console.WriteLine(p.Name + " " + p.Price); } } public static bool isContentEqual(List<Product> l1, List<Product> l2) { if (l1.Capacity != l2.Capacity) return false; Product[] p1 = l1.ToArray(); Product[] p2 = l2.ToArray(); for (int i = 0; i < p1.Length; i++) { if (p1[i].Price != p2[i].Price || p1[i].Name != p2[i].Name) return false; } return true; } } }
cd78ab8275d59f203d6cf7675ee1c6e26ebf5739
C#
hujgup/Snake
/src/namespaceModel/tests/testFruit.cs
2.78125
3
using System; using System.Timers; using System.Collections.Generic; using SnakeGame.GridSystem; using NUnit.Framework; namespace SnakeGame.Model { /// <summary> /// Provides unit tests for the Fruit class. /// </summary> [TestFixture()] public class TestFruit { private void TestConstruction(Grid g, Cell loc, int value) { Fruit f = new Fruit(g, loc, value); Assert.AreEqual(g, f.PlayArea); Assert.AreEqual(loc, f.OccupiedCell); Assert.AreEqual(value, f.Value); Assert.IsTrue(g.IsDefined(f.OccupiedCell)); } private void TestConstruction(Grid g, int value) { Fruit f = new Fruit(g, value); Assert.AreEqual(g, f.PlayArea); Assert.AreEqual(value, f.Value); Assert.IsTrue(g.IsDefined(f.OccupiedCell)); Assert.IsTrue(f.OccupiedCell.IsValid); } /// <summary> /// Tests fruit construction. /// </summary> [Test()] public void Construction() { Grid g = new Grid(16, 16); TestConstruction(g, g[5, 8], 8); TestConstruction(g, g[7, 7], 1); TestConstruction(g, g[1, 8], 5); TestConstruction(g, g[0, 10], 3); TestConstruction(g, g[12, 4], -2); Assert.Throws<ArgumentNullException>(delegate() { Fruit f = new Fruit(null, g[0, 0], 8); }); Assert.Throws<ArgumentException>(delegate() { Fruit f = new Fruit(g, Cell.INVALID_CELL, 1); }); Assert.Throws<ArgumentException>(delegate() { Fruit f = new Fruit(new Grid(18, 24), g[0, 0], 3); }); Assert.Throws<ArgumentOutOfRangeException>(delegate() { Fruit f = new Fruit(g, new Cell(g, 128, 128), 7); }); } /// <summary> /// Tests fruit constructor overloads. /// </summary> [Test()] public void Overloads() { Grid g = new Grid(8, 8); Fruit f = new Fruit(g, 4); Assert.IsTrue(f.OccupiedCell.IsValid); Assert.IsTrue(g.IsDefined(f.OccupiedCell)); } /// <summary> /// Tests fruit location randomization. /// </summary> [Test()] public void Randomization() { Grid g = new Grid(8, 8); Fruit f = new Fruit(g, g[5, 7], 4); int max = 65536; Dictionary<Cell, int> cells = new Dictionary<Cell, int>(max); { Cell c; for (int i = 0; i < max; i++) { f.RandomizeLocation(); c = f.OccupiedCell; if (cells.ContainsKey(c)) { cells[c]++; } else { cells.Add(c, 1); } } int expected = 1024; int errorMargin = 256; int value; foreach (KeyValuePair<Cell, int> kvp in cells) { value = Math.Abs(kvp.Value - expected); if (value > errorMargin) { Assert.Fail("Fruit.RandomizeLocation() randomization not random enough: Expected a value within " + errorMargin.ToString() + " of " + expected.ToString() + ", but was " + value.ToString() + " away (value = " + kvp.Value.ToString() + "). Note that this check may fail due to random chance - try running the tests again."); } } } cells.Clear(); List<Cell> exclude = new List<Cell>(16); exclude.Add(g[0, 10]); exclude.Add(g[6, 2]); exclude.Add(g[0, 5]); exclude.Add(g[2, 6]); exclude.Add(g[9, 1]); exclude.Add(g[4, 2]); exclude.Add(g[1, 4]); exclude.Add(g[3, 5]); exclude.Add(g[5, 5]); exclude.Add(g[6, 5]); exclude.Add(g[7, 5]); exclude.Add(g[1, 5]); exclude.Add(g[2, 5]); exclude.Add(g[0, 0]); exclude.Add(g[1, 0]); exclude.Add(g[2, 0]); { Cell c; for (int i = 0; i < max; i++) { f.RandomizeLocation(exclude); c = f.OccupiedCell; if (exclude.Contains(c)) { string fail = "Fruit.RandomizeLocation(List<Cell>) not excluding specified cells: Expected any cell except those in the set {"; foreach (Cell eCell in exclude) { fail += eCell.ToString() + ", "; } fail = fail.Substring(0, fail.Length - 2) + "}, but was " + c.ToString() + "."; Assert.Fail(fail); } else if (cells.ContainsKey(c)) { cells[c]++; } else { cells.Add(c, 1); } } int expected = 1365; int errorMargin = 341; int value; foreach (KeyValuePair<Cell, int> kvp in cells) { value = Math.Abs(kvp.Value - expected); if (value > errorMargin) { Assert.Fail("Fruit.RandomizeLocation(List<Cell>) randomization not random enough: Expected a value within " + errorMargin.ToString() + " of " + expected.ToString() + ", but was " + value.ToString() + " away (value = " + kvp.Value.ToString() + "). Note that this check may fail due to random chance - try running the tests again."); } } } cells.Clear(); { Cell c; for (int i = 0; i < max; i++) { f = new Fruit(g, 1); c = f.OccupiedCell; if (cells.ContainsKey(c)) { cells[c]++; } else { cells.Add(c, 1); } } int expected = 1024; int errorMargin = 256; int value; foreach (KeyValuePair<Cell, int> kvp in cells) { value = Math.Abs(kvp.Value - expected); if (value > errorMargin) { Assert.Fail("Fruit.Constructor(Grid, int) location randomization not random enough: Expected a value within " + errorMargin.ToString() + " of " + expected.ToString() + ", but was " + value.ToString() + " away (value = " + kvp.Value.ToString() + "). Note that this check may fail due to random chance - try running the tests again."); } } } cells.Clear(); { Cell c; for (int i = 0; i < max; i++) { f = new Fruit(g, exclude, 1); c = f.OccupiedCell; if (exclude.Contains(c)) { string fail = "Fruit.Constructor(Grid, List<Cell>, int) not excluding specified cells: Expected any cell except those in the set {"; foreach (Cell eCell in exclude) { fail += eCell.ToString() + ", "; } fail = fail.Substring(0, fail.Length - 2) + "}, but was " + c.ToString() + "."; Assert.Fail(fail); } else if (cells.ContainsKey(c)) { cells[c]++; } else { cells.Add(c, 1); } } int expected = 1365; int errorMargin = 341; int value; foreach (KeyValuePair<Cell, int> kvp in cells) { value = Math.Abs(kvp.Value - expected); if (value > errorMargin) { Assert.Fail("Fruit.Constructor(Grid, List<Cell>, int) randomization not random enough: Expected a value within " + errorMargin.ToString() + " of " + expected.ToString() + ", but was " + value.ToString() + " away (value = " + kvp.Value.ToString() + "). Note that this check may fail due to random chance - try running the tests again."); } } } { g = new Grid(1, 1); f = new Fruit(g, 1); exclude.Clear(); exclude.Add(g[0, 0]); f.RandomizeLocation(exclude); Assert.IsFalse(f.OccupiedCell.IsValid, "Attempting to randomize location when all cells in a grid have been excluded should return an invalid cell."); } } /// <summary> /// Tests fruit eating. /// </summary> [Test()] public void TestEat() { Grid g = new Grid(16, 16); Snake s = new Snake(g, g[8, 8], 2, Direction.Up); Fruit f = new Fruit(g, g[0, 0], 1); Timer t = new Timer(1000); f.Eaten += (object sender, EatenEventArgs e) => { t.Stop(); t.Dispose(); Assert.AreEqual(s, e.Eater, "The argument passed to EatenEventArgs must be the snake that ate the fruit."); Assert.Pass(); }; t.Elapsed += (object sender, ElapsedEventArgs e) => { Assert.Fail("Fruit.Eaten event did not fire."); }; t.Start(); f.Eat(s); } /// <summary> /// Tests snake length when fruit eaten. /// </summary> [Test()] public void TestSnakeLengthWhenEaten() { Grid g = new Grid(16, 16); Snake s = new Snake(g, g[8, 8], 2, Direction.Up); Fruit f = new Fruit(g, g[0, 0], 1); f.Eaten += (object sender, EatenEventArgs e) => { Assert.AreEqual(3, s.Length, "Snakes length should increase by one as it consumes a fruit"); }; f.Eat(s); } } }
c2532d19a62d39a82b2d3317b807f661444a9b4c
C#
otemnov/ncqrs
/Framework/src/Ncqrs/Eventing/UncommittedEvent.cs
2.75
3
using System; using Ncqrs.Eventing.ServiceModel.Bus; namespace Ncqrs.Eventing { /// <summary> /// Represents an event which has not been yet persisted. /// </summary> public class UncommittedEvent : IPublishableEvent { private readonly object _payload; private readonly long _eventSequence; private readonly Guid _eventIdentifier; private readonly DateTime _eventTimeStamp; private readonly Guid _eventSourceId; private readonly Type _eventSourceType; private readonly long _initialVersionOfEventSource; private readonly Version _eventVersion; private Guid _commitId; /// <summary> /// Gets the initial version of event source (the version it was just after creating/retrieving from the store) /// </summary> public long InitialVersionOfEventSource { get { return _initialVersionOfEventSource; } } /// <summary> /// Gets the payload of the event. /// </summary> public object Payload { get { return _payload; } } /// <summary> /// Gets the unique identifier for this event. /// </summary> public Guid EventIdentifier { get { return _eventIdentifier; } } /// <summary> /// Gets the time stamp for this event. /// </summary> /// <value>a <see cref="DateTime"/> UTC value that represents the point /// in time where this event occurred.</value> public DateTime EventTimeStamp { get { return _eventTimeStamp; } } /// <summary> /// Gets the id of the event source that caused the event. /// </summary> /// <value>The id of the event source that caused the event.</value> public Guid EventSourceId { get { return _eventSourceId; } } /// <summary> /// Gets the type of the event source that caused the event. /// </summary> /// <value>The type of the event source that caused the event.</value> public Type EventSourceType { get { return _eventSourceType; } } /// <summary> /// Gets the event sequence number. /// </summary> /// <remarks> /// An sequence of events always starts with <c>1</c>. So the first event in a sequence has the <see cref="EventSequence"/> value of <c>1</c>. /// </remarks> /// <value>A number that represents the order of where this events occurred in the sequence.</value> public long EventSequence { get { return _eventSequence; } } /// <summary> /// If of a commit in which this event is to be stored (usually corresponds to a command id which caused this event). /// </summary> public Guid CommitId { get { return _commitId; } } public void OnAppendedToStream(Guid streamCommitId) { _commitId = streamCommitId; } public UncommittedEvent(Guid eventIdentifier, Guid eventSourceId, Type eventSourceType, long eventSequence, long initialVersionOfEventSource, DateTime eventTimeStamp, object payload, Version eventVersion) { _payload = payload; _eventVersion = eventVersion; _initialVersionOfEventSource = initialVersionOfEventSource; _eventSourceId = eventSourceId; _eventSourceType = eventSourceType; _eventSequence = eventSequence; _eventIdentifier = eventIdentifier; _eventTimeStamp = eventTimeStamp; } public Version EventVersion { get { return _eventVersion; } } public override string ToString() { return string.Format("{0}[{1}]", Payload.GetType().FullName, EventIdentifier.ToString("D")); } } }
f7db638cce3bb6a9f817f53252ec472850f74fc8
C#
lucasloss/TextFileSearch
/TextFileSearch/Model/PathInformation.cs
3.375
3
using System.Collections.Generic; namespace TextFileSearch { /// <summary> /// Represents the path where the application is going to search for files. /// </summary> public class PathInformation { /// <summary> /// Gets or sets the path where the aplication is going to search for files. /// </summary> public string Path { get; set; } /// <summary> /// Gets or sets a value indicating whether the path exists. /// </summary> public bool Exists { get; set; } /// <summary> /// Gets or sets a value indicating whether the application should search recursively in the specified path. /// </summary> public bool RecursiveSearch { get; set; } /// <inheritdoc/> public override bool Equals(object obj) { return obj is PathInformation information && Path == information.Path && Exists == information.Exists && RecursiveSearch == information.RecursiveSearch; } /// <inheritdoc/> public override int GetHashCode() { var hashCode = -64031662; hashCode = (hashCode * -1521134295) + EqualityComparer<string>.Default.GetHashCode(Path); hashCode = (hashCode * -1521134295) + Exists.GetHashCode(); hashCode = (hashCode * -1521134295) + RecursiveSearch.GetHashCode(); return hashCode; } } }
7a131a753b32e3ad39ada3b19e76ca4f75604c0b
C#
vukhai98/csharpbasic
/test/csharpbasic/ConsoleRead/Program.cs
3.09375
3
using System; namespace ConsoleRead { class Program { static void Main(string[] args) { //Console.WriteLine(Console.Read()); // đọc 1 ký tự từ bàn phím bằng lệnh Console.Read() sau đó in ra ký tự vừa đọc ( bảng mã askey) //Console.ReadKey(); // lệnh này dùng với mục đích dừng màn hình để xem kết quả. //Console.WriteLine(Console.ReadLine()); // đọc dữ liệu từ bàn phím cho đến khi gặp ký tự xuống dòng thì dừng. Sau đó in giá trị để nhập ra màn hình //Console.ReadKey(); // lệnh dùng với mục đích dừng màn hình để xem kết quả Console.WriteLine("Kteam"); Console.ReadKey(); // không truyền tham số vào thì mặc định là false Console.ReadKey(false); // hiển thị phím bạn nhập trên màn hình. Console.ReadKey(true); //không hiển thị phím bạn nhập nên màn hình. } } }
77b28cf62dcdaadd43ce97928d0ed9d99de29e23
C#
flashd2n/main-telerik-git
/databases/Training/Code-First/CFTraining/ACFTraining.Data/Migrations/Configuration.cs
2.515625
3
namespace ACFTraining.Data.Migrations { using CFTraining.Models; using System.Data.Entity.Migrations; public sealed class Configuration : DbMigrationsConfiguration<CFTrainingDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; ContextKey = "ACFTraining.Data.CFTrainingDbContext"; } protected override void Seed(CFTrainingDbContext context) { context.Artists.AddOrUpdate(a => a.Name ,new Artist { Name = "First Seeded Artist" }, new Artist { Name = "Second Seeded Artist" }); } } }
73ed0ec2d2079b4655d0c553400a59dd506e6121
C#
jrmrtns/cwat
/CWAT/Cellent.Template.Common/Interceptors/LoggingInterceptor.cs
2.953125
3
using System; using System.Diagnostics; using System.Linq; using System.Threading; using Cellent.Template.Common.Extensions; using Microsoft.Practices.Unity.InterceptionExtension; namespace Cellent.Template.Common.Interceptors { /// <summary> /// Interceptor für das Log /// </summary> public class LoggingInterceptor : ICallHandler { #region Properties (2)  /// <summary> /// Order in which the handler will be executed /// </summary> public int Order { get; set; } #endregion Properties  #region Methods (1)  #region Public Methods (1)  /// <summary> /// Implement this method to execute your handler processing. /// </summary> /// <param name="input">Inputs to the current call to the target.</param> /// <param name="getNext">Delegate to execute to get the next delegate in the handler /// chain.</param> /// <returns> /// Return value from the target. /// </returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { string name = "unknown User"; try { string n = Thread.CurrentPrincipal.Identity.Name; if (string.IsNullOrEmpty(n)) name = null; } catch (ObjectDisposedException) { //kann passieren, dann steht weiter unknown user im log } string param = input.Arguments.Cast<object>() .Aggregate("", (current, parameter) => current + (", " + (parameter == null ? "null" : parameter.ToString()))); if (param.Length > 0) param = param.Substring(2); Logger.Logger.Write(string.Format("{0}: Enter Method: {1}.{2}({3})", name, input.MethodBase.DeclaringType, input.MethodBase.Name, param), TraceEventType.Verbose); IMethodReturn value = getNext()(input, getNext); value.InvokeAfterCall(input, d => { if (d.Exception != null) { Logger.Logger.Write(d.Exception); } Logger.Logger.Write(string.Format("{0}: Exit Method: {1}.{2}({3})", name, input.MethodBase.DeclaringType, input.MethodBase.Name, param), TraceEventType.Verbose); }); return value; } #endregion Public Methods  #endregion Methods  } }
0c3c984a5c6b9d091b9328bdeb0a51bbac737c26
C#
joycymichael/CSExercises
/CSExercises/Ex07-15/Ex10.cs
3.640625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSExercises { public class Ex10 { public static void Main(string[] args) { int d1, d2; double d; Console.Write("\n\t\tDistance between two points"); Console.Write("\n\tEnter value of x1: "); int x1 = Convert.ToInt16(Console.ReadLine()); Console.Write("\n\tEnter value of y1: "); int y1 = Convert.ToInt16(Console.ReadLine()); Console.Write("\n\tEnter value of x2: "); int x2 = Convert.ToInt16(Console.ReadLine()); Console.Write("\n\tEnter value of y2: "); int y2 = Convert.ToInt16(Console.ReadLine()); d1 = (x2 - x1) * (x2 - x1); d2 = (y2 - y1) * (y2 - y1); //d=math.sqrt(d1+d2); try { d = Math.Sqrt(d1 + d2); Console.WriteLine("\n\tDistance is {0}", d); } catch (Exception ex) { Console.ReadLine(); } Console.ReadLine(); } } }
e0bf210ef6f3666ec71b0e3b0b0575b73a49a279
C#
binary-dao/A-star
/Assets/Scripts/ModelScript.cs
2.578125
3
using System; using System.Collections.Generic; using UnityEngine; public class ModelScript : MonoBehaviour { internal const int MAX_ROWS = 50; internal const int MAX_COLS = 50; private const int NEIGHBOUR_DISTANCE = 1; //for really bad cases and mistakes private static int MAX_ITERATIONS = MAX_COLS*MAX_COLS; private static int steps; private static Vector2Int startPoint; private static Vector2Int endPoint; private static List<Vector2Int> obstacleList = new List<Vector2Int>(); private static System.Random rand; // Use this for initialization void Start () { rand = new System.Random(); startPoint = new Vector2Int(0, 0); endPoint = new Vector2Int(49, 49); obstacleList.Add(new Vector2Int(1, 1)); Randomize(); } // Update is called once per frame void Update () { } private static void RefreshField() { ViewScript.Instance.RefreshField(startPoint, endPoint, obstacleList); } internal static void AddRemoveObstacle(Vector2Int coord) { var badPoint = new Vector2Int(-1, -1); if (coord == startPoint) startPoint = badPoint; if (coord == endPoint) endPoint = badPoint; if (obstacleList.Contains(coord)) obstacleList.Remove(coord); else obstacleList.Add(coord); RefreshField(); } internal static void SetStartEndPoint(Vector2Int coord) { var badPoint = new Vector2Int(-1, -1); if(startPoint == badPoint) { startPoint = coord; } else if (endPoint == badPoint) { badPoint = coord; } else if (coord == startPoint) { endPoint = coord; startPoint = badPoint; } else if(coord == endPoint) { endPoint = badPoint; } else if (obstacleList.Contains(coord)) { obstacleList.Remove(coord); startPoint = coord; } else { startPoint = coord; } RefreshField(); } internal static void Randomize() { int obstacleNumber = rand.Next(MAX_COLS*MAX_ROWS/2); obstacleList = new List<Vector2Int>(); do { int x = rand.Next(MAX_COLS); int y = rand.Next(MAX_ROWS); Vector2Int vect = new Vector2Int(x, y); if (!obstacleList.Contains(vect)) obstacleList.Add(vect); } while (obstacleList.Count < obstacleNumber); startPoint = new Vector2Int(-1,-1); endPoint = new Vector2Int(-1, -1); do { int x = rand.Next(MAX_COLS); int y = rand.Next(MAX_ROWS); Vector2Int vect = new Vector2Int(x, y); if (!obstacleList.Contains(vect)) startPoint = vect; } while (startPoint.x == -1); do { int x = rand.Next(MAX_COLS); int y = rand.Next(MAX_ROWS); Vector2Int vect = new Vector2Int(x, y); if (!obstacleList.Contains(vect)) endPoint = vect; } while (endPoint.x == -1); RefreshField(); } public static void AStarClick() { if (IsBadPoints()) { ViewScript.Instance.ShowStartEndError(); return; } var path = AStar(); if (path != null) { ViewScript.Instance.DrawPath(path); } ViewScript.Instance.ShowResult(path!=null, steps); } private static bool IsBadPoints() { return startPoint.x < 0 || startPoint.y < 0 || endPoint.x < 0 || endPoint.y < 0; } private static List<Vector2Int> AStar() { float startTime = Time.time; var opened = new List<Cell>(); var closed = new List<Cell>(); var startCell = new Cell { coords = startPoint, previousCell = null, distanceFromStart = 0, approximateToEnd = DistanceBetweenPoints(startPoint, endPoint) }; opened.Add(startCell); steps = 0; while (opened.Count > 0 && steps < MAX_ITERATIONS) { steps++; Cell currentCell = GetWithMinApprox(opened); if(currentCell.coords == endPoint) { return PathForCell(currentCell); } opened.Remove(currentCell); closed.Add(currentCell); var neighbours = GetNeighbours(currentCell); foreach(var neighbour in neighbours) { bool isClosed = false; foreach (var close in closed) { if (close.coords == neighbour.coords) { isClosed = true; break; } } if(isClosed) continue; Cell openCell = null; foreach(var open in opened) { if (open.coords == neighbour.coords) { openCell = open; break; } } if (openCell == null) opened.Add(neighbour); else if (openCell.distanceFromStart > neighbour.distanceFromStart) { openCell.previousCell = currentCell; openCell.distanceFromStart = neighbour.distanceFromStart; } } } return null; } private static Cell GetWithMinApprox(List<Cell> opened) { Cell answer = opened[0]; foreach (var cell in opened) { if (answer.approximateToEnd > cell.approximateToEnd) answer = cell; } return answer; } //go away, Pythagoras, we don't have diagonal connection here private static int DistanceBetweenPoints(Vector2Int a, Vector2Int b) { return Math.Abs((a - b).x) + Math.Abs((a - b).y); } public static List<Vector2Int> PathForCell(Cell currentCell) { var answer = new List<Vector2Int>(); var iterCell = currentCell; while (iterCell != null) { answer.Add(iterCell.coords); iterCell = iterCell.previousCell; } answer.Reverse(); return answer; } private static List<Cell> GetNeighbours(Cell cell) { var neighbours = new List<Cell>(); Vector2Int[] points = new Vector2Int[4]; points[0] = new Vector2Int(cell.coords.x, cell.coords.y + 1); points[1] = new Vector2Int(cell.coords.x + 1, cell.coords.y); points[2] = new Vector2Int(cell.coords.x, cell.coords.y - 1); points[3] = new Vector2Int(cell.coords.x - 1, cell.coords.y); for(int i = 0; i<4; i++) { var point = points[i]; if (point.x < 0 || point.y < 0 || point.x >= MAX_COLS || point.y >= MAX_ROWS) continue; if (obstacleList.Contains(point)) continue; var neighbour = new Cell { coords = point, previousCell = cell, distanceFromStart = cell.distanceFromStart + NEIGHBOUR_DISTANCE, approximateToEnd = DistanceBetweenPoints(point, endPoint) }; neighbours.Add(neighbour); } return neighbours; } }
8bdc65ffc52e062cdea9b87cc426d900f511c522
C#
brianly/Yammer.NET-2.0
/Yammer.APIWrapper/Group.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; using System.Collections.Specialized; namespace Yammer.APIWrapper { public class Group { #region Yammer Properties /// <summary> /// The object type, such as user, tag, etc. /// </summary> [JsonProperty(PropertyName = "type")] public string Type { get; set; } /// <summary> /// The ID number for this object. Note that IDs are not unique across all object types: /// there may be a user and tag with the same numerical ID. /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Name given to this group. /// </summary> [JsonProperty(PropertyName = "full-name")] public string FullName { get; set; } /// <summary> /// Shortened name of this group. Used in references (@salesteam), addressing (to:salesteam), /// the email address for group updates (salesteam@yammer.com) and the web URL (www.yammer.com/groups/salesteam). /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Either public or private, to indicate whether updates are visible to non-members /// (public) and whether joining requires a group admin's approval (private). /// </summary> [JsonProperty(PropertyName = "privacy")] public string Privacy { get; set; } /// <summary> /// The API resource for fetching this object. /// </summary> [JsonProperty(PropertyName = "url")] public string Url { get; set; } /// <summary> /// The URL for viewing this object on the main Yammer website. /// </summary> [JsonProperty(PropertyName = "web-url")] public string WebUrl { get; set; } /// <summary> /// The URL of this group's picture. /// </summary> [JsonProperty(PropertyName = "mugshot_url")] public string MugshotUrl { get; set; } /// <summary> /// Group stats /// </summary> [JsonProperty(PropertyName = "stats")] public GroupStats Stats { get; set; } #endregion public static List<Group> GetAllMyGroups() { return JsonConvert.DeserializeObject<List<Group>>(Json.GetAllMyGroups()); } public static List<Group> GetAllMyGroups(MembershipParameters groupParams) { return JsonConvert.DeserializeObject<List<Group>>(Json.GetAllMyGroups(groupParams)); } public static List<Group> GetAllGroups() { return JsonConvert.DeserializeObject<List<Group>>(Json.GetAllGroups()); } public static List<Group> GetAllGroups(MembershipParameters groupParams) { return JsonConvert.DeserializeObject<List<Group>>(Json.GetAllGroups(groupParams)); } public static Group GetGroupById(int id) { return JsonConvert.DeserializeObject<Group>(Json.GetGroupById(id)); } public void Join() { Group.JoinGroup(int.Parse(this.Id)); } public static void JoinGroup(int id) { Json.JoinGroup(id); } public void Leave() { Group.LeaveGroup(int.Parse(this.Id)); } public static void LeaveGroup(int id) { Json.LeaveGroup(id); } public static Group CreateGroup(string name, PrivacyFlag flag) { Group g = null; string response = Json.CreateGroup(name, flag); Uri uri; bool successful = Uri.TryCreate(response, UriKind.Absolute, out uri); if (successful) { string groupId = uri.Segments[uri.Segments.Length - 1]; g = Yammer.APIWrapper.Group.GetGroupById(int.Parse(groupId)); } return g; } public void Modify(string name, PrivacyFlag flag) { Group.ModifyGroup(int.Parse(this.Id), name, flag); this.Name = name; this.Privacy = flag.ToString().ToLower(); } public static Group ModifyGroup(int groupId, string name, PrivacyFlag flag) { bool p = flag == PrivacyFlag.Private ? false : true; NameValueCollection parameters = new NameValueCollection(); parameters.Add("name", name); parameters.Add("private", p.ToString()); string response = Json.ModifyGroup(groupId, name, flag); return Yammer.APIWrapper.Group.GetGroupById(groupId); } public static System.Drawing.Image GetAvatar(string url) { try { return HttpUtility.GetImage(url); } catch (Exception ex) { throw ex; } } public override string ToString() { return String.Format("Name:{0}, Members:{1}, Updates:{2}", this.Name, this.Stats.Members, this.Stats.Updates); } public override bool Equals(object obj) { return this.Id == ((Group)obj).Id; } } public class GroupStats { [JsonProperty(PropertyName = "members")] public string Members { get; set; } [JsonProperty(PropertyName = "updates")] public string Updates { get; set; } } public class Json { Group _group; public Json(Group group) { _group = group; } public static string GetAllMyGroups() { NameValueCollection parameters = new NameValueCollection(); parameters.Add("mine", "1"); string response = Yammer.APIWrapper.HttpUtility.Get(Resources.Groups.All, parameters); return response; } public static string GetAllMyGroups(MembershipParameters groupParams) { MembershipParameters.AddMembershipParams(groupParams); MembershipParameters.Parameters.Add("mine", "1"); string response = Yammer.APIWrapper.HttpUtility.Get(Resources.Groups.All, MembershipParameters.Parameters); return response; } public static string GetAllGroups() { string response = Yammer.APIWrapper.HttpUtility.Get(Resources.Groups.All); return response; } public static string GetAllGroups(MembershipParameters groupParams) { MembershipParameters.AddMembershipParams(groupParams); string response = Yammer.APIWrapper.HttpUtility.Get(Resources.Groups.All, MembershipParameters.Parameters); return response; } public static string GetGroupById(int id) { string response = Yammer.APIWrapper.HttpUtility.Get(Resources.Groups.Detail(id.ToString())); return response; } public void Join() { Group.JoinGroup(int.Parse(this._group.Id)); } public static string JoinGroup(int id) { NameValueCollection parameters = new NameValueCollection(); parameters.Add("group_id", id.ToString()); string response = Yammer.APIWrapper.HttpUtility.Post(Resources.Groups.Join, parameters); return response; } public void Leave() { Group.LeaveGroup(int.Parse(this._group.Id)); } public static string LeaveGroup(int id) { NameValueCollection parameters = new NameValueCollection(); parameters.Add("group_id", id.ToString()); string response = Yammer.APIWrapper.HttpUtility.Delete(Resources.Groups.Leave(id.ToString()), parameters); return response; } public static string CreateGroup(string name, PrivacyFlag flag) { Group g = null; bool p = flag == PrivacyFlag.Private ? true : false; NameValueCollection parameters = new NameValueCollection(); parameters.Add("name", name); parameters.Add("private", p.ToString().ToLower()); string response = Yammer.APIWrapper.HttpUtility.Post(Resources.Groups.Create, parameters, true); return response; } public void Modify(string name, PrivacyFlag flag) { Group.ModifyGroup(int.Parse(this._group.Id), name, flag); this._group.Name = name; this._group.Privacy = flag.ToString().ToLower(); } public static string ModifyGroup(int groupId, string name, PrivacyFlag flag) { bool p = flag == PrivacyFlag.Private ? false : true; NameValueCollection parameters = new NameValueCollection(); parameters.Add("name", name); parameters.Add("private", p.ToString()); string response = Yammer.APIWrapper.HttpUtility.Put(Resources.Groups.Modify(groupId.ToString()), parameters); return response; } } }
8320bf9a2ccbd24ef6df1ea299b779e5afdfb0b2
C#
MadcowD/DeepLearn.NET
/NeuralLibrary/NeuralNetwork/Neuron.cs
3.40625
3
namespace NeuralLibrary.NeuralNetwork { /// <summary> /// The base unit of the neural network. /// Contains pertinent information to neural nodes and feedforward propagation thereof. /// </summary> public class Neuron { public Neuron() { Net = 0; Output = 0; Error = 0; } /// <summary> /// Resets the given neuron to its initial state. /// </summary> public void Reset() { Net = 0; Error = 0; Output = 0; } #region Properties /// <summary> /// The net input to the sigmoid function of the neuron. /// </summary> public double Net { set; get; } public virtual double Output { get; protected set; } /// <summary> /// Updates the output of the neuron. /// </summary> /// <param name="activation">The activation function with which the output is calculated.</param> /// <returns></returns> public virtual void UpdateOutput(Sigmoid activation) { Output = activation.Function(Net); } public double Error { get; protected set; } /// <summary> /// Updates the error of the neuron based on some activation function and some error coefficient (subject to change in Output Neurons). /// </summary> /// <param name="activation">The activation function with which the error will be calculated.</param> /// <param name="errorCoefficient">The standard coefficient of error for neurons. /// SUM (for I in Posterior Neurons) Error_i * W_ij. Where j is this neuron.</param> /// <returns>The neural error of the neuron.</returns> public virtual void UpdateError(Sigmoid activation, double errorCoefficient) { Error = activation.Derivative(Net) * errorCoefficient; } #endregion Properties public int GetID(Network network) { foreach (Neuron[] n in network.Neurons) for (int i = 0; i < n.Length; i++) if (n[i].Equals(this)) return i; return -1; } } }
c4c32e0d5e8d1f05e7bcd4f0764694f013ec5043
C#
alexizt/CompositePattern
/CompositePattern/Program.cs
3.140625
3
using System; namespace CompositePattern { class Program { static void Main(string[] args) { var t1 = new Todo("Hacer A I"); var t2 = new Todo("Hacer A II"); var tc1 = new TodoComposite("Hacer Composite A"); var tc2 = new TodoComposite("Hacer Sub Composite B"); tc2.Add(new Todo("Hacer B I")); tc2.Add(new Todo("Hacer B II")); tc2.Add(new Todo("Hacer B III")); tc1.Add(t1); tc1.Add(t2); tc1.Add(tc2); var project = tc1; Console.Write(project.GetHtml()); Console.ReadKey(true); } } }
385273784e0f9c550b92400deec643fde50bfd5e
C#
TodorVyagov/C-Sharp-Part-2
/2.Homework.MultidimensionalArrays/07.LargestAreaOfEqualElementsInArray/LargestAreaOfEqualElementsInArray.cs
3.953125
4
using System; //Write a program that finds the largest area of equal neighbor elements //in a rectangular matrix and prints its size. namespace LargestAreaOfEqualElementsInArray { class LargestAreaOfEqualElementsInArray { static int[,] matrix = { {1, 3, 2, 2, 2, 4}, {3, 3, 3, 2, 4, 4}, {4, 3, 1, 2, 3, 3}, {4, 3, 1, 3, 3, 1}, {4, 3, 3, 3, 1, 1} }; static bool[,] isCounted = new bool[matrix.GetLength(0), matrix.GetLength(1)]; static void Main() { int counter = 0; int element = 0; for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { int currentCounter = 0; if (!isCounted[row, col]) { currentCounter = CounterOfEqualNeighborElements(row, col, currentCounter); } if (currentCounter > counter) { counter = currentCounter; element = matrix[row, col]; } } } //Printing array: for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { Console.Write(matrix[row, col] + " "); } Console.WriteLine(); } Console.WriteLine("There is sequence of {0} neighbor elements with value = {1}.", counter, element); } static int CounterOfEqualNeighborElements(int startRow, int startCol, int counter) { isCounted[startRow, startCol] = true; counter++; if (startRow - 1 >= 0) //up direction //this check is if the element is in the bounds of the matrix { if (matrix[startRow - 1, startCol] == matrix[startRow, startCol] && isCounted[startRow - 1, startCol] == false) //This checks if the neighbor element has the same value and whether the element is already counted { counter = CounterOfEqualNeighborElements(startRow - 1, startCol, counter); } } if (startCol - 1 >= 0) //left { if (matrix[startRow, startCol - 1] == matrix[startRow, startCol] && isCounted[startRow, startCol - 1] == false) { counter = CounterOfEqualNeighborElements(startRow, startCol - 1, counter); } } if (startRow + 1 < matrix.GetLength(0)) //down { if (matrix[startRow + 1, startCol] == matrix[startRow, startCol] && isCounted[startRow + 1, startCol] == false) { counter = CounterOfEqualNeighborElements(startRow + 1, startCol, counter); } } if (startCol + 1 < matrix.GetLength(1)) //right { if (matrix[startRow, startCol + 1] == matrix[startRow, startCol] && isCounted[startRow, startCol + 1] == false) { counter = CounterOfEqualNeighborElements(startRow, startCol + 1, counter); } } return counter; } } }
975099e04c4dd7b346f153abaf2582301c1dd2ec
C#
showtroylove/IGS
/Data/CodeExamples/SortActions.cs
2.96875
3
using System; using DevExpress.Spreadsheet; using DevExpress.Utils; using System.Globalization; using System.Collections.Generic; namespace SpreadsheetExamples { public static class SortActions { static void SimpleSort(IWorkbook workbook) { #region #SimpleSort Worksheet worksheet = workbook.Worksheets[0]; // Fill in the range with data. worksheet.Cells["A2"].Value = "Ray Bradbury"; worksheet.Cells["A3"].Value = "F. Scott Fitzgerald"; worksheet.Cells["A4"].Value = "Harper Lee"; worksheet.Cells["A5"].Value = "Ernest Hemingway"; worksheet.Cells["A6"].Value = "J.D. Salinger"; worksheet.Cells["A7"].Value = "Gene Wolfe"; // Sort the range in ascending order. Range range = worksheet.Range["A2:A7"]; worksheet.Sort(range); // Create a heading. Range header = worksheet.Range["A1"]; header[0].Value = "Authors in ascending order"; header.ColumnWidthInCharacters = 28; header.Style = workbook.Styles["Header"]; #endregion #SimpleSort } static void DescendingOrder(IWorkbook workbook) { #region #DescendingOrder Worksheet worksheet = workbook.Worksheets[0]; // Fill in the range with data. worksheet.Cells["A2"].Value = "Ray Bradbury"; worksheet.Cells["A3"].Value = "F. Scott Fitzgerald"; worksheet.Cells["A4"].Value = "Harper Lee"; worksheet.Cells["A5"].Value = "Ernest Hemingway"; worksheet.Cells["A6"].Value = "J.D. Salinger"; worksheet.Cells["A7"].Value = "Gene Wolfe"; // Sort the range in descending order. Range range = worksheet.Range["A2:A7"]; worksheet.Sort(range, false); // Create a heading. Range header = worksheet.Range["A1"]; header[0].Value = "Authors in descending order"; header.ColumnWidthInCharacters = 28; header.Style = workbook.Styles["Header"]; #endregion #DescendingOrder } static void SelectComparer(IWorkbook workbook) { #region #SelectComparer Worksheet worksheet = workbook.Worksheets[0]; // Fill in the range with data. worksheet.Cells["A2"].Value = 0.7; worksheet.Cells["A3"].Value = 0.45; worksheet.Cells["A4"].Value = 0.53; worksheet.Cells["A5"].Value = 0.33; worksheet.Cells["A6"].Value = 0.99; worksheet.Cells["A7"].Value = 0.62; // Specify a built-in comparer. IComparer<CellValue> comparer = worksheet.Comparers.Descending; // Sort values using the comparer. Range range = worksheet.Range["A2:A7"]; worksheet.Sort(range, 0, comparer); // Create a heading. Range header = worksheet.Range["A1"]; header[0].Value = "Values sorted by selected comparer"; header.ColumnWidthInCharacters = 40; header.Style = workbook.Styles["Header"]; #endregion #SelectComparer } static void SortBySpecifiedColumn(IWorkbook workbook) { #region #SortBySpecifiedColumn Worksheet worksheet = workbook.Worksheets["SortSample"]; workbook.Worksheets.ActiveWorksheet = worksheet; // Sort by a column with offset = 6 within the range being sorted. // Use ascending order. Range range = worksheet.Range["B5:H18"]; worksheet.Sort(range, 6); worksheet["B2"].Value = "Table is sorted by markup column using ascending order."; worksheet.Visible = true; #endregion #SortBySpecifiedColumn } static void SortByMultipleColumns(IWorkbook workbook) { #region #SortByMultipleColumns Worksheet worksheet = workbook.Worksheets["SortSample"]; workbook.Worksheets.ActiveWorksheet = worksheet; // Create sorting fields. List<SortField> fields = new List<SortField>(); // First sorting field. Author column (offset = 0) will be sorted using ascending order. SortField sortField1 = new SortField(); sortField1.ColumnOffset = 0; sortField1.Comparer = worksheet.Comparers.Ascending; fields.Add(sortField1); // Second sorting field. Title column (offset = 1) will be sorted using ascending order. SortField sortField2 = new SortField(); sortField2.ColumnOffset = 1; sortField2.Comparer = worksheet.Comparers.Ascending; fields.Add(sortField2); // Sort the range by sorting fields. Range range = worksheet.Range["B5:H18"]; worksheet.Sort(range, fields); // Add a note. worksheet["B2"].Value = "Table is sorted by two columns: by author, then by title in ascending order."; worksheet.Visible = true; #endregion #SortByMultipleColumns } } }
592756717a0ceb03c3526ff913e72b5c8c22c15c
C#
kobbikobb/Folferine
/Folferine.Website/Domain/Game.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; namespace Folferine.Website.Domain { public class Game { public int Id { get; set; } public DateTime CreatedDate { get; set; } public virtual Course Course { get; set; } public virtual List<Scorecard> Scorecards { get; set; } public Game() { Scorecards = new List<Scorecard>(); } public void AddPlayer(Player player) { Scorecards.Add(new Scorecard(this, player)); } public void CreateRounds() { foreach (var scorecard in Scorecards) { scorecard.CreateRounds(Course.HoleCount); } } public void SetRoundScore(int number, string userName, int score) { Scorecards.Single(x => x.GetUserName() == userName) .GetRound(number) .Score = score; } public int GetLastRoundNumber() { var lastRoundWithScore = Scorecards.SelectMany(x => x.Rounds) .Where(x => x.Score != 0) .OrderByDescending(x => x.Number) .FirstOrDefault(); return lastRoundWithScore == null ? 1 : lastRoundWithScore.Number; } public int GetNextRoundNumber() { var firstRoundWithoutScore = Scorecards.SelectMany(x => x.Rounds) .Where(x => x.Score == 0) .OrderBy(x => x.Number) .FirstOrDefault(); if (firstRoundWithoutScore == null) return Course.HoleCount; return firstRoundWithoutScore.Number; } public int GetHoleCount() { return Course.HoleCount; } public bool HasPlayer(string userName) { return Scorecards.Any(x => x.GetUserName() == userName); } } }
6ec7cd2eced3f558b33f1c45de3770ae9c732cf2
C#
LightRay2/game
/Utils/Helpers/HEncoder.cs
3.46875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Game2D.Game.Helpers { public class HEncoder { public enum Type{Byte, Int, Double, String} public static List<byte> Encode(params object[] vars) { MemoryStream stream = new MemoryStream(); BinaryWriter binary = new BinaryWriter(stream, UnicodeEncoding.Unicode); foreach (object v in vars) { if (v is int) { binary.Write((int)v); } else if (v is double) binary.Write((double)v); else if (v is byte) binary.Write((byte)v); else if (v is string) { string s = (string)v; byte[] array = Encoding.UTF8.GetBytes(s); //todo тут лажа, строка только 256 символов может быть binary.Write((byte)array.Length); binary.Write(array); } else throw new Exception("Encoder: тип данных не поддерживается"); } return new List<byte>( stream.ToArray()); } /// <summary> /// делает 2 вещи - возвращает переменную и удаляет считанное из message. Возможен вылет с exception /// </summary> public static int GetInt(ref List<byte> message) { int r = BitConverter.ToInt32(message.ToArray(), 0); message.RemoveRange(0, 4); return r; } /// <summary> /// делает 2 вещи - возвращает переменную и удаляет считанное из message. Возможен вылет с exception /// </summary> public static double GetDouble(ref List<byte> message) { double r = BitConverter.ToDouble(message.ToArray(), 0); message.RemoveRange(0, 8); return r; } /// <summary> /// делает 2 вещи - возвращает переменную и удаляет считанное из message. Возможен вылет с exception /// </summary> public static string GetString(ref List<byte> message) { BinaryReader reader = new BinaryReader(new MemoryStream(message.ToArray()), UnicodeEncoding.UTF8); byte n = reader.ReadByte(); string str = Encoding.UTF8.GetString(message.ToArray(), 1, n); message.RemoveRange(0, 1 + n); return str; } /// <summary> /// делает 2 вещи - возвращает переменную и удаляет считанное из message. Возможен вылет с exception /// </summary> public static byte GetByte(ref List<byte> message) { BinaryReader reader = new BinaryReader(new MemoryStream(message.ToArray())); message.RemoveRange(0, 1); return reader.ReadByte(); } } }
bdcb3d9e72d347f7569806b2c7bd09259c9cf293
C#
RainMaker777/my-time-tracker
/My Time Tracker - Windows/Classes/MostRecentUsed.cs
3.046875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyTimeTracker.Classes { public class MostRecentUsed<T> { #region Constants private string regKey_MaxItems = "MRU_MaxItems"; private string regKey_ItemCount = "MRU_ItemCount"; private string regKey_mruBaseName = "MRU_Item"; #endregion public MostRecentUsed(int maxItems) { MaxItems = maxItems; } #region Properties private int _maxItems = 20; public int MaxItems { get { return _maxItems; } set { _maxItems = value; Registry.Write(regKey_MaxItems, value); } } private List<T> _items = new List<T>(); public IEnumerable<T> Items { get { return _items; } } public int ItemCount { get { return _items.Count; } } private RegistryTool _registry = new RegistryTool(); public RegistryTool Registry { get { return _registry; } } #endregion #region Methods public void Add(T item) { _items.Add(item); if (_items.Count > MaxItems) { for (int i = 0; i < _items.Count -1; i++) { _items[i] = _items[i + 1]; } _items.RemoveAt(MaxItems); } } public void AddRange(IEnumerable<T> items) { if (items != null) _items.AddRange(items); } public void Insert(T item) { _items.Insert(0, item); if (_items.Count > MaxItems) _items.RemoveAt(MaxItems); } public bool Remove(T item) { return _items.Remove(item); } public void Clear() { _items.Clear(); } public virtual void Load() { Clear(); int itemCount = 0; int.TryParse((Registry.Read(regKey_ItemCount) ?? 0).ToString(), out itemCount); T item; for (int i = 1; i <= itemCount; i++) { item = (T)Registry.Read(ItemName(i)); if (item != null) Add(item); } } public virtual void Save() { // Save the number of current items. Registry.Write(regKey_ItemCount, _items.Count); // Write each item to the registry. int itemNumber = 0; foreach (T item in Items) { itemNumber++; Registry.Write(ItemName(itemNumber), item); } } private string ItemName(int itemNumber) { return string.Format("{0}{1}", regKey_mruBaseName, itemNumber); } #endregion } }
521880184f0339238eaf52d4e28ec6b5af1c372e
C#
gfloresuth/SimpleCRUDcsSource
/SimpleCRUDcsModel/MySQLDriver/MySQLDriver.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; namespace SimpleCRUDcsModel.MySQLDriver { public class MySQLDriver : ErrorHandler, IDatabaseConnection { private MySqlConnection _connection; public MySQLDriver(string host, string user, string pwd, string database) { string connectionString = string.Format("host={0};user={1};pwd={2};database={3};", host, user, pwd, database); _connection = new MySqlConnection(connectionString); } public bool close() { bool response=false; if(isConnected()) { _connection.Close(); response = true; } return response; } public SimpleResponse executeSQL(string sql, Dictionary<string, object> parameters) { SimpleResponse response = SimpleResponse.create(); MySqlCommand cmd; try { cmd = new MySqlCommand(sql, _connection); foreach (string paramName in parameters.Keys) { cmd.Parameters.AddWithValue(paramName, parameters[paramName]); } cmd.ExecuteNonQuery(); response.ok = true; } catch (Exception ex) { response.ok = false; response.LastError = ex.Message; LastError = ex.Message; } return response; } public IDataReader executeSQLReader(string sql, Dictionary<string, object> parameters) { MySQLSimpleReader reader=null; MySqlDataReader dr; MySqlCommand cmd; try { cmd = new MySqlCommand(sql, _connection); foreach(string paramName in parameters.Keys) { cmd.Parameters.AddWithValue(paramName, parameters[paramName]); } dr = cmd.ExecuteReader(); reader =MySQLSimpleReader.create(dr); }catch(Exception ex) { LastError = ex.Message; } return reader; } public bool isConnected() { return _connection.State == System.Data.ConnectionState.Open; } public bool open() { bool response = false; try { _connection.Open(); response = true; }catch(Exception ex) { LastError = ex.Message; } return response; } } }
d558a0cde1c500c4d08a7888a40caa7ad4ee975d
C#
HendrickSamuel/MyCartography
/CLShape/POI.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CLShape { public class POI: Coordonnees { #region VARIABLES private string _description; #endregion #region PROPRIETES public string Description { get { return _description; } set { _description = value; } } #endregion #region CONSTRUCTEURS public POI(string description, double latitude, double longitude): base(latitude, longitude) { Description = description; } public POI() : this("HEPL",50.620796, 5.581418) { } public POI(string description, Coordonnees c) : this(description, c.Longitude, c.Latitude) { } #endregion #region METHODES public override string ToString() { return base.ToString() + " " + Description; } #endregion } }
b636f84fcba77757617916e0ed8fd29f2d6faded
C#
shendongnian/download4
/code2/195447-3733925-7816637-2.cs
2.78125
3
private readonly object _sync = new object(); public event PropertyChangedEventHandler PropertyChanged { add { lock (_sync) _propertyChanged += value; } remove { lock (_sync) _propertyChanged -= value; } } private PropertyChangedEventHandler _propertyChanged; protected void OnPropertyChanged(Expression<Func<object>> propertyExpression) { OnPropertyChanged(GetPropertyName(propertyExpression)); } protected string GetPropertyName(Expression<Func<object>> propertyExpression) { MemberExpression body; if (propertyExpression.Body is UnaryExpression) body = (MemberExpression) ((UnaryExpression) propertyExpression.Body).Operand; else body = (MemberExpression) propertyExpression.Body; return body.Member.Name; } protected virtual void OnPropertyChanged(string propertyName) { var handler = _propertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); }
6fcd82a6fec95df98d407ce66c0212d8840a2d0b
C#
radtek/credit-card-exchange
/Client Generator/TargetClass/WaitForUpdateMethod.cs
2.734375
3
namespace FluidTrade.ClientGenerator.TargetClass { using System.CodeDom; using FluidTrade.Core; /// <summary> /// Creates a method to dispose of the resources used by the data model. /// </summary> class WaitForUpdateMethod : CodeMemberMethod { /// <summary> /// Creates a method to dispose of the resources used by the data model. /// </summary> /// <param name="schema">The data model schema.</param> public WaitForUpdateMethod(DataModelSchema dataModelSchema) { // /// <summary> // /// Waits for an update to the data model. // /// </summary> // public static void WaitForUpdate() // { this.Comments.Add(new CodeCommentStatement("<summary>", true)); this.Comments.Add(new CodeCommentStatement(string.Format("Dispose of the managed resources allocated by this object.", dataModelSchema.Name), true)); this.Comments.Add(new CodeCommentStatement("</summary>", true)); this.Comments.Add(new CodeCommentStatement("<param name=\"disposing\">true to indicate managed resources should be relesaed.</param>", true)); this.CustomAttributes.AddRange(new CodeCustomAttributesForMethods()); this.Name = "WaitForUpdate"; this.Attributes = MemberAttributes.Public | MemberAttributes.Static; // try // { // Monitor.Enter(DataModel.syncUpdate); // Monitor.Wait(DataModel.syncUpdate); // } // finally // { // Monitor.Exit(DataModel.syncUpdate); // } CodeTryCatchFinallyStatement tryLockUpdateEvent = new CodeTryCatchFinallyStatement(); tryLockUpdateEvent.TryStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Threading.Monitor)), "Enter", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncUpdate"))); tryLockUpdateEvent.TryStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Threading.Monitor)), "Wait", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncUpdate"))); tryLockUpdateEvent.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Threading.Monitor)), "Exit", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncUpdate"))); this.Statements.Add(tryLockUpdateEvent); // } } } }
21f69bffc88eac185eaf71f7b755652af34dbf26
C#
ahristoff/OOP-Advanced
/5_Reflection/EXERCISES/EXERCISES/P04_BarraksWars/Core/Engine.cs
3.125
3
using System; using _04BarracksFactory.Contracts; namespace _04BarracksFactory.Core { class Engine : IRunnable { private IRepository repository; private IUnitFactory unitFactory; private ICommandInterpreter commandInterpreter; public Engine(IRepository repository, IUnitFactory unitFactory, ICommandInterpreter commandInterpreter) { this.repository = repository; this.unitFactory = unitFactory; this.commandInterpreter = commandInterpreter; } public void Run() { while (true) { try { string input = Console.ReadLine(); string[] data = input.Split(); var instance = commandInterpreter.InterpretCommand(data); var type = typeof(IExecutable); try { var method = type.GetMethod("Execute"); var res = method.Invoke(instance, new object[] { }); Console.WriteLine(res); } catch (Exception ex) { Console.WriteLine(ex.InnerException.Message); //throw new ArgumentException("No such units in repository"); } } catch (Exception e) { Console.WriteLine(e.Message); } } } } }
47b3a640f2dfe10506c3fdd90e1ec6f76b8b883b
C#
canab/flunity
/SampleProject/Assets/Flunity/Internal/MovieClipParser.cs
2.671875
3
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Flunity.Internal { internal class MovieClipParser { private const int RES_LINE = 1; private const int INST_LINE = 2; private const int FRAME_LINE = 3; public static TimeLine ReadTimeLine(string[] description) { var timeLine = new TimeLine(); timeLine.resources = description[RES_LINE].Split(','); timeLine.instances = ReadInstanceInfo(description[INST_LINE]); timeLine.frames = ReadFrames(description, timeLine.instances.Length); return timeLine; } private static InstanceInfo[] ReadInstanceInfo(string instLine) { var instanceStrings = instLine.Split('|'); var instanceCount = instanceStrings.Length; var instances = new InstanceInfo[instanceCount]; for (int i = 0; i < instanceStrings.Length; i++) { var instData = instanceStrings[i]; if (instData.Length == 0) continue; var pair = instData.Split(','); var resourceNum = Convert.ToInt32(pair[0]); var instanceName = pair[1]; instances[i] = new InstanceInfo { resourceNum = resourceNum, name = instanceName, }; } return instances; } private static FrameData[] ReadFrames(string[] lines, int instanceCount) { var framesCount = lines.Length - FRAME_LINE; var frames = new FrameData[framesCount]; for (int i = 0; i < framesCount; i++) { var prevFrame = (i > 0) ? frames[i - 1] : null; frames[i] = ReadFrame(lines[FRAME_LINE + i], prevFrame, instanceCount); } return frames; } private static FrameData ReadFrame(string frameLine, FrameData prevFrame, int totalInstanceCount) { var frame = new FrameData(); frame.existingInstancesBits = new BitArray(totalInstanceCount, false); var parts = frameLine.Split('|'); var labels = parts[0]; frame.labels = string.IsNullOrEmpty(labels) ? new string[] { } : labels.Split(','); if (parts[1].Length == 0) { frame.instances = new InstanceData[] { }; } else { var instanceCount = parts.Length - 1; frame.instances = new InstanceData[instanceCount]; var prevFrameInstances = prevFrame != null ? prevFrame.instances.ToDictionary(it => it.id, it => it) : new Dictionary<int, InstanceData>(); for (int i = 0; i < instanceCount; i++) { var instance = ReadInstance(parts[i + 1], prevFrameInstances); frame.instances[i] = instance; frame.existingInstancesBits[instance.id] = true; } } return frame; } private static InstanceData ReadInstance(string data, IDictionary<int, InstanceData> prevFrameInstances) { var instance = new InstanceData(); var properties = data.Split(','); int propIndex = 0; instance.id = Convert.ToInt32(properties[propIndex]); InstanceData prevInstance; prevFrameInstances.TryGetValue(instance.id, out prevInstance); if (prevInstance == null) prevInstance = instance; instance.position.x = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.position.x); instance.position.y = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.position.y); instance.rotation = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.rotation); instance.scale.x = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.scale.x); instance.scale.y = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.scale.y); instance.color.rMult = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.color.rMult); instance.color.gMult = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.color.gMult); instance.color.bMult = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.color.bMult); instance.color.aMult = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.color.aMult); instance.color.rOffset = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.color.rOffset); instance.color.gOffset = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.color.gOffset); instance.color.bOffset = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.color.bOffset); instance.color.aOffset = ReadProperty(properties, ++propIndex, GetFloat, prevInstance.color.aOffset); return instance; } private static T ReadProperty<T>(string[] properties, int index, Func<string, T> func, T defaultValue) { if (index >= properties.Length) return defaultValue; var stringValue = properties[index]; return stringValue.Length > 0 ? func(stringValue) : defaultValue; } private static float GetFloat(string value) { return Convert.ToSingle(value, CultureInfo.InvariantCulture); } } }
17a856c60723303b785a5306fb73d3b36a257c42
C#
liujingcheng/LogAnTest
/LogAnTest/LogAn/LogAnalyzer.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LogAn { public class LogAnalyzer { public int MinNameLength = 8; private IWebService _service; public LogAnalyzer(IWebService service) { this._service = service; } public void Analyze(string fileName) { if (fileName.Length < MinNameLength) { try { _service.LogError("Filename too short:" + fileName); } catch (Exception e) { } } } public LogAnalyzer() { } public bool WasLastFileNameValid { get; set; } public bool IsValidLogFileName(string fileName) { WasLastFileNameValid = false; if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException("filename has to be provided"); } if (!fileName.EndsWith(".SLF", StringComparison.CurrentCultureIgnoreCase)) { return false; } WasLastFileNameValid = true; return true; } } }
0eb6c7c8ae1ba9525d434bf499fd2baefb299dfc
C#
ygtegeyvz/Car-Sales-Management-System-With-Layered-Architecture
/DataAccess/Concrete/EntityFramework/UserDal.cs
2.90625
3
using System.Linq; using DataAccess.Abstract; using Entities.Concrete; namespace DataAccess.Concrete.EntityFramework { public class UserDal:EfEntityRepositoryBase<Users,CarsCompanyContext>,IUsersDal { public static bool isValidLogin(string userName, string password) { using (CarsCompanyContext db = new CarsCompanyContext()) { Users user = (from u in db.Users where u.UserName.Equals(userName) select u).FirstOrDefault(); if (user == null) { return false; } else if (!user.Password.Equals(password)) { return false; } else { return true; } } } bool IUsersDal.isValidLogin(string userName, string password) { return isValidLogin(userName, password); } } }
0ea7882d322460936389457b8c3c76565e7f88b4
C#
aerobless/HSR_MsTech
/Ex01/2.1/ShapesMain.cs
3.671875
4
using System; namespace Shapes { public class ShapesMain { public static void Main() { // TODO: // Erzeuge Square-Objekt Square myFirstSquare = new Square(1,2,4); // Ausgabe Degrees Console.WriteLine("Degrees: "+myFirstSquare.Degrees); // Ausgabe Area Console.WriteLine("Area: " + myFirstSquare.Area()); // Ausgabe x1, y1, x2, y2 Console.WriteLine("X1:" + myFirstSquare.X1+" Y1:"+myFirstSquare.Y1+" X2:"+myFirstSquare.X2+" Y2:"+myFirstSquare.Y2); Console.WriteLine("press enter to exit"); Console.ReadLine(); } } }
1fab18ac44a1f918981c83535302b83dc316c25c
C#
bildermann/dotnet-sqlproxy-proto
/Controllers/RequestController.cs
2.546875
3
using Microsoft.AspNetCore.Mvc; using dotnet_sandbox.Models; using System.Collections.Generic; using MySql.Data.MySqlClient; using SqlKata; using SqlKata.Compilers; using System; namespace dotnet_sandbox.Controllers { [Route("api/[controller]")] public class RequestController : Controller { [HttpPost()] public IActionResult Post([FromBody]SQLRequest req) { var conn = new MySqlConnection("server=192.168.99.100;port=3306;user=root;password=root;database=employees"); var cmd = new MySqlCommand("", conn); // var compiler = new SqlServerCompiler(); var compiler = new MySqlCompiler(); var q = new Query(req.From); var paramCounter = 0; foreach (var literal in req.Where) { var val = literal.Values[0]; q.Where( literal.FieldName, literal.Operator, val.Value); // var p = cmd.CreateParameter(); // p.Value = val.Value; // p.ParameterName = "p" + paramCounter; cmd.Parameters.AddWithValue("@p" + paramCounter, val.Value); paramCounter++; // .Value = val.Value } q.Limit(req.Limit); q.Offset(req.Offset); cmd.Parameters.AddWithValue("@p" + paramCounter, req.Limit); paramCounter++; if (req.Offset > 0) { cmd.Parameters.AddWithValue("@p" + paramCounter, req.Offset); paramCounter++; } var sql = compiler.Compile(q).Sql; Console.Write(sql); cmd.CommandText = sql; conn.Open(); var resp = cmd.ExecuteReader(); var responseList = new List<Dictionary<string, object>>(); while (resp.Read()) { var rowDict = new Dictionary<string, object>(); for (var i = 0; i < resp.FieldCount; i++) { rowDict.Add(resp.GetName(i), resp[i]); } responseList.Add(rowDict); } conn.Close(); return Ok(new SQLResponse() { ResultSet = responseList, Next = new SQLRequest() { Select = req.Select, From = req.From, Where = req.Where, OrderBy = req.OrderBy, Limit = req.Limit, Offset = req.Offset + req.Limit }, Page = 1, Pages = 10, Count = 100 }); } } }
3933b18b44ed7591ed16e8801a471fe620b13c57
C#
nowanys/Wirehome.Core
/Wirehome.Core/MessageBus/MessageBusSubscriber.cs
2.65625
3
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading; namespace Wirehome.Core.MessageBus { public class MessageBusSubscriber { readonly Action<IDictionary<object, object>> _callback; readonly ILogger _logger; long _processedMessagesCount; long _pendingMessagesCount; long _faultedMessagesCount; public MessageBusSubscriber(string uid, IDictionary<object, object> filter, Action<IDictionary<object, object>> callback, ILogger logger) { Uid = uid ?? throw new ArgumentNullException(nameof(uid)); Filter = filter ?? throw new ArgumentNullException(nameof(filter)); _callback = callback ?? throw new ArgumentNullException(nameof(callback)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public string Uid { get; } public IDictionary<object, object> Filter { get; } public long ProcessedMessagesCount => Interlocked.Read(ref _processedMessagesCount); public long FaultedMessagesCount => Interlocked.Read(ref _faultedMessagesCount); public long PendingMessagesCount => Interlocked.Read(ref _pendingMessagesCount); public void ProcessMessage(IDictionary<object, object> message) { if (message is null) throw new ArgumentNullException(nameof(message)); try { Interlocked.Increment(ref _pendingMessagesCount); _callback.Invoke(message); Interlocked.Increment(ref _processedMessagesCount); } catch (Exception exception) { if (!(exception is OperationCanceledException)) { _logger.LogError(exception, $"Error while processing bus message for subscriber '{Uid}'."); } Interlocked.Increment(ref _faultedMessagesCount); } finally { Interlocked.Decrement(ref _pendingMessagesCount); } } //public bool TryProcessNextMessage() //{ // var isFirstProcessor = Interlocked.Increment(ref _processorGate) == 1; // try // { // if (!isFirstProcessor) // { // Ensures that only one out of n threads will process messages for this // instance at a time.The thread will return here and continues with // the next subscriber. // return false; // } // MessageBusMessage message; // lock (_messageQueue) // { // if (!_messageQueue.TryDequeue(out message)) // { // return false; // } // } // _callback.Invoke(message); // ProcessedMessagesCount++; // return true; // } // catch (Exception exception) // { // if (!(exception is OperationCanceledException)) // { // _logger.LogError(exception, $"Error while processing bus message for subscriber '{Uid}'."); // } // FaultedMessagesCount++; // return false; // } // finally // { // Interlocked.Decrement(ref _processorGate); // } //} } }
d356fea8a2a5dfc93d8a0d5b0ae359cb8b664a08
C#
vytautas-dotcom/DotNetEgzaminas
/AntraUzduotis/AntraUzduotis/Program.cs
3.265625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AntraUzduotis { class Program { static void Main(string[] args) { Console.WriteLine("Matricu sudetis atimtis. Matricu dimensijos turi sutapti"); Console.WriteLine("------------------------------------"); Console.WriteLine("Pirmosios matricos dimencijos"); if (!int.TryParse(Console.ReadLine(), out int m1) || !int.TryParse(Console.ReadLine(), out int n1)) { Console.WriteLine("Turite vesti skaicius"); } else { Console.WriteLine("Iveskite antraja trikampio krastine"); if (!int.TryParse(Console.ReadLine(), out int m2) || !int.TryParse(Console.ReadLine(), out int n2)) { Console.WriteLine("Turite vesti skaicius"); } else { Matrica1 matrica1 = new Matrica1(m1, n1); Matrica2 matrica2 = new Matrica2(m2, n2); AutomatinisMatricuUzpildymas(m1, n1, matrica1, m2, n2, matrica2); MatricuSudetis(m1, n1, matrica1, m2, n2, matrica2); MatricuAtimtis(m1, n1, matrica1, m2, n2, matrica2); } } Console.ReadKey(); } static void AutomatinisMatricuUzpildymas(int m1, int n1, Matrica1 A, int m2, int n2, Matrica2 B) { //Pirmos uzpildymas int rows1 = m1; int columns1 = n1; for (int i = 0; i < m1; i++) { for (int j = 0; j < n1; j++) { A.matrica[i, j] = i + j; } } //Antros uzpildymas int rows2 = m2; int columns2 = n2; for (int i = 0; i < m2; i++) { for (int j = 0; j < n2; j++) { B.matrica[i, j] = i + j + 5; } } } static void MatricuSudetis(int m1, int n1, Matrica1 A, int m2, int n2, Matrica2 B) { int[,] C = new int[m1, n1]; if((m1 == m2) && n1 == n2) { for (int i = 0; i < m1; i++) { for (int j = 0; j < n1; j++) { C[i, j] = A.matrica[i, j] + B.matrica[i, j]; } } } Console.WriteLine("-----------------------------------------"); Console.WriteLine("Nauja matrica C sudejus A ir B matricas:\n"); for (int i = 0; i < C.GetUpperBound(0) + 1; i++) { for (int j = 0; j < C.Length / C.GetUpperBound(0) + 1; j++) { Console.Write(C[i, j]); } Console.WriteLine(); } } static void MatricuAtimtis(int m1, int n1, Matrica1 A, int m2, int n2, Matrica2 B) { int[,] C = new int[m1, n1]; if ((m1 == m2) && n1 == n2) { for (int i = 0; i < m1; i++) { for (int j = 0; j < n1; j++) { C[i, j] = A.matrica[i, j] - B.matrica[i, j]; } } } Console.WriteLine("-----------------------------------------"); Console.WriteLine("Nauja matrica C atemus A ir B matricas:\n"); for (int i = 0; i < C.GetUpperBound(0) + 1; i++) { for (int j = 0; j < C.Length / C.GetUpperBound(0) + 1; j++) { Console.Write(C[i, j]); } Console.WriteLine(); } } } }
fb1d24e5635730f39b8b1b1e5995bcf839c918cc
C#
dmitriy27sprinchak/Lab1_Sqr_Allied_testing
/Lab1_Sqr_Allied_testing/Sq_Figure_Allied_lab/CircleParam.cs
2.765625
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 Sq_Figure_Allied_lab { public partial class CircleParam : Form { string s; double r,r2; double PI = 3.14; public CircleParam() { InitializeComponent(); } private void label2_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { s = textBox1.Text; r = Convert.ToDouble(s); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox2_MouseClick(object sender, MouseEventArgs e) { r2 = (r * r) * PI; textBox2.Text = Convert.ToString(r2); } } }
73d908ac3c18189ef23f6ac5ad6111b81540b5fe
C#
PelleRemus/Facultate
/Anul3Sem1/Inteligenta Artificiala/RegresieLiniara/RegresieLiniara/Program.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace RegresieLiniara { class Program { static void Main(string[] args) { Engine.Init(); for(int i=0; i<1000; i++) { Run(); Console.WriteLine(Engine.FAdec()); } File.WriteAllText(@"../../extData.txt", Engine.weights); Console.ReadLine(); } public static void Run() { for (int i = 0; i < Engine.nrOfIterations; i++) { Engine.GradientDescent(); } Engine.weights += Engine.W[0, 0] + " " + Engine.W[1, 0] + "\n"; } } }
90dd65cc08fec0101688c99e1886e90777d30d39
C#
mcaden/Sweeper
/Sweeper/Tasks/RunStyleCopRescanAll.cs
2.640625
3
namespace Sweeper { using System; using System.Diagnostics; /// <summary> /// Formats the document based on visual studio formatter settings. /// </summary> public class RunStyleCopRescanAll : SolutionStyleTaskBase { /// <summary> /// Initializes a new instance of the RunStyleCopRescanAll class. /// </summary> public RunStyleCopRescanAll() { TaskName = "Run StyleCop (Rescan All)"; TaskDescription = "Runs StyleCop (Rescan All) on the entire solution"; Debug.WriteLine("Task: " + TaskName + " created."); } /// <summary> /// Gets or sets a value indicating whether the task is enabled or not. /// </summary> public override bool IsEnabled { get { return Properties.Settings.Default.RunStyleCopRescanAllEnabled; } set { Properties.Settings.Default.RunStyleCopRescanAllEnabled = value; } } /// <summary> /// Performs the style task. /// </summary> /// <param name="ideWindow">The IDE window.</param> protected override void DoWork(EnvDTE.Window ideWindow) { try { Debug.WriteLine("Running StyleCop (Rescan All) on Solution"); ideWindow.SetFocus(); ideWindow.DTE.ExecuteCommand("Tools.RunStyleCopRescanAll", string.Empty); } catch (Exception exc) { Debug.WriteLine(exc.ToString()); Debug.WriteLine("StyleCop (Rescan All) failed, skipping"); } } } }
1de5e8516e77ce02e46b88b01ff23ab156c9fac9
C#
AnthonyLasiewicki/Virtual_Electronics_Lab
/Assets/Electrical/Circuit/Node/Node.cs
2.875
3
using System; using System.Collections.Generic; using UnityEngine; /// Node.cs is the script for the Node Component attached to the node objects. public class Node : MonoBehaviour { public static List<Node> TotalNodes { get; private set; } = new List<Node>(); public List<Component> Components { get; private set; } = new List<Component>(); public List<Node> AdjacentNodes { get; private set; } = new List<Node>(); public int x, y; private void Awake() { TotalNodes.AddRange(FindObjectsOfType<Node>()); AdjacentNodes = FindAdjacentNodes(this); } void OnTriggerEnter(Collider other) { if (other.gameObject.GetComponent<Component>() != null) Components.Add(other.gameObject.GetComponent<Component>()); if (other.gameObject.GetComponentInParent<Component>() != null) Components.Add(other.gameObject.GetComponentInParent<Component>()); } void OnTriggerExit(Collider other) { if (other.gameObject.GetComponent<Component>() != null) Components.Remove(other.gameObject.GetComponent<Component>()); if (other.gameObject.GetComponentInParent<Component>() != null) Components.Add(other.gameObject.GetComponentInParent<Component>()); } /// <summary> ///Returns a list of each node a component is in. /// </summary> public static List<Node> FindNodesForComponent(Component component) { List<Node> nodesComponentIn = new List<Node>(); foreach (Node n in TotalNodes) { foreach (Component c in n.Components) { if (c == component) nodesComponentIn.Add(n); } } return nodesComponentIn; } /// <summary> /// Returns a list of adjacent nodes. Returns an empty list if none adjacent. /// </summary> public List<Node> FindAdjacentNodes(Node n) { List<Node> adj = new List<Node>(); foreach(Node t in TotalNodes) { if ((Math.Abs(t.x - n.x) == 1 && (Math.Abs(t.y - n.y)) == 0) || (Math.Abs(t.x - n.x) == 0 && (Math.Abs(t.y - n.y)) == 1) ) { adj.Add(t); } } return adj; } }
24726e5cee82880ad2670034c36b8c45d4d8c27c
C#
Jazz-Harris/NeedForSpeedZombieEdition
/Assets/Scripts/CameraController.cs
2.953125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; // This class controls the behavior of the camera in conjuction to the player public class CameraController : MonoBehaviour { public GameObject player; //Public variable to store a reference to the player game object private Vector3 offset; //Private variable to store the offset distance between the player and camera public Transform target; private float xMin = -1.0f, xMax = 1.0f; private float timeValue = 0.0f; // Use this for initialization void Start() { //Calculate and store the offset value by getting the distance between the player's position and camera's position. offset = transform.position - player.transform.position; } void Update() { // Rotate the camera every frame so it keeps looking at the target transform.LookAt(target); // Same as above, but setting the worldUp parameter to Vector3.left in this example turns the camera on its side transform.LookAt(target, Vector3.left); // Compute the sin position. float xValue = Mathf.Sin(timeValue * 5.0f); // Now compute the Clamp value. float xPos = Mathf.Clamp(xValue, xMin, xMax); // Update the position of the cube. transform.position = new Vector3(xPos, 0.0f, 0.0f); // Increase animation time. timeValue = timeValue + Time.deltaTime; // Reset the animation time if it is greater than the planned time. if (xValue > Mathf.PI * 2.0f) { timeValue = 0.0f; } } // LateUpdate is called after Update each frame void LateUpdate() { // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance. transform.position = player.transform.position + offset; } }
31dec60add9e9403a380df79d7b66540bd9e4ce3
C#
google-code/bizblox
/API/BizBloxCSExamples/DataObjects/StudentCollection.cs
2.609375
3
using pixolut.BizBlox; public class StudentCollection : DOCollection { //START BizBlox Generated Code : Do not remove or alter this comment //Last Updated : Thursday, 24 August 2006 4:57:09 PM //BizBlox Version : 1.2.0.0 #region "BizBlox Generated Code" public StudentCollection() : base(new DOFactory((DataObject)new Student())) { } //to typecast your item() property public new Student this[int i]{ get{ return (Student)base[i]; } } #endregion //END BizBlox Generated Code : Do not remove or alter this comment public void FindByStudentName(string name) { SQLBuilder mySql = base.GetSqlBuilder(); mySql.addWhere(Student.Columns.Name, name); base.SetCurrentQuery(mySql); base.Find(); } public void SearchByStudentName(string SearchTerm) { SQLBuilder mySql = base.GetSqlBuilder(); if(SearchTerm != "") { SearchBuilder sb = new SearchBuilder(SearchTerm); mySql.addSearch(Student.Columns.Name, sb); } base.SetCurrentQuery(mySql); base.Find(); } public void FindByNameEmailAge( string name, string email, int ageLower, int ageUpper ) { SQLBuilder mySql = base.GetSqlBuilder(); if ( name.Length > 0 ) { SearchBuilder sb1 = new SearchBuilder( name ); mySql.addSearch( Student.Columns.Name, sb1 ); mySql.addAnd(); } if ( email.Length > 0 ) { SearchBuilder sb2 = new SearchBuilder( email ); mySql.addSearch( Student.Columns.Email, sb2 ); mySql.addAnd(); } mySql.AddWhereGTE( Student.Columns.Age, ageLower.ToString() ); mySql.addAnd(); mySql.AddWhereLTE( Student.Columns.Age, ageUpper.ToString() ); base.SetCurrentQuery(mySql); base.Find(); } }
fdf9e3d8d159cfd153f9f997ab1aaaf2eb03d9f5
C#
abhishekarora185/Imperial-Chess
/Assets/Scripts/Pieces/Rook.cs
2.53125
3
using System.Collections.Generic; using UnityEngine; public class Rook : AbstractPiece { public bool canCastle; public Rook() { this.InitializationActions(); } public Rook(Position position) { this.InitializationActions(); this.SetCurrentPosition(position); } // Use this for initialization void Start() { this.InitializationActions(); } // Update is called once per frame void Update() { } public override void PostMoveActions() { if (this.canCastle) { this.canCastle = false; } } public override void PerTurnProcessing() { } protected override void ComputeMoves() { // Compute universal moves for rooks this.moves = new Dictionary<Position, Bitboard>(); int column, row; for (column = Position.min; column <= Position.max; column++) { for (row = Position.min; row <= Position.max; row++) { Position position = new Position(column, row); Bitboard positionBitboard = new Bitboard(); int positionRow, positionColumn; for (positionColumn = Position.min; positionColumn <= Position.max; positionColumn++) { if (positionColumn != column) { positionBitboard.FlipPosition(new Position(positionColumn, row)); } } for (positionRow = Position.min; positionRow <= Position.max; positionRow++) { if (positionRow != row) { positionBitboard.FlipPosition(new Position(column, positionRow)); } } this.moves[position] = positionBitboard; } } } protected override Bitboard AdditionalMoveProcessing(Bitboard movesForCurrentPosition) { if (this.side == Side.Black) { movesForCurrentPosition = movesForCurrentPosition.ComputeRayIntersections(this.chessBoard.GetPieceLocations(Side.White), this.GetCurrentPosition(), true); } else { movesForCurrentPosition = movesForCurrentPosition.ComputeRayIntersections(this.chessBoard.GetPieceLocations(Side.Black), this.GetCurrentPosition(), true); } movesForCurrentPosition = movesForCurrentPosition.ComputeRayIntersections(this.chessBoard.GetPieceLocations(this.side), this.GetCurrentPosition(), false); return movesForCurrentPosition; } public override AbstractPiece CopyPiece(AbstractPiece pieceToCopy) { pieceToCopy = base.CopyPiece(pieceToCopy); Rook rookToCopy = (Rook)pieceToCopy; rookToCopy.canCastle = this.canCastle; return rookToCopy; } protected override void InitializationActions() { this.ComputeMoves(); this.canCastle = true; } }
217d51fa898dd05d010cd4f09e9f61c99df5e69c
C#
SatyaWeb006/comp-programing
/leetcode/_csharp/medium/_870_advantage_shuffle.cs
3.640625
4
using System; using System.Collections.Generic; // https://leetcode.com/problems/advantage-shuffle/ namespace _csharp { public class _870_advantage_shuffle { public int[] AdvantageCount(int[] A, int[] B) { int an = A.Length; int bn = B.Length; // index | value KeyValuePair<int,int>[] aa = new KeyValuePair<int,int>[an]; KeyValuePair<int,int>[] bb = new KeyValuePair<int,int>[bn]; for(int ii=0;ii<an;++ii){ aa[ii] = new KeyValuePair<int,int>(ii,A[ii]); } for(int ii=0;ii<bn;++ii){ bb[ii] = new KeyValuePair<int,int>(ii,B[ii]); } Array.Sort(aa, sortme); Array.Sort(bb, sortme); int i=0; int j=0; int n=an; int m=bn; while(i<n && j<m){ int aValue = aa[i].Value; int bValue = bb[j].Value; if(aValue > bValue){ int bIndex = bb[j].Key; A[bIndex] = aValue; ++i; ++j; } else{ while(i<n && j<m && aa[i].Value <= bValue){ int indexOfBiggestB = bb[m-1].Key; A[indexOfBiggestB] = aa[i].Value; --m; ++i; } } } return A; } private static int sortme(KeyValuePair<int,int> a, KeyValuePair<int,int> b){ if(a.Value < b.Value) return -1; if(a.Value > b.Value) return 1; return 0; } } }
30facfa2c65dcd837bf635996cf91812229189b0
C#
a407121393/neo-express
/src/neo-express/Extensions.cs
2.734375
3
using McMaster.Extensions.CommandLineUtils; using NeoExpress.Abstractions.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.IO; using System.Linq; using System.Text; namespace NeoExpress { internal static class Extensions { public static string ToHexString(this byte[] value, bool reverse = false) { StringBuilder sb = new StringBuilder(); if (reverse) { for (int i = value.Length - 1; i >= 0; i--) { sb.AppendFormat("{0:x2}", value[i]); } } else { for (int i = 0; i < value.Length; i++) { sb.AppendFormat("{0:x2}", value[i]); } } return sb.ToString(); } public static byte[] ToByteArray(this string value) { if (value == null || value.Length == 0) return new byte[0]; if (value.Length % 2 == 1) throw new FormatException(); byte[] result = new byte[value.Length / 2]; for (int i = 0; i < result.Length; i++) result[i] = byte.Parse(value.Substring(i * 2, 2), System.Globalization.NumberStyles.AllowHexSpecifier); return result; } static void WriteMessage(IConsole console, string message, ConsoleColor color) { var currentColor = console.ForegroundColor; try { console.ForegroundColor = color; console.WriteLine(message); } finally { console.ForegroundColor = currentColor; } } public static void WriteError(this IConsole console, string message) { WriteMessage(console, message, ConsoleColor.Red); } public static void WriteWarning(this IConsole console, string message) { WriteMessage(console, message, ConsoleColor.Yellow); } public static void WriteResult(this IConsole console, JToken? result) { if (result != null) { console.WriteLine(result.ToString(Formatting.Indented)); } else { console.WriteLine("<no result provided>"); } } public static void Save(this ExpressChain chain, string fileName) { var serializer = new JsonSerializer(); using (var stream = File.Open(fileName, FileMode.Create, FileAccess.Write)) using (var writer = new JsonTextWriter(new StreamWriter(stream)) { Formatting = Formatting.Indented }) { serializer.Serialize(writer, chain); } } public static bool IsReservedName(this ExpressChain chain, string name) { if ("genesis".Equals(name, StringComparison.InvariantCultureIgnoreCase)) return true; foreach (var node in chain.ConsensusNodes) { if (string.Equals(name, node.Wallet.Name, StringComparison.InvariantCultureIgnoreCase)) return true; } return false; } private static bool NameEquals(this ExpressWallet wallet, string name) => string.Equals(wallet.Name, name, StringComparison.InvariantCultureIgnoreCase); public static ExpressWallet GetWallet(this ExpressChain chain, string name) => (chain.Wallets ?? Enumerable.Empty<ExpressWallet>()) .SingleOrDefault(w => w.NameEquals(name)); public static string GetBlockchainPath(this ExpressWalletAccount account) { if (account == null) { throw new ArgumentNullException(nameof(account)); } return Path.Combine(Program.ROOT_PATH, account.ScriptHash); } public static ExpressContract? GetContract(this ExpressChain chain, string name) { foreach (var contract in chain.Contracts ?? Enumerable.Empty<ExpressContract>()) { if (string.Equals(name, contract.Name, StringComparison.InvariantCultureIgnoreCase)) { return contract; } } return null; } public static ExpressWalletAccount? GetAccount(this ExpressChain chain, string name) { if (chain.Wallets != null) { var wallet = chain.Wallets.SingleOrDefault(w => w.NameEquals(name)); if (wallet != null) { return wallet.DefaultAccount; } } var node = chain.ConsensusNodes.SingleOrDefault(n => n.Wallet.NameEquals(name)); if (node != null) { return node.Wallet.DefaultAccount; } if ("genesis".Equals(name, StringComparison.InvariantCultureIgnoreCase)) { return chain.ConsensusNodes .Select(n => n.Wallet.Accounts.Single(a => a.Label == "MultiSigContract")) .FirstOrDefault(); } return null; } public static string GetBlockchainPath(this ExpressWallet wallet) { if (wallet == null) { throw new ArgumentNullException(nameof(wallet)); } return wallet.Accounts .Single(a => a.IsDefault) .GetBlockchainPath(); } public static string GetBlockchainPath(this ExpressConsensusNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return node.Wallet.GetBlockchainPath(); } } }
55e9dee428bb7c9dfc620efc4b6e3688f6daef34
C#
ConfirmitYaroslavlStudents/Students
/2014/Kuzmin, Ovchenkov, Ragimov/HospitalApplication/HospitalApp/UserPages/SelectUser.xaml.cs
2.765625
3
using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Windows; using System.Windows.Controls; using HospitalLib.Data; using HospitalLib.Providers; namespace HospitalApp.UserPages { /// <summary> /// Interaction logic for SelectUser.xaml /// </summary> public partial class SelectUser { private IDictionary<string, Person> _personsDictionary; public SelectUser() { InitializeComponent(); _personsDictionary = new Dictionary<string, Person>(); LoadAllPerson(); if (PersonsComboBox.Items.Count == 0) throw new InvalidDataException("Persons Database is empty"); PersonsComboBox.SelectedIndex = 0; } private void CancelButton_Click(object sender, RoutedEventArgs e) { Switcher.PageSwitcher.Navigate(new StartPage()); } private void SelectUserButton_Click(object sender, RoutedEventArgs e) { if (PersonsComboBox.SelectedValue == null) { MessageBox.Show("Вам следует выбрать пациента"); return; } CurrentState.CurrentPerson = _personsDictionary[PersonsComboBox.SelectedValue.ToString()]; Switcher.PageSwitcher.Navigate(new UserLoaded()); } private void Search(string lastName, string firstName) { var personProvider = new PersonProvider(new DatabaseProvider()); var persons = personProvider.Search(firstName, lastName); AddToDictionary(persons); } private void LoadAllPerson() { var personProvider = new PersonProvider(new DatabaseProvider()); var persons = personProvider.Load(); AddToDictionary(persons); } private void AddToDictionary(IEnumerable<Person> persons) { var list = new ObservableCollection<string>(); foreach (var person in persons) { var name = person.ToString(); _personsDictionary[name]= person; list.Add(name); } PersonsComboBox.ItemsSource = list; } private void TextSomeWhereChanged(object sender, TextChangedEventArgs e) { _personsDictionary = new Dictionary<string, Person>(); var firstName = SearchByFirstNameTextBox.Text; var lastName = SearchByLastNameTextBox.Text; if (!string.IsNullOrEmpty(firstName) || !string.IsNullOrEmpty(lastName)) Search(lastName, firstName); else { LoadAllPerson(); } if (PersonsComboBox.Items.Count != 0) PersonsComboBox.SelectedIndex = 0; } } }
0a32aea91dac1668cfcf8f4223014f696da1bf77
C#
AllisterChew/helper
/tests/HelperTest.cs
3
3
using Helper; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace HelperTest { [TestClass] public class HelperTest { [TestMethod] public void ToCamelCase() { StringHelper sh = new StringHelper(); Assert.AreEqual(sh.ToCamelCase("this is a test"), "This Is A Test"); } [TestMethod] public void TruncateWord() { StringHelper sh = new StringHelper(); Assert.AreEqual(sh.TruncateWord("this is a test", 1), "this..."); } [TestMethod] public void StringToInt() { StringHelper sh = new StringHelper(); Assert.AreEqual(sh.StringToInt("8"), 8); } [TestMethod] public void ExplodeToList() { StringHelper sh = new StringHelper(); var result = new List<string>(); result.Add("this"); result.Add("is"); result.Add("a"); result.Add("test"); CollectionAssert.AreEqual(sh.ExplodeToList("this is a test", ' '), result); } [TestMethod] public void ImplodeToString() { StringHelper sh = new StringHelper(); var result = new List<string>(); result.Add("this"); result.Add("is"); result.Add("a"); result.Add("test"); Assert.AreEqual(sh.ImplodeToString(result, " "), "this is a test"); } [TestMethod] public void ReadFile() { FileHelper fh = new FileHelper(); Assert.AreEqual(fh.ReadFileAsText(@"C:\Users\allisterck\Documents\test.txt"), "test"); } } }
15c0f12d3df6474ce6e023ebd080b5bc9e21eb91
C#
Patrickode/603-Narrative-Project
/Assets/Scripts/System/EventSystem.cs
2.53125
3
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class EventSystem : MonoBehaviour { public static EventSystem instance; private void Awake() { instance = this; } public event Action OnEventA; public void EventA() { if(OnEventA != null) { OnEventA(); } } public event Action OnEventB; public void EventB() { if (OnEventB != null) { OnEventB(); } } }