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
b4cabab598a0f84cb43f8f9a2f7da830b48f8828
C#
shendongnian/download4
/code5/851988-21163312-55786057-1.cs
2.578125
3
XElement output = XElement.Load("c:\\temp\\input.xml"); IEnumerable<XElement> users = output.Elements(); DataTable dt = new DataTable(); dt.Columns.Add("CLIENT_INPUT_MHS_ID", typeof(int)); dt.Columns.Add("CLIENT_INPUT_MHS_GUID",typeof(Guid)); dt.Columns.Add("ITEM", typeof(string)); dt.Columns.Add("ITEM_ID", typeof(int)); dt.Columns.Add("ITEM_NUMBER", typeof(string)); dt.Columns.Add("CATEGORY", typeof(string)); foreach (XElement str in users) { DataRow dr = dt.NewRow(); foreach (XElement node in str.Elements()) { dr[node.Name.LocalName] = node.Value; } dt.Rows.Add(dr); } SqlBulkCopy bulkCopy = new SqlBulkCopy("ConnectionString..."); using (bulkCopy ) { bulkCopy .BulkCopyTimeout = 0; bulkCopy .ColumnMappings.Add(dt.Columns[0].ColumnName, "CLIENT_INPUT_MHS_ID"); bulkCopy .ColumnMappings.Add(dt.Columns[1].ColumnName, "CLIENT_INPUT_MHS_GUID"); bulkCopy .ColumnMappings.Add(dt.Columns[2].ColumnName, "ITEM"); bulkCopy .ColumnMappings.Add(dt.Columns[3].ColumnName, "ITEM_ID"); bulkCopy .ColumnMappings.Add(dt.Columns[4].ColumnName, "ITEM_NUMBER"); bulkCopy .ColumnMappings.Add(dt.Columns[5].ColumnName, "CATEGORY"); bulkCopy.DestinationTableName = "DestinationTableName"; bulkCopy.WriteToServer(dt); } Its working fine with my scenario.
e6a6867e865e45bdff74f3fe3a0b4bbb279c5298
C#
Peter-Georgiev/Programming.Fundamentals
/DataAndTypesExercises-Fast/06.CatchTheThief/CatchTheThief.cs
3.5
4
using System; using System.Linq; class CatchTheThief { static void Main() { string message = Console.ReadLine(); int n = int.Parse(Console.ReadLine()); long[] array = new long[n]; for (int i = 0; i < array.Length; i++) { array[i] = long.Parse(Console.ReadLine()); } long result = 0; for (int i = 0; i < array.Length; i++) { bool isLong = int.MaxValue <= array[i] && n <= array[i] && array[i] <= long.MaxValue && message.Equals("long"); bool isInt = sbyte.MaxValue <= array[i] && n <= array[i] && array[i] <= int.MaxValue && message.Equals("int"); bool isSbyte = sbyte.MinValue <= array[i] && n <= array[i] && array[i] <= sbyte.MaxValue && message.Equals("sbyte"); if (isLong) { result = array[i]; break; } else if (isInt) { result = array[i]; break; } else if (isSbyte) { result = array[i]; break; } } Console.WriteLine(result); } }
65851aacb0928f8b79cec7bc0287118a6abc6e64
C#
nhiuyenc7full/Module2
/ConsoleApp3/Vehicles/Bike.cs
3.09375
3
using System; using System.Collections.Generic; using System.Text; namespace OOP.Vehicles { class Bike: Vehicle { private int wheel; private string idBike = "CIRCLE"; private static int count = 0; private string id; public Bike() { count++; id = idBike + count; } public int Wheel { get => wheel; set => wheel = value; } public override void ToString() { Console.WriteLine("Xe thuoc hang: " + Make + ", doi: " + Model + ", nam: " + Year + ", id xe: " + id); } } }
be8792cbee935c2fb66f922d7bdd1cc5a91c26dd
C#
krishnareddyerredla/codility-csharp
/Lesson 01 - Iterations/BinaryGap_4.cs
3.34375
3
using System; // you can also use other imports, for example: // using System.Collections.Generic; // you can write to stdout for debugging purposes, e.g. // Console.WriteLine("this is a debug message"); class Solution { public int solution(int N) { // write your code in C# 6.0 with .NET 4.5 (Mono) string N_binary = Convert.ToString(N, 2); int max_gap = 0; int current_gap = -1; for (int i = 1; i < N_binary.Length; i++) { if (N_binary[i-1] == '1' && N_binary[i] == '0') { current_gap = 1; } else if (N_binary[i - 1] == '0' && N_binary[i] == '0') { current_gap++; } else if (N_binary[i - 1] == '0' && N_binary[i] == '1') { max_gap = Math.Max(max_gap, current_gap); } } return max_gap; } }
e14b270c41ac8de869a14ad3f27f04aed575aecd
C#
Blooker/MarchTheCube
/MarchingCubes/Assets/Scripts/Player/PlayerSound.cs
2.53125
3
using UnityEngine; using System.Collections; public class PlayerSound : MonoBehaviour { [SerializeField] private AudioSource audioSource; public void PlayPlayerSound (AudioClip clip) { if (audioSource.clip == null) { Debug.Log("Changed clip to " + clip.name); audioSource.clip = clip; } else { if (audioSource.clip.name != clip.name) { Debug.Log("Changed clip to " + clip.name); audioSource.clip = clip; } } audioSource.Play(); } }
d8e9fdeca9c89b0269002664f68ddcd78d3320aa
C#
michael-ell/Pies
/Tests/Core/Domain/TagsSpecs.cs
2.8125
3
using System.Collections.Generic; using System.Linq; using Codell.Pies.Core.Domain; using Codell.Pies.Testing.BDD; using FluentAssertions; namespace Codell.Pies.Tests.Core.Domain.TagsSpecs { [Concern(typeof (Tags))] public class When_tags_are_empty : ContextBase { private Tags _tags; protected override void When() { _tags = new Tags(new List<string> {null, "", " "}); } [Observation] public void Then_they_should_not_be_included_as_valid_tags() { _tags.Count().Should().Be(0); } } [Concern(typeof(Tags))] public class When_tags_are_less_than_3_characters: ContextBase { private Tags _tags; protected override void When() { _tags = new Tags(new List<string> { "x", "xy", " x", "y " }); } [Observation] public void Then_they_should_not_be_included_as_valid_tags() { _tags.Count().Should().Be(0); } } [Concern(typeof(Tags))] public class When_tags_are_greater_than_or_equal_to_3_characters : ContextBase { private Tags _tags; protected override void When() { _tags = new Tags(new List<string> { "abcd", "efg"} ); } [Observation] public void Then_they_should_be_included_as_valid_tags() { _tags.Count().Should().Be(2); } } [Concern(typeof(Tags))] public class When_tags_are_greater_than_or_equal_to_3_characters_but_have_duplicates : ContextBase { private Tags _tags; protected override void When() { _tags = new Tags(new List<string> { "abcd", "abcd" }); } [Observation] public void Then_they_should_only_include_unique_tags() { _tags.Count().Should().Be(1); } } [Concern(typeof(Tags))] public class When_tags_that_are_greater_than_or_equal_to_3_characters_have_preceding_or_trailing_spaces : ContextBase { private Tags _tags; private List<string> _expectedTags; protected override void Given() { _expectedTags = new List<string>{ "abcd", "efg"}; } protected override void When() { _tags = new Tags(new List<string> { " abcd", "efg " }); } [Observation] public void Then_the_tags_should_be_trimmed() { foreach (var expectedTag in _expectedTags) { _tags.Should().Contain(expectedTag); } } } [Concern(typeof(Tags))] public class When_tags_that_are_greater_than_or_equal_to_3_characters_have_mixed_case : ContextBase { private Tags _tags; private List<string> _expectedTags; protected override void Given() { _expectedTags = new List<string> { "abcd", "efg" }; } protected override void When() { _tags = new Tags(new List<string> { "ABCD", "eFg" }); } [Observation] public void Then_the_tags_should_be_converted_to_lowercase() { foreach (var expectedTag in _expectedTags) { _tags.Should().Contain(expectedTag); } } } }
fd45f53285b3285c308a1060507a78ff4e69cada
C#
Dilatazu/RealmPlayers
/RealmPlayers/RealmPlayersWebsite/Code/Logger.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Threading; using Utility = VF_RealmPlayersDatabase.Utility; namespace RealmPlayersServer { public class Logger { private static DateTime sm_LogStartTime = DateTime.Now; private static List<string> sm_Log = new List<string>(); public static void Initialize() { VF_RealmPlayersDatabase.Logger.SetupExternalLog(ConsoleWriteLine, LogException); } public static void LogException(Exception _Ex) { ConsoleWriteLine(_Ex.ToString(), ConsoleColor.Red); } public static void ConsoleWriteLine(string _Message, System.Drawing.Color _Color) { string dateTimeNow = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); string fullMessage = dateTimeNow + " : " + _Message; int colorARGB = _Color.ToArgb() & 0xFFFFFF; fullMessage = "<font color='#" + colorARGB.ToString("X6") + "'>" + fullMessage + "</font><br/>"; lock(sm_Log) { bool addedDuplicate = false; if(sm_Log.Count > 0) { try { if (sm_Log.Last().Contains(_Message)) { if(sm_Log.Last().StartsWith("<") == false) { int indexOfStar = sm_Log.Last().IndexOf('*'); string num = sm_Log.Last().Substring(0, indexOfStar); num = "" + (int.Parse(num) + 1); sm_Log[sm_Log.Count-1] = num + sm_Log[sm_Log.Count-1].Substring(indexOfStar); addedDuplicate = true; } else { sm_Log[sm_Log.Count - 1] = "2* " + sm_Log[sm_Log.Count - 1]; addedDuplicate = true; } } } catch (Exception) {} } if (addedDuplicate == false) { sm_Log.Add(fullMessage); } } } public static void ConsoleWriteLine(string _Message, ConsoleColor _Color = ConsoleColor.White) { ConsoleWriteLine(_Message, System.Drawing.Color.FromName(_Color.ToString())); } public static List<string> GetCopyOfLog(int _Count) { List<string> retLog = new List<string>(); lock(sm_Log) { if (_Count > sm_Log.Count) _Count = sm_Log.Count; for (int i = sm_Log.Count - _Count; i < sm_Log.Count; ++i) { retLog.Add(sm_Log[i]); } } return retLog; } public static List<string> GetCopyOfLog() { List<string> retLog = null; lock (sm_Log) { retLog = new List<string>(sm_Log); } return retLog; } public static void SaveToDisk() { try { var logCopy = GetCopyOfLog(999999); string logFilename = Constants.RPPDbWriteDir + "WebsiteLogs\\Log_" + sm_LogStartTime.ToString("yyyy_MM_dd_HH_mm_ss") + ".html"; Utility.AssertFilePath(logFilename); sm_Log.Insert(0, "<body bgcolor='#111'>"); System.IO.File.WriteAllLines(logFilename, sm_Log); Logger.ConsoleWriteLine("SaveToDisk(): Saved Logfile to disk!", ConsoleColor.Yellow); } catch (Exception ex) { LogException(ex); } } } }
7ec628e7eee4355399c28a7ec8410735cb46e8e8
C#
scaepz/shapist-game
/WpfApplication1/ViewModel/LevelEditViewModel.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Editor.Model; using System.ComponentModel.DataAnnotations; using System.ComponentModel; namespace Editor.ViewModel { public class LevelEditViewModel { public Level lvl; public LevelEditViewModel() { } public void CreateLevel(int x, int y, char defaultChar, string name) { lvl = new Level(); lvl.CreateLevel(x,y, defaultChar); lvl.Name = name; } public void OpenLevel(string name) { lvl = DataProvider.OpenLevel(name); } public void SaveLevel() { DataProvider.SaveLevel(lvl); } } public class ImportTextureViewModel : INotifyPropertyChanged { [Validation.UniqueTextureName] [Required(ErrorMessage = "Name is required")] public string Name { get; set; } [Range(1, 200,ErrorMessage="Frame amount must be in the range of [1, 200]")] [Required(ErrorMessage = "Frame amount is required")] public int Frames { get; set; } public void Import() { DataProvider.ImportTexture(Name, Frames, Path); } public string Path { get; set; } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(info)); } } } }
e3b3fe20688f93e43ce111ef474d2f1b5d57b8a8
C#
KevinKao809/SunnyPoint-Azure
/ShareClasses/DateTimeService.cs
3.265625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShareClasses { public class DateTimeService { public static long GetTimeStampByDateTime(DateTime inputDateTime) { DateTime baseTime = new DateTime(1970, 1, 1);//宣告一個GTM時間出來 long timeStamp = Convert.ToInt64(((TimeSpan)inputDateTime.Subtract(baseTime)).TotalMilliseconds); return timeStamp; } public static DateTime GetDateTimeByTimeStamp(long timeStamp) { timeStamp = timeStamp / 1000; System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); dtDateTime = dtDateTime.AddSeconds(timeStamp); return dtDateTime; } public static string ConvertTotalSecondToString(double totalSecond) { int i_duration = (int)Math.Round(totalSecond, 0); int hh = i_duration / 3600; int j_duration = i_duration - (hh * 3600); int mm = j_duration / 60; int ss = j_duration - (mm * 60); string s_duration = hh.ToString("00") + ":" + mm.ToString("00") + ":" + ss.ToString("00"); return s_duration; } } }
b3a0045030718661106e8b01b2897a6798da70be
C#
geffzhang/test-cse-dapr-icebreaker
/Vigilantes.DaprWorkshop.OrderService/csharp/Controllers/OrderController.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Vigilantes.DaprWorkshop.OrderService.Models; namespace Vigilantes.DaprWorkshop.OrderService.Controllers { [ApiController] [EnableCors] [Route("[controller]")] public class OrderController : ControllerBase { private readonly ILogger<OrderController> _logger; private readonly HttpClient _httpClient; public OrderController(IHttpClientFactory httpClientFactory, ILogger<OrderController> logger) { _httpClient = httpClientFactory.CreateClient(); _logger = logger; } [HttpPost] public async Task<IActionResult> NewOrder([FromBody]CustomerOrder order) { _logger.LogInformation("Customer Order received: {@CustomerOrder}", order); // Create an order summary that will be used as the // message body when published var orderSummary = CreateOrderSummary(order); _logger.LogInformation("Created Order Summary: {@OrderSummary}", orderSummary); // TODO: Challenge 2 - Publish an OrderSummary message via Dapr return Ok("Bummer. Business logic and pub/sub isn't implemented yet but, hey, at least your POST worked and you should see the order in the log! YOINK!"); } private static OrderSummary CreateOrderSummary(CustomerOrder order) { // Retrieve all the menu items var menuItems = MenuItem.GetAll(); // Iterate through the list of ordered items to calculate // the total and compile a list of item summaries. var orderTotal = 0.0m; var itemSummaries = new List<OrderItemSummary>(); foreach (var orderItem in order.OrderItems) { var menuItem = menuItems.FirstOrDefault(x => x.MenuItemId == orderItem.MenuItemId); if (menuItem == null) continue; orderTotal += (menuItem.Price * orderItem.Quantity); itemSummaries.Add(new OrderItemSummary { Quantity = orderItem.Quantity, MenuItemId = orderItem.MenuItemId, MenuItemName = menuItem.Name }); } // Initialize and return the order summary var summary = new OrderSummary { OrderId = Guid.NewGuid(), StoreId = order.StoreId, CustomerName = order.CustomerName, LoyaltyId = order.LoyaltyId, OrderDate = DateTime.UtcNow, OrderItems = itemSummaries, OrderTotal = orderTotal }; return summary; } } }
dccdd6e76efb8ce0e963eff04ead1d7bc7a140f6
C#
jurriemcflurry/BotjeDeVis-src
/Dialogs/AddProductsToOrderDialog.cs
2.796875
3
using CoreBot.Database; using CoreBot.Models; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Dialogs.Choices; using Microsoft.Bot.Schema; using Microsoft.BotBuilderSamples.Dialogs; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace CoreBot.Dialogs { // NO LONGER IN USE public class AddProductsToOrderDialog : CancelAndHelpDialog { private GremlinHelper gremlinHelper; private List<Product> productList = new List<Product>(); private bool toevoegen = true; private string productListString = "Producten: "; public AddProductsToOrderDialog(IConfiguration configuration) : base(nameof(AddProductsToOrderDialog)) { this.gremlinHelper = new GremlinHelper(configuration); AddDialog(new TextPrompt(nameof(TextPrompt))); AddDialog(new ChoicePrompt(nameof(ChoicePrompt))); AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[] { AskForProductsAsync, PromptQuestionAsync, HandleChoiceAsync, UpdateProductListAsync, })); InitialDialogId = nameof(WaterfallDialog); } private async Task<DialogTurnResult> AskForProductsAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { productList = (List<Product>)stepContext.Options; if(productList.Count > 0) { string producten = ""; foreach(Product p in productList) { producten += p.GetProductName() + ", "; } producten = producten.Remove(producten.Length - 2); await stepContext.Context.SendActivityAsync("In je bestelling staan nu de volgende producten: " + producten + "."); } return await stepContext.NextAsync(); } // after this step, it just returns to the previous step instead of moving forward, and then ends this dialog private async Task<DialogTurnResult> PromptQuestionAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { return await stepContext.PromptAsync(nameof(ChoicePrompt), new PromptOptions { Prompt = MessageFactory.Text("Wil je nog een product toevoegen of verwijderen?"), Choices = ChoiceFactory.ToChoices(new List<string> { "Toevoegen", "Verwijderen", "Klaar met bestellen" }) }, cancellationToken); } private async Task<DialogTurnResult> HandleChoiceAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { FoundChoice choice = (FoundChoice)stepContext.Result; switch (choice.Index) { case 0: toevoegen = true; var messageText = "Welk product wil je toevoegen?"; var promptMessage = MessageFactory.Text(messageText, messageText, InputHints.ExpectingInput); return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = promptMessage }, cancellationToken); case 1: toevoegen = false; List<string> productsString = new List<string>(); foreach (Product p in productList) { productsString.Add(p.GetProductName()); } return await stepContext.PromptAsync(nameof(ChoicePrompt), new PromptOptions { Prompt = MessageFactory.Text("Welk product wil je verwijderen?"), Choices = ChoiceFactory.ToChoices(productsString) }, cancellationToken); case 2: return await stepContext.EndDialogAsync(productList); default: break; } return await stepContext.NextAsync(); } private async Task<DialogTurnResult> UpdateProductListAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { if (toevoegen) { string productName = (string)stepContext.Result; //hele string wordt gepakt als product, kijken om te verbeteren (nog een Luis-call om entiteit te filteren) bool productExists = await gremlinHelper.ProductExistsAsync(productName); if (productExists) { Product product = new Product(productName); productList.Add(product); } else { await stepContext.Context.SendActivityAsync("Product " + productName + " is helaas niet in ons assortiment."); } } else if (!toevoegen) { FoundChoice choice = (FoundChoice)stepContext.Result; string productFound = choice.Value.ToString(); foreach (Product p in productList) { if (p.GetProductName().Equals(productFound)) { productList.Remove(p); await stepContext.Context.SendActivityAsync("Product " + productFound + " is verwijderd uit uw bestelling."); } } } await stepContext.Context.SendActivityAsync("De volgende producten staan nu in je bestelling:"); foreach(Product p in productList) { productListString += p.GetProductName() + ", "; } productListString = productListString.Remove(productListString.Length - 2); await stepContext.Context.SendActivityAsync(productListString); return await stepContext.ReplaceDialogAsync(nameof(AddProductsToOrderDialog), productList, cancellationToken); } } }
3e4681285328252f655073b8d8dd60875bbe69e3
C#
a-postx/Delobytes.Mapper
/tst/Delobytes.Mapper.Test/MapperTest.cs
2.71875
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Xunit; namespace Delobytes.Mapper.Test { public class MapperTest { [Fact] public void Map_Null_ThrowsArgumentNullException() { Mapper mapper = new Mapper(); Assert.Throws<ArgumentNullException>("source", () => mapper.Map(null)); } [Fact] public void Map_ToNewObject_Mapped() { Mapper mapper = new Mapper(); MapTo to = mapper.Map(new MapFrom() { Property = 1 }); Assert.Equal(1, to.Property); } [Fact] public void MapArray_Empty_Mapped() { Mapper mapper = new Mapper(); MapTo[] to = mapper.MapArray(new MapFrom[0]); Assert.IsType<MapTo[]>(to); Assert.Empty(to); } [Fact] public void MapArray_ToNewObject_Mapped() { Mapper mapper = new Mapper(); MapTo[] to = mapper.MapArray( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 } }); Assert.IsType<MapTo[]>(to); Assert.Equal(2, to.Length); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } [Fact] public void MapTypedCollection_Empty_Mapped() { Mapper mapper = new Mapper(); List<MapTo> to = mapper.MapCollection( new MapFrom[0], new List<MapTo>()); Assert.IsType<List<MapTo>>(to); Assert.Empty(to); } [Fact] public void MapTypedCollection_ToNewObject_Mapped() { Mapper mapper = new Mapper(); List<MapTo> to = mapper.MapCollection( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 } }, new List<MapTo>()); Assert.IsType<List<MapTo>>(to); Assert.Equal(2, to.Count); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } [Fact] public void MapCollection_Empty_Mapped() { Mapper mapper = new Mapper(); Collection<MapTo> to = mapper.MapCollection(new MapFrom[0]); Assert.IsType<Collection<MapTo>>(to); Assert.Empty(to); } [Fact] public void MapCollection_ToNewObject_Mapped() { Mapper mapper = new Mapper(); Collection<MapTo> to = mapper.MapCollection( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 } }); Assert.IsType<Collection<MapTo>>(to); Assert.Equal(2, to.Count); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } [Fact] public void MapList_Empty_Mapped() { Mapper mapper = new Mapper(); List<MapTo> to = mapper.MapList(new MapFrom[0]); Assert.IsType<List<MapTo>>(to); Assert.Empty(to); } [Fact] public void MapList_ToNewObject_Mapped() { Mapper mapper = new Mapper(); List<MapTo> to = mapper.MapList( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 } }); Assert.IsType<List<MapTo>>(to); Assert.Equal(2, to.Count); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } [Fact] public void MapObservableCollection_Empty_Mapped() { Mapper mapper = new Mapper(); ObservableCollection<MapTo> to = mapper.MapObservableCollection(new MapFrom[0]); Assert.IsType<ObservableCollection<MapTo>>(to); Assert.Empty(to); } [Fact] public void MapObservableCollection_ToNewObject_Mapped() { Mapper mapper = new Mapper(); ObservableCollection<MapTo> to = mapper.MapObservableCollection( new MapFrom[] { new MapFrom() { Property = 1 }, new MapFrom() { Property = 2 } }); Assert.IsType<ObservableCollection<MapTo>>(to); Assert.Equal(2, to.Count); Assert.Equal(1, to[0].Property); Assert.Equal(2, to[1].Property); } } }
09d493fa76d739dab1232d9356cf5686857ed0fb
C#
ASbeletsky/HexagonArchitectureTempalate
/src/Domain/HexagonArchitecture.Domain.Interfaces/Sorting.cs
2.921875
3
using System; using System.Linq.Expressions; using JetBrains.Annotations; namespace HexagonArchitecture.Domain.Interfaces { /// <summary> /// Sort order enumeration /// </summary> [PublicAPI] public enum SortOrder { [PublicAPI] Asc = 1, [PublicAPI] Desc = 2 } [PublicAPI] public class Sorting<TEntity, TKey> where TEntity: class { public Sorting([NotNull] Expression<Func<TEntity, TKey>> expression, SortOrder sortOrder = SortOrder.Asc) { if (expression == null) throw new ArgumentNullException(nameof(expression)); Expression = expression; SortOrder = sortOrder; } public Expression<Func<TEntity, TKey>> Expression { get; private set; } public SortOrder SortOrder { get; private set; } } }
f06439cd691af4d41cc812a34a80b12564cfc23f
C#
nguyentansongbsd/InsightLand
/ConasiCRM/Portable/Models/PhiMoGioiFormModel.cs
2.515625
3
using ConasiCRM.Portable.Helper; using System; using System.Collections.Generic; using System.Text; namespace ConasiCRM.Portable.Models { public class PhiMoGioiFormModel { public string bsd_name { get; set; } public string project_bsd_name { get; set; } public int bsd_loaimoigioi { get; set; } public string bsd_loaimoigioi_format { get { switch (this.bsd_loaimoigioi) { case 100000000: return "Cộng tác viên"; case 100000001: return "Khách hàng giới thiệu"; case 100000002: return "Đơn vị liên kết"; default: return " "; } } } public int bsd_calculation { get; set; } // cách tính public string bsd_calculation_format { get { switch (this.bsd_calculation) { case 100000000: return "Số lượng"; case 100000001: return "Số tiền"; default: return " "; } } } public int soluong { get { if(this.bsd_calculation == 100000000) { return 48; } else { return 0; } } } public int sotien { get { if (this.bsd_calculation == 100000001) { return 48; } else { return 0; } } } public int bsd_method { get; set; } // phương thức public string bsd_method_format { get { switch (this.bsd_method) { case 100000000: return "Phần trăm"; case 100000001: return "Số tiền"; default: return " "; } } } public int phiPhanTram { get { if (this.bsd_method == 100000000) return 48; else return 0; } } public int phiTien { get { if (this.bsd_method == 100000001) return 48; else return 0; } } public bool bsd_progressive { get; set; } //lũy tiến public int bsd_level { get; set; } public string bsd_level_format { get { switch (this.bsd_level) { case 100000000: return "Mức 1"; case 100000001: return "Mức 2"; case 100000002: return "Mức 3"; case 100000003: return "Mức 4"; case 100000004: return "Mức 5"; default: return " "; } } } public int bsd_quantityfrom { get; set; } // số lượng từ public int bsd_quantityto { get; set; } // số lượng đến public decimal bsd_amountfrom { get; set; } // số tiền từ public string bsd_amountfrom_format { get => StringHelper.DecimalToCurrencyText(bsd_amountfrom); } public decimal bsd_amountto { get; set; } // số tiền đến public string bsd_amountto_format { get => StringHelper.DecimalToCurrencyText(this.bsd_amountto); } public decimal bsd_feepercent { get; set; } // phi % public string bsd_feepercent_format { get => StringHelper.DecimalToPercentFormat(this.bsd_feepercent); } public decimal bsd_feeamount { get; set; } // phi số tiền public string bsd_feeamount_format { get => StringHelper.DecimalToCurrencyText(bsd_feeamount); } public int statuscode { get; set; } public string statuscode_format { get { switch (this.statuscode) { case 1: return "Nháp"; case 100000000: return "Áp dụng"; case 100000001: return "Từ chối"; case 100000002: return "Hết hạn"; default: return " "; } } } public DateTime bsd_startdate { get; set; } public string bsd_startdate_format { get => StringHelper.DateFormat(this.bsd_startdate); } public DateTime bsd_enddate { get; set; } public string bsd_enddate_format { get => StringHelper.DateFormat(this.bsd_enddate); } } }
af8ae3e6dbd119f6bf280645f302bd07bdd794e8
C#
eduardo-salazar/sag
/Sistema De Administracion De Servicios/EncryptPassphraseAlgorithm.cs
2.921875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sistema_De_Administracion_De_Servicios { class EncryptPassphraseAlgorithm { public static string EncryptSHA1(string passphrase) { string psEncrypted=""; System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create(); System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding(); byte[] combined = encoder.GetBytes(passphrase); hash.ComputeHash(combined); psEncrypted = Convert.ToBase64String(hash.Hash); return psEncrypted; } } }
d8ca0c73325fdec46cd983a4e2a199508a34efc4
C#
mff-uk/exolutio
/Model/OCL/AST/OperationCallExp.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Exolutio.Model.OCL.Types; namespace Exolutio.Model.OCL.AST { /// <summary> /// An OperationCallExp refers to an operation defined in a Classifier. The expression may contain a list of argument /// expressions if the operation is defined to have parameters. In this case, the number and types of the arguments must match /// the parameters. /// </summary> public class OperationCallExp : FeatureCallExp { public Environment Environment { get; set; } /// <summary> /// /// </summary> /// <param name="source">Source expression of iterotor. Itertor is calling on this expression.</param> /// <param name="isPre">Is marked by pre</param> /// <param name="refOperation">Called operation</param> /// <param name="args">Parameters of operation</param> /// <param name="environment">Environment</param> public OperationCallExp(OclExpression source, bool isPre, Operation refOperation, List<OclExpression> args, Environment environment = null):base(source,isPre,refOperation.GetReturnType(args)) { this.ReferredOperation = refOperation; this.Arguments = args; this.Environment = environment; } /// <summary> /// The arguments denote the arguments to the operation call. This is only useful when the /// operation call is related to an Operation that takes parameters. /// </summary> public List<OclExpression> Arguments { get; set; } /// <summary> /// The Operation to which this OperationCallExp is a reference. This is an Operation of a /// Classifier that is defined in the UML model. /// </summary> public Operation ReferredOperation { get; set; } public override T Accept<T>(IAstVisitor<T> visitor) { return visitor.Visit(this); } public override void Accept(IAstVisitor visitor) { visitor.Visit(this); } } }
9812f57603f7cafc63c8ff84cb9453b8073a40d0
C#
jacgit18/Asp-Class-intro-1
/WebApplication4/WebForm1.aspx.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication4 { public partial class WebForm1 : System.Web.UI.Page { int Numfailures; protected void Button1_Click(object sender, EventArgs e) { if (4 == 4) { return; } if (TextBox1.Text == TextBox2.Text) { // TextBox3.Text = "Success"; String Uname; Uname = TextBox1.Text; // creating session object Session["username"] = Uname; Response.Redirect("Greetings.aspx?username= "); } else { TextBox3.Text = "Failure"; Numfailures =int.Parse( txtNumfail.Value); Numfailures = int.Parse(Session["failures"].ToString()); Numfailures++; Session["failures"] = Numfailures.ToString(); if (Numfailures > 3) { TextBox3.Text = "Blocked"; } } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["failures"] = 0; } } protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { if (args.Value == "Dmoody") { args.IsValid = false; } else { args.IsValid = true; } } } }
3ca371d60e50e5c69d76fb56b80ff03648586d37
C#
kraian/Trevendi
/src/Web/Utils/Utils.cs
2.890625
3
using System; using System.Linq; namespace Web.Utils { public static class Utils { private const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; public static string GenerateRandomId(int length) { var random = new Random(Guid.NewGuid().GetHashCode()); return new string(Enumerable.Repeat(Chars, length).Select(s => s[random.Next(s.Length)]).ToArray()); } } }
daf447e4032c50dea8bff89992fdc8824d4c7609
C#
FURams09/Vidly
/Vidly/ViewModels/MovieViewModel.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using Vidly.Models; namespace Vidly.ViewModels { public class MovieViewModel { public IEnumerable<Genre> Genre { get; set; } public int ID { get; set; } [Required] [StringLength(400)] public string Name { get; set; } [Required] [Display(Name = "Release Date")] public DateTime? ReleaseDate { get; set; } [Required] [Display(Name = "Date Added")] public DateTime? DateAdded { get; set; } [Required] [Display(Name = "# in Stock")] [Range(0, 20, ErrorMessage = "Stock must be between 0 and 20.")] public short? NoAvailable { get; set; } [Required] [Display(Name = "Genre")] public short? GenreId { get; set; } public string Title { get { return ID != 0 ? "Edit Movie" : "New Movie"; } } public MovieViewModel() { ID = 0; } public MovieViewModel(Movie movie) { ID = movie.ID; Name = movie.Name; GenreId = movie.GenreId; ReleaseDate = movie.ReleaseDate; NoAvailable = movie.NoAvailable; DateAdded = movie.DateAdded; } } }
5356757019ff4569ab7c10c97b4f0e79b58b43f5
C#
AppReadyGo/EyeTracker
/EyeTracker.Model/Commands/Users/CreateUserCommand.cs
2.875
3
using System.Collections.Generic; namespace EyeTracker.Common.Commands.Users { public abstract class CreateUserCommand : ICommand<int> { public string Email { get; set; } public string Password { get; set; } protected CreateUserCommand(string email, string password) { this.Email = email; this.Password = password; } public virtual IEnumerable<ValidationResult> ValidatePermissions(ISecurityContext security) { yield break; } public IEnumerable<ValidationResult> Validate(IValidationContext validation) { if (string.IsNullOrEmpty(this.Email)) { yield return new ValidationResult(ErrorCode.WrongEmail, "The command must have an Email parameter."); } if (!validation.IsCorrectEmail(this.Email)) { yield return new ValidationResult(ErrorCode.WrongEmail, "The email is wrong."); } if (validation.IsEmailExists(this.Email)) { yield return new ValidationResult(ErrorCode.EmailExists, "The email exists in the system."); } if (string.IsNullOrEmpty(this.Password)) { yield return new ValidationResult(ErrorCode.WrongPassword, "The command must have an Password parameter."); } if (!validation.IsCorrectPassword(this.Password)) { yield return new ValidationResult(ErrorCode.WrongPassword, "The password is wrong."); } } } public class CreateMemberCommand : CreateUserCommand { public CreateMemberCommand(string email, string password) : base(email, password) { } } public class CreateStaffCommand : CreateUserCommand { public CreateStaffCommand(string email, string password) : base(email, password) { } } }
5fc80afa2df9ffd59c1c27d1b66fc89b8477f411
C#
sedc-codecademy/skwd9-net-06-csharpadv
/G2/HomeworkClass01/Task01/Entities/Game.cs
2.90625
3
using System; using System.Collections.Generic; using System.Text; namespace Task01.Entities { public class Game { private int _gamesPlayed { get; set; } protected bool IsActive { get; set; } public Game() { _gamesPlayed = 0; } protected void IncreaseGamesPlayed() { _gamesPlayed += 1; } protected int GetGamesPlayed() { return _gamesPlayed; } } }
71b503cd8ae36e2ec49151753f1d7bf3fd7b6649
C#
JMPSequeira/json-everything
/JsonLogic/JsonLogicException.cs
2.671875
3
using System; namespace Json.Logic { /// <summary> /// Thrown when a rule cannot be processed or deserialized. /// </summary> public class JsonLogicException : Exception { /// <summary> /// Creates a new instance of the <see cref="JsonLogicException"/> class. /// </summary> /// <param name="message">The exception message.</param> public JsonLogicException(string message) : base(message) { } } }
5b684174d7380e9d642aa48bb064a98722c95658
C#
patrickdemooij9/Umbraco-CMS
/src/Umbraco.Web/PropertyEditors/FileUploadPropertyValueEditor.cs
2.515625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json.Linq; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Models.Editors; using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { /// <summary> /// The value editor for the file upload property editor. /// </summary> internal class FileUploadPropertyValueEditor : DataValueEditor { private readonly IMediaFileSystem _mediaFileSystem; public FileUploadPropertyValueEditor(DataEditorAttribute attribute, IMediaFileSystem mediaFileSystem) : base(attribute) { _mediaFileSystem = mediaFileSystem ?? throw new ArgumentNullException(nameof(mediaFileSystem)); } /// <summary> /// Converts the value received from the editor into the value can be stored in the database. /// </summary> /// <param name="editorValue">The value received from the editor.</param> /// <param name="currentValue">The current value of the property</param> /// <returns>The converted value.</returns> /// <remarks> /// <para>The <paramref name="currentValue"/> is used to re-use the folder, if possible.</para> /// <para>The <paramref name="editorValue"/> is value passed in from the editor. We normally don't care what /// the editorValue.Value is set to because we are more interested in the files collection associated with it, /// however we do care about the value if we are clearing files. By default the editorValue.Value will just /// be set to the name of the file - but again, we just ignore this and deal with the file collection in /// editorValue.AdditionalData.ContainsKey("files")</para> /// <para>We only process ONE file. We understand that the current value may contain more than one file, /// and that more than one file may be uploaded, so we take care of them all, but we only store ONE file. /// Other places (FileUploadPropertyEditor...) do NOT deal with multiple files, and our logic for reusing /// folders would NOT work, etc.</para> /// </remarks> public override object FromEditor(ContentPropertyData editorValue, object currentValue) { var currentPath = currentValue as string; if (!currentPath.IsNullOrWhiteSpace()) currentPath = _mediaFileSystem.GetRelativePath(currentPath); string editorFile = null; if (editorValue.Value != null) { editorFile = editorValue.Value as string; } // ensure we have the required guids var cuid = editorValue.ContentKey; if (cuid == Guid.Empty) throw new Exception("Invalid content key."); var puid = editorValue.PropertyTypeKey; if (puid == Guid.Empty) throw new Exception("Invalid property type key."); var uploads = editorValue.Files; if (uploads == null) throw new Exception("Invalid files."); var file = uploads.Length > 0 ? uploads[0] : null; if (file == null) // not uploading a file { // if editorFile is empty then either there was nothing to begin with, // or it has been cleared and we need to remove the file - else the // value is unchanged. if (string.IsNullOrWhiteSpace(editorFile) && string.IsNullOrWhiteSpace(currentPath) == false) { _mediaFileSystem.DeleteFile(currentPath); return null; // clear } return currentValue; // unchanged } // process the file var filepath = editorFile == null ? null : ProcessFile(editorValue, file, currentPath, cuid, puid); // remove all temp files foreach (var f in uploads) File.Delete(f.TempFilePath); // remove current file if replaced if (currentPath != filepath && string.IsNullOrWhiteSpace(currentPath) == false) _mediaFileSystem.DeleteFile(currentPath); // update json and return if (editorFile == null) return null; return filepath == null ? string.Empty : _mediaFileSystem.GetUrl(filepath); } private string ProcessFile(ContentPropertyData editorValue, ContentPropertyFile file, string currentPath, Guid cuid, Guid puid) { // process the file // no file, invalid file, reject change if (UploadFileTypeValidator.IsValidFileExtension(file.FileName) is false || UploadFileTypeValidator.IsAllowedInDataTypeConfiguration(file.FileName, editorValue.DataTypeConfiguration) is false) return null; // get the filepath // in case we are using the old path scheme, try to re-use numbers (bah...) var filepath = _mediaFileSystem.GetMediaPath(file.FileName, currentPath, cuid, puid); // fs-relative path using (var filestream = File.OpenRead(file.TempFilePath)) { // TODO: Here it would make sense to do the auto-fill properties stuff but the API doesn't allow us to do that right // since we'd need to be able to return values for other properties from these methods _mediaFileSystem.AddFile(filepath, filestream, true); // must overwrite! } return filepath; } } }
d225ef2448ac15f3a3055ce2107e6e8921f0e3db
C#
limjh/DailyKata
/IncreasingOrderSearchTree/Ordering/Ordering.Test/UnitTest1.cs
3.34375
3
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Ordering.Test { [TestClass] public class UnitTest1 { //Input: [5,3,6,2,4,null,8,1,null,null,null,7,9] // 5 // / \ // 3 6 // / \ \ // 2 4 8 // / / \ // 1 7 9 // [1, 2, 3, 4, 5, 6, 7, 8, 9] [TestMethod] public void tree_to_ordered_list() { TreeNode node = new TreeNode(5); node.left = new TreeNode(3); node.left.left = new TreeNode(2); node.left.right = new TreeNode(4); node.left.left.left = new TreeNode(1); node.left.left.right = null; node.right = new TreeNode(6); node.right.left = null; node.right.right = new TreeNode(8); node.right.right.left = new TreeNode(7); node.right.right.right = new TreeNode(9); node.right.right.left.left = null; node.right.right.left.right = null; node.right.right.right.left = null; node.right.right.right.right = null; Solution solution = new Solution(); List<int> result = new List<int>(); solution.MakeOrderdList(node, ref result); List<int> expectedList = new List<int>(); expectedList.Add(1); expectedList.Add(2); expectedList.Add(3); expectedList.Add(4); expectedList.Add(5); expectedList.Add(6); expectedList.Add(7); expectedList.Add(8); expectedList.Add(9); CollectionAssert.AreEqual(expectedList, result); } } }
59dbdf0393ebc03776208002ee8c8ea30de1dc60
C#
Bulldozer777/Console_Modul_Project
/F_6_Create_Base_Type_Data.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Training_Csharp { class F_6_Create_Base_Type_Data : Modul_Struct { public static void TypeCreate(int i) { if (i == 6) { Modul_Struct Six = new F_6_Create_Base_Type_Data(); //нужно создавать объект класса наследника, после ключевого слова new Six.Operation_Info_Method_1 = Structures_Create(Code_Writer_Console(i, 3)); Six.Operation_Create_Method_1 = Code_Writer_Console(i, 1); Six.Create_Create_Method_1 = "\nРезультат работы метода \"Check:\"\n" + Check(); Six.Operation_Info_Method_1 = Code_Writer_Console(i, 2); Six.Operation_Tasks_Method_1 = Code_Writer_Console(i, 5); Six.Operation_Tasks_Method_2 = Code_Writer_Console(i, 6); Six.Operation_Examples_Method_1 = Code_Writer_Console(i, 4) + "\n" + "Результат работы тренировочного метода" + Examples(); Six.Method_Modul_Start_1(i); Generation_Operation.EndInStart(); } } public override void Create_Method(int a) //работает переопределение метода { Console.WriteLine($"{Operation_Create_Method_1}"); Console.WriteLine($"{Create_Create_Method_1}"); } public static void Check_1() { byte a = 4; byte b = (byte)(a + 70); Console.WriteLine(b); try { int k = 33; int y = 600; byte l = checked((byte)(k + y)); Console.WriteLine(l); } catch (OverflowException) { Console.WriteLine("Недоступный диапазон"); } //Ключевое слово checked проверяет не теряется ли диапазон, если теряется то выводит ошибку short b1 = (short)(a + 70);//byte/short/int - при произведении операции используется тип int //изначально в byte переменной при созданиии 1 байт а при операции типа int там уже 4 байта Console.WriteLine(b1); } public override void Tasks_Method() { Console.WriteLine($"{Operation_Tasks_Method_1}" ); Console.WriteLine("Введите 1, чтобы узнать ответы на вопросы"); int y = int.Parse(Console.ReadLine()); if (y== 1) { Console.WriteLine($"{Operation_Tasks_Method_2}"); } else { Console.WriteLine("Вы ввели не 1"); Tasks_Method(); } Console.WriteLine(); } public static string Check() { byte a = 4; byte b = (byte)(a + 70); //byte/short/int - при произведении операции используется тип int //изначально в byte переменной при созданиии 1 байт а при операции типа int там уже 4 байта //называется расширяющее перобразование string a1 = Convert.ToString(b); string a11 = ""; string a12 = ""; try { int k = 33; int y = 600; byte l = checked((byte)(k + y)); a11 = Convert.ToString(l); } catch (OverflowException) { a12 = "Недоступный диапазон"; } //Ключевое слово checked проверяет не теряется ли диапазон, если теряется то выводит ошибку"); short b1 = (short)(a + 70);//byte/short/int - при произведении операции используется тип int //изначально в byte переменной при созданиии 1 байт а при операции типа int там уже 4 байта string a2 = Convert.ToString(b1); return "\nПример явного преобразования (int) в (byte)\n" + a1 +"\n" + "Пример явного преобразования (int) в (short)\n" + a2 + "\n" +"Проверка словом \"checked\"\n" + a11 + "\n" +"Проверка не пройдена\n" + a12 + "\n"; } public static string Examples() { byte a = 89; byte b = (byte)(a + 70); //byte/short/int - при произведении операции используется тип int //изначально в byte переменной при созданиии 1 байт а при операции типа int там уже 4 байта //называется расширяющее перобразование string a1 = Convert.ToString(b); string a11 = ""; string a12 = ""; try { int k = 33; int y = 6000; byte l = checked((byte)(k + y)); a11 = Convert.ToString(l); } catch (OverflowException) { a12 = "Недоступный диапазон"; } //Ключевое слово checked проверяет не теряется ли диапазон, если теряется то выводит ошибку"); short b1 = (short)(a + 70);//byte/short/int - при произведении операции используется тип int //изначально в byte переменной при созданиии 1 байт а при операции типа int там уже 4 байта string a2 = Convert.ToString(b1); return "\n" + a1 + "\n" + a2 + "\n" + a11 + "\n" + a12 + "\n"; } public static string Task(int h, Modul_Struct Six, int a) { if (h == 1 ) { return Code_Writer_Console(6, 5); } else { Six.Method_Modul_Start_1(a); return "Вы ввели неверное число"; } } } }
75a08de5d13e35dec5ecd476936e74b968c66337
C#
allenwang162/MySql
/Program.cs
2.59375
3
using MySql.Data.MySqlClient; using System; namespace MySQL { class Program { static void Main(string[] args) { MyDataInfo mydata = new MyDataInfo(); mydata = MySQLDB.GetTestDemoData(); if (MySQLDB.InsertDataInfoWithOutDuplicate(mydata)) { Console.WriteLine("success on step : mydata.InsertDataInfoWithOutDuplicate(mydata)"); } else { Console.WriteLine("error on step : mydata.InsertDataInfoWithOutDuplicate(mydata)"); Console.WriteLine("error on mydata.ItemID = {0}", mydata.ItemID); } if (MySQLDB.DeleteDataInfoByItemID(mydata.ItemID)) { if (MySQLDB.InsertDataInfo(mydata)) { Console.WriteLine("success on step : mydb.InsertDataInfo(mydata)"); } else { Console.WriteLine("error on step : mydb.InsertDataInfo(mydata)"); Console.WriteLine("error on mydata.ItemID = {0}", mydata.ItemID); } } else { Console.WriteLine("error on step : mydb.DeleteDataInfoByItemID(mydata.ItemID)"); Console.WriteLine("error on mydata.ItemID = {0}", mydata.ItemID); } mydata = MySQLDB.GetDataInfoByItemId(mydata.ItemID); if (MySQLDB.UpDateDataInfoField(mydata.ItemID, "ItemName", "XXX")) { Console.WriteLine("success on step : mydb.UpDateDataInfoField(mydata.ItemID, filedName, filedValue)"); } mydata = MySQLDB.GetDataInfoByItemId(mydata.ItemID); } } }
4f69c87e694e2de02d6a36acec4f1d51ce1bd207
C#
ek7/stationery_shop
/shop/Forms/stationeryEditForm.cs
2.578125
3
using System; using System.Windows.Forms; namespace shop.Forms { public partial class stationeryEditForm : Form { private bool isEdit; private int pid; public stationeryEditForm() { InitializeComponent(); isEdit = false; } public stationeryEditForm(int id, string name,string price,string manufacturer,string articul, int inShop, int inStock,int id_department,int id_provider) { InitializeComponent(); isEdit = true; pid = id; this.ProductName.Text = name; this.Price.Text = price; this.Manufacturer.Text = manufacturer; this.Articul.Text = articul; this.inShop.Text = Convert.ToString(inShop); this.inStock.Text = Convert.ToString(inStock); this.idDepartment.SelectedValue = id_department; this.idProvider.SelectedValue = id_provider; } private void stationeryEditForm_Load(object sender, EventArgs e) { // TODO: данная строка кода позволяет загрузить данные в таблицу "shopdbDataSet.provider". При необходимости она может быть перемещена или удалена. this.providerTableAdapter.Fill(this.shopdbDataSet.provider); // TODO: данная строка кода позволяет загрузить данные в таблицу "shopdbDataSet.department". При необходимости она может быть перемещена или удалена. this.departmentTableAdapter.Fill(this.shopdbDataSet.department); } private void CancelButton_Click(object sender, EventArgs e) { this.Close(); } private void editStationery() { _stationeryTableAdapter.UpdateQuery(Convert.ToInt32(inShop.Text), Convert.ToInt32(inStock.Text),Convert.ToInt32(idProvider.SelectedValue), Convert.ToInt32(idDepartment.SelectedValue),ProductName.Text,Price.Text, Manufacturer.Text,Articul.Text,pid); } private void addStationery() { _stationeryTableAdapter.InsertQuery(Convert.ToInt32(inShop.Text), Convert.ToInt32(inStock.Text),Convert.ToInt32(idProvider.SelectedValue), Convert.ToInt32(idDepartment.SelectedValue),ProductName.Text,Price.Text, Manufacturer.Text,Articul.Text); } private void OkButton_Click(object sender, EventArgs e) { try { if (isEdit) { editStationery(); MessageBox.Show("Запись обновлена"); } else { addStationery(); MessageBox.Show("Запись добавлена"); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); return; } this.Close(); } } }
1c40e20fd48fb5f5205cd71be664660d4defc8ef
C#
sharanya204/GDDProj2
/Proj2a/Assets/Scripts/PlayerController.cs
2.546875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PlayerController : MonoBehaviour { // Change Notes 2/24/20: I added the condition "&& canJump()" to the move right if statement (Line 64) // to deal with the weird physics where you can move while in the air. This means that the player // cannot move right if they are in the air. To deal with not being able to move right while jumping, // I added a jumpforceX variable to the jump code (Line 80) to give the player horizontal velocity // to make a jump to the next platform. - MB // Change Notes 2/25/20: I added a call method in the Point Functions region to show the points // the player has on the screen. Specifically, I added Line 34 and Line 109. - MB #region movement_variables public float movespeed; public float jumpforceY; public float jumpforceX; float x_input; float y_input; private bool shouldJump; //private bool canJump; Vector2 currDirection; public bool feetContact; #endregion #region points_variables public float points; public float globPoints; float currPoints; public Slider pointsSlider; [SerializeField] Text pointUIText; #endregion #region physics_components Rigidbody2D playerRB; #endregion #region Unity_functions //called once on creation private void Awake() { playerRB = GetComponent<Rigidbody2D>(); } public void Start() { currPoints = GlobalControl.Instance.points; } //called every frame private void Update() { //access input values x_input = Input.GetAxisRaw("Horizontal"); y_input = Input.GetAxisRaw("Vertical"); Move(); } #endregion #region movement_functions //moves or jumps player based on keyboard input and movespeed private void Move() { //if player is pressing right key if ((x_input > 0) && canJump()) { Debug.Log("right button pressed"); playerRB.velocity = Vector2.right * movespeed; } //if player is pressing spacebar else if (Input.GetKeyDown(KeyCode.Space) && canJump()) { Debug.Log("space bar pressed"); playerRB.velocity = new Vector2(playerRB.velocity.x, 0); //playerRB.AddForce(Vector2.up * jumpforce); playerRB.AddForce(new Vector2(jumpforceX, jumpforceY)); } } bool canJump() { return feetContact; } #endregion #region points_functions //gain points if hitting objects public void GainPoints(float value) { //increment points currPoints += value; Debug.Log("Points is now " + currPoints.ToString()); pointUIText.text = ("Points: " + currPoints.ToString()); } public void SavePlayerState() { GlobalControl.Instance.points = currPoints; } //Destroy player + end scene public void Die() { //destroy gameobject Destroy(this.gameObject); //trigger anything to end game - find game manager and lose game GameObject gm = GameObject.FindWithTag("GameController"); Debug.Log("Died"); gm.GetComponent<GameManager>().LoseGame(); } #endregion }
27fb3af546118dd8edc747cb5fedc097ff136aad
C#
eopoku61057/Data-Structures-Array-Strings
/TREES-AND-GRAPHS-LEETCODE/Alien-Dictionary.cs
3.515625
4
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace DataStructure { public class NumMatrix { public string alienOrder(string[] words) { int[] indegree = new int[26]; Dictionary<char, List<char>> g = new Dictionary<char, List<char>>(); BuildGraph(g, words, indegree); return BFS(g, indegree); } private string BFS(Dictionary<char, List<char>> g, int[] indegree) { StringBuilder sb = new StringBuilder(); int totalChars = g.Count(); Queue<char> queue = new Queue<char>(); foreach (char c in g.Keys) { if (indegree[c - 'a'] == 0) { sb.Append(c); queue.Enqueue(c); } } while (queue.Count > 0) { char curr = queue.Peek(); if (g.GetValueOrDefault(curr) != null || g.GetValueOrDefault(curr).Count == 0) continue; foreach (char neighbor in g.GetValueOrDefault(curr)) { indegree[neighbor - 'a']--; if (indegree[neighbor - 'a'] == 0) { queue.Enqueue(neighbor); sb.Append(neighbor); } } } return sb.Length == totalChars ? sb.ToString() : ""; } private void BuildGraph(Dictionary<char, List<char>> g, string[] words, int[] indegree) { foreach (var word in words) { foreach (var c in word) { if (!g.ContainsKey(c)) { g.Add(c, new List<char>()); } } } for (int i = 1; i < words.Length; i++) { string first = words[i - 1]; string second = words[i]; int len = Math.Min(first.Length, second.Length); for (int j = 0; j < len; j++) { if(first[j] != second[j]) { char out1 = first[j]; char in1 = second[j]; if (!g.GetValueOrDefault(out1).Contains(in1)) { g.GetValueOrDefault(out1).Add(in1); indegree[in1 - 'a']++; } break; } } } } } }
83d51968d754212270427533d0dd22278405176e
C#
DenisOliveira1/course_csharp_from_the_beginning
/1 - Basics/6 - Loops/6 - Loops/Program.cs
4.0625
4
using System; namespace _6___Loops { class Program { static void Main(string[] args) { int[] array = { 12, 54, 23, 78 }; for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } Console.WriteLine("----------------"); foreach (int item in array) { Console.WriteLine(item); } Console.WriteLine("----------------"); int num = 0; while (num < 10) { if (num % 2 == 0) { Console.WriteLine(num + " é par!"); } num++; } Console.WriteLine("----------------"); Console.WriteLine("Break e Continue"); foreach (int item in array) { if (item == 23) { break; // Encerra o for } else if (item == 54) { continue; // Vai paraa próxima interação do for } Console.WriteLine(item); } } } }
55f9e1361fb1974eeb75265e5f51297ee18f06c5
C#
VasilVP/Software-University-Courses
/Level 2/Object-Oriented-Programming-January2015/04.FunctionalProgramming/15.LinqToExcel/LinqToExcel.cs
3.09375
3
using ExcelLibrary.SpreadSheet; using QiHe.CodeLib; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; class LinqToExcel { static void Main() { StreamReader reader = new StreamReader("../../Resources/Students-data.txt"); List<Student> studentsList = new List<Student>(); Workbook workbook = new Workbook(); Worksheet worksheet = new Worksheet("Students-Data"); string[] firstRow = reader.ReadLine().Split('\t'); for (int i = 0; i < firstRow.Length; i++) { worksheet.Cells[0, i] = new Cell(firstRow[i]); worksheet.Cells.ColumnWidth[0, (ushort)i] = 5000; } worksheet.Cells[0, 12] = new Cell("Course result"); worksheet.Cells.ColumnWidth[0, 12] = 5000; while (!reader.EndOfStream) { string[] input = reader.ReadLine().Split('\t'); int id = int.Parse(input[0]); string firstName = input[1]; string lastName = input[2]; string email = input[3]; string gender = input[4]; string type = input[5]; int examResult = int.Parse(input[6]); int homeworksSent = int.Parse(input[7]); int homeworksEvaluated = int.Parse(input[8]); double teamworkScore = double.Parse(input[9]); int attendancesCound = int.Parse(input[10]); double bonus = double.Parse(input[11]); studentsList.Add(new Student(id, firstName, lastName, email, gender, type, examResult, homeworksSent, homeworksEvaluated, teamworkScore, attendancesCound, bonus)); } var sortedOnsiteStudents = studentsList .Select(s => s) .Where(s => s.Type == "Online") .OrderByDescending(s => s.CalculateResult()); int rowCount = 1; foreach (var student in sortedOnsiteStudents) { worksheet.Cells[rowCount, 0] = new Cell(student.ID); worksheet.Cells[rowCount, 1] = new Cell(student.FirstName); worksheet.Cells[rowCount, 2] = new Cell(student.LastName); worksheet.Cells[rowCount, 3] = new Cell(student.Email); worksheet.Cells[rowCount, 4] = new Cell(student.Gender); worksheet.Cells[rowCount, 5] = new Cell(student.Type); worksheet.Cells[rowCount, 6] = new Cell(student.ExamResult); worksheet.Cells[rowCount, 7] = new Cell(student.HomeworksSent); worksheet.Cells[rowCount, 8] = new Cell(student.HomeworksEvaluated); worksheet.Cells[rowCount, 9] = new Cell(student.TeamworkScore); worksheet.Cells[rowCount, 10] = new Cell(student.AttendancesCount); worksheet.Cells[rowCount, 11] = new Cell(student.Bonus); worksheet.Cells[rowCount, 12] = new Cell(student.CalculateResult()); rowCount++; } string xlsFile = "../../Resources/students-data.xls"; workbook.Worksheets.Add(worksheet); workbook.Save(xlsFile); } }
617c5a46676f6c8fa5e2890af49fbf67c969c5f3
C#
caesuric/familiar-quest
/FamiliarQuestMainGame/Assets/Scripts/Characters/Attributes/CharacterAttributeInstance.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class CharacterAttributeInstance { public Character character = null; public event EventHandler ValueChanged; private float _baseValue = 0; public float BaseValue { get => _baseValue; set { _baseValue = value; TotalValue = _baseValue + _itemValue + _abilityValue + _derivedValue + _buffValue; ValueUpdated(); } } private float _itemValue = 0; public float ItemValue { get => _itemValue; set { _itemValue = value; TotalValue = _baseValue + _itemValue + _abilityValue + _derivedValue + _buffValue; ValueUpdated(); } } private float _abilityValue = 0; public float AbilityValue { get => _abilityValue; set { _abilityValue = value; TotalValue = _baseValue + _itemValue + _abilityValue + _derivedValue + _buffValue; ValueUpdated(); } } private float _buffValue = 0; public float BuffValue { get => _buffValue; set { _buffValue = value; TotalValue = _baseValue + _itemValue + _abilityValue + _derivedValue + _buffValue; ValueUpdated(); } } private float _derivedValue = 0; public float DerivedValue { get => _derivedValue; private set { _derivedValue = value; TotalValue = _baseValue + _itemValue + _abilityValue + _derivedValue + _buffValue; ValueUpdated(); } } public float TotalValue { get; private set; } = 0; public string name = ""; public static void CreateAllAttributesForCharacter(Character character) { foreach (var kvp in CharacterAttribute.attributes) { var temp = new CharacterAttributeInstance(character, kvp.Key); } } public CharacterAttributeInstance(Character character, string name) { this.character = character; this.name = name; CharacterAttribute.attributes[name].instances[character] = this; if (CharacterAttribute.attributes[name].isSecondary) { foreach (var baseStat in CharacterAttribute.attributes[name].basedOn) { CharacterAttribute.attributes[baseStat].instances[character].ValueChanged += UpdateFromBaseStat; } } } private void UpdateFromBaseStat(object sender, EventArgs e) { var senderObj = (CharacterAttributeInstance)sender; float derivedValueTotal = 0; foreach (var kvp in CharacterAttribute.attributes) { if (CharacterAttribute.attributes[name].basedOn.Contains(kvp.Key)) { derivedValueTotal += kvp.Value.instances[character].TotalValue; } } DerivedValue = CalculateDerivedValue(derivedValueTotal); } private float CalculateDerivedValue(float baseValue) { int level = SecondaryStatUtility.GetLevel(character); float percentage = SecondaryStatUtility.GetPercent((int)baseValue, level); float minimum = CharacterAttribute.attributes[name].GetMinimum(level); float average = CharacterAttribute.attributes[name].GetAverage(level); float maximum = CharacterAttribute.attributes[name].GetMaximum(level); if (percentage < 0.5) return ((average - minimum) * (percentage * 2) + minimum); else if (percentage == 0.5) return average; else return ((maximum - average) * ((percentage - 0.5f) * 2) + average); } protected void ValueUpdated() { var e = new EventArgs(); ValueChanged?.Invoke(this, e); } }
8f9913d5f6d8118142c5b056e236e06be1a2e723
C#
JakedStevens/FancyCalculator
/CalculatorCore/Calculator.cs
3.265625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CalculatorCore { public class Calculator { public EvaluationResult Evaluate(Expression expression, decimal prevResult) { //return new EvaluationResult { ErrorMessage = $"\u001b[31mYour entry was invalid, two numbers with an operator inbetween them are required ex: 1 + 1\u001b[0m" }; //if () { } if ((decimal.TryParse(expression.FirstValue, out decimal firstOperand) == false) && expression.ContinueLastOperation == false) { return new EvaluationResult { ErrorMessage = $"\u001b[31mThe first number, '{expression.FirstValue}', was not a valid number.\u001b[0m" }; } if (decimal.TryParse(expression.SecondValue, out decimal secondOperand) == false) { return new EvaluationResult { ErrorMessage = $"\u001b[31mThe second number, '{expression.SecondValue}', was not a valid number.\u001b[0m" }; } expression.FirstNumber = firstOperand; expression.SecondNumber = secondOperand; decimal result; switch (expression.Operator) { case "+": result = expression.ContinueLastOperation ? prevResult + secondOperand : firstOperand + secondOperand; break; case "-": result = expression.ContinueLastOperation ? prevResult - secondOperand : firstOperand - secondOperand; break; case "*": result = expression.ContinueLastOperation ? prevResult * secondOperand : firstOperand * secondOperand; break; case "/": result = expression.ContinueLastOperation ? prevResult / secondOperand : firstOperand / secondOperand; break; default: return new EvaluationResult { ErrorMessage = $"\u001b[31m'{expression.Operator}' is not a valid operator please use of of these: '+', '-', '*', '/'\u001b[0m" }; } return new EvaluationResult { Result = result, Expression = expression, PreviousResult = prevResult }; } } }
8c9a3bc9a3f631eb20e01c0c027c4205af8b170d
C#
LiteObject/TestIdentityServer
/Demo.Api/Controllers/WeatherForecastController.cs
2.640625
3
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Identity.Web.Resource; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Demo.Api.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; static readonly string[] scopeRequiredByApi = new string[] { "demoapi.weatherforecast.read" }; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] [Authorize("demoapi.weatherforecast.read")] // [RequiredScope(scopeRequiredByApi)] public IEnumerable<WeatherForecast> Get() { // HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); var claims = from c in User.Claims select new { c.Type, c.Value }; foreach (var c in claims) { Console.WriteLine($"{c.Type}, {c.Value}"); /* * nbf - stands for not before. * exp - stands for expiry. * iss - stands for issuer. * aud - stands for audience. The resource name in which a client is needed to access. * client_id - the client id of the client application requesting the token. * scope - the scope in which a client is allowed to access. */ } var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } [HttpPost] [Authorize("demoapi.weatherforecast.write")] public async Task<IActionResult> Post(WeatherForecast payload) { await Task.Delay(2000); Console.WriteLine($"Created:\n{System.Text.Json.JsonSerializer.Serialize(payload)}"); return Created("/", payload); } } }
95de22403fa10714fa0a5caa45853265d8f50830
C#
Lelikeks/Toto
/IdiotKuponsProvider.cs
2.859375
3
using Newtonsoft.Json; using System.IO; using System.Net; namespace Toto { public class IdiotKuponsProvider { private int _drawingId; public IdiotKuponsProvider(int drawingId) { _drawingId = drawingId; } public IdiotsKupon[] GetKupons() { var data = GetData(); // var data = GetDataFromFile(); var json = JsonConvert.DeserializeObject<dynamic>(data); var res = new IdiotsKupon[json.d.Items.Count]; var i = 0; foreach (var item in json.d.Items) { res[i] = new IdiotsKupon { Cells = GetCellFromString(item.Code.Value), Count = (int)item.Count.Value }; i++; } return res; } short[] GetCellFromString(string code) { var res = new short[3]; for (int i = 0; i < 15; i++) { var index = -1; switch (code[i]) { case '1': index = 0; break; case 'X': index = 1; break; case '2': index = 2; break; } res[index] |= (short)(1 << i); } return res; } string GetDataFromFile() { return File.ReadAllText(@"D:\000\betres.txt"); } string GetData() { var req = WebRequest.CreateHttp(@"http://old.toto-info.co/DataService.svc/GetStakeDict"); req.Method = "POST"; req.ContentType = "application/json; charset=utf-8"; using (var sw = new StreamWriter(req.GetRequestStream())) { sw.Write("{\"options\":{\"StartFrom\":0,\"Count\":200,\"DrawingId\":" + _drawingId + "}}"); } var resp = req.GetResponse(); using (var sr = new StreamReader(resp.GetResponseStream())) { var res = sr.ReadToEnd(); return res; } } } }
cb048611335b2490548e8c0ba75cbb1c4d63a15a
C#
Akema8/Lab4EnterSys
/Lab4/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; using System.Management; using System.IO; namespace Lab4 { public partial class Form1 : Form { string Path; string Path2; shifr gr; List<string> Lst; List<string> Lst2; public Form1() { InitializeComponent(); Path = "OS1"; Path2 = "OS2"; gr = new shifr(); Lst = new List<string>(); Lst2 = new List<string>(); if (!System.IO.File.Exists(Path)) File.Create(Path); if (!System.IO.File.Exists(Path2)) File.Create(Path2); if (System.IO.File.Exists(Path)) { ReadFromFile(Path, Lst); if (Lst[0] != "true") InFil(Path); } Lst = new List<string>(); } private List<string> InfoFromPK(string WIN32_Class, string ClassItemField) { List<string> result = new List<string>(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM " + WIN32_Class); try { foreach (ManagementObject obj in searcher.Get()) result.Add(gr.GetShifr(obj[ClassItemField].ToString(), "rita")); } catch (Exception ex) { MessageBox.Show(ex.Message); } return result; } private void OutRes(string info, List<string> result, string path) { FileStream fl = new FileStream(path, FileMode.Append); //открываем поток на добавление StreamWriter sw = new StreamWriter(fl); //поток для записи if (info.Length > 0) sw.WriteLine(gr.GetShifr(info, "rita")); if (result.Count > 0) { for (int i = 0; i < result.Count; ++i) sw.WriteLine(result[i]); } sw.Close(); fl.Close(); } private void InFil(string path) { string[] str = { "true" }; File.WriteAllLines(path, str); OutRes("CPU:", InfoFromPK("Win32_Processor", "Name"), path); //процессор OutRes("Manufacturer:", InfoFromPK("Win32_Processor", "Manufacturer"), path); //производитель OutRes("Description:", InfoFromPK("Win32_Processor", "Description"), path); //описание OutRes("Videocard:", InfoFromPK("Win32_VideoController", "Name"), path); //видеокарта OutRes("VP:", InfoFromPK("Win32_VideoController", "VideoProcessor"), path); //видеопроцессор OutRes("Memory size:", InfoFromPK("Win32_VideoController", "AdapterRAM"), path); //объем памяти в байтах OutRes("HDD:", InfoFromPK("Win32_DiskDrive", "Caption"), path); //ЖД OutRes("Size:", InfoFromPK("Win32_DiskDrive", "Size"), path); //объем в байтах } private void ReadFromFile(string path, List<string> lst) { FileStream opfl = new FileStream(path, FileMode.Open); StreamReader rdfl = new StreamReader(opfl); int i = 0; while (i < 18) { lst.Add(rdfl.ReadLine()); i++; } rdfl.Close(); opfl.Close(); } private int Sravn(List<string> lst1, List<string> lst2) { ReadFromFile(Path, lst1); ReadFromFile(Path2, lst2); int count = 0; for (int i = 0; i < lst1.Count; i++) if (lst1[i] != lst2[i]) count++; return count; } int count = 0; private void button1_Click(object sender, EventArgs e) { if (!System.IO.File.Exists(Path2)) File.Create(Path2); InFil(Path2); if ((Sravn(Lst, Lst2) != 0)) { button1.BackColor = Color.Red; if (count == 0) button1.Enabled = false; button1.Visible = false; label1.Visible = true; } else { Form2 fr2 = new Form2(); fr2.Show(); // button1.Enabled = false; button1.BackColor = Color.Blue; // this.Hide(); //скрывает элемент от пользователя } count++; } } }
f0d476052d36d945cb27958f63c6f8535ca2d841
C#
bashiransari/ConfigUtil
/BAS.ConfigUtil/ConfigWriter.cs
2.609375
3
using System; using System.Diagnostics; using System.Reflection; using System.Configuration; using System.Drawing; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using BAS.ConfigUtil.ConfigSource; namespace BAS.ConfigUtil { public class ConfigWriter { public string Prefix { get; set; } public ConfigWriter(string prefix) { this.Prefix = prefix; } public ConfigWriter() : this("") { } public bool WriteConfig(object theobject, IConfigSource configSource, bool useDefaultValues = false) { Type type = theobject.GetType(); foreach (Tuple<PropertyInfo, ConfigProp> items in Helper.GetConfigProps(theobject)) { var prop = items.Item1; var configurationprop = items.Item2; string configName = configurationprop.Name; if (string.IsNullOrEmpty(configurationprop.Name)) { configName = prop.Name; } object propValue = null; if (useDefaultValues) propValue = configurationprop.DefaultValue ?? ""; else propValue = prop.GetValue(theobject, new object[] { }) ?? ""; string propStrValue = ""; try { propValue = StringParser.ToString(propValue, prop.PropertyType); } catch (Exception ex) { throw new InvalidOperationException(String.Format("Cannot convert value for \"{0}\" property to string.", prop.Name), ex); } configSource.SetValue(this.Prefix + "." + configName, propStrValue); } return true; } public bool WriteDefaultConfig(object theobject, IConfigSource configSource) { return WriteConfig(theobject, configSource, true); } public bool WriteConfig(object theobject, bool useDefaultValues = false) { var appSettingSource = ConfigSourceFactory.GetDefaultSource(); WriteConfig(theobject, appSettingSource, useDefaultValues); appSettingSource.FlushValues(); return true; } public bool WriteDefaultConfig(object theobject) { return WriteConfig(theobject, true); } public string GetConfigString(object theobject, IConfigSource configSource, bool useDefaultValues = false) { Type type = theobject.GetType(); WriteConfig(theobject, configSource, useDefaultValues); return configSource.GetConfigString(); } } }
31add4cec40c8f5ed88b5143b8f46f278352fd62
C#
shubhnake287/.Net-Assignments
/Day4-Assign-3/Refandvaluetypesin.netcode/Program.cs
3.546875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Refandvaluetypesin.netcode { class Program { static void Main(string[] args) { int i; int j; Init(out i, out j);//with using init out is just changes made in code reflect in original code.. Swap(ref i, ref j);// they just does not required incial value... Console.WriteLine(i); Console.WriteLine(j); Console.ReadLine(); } static void Swap(ref int i, ref int j)//in this function the value swap.. { int temp = i; i = j; j = temp; } static void Init(out int i, out int j) { i = 100; j = 200; } } }
0ffb08106d157aba54fdb8c83ea79a268879f09b
C#
brikibsw/EdukacijaXamarin
/Adresar/Adresar/ViewModels/CityPageViewModel.cs
2.78125
3
using Adresar.Data; using System.Windows.Input; using Xamarin.Forms; namespace Adresar.ViewModels { public class CityPageViewModel : BaseViewModel { private readonly AdresarDatabase database; public CityPageViewModel(City grad) { database = new AdresarDatabase(); //if(grad == null) //{ // City = new City(); //} //else //{ // City = grad; //} SaveCommand = new Command(Save, () => City != null); SaveCommand.CanExecuteChanged += SaveCommand_CanExecuteChanged; DeleteCommand = new Command(Delete); } private void SaveCommand_CanExecuteChanged(object sender, System.EventArgs e) { var p = e; } public ICommand SaveCommand { get; private set; } public async void Save() { if(City.Name == null || City.Name.Length == 0 || City.ZipCode == 0 ) { await DisplayAlert("Upozorenje", "Vrijednosti naziva i poštanskog broja moraju biti unešeni!", "OK"); } else { var postoji = database.Cities.Exists(a => a.Name.ToUpper() == City.Name.ToUpper() && a.ZipCode == City.ZipCode); if( postoji ) { await DisplayAlert("Upozorenje", "Grad sa istim imenom i poštanskim brojem već postoji!", "OK"); } else { // spremimo City ako je novi if (City.Id == 0) { database.Cities.Insert(City); } // ili ažuriramo ako je postojeci else { database.Cities.Update(City); } // vratimo se na popis gradova CityList await Navigation.PopAsync(); } } } public ICommand DeleteCommand { get; private set; } private void Delete() { City = new City(); //// pitati korisnika da li je siguran da zeli obrsati grad //var result = await DisplayAlert("Brisanje", // "Jeste li ste sigurni da želite obrisati grad?", // "Da", // "Ne"); //if( result ) //{ // // ako je postojeci grad obrisati ga iz baze // if (City.Id != 0) // { // database.Cities.Delete( (a) => a.Id == City.Id ); // } // // vratimo se na popis gradova CityList // await Navigation.PopAsync(); //} } public int MyProperty { get; set; } private City _city; public City City { get { return _city; } set { _city = value; OnPropertyChanged(); ((Command)SaveCommand).ChangeCanExecute(); } } } }
14b1d20557ecfc16e8ccec4d530f01f05ab93f84
C#
HFisher1212/halfisher1212
/FisherHal/Lec11Lab/Program.cs
3.078125
3
/****************************************************************** * @author Hal Fisher * @class CS155 * @project lec11lab * @date 11.21.2016 * **************************************************************** * Alogrithm * 0. START PROGRAM * 1. OPEN streamreader for boy file * 2. WHILE readline not null * 3. SET stream field 0 to boy dictionary array key * 4. SET object field to stream field 1 * 5. SET object field to count * 6. INCREMENT counter * 7. END WHILE * 8. OPEN streamreader for girl file * 9. WHILE readline not null * 10. SET stream field 0 to girl dictionary array key * 11. SET object field to stream field 1 * 12. SET object field to count * 13. INCREMENT count * 14. END WHILE * 15. DISPLAY request for search name * 16. SET searchname to entry * 17. IF boy dictionary array contains searchname * 18. DISPLAY key, object rank, object count * 19. ELSE * 20. DISPLAY key not found * 21. IF girl dictionary array contains searchname * 22. DISPLAY key, object rank, object count * 23. ELSE * 24. DISPLAY key not found * 00. END PROGRAM */ ///////////////////////////////// START PROGRAM ///////////////////// // IMPORT SECTION using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lec11Lab { class Program { // DECLARATION AND INSTANTIATION SECTION private static Names boyObject; private static Names girlObject; private static Dictionary<string, dynamic> popularBoyNameRank = new Dictionary<string, dynamic>(); private static Dictionary<string, dynamic> popularGirlNameRank = new Dictionary<string, dynamic>(); private static string searchName; private static string fileName = "c://Users/Work Laptop/Desktop/"; // MAIN SECTION static void Main(string[] args) { CreateBoyDictionaryArray(); CreateGirlDictionaryArray(); EnterName(); //GetSearchName(); //SearchArrays(); Console.ReadKey(); } public static void EnterName() { bool quit = false; while(!quit) { GetSearchName(); if(searchName.Equals("q")) { quit = true; } else { SearchArrays(); } } } // GETSEARCHNAME METHOD // Precondition- n/a // Postcondition- searchName field contains user entry public static void GetSearchName() { Console.Write("\n Enter Name For Search: "); searchName = Console.ReadLine(); } // SEARCHARRAYS METHODS // Precondition- boy and girl dictionary arrays are available // Postcondition- array unchanged public static void SearchArrays() { if (popularBoyNameRank.ContainsKey(searchName)) { Names value = popularBoyNameRank[searchName]; Console.Write(" " + searchName + " is ranked " + value.Rank + " amoung boys with " + value.Count + " namings."); } else { Console.Write(" " + searchName + " is not ranked among the top 1000 boy names."); } if (popularGirlNameRank.ContainsKey(searchName)) { Names value = popularGirlNameRank[searchName]; Console.Write("\n " + searchName + " is ranked " + value.Rank + " amoung girls with " + value.Count + " namings."); } else { Console.Write("\n " + searchName + " is not ranked among the top 1000 girl names."); } } // CREATEBOYDICTIONARRY METHOD // Precondition- boy dictionary array is instantiated // Postcondition- boy dictionary array is filled with boy file public static void CreateBoyDictionaryArray() { char[] delimiterChars = { ' ' }; string[] arrayFields; int count = 1; using (StreamReader s = new StreamReader(fileName + "boynames.txt")) { string line = null; while ((line = s.ReadLine()) != null) { arrayFields = line.Split(delimiterChars); boyObject = new BoyNames(Convert.ToInt32(arrayFields[1]), count); popularBoyNameRank.Add(arrayFields[0], boyObject); count++; } } } // CREATEGIRLDICTIONARRY METHOD // Precondition- girl dictionary array is instantiated // Postcondition- girl dictionary array is filled with boy file public static void CreateGirlDictionaryArray() { char[] delimiterChars = { ' ' }; string[] arrayFields; int count = 1; using (StreamReader s = new StreamReader(fileName + "girlnames.txt")) { string line = null; while ((line = s.ReadLine()) != null) { arrayFields = line.Split(delimiterChars); girlObject = new GirlNames(Convert.ToInt32(arrayFields[1]), count); popularGirlNameRank.Add(arrayFields[0], girlObject); count++; } } } } }
b6e88122f2eaab80e8e16734f41fd814a92dcb3d
C#
steville1/HotelsRatesAPI5.0
/HotelsRatesAPI5.0.Repositories/common/HotelsRatesRepository.cs
2.703125
3
using HotelsRatesAPI5._0.Data.Interfaces; using HotelsRatesAPI5._0.Data.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HotelsRatesAPI5._0.Repositories.common { public class HotelsRatesRepository : IHotelsRates { IConfiguration _configuration { get; } private readonly ILogger<HotelsRatesRepository> _logger; public HotelsRatesRepository(IConfiguration configuration, ILogger<HotelsRatesRepository> logger) { _configuration = configuration; _logger = logger; } public HotelsRatesModel GetHotelRates(int HotelId, DateTime ArrivalDate) { try { //get the Json filepath string filepath = _configuration.GetSection("ReadFiles").GetSection("Path").Value; string file = Path.Combine(filepath); //Read all the text string Json = System.IO.File.ReadAllText(file); //deserialize JSON from file var hotels = JsonConvert.DeserializeObject<List<HotelsRatesModel>>(Json); //Filtered the result from the Json Data var filterHotelResult = hotels.Where(a => a.hotel.hotelID == HotelId).FirstOrDefault(); if (filterHotelResult == null) { return new HotelsRatesModel { responseMessage = "The Hotel Id Is Not Found" }; } var filterHotelRateResult = filterHotelResult.hotelRates.Where(a => a.targetDay.Date == ArrivalDate).ToList(); if (filterHotelRateResult.Count != 0) { return new HotelsRatesModel { hotelRates = filterHotelRateResult, responseMessage = "Success" }; } else { return new HotelsRatesModel { responseMessage = "There Is No Hotel Rate Found" }; } } catch (Exception ex) { _logger.LogInformation(ex.InnerException.ToString()); return null; } } } }
0f653ab7289d0346b86ca63fa8cd7ad7e4749fda
C#
pedroyan/MbOS
/MbOS/FileDomain/DataStructures/Instructions/FileInstruction.cs
2.78125
3
using System; using System.Collections.Generic; using System.Text; namespace MbOS.FileDomain.DataStructures.Instructions { public abstract class FileInstruction { protected FileInstruction(int pid, string fileName) { PID = pid; FileName = fileName; } /// <summary> /// ID do processo realizando a operação /// </summary> public int PID { get; set; } /// <summary> /// Nome do arquivo a ser operado /// </summary> public string FileName { get; set; } /// <summary> /// Executa a instrução /// </summary> /// <param name="hdd">HDD que será executada a instrução</param> /// <param name="operationNumber">Número da instrução</param> public abstract void Execute(HardDrive hdd, int operationNumber); } }
bba164d0a2636ef38f587035e9633567bbc2960f
C#
AhmadOthmanAdi/ZooApplication-For-Class
/Zoo/Form1.cs
2.75
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Zoo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Button1_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Bild *.jpg;|*.jpg"; ofd.Title = "Bildwahl"; string dateiname = String.Empty; if (ofd.ShowDialog() == DialogResult.OK) { dateiname = ofd.FileName; string newPath = "Bilder\\" + textBox1.Text + ".jpg"; int i = 0; while (File.Exists(newPath)) { newPath = "Bilder\\" + textBox1.Text + i.ToString() + ".jpg"; i++; } label1.Text = newPath; File.Copy(dateiname, newPath); // oder: File.Move() pictureBox1.Image = Image.FromFile(newPath); } } private void PictureBox1_DragDrop(object sender, DragEventArgs e) { string[] fileList = (string[])e.Data.GetData(DataFormats.FileDrop, false); string[] fnarr = fileList[0].Split('\\'); if (fnarr[fnarr.Length - 1].ToLower().Contains(".jpg")) { string dateiname = fileList[0]; string newPath = "Bilder\\" + textBox1.Text + ".jpg"; int i = 0; while (File.Exists(newPath)) { newPath = "Bilder\\" + textBox1.Text + i.ToString() + ".jpg"; i++; } label1.Text = newPath; File.Copy(dateiname, newPath); // oder: File.Move() pictureBox1.Image = Image.FromFile(newPath); } } private void PictureBox1_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; } private void Form1_Load(object sender, EventArgs e) { } } }
34e5b28f509daded5417bd7c849fafed87b50dac
C#
cat-begemot/IT_Data
/IT_Data/Models/Order.cs
3.0625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace IT_Data.Models { public class Order { public DateTime OrderDate { get; set; } public String Company { get; set; } public String City { get; set; } public String Country { get; set; } public String Manager { get; set; } public Int32 Qty { get; set; } public Decimal Amount { get; set; } } public class Orders { // Flags point which columns were selected public Boolean FlagOrderDate { get; set; } = false; public Boolean FlagCompany { get; set; } = false; public Boolean FlagCity { get; set; } = false; public Boolean FlagCountry { get; set; } = false; public Boolean FlagManager { get; set; } = false; // Array with columns sequence in accordance to flags private Int32[] columnSequence = new Int32[7]; private List<Order> orders = new List<Order>(); /// <summary> /// Instances count /// </summary> public Int64 Length { get => orders.Count; } /// <summary> /// All instances of Orders /// </summary> /// <returns></returns> public List<Order> GetOrders() => orders; public List<Order> AllOrders { get => orders; } /// <summary> /// Returns TRUE if at least one flag was choosen /// </summary> /// <returns></returns> public Boolean IsAnyFlagSelected() { return FlagOrderDate || FlagCompany || FlagCity || FlagCountry || FlagManager; } /// <summary> /// Add new instance to Orders /// </summary> public void AddOrder(DateTime orderdate, String company, String city, String country, String manager, Int32 qty, decimal amount) { orders.Add(new Order() { OrderDate = orderdate, Company = company, City = city, Country = country, Manager = manager, Qty = qty, Amount = amount }); } /// <summary> /// Fill instance by response from DB according flags. /// If flag is FALSE, appropriate property will be default value /// </summary> /// <param name="dataReader">Values is returned by ExecuteReader method</param> public void FeelOrders(SqlDataReader dataReader) { orders = new List<Order>(); while (dataReader.Read()) { Int32 lastSequence; Boolean clearedFlags = !IsAnyFlagSelected(); if (IsAnyFlagSelected()) { lastSequence = -1; if (FlagOrderDate) columnSequence[0] = ++lastSequence; if (FlagCompany) columnSequence[1] = ++lastSequence; if (FlagCity) columnSequence[2] = ++lastSequence; if (FlagCountry) columnSequence[3] = ++lastSequence; if (FlagManager) columnSequence[4] = ++lastSequence; columnSequence[5] = ++lastSequence; columnSequence[6] = ++lastSequence; } else { lastSequence = 0; for (; lastSequence < 7; lastSequence++) columnSequence[lastSequence] = lastSequence; } this.AddOrder( FlagOrderDate || clearedFlags ? dataReader.GetDateTime(columnSequence[0]) : default(DateTime), FlagCompany || clearedFlags ? dataReader.GetString(columnSequence[1]) : default(string), FlagCity || clearedFlags ? dataReader.GetString(columnSequence[2]) : default(string), FlagCountry || clearedFlags ? dataReader.GetString(columnSequence[3]) : default(string), FlagManager || clearedFlags ? dataReader.GetString(columnSequence[4]) : default(string), dataReader.GetInt32(columnSequence[5]), dataReader.GetDecimal(columnSequence[6]) ); } } /// <summary> /// Return SQL query of report /// </summary> /// <returns></returns> public String GetSQLReportString() { // Check filters and create columns list StringBuilder columns = new StringBuilder(50); void BuildColList(String columnName) { if (columns.Length != 0) columns.Append(", "); columns.Append(columnName); } if (FlagOrderDate) BuildColList("orderdate"); if (FlagCompany) BuildColList("company"); if (FlagCity) BuildColList("city"); if (FlagCountry) BuildColList("country"); if (FlagManager) BuildColList("manager"); StringBuilder sql=new StringBuilder(500); if (IsAnyFlagSelected()) { sql.Append($"SELECT {columns}, SUM(qty), SUM(amount)").AppendLine(); sql.Append($"FROM dbo.Orders").AppendLine(); sql.Append($"GROUP BY {columns}").AppendLine(); sql.Append($"ORDER BY {columns};"); } else sql.Append("SELECT * FROM dbo.Orders;"); return sql.ToString(); } /// <summary> /// Reset all flags to False /// </summary> public void ResetFlags() { FlagOrderDate = false; FlagCompany = false; FlagCity = false; FlagCountry = false; FlagManager = false; } } }
c05922caf86c36366158f249403f5ed5736dcd0e
C#
Vadim4016/PacMan
/Assets/Scripts/PacmanCollision.cs
2.703125
3
using System; using UnityEngine; using UnityEngine.UI; namespace Assets.Scripts { public class PacmanCollision : MonoBehaviour { public AudioClip cherry; public AudioClip food; public Text scoreText; public delegate void Collision(); public static event Collision GhostCollisionEvent; public static event Collision FoodCollisionEvent; private int _oldScore; private int _currentScore; private AudioSource _audio; void Start() { _audio = GetComponent<AudioSource>(); } void OnTriggerEnter2D(Collider2D other) { CheckFoodCollision(other); CheckCherryCollision(other); CheckGhostCollision(other); if (_oldScore != _currentScore) { _oldScore = _currentScore; scoreText.text = _currentScore.ToString(); } } /// <summary> /// Check collision with Food /// </summary> /// <param name="other"></param> private void CheckFoodCollision(Collider2D other) { if (other.tag == "Food") { if (FoodCollisionEvent != null) FoodCollisionEvent(); if (!_audio.isPlaying) { _audio.PlayOneShot(food); } _currentScore += 10; Destroy(other.gameObject); } } /// <summary> /// Check collision with Cherry /// </summary> /// <param name="other"></param> private void CheckCherryCollision(Collider2D other) { if (other.tag == "Cherry") { _audio.PlayOneShot(cherry); _currentScore += 10; Destroy(other.gameObject); } } /// <summary> /// Check collision with Chost /// </summary> /// <param name="other"></param> private void CheckGhostCollision(Collider2D other) { if (other.tag == "Ghost") { if (GhostCollisionEvent != null) { GhostCollisionEvent(); } Destroy(this.gameObject); } } } }
84202dddd90801de9a25de0b22d74cce0f638911
C#
juniorgasparotto/GraphExpression
/src/GraphExpression.Examples/Examples/SerializationComplex.cs
2.5625
3
using GraphExpression.Examples.Models; using GraphExpression.Serialization; using SysCommand.ConsoleApp; using SysCommand.Mapping; using System; using System.Collections.Generic; using System.Linq; namespace GraphExpression.Examples { public partial class Examples { [Action(Help = "")] public void SerializationComplex1() { // create a simple object var model = new { A = "A", B = "B", C = "C", D = "D", E = "E", }; var expression = model.AsExpression(); var serialization = new ComplexEntityExpressionSerializer(expression); var expressionAsString = serialization.Serialize(); System.Console.WriteLine(expressionAsString); } [Action(Help = "")] public void SerializationComplex2() { // create a simple object var model = new { A = "A", B = "B", C = "C", D = "D", E = "BIG VALUE", }; var expression = model.AsExpression(); var serialization = new ComplexEntityExpressionSerializer(expression); serialization.EncloseParenthesisInRoot = true; serialization.ValueFormatter = new TruncateFormatter(3); serialization.ShowType = ShowTypeOptions.TypeName; var expressionAsString = serialization.Serialize(); System.Console.WriteLine(expressionAsString); } [Action(Help = "")] public void SerializationComplex3() { var factory = new ComplexExpressionFactory(); factory.MemberReaders.Add(new MethodReader()); var model = new Model(); var expression = model.AsExpression(factory); var serialization = expression.GetSerializer<ComplexEntityExpressionSerializer>(); serialization.ItemsSerialize.Add(new MethodSerialize()); System.Console.WriteLine(serialization.Serialize()); } #region auxs public class MethodSerialize : IEntitySerialize { public string Symbol { get; set; } = null; public bool CanSerialize(ComplexEntityExpressionSerializer serializer, EntityItem<object> item) { return item is MethodEntity; } public (Type Type, string ContainerName) GetSerializeInfo(ComplexEntityExpressionSerializer serializer, EntityItem<object> item) { var cast = (MethodEntity)item; return ( item.Entity?.GetType(), $"{cast.MethodInfo.Name}({string.Join(",", cast.Parameters)})" ); } } #endregion } }
5334fb3b38e1a171d59e5462db6122f008fa9444
C#
ArjunChandarana/TestingAssignment-2
/UnitTestProject/UnitTest.cs
3.015625
3
using Testing_Assignment_2; using Xunit; namespace UnitTestProject { public class UnitTest { string inputString = ""; string expected = ""; [Fact] public void UppartoLower() { // Arrange inputString = "Unit Test"; expected = "uNIT tEST"; // Act string output = inputString.ViceVersaConverter(); // Assert Assert.Equal(expected ,output); } [Fact] public void TitleCase() { // Arrange inputString = "unit test"; expected = "Unit Test"; // Act string output = inputString.TitleCaseConversion(); // Assert Assert.Equal(expected, output); } [Fact] public void Capitalized() { // Arrange inputString = "unit test"; expected = "Unit Test"; // Act string output =inputString.CapitalizedCaseConverter(); // Assert Assert.Equal(expected, output); } [Fact] public void CheckLower() { // Arrange inputString = "unit test"; expected = "lowerCase"; // Act string output = inputString.LowerCaseChecker(); // Assert Assert.Equal(expected, output); } [Fact] public void CheckUppar() { // Arrange inputString = "UNIT"; expected = "upparCase"; // Act string output = inputString.UpperCaseChecker(); // Assert Assert.Equal(expected, output); } [Fact] public void CheckforInt() { // Arrange inputString = "100"; expected = "Success"; // Act string output = inputString.ConverterCheck(); // Assert Assert.Equal(expected, output); } [Fact] public void RemoveLastChar_String_Input_Test() { // Arrange inputString = "Unit Test"; expected = "Unit Tes"; // Act string output = inputString.CharacterRemoval(); // Assert Assert.Equal(expected, output); } [Fact] public void WordCount() { // Arrange inputString = "Unit Test"; expected = "2"; // Act string output = inputString.WordCount(); // Assert Assert.Equal(expected, output); } [Fact] public void StringToInt() { // Arrange inputString = "100"; expected = "100"; // Act string output = inputString.IntegerConverter(); // Assert Assert.Equal(expected, output); } } }
06f0b3cb809238ef97e436bc16f0c1b974226c7e
C#
fbardelli/compsci
/euler/009/pythtrip.cs
3.828125
4
using System; /* Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^(2) + b^(2) = c^(2) For example, 3^(2) + 4^(2) = 9 + 16 = 25 = 5^(2). There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. */ public class Pyth { static public void Main () { int target = 1000; /* Assumptions: sum of squares < square of sums (a)^2 + (b)^2 < (a+b)^2 1^2 + 2^2 < (1+2)^2 so c < a + b so a < b < c < (a + b) if ((a+b)+c) = 1000 then (a+b)>500 and c < 500 min c is 334 since a < b < c and a+b+c=1000 332+333+334=999 < 1000 */ int max_c = (target/2) - 1; int min_c = (target/3) + 1; Console.WriteLine(max_c); int max_b = max_c - 1; int min_b = min_c - 1; int[] squares_table = new int[max_c+1]; for(int i = 0; i <= max_c; i++){ squares_table[i] = (int)Math.Pow(i,2); } for(int c = min_c;c <= max_c; c++){ for(int b = min_b;b <= max_b;b++){ int a = 1000 - b - c; if( (squares_table[a]+squares_table[b])==squares_table[c]){ Console.WriteLine( "a: " + a + " b: " + b + " c: " + c ); Console.WriteLine( squares_table[a] + " + " + squares_table[b] + " = " + squares_table[c] ); int product = a*b*c; Console.WriteLine("a*b*c = " + product); } } } } }
a77ab86841ba7a4e41f4e495a685118327bcb58a
C#
mwirzba/Shop
/Shop/Controllers/AdministrationController.cs
2.609375
3
using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Shop.Data; using Shop.Data.Repositories; using Shop.Dtos; using Shop.Models; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Shop.Controllers { /// <summary> /// Controller responsible for user management /// </summary> [ApiController] [Route("api/[controller]")] [Authorize(Roles = Roles.Admin + "," + Roles.UserManager)] public class AdministrationController: ControllerBase { private readonly UserManager<User> _userManager; private readonly RoleManager<IdentityRole> _roleManager; private readonly IMapper _mapper; private readonly IUnitOfWork _unitOfWork; public AdministrationController(UserManager<User> userManager, IMapper mapper, IUnitOfWork unitOfWork,RoleManager<IdentityRole> roleManager) { _roleManager = roleManager; _userManager = userManager; _mapper = mapper; _unitOfWork = unitOfWork; } /// <summary> /// Returns list of users with given role id. /// </summary> /// <response code="200">Returned users</response> /// <response code="404">Role with given id not found in db.</response> /// <response code="403">User is unauthorized.</response> /// <response code="400">Exception during code execution</response> [HttpGet("usersInRole/{roleId}")] public async Task<IActionResult> GetUsersInRole(string roleId) { try { if (!User.Identity.IsAuthenticated) { return Unauthorized(); } var role = await _roleManager.FindByIdAsync(roleId); if (role == null) { return NotFound(); } var users = new List<UserDto>(); foreach (var user in _userManager.Users) { if (await _userManager.IsInRoleAsync(user, role.Name)) { var userDto = new UserDto { UserName = user.UserName }; users.Add(userDto); } } return Ok(users); } catch (Exception e) { return BadRequest(e.Message); } } /// <summary> /// Returns all users. /// </summary> /// <response code="200">Returned users</response> /// <response code="404">Users not found in database.</response> /// <response code="403">User is unauthorized.</response> /// <response code="400">Exception during code execution</response> [HttpGet] public IActionResult GetUsers() { try { var users = _userManager.Users; if(users == null) { return NotFound(); } var usersDto = _mapper.Map<IEnumerable<User>, IEnumerable<UserDto>>(users); return Ok(usersDto); } catch (Exception e) { return BadRequest(e.Message); } } /// <summary> /// Returns user with given username. /// </summary> /// <response code="200">Returned user</response> /// <response code="404">User not found in database.</response> /// <response code="403">User is unauthorized.</response> /// <response code="400">Exception during code execution</response> [HttpGet("{username}")] public async Task<IActionResult> GetUserByUserName(string username) { try { var user = await _userManager.FindByNameAsync(username); if(user == null) { return NotFound(); } var userDto = _mapper.Map<User,UserDto>(user); return Ok(userDto); } catch (Exception e) { return BadRequest(e.Message); } } /// <summary> /// Adds role to user. /// </summary> /// <param name="roleId">Role id</param> /// <param name="userName">User name of the user to whom we want to assign role.</param> /// <response code="200">Added role to user.</response> /// <response code="404">User not found in database or role not found.</response> /// <response code="403">User is unauthorized to add roles to users.</response> /// <response code="400">Exception during code execution</response> [HttpPatch("addToRole")] public async Task<IActionResult> AddUserToRole(string roleId,string userName) { try { var role = await _roleManager.FindByIdAsync(roleId); if (role == null) { return NotFound("Can not find role with given id."); } var userInDb = await _userManager.FindByNameAsync(userName); if (userInDb == null) { return NotFound("Can not find user with given username."); } bool isInRole = await _userManager.IsInRoleAsync(userInDb, role.Name); if (!isInRole) { await _userManager.AddToRoleAsync(userInDb, role.Name); await _unitOfWork.CompleteAsync(); } return Ok(); } catch (Exception e) { return BadRequest(e.Message); } } /// <summary> /// Removes role from user. /// </summary> /// <param name="roleId">Role id</param> /// <param name="userName">User name of the user to whom we want to remove role.</param> /// <response code="200">Removed role from user.</response> /// <response code="404">User not found in database or role not found.</response> /// <response code="403">User is unauthorized to add roles to users.</response> /// <response code="400">Exception during code execution</response> [HttpPatch("removeFromRole")] public async Task<IActionResult> RemoveUserFromRole(string roleId, string userName) { try { var role = await _roleManager.FindByIdAsync(roleId); if (role == null) { return NotFound("Can not find role with given id."); } var userInDb = await _userManager.FindByNameAsync(userName); if (userInDb == null) { return NotFound("Can not find user with given username."); } bool isInRole = await _userManager.IsInRoleAsync(userInDb, role.Name); if (isInRole) { await _userManager.RemoveFromRoleAsync(userInDb, role.Name); } await _unitOfWork.CompleteAsync(); return Ok(); } catch (Exception e) { return BadRequest(e.Message); } } } }
989049b2d4fba6054140f05dd4410e89c4fd6841
C#
halilsatik/MarsRover
/MarsRover.Service/RoverController.cs
2.796875
3
using MarsRover.Service.CustomExceptions; using MarsRover.Service.Enums; using MarsRover.Service.Models; using System; using System.Collections.Generic; using System.Text; namespace MarsRover.Service { public class RoverController : IRoverController { public Position Position { get; set; } public Plateau Plateau { get; set; } public void MoveForward() { ValidateCoordinate(Position.Coordinate); Coordinate nextCoordinate = new Coordinate { X = Position.Coordinate.X, Y = Position.Coordinate.Y }; switch (Position.DirectionType) { case DirectionType.N: nextCoordinate.Y++; break; case DirectionType.S: nextCoordinate.Y--; break; case DirectionType.E: nextCoordinate.X++; break; case DirectionType.W: nextCoordinate.X--; break; default: break; } ValidateCoordinate(nextCoordinate); Position.Coordinate = nextCoordinate; } private void ValidateCoordinate(Coordinate coordinate) { if (!(coordinate.X >= Plateau.LowerLefttCoordinate.X && coordinate.X <= Plateau.UpperRightCoordinate.X && coordinate.Y >= Plateau.LowerLefttCoordinate.Y && coordinate.Y <= Plateau.UpperRightCoordinate.Y)) { throw new RoverOutOfPlateauException(); } } public void TurnLeft() { switch (Position.DirectionType) { case DirectionType.N: Position.DirectionType = DirectionType.W; break; case DirectionType.S: Position.DirectionType = DirectionType.E; break; case DirectionType.E: Position.DirectionType = DirectionType.N; break; case DirectionType.W: Position.DirectionType = DirectionType.S; break; } } public void TurnRight() { switch (Position.DirectionType) { case DirectionType.N: Position.DirectionType = DirectionType.E; break; case DirectionType.S: Position.DirectionType = DirectionType.W; break; case DirectionType.E: Position.DirectionType = DirectionType.S; break; case DirectionType.W: Position.DirectionType = DirectionType.N; break; } } public void ExecuteNavigationPlan(Plateau plateau, NavigationPlan navigationPlan) { this.Plateau = plateau; this.Position = navigationPlan.InitialPosition; foreach (InstructionType instructionType in navigationPlan.InstructionTypeSequence) { switch (instructionType) { case InstructionType.M: this.MoveForward(); break; case InstructionType.L: this.TurnLeft(); break; case InstructionType.R: this.TurnRight(); break; } } } } }
fa185f5cedd2d1cf5a2cd7e2f10c5834d14b0765
C#
tlagmltjq11/Algorithm
/Graph-DFS,BFS/1012.cs
3.546875
4
using System; using System.Collections.Generic; using System.Text; namespace CodingTestPractice { class _1012 { static int[,] mat; static int m; static int n; static void DFS(int i, int j) { mat[i, j] = 0; if ((i - 1) >= 0 && mat[i - 1, j] == 1) { DFS(i - 1, j); } if ((i + 1) < m && mat[i + 1, j] == 1) { DFS(i + 1, j); } if ((j - 1) >= 0 && mat[i, j - 1] == 1) { DFS(i, j - 1); } if ((j + 1) < n && mat[i, j + 1] == 1) { DFS(i, j + 1); } } static void Main() { int t = int.Parse(Console.ReadLine()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; i++) { string[] read = Console.ReadLine().Split(" "); m = int.Parse(read[0]); n = int.Parse(read[1]); int k = int.Parse(read[2]); mat = new int[m, n]; for (int j = 0; j < k; j++) { read = Console.ReadLine().Split(" "); int x = int.Parse(read[0]); int y = int.Parse(read[1]); mat[x, y] = 1; } int cnt = 0; for(int j=0; j<m; j++) { for(int l=0; l<n; l++) { if(mat[j, l] == 1) { DFS(j, l); cnt++; } } } sb.AppendLine(cnt.ToString()); } Console.WriteLine(sb.ToString()); } } }
1b67ae4bb05155f71f4c02319e7c20ef5a8bfa3b
C#
yassinemaghfour/Anouar-CMIM-GIT
/CMIM/CMIM/Models/Bordereau.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace CMIM.Models { public class Bordereau { [Key] public long BordereauId { get; set; } public virtual ICollection<Dossier> Dossiers { get; set; } private string company; private DateTime dateCreation; public string Company { get { return company; } set { if (value.ToUpper() != "VEM" && value.ToUpper() != "VEAS" && value.ToUpper() != "SVL") throw new Exception("Invalide Company"); else this.company = value.ToUpper(); } } public DateTime DateCreation { get => dateCreation; set { this.dateCreation = DateTime.Now; } } public int CompareTo(object obj) { Bordereau d = (Bordereau)obj; if (this.BordereauId == d.BordereauId) return 0; return 1; } } }
2092f68b0a2b3ccca74b5f7e9eb2be3f5acac9f1
C#
joaofreitas21/16968_17632_LP2
/DAO/Hotel.cs
2.625
3
using System; using BO; using System.Collections.Generic; namespace DAO { interface IHotel { bool EfetuarCheckIn(Cliente c , DateTime check, int num); Registo RemoverRegistoQuarto(int num); Registo AddRegistoQuarto(Quarto q,int num); double EfetuarPagamento(int num, double precoDia); } [Serializable] public class Hotel : HotelBO , IHotel { static int MAX = 100; #region ESTADO Quarto[] quartos; Clientes clientes; Empregados empregados; #endregion #region METODOS #region CONSTRUTORES /// <summary> /// Valores inseridos por default /// </summary> public Hotel() { quartos =new Quarto[MAX]; clientes = new Clientes(); empregados = new Empregados(); } public Hotel(int c) { quartos = new Quarto[c]; clientes = new Clientes(); empregados = new Empregados(); maxQuartos = c; } public Hotel(string a, string b,int c) { quartos = new Quarto[c]; clientes = new Clientes(); empregados = new Empregados(); maxQuartos = c; } #endregion #region METODOS_HOTEL /// <summary> /// Guarda infos dos parametros em BO /// </summary> /// <param name="hotel"></param> public void GuardaInfoHotel(HotelBO hotel) { base.MaxQuartos = hotel.MaxQuartos; base.Morada = hotel.Morada; base.Nome = hotel.Nome; base.NumTelemovel = hotel.NumTelemovel; } public HotelBO DevolveInfo() { HotelBO hotel = new HotelBO(); hotel.MaxQuartos = base.MaxQuartos; hotel.Morada = base.Morada; hotel.Nome = base.Nome; hotel.NumTelemovel = base.NumTelemovel; return hotel; } #endregion #region METODOS_QUARTO public Quarto FichaQuarto(int num) { if (quartos[num].Cli.NIF != 0) { return quartos[num].FichaQuarto(); } else return new Quarto(); } /// <summary> /// Método que faz o registo de um quarto /// </summary> /// <param name="c">Cliente</param> /// <param name="reserva">Dia de reserva</param> /// <param name="num">Numero quarto</param> /// <param name="add">Extras</param> /// <returns>Retorno do enumerador Registo</returns> public Registo AddRegistoQuarto(Quarto q, int num) { if (quartos[num].Reserva() == true) { if (quartos[num].Reserva(q) == true) { return Registo.Efetuado; } else return Registo.NaoEfetuado; } else { return Registo.NaoEfetuado; } } /// <summary> /// Método que remove o registo de um quarto /// </summary> /// <param name="num">Numero do Quarto</param> /// <returns>Retorno do enumerador Registo</returns> public Registo RemoverRegistoQuarto(int num) { if (quartos[num].Reserva() == false) { quartos[num].StatusReserva(Status.NaoReservado); return Registo.Efetuado; } else return Registo.NaoEfetuado; } /// <summary> /// Método que efetua o CheckIn no hotel /// </summary> /// <param name="check">tempo da estadia</param> /// <param name="num">Numero do quarto</param> /// <returns>Booleano</returns> public bool EfetuarCheckIn(Cliente c, DateTime check, int num) { if (quartos[num].Reserva() == false) { if (quartos[num].CheckIn(c,check) == Check.Efetuado) return true; else return false; } else return false; } /// <summary> /// Mecanica de preços por tipo de quarto /// </summary> /// <param name="num">Numero que identifica o tipo de Quarto</param> /// <param name="precoDia">Preco por dia</param> /// <returns>Custo estadia</returns> public double EfetuarPagamento(int num,double precoDia) { Cliente c = quartos[num].Cli; double valor=quartos[num].Custo(DateTime.Today,precoDia); Console.WriteLine("Quarto Numero - {0} ", num); if (num <= maxQuartos * 0.25) { Console.WriteLine("Quarto Individual"); } if (maxQuartos * 0.25<num && num <= maxQuartos * 0.50) { Console.WriteLine("Quarto Standard"); valor = valor + 20; } if (maxQuartos * 0.50<num && num <= maxQuartos * 0.50) { Console.WriteLine("Quarto Master"); valor = valor + 45; } if (num > maxQuartos * 0.75) { Console.WriteLine("Quarto Deluxe"); valor = valor + 125; } c.TotalAPagar = valor; AddCliente(c); return valor; } public List<int> QuartosLivres() { int i = 0; List<int> quartosLivres = new List<int>(); foreach(Quarto q in quartos) { if (q.Reserva() == true) { quartosLivres.Add(i); } i++; } return quartosLivres; } #endregion #region METODOS_CLIENTE /// <summary> /// Guarda o cliente todo (objeto) /// </summary> /// <param name="c"></param> /// <returns></returns> public bool AddCliente(Cliente c) { return clientes.GuardaCliente(c); } /// <summary> /// Procura cliente pelo seu numero /// </summary> /// <param name="numCliente"></param> /// <returns></returns> public Cliente ProcuraClient(int numCliente) { Cliente cli = clientes.ProcuraCliente(numCliente); return cli; } /// <summary> /// Remove cliente pelo numero /// </summary> /// <param name="numCliente"></param> /// <returns></returns> public bool RemoveCliente(int numCliente) { return clientes.RemoveCliente(numCliente); } /// <summary> /// Lista toda a info do cliente atraves do seu numero /// </summary> /// <param name="numCliente"></param> /// <returns></returns> public List<Cliente> FichaCliente(int numCliente) { return clientes.ListaInfo(numCliente); } #endregion #region METODO_EMPREGADOS /// <summary> /// Adiciona empregado todo (objeto) /// </summary> /// <param name="e"></param> /// <returns></returns> public bool AddEmpregado(Empregado e) { return empregados.GuardaEmpregado(e); } /// <summary> /// Procura empregado pelo ID Empregado /// </summary> /// <param name="idEmpregado"></param> /// <returns></returns> public Empregado ProcuraOEmpregado(int idEmpregado) { Empregado emp = empregados.ProcuraEmpregado(idEmpregado); return emp; } /// <summary> /// Remove empregado pelo ID Empregado /// </summary> /// <param name="idEmpregado"></param> /// <returns></returns> public bool RemoveEmpregado(int idEmpregado) { return empregados.RemoveEmpregado(idEmpregado); } /// <summary> /// Lista a info do empregado pelo ID /// </summary> /// <param name="idEmpregado"></param> /// <returns></returns> public List<Empregado> FichaEmpregado (int idEmpregado) { return empregados.ListaInfo(idEmpregado); } #endregion #region DEST ~Hotel() { } #endregion #endregion } }
480a5ab6ddb30d635d77a388a7ba3c18468af60a
C#
pipe01/pi
/Pi/Parser/Syntax/Expressions/UnaryExpression.cs
2.53125
3
namespace Pi.Parser.Syntax.Expressions { internal sealed class UnaryExpression : Expression { public UnaryOperators Operator { get; } public Expression Argument { get; } public UnaryExpression(SourceLocation location, UnaryOperators @operator, Expression argument) : base(location) { this.Operator = @operator; this.Argument = argument; } } public enum UnaryOperators { LogicalNegation } }
c4bbe50d508e75ff755272d44d0b2072a244f72b
C#
Nhawdge/takeover
/GameEngine.cs
2.703125
3
using System; using System.Collections.Generic; using Takeover.Components; using Takeover.Entities; using Takeover.Systems; namespace Takeover { public class GameEngine { private List<Systems.System> Systems { get; set; } = new List<Systems.System>(); public List<Entity> Entities { get; set; } = new List<Entity>(); public GameEngine() { this.Systems.Add(new LevelGeneratorSystem()); this.Systems.Add(new RenderSystem()); this.Systems.Add(new MovementSystem()); this.Systems.Add(new AttackSystem()); this.Systems.Add(new RegenerationSystem()); this.Systems.Add(new WinSystem()); this.Systems.Add(new AISystem()); this.Systems.Add(new MenuSystem()); var singleton = new Entity(); singleton.Components.Add(new Singleton()); this.Entities.Add(singleton); } public void GameLoop() { foreach (var system in this.Systems) { system.UpdateAll(this.Entities, this); } } } }
61ea2d0d366be528cad91d96c267d875d0d15fbe
C#
alyons/PokemonInfinity
/PEEditor/PEEditor/Data Objects/Ability.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PEEditor { public class Ability : ViewModelBase { private int id; private String internalName; private String displayName; private String description; public int ID { get { return id; } set { if (value != id) { id = value; OnPropertyChanged("ID"); } } } public String InternalName { get { return internalName; } set { if (internalName == null || !internalName.Equals(value)) { internalName = value; OnPropertyChanged("InternalName"); } } } public String DisplayName { get { return displayName; } set { if (displayName == null || !displayName.Equals(value)) { displayName = value; OnPropertyChanged("DisplayName"); } } } public String Description { get { return description; } set { if (description == null || !description.Equals(value)) { description = value; OnPropertyChanged("Description"); } } } public Ability() { } public Ability(string text) { string[] parts = text.Split(','); if (parts.Count() >= 4) { this.ID = Convert.ToInt32(parts[0]); this.InternalName = parts[1]; this.DisplayName = parts[2]; string desc = parts[3]; for (int i = 4; i < parts.Count(); i++) { desc += "," + parts[i]; } this.Description = desc; } } public override String ToString() { return this.ID + "," + this.InternalName + "," + this.DisplayName + "," + this.Description; } } }
b5bc1986de25a9b389e4ee6240daa7518a6fa5f5
C#
dgarcia202/grassworld
/Assets/Scripts/Resources/Transaction.cs
2.546875
3
using System; using Behaviours; namespace Resources { public class Transaction { public static int Perform(ResourceContainer origin, ResourceContainer destination, ResourceType resource, int amount) { if (origin.Count (resource) < amount) { var availableAmount = origin.Count (resource); origin.Take (resource, availableAmount); destination.Add (resource, availableAmount); return availableAmount; } origin.Take (resource, amount); destination.Add (resource, amount); return amount; } } }
6fec35f0c3305e4cd9eb97309a07cf47987a33cc
C#
radtek/shi5588
/RMCrypt/RMCrypt/RMCrypt.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; namespace app3 { public class RMCrypt { private Byte[] _Key = {0x01, 0x09, 0x08, 0x05, 0x00, 0x06, 0x00, 0x05, 0x01, 0x09, 0x07, 0x09, 0x00, 0x08, 0x00, 0x08}; private Byte[] _IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; private RijndaelManaged _RM; public RMCrypt() { this._RM = new RijndaelManaged(); this._RM.Key = this._Key; this._RM.IV = this._IV; } public RMCrypt(string strKey):this() { string myKey = strKey.PadLeft(16, 'x').Substring(0, 16);//必须为16位长,不足以‘x’填充 this._RM.Key = ASCIIEncoding.ASCII.GetBytes(myKey); this._RM.IV = ASCIIEncoding.ASCII.GetBytes(myKey); } public string Encrypt(string strContext) { byte[] inputByteArray = Encoding.Default.GetBytes(strContext); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, this._RM.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder strResult = new StringBuilder(); foreach(byte b in ms.ToArray()) { strResult.AppendFormat("{0:X2}", b);//格式化为16进制数字 } return strResult.ToString(); } public string Decrypt(string strContext) { //将加密后的字符串转为 ByteArray byte[] inputByteArray = new byte[strContext.Length / 2]; for (int x = 0; x < strContext.Length / 2; x++) { int i = (Convert.ToInt32(strContext.Substring(x * 2, 2), 16));//从数字串转为16进制数字后放入byteArray inputByteArray[x] = (byte)i; } MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, this._RM.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return System.Text.Encoding.Default.GetString(ms.ToArray()); } } }
946b7833391144ee19df3772aef0b284df20fcca
C#
jakubkozera/DesignPatterns
/Structural/Decorator/PizzaDecorator.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decorator { public abstract class PizzaDecorator : IPizza { private IPizza _pizza; protected PizzaDecorator(IPizza pizza) { _pizza = pizza; } public virtual double CalculatePrice() { return _pizza.CalculatePrice(); } } }
4d784f4d11b1e2af8c08771c3e1fe2357268250e
C#
wlindley/AngryShihTzu
/Assets/Scripts/Editor/ScriptableObjectHelper.cs
2.734375
3
using System; using UnityEngine; using UnityEditor; namespace AST { public class ScriptableObjectHelper { public bool IsTypeScriptableObject(Type type) { return null != type && !type.IsAbstract && type.IsSubclassOf(typeof(ScriptableObject)) && !type.IsSubclassOf(typeof(Editor)) && !type.IsSubclassOf(typeof(EditorWindow)); } public ScriptableObject CreateScriptableObjectInstance(Type type, string path = null) { if (!IsTypeScriptableObject(type)) { Debug.LogError("Tried to create instance of " + type.FullName + ", but it is not a ScriptableObject"); return null; } var asset = ScriptableObject.CreateInstance(type); path = ValidatePath(type, path); AssetDatabase.CreateAsset(asset, path); EditorGUIUtility.PingObject(asset); return AssetDatabase.LoadAssetAtPath(path, type) as ScriptableObject; } private string ValidatePath(Type type, string path) { if (null == path) path = "Assets/" + type.Name + ".asset"; path = AssetDatabase.GenerateUniqueAssetPath(path); return path; } private ScriptableObjectHelper() { } public static ScriptableObjectHelper GetInstance() { return new ScriptableObjectHelper(); } } }
3ae639aa843eb14ad329b83d615662f53504d7ac
C#
kindex/labyrinth2
/sources/Math/Degrees.cs
3.375
3
using System; namespace Game { public static class Degrees { public static float ToRadians(float degrees) { return degrees * (float)Math.PI / 180.0f; } public static double ToRadians(double degrees) { return degrees * Math.PI / 180.0; } public static float Sin(float x) { return (float)Math.Sin(ToRadians(x)); } public static double Sin(double x) { return Math.Sin(ToRadians(x)); } public static float Cos(float x) { return (float)Math.Cos(ToRadians(x)); } public static double Cos(double x) { return Math.Cos(ToRadians(x)); } public static float Tan(float x) { return (float)Math.Tan(ToRadians(x)); } public static double Tan(double x) { return Math.Tan(ToRadians(x)); } public static float Atan2(float y, float x) { return Radians.ToDegrees((float)Math.Atan2(y, x)); } public static double Atan2(double y, double x) { return Normalize(Radians.ToDegrees(Math.Atan2(y, x))); } public static double Normalize(double x) { double result = Math.IEEERemainder(x, 360.0); if (result < 0.0) { result += 360.0; } return result; } } }
828af34883b76ab1d0825fe8efae85cec84a31d0
C#
uk-gov-mirror/SkillsFundingAgency.DC-ILR-2021-Tools
/legacy/src/Easy OPA/Visuals/Abstract/VisualBindingWrapper.cs
2.953125
3
using EasyOPA.Model; using System; using Tiny.Framework.Abstracts; namespace EasyOPA.Abstract { /// <summary> /// an abstract visual element binding class /// </summary> /// <typeparam name="TSource">The type of source.</typeparam> /// <seealso cref="ObservableBase" /> public abstract class VisualBindingWrapper<TSource> : ObservableBase where TSource : class, ICanBeSelectedForProcessing { /// <summary> /// Initializes a new instance of the <see cref="VisualBindingWrapper{TSource}"/> class. /// </summary> /// <param name="source">The source.</param> /// <param name="onStateChanged">The on state changed (action).</param> protected VisualBindingWrapper(TSource source, Action onStateChanged) { Source = source; IsSelectedForProcessing = Source.IsSelectedForProcessing; OnStateChanged = onStateChanged; } /// <summary> /// Gets or sets the identifier. /// </summary> public TSource Source { get; } /// <summary> /// Gets or sets the run update. /// </summary> public Action OnStateChanged { get; } /// <summary> /// is selected for processing /// </summary> private bool _isSelectedForProcessing; /// <summary> /// Gets or sets a value indicating whether this instance is selected for processing. /// </summary> public bool IsSelectedForProcessing { get { return _isSelectedForProcessing; } set { if (SetPropertyValue(ref _isSelectedForProcessing, value)) { Source.IsSelectedForProcessing = value; OnStateChanged?.Invoke(); } } } /// <summary> /// is selected for processing /// </summary> private bool _isEnabledForSelection; /// <summary> /// Gets or sets a value indicating whether this instance is selected for processing. /// </summary> public bool IsEnabledForSelection { get { return _isEnabledForSelection; } set { if (SetPropertyValue(ref _isEnabledForSelection, value)) { Source.IsSelectedForProcessing ^= _isEnabledForSelection; } } } /// <summary> /// Sets the selection without propogation. /// </summary> /// <param name="selectionState">if set to <c>true</c> [selection state].</param> public void SetSelectionWithoutPropogation(bool selectionState) { _isSelectedForProcessing = selectionState; Source.IsSelectedForProcessing = selectionState; OnPropertyChanged(nameof(IsSelectedForProcessing)); } // note: the following two properties are here to resolve 'listbox item' binding issues /// <summary> /// is selected /// </summary> private bool _isSelected; /// <summary> /// Gets or sets a value indicating whether this instance is selected. /// reduced scope to bind and remove general accesibility /// </summary> internal bool IsSelected { get { return _isSelected; } set { SetPropertyValue(ref _isSelected, value); } } /// <summary> /// is enabled /// </summary> private bool _isEnabled = true; /// <summary> /// Gets or sets a value indicating whether this instance is enabled. /// reduced scope to bind and remove general accesibility /// </summary> internal bool IsEnabled { get { return _isEnabled; } set { SetPropertyValue(ref _isEnabled, value); } } } }
9b870db126f43283ee674663ba664add96d12896
C#
MichaelAllenClark/ETConsoleExample
/ETConsoleExample/Program.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using ETConsoleExample.ExactTargetSOAPAPI; namespace ETConsoleExample { class Program { static void Main(string[] args) { BasicHttpBinding binding = new BasicHttpBinding(); binding.Name = "UserNameSoapBinding"; binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential; binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName; binding.ReceiveTimeout = new TimeSpan(0, 5, 0); binding.OpenTimeout = new TimeSpan(0, 5, 0); binding.CloseTimeout = new TimeSpan(0, 5, 0); binding.SendTimeout = new TimeSpan(0, 5, 0); EndpointAddress endpoint = new EndpointAddress("https://webservice.exacttarget.com/Service.asmx"); SoapClient ETSOAPAPI = new SoapClient(binding, endpoint); ETSOAPAPI.ClientCredentials.UserName.UserName = "ccc"; ETSOAPAPI.ClientCredentials.UserName.Password = "ccc"; RetrieveRequest getLists = new RetrieveRequest(); getLists.ObjectType = "List"; getLists.Properties = new string[] { "ID", "ListName" }; String RequestID = String.Empty; APIObject[] responseObjects = new APIObject[] { }; String OverallStatus = String.Empty; OverallStatus = ETSOAPAPI.Retrieve(getLists, out RequestID, out responseObjects); Console.WriteLine("OverallStatus: " + OverallStatus + " RequestID: " + RequestID); if (responseObjects.Length > 0) { foreach (List l in responseObjects) { Console.WriteLine("ListID : " + l.ID.ToString() + " Name: " + l.ListName); } } Console.ReadLine(); } } }
1d78457f76ea93b888d3ba05c6194e86951a93fe
C#
SSSxCCC/Survival
/Assets/Scripts/Public/PathFinding/BinaryHeap.cs
3.578125
4
 // 这是一个只适合本程序A*算法使用的二叉堆,堆顶元素最小 public class BinaryHeap { public Vertex[] vertexes; // 二叉堆内容 private int length; // 当前长度 // 新建二叉堆,最大长度为size public BinaryHeap(int size) { vertexes = new Vertex[size + 1]; // items[0]并不会使用,所以这里需要一个额外空间 length = 0; } // 插入新元素 public void Add(Vertex vertex) { length++; // 当前二叉堆长度加一 // 新来元素先插到最后面 vertexes[length] = vertex; // 上浮 Float(length); } // 对下标为index的元素进行上浮,在对二叉堆元素的值改变后必须调用,以保持二叉堆的有序 public void Float(int index) { // 上浮 int parentIndex = index / 2; while (parentIndex != 0) { // 如果自己比父节点小,则与父节点换位 if (vertexes[index].f() < vertexes[parentIndex].f()) { Swap(ref vertexes[index], ref vertexes[parentIndex]); index = parentIndex; parentIndex = index / 2; } else break; } } // 删除并返回堆顶元素 public Vertex Remove() { Vertex removedItem = vertexes[1]; // 记下堆顶元素 vertexes[1] = vertexes[length]; // 最后一个元素取代堆顶元素 length--; // 当前二叉堆长度减一 // 下沉 int currentIndex = 1; int leftChildIndex = currentIndex * 2; int rightChildIndex = currentIndex * 2 + 1; while (leftChildIndex <= length) { if (rightChildIndex <= length) { // 有两个子节点 if (vertexes[leftChildIndex].f() <= vertexes[rightChildIndex].f() && vertexes[leftChildIndex].f() < vertexes[currentIndex].f()) { // 左子节点最小 Swap(ref vertexes[currentIndex], ref vertexes[leftChildIndex]); currentIndex = leftChildIndex; } else if (vertexes[rightChildIndex].f() < vertexes[leftChildIndex].f() && vertexes[rightChildIndex].f() < vertexes[currentIndex].f()) { // 右子节点最小 Swap(ref vertexes[currentIndex], ref vertexes[rightChildIndex]); currentIndex = rightChildIndex; } else break; // 自己已经是最小的了 } else { // 只有一个左子节点 if (vertexes[currentIndex].f() > vertexes[leftChildIndex].f()) { // 左子节点最小 Swap(ref vertexes[currentIndex], ref vertexes[leftChildIndex]); } break; // 无论如何,已经再不会有子节点了 } leftChildIndex = currentIndex * 2; rightChildIndex = currentIndex * 2 + 1; } return removedItem; } // 返回代表路径点id为waypointId的顶点下标,如果没有,返回0 public int FindVertex(Waypoint waypoint) { for (int i = 1; i <= length; i++) { if (vertexes[i].waypoint == waypoint) { return i; } } return 0; } // 二叉堆是否为空 public bool IsEmpty() { return length == 0; } // 交换两值 private void Swap(ref Vertex t1, ref Vertex t2) { Vertex temp = t1; t1 = t2; t2 = temp; } }
1e2048e47e6ba99914d32e2aca139fce07b05548
C#
ggarabedian/TelerikAcademy
/CSharpOOP/ExtensionMethodsDelegatesLambdaLINQ/Timer/Test.cs
3.65625
4
/* Using delegates write a class Timer that can execute certain method at each t seconds. */ namespace Timer { using System; using System.Threading; public class Test { static void Main() { Timer timer = new Timer(1); Timer.TimerDelegate dlgt = delegate() { Console.WriteLine(DateTime.Now); }; timer.AddDelegate(dlgt); timer.Start(); Thread.Sleep(10000); timer.Stop(); } } }
b27b22ea246c33448de9b5517dc096af56e23cdb
C#
ilandeka/masters-thesis-paper
/DevQuiz/DevQuiz.Core/Models/ViewModels/GameViewModel.cs
2.734375
3
using DevQuiz.Core.Models.ApplicationModels; using DevQuiz.Core.Models.TransportModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DevQuiz.Core.Models.ViewModels { public class GameViewModel : BaseViewModel { public const uint NUMBER_OF_QUESTIONS = 5; public DateTime StartTime { get; set; } public DifficultyEnum CurrentDifficulty { get; set; } public int CurrentQuestionNumber { get; set; } public IEnumerable<Question> CurrentQuestions { get; set; } private int _correctAnswers = 0; public int CorrectAnswers { get { return _correctAnswers; } } public int WrongAnswers { get { return (int)NUMBER_OF_QUESTIONS - CorrectAnswers; } } public int Score { get { return CorrectAnswers * 1000; } } public Question CurrentQuestion { get { return CurrentQuestions.ElementAt(CurrentQuestionNumber - 1); } } public async Task LoadQuestions() { IsBussy = true; try { CurrentQuestions = await GameService.GetQuestions(CurrentDifficulty, 5); CurrentQuestionNumber = 1; } catch (Exception ex) { // TODO: log error } finally { IsBussy = false; } } public void ResetAnswerCounter() { _correctAnswers = 0; } public void ConfirmAnswerAtIndex(int answerIndex) { var answer = CurrentQuestion.PossibleAnswers.ElementAt(answerIndex); answer.MarkedByPlayerAsCorrectAnswer = true; if (answer.IsReallyCorrectAnswer) _correctAnswers++; } public Question NextQuestion() { if (CurrentQuestionNumber <= NUMBER_OF_QUESTIONS) { var q = CurrentQuestions.ElementAt(CurrentQuestionNumber); CurrentQuestionNumber++; return q; } else { CurrentQuestionNumber = 1; ResetAnswerCounter(); return CurrentQuestions.ElementAt(CurrentQuestionNumber); } } } }
fd3b63bc97e668c37a7c1cb3a020dd8ef721875e
C#
senchov/ECS
/Assets/Scripts/Fuzzy/sets/TriangleFuzzySet.cs
3.1875
3
namespace Fuzzy { public struct TriangleFuzzySet : IFuzzySet { private int LeftOffset; private int Peak; private int RightOffset; public TriangleFuzzySet(int leftOffset, int peak, int rightOffset) { LeftOffset = leftOffset; Peak = peak; RightOffset = rightOffset; } public float CalculateDom(int value) { if (value < LeftOffset || RightOffset < value) return 0; float wholeDiff = 0; float valueDiff = 0; if (LeftOffset <= value && value <= Peak) { wholeDiff = Peak - LeftOffset; valueDiff = value - LeftOffset; return valueDiff / wholeDiff; } wholeDiff = RightOffset - Peak; valueDiff = value - Peak; return 1 - valueDiff / wholeDiff; } } }
a03674bd2d25081732fb7a7670169b9f2b2b91d1
C#
alma-sys/alma-infra
/Common/Security/Hash.cs
2.671875
3
using System; using System.Security.Cryptography; namespace Alma.Common.Security { public static class Hash { public static string Create(string input) { var inputBytes = System.Text.Encoding.UTF8.GetBytes(input); using (var hash = SHA512.Create()) { var result = hash.ComputeHash(inputBytes); return BitConverter.ToString(result).Replace("-", ""); } } } }
4324585709d34e504192b4bc17c36cd16d6216da
C#
benmpeterson/CSharpLibrary
/0.21_Generics_BestPractices_PluralsightCourse/OperationResult.cs
3.125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _0._21_Generics_BestPractices_PluralsightCourse { public class OperationResult<T> { public OperationResult() { } public OperationResult(T result, string message) : this() { this.Result = result; this.Message = message; } public string Message { get; set; } public T Result { get; set; } //Generic Method public B PrintParameter<B>(B defaultValue) where B : class { B value = defaultValue; return value; } } }
6d915670fa15bdfd06a3b94bddc4f0b4244e77d9
C#
joelmora9618/POO-C-SHARP
/Practica 2/Practica 2/Program.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Practica_2 { class Program { static void Main(string[] args) { string value; clsClientesFijos Clientes; Clientes = new clsClientesFijos(); Console.WriteLine("ingrese su nombre: "); Clientes.Nombre = Console.ReadLine(); Console.WriteLine("ingrese su apellido: "); Clientes.Apellido = Console.ReadLine(); Clientes.IdCliente = 2; Console.WriteLine("ingrese su direccion: "); Clientes.Direccion = Console.ReadLine(); Console.WriteLine("ingrese su numero de telefono: "); value = Console.ReadLine(); Clientes.Telefono = Convert.ToInt64(value); Console.Clear(); Console.WriteLine(Clientes.Nombre + " " + Clientes.Apellido); Console.WriteLine(Clientes.Direccion + " " + Clientes.Telefono); Console.WriteLine(Clientes.Email); Console.ReadKey(); } } }
c126e368369994a3c5f0a7f30532e6db8a5b8f6c
C#
DMBS/.NET-Design-Patterns
/Behavioral/Iterator/GeneratorThroughIterator/GeneratorThroughIterator/Program.cs
3.296875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GeneratorThroughIterator { class Program { static void Main(string[] args) { var n = GenerateFibonaci(); } public static IEnumerable<int> GenerateFibonaci() { int prev = 0; int current = 1; while (true) { yield return current; int tmp = current; current = prev + current; prev = tmp; } } } }
169eedde950c97d40bcfd40b2cb12e27dc6bd5c6
C#
CptWesley/Clap
/src/Clap/Arguments.cs
2.796875
3
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; namespace Clap { /// <summary> /// Class containing static functions for parsing arguments. /// </summary> public static class Arguments { /// <summary> /// Parses the specified arguments. /// </summary> /// <typeparam name="T">Type of object to parse the arguments to.</typeparam> /// <param name="args">The arguments.</param> /// <returns>Returns the parsed arguments object.</returns> public static T Parse<T>(string args) => Parse<T>(SplitArgs(args)); /// <summary> /// Parses the specified arguments. /// </summary> /// <typeparam name="T">Type of object to parse the arguments to.</typeparam> /// <param name="args">The arguments.</param> /// <returns>Returns the parsed arguments object.</returns> public static T Parse<T>(string[] args) => Parse<T>(args, CultureInfo.CurrentCulture); /// <summary> /// Parses the specified arguments. /// </summary> /// <typeparam name="T">Type of object to parse the arguments to.</typeparam> /// <param name="args">The arguments.</param> /// <param name="culture">Culture used for parsing arguments.</param> /// <returns>Returns the parsed arguments object.</returns> public static T Parse<T>(string args, CultureInfo culture) => Parse<T>(SplitArgs(args), culture); /// <summary> /// Parses the specified arguments. /// </summary> /// <typeparam name="T">Type of object to parse the arguments to.</typeparam> /// <param name="args">The arguments.</param> /// <param name="culture">Culture used for parsing arguments.</param> /// <returns>Returns the parsed arguments object.</returns> public static T Parse<T>(string[] args, CultureInfo culture) => (T)Parse(typeof(T), args, culture); /// <summary> /// Parses the specified arguments. /// </summary> /// <param name="type">Type of object to parse the arguments to.</param> /// <param name="args">The arguments.</param> /// <returns>Returns the parsed arguments object.</returns> public static object Parse(Type type, string args) => Parse(type, SplitArgs(args), CultureInfo.CurrentCulture); /// <summary> /// Parses the specified arguments. /// </summary> /// <param name="type">Type of object to parse the arguments to.</param> /// <param name="args">The arguments.</param> /// <returns>Returns the parsed arguments object.</returns> public static object Parse(Type type, string[] args) => Parse(type, args, CultureInfo.CurrentCulture); /// <summary> /// Parses the specified arguments. /// </summary> /// <param name="type">Type of object to parse the arguments to.</param> /// <param name="args">The arguments.</param> /// <param name="culture">Culture used for parsing arguments.</param> /// <returns>Returns the parsed arguments object.</returns> public static object Parse(Type type, string args, CultureInfo culture) => Parse(type, SplitArgs(args), culture); /// <summary> /// Parses the specified arguments. /// </summary> /// <param name="type">Type of object to parse the arguments to.</param> /// <param name="args">The arguments.</param> /// <param name="culture">Culture used for parsing arguments.</param> /// <returns>Returns the parsed arguments object.</returns> public static object Parse(Type type, string[] args, CultureInfo culture) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (args == null) { throw new ArgumentNullException(nameof(args)); } object result = Activator.CreateInstance(type); Dictionary<string, PropertyInfo> options = CreateAliasMap(type); PropertyInfo[] unnamedOptions = CreateUnnamedMap(type); HashSet<PropertyInfo> setOptions = new HashSet<PropertyInfo>(); PropertyInfo property = null; List<object> parsedArgs = new List<object>(); string option = null; int unnamedIndex = 0; for (int i = 0; i < args.Length; i++) { string arg = args[i]; if (property == null) { if (arg[0] == '-') { option = arg.Substring(1).ToUpperInvariant(); if (options.TryGetValue(option, out property)) { if (setOptions.Contains(property)) { throw new CommandLineArgumentsException($"Option '{option}' can not be set twice."); } setOptions.Add(property); if (property.PropertyType == typeof(bool)) { property.SetValue(result, true); property = null; } } else { throw new CommandLineArgumentsException($"Option '{option}' was not recognized."); } } else if (unnamedIndex < unnamedOptions.Length) { property = unnamedOptions[unnamedIndex++]; i--; } else { throw new CommandLineArgumentsException($"Unrecognized argument '{arg}'."); } } else if (property != null) { if (IsArrayLike(property)) { if (arg[0] == '-') { EndArray(property, result, parsedArgs); property = null; i--; } else { Type elementType = GetArrayLikeElementType(property); object parsedArg = ParseValue(elementType, arg, culture); parsedArgs.Add(parsedArg); } } else { if (arg[0] == '-') { throw new CommandLineArgumentsException($"Option '{option}' required a value."); } else { object value = ParseValue(property.PropertyType, arg, culture); property.SetValue(result, value); property = null; } } } } if (property != null) { if (IsArrayLike(property)) { EndArray(property, result, parsedArgs); } else { throw new CommandLineArgumentsException($"Option '{option}' required a value."); } } return result; } /// <summary> /// Generate a help page for the given type. /// </summary> /// <typeparam name="T">Type of which to create a help page.</typeparam> /// <returns>A help page as a string.</returns> public static string GetHelpPage<T>() => GetHelpPage(typeof(T)); /// <summary> /// Generate a help page for the given type. /// </summary> /// <typeparam name="T">Type of which to create a help page.</typeparam> /// <param name="programName">The name of the program in the console.</param> /// <returns>A help page as a string.</returns> public static string GetHelpPage<T>(string programName) => GetHelpPage(typeof(T), programName); /// <summary> /// Generate a help page for the given type. /// </summary> /// <param name="type">Type of which to create a help page.</param> /// <returns>A help page as a string.</returns> public static string GetHelpPage(Type type) => GetHelpPage(type, Environment.GetCommandLineArgs()[0]); /// <summary> /// Generate a help page for the given type. /// </summary> /// <param name="type">Type of which to create a help page.</param> /// <param name="programName">The name of the program in the console.</param> /// <returns>A help page as a string.</returns> public static string GetHelpPage(Type type, string programName) { if (type == null) { throw new ArgumentNullException(nameof(type)); } PropertyInfo[] properties = type.GetProperties(); List<string> options = new List<string>(); List<string> arguments = new List<string>(); List<string> descriptions = new List<string>(); List<string> unnamedArgs = new List<string>(); for (int i = 0; i < properties.Length; i++) { PropertyInfo property = properties[i]; UnnamedAttribute unnamed = property.GetCustomAttribute<UnnamedAttribute>(); if (unnamed != null) { unnamedArgs.Add(GetArgumentName(property)); } else { StringBuilder aliases = new StringBuilder(); aliases.Append($"-{property.Name}"); AliasAttribute aliasAttribute = property.GetCustomAttribute<AliasAttribute>(); if (aliasAttribute != null) { foreach (string alias in aliasAttribute.Aliases) { aliases.Append($" -{alias}"); } } DescriptionAttribute descAttr = property.GetCustomAttribute<DescriptionAttribute>(); options.Add(aliases.ToString()); arguments.Add(GetArgumentName(property)); descriptions.Add(descAttr == null ? string.Empty : descAttr.Text); } } int optionsLength = options.Max(x => x.Length); int argumentsLength = arguments.Max(x => x.Length); StringBuilder help = new StringBuilder(); DescriptionAttribute classDescAttr = type.GetCustomAttribute<DescriptionAttribute>(); if (classDescAttr != null && classDescAttr.Text != null) { help.AppendLine(classDescAttr.Text); } help.AppendLine($"Usage: {programName} [options] {string.Join(" ", unnamedArgs.Select(x => $"[{x}]"))}".Trim()); help.AppendLine("Options:"); for (int i = 0; i < options.Count; i++) { help.Append(" ").AppendLine($"{GetTextWithFiller(options[i], optionsLength + 4)}{GetTextWithFiller(arguments[i], argumentsLength + 4)}{descriptions[i]}".Trim()); } return help.ToString(); } private static string GetTextWithFiller(string text, int size) { StringBuilder sb = new StringBuilder(); sb.Append(text); for (int i = 0; i < size - text.Length; i++) { sb.Append(' '); } return sb.ToString(); } private static string GetArgumentName(PropertyInfo property) { ArgumentNameAttribute attribute = property.GetCustomAttribute<ArgumentNameAttribute>(); if (IsArrayLike(property)) { Type type = GetArrayLikeElementType(property); return $"{GetArgumentName(type, attribute, "1")} {GetArgumentName(type, attribute, "2")} ..."; } return GetArgumentName(property.PropertyType, attribute, string.Empty); } private static string GetArgumentName(Type type, ArgumentNameAttribute attribute, string suffix) { if (type == typeof(bool)) { return string.Empty; } if (type.IsEnum) { return string.Join("|", Enum.GetNames(type)); } if (attribute != null) { return $"<{attribute.Name}{suffix}>"; } return $"<{type.Name}{suffix}>"; } private static Type GetArrayLikeElementType(PropertyInfo property) { Type type = property.PropertyType; if (type.IsArray) { return type.GetElementType(); } return type.GetGenericArguments()[0]; } private static bool IsArrayLike(PropertyInfo property) { Type type = property.PropertyType; return type.IsArray || type.GetInterface("ICollection`1") != null; } private static void EndArray(PropertyInfo property, object result, List<object> parsedArgs) { object value; if (property.PropertyType.IsArray) { Type elementType = GetArrayLikeElementType(property); value = Array.CreateInstance(elementType, parsedArgs.Count); Array array = value as Array; for (int i = 0; i < array.Length; i++) { array.SetValue(parsedArgs[i], i); } } else { value = Activator.CreateInstance(property.PropertyType); MethodInfo add = property.PropertyType.GetMethod("Add"); foreach (object parsedArg in parsedArgs) { add.Invoke(value, new[] { parsedArg }); } } property.SetValue(result, value); parsedArgs.Clear(); } private static string[] SplitArgs(string args) => args?.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); private static Dictionary<string, PropertyInfo> CreateAliasMap(Type type) { Dictionary<string, PropertyInfo> options = new Dictionary<string, PropertyInfo>(); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { AddProperty(options, property.Name, property); AliasAttribute aliasAttribute = property.GetCustomAttribute<AliasAttribute>(); if (aliasAttribute != null) { foreach (string alias in aliasAttribute.Aliases) { AddProperty(options, alias, property); } } } return options; } private static PropertyInfo[] CreateUnnamedMap(Type type) => type.GetProperties() .Where(x => x.GetCustomAttribute<UnnamedAttribute>() != null) .OrderBy(x => x.GetCustomAttribute<UnnamedAttribute>().Order) .ToArray(); private static void AddProperty(Dictionary<string, PropertyInfo> options, string name, PropertyInfo property) { string key = name.ToUpperInvariant(); if (options.ContainsKey(key)) { throw new CommandLineArgumentsException($"Key '{name}' is used multiple times."); } options.Add(key, property); } [SuppressMessage("Layout", "SA1503", Justification = "Readability.")] private static object ParseValue(Type type, string value, CultureInfo culture) { if (type == typeof(string)) return value; else if (type == typeof(char)) return char.Parse(value); else if (type == typeof(byte)) return byte.Parse(value, culture); else if (type == typeof(sbyte)) return sbyte.Parse(value, culture); else if (type == typeof(short)) return short.Parse(value, culture); else if (type == typeof(ushort)) return ushort.Parse(value, culture); else if (type == typeof(int)) return int.Parse(value, culture); else if (type == typeof(uint)) return uint.Parse(value, culture); else if (type == typeof(long)) return long.Parse(value, culture); else if (type == typeof(ulong)) return ulong.Parse(value, culture); else if (type == typeof(float)) return float.Parse(value, culture); else if (type == typeof(double)) return double.Parse(value, culture); else if (type == typeof(decimal)) return decimal.Parse(value, culture); else if (type.IsEnum) return Enum.Parse(type, value, true); throw new CommandLineArgumentsException($"There is no support for arguments of type '{type.Name}'."); } } }
d0601b2d95105b7b6bfe3fd8e1d0c18f66ddce10
C#
terry-u16/AtCoder
/Nomura2020/Nomura2020/Nomura2020/Questions/QuestionD.cs
2.8125
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Nomura2020.Algorithms; using Nomura2020.Collections; using Nomura2020.Extensions; using Nomura2020.Numerics; using Nomura2020.Questions; namespace Nomura2020.Questions { public class QuestionD : AtCoderQuestionBase { public override IEnumerable<object> Solve(TextReader inputStream) { var townsCount = inputStream.ReadInt(); var plan = inputStream.ReadIntArray().Select(i => i - 1).ToArray(); int baseRoads = 0; var unionFind = new UnionFindTree(townsCount); for (int town = 0; town < plan.Length; town++) { if (plan[town] >= 0 && !unionFind.IsInSameGroup(town, plan[town])) { unionFind.Unite(town, plan[town]); baseRoads++; } } var parents = new int[townsCount]; for (int i = 0; i < parents.Length; i++) { parents[i] = unionFind.GetRootOf(i); } var roots = parents.Distinct().ToArray(); var dictionary = new Dictionary<int, int>(); foreach (var group in parents.GroupBy(i => i)) { dictionary[group.Key] = group.Count(); } for (int i = 0; i < roots.Length; i++) { for (int j = i + 1; j < roots.Length; j++) { } } } } }
95c7eb246da118edc37a1a11a5f88e7d7ec1e9a0
C#
lhorsager/XamarinLocalStorage
/XamarinLocalStorage/XamarinLocalStorage/FileIO/FileIOController.cs
2.5625
3
/* * Example from Xamarin * http://docs.xamarin.com/samples/FileSystemSampleCode/ * * */ using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace XamarinLocalStorage { public class FileIOController : UIViewController { UIButton btnFiles, btnDirectories, btnAll, btnWrite, btnDirectory, btnAllDocs; UITextView txtView; public FileIOController () { this.Title = "IO"; this.View.BackgroundColor = ColorConverter.ConvertFromString ("BFDFFF"); } public override void ViewDidLoad () { //TITLE UILabel lblTitle = new UILabel (new RectangleF (0, 30, 1024, 35)); lblTitle.Text = "File IO"; lblTitle.TextAlignment = UITextAlignment.Center; lblTitle.Font = UIFont.FromName ("Optima-Bold", 24); this.View.AddSubview (lblTitle); // Create the buttons and TextView to run the sample code btnFiles = UIButton.FromType(UIButtonType.RoundedRect); btnFiles.Frame = new RectangleF(20,50,145,50); btnFiles.SetTitle("Open 'ReadMe.txt'", UIControlState.Normal); btnDirectories = UIButton.FromType(UIButtonType.RoundedRect); btnDirectories.Frame = new RectangleF(20,110,145,50); btnDirectories.SetTitle("List Directories", UIControlState.Normal); btnAllDocs = UIButton.FromType(UIButtonType.RoundedRect); btnAllDocs.Frame = new RectangleF(175,50,145,50); btnAllDocs.SetTitle("All Docs", UIControlState.Normal); btnAll = UIButton.FromType(UIButtonType.RoundedRect); btnAll.Frame = new RectangleF(175,110,145,50); btnAll.SetTitle("List All", UIControlState.Normal); btnWrite = UIButton.FromType(UIButtonType.RoundedRect); btnWrite.Frame = new RectangleF(20,170,145,50); btnWrite.SetTitle("Write File", UIControlState.Normal); btnDirectory = UIButton.FromType(UIButtonType.RoundedRect); btnDirectory.Frame = new RectangleF(175,170,145,50); btnDirectory.SetTitle("Create Directory", UIControlState.Normal); txtView = new UITextView(new RectangleF(20, 230, 900, 450)); txtView.Editable = false; txtView.ScrollEnabled = true; // Wire up the buttons to the SamplCode class methods btnFiles.TouchUpInside += (sender, e) => { txtView.Text = ""; // Sample code from the article var text = System.IO.File.ReadAllText("FileIO/ReadMe.txt"); // Output to app UITextView txtView.Text = text; }; btnDirectories.TouchUpInside += (sender, e) => { txtView.Text = ""; // Sample code from the article var directories = Directory.EnumerateDirectories("./"); // Output to app UITextView foreach (var directory in directories) { txtView.Text += directory + Environment.NewLine; } }; btnAllDocs.TouchUpInside += (sender, e) => { txtView.Text = ""; // Sample code from the article var docs = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); var fileOrDirectory = Directory.EnumerateFileSystemEntries(docs); foreach (var entry in fileOrDirectory) { Console.WriteLine(entry); } // Output to app UITextView foreach (var entry in fileOrDirectory) { txtView.Text += entry + Environment.NewLine; } }; btnAll.TouchUpInside += (sender, e) => { txtView.Text = ""; // Sample code from the article var fileOrDirectory = Directory.EnumerateFileSystemEntries("./"); foreach (var entry in fileOrDirectory) { Console.WriteLine(entry); } // Output to app UITextView foreach (var entry in fileOrDirectory) { txtView.Text += entry + Environment.NewLine; } }; btnWrite.TouchUpInside += (sender, e) => { // Sample code from the article var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); var filename = Path.Combine (documents, "Write.txt"); File.WriteAllText(filename, "Write this text into a file!"); // Output to app UITextView txtView.Text = "Text was written to a file." + Environment.NewLine + "-----------------" + Environment.NewLine + System.IO.File.ReadAllText(filename); }; btnDirectory.TouchUpInside += (sender, e) => { // Sample code from the article var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); var directoryname = Path.Combine (documents, "NewDirectory"); Directory.CreateDirectory(directoryname); // Output to app UITextView txtView.Text = "A directory was created." + Environment.NewLine + "-----------------" + Environment.NewLine + directoryname; }; // Add the controls to the view this.Add(btnFiles); this.Add(btnDirectories); this.Add (btnAllDocs); this.Add(btnAll); this.Add(btnWrite); this.Add(btnDirectory); this.Add(txtView); // Write out this special folder, just for curiousity's sake Console.WriteLine("MyDocuments:"+Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); } } }
1dc7cfede9ee04704e7e31e23803531985eda4a2
C#
JacobVerona/HelicopterAttack3d
/Assets/Scripts/Global/RectTransfromUtilityExtention.cs
2.546875
3
using HelicopterAttack.Global; using UnityEngine; namespace HelicopterAttack.Global { public static class RectTransfromUtilityExtention { public static Vector2 WorldPositionToRectLocalPosition( Vector3 centerWorldPosition, Vector3 targetPosition, float scale) { var pos = targetPosition - centerWorldPosition; return pos.ToVector2XZ() * scale; } public static Vector2 WorldPositionToRectLocalPositionClampedInRect( Vector3 centerWorldPosition, Vector3 targetPosition, Rect clampRect, float scale) { var pos = targetPosition - centerWorldPosition; var resultPosition = pos.ToVector2XZ() * scale; resultPosition = new Vector2(Mathf.Clamp(resultPosition.x, clampRect.min.x, clampRect.max.x), Mathf.Clamp(resultPosition.y, clampRect.min.y, clampRect.max.y)); return resultPosition; } } }
0a6d14b1be3e56b832f22dba4de0e5c72ebc3340
C#
wangzhilinet/web_csharp_sqlserver
/fishercommunity/App_Code/DAL/Class1.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using System.Data; /// <summary> ///Class1 的摘要说明 /// </summary> public class Class1 { private static string connStr = "server=.;database=test;uid=sa;pwd=123"; private SqlConnection conn = new SqlConnection(connStr); private SqlCommand cmd = null; private SqlDataAdapter da = null; public DataTable dtbysql(string sql) { da = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable(); da.Fill(dt); return dt; } public int exbysql(string sql) { cmd = new SqlCommand(sql, conn); conn.Open(); int num = cmd.ExecuteNonQuery(); conn.Dispose(); conn.Close(); return num; } }
59217e05bd55d233171e4d053b20fb887a1fcd5c
C#
l42111996/kcp4sharp
/kcp4sharp/KcpClient.cs
2.6875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.IO; namespace cocosocket4unity { /// <summary> /// kcp客戶端程序 /// </summary> public abstract class KcpClient : KcpOnUdp { protected volatile bool running; /// <summary> /// kcp,随机分配一个端口 /// </summary> public KcpClient():base(0) { } /// <summary> /// 初始化kcp /// </summary> /// <param name="port">监听端口</param> /// public KcpClient(int port):base(port) { } /// <summary> /// 是否在运行状态 /// </summary> /// <returns></returns> public bool IsRunning() { return this.running; } /// <summary> /// 停止udp /// </summary> public void Stop() { if(running) { running = false; try { this.client.Close(); }catch (Exception ex) { } } } protected override void HandleException(Exception ex) { this.Stop(); } protected override void HandleTimeout() { this.Stop(); } /// <summary> /// 开启线程开始工作 /// </summary> public void Start() { if (!this.running) { this.running = true; Thread t = new Thread(new ThreadStart(run));//状态更新 t.IsBackground = true; t.Start(); } } private void run() { while (running) { DateTime st = DateTime.Now; this.Update(); if (this.needUpdate) { continue; } DateTime end = DateTime.Now; while ((end - st).TotalMilliseconds < 10) { if (this.needUpdate) { break; } Thread.Sleep(0); end = DateTime.Now; } } } } }
e551e7b28ffd9d17ae07ae2d619934db5622c0bf
C#
Myvar/Eclang
/Src/Eclang/ECLang/BuildInTypes/EcByte.cs
2.78125
3
using System.Collections.Generic; using System.Text.RegularExpressions; namespace ECLang.BuildInTypes { using ECLang.BuildInTypes.Base; public class EcByte : EcBuiltInType { public static EcByte Null { get { return new EcByte() { value = "0" }; } } public static explicit operator int(EcByte i) { return int.Parse(i.value); } public static explicit operator EcByte(int i) { return Parse(i.ToString()); } private string value; public static bool IsValid(string s) { var pattern = @"[0-255]"; return Regex.IsMatch(s, pattern); } public static EcByte Parse(string s) { if (IsValid(s)) return new EcByte() { value = s }; return Null; } public static bool TryParse(string s, out EcByte num) { var valid = IsValid(s); num = Parse(s); return valid; } public override string ToString() { return this.value; } public override object call(string data, List<object> perams) { throw new System.NotImplementedException(); } //ToDo: add more functions } }
795482d35e3dcf215c3c9479cb0c3755c5b80e20
C#
EmanuelMoldovan/PSSC-2017
/Turcian Darius/CURS/TEMA2/DariusDDD/DariusDDD/Infrastructure/CalculatorManager.cs
3.46875
3
using System; namespace DariusDDD.Infrastructure { public class CalculatorManager { private readonly decimal _fuelValue; private readonly decimal _powerValue; private readonly decimal _yearValue; private readonly decimal _price; public CalculatorManager(decimal price, int power, int year, string fuel) { _price = price; _fuelValue = (fuel == "diesel") ? 2.5m : (fuel == "benzine") ? 1 : -1; if(_fuelValue == -1) throw new Exception("Fuel Error"); _powerValue = Convert.ToDecimal(power / 10); _yearValue = Convert.ToDecimal((DateTime.Now.Year - year) / 3); } public decimal CalculateTax() { return (2m / 100 * _price) * _fuelValue + (4m / 100 * _price) * _yearValue + _powerValue; } } }
ce3484163ad7f70bd02f37202bfe8a5d6f9089bd
C#
Shushoto/Breeze
/code/Breeze.Core/Services/PlayersService.cs
2.6875
3
using System; using System.Collections.Generic; using System.Threading; using Breeze.Model.DataObjects; namespace Breeze.Core.Services { public class PlayersService : IPlayersService, IDisposable { private readonly IIDService _idService; private readonly PlayersData _allPlayers = new PlayersData(); private readonly TimeSpan _timeoutPlayersPeriod = TimeSpan.FromSeconds(5); // todo change this private readonly Timer _timer; public PlayersService(IIDService idService) { _idService = idService; _timer = new Timer(CleanTimeoutPlayers, null, 0, (int)_timeoutPlayersPeriod.TotalMilliseconds); } private void CleanTimeoutPlayers(object state) { lock (_allPlayers) { foreach (var player in _allPlayers.PlayersCopy) { if (DateTime.Now.Subtract(player.LastPingReceived).CompareTo(_timeoutPlayersPeriod) > 0) _allPlayers.RemovePlayer(player.Id); } } } public int RegisterNewPlayer(string nick) { var id = _idService.CreateID(); var playerData = new PlayerData(nick, id); lock (_allPlayers) _allPlayers.AddPlayer(playerData); return id; } public ICollection<PlayerData> GetPlayersInLobby() { lock (_allPlayers) return _allPlayers.PlayersCopy; } public void PingReceived(int id) { PlayerData player; lock (_allPlayers) { player = _allPlayers.Get(id); } if (player == null) return; player.LastPingReceived = DateTime.Now; } public PlayerData Get(int id) { lock (_allPlayers) return _allPlayers.Get(id); } public PlayersData GetPlayersInDraft(int draftId) { throw new NotImplementedException(); } public void Dispose() { _timer.Dispose(); } } }
61d69c3599db5dc39cba8c255c199ec88d08cfc7
C#
StureTh/ec_utbildning
/ec_utbildning/MediaLib/MediaLib/Movie.cs
3.109375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MediaLib { class Movie:Media { public string Director { get; set; } public Movie(string name="",string genre="",int year=0,string publisher="",string director=""):base(name,genre,year,publisher) { this.Director = director; } public void PrintDirector() { Console.WriteLine("Director: {0}",Director); } } }
dbda685673cd0c32a675f905142784fab0ec52d2
C#
tiaofu/tsdn.MS
/src/(V)NetCore/IMS/tsdn.Core/tsdn.Common.Core/TypeManager.cs
2.75
3
/********************************************************* * CopyRight: tiaoshuidenong. * Author: tiaoshuidenong * Address: wuhan * Create: 2018-04-10 17:44:16 * Modify: 2018-04-10 17:44:16 * Blog: http://www.cnblogs.com/tiaoshuidenong/ * Description: ef管理 *********************************************************/ using System; using System.Collections.Generic; namespace tsdn.Common { /// <summary> /// 类型管理 /// </summary> public class TypeManager { /// <summary> /// 使用实例 /// </summary> public static readonly TypeManager Instance = new TypeManager(); private readonly ISet<Type> _typeSet = new HashSet<Type>(); public ISet<Type> TypeSet { get { return _typeSet; } } /// <summary> /// 注册类型 /// </summary> /// <param name="type">The type.</param> public void RegisterType(Type type) { TypeSet.Add(type); } /// <summary> /// 注册类型 /// </summary> /// <typeparam name="T"></typeparam> public void RegisterType<T>() where T: class, new() { RegisterType(typeof(T)); } } }
388a3b03b0a367877ee5297acf77af5c97c3ecf3
C#
hackerlank/TraderClientTest
/ConsoleApplication8/ConsoleApplication8/ThreadDemo.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication8 { public class ThreadDemo { private readonly object objBlock = new object(); public void Call1() { lock (this.objBlock) { Console.WriteLine("Step1"); ThreadPool.QueueUserWorkItem(o => { lock (this.objBlock) { Console.WriteLine("Step2"); } }); Console.ReadLine(); } } } }
9ab14d1a9e6ab9d20948069f44cf39d54fd99ec1
C#
moneymakermaster2010/MyPersonalProject
/EntityFramework/src/EntityFramework/Migrations/Model/DropTableOperation.cs
2.6875
3
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Migrations.Model { using System.Data.Entity.Utilities; using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents dropping an existing table. /// </summary> public class DropTableOperation : MigrationOperation { private readonly string _name; private readonly CreateTableOperation _inverse; /// <summary> /// Initializes a new instance of the DropTableOperation class. /// </summary> /// <param name="name"> The name of the table to be dropped. </param> /// <param name="anonymousArguments"> Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'. </param> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public DropTableOperation(string name, object anonymousArguments = null) : base(anonymousArguments) { Check.NotEmpty(name, "name"); _name = name; } /// <summary> /// Initializes a new instance of the DropTableOperation class. /// </summary> /// <param name="name"> The name of the table to be dropped. </param> /// <param name="inverse"> An operation that represents reverting dropping the table. </param> /// <param name="anonymousArguments"> Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'. </param> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public DropTableOperation(string name, CreateTableOperation inverse, object anonymousArguments = null) : this(name, anonymousArguments) { Check.NotNull(inverse, "inverse"); _inverse = inverse; } /// <summary> /// Gets the name of the table to be dropped. /// </summary> public virtual string Name { get { return _name; } } /// <summary> /// Gets an operation that represents reverting dropping the table. /// The inverse cannot be automatically calculated, /// if it was not supplied to the constructor this property will return null. /// </summary> public override MigrationOperation Inverse { get { return _inverse; } } /// <inheritdoc /> public override bool IsDestructiveChange { get { return true; } } } }
00e77f4dce52abcd52e4d2d21879b801949ee37d
C#
bausshf/Wordgorithm
/Source/WordBuilder.cs
3.46875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wordgorithm { /// <summary> /// A word builder that can be used to construct sentences etc. /// </summary> public sealed class WordBuilder { /// <summary> /// Collection of the current word sequence. /// </summary> private List<WordInstance> _wordSequence; /// <summary> /// The trainer data associated with the word builder. /// </summary> private WordTrainer _trainer; /// <summary> /// The current word instance. /// </summary> private WordInstance _currentWord; /// <summary> /// The minimum words of the builder. /// </summary> private int _minWords; /// <summary> /// The maximum words of the builder. /// </summary> private int _maxWords; /// <summary> /// Creates a new word builder. /// </summary> /// <param name="trainer">The trainer that holds the training data.</param> /// <param name="minWords">The minimum words a sentence must contain.</param> /// <param name="maxWords">The maximum words a sentence must contain. This is only approximate and it might still contain more words.</param> public WordBuilder(WordTrainer trainer, int minWords, int maxWords) { _wordSequence = new List<WordInstance>(); _trainer = trainer; _minWords = minWords; _maxWords = maxWords; } /// <summary> /// Boolean determining whether the builder has reached the end of the sequence when generating. /// </summary> public bool EndOfSequence { get; private set; } /// <summary> /// The current symbol wrapper instance. /// </summary> private WordInstance _wrapperInstance; /// <summary> /// The amount of tries when building. /// </summary> private int _tries; /// <summary> /// Generates the next word or symbol in the sequence. /// </summary> /// <param name="selectUntilEndSymbol">Boolean determining whether it should select until the end symbol only.</param> /// <param name="includeEndSymbol">Boolean determining whether it should include the end symbol too.</param> /// <returns>The word builder allowing for chaining.</returns> public WordBuilder Next(bool selectUntilEndSymbol = true, bool includeEndSymbol = true) { if (_tries > 10) { EndOfSequence = true; _wordSequence.Clear(); return this; } if (EndOfSequence) { return this; } if (_currentWord == null) { _currentWord = _trainer.SelectStartWord(); if (_currentWord == null) { EndOfSequence = true; return this; } } else { _currentWord = _currentWord.Word.SelectWord(); if (_currentWord == null) { EndOfSequence = true; return this; } } if (_currentWord.SymbolType == SymbolType.Wrapper && string.IsNullOrWhiteSpace(_currentWord.SymbolWrapperEnd)) { _tries++; return Next(selectUntilEndSymbol, includeEndSymbol); } if (selectUntilEndSymbol && _currentWord.SymbolType == SymbolType.End) { if (includeEndSymbol || _wrapperInstance != null) { _wordSequence.Add(_currentWord); } if (_wrapperInstance != null) { _wordSequence.Add(_wrapperInstance); } EndOfSequence = true; } else { if (_wrapperInstance != null && _currentWord.SymbolType == SymbolType.Wrapper && _wrapperInstance.SymbolWrapperEnd == _currentWord.Word.Word) { _wrapperInstance = null; } else if (_currentWord.SymbolType == SymbolType.Wrapper) { _wrapperInstance = _currentWord; } _wordSequence.Add(_currentWord); } return this; } /// <summary> /// Converts the first character of a string to upper. /// </summary> /// <param name="s">The string.</param> /// <returns>Returns the new string.</returns> private static string FirstToUpper(string s) { return s.Substring(0, 1).ToUpper() + s.Substring(1); } /// <summary> /// Generates the sequence. /// </summary> /// <param name="selectUntilEndSymbol">Boolean determining whether it should select until the end symbol only.</param> /// <param name="includeEndSymbol">Boolean determining whether it should include the end symbol too.</param> private void Generate(bool selectUntilEndSymbol, bool includeEndSymbol) { var brain = this; do { brain = Next(selectUntilEndSymbol, includeEndSymbol); } while (!EndOfSequence && _wordSequence.Count(w => w.SymbolType == SymbolType.None) < _maxWords); } /// <summary> /// Converts the sequence of the builder to a constructed string. /// </summary> /// <returns>Returns the constructed string.</returns> public override string ToString() { return ToString(selectUntilEndSymbol: true, includeEndSymbol: true); } /// <summary> /// Converts the sequence of the builder to a constructed string. /// </summary> /// <param name="selectUntilEndSymbol">Boolean determining whether it should select until the end symbol only.</param> /// <param name="includeEndSymbol">Boolean determining whether it should include the end symbol too.</param> /// <returns>Returns the constructed string.</returns> public string ToString(bool selectUntilEndSymbol, bool includeEndSymbol) { if (_tries > 10) { return null; } if (_wordSequence.Count(w => w.SymbolType == SymbolType.None) > _maxWords) { _maxWords = Math.Min(_wordSequence.Count, _maxWords); for (var i = 0; i < _maxWords; i++) { var word = _wordSequence[i]; var nextWord = i < (_maxWords - 1) ? _wordSequence[i + 1] : null; if (word.SymbolType == SymbolType.Wrapper && string.IsNullOrWhiteSpace(word.SymbolWrapperEnd)) { _wordSequence = _wordSequence.Take(i + 1).ToList(); break; } else if (word.SymbolType == SymbolType.End && (nextWord == null || !(nextWord.SymbolType == SymbolType.Wrapper && string.IsNullOrWhiteSpace(nextWord.SymbolWrapperEnd)))) { _wordSequence = _wordSequence.Take(i + 1).ToList(); break; } } } if (_wordSequence.Count(w => w.SymbolType == SymbolType.None) < _minWords) { _wordSequence.Clear(); EndOfSequence = false; _currentWord = null; _wrapperInstance = null; Generate(selectUntilEndSymbol, includeEndSymbol); _tries++; return ToString(selectUntilEndSymbol, includeEndSymbol); } var result = new StringBuilder(); for (var i = 0; i < _wordSequence.Count; i++) { var word = _wordSequence[i]; var nextWord = i < (_wordSequence.Count - 1) ? _wordSequence[i + 1] : null; switch (word.SymbolType) { case SymbolType.Spacing: result.AppendFormat(" {0} ", word.Word.Word); break; case SymbolType.Combinator: case SymbolType.Separator: case SymbolType.Wrapper: result.AppendFormat("{0}", word.Word.Word); break; case SymbolType.End: case SymbolType.EndSeparator: case SymbolType.None: default: if (nextWord != null && (nextWord.SymbolType == SymbolType.End || nextWord.SymbolType == SymbolType.EndSeparator || nextWord.SymbolType == SymbolType.Combinator)) { result.AppendFormat("{0}", word.Word.Word); } else if (nextWord != null && nextWord.SymbolType == SymbolType.Wrapper && word.SymbolType == SymbolType.End) { result.AppendFormat("{0}", word.Word.Word); } else { result.AppendFormat("{0} ", word.Word.Word); } break; } } return FirstToUpper(result.ToString().Trim()); } } }
c58a266bbcc6dd22a3dcc7bd5eb03111128246e4
C#
tomitrescak/EI3
/Ei/Ei/Runtime/VariableDefinition.cs
2.65625
3
using Ei.Ontology; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace Ei.Runtime { public enum VariableAccess { Public, Protected, Private } public interface IVariableDefinition { string Name { get; } object DefaultValue { get; } VariableAccess Access { get; } bool CanAccess(Group[] groups, VariableState state); object Value(VariableState state); void Update(VariableState state, object value); void Parse(VariableState state, string value); } public class Variable : System.Attribute { public object DefaultValue { get; set; } public VariableAccess Access { get; set; } public Variable(VariableAccess access, object defaultValue = null) { this.Access = access; this.DefaultValue = defaultValue; } } public struct VariableDefinition<T, V> : IVariableDefinition where V : VariableState { public string Name { get; private set; } public VariableAccess Access { get; private set; } public T Default; public delegate T ParseDelegate(string value); private Func<V, T> selector; private Action<V, T> updater; private ParseDelegate parser; public VariableDefinition(VariableState state, string name) : this(state, name, default(T), VariableAccess.Public) { } public VariableDefinition(VariableState state, string name, T defaultValue, VariableAccess access = VariableAccess.Public) { this.Name = name; this.Access = access; this.Default = defaultValue; var parameter = typeof(V).GetProperty(name); this.selector = BuildTypedGetter(parameter); this.updater = BuildTypedSetter(parameter); // find parse method MethodInfo parseMethod = typeof(T).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string) }, null); if (parseMethod != null) { this.parser = (ParseDelegate)Delegate.CreateDelegate(typeof(ParseDelegate), parseMethod); } else if (typeof(T) == typeof(String)) { this.parser = Identity; } else { this.parser = null; // throw new Exception("DataType needs to define a Parse method"); } // find custom attributes foreach (var ca in parameter.GetCustomAttributes(false)) { var variable = ca as Variable; if (variable != null) { this.Access = variable.Access; if (variable.DefaultValue != null) { if (state == null) { throw new Exception("You need to provide state to store the default value"); } this.Default = (T)variable.DefaultValue; this.Update(state, variable.DefaultValue); } } } } public VariableDefinition(string name, VariableAccess access, T defaultValue, ParseDelegate parser, Func<V, T> selector, Action<V, T> updater = null) { this.Name = name; this.Access = access; this.Default = defaultValue; this.selector = selector; this.updater = updater; this.parser = parser; } public object DefaultValue { get { return this.Default; } } public T TypedDefaultValue { get { return this.Default; } } public object Value(VariableState state) { return this.Value((V)state); } public object Value(V state) { return this.selector(state); } public bool CanAccess(Group[] groups, VariableState state) { if (this.Access == VariableAccess.Protected) { throw new NotImplementedException(); } return this.Access == VariableAccess.Public; // || this.Access.CanAccess(groups, state); } public void Update(VariableState state, object value) { this.Update((V)state, (T)value); } public void Update(V state, object value) { this.updater(state, (T)value); } public void Parse(VariableState state, string value) { this.Parse((V)state, value); } public void Parse(V state, string value) { this.updater(state, this.parser(value)); } public T Parse(string value) { return this.parser(value); } public static T Identity(object value) { return (T)value; } public static Action<V, T> BuildTypedSetter(PropertyInfo propertyInfo) { var targetType = propertyInfo.DeclaringType; var methodInfo = propertyInfo.GetSetMethod(); if (methodInfo == null) { return null; } var exTarget = Expression.Parameter(targetType, "t"); var exValue = Expression.Parameter(typeof(T), "p"); var exBody = Expression.Call(exTarget, methodInfo, Expression.Convert(exValue, propertyInfo.PropertyType)); var lambda = Expression.Lambda<Action<V, T>>(exBody, exTarget, exValue); var action = lambda.Compile(); return action; } public static Func<V, T> BuildTypedGetter(PropertyInfo propertyInfo) { var targetType = propertyInfo.DeclaringType; var methodInfo = propertyInfo.GetGetMethod(); var returnType = methodInfo.ReturnType; var exTarget = Expression.Parameter(targetType, "t"); var exBody = Expression.Call(exTarget, methodInfo); var exBody2 = Expression.Convert(exBody, typeof(T)); var lambda = Expression.Lambda<Func<V, T>>(exBody2, exTarget); var action = lambda.Compile(); return action; } } }
95b65a887c800e1e6afff2a9658ce03ebd1057c8
C#
ange-arthur/POO-Basis
/Properties.cs
3.25
3
using System; using System.Collections.Generic; using System.Text; namespace POO_Basis { class Properties { public readonly DateTime _dateDeNaissance; public string Nom { get; set; } public string Prenom { get; set; } public int Age { get { var ageref = DateTime.Now - _dateDeNaissance; return (ageref.Days / 365); } private set { } } public Properties(DateTime DateNaissance) { _dateDeNaissance = DateNaissance; } public void AfficherInfo() { Console.WriteLine("Nom : {0}", Nom); Console.WriteLine("Prenom : {0}", Prenom); Console.WriteLine("Date de naissance : {0}", _dateDeNaissance.ToShortDateString()); Console.WriteLine("Age : {0}", Age); } } }
02dd97d9cc15924cdeec19d53bbe3784a8f205b5
C#
gleblebedev/UrhoSharpToolkit
/src/UrhoSharp.Prefabs/AbstractComponentPrefab.cs
2.609375
3
using System; using System.Xml.Linq; using Urho; namespace UrhoSharp.Prefabs { public abstract class AbstractComponentPrefab<T> : AbstractPrefab, IComponentPrefab where T : Component { public abstract string TypeName { get; } object IPrefab.Create() { return Create(); } public virtual uint? ID { get; set; } public abstract T Create(); public virtual void ParseXml(XElement element) { foreach (var childElement in element.Elements()) if (childElement.Name == XmlElement.Attribute) { var name = childElement.Attribute(XmlAttribute.Name)?.Value; var value = childElement.Attribute(XmlAttribute.Value)?.Value; if (!string.IsNullOrWhiteSpace(name)) ParseXmlAttribute(name, value); } } public virtual XElement SerializeToXml() { var element = new XElement(XmlElement.Component); element.SetAttributeValue(XmlAttribute.Type, TypeName); foreach (var property in Properties) { if (property.PrefabHasValue(this)) { var value = property.ToStringPrefab(this); element.Add(new XElement(XmlElement.Attribute, new XAttribute(XmlAttribute.Name, property.Name), new XAttribute(XmlAttribute.Value, value))); } } return element; } public abstract void ParseXmlAttribute(string name, string value); protected static class XmlElement { public static readonly XName Component = XName.Get("component"); public static readonly XName Attribute = XName.Get("attribute"); } protected static class XmlAttribute { public static readonly XName Type = XName.Get("type"); public static readonly XName Name = XName.Get("name"); public static readonly XName Value = XName.Get("value"); } } }
78ea9680f4fd3e1fbf4cd8e332fe67a72b928d52
C#
pphuppertz/SimpleDllProjectToTestTeamCity
/SimpleDllProjectToTestTeamCity/Class1.cs
2.578125
3
using System; namespace SimpleDllProjectToTestTeamCity { public class Person { public string Name { get; set; } public DateTime BirthDate { get; set; } public int AgeInDays { get { return (DateTime.Today - BirthDate).Days; } } } }
7780124a93eaa2ad0f7ae2f46efdc17973e5ce5b
C#
msadeqshajary/graphql-aspnet
/src/graphql-aspnet-subscriptions/Execution/Subscriptions/SubscriptionEventName.cs
2.65625
3
// ************************************************************* // project: graphql-aspnet // -- // repo: https://github.com/graphql-aspnet // docs: https://graphql-aspnet.github.io // -- // License: MIT // ************************************************************* namespace GraphQL.AspNet.Execution.Subscriptions { using System; using System.Collections.Generic; using System.Diagnostics; using GraphQL.AspNet.Common; using GraphQL.AspNet.Common.Extensions; using GraphQL.AspNet.Interfaces.Schema.TypeSystem; using GraphQL.AspNet.Interfaces.TypeSystem; /// <summary> /// A qualified subscription name representing both the unique path in a schema /// and the optional short name of said subscription event. /// </summary> [DebuggerDisplay("Event Name: {EventName}")] public class SubscriptionEventName { /// <summary> /// Creates a set of event names representing all the possible forms of the event as defined /// by the grpah field. /// </summary> /// <typeparam name="TSchema">The type of the schema the graph field exists in.</typeparam> /// <param name="field">The field to create names for.</param> /// <returns>IEnumerable&lt;SubscriptionEventName&gt;.</returns> public static IEnumerable<SubscriptionEventName> FromGraphField<TSchema>(ISubscriptionGraphField field) where TSchema : class, ISchema { Validation.ThrowIfNull(field, nameof(field)); return SubscriptionEventName.FromSchemaTypeAndField(typeof(TSchema), field); } /// <summary> /// Creates a set of event names representing all the possible forms of the event as defined /// by the graph field. /// </summary> /// <param name="schema">The schema owning the field definition.</param> /// <param name="field">The field to create names for.</param> /// <returns>IEnumerable&lt;SubscriptionEventName&gt;.</returns> public static IEnumerable<SubscriptionEventName> FromGraphField(ISchema schema, ISubscriptionGraphField field) { Validation.ThrowIfNull(schema, nameof(schema)); Validation.ThrowIfNull(field, nameof(field)); return SubscriptionEventName.FromSchemaTypeAndField(schema.GetType(), field); } /// <summary> /// Creates a set of event names representing all the possible forms of the event as defined /// by the graph field. /// </summary> /// <param name="schemaType">The raw data type of the target schema.</param> /// <param name="field">The field to create names for.</param> /// <returns>IEnumerable&lt;SubscriptionEventName&gt;.</returns> private static IEnumerable<SubscriptionEventName> FromSchemaTypeAndField(Type schemaType, ISubscriptionGraphField field) { yield return new SubscriptionEventName(schemaType, field.Route.Path); if (!string.IsNullOrWhiteSpace(field.EventName)) yield return new SubscriptionEventName(schemaType, field.EventName); } /// <summary> /// Attempts to unpacked the string representation of the event name into a qualified object. /// </summary> /// <param name="value">The value.</param> /// <returns>SubscriptionEventName.</returns> public static SubscriptionEventName UnPack(string value) { if (string.IsNullOrWhiteSpace(value) || !value.Contains(":")) return null; var left = value.Substring(0, value.IndexOf(":", StringComparison.Ordinal)); var right = value.Substring(value.IndexOf(":", StringComparison.Ordinal) + 1); if (string.IsNullOrWhiteSpace(left) || string.IsNullOrWhiteSpace(right)) return null; return new SubscriptionEventName(left, right); } /// <summary> /// Initializes a new instance of the <see cref="SubscriptionEventName" /> class. /// </summary> /// <param name="schemaType">Type of the schema which owns this name.</param> /// <param name="eventName">Name the event.</param> public SubscriptionEventName(Type schemaType, string eventName) : this(SchemaExtensions.RetrieveFullyQualifiedSchemaTypeName(schemaType), eventName) { } /// <summary> /// Initializes a new instance of the <see cref="SubscriptionEventName" /> class. /// </summary> /// <param name="fullyQualifiedSchemaTypeName">A string representing the "FullName" of the schema type.</param> /// <param name="eventName">Name the event.</param> public SubscriptionEventName(string fullyQualifiedSchemaTypeName, string eventName) { fullyQualifiedSchemaTypeName = Validation.ThrowIfNullWhiteSpaceOrReturn( fullyQualifiedSchemaTypeName, nameof(fullyQualifiedSchemaTypeName)); eventName = Validation.ThrowIfNullWhiteSpaceOrReturn(eventName, nameof(eventName)); this.OwnerSchemaType = fullyQualifiedSchemaTypeName; this.EventName = eventName; this.SchemaQualifiedEventName = $"{fullyQualifiedSchemaTypeName}:{eventName}"; } /// <summary> /// Initializes a new instance of the <see cref="SubscriptionEventName"/> class. /// </summary> public SubscriptionEventName() { this.OwnerSchemaType = null; this.EventName = null; this.SchemaQualifiedEventName = null; } /// <summary> /// Gets the full name of the owner schema that created this event name. /// </summary> /// <value>The type of the owner schema.</value> public string OwnerSchemaType { get; } /// <summary> /// Gets root event name of this event. /// </summary> /// <value>The name of the event.</value> public string EventName { get; } /// <summary> /// Gets the fully qualified name of the event including its target schema. /// </summary> /// <value>The name of the schema qualified event.</value> public string SchemaQualifiedEventName { get; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns>A <see cref="string" /> that represents this instance.</returns> public override string ToString() { return this.SchemaQualifiedEventName; } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to the <paramref name="other">other</paramref> parameter; otherwise, false.</returns> public bool Equals(SubscriptionEventName other) { if (ReferenceEquals(null, other)) return false; return this.Equals(other.SchemaQualifiedEventName); } /// <summary> /// Indicates whether the current object is equal to the supplied string. /// </summary> /// <param name="other">The other string to compare against.</param> /// <returns>true if the current object is equal to the <paramref name="other">other</paramref> parameter; otherwise, false.</returns> public bool Equals(string other) { if (ReferenceEquals(null, other) || string.IsNullOrWhiteSpace(other)) return false; return this.SchemaQualifiedEventName != null && string.Equals(this.SchemaQualifiedEventName, other, StringComparison.Ordinal); } /// <summary> /// Determines whether the specified <see cref="object" /> is equal to this instance. /// </summary> /// <param name="obj">The object to compare with the current object.</param> /// <returns><c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (obj is SubscriptionEventName subEventName) return this.Equals(subEventName); if (obj is string str) return this.Equals(str); return false; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { return this.ToString().GetHashCode(); } /// <summary> /// Implements the == operator. /// </summary> /// <param name="ls">The left side of the operation.</param> /// <param name="rs">The right side of the operation.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(SubscriptionEventName ls, SubscriptionEventName rs) { return ls.Equals(rs); } /// <summary> /// Implements the != operator. /// </summary> /// <param name="ls">The left side of the operation.</param> /// <param name="rs">The right side of the operation.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(SubscriptionEventName ls, SubscriptionEventName rs) { return !(ls == rs); } /// <summary> /// Implements the == operator. /// </summary> /// <param name="ls">The left side of the operation.</param> /// <param name="rs">The right side of the operation.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(SubscriptionEventName ls, object rs) { if (rs is null) return false; if (rs is string rss) return ls.Equals(rss); return false; } /// <summary> /// Implements the != operator. /// </summary> /// <param name="ls">The left side of the operation.</param> /// <param name="rs">The right side of the operation.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(SubscriptionEventName ls, object rs) { return !(ls == rs); } /// <summary> /// Implements the == operator. /// </summary> /// <param name="ls">The left side of the operation.</param> /// <param name="rs">The right side of the operation.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(object ls, SubscriptionEventName rs) { if (ls is null) return false; if (ls is string lss) return rs.Equals(lss); return false; } /// <summary> /// Implements the != operator. /// </summary> /// <param name="ls">The left side of the operation.</param> /// <param name="rs">The right side of the operation.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(object ls, SubscriptionEventName rs) { return !(ls == rs); } } }
1a2f1577c8a83a6d50622aca5fa5070b517dcc18
C#
MykhailoIvchenko/Finite-state-machine-algorithm
/End automate/End automate/Program.cs
3.3125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace End_automate { class Program { static void Main(string[] args) { PinCreation myPin = new PinCreation(); //Creation of PinCreation class instance int[] newPin; //Creation of the array, which stores each number of the new pin myPin.CreatePin(out newPin); //Creation of the customer pin-code foreach (var number in newPin) { Console.Write(number); } Console.WriteLine(); Console.Clear(); Console.WriteLine("Try to break in the pin-code");//Suppose, that someone else entered the pin-code earlier PinBreaking myBreaking = new PinBreaking(newPin); myBreaking.CheckNumbers(); Console.ReadKey(); } } }
dc65b7fabc8a6a8807429b214f86de6db1f95ab9
C#
Ashirbadc/AspNet
/NewProjectASP/Default.aspx.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { LabelDate.Text = "The date and time is: " + DateTime.Now.ToString(); TextBoxEmailLabel.Text = ""; } protected void ButtonName_Click(object sender, EventArgs e) { LabelNameResponse.Text = "Hello," + TextBoxName.Text; } protected void ButtonCheckBox_Click(Object sender, EventArgs e) { if (CheckBox1.Checked) { LabelCheckBox.Text = "The box has been Checked"; } else { LabelCheckBox.Text = "The box has been Unchecked"; } } protected void ButtonRBList_Click(Object sender, EventArgs e) { if (RadioButtonList2.SelectedValue == "RB1") { LabelRBList.Text = "RB1 was selected"; } else if (RadioButtonList2.SelectedValue == "RB2") { LabelRBList.Text = "The second radio button has been selected"; } else { LabelRBList.Text = "The third radio button has been selected"; } } protected void ButtonTextBoxMultiLine_Click(object sender, EventArgs e) { int textLength = TextBoxMultiLine.Text.Length; TextBoxMultiLineLablel.Text = "You typed " + textLength + "Characters in this text box. <br/>"; } protected void ButtonTextBoxEmail_Click(object sender, EventArgs e) { string email = TextBoxEmail.Text; if (email.IndexOf('@') == -1 || email.IndexOf('.') == -1) { TextBoxEmailLabel.Text = "Invalid"; } else { TextBoxEmailLabel.Text = "Valid Email Address"; } } protected void Calendar1_SelectionChanged(object sender, EventArgs e) { CalendarLabel.Text = "The date you've selected is: " + Calendar1.SelectedDate.ToString(); } }
af4f1dc995a4bd8729a9c5a0243a17204bef37ed
C#
DigitalSkunkworks/MediaAnalyser
/VisionProcessor/AzureQueueHandler.cs
2.765625
3
using Microsoft.Azure.WebJobs.Host; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using System; using System.Threading.Tasks; namespace VisionProcessor { /// <summary> /// Class AzureQueueHandler /// Azure specific message handling methods. /// /// </summary> public class AzureQueueHandler : QueueHandler { // attributes /// <summary> /// _log /// Contains the log object instance. /// </summary> private static TraceWriter _log = null; /// <summary> /// _queue /// Azure queue object instance. /// </summary> private static CloudQueue _queue { get; set; } = null; //methods protected internal AzureQueueHandler (TraceWriter log, string queueConnectionString, string queueName, string messageData) : base(queueConnectionString, queueName, messageData) { _log = log; } /// <summary> /// CreateQueueClient /// Creates a connection to a queue 'queueName' using connection 'queueConnectionString'. /// </summary> /// <param name="queueConnectionString"></param> /// <param name="queueName"></param> /// <returns></returns> public override CloudQueue CreateQueueClient (string queueConnectionString, string queueName) { try { if (null == _queue) { // Get storage account name and create queue client. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(queueConnectionString); CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); // Retrieve a reference to a queue for this storage account. _queue = queueClient.GetQueueReference(queueName); } else { throw new Exception("Cannot create CloudQueue Client reference."); } } catch (FormatException fe) { //Format Exception logging. _log.Error($"Format Exception found: {fe.Message}"); throw fe; } catch (StorageException se) { // Error logging. _log.Error($"Exception occurred connecting to the message queue: { queueName } { se.ToString() }."); throw; } return _queue; } /// <summary> /// CreateMessageQueueAsync /// Create message queue 'queueName' using connection 'queueConnectionString'. /// </summary> /// <param name="queueConnectionString"></param> /// <param name="queueName"></param> /// <returns></returns> public override async Task<Boolean> CreateMessageQueueAsync(string queueConnectionString, string queueName) { Boolean azureQueueCreateResponse = false; Boolean azureCreateMessageQueueReturnReponse = false; try { if (null == _queue) { CreateQueueClient(queueConnectionString, queueName); } else { azureQueueCreateResponse = await _queue.CreateIfNotExistsAsync(); // Process return value. if (azureQueueCreateResponse) { // Successful queue creation. azureCreateMessageQueueReturnReponse = true; } else { // Unsuccessful queue creation. throw new Exception($"Cannot create Azure storage queue { queueName }."); } } } catch (StorageException se) { // Error logging. _log.Error($"Exception occurred creating message queue: { se.Message }."); throw; } return azureCreateMessageQueueReturnReponse; } /// <summary> /// AddMessageToQueueAsync /// Add a message given by 'messageData' on the queue specified in 'queueName' using connection 'queueConnectionString'. /// </summary> /// <param name="queueConnectionString"></param> /// <param name="queueName"></param> /// <param name="messageData"></param> /// <returns></returns> public override async Task<Boolean> AddMessageToQueueAsync(string queueConnectionString, string queueName, string messageData) { Boolean azureAddMessageReturnReponse = false; try { if (null == _queue) { CreateQueueClient(queueConnectionString, queueName); } else { // Create a message and add it to the queue. CloudQueueMessage message = new CloudQueueMessage(messageData); await _queue.AddMessageAsync(message); _log.Info($"Message added to queue: { message }."); azureAddMessageReturnReponse = true; } } catch (StorageException se) { _log.Error($"Exception occurred posting to the message queue: { se.Message }."); throw; } catch (Exception se) { _log.Error($"Storage Exception occurred posting to the message queue: { se.Message }."); throw; } return azureAddMessageReturnReponse; } /// <summary> /// PeekNextMessageOnQueueAsync /// Look at the next available message on a queue 'queueName' using connection 'queueConnectionString' without removing it from the queue. /// Peek message on queue method /// </summary> /// <param name="queueConnectionString"></param> /// <param name="queueName"></param> /// <returns></returns> public override async Task<String> PeekNextMessageOnQueueAsync(string queueConnectionString, string queueName) { CloudQueueMessage azurePeekedMessageReturnReponse = null; try { if (null == _queue) { CreateQueueClient(queueConnectionString, queueName); } else { // Peek at the next message azurePeekedMessageReturnReponse = await _queue.PeekMessageAsync(); _log.Info($"Message peeked."); } } catch (StorageException se) { // Error logging. _log.Error($"Exception occurred peeking message queue: { se.Message }."); throw; } return azurePeekedMessageReturnReponse.AsString; } } }
052c403d7f55e5eb0622ddf63d05437b79d32b92
C#
ShourovSaha/DataStructurePractice-
/Stack/StringAnagramCheck/Program.cs
4.03125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //A programe to check is a string is anagram to another string. namespace StringAnagramCheck { class Program { static void Main(string[] args) { Console.WriteLine("Input a string...\n"); var ipStr1 = Console.ReadLine(); Console.WriteLine("Input another string...\n"); var ipStr2 = Console.ReadLine(); if (IsAnagram(ipStr1, ipStr2)) { Console.WriteLine("\n\n#Anagram"); } else { Console.WriteLine("\n\n#Not Anagram"); } Console.ReadKey(); } static bool IsAnagram(string str1, string str2) { List<char> CharList1 = new List<char>(); bool result = false; if (str1.Length != str2.Length) { result = false; } else { for (int i = 0; i < str1.Length; i++) { CharList1.Add(str1[i]); } for (int i = 0; i < str1.Length; i++) { if (CharList1.Contains(str2[i]) == false) { result = false; break; } else { result = true; } } } return result; } } }
41163034cd40e2637b827c9a0925358e39925a67
C#
lucasbriguenti/MestreDosCodigosNet
/MestreDosCodigosLucas/MestreDosCodigosPOOLucas/Modulos/PessoaModulo/PessoaModulo.cs
2.578125
3
using System; using System.Collections.Generic; using System.Text; using Xunit.Abstractions; namespace MestreDosCodigosPOOLucas.Modulos.PessoaModulo { public class PessoaModulo : Modulo { private readonly ITestOutputHelper _output; public PessoaModulo() { } public PessoaModulo(ITestOutputHelper output) { _output = output; } public void Executar() { var pessoa = new Pessoa("Lucas Briguenti", new DateTime(1996,03,02), 1.70); pessoa.ImprimirPessoa(); if(_output != null) { _output.WriteLine("Passou pelo output"); } } } }
7fb9a020a59e2b92f0a43a53e195bb59757c1506
C#
KennethRPedersen/PetShop
/PetShop.Core/ApplicationService/Impl/UserService.cs
2.875
3
using System; using System.Collections.Generic; using System.Data.SqlTypes; using System.Security.Cryptography; using System.Text; using PetShop.Core.DomainService; using PetShop.Core.Entities; namespace PetShop.Core.ApplicationService.Impl { public class UserService : IUserService { private readonly IUserRepository _userRepo; public UserService(IUserRepository userRepo) { _userRepo = userRepo; } public User ValidateUser(LoginInput input) { User user = _userRepo.ValidateUser(input); if(!user.PasswordHash .Equals(GetHashValue(input.Password + user.PasswordSalt))) throw new UnauthorizedAccessException(); user.LastLogin = DateTime.Now; _userRepo.UpdateUser(user); return user; } public IEnumerable<User> GetAllUsers() { return _userRepo.GetAllUsers(); } public User GetUserById(int id) { return _userRepo.GetUserById(id); } public User UpdateUser(UpdateUserInput userInput) { // Fetch existing version of user from DB User user = _userRepo.GetUserById(userInput.Id); // Check if user was actually found, and that their ID equals the inputs one. //If not, throw exception if(user == null || user.Id != userInput.Id) throw new ArgumentException(); // Ensure that inputs 'oldPassword' is actually the same as the stored one. // If not, throw exception. if(user.PasswordHash != GetHashValue(userInput.oldPassword + user.PasswordSalt)) throw new ArgumentException(); var salt = user.PasswordSalt; // Set to currently stored salt var pass = user.PasswordHash; // Set to currently stored hash //If a new password is in the input: //1. Generate a new salt, so we don't use the same. //2. Generate new hash with 'newPassword' and the newly generated salt. if (userInput.newPassword != null || userInput.newPassword != "") { salt = GenerateSalt(); pass = GetHashValue(userInput.newPassword + salt); } //Finally, create the updated user object user = new User() { Id = userInput.Id, Username = userInput.Username, PasswordHash = pass, PasswordSalt = salt, IsAdmin = userInput.isAdmin }; //Update user in DB and return the new object. return _userRepo.UpdateUser(user); } public User CreateNewUser(CreateUserInput userInput) { var salt = GenerateSalt(); User user = new User { Username = userInput.Username, IsAdmin = userInput.isAdmin, PasswordSalt = salt, CreationDate = DateTime.Now, LastLogin = DateTime.MinValue, PasswordHash = GetHashValue(userInput.Password + salt) }; return (_userRepo.CreateNewUser(user)); } public void DeleteUser(User user) { _userRepo.DeleteUser(user); } private string GenerateSalt() { byte[] bytes = new byte[128 / 8]; using (var keyGenerator = RandomNumberGenerator.Create()) { keyGenerator.GetBytes(bytes); return BitConverter.ToString(bytes).Replace("-", "").ToLower(); } } private string GetHashValue(string input) { using (var sha = SHA256Managed.Create()) { var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(input)); return BitConverter.ToString(bytes); } } } }
0a02c30ce6db8a9613656eb823583230db97791b
C#
pcardot/KinectProject
/ProjetIEC.b/Assets/Resources/Scripts/Game2-specific/ObjectFactory.cs
2.75
3
using UnityEngine; using System.Collections; using System.Collections.Generic; public class ObjectFactory : MonoBehaviour { [SerializeField] private GameObject objectPrefab; private Stack<GameObject> unusedObjects; public static ObjectFactory instance = null; public enum positions{ left, right, up } /** * Unity Generic Event delegates **/ // Use this for initialization void Start () { unusedObjects = new Stack<GameObject>(); } // Update is called once per frame void Update () { } void Awake () { if (instance != null) Debug.Log("ObjectFactory is supposed to be a singleton"); else instance = this; } /** * Factory public functions **/ public GameObject getObject(positions pos) { GameObject retour; if(unusedObjects.Count > 0) { retour = unusedObjects.Pop(); retour.gameObject.SetActive(true); } else { retour = (GameObject) Instantiate(objectPrefab); } switch(pos) { case positions.left: retour.transform.position = new Vector3(-2.0f,0,10.0f); retour.renderer.material.color = Color.white; break; case positions.right: retour.transform.position = new Vector3(2.0f,0,10.0f); retour.renderer.material.color = Color.yellow; break; case positions.up: retour.transform.position = new Vector3(0,2.0f,10.0f); retour.renderer.material.color = Color.red; break; default: break; } ObjectMovingScript OMS = (ObjectMovingScript) retour.GetComponent("ObjectMovingScript"); OMS.pos = pos; return retour; } public void releaseObject(GameObject obj) { obj.gameObject.SetActive(false); unusedObjects.Push(obj); } }
ea7b3999e1d452099028c3d2a275ee0dc6680e4c
C#
ryomutk/walkingInTheWorldOf_HDRPv
/Assets/Scripts/Utility/Singleton.cs
2.828125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Utility { public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T> { public static T instance = null; protected virtual void Awake() { CreateSingleton(); } void CreateSingleton() { if (instance == null) { instance = this as T; } else { Debug.LogWarning(this.GetType() + "is singleton! now been killed"); Destroy(this.gameObject); } } void OnDestroy() { instance = null; } } }
1b6c2b58c47c6484f1a5ef29a1f8c54b8dc64950
C#
SRINIVAS2698/CSharpExercise
/src/Problem2/Requirements.cs
2.984375
3
namespace src.Problem2 { /* A class, entitled Requirements, that contains two pieces of data. The first is an instance of the enumerated type above. The second is an integer that represents the required number of units of the enumerated type specified in the first piece of data. The class should have a constructor or member function that accepts the enumerated type and the value of the units variable. */ public class Requirements : GenericEntity { public Requirements(eResourceType resourceType,int numberOfUnits) :base(resourceType,numberOfUnits) { } } }
1673f8e79c394552e3c68c1dcb78e076210c2010
C#
shendongnian/download4
/latest_version_download2/20859-2980974-26748941-6.cs
2.8125
3
public class DynamicProxy : System.Dynamic.DynamicObject { private object _innerObject; private Type _innerType; public DynamicProxy(object inner) { if (inner == null) throw new ArgumentNullException("inner"); _innerObject = inner; _innerType = _innerObject.GetType(); } public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result) { System.Diagnostics.Debug.WriteLine("Enter: ", binder.Name); try { result = _innerType.InvokeMember( binder.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, _innerObject, args); } catch (MissingMemberException) { return base.TryInvokeMember(binder, args, out result); } finally { System.Diagnostics.Debug.WriteLine("Exit: ", binder.Name); } return true; } public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result) { System.Diagnostics.Debug.WriteLine("Enter: ", binder.Name); try { result = _innerType.InvokeMember( binder.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty, null, _innerObject, null); } catch (MissingMemberException) { return base.TryGetMember(binder, out result); } finally { System.Diagnostics.Debug.WriteLine("Exit: ", binder.Name); } return true; } public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value) { System.Diagnostics.Debug.WriteLine("Enter: ", binder.Name); try { _innerType.InvokeMember( binder.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, null, _innerObject, new object[]{ value }); } catch (MissingMemberException) { return base.TrySetMember(binder, value); } finally { System.Diagnostics.Debug.WriteLine("Exit: ", binder.Name); } return true; } public override string ToString() { try { System.Diagnostics.Debug.WriteLine("Enter: ToString"); return _innerObject.ToString(); } finally { System.Diagnostics.Debug.WriteLine("Exit: ToString"); } } }