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
f540ac66b95f6cb42d9a92875d6d40c0a6d98340
C#
takepara/RazorDoIt
/RazorDoIt/Data/SiteRepository.cs
2.625
3
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.Entity; using System.Data.Entity.Database; using System.Data.Entity.Infrastructure; using System.Linq; using RazorDoIt.Data.EfCodeFirst; using RazorDoIt.Models; namespace RazorDoIt.Data { public interface ISiteRepository { Account GetAccount(string userName); Account SaveAccount(Account account); Template GetTemplate(int id); Template GetTemplate(string key); Template SaveTemplate(Template template); Tag GetTag(int id); Tag GetTag(string keyword); IEnumerable<Template> FindRecentTemplates(); int SaveChanges(); } public class SiteRepository : ISiteRepository, IDisposable { private SiteContext _db; private static bool _started; public static void Bootstrap() { if (_started) return; _started = true; var drop = bool.Parse(ConfigurationManager.AppSettings["DropDatabase"] ?? "false"); if(drop) DbDatabase.SetInitializer(new DropCreateDatabaseIfModelChanges<SiteContext>()); else DbDatabase.SetInitializer(new CreateDatabaseIfNotExists<SiteContext>()); } public SiteRepository() { _db = new SiteContext(); // RelationデータをProxyを作成せずに管理する。 // だからIncludeが必須。 // Attachはうまくいく!! ((IObjectContextAdapter)_db).ObjectContext.ContextOptions.ProxyCreationEnabled = false; } public Account GetAccount(string userName) { var query = from account in _db.Accounts where account.UserName == userName select account; return query.FirstOrDefault(); } public Account SaveAccount(Account account) { var now = DateTime.Now; account.UpdateAt = now; var existAccount = GetAccount(account.UserName); if (existAccount != null) { account.CreateAt = existAccount.CreateAt; var entry = _db.Entry(existAccount); entry.OriginalValues.SetValues(existAccount); entry.CurrentValues.SetValues(account); } else { account.CreateAt = now; _db.Accounts.Add(account); } return account; } private IQueryable<Template> QueryTemplate() { return from template in _db.Templates.Include(m => m.Account).Include(m => m.Tags) select template; } public Template GetTemplate(int id) { var query = from template in QueryTemplate() where template.Id == id select template; return query.FirstOrDefault(); } public Template GetTemplate(string key) { var query = from template in QueryTemplate() where template.UrlKey == key select template; return query.FirstOrDefault(); } public IEnumerable<Template> FindRecentTemplates() { var query = from template in QueryTemplate().AsNoTracking() orderby template.UpdateAt descending select template; return query.Take(20).ToList(); } public Template SaveTemplate(Template template) { var now = DateTime.Now; template.UpdateAt = now; var existTemplate = GetTemplate(template.Id); if (existTemplate != null) { var entry = _db.Entry(existTemplate); entry.OriginalValues.SetValues(existTemplate); entry.CurrentValues.SetValues(template); // 今持ってるTagを一旦全部消す existTemplate.Tags.Clear(); } else { template.CreateAt = now; _db.Templates.Add(template); } foreach (var tag in template.Tags) { tag.Templates.Add(template); _db.Tags.Add(tag); } return template; } public Tag GetTag(int id) { var query = from tag in _db.Tags where tag.Id == id select tag; return query.FirstOrDefault(); } public Tag GetTag(string keyword) { var query = from tag in _db.Tags where tag.Keyword == keyword select tag; return query.FirstOrDefault(); } public int SaveChanges() { return _db.SaveChanges(); } #region disposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~SiteRepository() { // Finalizer calls Dispose(false) Dispose(false); } protected virtual void Dispose(bool disposing) { if (disposing) { // free managed resources if (_db != null) { if (_db.Database.Connection.State != ConnectionState.Closed) _db.Database.Connection.Close(); _db.Dispose(); _db = null; } } } #endregion } }
3caac7b4a3300c770e1588e1b2f494b338e11eab
C#
Sora2455/Sora-s-Nerd-Den
/Testing/ConcurrentDictionaryOfCollectionsTests.cs
2.59375
3
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Common.Concurrency; //using Microsoft.Concurrency.TestTools.UnitTesting; //using Microsoft.Concurrency.TestTools.UnitTesting.Chess; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assert = Microsoft.Concurrency.TestTools.UnitTesting.Assert; //********************************************************************************************** // Instruct Chess to instrument the System.dll assembly so we can catch data races in CLR classes // such as LinkedList{T} //********************************************************************************************** //[assembly: ChessInstrumentAssembly("System")] //[assembly: ChessInstrumentAssembly("Concurrency")] //Run //.\/mcut.exe runAllTests [PathToRepo]\Testing\bin\Debug\Testing.dll //From //[PathToRepo]\packages\Chess.1.0.1\tools //Correct as needed namespace Testing { [TestClass] public class ConcurrentDictionaryOfCollectionsTests { [TestMethod] public void AddAndGetSingleValues() { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); testDic.Add(1, "There"); testDic.Add(2, "Hello"); testDic.Add(3, "World"); Assert.AreEqual(testDic.Get(0).FirstOrDefault(), "Hi"); Assert.AreEqual(testDic.Get(1).FirstOrDefault(), "There"); Assert.AreEqual(testDic.Get(2).FirstOrDefault(), "Hello"); Assert.AreEqual(testDic.Get(3).FirstOrDefault(), "World"); } [TestMethod] public void AddAndGetGroupedValues() { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); testDic.Add(0, "There"); testDic.Add(0, "Hello"); testDic.Add(0, "World"); string[] finalValues = testDic.Get(0).ToArray(); Assert.AreEqual(finalValues[0], "Hi"); Assert.AreEqual(finalValues[1], "There"); Assert.AreEqual(finalValues[2], "Hello"); Assert.AreEqual(finalValues[3], "World"); } [TestMethod] public void GetAll() { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); testDic.Add(0, "There"); testDic.Add(1, "Hello"); testDic.Add(1, "World"); List<string> finalValues = testDic.GetAll(); Assert.AreEqual(finalValues[0], "Hi"); Assert.AreEqual(finalValues[1], "There"); Assert.AreEqual(finalValues[2], "Hello"); Assert.AreEqual(finalValues[3], "World"); } [TestMethod] public void AddThenRemove() { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); Assert.AreEqual(testDic.Get(0).FirstOrDefault(), "Hi"); testDic.Remove(0, "Hi"); Assert.IsTrue(testDic.Get(0) is string[] arr && arr.Length == 0); } [TestMethod] //[DataRaceTestMethod] public void ConcurrentAddDiffKeys() { for (int i = 0; i < 100; i++) { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); Parallel.Invoke(() => { testDic.Add(0, "Hi"); }, () => { testDic.Add(1, "There"); }); Assert.AreEqual(testDic.Get(0).FirstOrDefault(), "Hi"); Assert.AreEqual(testDic.Get(1).FirstOrDefault(), "There"); } } [TestMethod] //[DataRaceTestMethod] public void ConcurrentAddSameKey() { for (int i = 0; i < 100; i++) { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); Parallel.Invoke(() => { testDic.Add(0, "Hi"); }, () => { testDic.Add(0, "There"); }); List<string> finalValues = testDic.Get(0).ToList(); Assert.IsTrue(finalValues.Contains("Hi")); Assert.IsTrue(finalValues.Contains("There")); } } [TestMethod] //[DataRaceTestMethod] public void ConcurrentAddAndRemoveSameKey() { for (int i = 0; i < 100; i++) { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); Parallel.Invoke(() => { testDic.Add(0, "There"); }, () => { testDic.Remove(0, "Hi"); }); List<string> finalValues = testDic.Get(0).ToList(); Assert.IsFalse(finalValues.Contains("Hi")); Assert.IsTrue(finalValues.Contains("There")); } } [TestMethod] //[DataRaceTestMethod] public void ConcurrentAddAndRemoveDiffKey() { for (int i = 0; i < 100; i++) { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); Parallel.Invoke(() => { testDic.Add(1, "There"); }, () => { testDic.Remove(0, "Hi"); }); List<string> finalValues = testDic.Get(1).ToList(); Assert.IsTrue(finalValues.Contains("There")); Assert.IsTrue(testDic.Get(0) is string[] arr && arr.Length == 0); } } [TestMethod] //[DataRaceTestMethod] public void ConcurrentReadAndRemove() { bool readBeforeDeleteAtLeastOnce = false; for (int i = 0; i < 100; i++) { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); Parallel.Invoke(() => { string[] values = testDic.Get(0).ToArray(); readBeforeDeleteAtLeastOnce = readBeforeDeleteAtLeastOnce || values.Length == 1 && values[0] == "Hi"; }, () => { testDic.Remove(0, "Hi"); }); Assert.IsTrue(testDic.Get(0) is string[] arr && arr.Length == 0); } Assert.IsTrue(readBeforeDeleteAtLeastOnce); } } }
07353a497abdf36a8d979c6dc7a751097afb7852
C#
FubuMvcArchive/FubuCsProjFile
/src/FubuCsProjFile/MSBuild/MSBuildItemGroup.cs
2.515625
3
using System.Collections.Generic; using System.Xml; namespace FubuCsProjFile.MSBuild { public class MSBuildItemGroup : MSBuildObject { private readonly MSBuildProject parent; internal MSBuildItemGroup(MSBuildProject parent, XmlElement elem) : base(elem) { this.parent = parent; } public IEnumerable<MSBuildItem> Items { get { foreach (XmlNode node in Element.ChildNodes) { var elem = node as XmlElement; if (elem != null) yield return parent.GetItem(elem); } } } public MSBuildItem AddNewItem(string name, string include) { XmlElement elem = AddChildElement(name); MSBuildItem it = parent.GetItem(elem); it.Include = include; return it; } } }
d872438a48f241c16f10c72868e6cf46f0676510
C#
Vick-edit/InsuranceTestServer
/ServiceCore.Tests/AutoMockingContainer.cs
2.609375
3
using SimpleInjector; using System; using Moq; namespace ServiceCore.Tests { public class AutoMockingContainer { public static Container GetNew() { var container = new Container(); container.ResolveUnregisteredType += ResolveUnregisteredType; return container; } private static void ResolveUnregisteredType(object sender, UnregisteredTypeEventArgs eventArgs) { var container = (Container)sender; //Регистрируем создание объекта типа Mock напрямую if (typeof(Mock).IsAssignableFrom(eventArgs.UnregisteredServiceType)) { eventArgs.Register( Lifestyle.Singleton.CreateRegistration( eventArgs.UnregisteredServiceType, () => Activator.CreateInstance(eventArgs.UnregisteredServiceType), container ) ); } //Регистрируем создание инстансов любых интерфейсов через создание соответствующего мока if (eventArgs.UnregisteredServiceType.IsInterface) { Type mockType = typeof(Mock<>).MakeGenericType(eventArgs.UnregisteredServiceType); eventArgs.Register( Lifestyle.Singleton.CreateRegistration( eventArgs.UnregisteredServiceType, () => ((Mock)container.GetInstance(mockType)).Object, container ) ); } } } }
9ccef22baadf6c6b7c5f52545d1304e7bcb3b944
C#
CrimsonScythe/su19-kkk
/SU19-Exercises/Galaga-Exercise-2/Player.cs
2.828125
3
using System.Collections.Generic; using System.IO; using System.Net; using DIKUArcade.Entities; using DIKUArcade.EventBus; using DIKUArcade.Graphics; using DIKUArcade.Math; namespace Galaga_Exercise_2 { public class Player : IGameEventProcessor<object> { public Entity Entity { get; private set; } private Game game; private Shape shape; private IBaseImage image; public Player(Game game, Shape shape, IBaseImage image) { this.game = game; this.shape = shape; this.image = image; Entity = new Entity(shape, image); } public void ProcessEvent(GameEventType eventType, GameEvent<object> gameEvent) { switch (eventType) { case GameEventType.PlayerEvent: if (gameEvent.Message.Equals("move left")) { Direction(new Vec2F(-0.01f, 0.0f)); } else if (gameEvent.Message.Equals("move right")) { Direction(new Vec2F(0.01f, 0.0f)); } else { Direction(new Vec2F(0.0f,0.0f)); } break; } } private void Direction(Vec2F vec2F) { this.shape.AsDynamicShape().ChangeDirection(vec2F); } public void Move() { //moving right if (shape.AsDynamicShape().Direction.X > 0.0f && shape.Position.X < 0.90f) { shape.Move(); } //moving left if (shape.AsDynamicShape().Direction.X < 0.0f && shape.Position.X > 0) { shape.Move(); } } public void CreateShot() { PlayerShot playerShot = new PlayerShot(game, new DynamicShape(new Vec2F(shape.Position.X + 0.05f, shape.Position.Y+0.05f), new Vec2F(0.008f, 0.027f) ), game.shotImages); game.playerShots.Add(playerShot); } } }
adc2a1126a91dfdd65af63b5684f5442c4af541a
C#
e310905-Saimia/digitrade-test-2019
/IfTasks/IfTask32/IfTask32/Program.cs
3.28125
3
using System; namespace IfTask32 { class Program { static void Main(string[] args) { Console.WriteLine("Ohjelma laskee N lukujen summan"); Console.Write("Syötä luku: "); int userInput = int.Parse(Console.ReadLine()); Console.WriteLine("FOR ---------------"); for (int i = 0; i < userInput; i++) { Console.WriteLine(i+1); } Console.WriteLine("WHILE ---------------"); int j = 0; // Laskurin määritys while(j < userInput) // Silmukan ehto. Silmukkaa tehdään niin pitkään kunnes se on epätosi { j++; //Laskuri kasvatus yhdellä Console.WriteLine(j); // Tulostus } Console.WriteLine("WHILE ikiluuppi---------------"); int k = 0; // Laskurin määritys while (true) // Ikuluuppi { k++; //Laskuri kasvatus yhdellä Console.WriteLine(k); // Tulostus if (k >= userInput) //Ehto silmukan lopetukselle break; } Console.WriteLine("DO-WHILE ---------------"); int n = 0; do { n++; Console.WriteLine(n); } while (n<userInput); Console.WriteLine("Ohjelman suoritus on päättynyt!"); } } }
0eabfed26531140e75451e82c96dd2a66683e3a6
C#
PaulMcPhee79/AwesomePirates-Win-Xbox360
/AwesomePirates/src/Audio/SfxChannel.cs
2.765625
3
using System; using System.Collections.Generic; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Media; using System.Diagnostics; namespace AwesomePirates { class SfxChannel : IDisposable { public SfxChannel(SoundEffectInstance instance, float volume = 1f, float masterVolume = 1f) { Debug.Assert(instance != null, "SfxChannel requires a non-null SoundEffectInstance."); mInstance = instance; mMasterVolume = masterVolume; VolumeProxy = volume; } protected bool mIsDisposed = false; private float mVolumeProxy; private float mMasterVolume; private SoundEffectInstance mInstance; public float VolumeProxy { get { return mVolumeProxy; } set { mVolumeProxy = Math.Max(0f, Math.Min(1f, value)); mInstance.Volume = mVolumeProxy * mMasterVolume; } } public float MasterVolume { get { return mMasterVolume; } set { mMasterVolume = Math.Max(0f, Math.Min(1f, value)); VolumeProxy = VolumeProxy; } } public SoundEffectInstance Instance { get { return mInstance; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!mIsDisposed) { try { if (disposing) { if (mInstance != null) { mInstance.Dispose(); mInstance = null; } } } catch (Exception) { // Ignore } finally { mIsDisposed = true; } } } ~SfxChannel() { Dispose(false); } } }
f6eddf2625a8a3d86be9daac6ccac8d87f7de7cf
C#
Harksa/Ludum-Dare-44
/Assets/Scripts/ObjectPool.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class ObjectPool : MonoBehaviour { [SerializeField] private List<GameObject> _objectList; [SerializeField] private GameObject _gameObject; [SerializeField] private int totalObjectInPool; private static Dictionary<int, ObjectPool> pools = new Dictionary<int, ObjectPool>(); private void Init() { _objectList = new List<GameObject>(totalObjectInPool); for (int i = 0; i < totalObjectInPool; i++) { GameObject objectToSpawn = Instantiate(_gameObject); objectToSpawn.transform.parent = transform; objectToSpawn.SetActive(false); _objectList.Add(objectToSpawn); } pools.Add(_gameObject.GetInstanceID(), this); } private GameObject PoolObject(Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion)) { var objectToSpawn = (from item in _objectList where item.activeSelf == false select item).FirstOrDefault(); if (objectToSpawn == null) { objectToSpawn = Instantiate(_gameObject, position, rotation); objectToSpawn.transform.parent = transform; _objectList.Add(objectToSpawn); } else { objectToSpawn.transform.position = position; objectToSpawn.transform.rotation = rotation; objectToSpawn.SetActive(true); } return objectToSpawn; } static public bool IsPoolReady(GameObject original) { return pools.ContainsKey(original.GetInstanceID()); } static public void InitPool(GameObject original, int poolSize = 200) { if (!pools.ContainsKey(original.GetInstanceID())) { GameObject go = new GameObject("Object pool: " + original.name); ObjectPool pool = go.AddComponent<ObjectPool>(); pool._gameObject = original; pool.totalObjectInPool = poolSize; pool.Init(); } } public static GameObject GetInstance(int instanceID, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion), int poolsize = 200) { return pools[instanceID].PoolObject(position, rotation); } public static GameObject GetInstance(GameObject toPool, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion), int poolSize = 200) { int id = toPool.GetInstanceID(); InitPool(toPool, poolSize); return pools[id].PoolObject(position, rotation); } public static void Release(GameObject obj) { if (!obj.GetComponentInParent<ObjectPool>()) { foreach (var objectPool in pools.Values) { if (objectPool._objectList.Contains(obj)) { obj.transform.parent = objectPool.transform; break; } } } obj.SetActive(false); } public static void ClearPool() { foreach (var item in pools) { item.Value._objectList.Clear(); } pools.Clear(); } }
33362ee5485759172d1f6a072376373b49791d4e
C#
YaniStaykov/DavidAcademy
/DavidAcademy/28.SoftwareAcademy/Models/Academy.cs
3.3125
3
namespace _28.SoftwareAcademy { using System.Collections.Generic; public class Academy { public Academy(string name) { this.Name = name; Students = new List<Student>(); Courses = new List<Course>(); } public string Name { get; set; } public List<Student> Students { get; set; } public List<Course> Courses { get; set; } public void AddStudent(Student student) { Students.Add(student); } public void AddCourse(Course course) { Courses.Add(course); } } }
74dad60d55aae20e27a052edd13fe801054158bf
C#
GhostBusterPL/ShelterInzynierka
/ShelterInzynierka/ValueConverters/OnlyYearMonthDay.cs
2.53125
3
using Renci.SshNet.Messages; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; namespace ShelterInzynierka.ValueConverters { class OnlyYearMonthDay : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { DateTime defaultDate = (DateTime)value; if (defaultDate == DateTime.MinValue) { return null; } else { DateTime returnDate = (DateTime)value; return returnDate.ToString("yyyy-MM-dd"); } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
02bf43dbf7ab39fcbc9ccda0002cf61f9bbd3c70
C#
devilheaven/smapi-mod-dump
/source/~Mizzion/PetWaterBowl/PetWaterBowl/PetWaterBowl.cs
2.53125
3
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; using SObject = StardewValley.Object; namespace PetWaterBowl { public class PetWaterBowl : Mod { private Config _config; private bool debugging; //Config Settings private bool _enableMod; private bool _enableSnowWatering; private bool _enableSprinklers; private Vector2 _waterBowlLocation; public override void Entry(IModHelper helper) { _config = helper.ReadConfig<Config>(); _enableMod = _config.EnableMod; _enableSnowWatering = _config.EnableSnowWatering; _enableSprinklers = _config.EnableSprinklerWatering; _waterBowlLocation = _config.WaterBowlLocation; //Whether Im debugging debugging = false; //Events helper.Events.Input.ButtonPressed += KeyPressed; helper.Events.GameLoop.SaveLoaded += AfterLoad; helper.Events.GameLoop.Saved += AfterSave; } private void KeyPressed(object sender, ButtonPressedEventArgs e) { if (!Context.IsWorldReady) return; //Reload Config file if (Helper.Input.IsDown(SButton.F5)) { _config = Helper.ReadConfig<Config>(); _enableMod = _config.EnableMod; _enableSnowWatering = _config.EnableSnowWatering; _enableSprinklers = _config.EnableSprinklerWatering; _waterBowlLocation = _config.WaterBowlLocation; Monitor.Log("Config Reloaded", LogLevel.Info); } //Grab the Coords of the mouse cursor if (Helper.Input.IsDown(SButton.F9)) { ICursorPosition cur = Helper.Input.GetCursorPosition(); _config.WaterBowlLocation = new Vector2(cur.Tile.X, cur.Tile.Y); Helper.WriteConfig(_config); //Reload the config after writing to it. _config = Helper.ReadConfig<Config>(); _enableMod = _config.EnableMod; _enableSnowWatering = _config.EnableSnowWatering; _enableSprinklers = _config.EnableSprinklerWatering; _waterBowlLocation = _config.WaterBowlLocation; Monitor.Log($"Current Water Bowl Location: X:{cur.Tile.X}, Y:{cur.Tile.Y}. Settings Updated."); } //For my testing purposes if (Helper.Input.IsDown(SButton.NumPad9) && debugging) { Monitor.Log($"Sprinkler Watering Activated: {_enableSprinklers}"); } //Check for water bowl at location if (Helper.Input.IsDown(SButton.NumPad8) && debugging) { if(CheckBowlLocation(_waterBowlLocation)) Monitor.Log("Bowl found.", LogLevel.Alert); else Monitor.Log("Bowl not found", LogLevel.Alert); } } private void AfterSave(object sender, SavedEventArgs e) { if (Game1.whichFarm < 4) WaterPetBowl(new Vector2(54, 7)); else { if (_waterBowlLocation.X == 54 && _waterBowlLocation.Y == 7) Monitor.Log("It appears, you are using a custom map. In order for this mod to work correctly, you will need to hover your mouse over the water bowl and hit F9. This will set the water bowls coords, then the mod should work correctly.", LogLevel.Info); else WaterPetBowl(_waterBowlLocation); } } private void AfterLoad(object sender, SaveLoadedEventArgs e) { if (Game1.whichFarm < 4) WaterPetBowl(new Vector2(54, 7)); else { if(_waterBowlLocation.X == 54 && _waterBowlLocation.Y == 7) Monitor.Log("It appears, you are using a custom map. In order for this mod to work correctly, you will need to hover your mouse over the water bowl and hit F9. This will set the water bowls coords, then the mod should work correctly.", LogLevel.Info); else WaterPetBowl(_waterBowlLocation); } } //Method that will be used to water the bowl. I added this, so I wont have to copy and paste code. private void WaterPetBowl(Vector2 tileLocation) { if (!_enableMod) return; Farm farm = Game1.getFarm(); if (Game1.isRaining || Game1.isLightning || (Game1.isSnowing && _enableSnowWatering) || CheckForSprinklers(tileLocation)) { farm.setMapTileIndex(Convert.ToInt32(tileLocation.X), Convert.ToInt32(tileLocation.Y), 1939, "Buildings", 0); Monitor.Log("Water bowl should be filled."); } else farm.setMapTileIndex(Convert.ToInt32(tileLocation.X), Convert.ToInt32(tileLocation.Y), 1938, "Buildings", 0); } private bool CheckForSprinklers(Vector2 tileLocation) { bool sprinklerFound = false; Farm farm = Game1.getFarm(); foreach (KeyValuePair<Vector2, SObject> farmObjects in farm.objects.Pairs) { if (_config.EnableSprinklerWatering && farmObjects.Value.ParentSheetIndex == 645) { for (int x = (int)tileLocation.X - 2; x <= tileLocation.X + 2; x++) { for (int y = (int) tileLocation.Y - 2; y <= tileLocation.Y + 2; y++) { Vector2 newLoc = new Vector2(x, y); if (farm.getTileIndexAt(Convert.ToInt32(newLoc.X), Convert.ToInt32(newLoc.Y), "Buildings") == 1938) sprinklerFound = true; } } } } return sprinklerFound; } private bool CheckBowlLocation(Vector2 tileLocation) { bool found = false; Farm farm = Game1.getFarm(); if (farm.getTileIndexAt((int)tileLocation.X, (int)tileLocation.Y, "Buildings") == 1938) found = true; return found; } } }
938123da8ce21e9e0cdcef8ed92a506ac34c70ed
C#
seangwright/talks-framework-features-anti-pattern-demos
/ASPNETCoreMVC.FeatureFocus.Web/Features/Customers/EcommerceContext.cs
2.53125
3
using Microsoft.AspNetCore.Http; using System; using System.Linq; using System.Threading.Tasks; namespace ASPNETCoreMVC.FeatureFocus.Web.Features.Customers { public class EcommerceContext : IEcommerceContext { private readonly ICustomerRepository repository; private readonly int? currentCustomerId; public EcommerceContext(ICustomerRepository repository, IHttpContextAccessor httpContextAccessor) { this.repository = repository; var customerCookie = httpContextAccessor .HttpContext .Request .Cookies .FirstOrDefault(c => c.Key.Equals("CustomerId", StringComparison.InvariantCultureIgnoreCase)); if (int.TryParse(customerCookie.Value, out int cookieCustomerId)) { currentCustomerId = cookieCustomerId; } } public Task<Customer> CurrentCustomer() => currentCustomerId == null ? Task.FromResult<Customer>(null) : repository.GetCustomer(currentCustomerId.Value); } }
d4f8d4fb2ce2ef4d5c958c9f9be716a612475a8c
C#
RauhoferE/SnakeInSignalR
/NetworkLibrary/EventArgs/ClientSnakeMovementEventArgs.cs
2.703125
3
//----------------------------------------------------------------------- // <copyright file="ClientSnakeMovementEventArgs.cs" company="FH Wiener Neustadt"> // Copyright (c) Emre Rauhofer. All rights reserved. // </copyright> // <author>Emre Rauhofer</author> // <summary> // This is a network library. // </summary> //----------------------------------------------------------------------- namespace NetworkLibrary { using System; /// <summary> /// The <see cref="ClientSnakeMovementEventArgs"/> class. /// </summary> public class ClientSnakeMovementEventArgs : EventArgs { /// <summary> /// Initializes a new instance of the <see cref="ClientSnakeMovementEventArgs"/> class. /// </summary> /// <param name="container"> The <see cref="MoveSnakeContainer"/>. </param> public ClientSnakeMovementEventArgs(MoveSnakeContainer container) { this.Container = container; } /// <summary> /// Gets the <see cref="MoveSnakeContainer"/>. /// </summary> /// <value> A <see cref="MoveSnakeContainer"/> object. </value> public MoveSnakeContainer Container { get; } } }
afc8ad414d9360a6c3e2d7fdb7a00e94d7c5fc15
C#
vebin/NewPOS
/stockitem.cs
2.765625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace NewPOS { public class stockitem { public int amountsold, currentstock; summaryreportTableAdapters.tblProductTableAdapter ProductTableAdapter = new summaryreportTableAdapters.tblProductTableAdapter(); public String OpeningStock(int ProductId) { DataTable products = ProductTableAdapter.GetData(); foreach (DataRow row in products.Rows) { foreach (DataColumn column in products.Columns) { if (row[column].ToString() == ProductId.ToString()) { return (row["openingstock"].ToString()); } } } return ""; } public String AmountSold(int ProductId) { DataTable products = ProductTableAdapter.GetData(); foreach (DataRow row in products.Rows) { foreach (DataColumn column in products.Columns) { if (row[column].ToString() == ProductId.ToString()) { return (row["amountsold"].ToString()); } } } return ""; } public void UpdateStock(int Productid, int number) { try { amountsold = Convert.ToInt32(AmountSold(Productid)); currentstock = Convert.ToInt32(OpeningStock(Productid)); amountsold = amountsold + number; currentstock = currentstock - number; } catch (Exception io) { } } public void SaveStock(int Productid) { ProductTableAdapter.UpdateStockQuery(currentstock, amountsold, Productid); } } }
41f84b83d0d7a84d1a8d303ef1fcf31dc79eaf45
C#
zhoujunxian/CSharpHomework
/homework4/program2/OrderService.cs
2.921875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace program2 { public class OrderService { public void AddOrder(string OrderNum , string OrderName,string OrderBuyer ) { Order.OrderNum.Add(OrderNum); Order.OrderName.Add(OrderName); Order.OrderBuyer.Add(OrderBuyer); } public void DelectOrderByNum(string OrderNum) { bool flag= Order.OrderNum.Contains(OrderNum); if(flag == false) { Console.WriteLine("未找到订单"); } else { int n = Order.OrderNum.IndexOf(OrderNum); Order.OrderNum.RemoveAt(n); Order.OrderName.RemoveAt(n); Order.OrderBuyer.RemoveAt(n); } } public void DelectOrderByName(string OrderName) { bool flag = Order.OrderName.Contains(OrderName); if (flag == false) { Console.WriteLine("未找到订单"); } else { int n = Order.OrderName.IndexOf(OrderName); Order.OrderNum.RemoveAt(n); Order.OrderName.RemoveAt(n); Order.OrderBuyer.RemoveAt(n); } } public void DelectOrderByBuyer(string OrderBuyer) { bool flag = Order.OrderBuyer.Contains(OrderBuyer); if (flag == false) { Console.WriteLine("未找到订单"); } else { int n = Order.OrderBuyer.IndexOf(OrderBuyer); Order.OrderNum.RemoveAt(n); Order.OrderName.RemoveAt(n); Order.OrderBuyer.RemoveAt(n); } } public void SearchOrderByNum(string OrderNum) { bool flag = Order.OrderNum.Contains(OrderNum); if(flag == false) { Console.WriteLine("未找到订单"); } else { int n = Order.OrderNum.IndexOf(OrderNum); Console.Write(Order.OrderNum[n]+"\t"+Order.OrderName[n]+"\t"+Order.OrderBuyer[n]); Console.WriteLine() ; } } public void SearchOrderByName(string OrderName) { bool flag = Order.OrderName.Contains(OrderName); if (flag == false) { Console.WriteLine("未找到订单"); } else { int n = Order.OrderName.IndexOf(OrderName); Console.Write(Order.OrderNum[n] + "\t" + Order.OrderName[n] + "\t" + Order.OrderBuyer[n]); Console.WriteLine(); } } public void SearchOrderByBuyer(string OrderBuyer) { bool flag = Order.OrderBuyer.Contains(OrderBuyer); if (flag == false) { Console.WriteLine("未找到订单"); } else { int n = Order.OrderBuyer.IndexOf(OrderBuyer); Console.Write(Order.OrderNum[n] + "\t" + Order.OrderName[n] + "\t" + Order.OrderBuyer[n]); Console.WriteLine(); } } public void ChangeOrderByNum(string OldOrderNum, string NewOrderNum) { bool flag = Order.OrderNum.Contains(OldOrderNum); if (flag == false) { Console.WriteLine("未找到订单"); } else { int n = Order.OrderNum.IndexOf(OldOrderNum); Order.OrderNum[n] = NewOrderNum; } } public void ChangeOrderByName(string OldOrderName, string NewOrderName) { bool flag = Order.OrderName.Contains(OldOrderName); if (flag == false) { Console.WriteLine("未找到订单"); } else { int n = Order.OrderName.IndexOf(OldOrderName); Order.OrderName[n] = NewOrderName; } } public void ChangeOrderByBuyer(string OldOrderBuyer, string NewOrderBuyer) { bool flag = Order.OrderBuyer.Contains(OldOrderBuyer); if (flag == false) { Console.WriteLine("未找到订单"); } else { int n = Order.OrderBuyer.IndexOf(OldOrderBuyer); Order.OrderBuyer[n] = NewOrderBuyer; } } } }
07778cf2d423218a07ffb39e1ce7f2a1a0d5b30a
C#
chris11kgf/Anvil
/Project_Anvil/Assets/_scripts/Utility/ReadLocationFile.cs
2.546875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.IO; using Mapbox.Geocoding; using System.Text; using Mapbox.Json; using Mapbox.Platform; using Mapbox.Utils.JsonConverters; using Mapbox.Utils; using Mapbox.Unity; public class ReadLocationFile : MonoBehaviour { public List<string> allLocations; // Use this for initialization void Start() { } // Update is called once per frame void Update() { } // public List<string> ReadLocation() // takes input from a file and puts them into a list of strings to be used on splash screen public List<string> ReadLocation() { allLocations = new List<string>(); string fileName = "Locations"; string path = "Assets/Resources/" + fileName + ".txt"; StreamReader reader = new StreamReader(path); string readString = reader.ReadLine(); // Debug.Log("trying saving to: " + path); while (readString != null) { char[] delimiter = { ',' }; string[] fields = readString.Split(delimiter); allLocations.Add(fields[0]); readString = reader.ReadLine(); } return allLocations; } }
5032a15ee4ca5d5d113bebb6646712d5d6ddcdca
C#
johngt66/CodeKatas
/JT.CodeKataClasses/BuildTower.cs
3.09375
3
using System; public class BuildTower { public static string[] TowerBuilder(int nFloors) { string[] tower = new string[nFloors]; for(int i = 0; i < nFloors; i++) tower[i] = $"{new string(' ',nFloors-i-1)}{new string('*',(i+1)*2-1)}{new string(' ',nFloors-i-1)}"; return tower; } }
845b61ba6492def1dc4435e08b387d20a067d823
C#
nfsiam/OnlineBusTicketBookingSystem
/Backend/OnlineBusTicketBookingSystem/Controllers/ReportController.cs
2.546875
3
using OnlineBusTicketBookingSystem.Attributes; using OnlineBusTicketBookingSystem.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace OnlineBusTicketBookingSystem.Controllers { [RoutePrefix("api/reports"),BasicAuth] public class ReportController : ApiController { [Route("vendors/{id}/sales")] public IHttpActionResult GetSales(int id) { Dictionary<string, double> keyValuePairs = new Dictionary<string, double>(); BookingRepository bookingRepository = new BookingRepository(); var bookings = bookingRepository.GetAll().Where(b => b.BookingTime <= DateTime.Now && b.Trip.Bus.VendorId == id); foreach (var booking in bookings) { var str = booking.BookingTime.Date.ToShortDateString(); if (keyValuePairs.ContainsKey(str)) { keyValuePairs[str] += booking.Trip.Bus.PerSeatFair; } else { keyValuePairs.Add(str, booking.Trip.Bus.PerSeatFair); } } var dates = keyValuePairs.Keys; var sales = keyValuePairs.Values; keyValuePairs = new Dictionary<string, double>(); bookingRepository = new BookingRepository(); bookings = bookingRepository.GetAll().Where(b => b.Trip.Bus.VendorId == 1); BusRepository busRepository = new BusRepository(); var buses = busRepository.GetAll().Where(b => b.VendorId == 1); List<string> busList = new List<string>(); List<double> earning = new List<double>(); foreach (var bus in buses) { var b = bus.BusName + "[" + bus.BusId.ToString() + "]"; var d = 0.0; var trp = bus.Trips; foreach (var t in trp) { int pti = t.Bookings.Where(x => x.SeatStatus != "reserved").ToList().Count; d += pti * t.Bus.PerSeatFair; } //busList.Add(b); //earning.Add(d); keyValuePairs.Add(b, d); } var ordered = keyValuePairs.OrderByDescending(x => x.Value).Take(10).ToDictionary(x => x.Key, x => x.Value); int n = ordered.Count < 3 ? ordered.Count : 3; for (int i = 0; i < n; i++) { busList.Add(ordered.Keys.ElementAt(i)); earning.Add(ordered.Values.ElementAt(i)); } return Ok(new { dates, sales, busList, earning }); } [Route("vendors/{id}/sales-per-bus")] public IHttpActionResult GetSalesPerBus(int id) { Dictionary<string, double> keyValuePairs = new Dictionary<string, double>(); BookingRepository bookingRepository = new BookingRepository(); var bookings = bookingRepository.GetAll().Where(b=>b.Trip.Bus.VendorId == 1); BusRepository busRepository = new BusRepository(); var buses = busRepository.GetAll().Where(b => b.VendorId == 1); List<string> busList = new List<string>(); List<double> earning = new List<double>(); foreach (var bus in buses) { var b = bus.BusName + "[" + bus.BusId.ToString() + "]"; var d = 0.0; var trp = bus.Trips; foreach(var t in trp) { int pti = t.Bookings.Where(x => x.SeatStatus != "reserved").ToList().Count; d += pti * t.Bus.PerSeatFair; } //busList.Add(b); //earning.Add(d); keyValuePairs.Add(b, d); } var ordered = keyValuePairs.OrderByDescending(x => x.Value).Take(10).ToDictionary(x => x.Key, x => x.Value); int n = ordered.Count < 3 ? ordered.Count : 3; for(int i = 0; i< n; i++) { busList.Add(ordered.Keys.ElementAt(i)); earning.Add(ordered.Values.ElementAt(i)); } return Ok(new { busList, earning }); } } }
7dc8cda6aa321b8943c0b4c94b56944fc06fdaba
C#
xuzhg/Moutain
/SupermarketManagement/UseCases/RecordTransactionUseCase.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UseCases { public class RecordTransactionUseCase : IRecordTransactionUseCase { public RecordTransactionUseCase( ITransactionRepository transactionRepository, IGetProductByIdUseCase getProductByIdUseCase) { TransactionRepository = transactionRepository; GetProductByIdUseCase = getProductByIdUseCase; } public ITransactionRepository TransactionRepository { get; } public IGetProductByIdUseCase GetProductByIdUseCase { get; } public void Execute(string cashierName, int productId, int qty) { var product = GetProductByIdUseCase.Execute(productId); TransactionRepository .Save(cashierName, productId, product.Name, product.Price.Value, product.Quantity.Value, qty); } } }
a53a01e41e7529df699f935372073b34ceac6e40
C#
InVale/ManuMilitari
/Assets/Scripts/Manager/AnimationManager.cs
2.53125
3
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnimationManager : MonoBehaviour { public static AnimationManager Instance; List<AbilityTickable> _abilitiesToTick = new List<AbilityTickable>(); void Awake() { if (Instance) Destroy(this); else Instance = this; } public void PlayAnimation() { StartCoroutine(MovementAnimation()); } IEnumerator MovementAnimation() { int stepsToFinish = Mathf.CeilToInt(SettingManager.Instance.CurrentGameSetting.MovementTimeWindow / SettingManager.Instance.AnimationTimestep); int currentStep = 0; float timeSinceLastFrame = 0; foreach (Player player in TurnManager.Instance.Players) { foreach (Unit unit in player.Units) { if (!unit.IsDead && unit.HasOrder) { AbilityTickable ability = unit.UnitAbilities[unit.UnitOrder.Abilities[0].Item1].AbilityLogic(unit.UnitOrder.Abilities[0].Item2); if (ability) _abilitiesToTick.Add(ability); } } } while (currentStep < stepsToFinish) { timeSinceLastFrame += Time.deltaTime; if (timeSinceLastFrame >= SettingManager.Instance.AnimationTimestep) { timeSinceLastFrame -= SettingManager.Instance.AnimationTimestep; currentStep++; for (int i = 0; i < _abilitiesToTick.Count; i++) { if (_abilitiesToTick[i].Owner.IsDead || !_abilitiesToTick[i].TickMe(SettingManager.Instance.AnimationTimestep, currentStep == stepsToFinish)) { Destroy(_abilitiesToTick[i].gameObject); _abilitiesToTick.RemoveAt(i); i--; continue; } } } yield return null; } TurnManager.Instance.NewTurn(); } }
5e9c5f6fe9c2b51f5dc5c9ec3f7f9a03fa89d62b
C#
diffix/explorer
/src/explorer/Queries/ColumnProjections/DatetimeProjection.cs
2.921875
3
namespace Explorer.Queries { using System; using System.Text.Json; public class DatetimeProjection : ColumnProjection { private readonly string dateInterval; private readonly Random rng = new Random(); public DatetimeProjection(string column, int index, string dateInterval) : base(column, index) { this.dateInterval = dateInterval; } public override string Project() { return $"date_trunc('{dateInterval}', \"{Column}\")"; } public override object? Invert(JsonElement value) { if (value.ValueKind == JsonValueKind.Null) { return null; } var lowerBound = value.GetDateTime(); return dateInterval switch { // Add a random offset at the next lower level of granularity. "year" => lowerBound.AddMonths(rng.Next(12)), "quarter" => lowerBound.AddMonths(rng.Next(3)), "month" => lowerBound.AddDays(rng.NextDouble() * DateTime.DaysInMonth(lowerBound.Year, lowerBound.Month)), "day" => lowerBound.AddHours(rng.NextDouble() * 24), "hour" => lowerBound.AddMinutes(rng.NextDouble() * 60), "minute" => lowerBound.AddSeconds(rng.NextDouble() * 60), "second" => lowerBound.AddMilliseconds(rng.NextDouble() * 1000), _ => lowerBound, }; } } }
df72396fe34f5d9761105594b879d4438c50972d
C#
Chimnii/Algospot
/Problems/Programmers/Lv2.70129.cs
3.640625
4
using System; using System.Linq; public class Solution { public string int_to_binary(int one) { string s = ""; while(one > 0) { s += (one % 2 == 0 ? 0 : 1); one /= 2; } return new string(s.Reverse().ToArray()); } public int[] solution(string s) { int converted = 0, removed = 0; while (s.Length > 1) { int zero = s.Count(c => c == '0'); int one = s.Length - zero; removed += zero; converted += 1; s = int_to_binary(one); } return new int[] {converted, removed}; } }
da9cb8cceb4ed2b8831dac83a81929797f1ce8d3
C#
wei772/Lync
/Lync/Kiosk/Converters/LyncPresenceTextConverter.cs
2.609375
3
/* Copyright (C) 2012 Modality Systems - All Rights Reserved * You may use, distribute and modify this code under the * terms of the Microsoft Public License, a copy of which * can be seen at: http://www.microsoft.com/en-us/openness/licenses.aspx * * http://www.LyncAutoAnswer.com */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; namespace SuperSimpleLyncKiosk.Converters { class LyncPresenceTextConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return "Unknown"; if (value is string) { switch ((string)value) { case "Free": return "Available"; case "FreeIdle": return "Inactive"; case "Busy": return "Busy"; case "BusyIdle": return "Busy"; case "DoNotDisturb": return "Do Not Disturb"; case "TemporarilyAway": return "Be Right Back"; case "Away": return "Away"; case "Offline": return "Offline"; default: return "Unknown"; } } throw new NotImplementedException(); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(string)) { return (string)value; } throw new NotImplementedException(); } } }
c0881ab2e6a5f8d3cfe314a395029680ee700470
C#
Phoenix-Game/ValheimMP
/ValheimMP/Framework/Extensions/PrivateAreaExtension.cs
2.671875
3
namespace ValheimMP.Framework.Extensions { public enum PrivateAreaAllowMode { Private = 0, Clan = 1 << 0, Party = 1 << 1, Both = Clan | Party, } public static class PrivateAreaExtension { public static PrivateAreaAllowMode GetAllowMode(this PrivateArea privateArea) { if (privateArea.m_nview && privateArea.m_nview.m_zdo != null) { return (PrivateAreaAllowMode)privateArea.m_nview.m_zdo.GetInt("allowMode"); } return PrivateAreaAllowMode.Private; } public static void SetAllowMode(this PrivateArea privateArea, PrivateAreaAllowMode allowMode) { if (privateArea.m_nview && privateArea.m_nview.m_zdo != null) { privateArea.m_nview.m_zdo.Set("allowMode", (int)allowMode); } } } }
bc94352f07a39f3e32be9138b0b884aeeea9234e
C#
kontax/ListToolbox
/BIApps.ListToolbox.WpfFrontend/ViewModel/MergeViewModel.cs
2.609375
3
using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using BIApps.DialogService; using BIApps.ListToolbox.ListHelpers; using BIApps.ListToolbox.ListHelpers.Operators; using BIApps.ListToolbox.ListHelpers.Savers; using BIApps.ListToolbox.WpfFrontend.Helpers; using GalaSoft.MvvmLight.CommandWpf; using GalaSoft.MvvmLight.Messaging; namespace BIApps.ListToolbox.WpfFrontend.ViewModel { public class MergeViewModel : ViewModelBase { private readonly IListSaver _saver; private ICommand _mergeListsCommand; private UploadedListGroup _uploadedLists; /// <summary> /// The <see cref="UploadedList"/> collection that the user has selected to perform operations on. /// </summary> public UploadedListGroup UploadedLists { get { return _uploadedLists; } private set { if(Equals(value, _uploadedLists)) return; _uploadedLists = value; OnPropertyChanged(); } } /// <summary> /// The command used to merge the lists based on the selections made by the user. /// </summary> public ICommand MergeListsCommand { get { return _mergeListsCommand ?? (_mergeListsCommand = new RelayCommand( async () => await MergeLists(), CanMergeLists)); } } /// <summary> /// Instantiates a new <see cref="MergeViewModel"/>, which is the view model used for allowing /// the user to merge <see cref="UploadedList"/> objects together. /// </summary> /// <param name="messenger">The <see cref="IMessenger"/> used for sending messages to other view models</param> /// <param name="loading">The <see cref="ILoading"/> used for notifying users about running tasks</param> /// <param name="dialog">The <see cref="IDialogService"/> used to display messages to the user</param> /// <param name="saver">The <see cref="IListSaver"/> used to save the results of the operations</param> public MergeViewModel( IMessenger messenger, ILoading loading, IDialogService dialog, IListSaver saver) : base(messenger, loading, dialog) { _saver = saver; Messenger.Register<UploadedListGroup>(this, "Uploaded", SetUploadedLists); Messenger.Register<ProcessedCommand>(this, "Process", async pcmd => await ProcessCommand(pcmd)); } /// <summary> /// Process any command line arguments. /// </summary> /// <param name="pcmd">The <see cref="ProcessedCommand"/> with the methods necessary</param> private async Task ProcessCommand(ProcessedCommand pcmd) { if(pcmd.Method != Method.Merge) return; await MergeLists(); } /// <summary> /// Set the lists that the user has uploaded to be in context. /// </summary> /// <param name="lists">The <see cref="UploadedListGroup"/> containing the lists</param> private void SetUploadedLists(UploadedListGroup lists) { UploadedLists = lists; } /// <summary> /// Merges the <see cref="UploadedList"/> collection. /// </summary> private async Task MergeLists() { Loading.Start(); var merger = new Merger(UploadedLists); var output = await merger.Operate(); Messenger.Send(output, "Output"); _saver.SaveLists(output, output.FilePath, true); Loading.End(); } /// <summary> /// Whether the user is able to perform an operation on the lists or not. /// </summary> /// <returns>True if the user can operate, otherwise false</returns> private bool CanMergeLists() { return !Loading.Value && UploadedLists != null && UploadedLists.Count() >= 2; } } }
c907aa95c09d2fcf96b82e9ae385ba59a4914f3e
C#
fengjixuchui/AssemblyDefender
/src/AssemblyDefender.Net/Fusion/AssemblyEnumerator.cs
2.515625
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using AssemblyDefender.Common; namespace AssemblyDefender.Net.Fusion { public class AssemblyEnumerator : IEnumerable<AssemblyName>, IEnumerator<AssemblyName> { #region Fields private AssemblyName _current; private UnmanagedApi.IAssemblyEnum _assemblyEnum; #endregion #region Ctors public AssemblyEnumerator(UnmanagedApi.IAssemblyEnum assemblyEnum) { if (assemblyEnum == null) throw new ArgumentNullException("assemblyEnum"); _assemblyEnum = assemblyEnum; } #endregion #region Properties public AssemblyName Current { get { return _current; } } object IEnumerator.Current { get { return _current; } } public UnmanagedApi.IAssemblyEnum IAssemblyEnum { get { return _assemblyEnum; } } #endregion #region Methods public bool MoveNext() { UnmanagedApi.IAssemblyName name; HRESULT.ThrowOnFailure(_assemblyEnum.GetNextAssembly(IntPtr.Zero, out name, 0)); if (name != null) _current = new AssemblyName(name); else _current = null; return _current != null; } public void Reset() { } public void Dispose() { } public IEnumerator<AssemblyName> GetEnumerator() { return this; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
34c410190c5911138a76e01a57d6650794c2a3e5
C#
JaredsRydalch/DemonicPursuit
/Book of the Dead/Form1.cs
2.6875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Book_of_the_Dead { public partial class Form1 : Form { public string name; public Form1() { InitializeComponent(); } public void button1_Click(object sender, EventArgs e) { if (radioButtonPhar.Checked == true) { Form2 Phar = new Form2(2, this, getMonster()); Phar.Show(); this.Hide(); } if (radioButtonNoble.Checked == true) { Form2 Noble = new Form2(3, this, getMonster()); Noble.Show(); this.Hide(); } if (radioButtonSlave.Checked == true) { Form2 Slave = new Form2(4, this, getMonster()); Slave.Show(); this.Hide(); } } public Monster getMonster() { if (radioButton2.Checked == true) { return new Monster(-1, 120, .025f, .005f, -1, -1, Monster.Monster_Type.Normal); } if (radioButton3.Checked == true) { return new Monster(32, 60, .015f, -1, -1, -1, Monster.Monster_Type.Glutton); } if (radioButton4.Checked == true) { return new Monster(-1, 60, .025f, .005f, -1, -1, Monster.Monster_Type.Ghost); } if (radioButton5.Checked == true) { return new Monster(Monster.Monster_Type.Posessor); } if (radioButton6.Checked == true) { return new Monster(-1, 0, .03f, .02f, -1, -1, Monster.Monster_Type.Normal); } if (radioButton7.Checked == true) { return new Monster(-1, -1, -1, .02f, 50, 50, Monster.Monster_Type.Normal); } if (radioButton8.Checked == true) { return new Monster(Monster.Monster_Type.Hook); } return new Monster(Monster.Monster_Type.Normal); } private void Form1_Load(object sender, EventArgs e) { } } }
0dd53c98cbc877b8853931a3038c9de2bd02fe11
C#
kleevs/user-manager-api
/src/Tool/Security/Hasher.cs
2.78125
3
using System.Security.Cryptography; using System.Text; namespace Tool { public class Hasher : IHasher { private SHA256 _SHA256; public Hasher() { _SHA256 = SHA256.Create(); } public string Compute(string text) { return System.Convert.ToBase64String(_SHA256.ComputeHash(Encoding.UTF8.GetBytes(text))); } } }
d606b26e7ad07cd83bed1cdbf30fc9ac658e188e
C#
deadbatterygames/system-fault
/Assets/Scripts/Combat/Explosion.cs
2.546875
3
using System.Collections; using UnityEngine; // // Explosion.cs // // Author: Eric Thompson (Dead Battery Games) // Purpose: An explosion that damages anything in a certain radius // public class Explosion : MonoBehaviour { const float DAMAGE = 250f; const float FORCE = 100f; float damageRadius; void Start() { SphereCollider sphere = GetComponent<SphereCollider>(); if (!sphere) Debug.LogError("Explosion: No sphere collider attached to explosion"); damageRadius = sphere.radius; Destroy(sphere); StartCoroutine("Explode"); } IEnumerator Explode() { Collider[] colliders = Physics.OverlapSphere(transform.position, damageRadius); foreach (Collider col in colliders) { Rigidbody rb = col.GetComponent<Rigidbody>(); if (rb) rb.AddExplosionForce(FORCE, transform.position, damageRadius, 0f, ForceMode.Impulse); IDamageable damageable = col.GetComponentInParent<IDamageable>(); if (damageable != null) { Vector3 centerToObject = col.transform.position - transform.position; Vector3 damageForce = centerToObject.normalized * FORCE; damageable.Damage(DAMAGE, GameTypes.DamageType.Physical, damageForce, Vector3.zero, Vector3.zero); } } yield return new WaitForSeconds(3f); Destroy(gameObject); } }
a50a50bf0c2201da2c150bbb8d0366940193ba38
C#
mattdoller/RandomData
/RandomData/Categories/RandomLocation.cs
2.765625
3
using System; using RandomData.Data; using RandomData.Extensions; using RandomData.Generators; namespace RandomData.Categories { public class RandomLocation : RandomCategoryBase { public RandomLocation(IRandomGenerator random) : base(random) { } public string AddressLine1() { return String.Format( "{0} {1} {2}.", NumericString(3), NewRandom().PickFrom(Locations.StreetNames), NewRandom().PickFrom(Locations.StreetTypes) ); } public string AddressLine2() { return String.Format( "{0}. {1}", NewRandom().PickFrom(Locations.AddressLine2Types), NumericString(3) ); } public string City() { return NewRandom().PickFrom(Locations.Cities); } public string ZipCode() { return NumericString(5); } public string ZipCodePlusFour() { return String.Format("{0}-{1}", ZipCode(), NumericString(4)); } public string PostalCode(PostalCodeFormat format = PostalCodeFormat.UnitedStatesZipCode) { switch (format) { case (PostalCodeFormat.UnitedStatesZipCode) : return ZipCode(); case (PostalCodeFormat.UnitedStatesZipCodePlusFour) : return ZipCodePlusFour(); case (PostalCodeFormat.Canada) : return PostalCodeCanada(); case (PostalCodeFormat.UnitedKingdom) : return PostalCodeUnitedKingdom(); default: throw new ArgumentException("Unrecognized PostalCodeFormat"); } } public string State() { return NewRandom().PickFrom(Locations.StateAbbreviations); } public string StateName() { return NewRandom().PickFrom(Locations.States); } public string Country() { return NewRandom().PickFrom(Locations.Countries); } private string PostalCodeCanada() { return String.Format("{0}{1}{2} {3}{4}{5}", RandomAlphaCharacter(), RandomNumericCharacter(), RandomAlphaCharacter(), RandomNumericCharacter(), RandomAlphaCharacter(), RandomNumericCharacter() ); } private string PostalCodeUnitedKingdom() { return String.Format("{0} {1}", AlphanumericString(4), AlphanumericString(3) ); } } public enum PostalCodeFormat { UnitedStatesZipCode, UnitedStatesZipCodePlusFour, Canada, UnitedKingdom } }
eca81cee316668bc0b9470aa40186da8fc8ac19d
C#
Mezion/WhatsYourAddiction
/Log635Lab03_Winform/Log635Lab03_Winform/KNN2.cs
2.984375
3
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; ////////////////////////////////////////////////////////////////////// using System.IO; using MathNet.Numerics.Statistics; namespace Log635Lab03_Winform { public enum KNNInterpretation { Mean, Median, Mode } public class KNN2 { private readonly int _neighborsInCondideration; private KNNInterpretation _interpretation; /// <summary> /// Liste de chaque row a evaluer contenant /// une liste de tous les voisins les plus proche pour chacune des rows /// Le voisin est un tuple qui contient la distance et la DataRow ( le data du voisin ) /// </summary> private List<List<Tuple<double, DataRow>>> _nearers = new List<List<Tuple<double, DataRow>>>(); private List<string> _columnsInConsideration; private DrugDataset _drugDataset; private DrugDataset _predictionDataset; public KNN2(DrugDataset drugDataset, List<string> columnsInConsideration, DrugDataset predictionDataset, int neighborsInCondideration, KNNInterpretation interpretation) { _drugDataset = drugDataset; _columnsInConsideration = columnsInConsideration; _predictionDataset = predictionDataset; _neighborsInCondideration = neighborsInCondideration; _interpretation = interpretation; _predictionDataset.CleanAllColumns(); _drugDataset.CleanAllColumns(); Predict(); ShowResult(); Interpret(); } private void Predict() { _nearers.Clear(); int index = 0; foreach (DataRow rowToPredict in _predictionDataset.DrugDataTable.Rows) { var neighbors = new List<Tuple<double, DataRow>>(); foreach (DataRow dataRow in _drugDataset.DrugDataTable.Rows) { var sum = 0.0; _columnsInConsideration.ForEach(column => { sum += Math.Pow( double.Parse(rowToPredict[column].ToString()) - double.Parse(dataRow[column].ToString()), 2); }); var distance = Math.Sqrt(sum); if (neighbors.Count < _neighborsInCondideration) { neighbors.Add(new Tuple<double, DataRow>(distance, dataRow)); neighbors = neighbors.OrderBy(n => n.Item1).ToList(); continue; } var indexPivot = -1; for (int i = 0; i < neighbors.Count; i++) { if (distance < neighbors[i].Item1) { indexPivot = i; break; } } if (indexPivot != -1) { var replacementNeighbor = new Tuple<double, DataRow>(distance, dataRow); for (int i = indexPivot; i < neighbors.Count; i++) { var tempNeighbor = neighbors[i]; neighbors[i] = replacementNeighbor; replacementNeighbor = new Tuple<double, DataRow>(tempNeighbor.Item1, tempNeighbor.Item2); } } } _nearers.Add(neighbors); Logger.LogMessage($"{neighbors.Count} nearer neighbors have been found for row {index}"); index++; } } private void ShowResult() { var index = 0; foreach (var nearer in _nearers) { var nicotine = nearer.Select(ne => { var value = double.Parse(ne.Item2["Nicotine"].ToString()); return $"Nicotine: {Math.Round(value * 6, 0, MidpointRounding.ToEven)} Distance: {ne.Item1}"; }); Logger.LogMessage( $"Nearer neighbors for row {index} has a Nicotine of \n- {string.Join("\n- ", nicotine)}"); index++; } } private void Interpret() { var index = 0; Logger.LogMessage("\n\nInterprétation des résultats"); foreach (var nearer in _nearers) { var nicotine = nearer.Select(ne => { var value = double.Parse(ne.Item2["Nicotine"].ToString()); return Math.Round(value * 6, 0, MidpointRounding.ToEven); }).ToList(); var result = -1.0; switch (_interpretation) { case KNNInterpretation.Mean: result = Math.Round(nicotine.Mean(), 0, MidpointRounding.ToEven); break; case KNNInterpretation.Median: result = nicotine.Median(); break; case KNNInterpretation.Mode: result = nicotine.GroupBy(d => d) .OrderByDescending(g => g.Count()) .First() .Key; break; } Logger.LogMessage($"Prediction for row {index} is {result}"); index++; } } } }
db8ed4c478216fe9f7936cec4efe25b19678c221
C#
spencewalters/hobby
/ProvingGrounds/HobbyGame/CycleTimer.cs
3.03125
3
using System; using System.Diagnostics; namespace HobbyGame { class CycleTimer { private Stopwatch stopWatch; private UInt32 count; public double CyclesPerSecond { get; internal set; } public UInt32 SecondsPerCalculation; public CycleTimer() { SecondsPerCalculation = 1; CyclesPerSecond = 0; count = 0; stopWatch = Stopwatch.StartNew(); } private void ResetWatch() { count = 0; stopWatch.Restart(); } public void CountCycle() { count++; if (stopWatch.Elapsed.TotalSeconds > SecondsPerCalculation) { CyclesPerSecond = count / stopWatch.Elapsed.TotalSeconds; ResetWatch(); } } } }
56741c895384036a18d86e487a8f290e3fc6941a
C#
LYLStudio/LYLCore
/LStudio.Core/LStudio.Core/Core/ObjectExtensions.cs
3.109375
3
namespace LStudio.Core { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; public static class ObjectExtensions { /// <summary> /// 物件屬性複製,自己複製到其他 /// </summary> /// <typeparam name="TSrc">來源類別</typeparam> /// <typeparam name="TDest">目標類別</typeparam> /// <param name="src">來源物件</param> /// <param name="dest">目標物件</param> /// <param name="skipSrcNull">忽略來源空值</param> /// <param name="skipDestNull">忽略目標空值</param> /// <param name="excludeProeprties">排除的屬性清單</param> public static void CopyPropertyTo<TSrc, TDest>(this TSrc src, TDest dest, bool skipSrcNull = true, bool skipDestNull = true, params string[] excludeProeprties) where TSrc : class where TDest : class { ObjectHelper.CopyPropeties(src, dest, skipSrcNull, skipDestNull, excludeProeprties); } /// <summary> /// 物件屬性複製,從其他複製到自己 /// </summary> /// <typeparam name="TDest">目標類別</typeparam> /// <typeparam name="TSrc">來源類別</typeparam> /// <param name="dest">目標物件</param> /// <param name="src">來源物件</param> /// <param name="skipSrcNull">忽略來源空值</param> /// <param name="skipDestNull">忽略目標空值</param> /// <param name="excludeProeprties">排除的屬性清單</param> public static void CopyPropertyFrom<TDest, TSrc>(this TDest dest, TSrc src, bool skipSrcNull = true, bool skipDestNull = true, params string[] excludeProeprties) where TSrc : class where TDest : class { ObjectHelper.CopyPropeties(src, dest, skipSrcNull, skipDestNull, excludeProeprties); } /// <summary> /// 從<typeparamref name="TSrc"/>複寫屬性值至<typeparamref name="TDest"/> /// </summary> /// <typeparam name="TSrc">來源類別,等同<typeparamref name="TDest"/>或<typeparamref name="TDest"/>的基底類別</typeparam> /// <typeparam name="TDest">目標類別</typeparam> /// <param name="src">來源物件</param> /// <param name="dest">目標物件</param> public static void OverridePropertiesTo<TSrc, TDest>(this TSrc src, TDest dest) where TDest : class, TSrc { ObjectHelper.OverrideProperties(src, dest); } /// <summary> /// 從<typeparamref name="TSrc"/>複寫屬性值至<typeparamref name="TDest"/> /// </summary> /// <typeparam name="TDest">目標類別</typeparam> /// <typeparam name="TSrc">來源類別,等同<typeparamref name="TDest"/>或<typeparamref name="TDest"/>的基底類別</typeparam> /// <param name="dest">目標物件</param> /// <param name="src">來源物件</param> public static void OverridePropertiesFrom<TDest, TSrc>(this TDest dest, TSrc src) where TDest : class, TSrc { ObjectHelper.OverrideProperties(src, dest); } /// <summary> /// 迴圈透過<paramref name="callback"/>取屬性為KeyValuePair /// </summary> /// <typeparam name="T">對象類別</typeparam> /// <param name="value">對象物件</param> /// <param name="callback">Callback函式</param> public static void ForEachProperty<T>(this T value, Action<NameValue> callback) { ObjectHelper.ForEachProperty(value, callback); } /// <summary> /// 迴圈透過<paramref name="callback"/>取屬性為KeyValuePair,並且針對屬性進行操作 /// </summary> /// <typeparam name="T">對象類別</typeparam> /// <param name="value">對象物件</param> /// <param name="callback">Callback函式</param> public static void ForEachProperty<T>(this T value, Action<PropertyInfo, NameValue> callback) { ObjectHelper.ForEachProperty(value, callback); } public static bool EqualsObject(this object value, object targetValue) { if (value is null) throw new ArgumentNullException(nameof(value)); if (targetValue is null) throw new ArgumentNullException(nameof(targetValue)); var targetArray = GetObjectByte(value); var expectedArray = GetObjectByte(targetValue); var equals = expectedArray.SequenceEqual(targetArray); return equals; } private static byte[] GetObjectByte(object model) { using (MemoryStream memory = new MemoryStream()) { System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(model.GetType()); xs.Serialize(memory, model); var array = memory.ToArray(); return array; } } //public static TDest CloneByJson<TDest, TSrc>(this TSrc source) //{ // TDest dest = default(TDest); // // initialize inner objects individually // // for example in default constructor some list property initialized with some values, // // but in 'source' these items are cleaned - // // without ObjectCreationHandling.Replace default constructor values will be added to result // var deserializeSettings = new JsonSerializerSettings // { // ObjectCreationHandling = ObjectCreationHandling.Replace, // ReferenceLoopHandling = ReferenceLoopHandling.Ignore, // }; // string json = JsonConvert.SerializeObject(source, deserializeSettings); // dest = JsonConvert.DeserializeObject<TDest>(json); // return dest; //} } }
5a19c95dafd5164f0a4c125f0cb10d04224fdd6c
C#
Ku6epnec/Lesson5
/Assets/Scripts/Enemy.cs
2.796875
3
using UnityEngine; public class Enemy : IEnemy { #region Fields private const float KPower = 1.2f; private const float KMoneyPower = 0.7f; private string _name; private int _countMoney; private int _countHealth; private int _countPower; private int _countCrime; #endregion #region UnityMethods public void Update(DataPlayer dataPlayer, DataType dataType) { switch (dataType) { case DataType.Money: _countMoney = dataPlayer.CountMoney; break; case DataType.Health: _countHealth = dataPlayer.CountHealth; break; case DataType.Power: _countPower = dataPlayer.CountPower; break; case DataType.CrimeLvl: _countCrime = dataPlayer.CountCrime; break; } Debug.Log($"Notify {_name} data {dataType}"); } #endregion #region OtherMethods public Enemy(string name) { _name = name; } public int Power { get { var countPower = (int)((_countPower + _countCrime) * KPower) - _countHealth - (int)(_countMoney * KMoneyPower); return countPower; } } #endregion }
7f41e0eff7517329a85cd4989d95815d4c059a39
C#
sapphire119/SoftUni
/techModule/Conditional Statements and Loops ДР/11.FiveDiffrentNumbers/Program.cs
3.609375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _11.FiveDiffrentNumbers { class Program { static void Main(string[] args) { var input = int.Parse(Console.ReadLine()); var second = int.Parse(Console.ReadLine()); for (int i = input; i <= second - 4; i++) { for (int j = input + 1; j <= second - 3; j++) { for (int k = input + 2; k <= second - 2; k++) { for (int h = input + 3; h <= second - 1; h++) { for (int p = input + 4; p <= second; p++) { if (input <= i && i < j && j < k && k < h && h < p && h <= second) { Console.WriteLine("{0} {1} {2} {3} {4}", i, j, k, h, p); } } } } } } if ((second -input) <5) { Console.WriteLine("No"); } } } }
a77ee9311fc6781bbe60465061052a6cee7927e5
C#
NickSegalle/crane
/src/Crane.Core/Configuration/ServiceLocator.cs
2.578125
3
using System; using System.Collections.Generic; using Autofac; using Crane.Core.Api; using Crane.Core.Configuration.Modules; namespace Crane.Core.Configuration { /// <summary> /// In the powershell cmdlet, havn't figured out a way to wire up /// the ioc engine, so using ServiceLocator until we do. /// </summary> public static class ServiceLocator { private static IContainer _container; private static IContainer Container { get { if (_container == null) { _container = BootStrap.Start(); } return _container; } } public static T BuildUp<T>(T item) { return Container.InjectProperties(item); } public static T Resolve<T>() where T : class { if (Container.IsRegistered<T>()) { return Container.Resolve<T>(); } return ResolveUnregistered(Container, typeof(T)) as T; } public static object ResolveUnregistered(IContainer container, Type type) { var constructors = type.GetConstructors(); foreach (var constructor in constructors) { try { var parameters = constructor.GetParameters(); var parameterInstances = new List<object>(); foreach (var parameter in parameters) { var service = container.Resolve(parameter.ParameterType); if (service == null) throw new Exception("Unkown dependency"); parameterInstances.Add(service); } return Activator.CreateInstance(type, parameterInstances.ToArray()); } catch (Exception) { } } throw new Exception("No contructor was found that had all the dependencies satisfied."); } } }
d93ec2c0fe703309598adeaa8e7b402900dfa9e5
C#
FoKycHuK/cs101-lectures
/Term2/Lecture06/S04.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace S04 { class Angle { double value; public static Angle operator+(Angle a, Angle b) { return new Angle { value=a.value+b.value }; } public static Angle operator*(Angle a, double c) { return new Angle { value=a.value*c }; } public static Angle operator *(double c, Angle a) { return new Angle { value = a.value * c }; } public static double operator /(Angle a, Angle b) { return a.value / b.value; } } }
78fcadcfe615669dff16fa96fd45b477b4f1fd06
C#
cmdrmander/Manderplan
/Masterplan/Data/PowerAction.cs
2.546875
3
using System; namespace Masterplan.Data { [Serializable] public class PowerAction { public const string RECHARGE_2 = "Recharges on 2-6"; public const string RECHARGE_3 = "Recharges on 3-6"; public const string RECHARGE_4 = "Recharges on 4-6"; public const string RECHARGE_5 = "Recharges on 5-6"; public const string RECHARGE_6 = "Recharges on 6"; private ActionType fAction = ActionType.Standard; private string fTrigger = ""; private ActionType fSustainAction; private PowerUseType fUse = PowerUseType.AtWill; private string fRecharge = ""; public ActionType Action { get { return this.fAction; } set { this.fAction = value; } } public string Recharge { get { return this.fRecharge; } set { this.fRecharge = value; } } public ActionType SustainAction { get { return this.fSustainAction; } set { this.fSustainAction = value; } } public string Trigger { get { return this.fTrigger; } set { this.fTrigger = value; } } public PowerUseType Use { get { return this.fUse; } set { this.fUse = value; } } public PowerAction() { } public PowerAction Copy() { PowerAction powerAction = new PowerAction() { Action = this.fAction, Trigger = this.fTrigger, SustainAction = this.fSustainAction, Use = this.fUse, Recharge = this.fRecharge }; return powerAction; } public override string ToString() { string str = ""; if (this.fUse == PowerUseType.AtWill || this.fUse == PowerUseType.Basic) { str = "At-Will"; if (this.fUse == PowerUseType.Basic) { str = string.Concat(str, " (basic attack)"); } } if (this.fUse == PowerUseType.Encounter && this.fRecharge == "") { str = "Encounter"; } if (this.fUse == PowerUseType.Daily) { str = "Daily"; } if (this.fRecharge != "") { if (str != "") { str = string.Concat(str, "; "); } str = string.Concat(str, this.fRecharge); } return str; } } }
0e35e1c30bf6deae8f15bd1555e8cc768a9b596f
C#
davidsl4/AmongUs-YouTubeIL
/YouTubeIL/Options/CustomOption.String.cs
3.015625
3
using System; using System.Collections.Generic; using UnityEngine; namespace YouTubeIL.Options { internal interface IStringOption { public void Increase(); public void Decrease(); public string GetText(); } internal sealed class CustomStringOption : CustomOption, IStringOption { private readonly string[] _values; /// <summary> /// The text values the option can present. /// </summary> public IReadOnlyCollection<string> Values => Array.AsReadOnly(_values); public CustomStringOption(string id, string name, string[] values, uint value, CustomOption parentOption = null) : base(id, name, CustomOptionType.String, (int)value, parentOption) { _values = values; ValueStringFormat = (_, v) => _values[(int) v]; } protected override bool GameOptionCreated(OptionBehaviour o) { base.GameOptionCreated(o); if (o is not StringOption str) return false; str.TitleText.Text = GetFormattedName(); str.Value = str.oldValue = GetValue(); str.ValueText.Text = GetFormattedValue(); return true; } public void Increase() { var newValue = Mathf.Clamp(GetValue() + 1, 0, _values.Length - 1); SetValue(newValue); } public void Decrease() { var newValue = Mathf.Clamp(GetValue() - 1, 0, _values.Length - 1); SetValue(newValue); } private void SetValue(int value, bool raiseEvents = true) { if (value < 0 || value >= _values.Length) value = GetDefaultValue(); base.SetValue(value, raiseEvents); } /// <returns>The int-casted default value.</returns> private int GetDefaultValue() { return GetDefaultValue<int>(); } /// <returns>The int-casted old value.</returns> public int GetOldValue() { return GetOldValue<int>(); } /// <returns>The int-casted current value.</returns> private int GetValue() { return GetValue<int>(); } /// <returns>The text at index <paramref name="value"/>.</returns> private string GetText(int value) { return _values[value]; } /// <returns>The current text.</returns> public string GetText() { return GetText(GetValue()); } } internal abstract partial class CustomOption { public static CustomStringOption AddString(string id, string name, string[] values, uint defaultValue = 0, CustomOption parentOption = null) => new(id, name, values, defaultValue, parentOption); } }
da31e325c97706c3c921f65471760630b78a95cc
C#
ThomasMathew1993/Learning
/LinkedListUser.cs
3.71875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStructure { public class LinkedListUser { private Node head; private Node tail; private int length; public LinkedListUser(int value) { head = new Node() { Value = value, Next = null }; tail = head; length = 1; } public LinkedListUser(List<int> values) { int i = 0; foreach (var value in values) { if (i == 0) { head = new Node() { Value = value, Next = null }; tail = head; length = 1; i++; } else { Append(value); } } } public void Append(int value) { var node = new Node() { Value = value, Next = null }; tail.Next = node; tail = node; length++; } public void Prepend(int value) { head = new Node() { Value = value, Next = head }; length++; } public void Insert(int index, int value) { var currentNode = this.head; if (index == 0) { Prepend(value); } else if (index >= length - 1) { Append(value); } else { ActualInsert(index, value, currentNode); } } private void ActualInsert(int index, int value, Node currentNode) { for (int i = 0; i <= index; i++) { if (i == index - 1) { var node = new Node() { Value = value, Next = currentNode.Next }; currentNode.Next = node; } else { currentNode = currentNode.Next; } } length++; } public void Remove(int index) { if (index > length - 1) { Console.Write("Invalid Index"); } var currentNode = this.head; Node node = new Node(); for (int i = 0; i <= index + 1; i++) { if (i == index - 1) { node = currentNode; } else if (i == index + 1) { node.Next = currentNode; } currentNode = currentNode.Next; } length--; } public void Print() { var currentNode = this.head; while (currentNode != null) { Console.WriteLine(currentNode.Value); currentNode = currentNode.Next; } } public int GetLength() { return length; } public void Reverse() { Node firstnode = this.head; Node secondNode = firstnode.Next; tail = firstnode; while (secondNode != null) { var nextNode = secondNode.Next; secondNode.Next = firstnode; firstnode = secondNode; secondNode = nextNode; } this.head = firstnode; tail.Next = null; } } public class Node { public int Value { get; set; } public Node Next { get; set; } } }
2ef0c0d7d05e27c228c1ae82a43afa3819dd22f1
C#
shendongnian/download4
/first_version_download2/539876-50681226-174882175-2.cs
2.640625
3
public static IObservable<T> When<T>(this IObservable<T> source, IObservable<bool> gate) { return source.Publish(ss => gate.Publish(gs => gs .Select(g => g ? ss : ss.IgnoreElements()) .Switch() .TakeUntil(Observable.Amb( ss.Select(s => true).Materialize().LastAsync(), gs.Materialize().LastAsync())))); }
d4ce8e3709b43d8dd16d2bc3ec40fbf6f3248466
C#
Rbeninche/RestaurantMenu
/ConsoleUI/MenuItem.cs
3.078125
3
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace ConsoleUI { //price, description, and category class MenuItem { public double Price { get; set; } public string Description { get; set; } public string Category { get; set; } private static int ID = 0; private int _menuItemID = 0; public int MenuItemID { get { return _menuItemID; } } public DateTime TimeAdded { get; set; } = DateTime.Now; public MenuItem() { ID++; this._menuItemID = ID; } public MenuItem(double price, string description, string category, DateTime timeAdded) { Price = price; Description = description; Category = category; TimeAdded = timeAdded; ID++; this._menuItemID = ID; } public MenuItem(double price, string description, string category) : this(price, description, category, DateTime.Now) { } public string Status() { //Convert.ToInt32(myTimeSpan.TotalDays) TimeSpan value = DateTime.Now.Subtract(TimeAdded); int valueInt = Convert.ToInt32(value.TotalDays); if (valueInt < 365) { return $"Updated {valueInt} days ago -(NEW)"; } return $"Updated {valueInt} days - (OLD)"; } public void Update([Optional]double price, [Optional] string description, [Optional] string category) { double oldPrice; oldPrice = Price; string oldDescription = Description, oldCategory = Category; Price = price; Description = description; Category = category; if (!oldPrice.Equals(price) || !oldDescription.Equals(description) || !oldCategory.Equals(category)) { TimeAdded = DateTime.Now; } } public override bool Equals(object toBeCompared) { if (toBeCompared == this) { return true; } if (toBeCompared == null) { return false; } if (toBeCompared.GetType() != this.GetType()) { return false; } MenuItem m = toBeCompared as MenuItem; return m.MenuItemID == MenuItemID; } public override int GetHashCode() { // Which is preferred? return base.GetHashCode(); } } }
a8f62863499ebdf8042dd39e07331a9765859b4e
C#
goblinfactory/konsole
/src/Konsole.Samples/Samples/WindowClientServerSamples.cs
2.984375
3
using Konsole.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.ConsoleColor; namespace Konsole.Samples { public static class WindowClientServerSamples { public static void Demo() { var con = Window.OpenBox("client server demo", 110, 30); con.WriteLine("starting client server demo"); var client = new Window(1, 4, 20, 20, ConsoleColor.Gray, ConsoleColor.DarkBlue, con).Concurrent(); var server = new Window(25, 4, 20, 20, con).Concurrent(); client.WriteLine("CLIENT"); client.WriteLine("------"); server.WriteLine("SERVER"); server.WriteLine("------"); client.WriteLine("<-- PUT some long text to show wrapping"); server.WriteLine(ConsoleColor.DarkYellow, "--> PUT some long text to show wrapping"); server.WriteLine(ConsoleColor.Red, "<-- 404|Not Found|some long text to show wrapping|"); client.WriteLine(ConsoleColor.Red, "--> 404|Not Found|some long text to show wrapping|"); con.WriteLine("starting names demo"); // let's open a window with a box around it by using Window.Open var names = Window.OpenBox("names", 50, 4, 40, 10); TestData.MakeNames(40).OrderByDescending(n => n).ToList() .ForEach(n => names.WriteLine(n)); con.WriteLine("starting numbers demo"); var numbers = Window.OpenBox("{numbers", 50, 15, 40, 10, new BoxStyle() { ThickNess = LineThickNess.Double, Body = new Colors(White, Blue) }); Enumerable.Range(1, 200).ToList() .ForEach(i => numbers.WriteLine(i.ToString())); // shows scrolling Console.ReadKey(true); } } }
8e00f01c72a981b3ca4bf6d5d085cc256514f753
C#
yang872546/ego.nefsedit
/VictorBush.Ego.NefsLib/Header/NefsHeaderPt5Entry.cs
2.75
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using VictorBush.Ego.NefsLib.DataTypes; namespace VictorBush.Ego.NefsLib.Header { /// <summary> /// Purpose of part 5 entries are unknown. /// </summary> public class NefsHeaderPt5Entry { public const UInt32 SIZE = 4; NefsHeaderPt5 _parent; /// <summary>The relative offset into part 5 where the entry begins.</summary> UInt32 _relOffset; [FileData] ByteArrayType byte1 = new ByteArrayType(0x00, 0x01); [FileData] ByteArrayType byte2 = new ByteArrayType(0x01, 0x01); [FileData] ByteArrayType byte3 = new ByteArrayType(0x02, 0x01); [FileData] ByteArrayType byte4 = new ByteArrayType(0x03, 0x01); /// <summary> /// Loads an entry from a file stream. /// </summary> /// <param name="file">The file stream to load from.</param> /// <param name="parent">The part 5 obj this entry belongs to.</param> /// <param name="relOffset">The relative offset into part 5 where the entry begins.</param> public NefsHeaderPt5Entry(FileStream file, NefsHeaderPt5 parent, UInt32 relOffset) { _parent = parent; _relOffset = relOffset; /* Read data from file as defined by [FileData] fields. */ FileData.ReadData(file, _parent.Offset + relOffset, this); } public byte Byte1 { get { return byte1.Value[0]; } } public byte Byte2 { get { return byte2.Value[0]; } } public byte Byte3 { get { return byte3.Value[0]; } } public byte Byte4 { get { return byte4.Value[0]; } } /// <summary> /// The relative offset into part 5 where the entry begins. /// </summary> public UInt32 RelOffset { get { return _relOffset; } } /// <summary> /// Writes this entry to a file stream. /// </summary> /// <param name="file">The file stream to write to.</param> public void Write(FileStream file) { FileData.WriteData(file, _parent.Offset + _relOffset, this); } } }
d94b590434802a801fad5aba76491e7a2847e50f
C#
kirbycope/sdetqa-framework-c-sharp
/FrameworkCommon/Toolbox/JsonUtils.cs
3.3125
3
using Newtonsoft.Json.Linq; namespace FrameworkCommon.Toolbox { public class JsonUtils { /// <summary> /// Serializes the JArray into a string. /// </summary> public string JsonArrayToString(JArray jArray) { return jArray.ToString(); } /// <summary> /// Serializes the JArray into a string. /// </summary> public string JsonObjectToString(JObject jObject) { return jObject.ToString(); } /// <summary> /// Deserializes the string into a JObject. /// </summary> public static JArray StringToJsonArray(string jsonString) { return JArray.Parse(jsonString); } /// <summary> /// Deserializes the string into a JObject. /// </summary> public static JObject StringToJsonObject(string jsonString) { return JObject.Parse(jsonString); } /// <summary> /// Gets the value of the given property from the given JSON string. /// </summary> /// <param name="jsonString">The string representation of the JSON object.</param> /// <param name="property">The property for which the value is returned.</param> /// <returns>The value of the given property as a string.</returns> public static string GetPropertyValueFromJsonString(string jsonString, string property) { // Convert the string to a JSON object JObject settings = StringToJsonObject(jsonString); // Return the given property's value return settings[property].ToString(); } } }
05e5c1243d486bdee32fc6f6414401010f9b56fe
C#
AleXFiLforGB/SoftwareDesignPattern
/Pattern/015Iterator/SimpleIterator/Program.cs
3.59375
4
using static System.Console; using System.Linq; namespace SimpleIterator { class Program { static void Main() { var array = Enumerable.Range(1, 10).ToArray(); //foreach (var item in array) Write($"{item} "); // Ошибка CS1579 Оператор foreach не работает с переменными типа "Set<int>" // так как "Set<int>" не содержит открытое // определение экземпляра или расширения для "GetEnumerator" //foreach (var item in set) Write($"{item} "); SimpleSet<int> set = new(array); WriteLine(); set.Reset(); while (set.MoveNext()) Write($"{set.Current} "); WriteLine(); } } }
3c96f17fa34cb30a010cf85faa3400d98e3980b1
C#
bannadude/Condurance
/TDD/MyStack.cs
3.3125
3
using System; using System.Collections.Generic; namespace TDD { internal class MyStack { Stack<object> stack_items; public MyStack() { stack_items = new Stack<object>(); } public void push(object item) { stack_items.Push(item); } public object pop() { try { return stack_items.Pop(); } catch { throw new Exception("my exception"); } } } }
f88bb690560d18e0552c8d516f41cebce8444ba7
C#
rjesquivias/OSRSPredator
/Application/Util/Random.cs
2.859375
3
namespace Application.Util { public class Random { private static readonly System.Random random = new System.Random(); private static readonly object syncLock = new object(); public static int RandomNumber(int min, int max) { lock(syncLock) { // synchronize return random.Next(min, max); } } } }
8fa1c36e48935f6ff59d72ad2a6d7a8ef37dc3b9
C#
noplisu/DirectXMonster
/MonsterTextured/Form1.cs
2.765625
3
using System; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using System.IO; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using Direct3D = Microsoft.DirectX.Direct3D; namespace MonsterTextured { public partial class Form1 : Form { Device device = null; // Our rendering device Mesh mesh = null; // Our mesh object in sysmem Direct3D.Material[] meshMaterials; // Materials for our mesh Texture[] meshTextures; // Textures for our mesh PresentParameters presentParams = new PresentParameters(); bool pause = false; public Form1() { // Set the initial size of our form this.ClientSize = new System.Drawing.Size(400, 300); // And its caption this.Text = "Direct3D Tutorial 6 - Meshes"; } bool InitializeGraphics() { // Get the current desktop display mode, so we can set up a back // buffer of the same format try { // Set up the structure used to create the D3DDevice. Since we are now // using more complex geometry, we will create a device with a zbuffer. presentParams.Windowed = true; presentParams.SwapEffect = SwapEffect.Discard; presentParams.EnableAutoDepthStencil = true; presentParams.AutoDepthStencilFormat = DepthFormat.D16; // Create the D3DDevice device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams); device.DeviceReset += new System.EventHandler(this.OnResetDevice); this.OnResetDevice(device, null); pause = false; } catch (DirectXException) { return false; } return true; } public void OnResetDevice(object sender, EventArgs e) { ExtendedMaterial[] materials = null; // Set the directory up two to load the right data (since the default build location is bin\debug or bin\release Directory.SetCurrentDirectory(Application.StartupPath + @"\..\..\"); Device dev = (Device)sender; // Turn on the zbuffer dev.RenderState.ZBufferEnable = true; // Turn on ambient lighting dev.RenderState.Ambient = System.Drawing.Color.White; // Load the mesh from the specified file mesh = Mesh.FromFile("Monster.X", MeshFlags.SystemMemory, device, out materials); if (meshTextures == null) { // We need to extract the material properties and texture names meshTextures = new Texture[materials.Length]; meshMaterials = new Direct3D.Material[materials.Length]; for (int i = 0; i < materials.Length; i++) { meshMaterials[i] = materials[i].Material3D; // Set the ambient color for the material (D3DX does not do this) meshMaterials[i].Ambient = meshMaterials[i].Diffuse; // Create the texture meshTextures[i] = TextureLoader.FromFile(dev, materials[i].TextureFilename); } } } void SetupMatrices() { // For our world matrix, we will just leave it as the identity device.Transform.World = Matrix.RotationY(Environment.TickCount / 1000.0f); // Set up our view matrix. A view matrix can be defined given an eye point, // a point to lookat, and a direction for which way is up. Here, we set the // eye five units back along the z-axis and up three units, look at the // origin, and define "up" to be in the y-direction. device.Transform.View = Matrix.LookAtLH(new Vector3(0.0f, 3.0f, -150.0f), new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 1.0f, 0.0f)); // For the projection matrix, we set up a perspective transform (which // transforms geometry from 3D view space to 2D viewport space, with // a perspective divide making objects smaller in the distance). To build // a perpsective transform, we need the field of view (1/4 pi is common), // the aspect ratio, and the near and far clipping planes (which define at // what distances geometry should be no longer be rendered). device.Transform.Projection = Matrix.PerspectiveFovLH((float)(Math.PI / 4), 1.0f, 1.0f, 1000.0f); } private void Render() { if (device == null) return; if (pause) return; //Clear the backbuffer to a blue color device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, System.Drawing.Color.Blue, 1.0f, 0); //Begin the scene device.BeginScene(); // Setup the world, view, and projection matrices SetupMatrices(); // Meshes are divided into subsets, one for each material. Render them in // a loop for (int i = 0; i < meshMaterials.Length; i++) { // Set the material and texture for this subset device.Material = meshMaterials[i]; device.SetTexture(0, meshTextures[i]); // Draw the mesh subset mesh.DrawSubset(i); } //End the scene device.EndScene(); device.Present(); } protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { this.Render(); // Render on painting } protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e) { if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.Escape) this.Dispose(); // Esc was pressed } protected override void OnResize(System.EventArgs e) { pause = ((this.WindowState == FormWindowState.Minimized) || !this.Visible); } /// <summary> /// The main entry point for the application. /// </summary> static void Main() { using (Form1 frm = new Form1()) { if (!frm.InitializeGraphics()) // Initialize Direct3D { MessageBox.Show("Could not initialize Direct3D. This tutorial will exit."); return; } frm.Show(); // While the form is still valid, render and process messages while (frm.Created) { frm.Render(); Application.DoEvents(); } } } } }
d2a5f42b892b136d64234fcc88effb8628bda6a6
C#
daniel-schukies/Magic-Marshmallows
/Assets/Scripts/collide.cs
2.703125
3
using UnityEngine; using System.Collections; public class collide : MonoBehaviour { private Vector3 startPosition; public float minDistance; private bool active = false; void OnCollisionEnter(Collision collisionInfo) { Debug.Log("Enemy Collision"); Destroy (this.gameObject, 0.5f); } // Use this for initialization void Start () { this.GetComponent<SphereCollider> ().enabled = false; this.startPosition = this.transform.position; } // Update is called once per frame void Update () { if (! active) return; float distance = Mathf.Abs((this.startPosition - this.transform.position).magnitude); if (distance >= minDistance) { this.GetComponent<SphereCollider> ().enabled = true; //Debug.Log ("Distance: " + distance); } } public void setActive(){ active = true; } }
1856289831dcfdba18e3dae3975472239ac5de36
C#
martynagryga/lab-2-programowanie
/ConsoleApp1Wsadowo/LED Numbers/Program.cs
3.578125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LED_Numbers { class Program { static void Main(string[] args) { string input = Console.ReadLine(); for (int i = 1; i <= 3; i++) { for (int j = 0; j < input.Length; j++) { int number = int.Parse(input[j].ToString()); if (i == 1) { if (number != 1 && number != 4) { Console.Write(" _ "); } else Console.Write(" "); } else if (i == 2) { if (number != 1 && number != 3 && number != 7 && number != 2) { Console.Write("|"); } else Console.Write(" "); if (number != 0 && number != 1 && number != 7) { Console.Write("_"); } else Console.Write(" "); if (number != 5 && number != 6) { Console.Write("|"); } else Console.Write(" "); } else if (i == 3) { if (number == 0 || number == 2 || number == 6 || number == 8) { Console.Write("|"); } else Console.Write(" "); if (number != 1 && number != 4 && number != 7 && number != 9) { Console.Write("_"); } else Console.Write(" "); if (number != 2) { Console.Write("|"); } else Console.Write(" "); } } Console.WriteLine(""); } } } }
9b969a0412a7406a59f245e3b64ce740e62edbe4
C#
CePur/Exercism
/csharp/protein-translation/ProteinTranslation.cs
2.859375
3
using System.Collections.Generic; public static class ProteinTranslation { private readonly static Dictionary<string, string> dict = new Dictionary<string, string>() { { "AUG","Methionine" }, { "UUU","Phenylalanine" }, { "UUC","Phenylalanine" }, { "UUA","Leucine" }, { "UUG","Leucine" }, { "UCU","Serine" }, { "UCC","Serine" }, { "UCA","Serine" }, { "UCG","Serine" }, { "UAU","Tyrosine" }, { "UAC","Tyrosine" }, { "UGU","Cysteine" }, { "UGC","Cysteine" }, { "UGG","Tryptophan" }, { "UAA","STOP" }, { "UAG","STOP" }, { "UGA","STOP" } }; public static string[] Proteins(string strand) { var list = new List<string>(); for (int i = 0; i < strand.Length; i += 3) { var protein = dict[strand.Substring(i, 3)]; if (protein == "STOP") break; list.Add(protein); } return list.ToArray(); } }
819219aa74377a3eabd6fccfb0598ec723bba67a
C#
vladdziun/Exclusion
/Assets/Scripts/LookAt.cs
2.5625
3
using UnityEngine; using System.Collections; //[RequireComponent(typeof(CharacterController))] public class LookAt : MonoBehaviour { public Transform target; // Use this for initialization void Start () { // if no target specified, assume the player if (target == null) { if (GameObject.FindWithTag ("Player")!=null) { target = GameObject.FindWithTag ("Player").GetComponent<Transform>(); } } } // Update is called once per frame void Update () { if (target == null) return; // face the targetrge this.transform.LookAt(new Vector3(target.position.x, this.transform.position.y, target.position.z)); //get the distance between the chaser and the target } // Set the target of the chaser public void SetTarget(Transform newTarget) { target = newTarget; } }
599f6d240eb143e33c43e2292526bcbe512389a1
C#
johelfoosCR/WebSiteASADA
/WebAsada/Models/GeneralEntities/PersonType.cs
2.59375
3
using WebAsada.BaseObjects; namespace WebAsada.Models { public class PersonType : GeneralEntity { private PersonType() { } public PersonType(string shortDesc, string longDesc, string officialId, string nemotecnico, string personTypeCode, bool isActive) : base(shortDesc, longDesc, officialId, nemotecnico, isActive) { PersonTypeCode = personTypeCode; } public string PersonTypeCode { get; private set; } public static PersonType SincronizeObject(PersonType currentCustomerType, PersonType newCustomerType) { currentCustomerType.PersonTypeCode = newCustomerType.PersonTypeCode; currentCustomerType.Clone(newCustomerType); return currentCustomerType; } } }
4718e812dec8eaf7f454275e1bc848c51462d222
C#
tom10987/Unity.SpaceFighter
/Project.SpaceFighter/Assets/Scripts/GameObject/Machine/MachineType.cs
3.234375
3
 using System.Collections.Generic; //------------------------------------------------------------ // TIPS: // マシンの型式を表すパラメータです。 // // 特殊攻撃ボタンを押した時の効果をコメントとして記入しています。 // //------------------------------------------------------------ public enum MachineType { /// <summary> X: 広範囲にショット攻撃 </summary> Balance, /// <summary> X: 瞬間的に超加速 </summary> Speed, /// <summary> X: 高威力・極大ショット攻撃 </summary> Power, /// <summary> X: 高威力・広範囲のボム攻撃 </summary> Bommer, /// <summary> マシン選択シーン用、ランダム </summary> Random, } public static class MachineTypeTable { public class TypeText { public string name { get; private set; } public string text { get; private set; } public TypeText(string name, string text) { this.name = name; this.text = text; } } static MachineTypeTable() { _table = new Dictionary<MachineType, TypeText> { { MachineType.Balance, new TypeText("バランス型", "広範囲にショット攻撃") }, { MachineType.Speed, new TypeText("スピード型", "瞬間的に超加速") }, { MachineType.Power, new TypeText("パワー型", "高威力・極大ショット攻撃") }, { MachineType.Bommer, new TypeText("ボマー型", "高威力・広範囲ボム攻撃") }, { MachineType.Random, new TypeText("ランダム", "???") }, }; } static readonly Dictionary<MachineType, TypeText> _table = null; /// <summary> マシンタイプの情報を取得 </summary> public static TypeText GetText(this MachineType type) { return _table[type]; } }
b067c81e22c1d9be415066dce7c976a33d6a7ffa
C#
ananth039/Anantha-Kumar-.net-Practice-programs
/old programs/ananth.acer.laptop.examples.partialclasses/Flag/Program.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Flag { class Program { static void Main(string[] args) { String name = "John"; String password = "letmein"; Boolean flag; flag = (name == "John" || name == "john"|| password=="letmein"); Console.WriteLine(flag); Console.ReadKey(); } } }
39fc92cfbc90641dd4be3e1487423be791403002
C#
RabidChinchilla/Unity-3D-Game-Mechanic---Weapons-Testing-Ricochet-gun-and-Gravity-well-gun-
/Weapons testing/Assets/Scripts/Score.cs
2.6875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Score : MonoBehaviour { public GameObject door; public static int scoreValue = 0; Text scoreText; // Use this for initialization void Start () { //set the text box scoreText = GetComponent<Text>(); } // Update is called once per frame void Update () { //set the contents of the textbox to a string and a int variable that can be changed scoreText.text = "Score: " + scoreValue; if (scoreValue == 1200) { //when a minimum score is reached remove the door Destroy(door); } } }
6aa4631ed854de569cc7a20c643bfee89b532217
C#
mustafahicyilmaz35/NewXamarinSupport
/Sekreter/Sekreter.Core/ViewModels/SendSmsPageViewModel.cs
2.5625
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Essentials; using Xamarin.Forms; namespace Sekreter.Core.ViewModels { public class SendSmsPageViewModel { // public string messageText { get; set; } // public string recipient { get; set; } public ICommand smsCommand { private set; get; } public SendSmsPageViewModel() { //smsCommand = new Command(() => SendSms(messageText, recipient)); } public SendSmsPageViewModel(string _messageText, string _recipient) { // messageText = _messageText; //recipient = _recipient; SendSms(_messageText, _recipient); } public async Task SendSms(string messageText, string recipient) { try { var message = new SmsMessage(messageText, new[] { recipient }); await Sms.ComposeAsync(message); } catch (FeatureNotSupportedException e) { Debug.WriteLine(e.Message); } catch (Exception e) { Debug.WriteLine(e.Message); } } } }
af17716328659bcb613698a21f1ea4e66096f0bd
C#
DivyaKumari1/EventBriteWithDockerAndTokenService
/EventBash/EventCatalogAPI/Data/EventContext.cs
3.09375
3
using EventCatalogAPI.Domains; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EventCatalogAPI.Data { public class EventContext : DbContext { //add dependency injection and config file using class constructor public EventContext(DbContextOptions options) : base(options) { //this is empty but needs to be filled shortly. } public DbSet<EventCategory> EventCategories { get; set; } //DB Table EventCategories public DbSet<EventVenue> EventVenues { get; set; } // DB table EventVenues public DbSet<EventItem> EventItems { get; set; } //DB Table EventItems //defining relationship of tables using Entity Framework protected override void OnModelCreating(ModelBuilder modelBuilder ) { modelBuilder.Entity<EventVenue>(ConfigureEventVenue); modelBuilder.Entity<EventCategory>(ConfigureEventCategory); modelBuilder.Entity<EventItem>(ConfigureEventItem); //Selvi -> updated ConfigureEventItems to ConfigureEventItem to make it more sensible } /** * creating table tableName :Events with a * primary key : Id, * ForeginKey : EventVenue,EventCategory */ private void ConfigureEventItem(EntityTypeBuilder<EventItem> builder) { builder.ToTable("Events");//the actual name of the event catalog builder.Property(c => c.Id) .IsRequired() .ForSqlServerUseSequenceHiLo("events_hilo"); builder.Property(c => c.EventName) .IsRequired() .HasMaxLength(100); builder.Property(c => c.EventCost) .IsRequired(); //Here, are the relationships between Events and the venue and category builder.HasOne(c => c.EventCategory) //red will go away when Items is successfully entered .WithMany() .HasForeignKey(c => c.EventCategoryId); builder.HasOne(c => c.EventVenue) //red will go away when Items is successfully entered .WithMany() .HasForeignKey(c => c.EventVenueId); } private void ConfigureEventCategory(EntityTypeBuilder<EventCategory> builder) { builder.ToTable("EventCategories"); builder.Property(c => c.Id) .IsRequired() //primary key .ForSqlServerUseSequenceHiLo("event_category_hilo"); // builder.Property(c => c.Category) //would be good to change type member to category. .IsRequired() .HasMaxLength(100); } private void ConfigureEventVenue(EntityTypeBuilder<EventVenue> builder) { builder.ToTable("EventVenues"); builder.Property(c => c.Id) //What to do with the properties .IsRequired() //required because Id is the primary key .ForSqlServerUseSequenceHiLo("event_venue_hilo"); builder.Property(c => c.Venue) .IsRequired() .HasMaxLength(100); } } }
ccaf392edcb9353548568bc1e84ddb9c48ea0b97
C#
Bratyun/Hotel-Epam
/DAL/EntityClasses/Request.cs
2.765625
3
using DAL.Account; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL.EntityClasses { public enum RequestStatus { None, New, Waiting, Executed, Refused } public class Request { [Key] public int Id { get; set; } [Range(0, 10)] public int RoomSize { get; set; } [Range(0, 5)] public int Comfort { get; set; } [Column(TypeName = "datetime2")] public DateTime StartDate { get; set; } [Column(TypeName = "datetime2")] public DateTime EndDate { get; set; } public string UserId { get; set; } public RequestStatus Status { get; set; } public int Answer { get; set; } public Request() { RoomSize = 0; Comfort = 0; StartDate = default(DateTime); EndDate = default(DateTime); UserId = null; Status = RequestStatus.None; Answer = 0; } public Request(int roomSize, int comfort, DateTime startDate, DateTime endDate, string userId, RequestStatus status, int roomsId = 0) { RoomSize = roomSize; Comfort = comfort; StartDate = startDate; EndDate = endDate; UserId = userId; Status = status; Answer = roomsId; } public static List<Request> GetByUserAndStatus(string userId, RequestStatus waiting) { using (ApplicationContext db = new ApplicationContext()) { try { List<Request> requests = db.Requests.Where(x => x.UserId == userId && x.Status == waiting).ToList(); if (requests != null) { return requests; } return null; } catch (Exception ex) { return null; } } } public static Request Add(Request request) { if (!request.IsValidDates()) { return null; } using (ApplicationContext db = new ApplicationContext()) { try { var c = db.Requests.Where(x => x.Id == request.Id).FirstOrDefault(); if (c == null) { db.Requests.Add(request); db.SaveChanges(); return request; } return null; } catch (Exception ex) { throw; } } } public bool IsValidDates() { return (StartDate.Date >= EndDate.Date || EndDate.Date < DateTime.Now || StartDate.Date < DateTime.Now.Date) ? false : true; } public static Request GetById(int id) { using (ApplicationContext db = new ApplicationContext()) { var c = db.Requests.Where(x => x.Id == id).FirstOrDefault(); if (c != null) { return c; } return null; } } public static List<Request> GetByUser(string userId) { using (ApplicationContext db = new ApplicationContext()) { try { List<Request> requests = db.Requests.Where(x => x.UserId == userId).ToList(); if (requests != null) { return requests; } return null; } catch (Exception ex) { return null; } } } public static List<Request> GetNewAndRefused() { using (ApplicationContext db = new ApplicationContext()) { try { List<Request> requests = db.Requests.Where(x => x.Status == RequestStatus.New || x.Status == RequestStatus.Refused).ToList(); if (requests != null) { return requests; } return null; } catch (Exception ex) { return null; } } } public static bool Delete(int request) { using (ApplicationContext db = new ApplicationContext()) { var c = db.Requests.Where(x => x.Id == request).FirstOrDefault(); if (c != null) { db.Requests.Remove(c); db.SaveChanges(); return true; } return false; } } public static bool DeleteByUser(ApplicationUser user) { if (user == null) { return false; } using (ApplicationContext db = new ApplicationContext()) { var c = db.Requests.Where(x => x.UserId == user.Id).ToList(); if (c != null) { foreach (var item in c) { Delete(item.Id); } db.SaveChanges(); return true; } return false; } } public static bool Update(Request request) { using (ApplicationContext db = new ApplicationContext()) { var c = db.Requests.Where(x => x.Id == request.Id).FirstOrDefault(); if (c != null) { c.Answer = request.Answer; c.RoomSize = request.RoomSize; c.StartDate = request.StartDate; c.Status = request.Status; c.UserId = request.UserId; c.Comfort = request.Comfort; c.EndDate = request.EndDate; db.SaveChanges(); return true; } return false; } } } }
badce838fbdb049c52a33fa15ce8e95a28045618
C#
ricantar/ProgIIFinalProject
/ProgIIFinalProject/ProgIIFinalProject/TempMat.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProgIIFinalProject { public class TempMat { private string _area; private string _codigo; private String _nombre; public string Area { get { return _area; } set { _area = value; } } public string Codigo { get { return _codigo; } set { _codigo = value; } } public string Nombre { get { return _nombre; } set { _nombre = value; } } public TempMat() { } public TempMat(string area, string codigo, string nombre) { _area = area; _codigo = codigo; _nombre = nombre; } } }
980a19a6ac5035d1eda49734029db57b6b3850c3
C#
fullstackbeast/MatrixBank
/MyBMS/Domain/Repository/AccountRepository.cs
2.6875
3
using System; using System.Collections.Generic; using System.Text; using System.Linq; using MySql.Data.MySqlClient; using MyBMS.Interface.Repository; using MyBMS.Models.Entities; using BMSEFDB.Models; namespace MyBMS.Domain.Repository { public class AccountRepository : IAccountRepository { private readonly BankDBContext _context; public AccountRepository(BankDBContext context) { _context = context; } public bool Create(Account account) { _context.Accounts.Add(account); _context.SaveChanges(); return true; } public Account FindById(int id) { return _context.Accounts.FirstOrDefault(a => a.AccountHolderId == id); } public Account Update(Account account) { _context.Accounts.Update(account); _context.SaveChanges(); return account; } public bool UpdateMultiple(List<Account> accounts) { _context.Accounts.UpdateRange(accounts); _context.SaveChanges(); return true; } public Account FindByAccountNumber(string accountNumber) { return _context.Accounts.FirstOrDefault(an => an.AccountNumber == accountNumber); } } }
38ee137a25141f4bad2fe9c1660d6cd249c58b8b
C#
tomasfriz/Prog-Labo_2
/Rueda.Matias/PracCasaClase/MiClass.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PracCasaClase {//acordate de q la clase y programa el mismo modificador, en este caso public ambos public class MiClass { //atributos //si no es public y static no aparece cuando haga el llamando en main public static string mensaje; public static ConsoleColor color; //metodos public static string Imprimir() { return MiClass.ArmarFormatoMensaje(); } public static void Borrar() { MiClass.mensaje = ""; } public static void ImprimirEnColor() { Console.ForegroundColor = MiClass.color; } private static string ArmarFormatoMensaje() { int cantidad; string mensajeNuevo = ""; cantidad = MiClass.mensaje.Length + 2; for(int i = 0; i < cantidad; i++) { mensajeNuevo += "*"; } mensajeNuevo += "\n*" + MiClass.mensaje + "*\n" + mensajeNuevo; return mensajeNuevo; } } }
573f02089ac1e07d9f57aad7402caa1edb9ee3a3
C#
araucanosland/MDN-Microservices
/src/Services/CompaniesOps/CompaniesOperations.API/Model/Lead.cs
2.5625
3
using System; using System.Collections.Generic; namespace CompaniesOperations.API.Model { /// <summary> /// Created By @Charlie /// </summary> public class Lead { /// <summary> /// /// </summary> public Lead(){} /// <summary> /// /// </summary> /// <param name="period"></param> /// <param name="leadTypeId"></param> /// <param name="companyId"></param> /// <param name="companyName"></param> /// <param name="assignedOfiice"></param> /// <param name="assginedTo"></param> public Lead(int period, int leadTypeId, string companyId, string companyName, int assignedOfiice, string assginedTo) { Period = period; LeadTypeId = leadTypeId; CompanyId = companyId; AssignedOfficce = AssignedOfficce; AssignedTo = assginedTo; CreatedAt = DateTime.Now; } /// <summary> /// /// </summary> /// <value></value> public int Id { get; set; } /// <summary> /// /// </summary> /// <value></value> public int Period { get; set; } /// <summary> /// /// </summary> /// <value></value> public int LeadTypeId { get; set; } /// <summary> /// /// </summary> /// <value></value> public LeadType LeadType { get; set; } /// <summary> /// /// </summary> /// <value></value> public string CompanyId { get; set; } /// <summary> /// /// </summary> /// <value></value> public Company Company { get; set; } /// <summary> /// /// </summary> /// <value></value> public int AssignedOfficce { get; set; } /// <summary> /// /// </summary> /// <value></value> public string AssignedTo { get; set; } /// <summary> /// /// </summary> /// <value></value> public DateTime CreatedAt { get; set; } /// <summary> /// /// </summary> /// <value></value> public IEnumerable<Management> Managements { get; set;} } }
1ca02a60a06a2037dc7a561e3fd76a8a9c4a35ed
C#
CarolineAntonello/GeradorDeProvas
/Mariana/GeradorDeProvas.Domain/Serie.cs
3.21875
3
using GeradorDeProvas.Domain.Abstract; using GeradorDeProvas.Domain.Helper; using System; namespace GeradorDeProvas.Domain { public class Serie : Entidade { public string Nome { get; set; } public override void Validar() { if (Nome.Length < 1 || String.IsNullOrEmpty(Nome)) throw new Exception("Deve conter um número!"); if (Nome.Length > 1 || String.IsNullOrEmpty(Nome)) throw new Exception("Não deve ter um nome com mais de 1 caractere!"); if (Util.VerificarExistenciaLetras(Nome) ||Util.VerificarExistenciaCaractereExpeciais(Nome)) throw new Exception("Somente permitido numeros"); if (Nome.Equals("0")) throw new Exception("Série inválida, insira uma de 1 a 9"); } public override string ToString() { return this.Nome+"ª série"; } public override bool Equals(object obj) { Serie serie = obj as Serie; if (serie == null) return false; else return Id.Equals(serie.Id); } } }
39de8d83993a1d47c3e49d02266406979b4cfbd9
C#
trbenning/Foundatio
/src/Core/Serializer/ISerializer.cs
2.859375
3
using System; using System.Text; using System.Threading.Tasks; using Foundatio.Extensions; namespace Foundatio.Serializer { public interface ISerializer { Task<object> DeserializeAsync(byte[] data, Type objectType); Task<byte[]> SerializeAsync(object value); } public static class SerializerExtensions { public static Task<object> DeserializeAsync(this ISerializer serializer, string data, Type objectType) { return serializer.DeserializeAsync(Encoding.UTF8.GetBytes(data ?? String.Empty), objectType); } public static async Task<T> DeserializeAsync<T>(this ISerializer serializer, byte[] data) { return (T)await serializer.DeserializeAsync(data, typeof(T)).AnyContext(); } public static Task<T> DeserializeAsync<T>(this ISerializer serializer, string data) { return DeserializeAsync<T>(serializer, Encoding.UTF8.GetBytes(data ?? String.Empty)); } public static async Task<string> SerializeToStringAsync(this ISerializer serializer, object value) { if (value == null) return null; return Encoding.UTF8.GetString(await serializer.SerializeAsync(value).AnyContext()); } } }
e2b0ef0702036930e280ae9d6e12c26ca5269f64
C#
Tuscann/Coding-101
/18.C# Basics Exam 20 December 2014/03. Boat/03.01 Boat.cs
3.625
4
using System; class Program { static void Main() { int number = int.Parse(Console.ReadLine()); //draw sail int sailCurrentW = 1; bool middlePointReached = false; for (int c = 0; c < number; c++) { Console.WriteLine("{0}{1}{2}", new string('.', number - sailCurrentW), new string('*', sailCurrentW), new string('.', number)); if (sailCurrentW >= number) { middlePointReached = true; } if (middlePointReached) { sailCurrentW = sailCurrentW - 2; } else { sailCurrentW = sailCurrentW + 2; } } int dots = 0; //draw boat int boatHight = number / 2; int boatWight = 2 * number; for (int row = 1; row <= boatHight; row++) { Console.WriteLine("{0}{1}{0}", new string('.', dots), new string('*', boatWight)); boatWight = boatWight - 2; dots = dots + 1; } } }
afd784e5340f59e93dca6e402b36c158aa370a86
C#
pepinho24/TelerikAcademyHomeworks2015
/C# OOP/04. OOP Principles - Part 1/01.SchoolClasses/Person.cs
3.5625
4
namespace _01.SchoolClasses { using System.Collections.Generic; public abstract class Person : ICommentable { private Name name; private ICollection<Comment> comments; public Person(Name name) { this.Name = name; this.Comments = new List<Comment>(); } public Name Name { get { return this.name; } set { this.name = value; } } public ICollection<Comment> Comments { get { return this.comments; } set { this.comments = value; } } public void AddComment(Comment comment) { this.Comments.Add(comment); } public void RemoveComment(Comment comment) { this.Comments.Remove(comment); } public void RemoveAllComments() { this.Comments.Clear(); } } }
da728c8d935c5920499b68270db94aa2ac3799ae
C#
valterc/lings
/LiNGSServer/GameClient.cs
2.703125
3
using LiNGS.Common; using LiNGS.Common.Network; using LiNGS.Server.Network; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace LiNGS.Server { /// <summary> /// Represent a client. /// </summary> public class GameClient { private static Guid sessionGuid; private static int userId; internal static Guid SessionGUID { get { if (sessionGuid == Guid.Empty) { sessionGuid = Guid.NewGuid(); } return sessionGuid; } } /// <summary> /// The network information of the client. /// </summary> public NetworkClient NetworkClient { get; internal set; } /// <summary> /// The client identification within this session of the game. /// </summary> public String SessionUserId { get; internal set; } /// <summary> /// The client identification. /// </summary> public String UserId { get; internal set; } /// <summary> /// The session identification. /// </summary> public String SessionId { get { return sessionGuid.ToString(); } } /// <summary> /// The time that this client established a connection. /// </summary> public DateTime ConnectedAt { get; internal set; } /// <summary> /// Creates a new instance of this class with the current session identification and generates a new unique session user identification. /// </summary> public GameClient() { if (sessionGuid == Guid.Empty) { sessionGuid = Guid.NewGuid(); } this.UserId = Interlocked.Increment(ref userId).ToString(); this.SessionUserId = SessionId.ToString() + LiNGSMarkers.Separator + this.UserId; this.ConnectedAt = DateTime.Now; } /// <summary> /// Creates a new instance of this class with the information of a user session identification. /// </summary> /// <param name="sessionString">The identification of the user and session.</param> public GameClient(String sessionString) { this.UserId = sessionString.Split(LiNGSMarkers.Separator[0])[1]; this.SessionUserId = sessionString; this.ConnectedAt = DateTime.Now; } } }
e27cee83bb1eb55a1962561271977d12b3e5c06c
C#
phillrog/lista-telefonica
/ListaTelefonica.Applications/PersonPhoneAppService.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using ListaTelefonica.Applications.Interfaces; using ListaTelefonica.Domain.Entities; using ListaTelefonica.Domain.Interfaces.Services; namespace ListaTelefonica.Applications { public class PersonPhoneAppService : AppServiceBase<PersonPhone>, IPersonPhoneAppService { private readonly IPersonPhoneService _personPhoneService; public PersonPhoneAppService(IPersonPhoneService personPhoneService) : base(personPhoneService) { _personPhoneService = personPhoneService; } public async Task<bool> Delete(int id) { var person = await _personPhoneService.GetPersonPhoneById(id); await _personPhoneService.Delete(person); return true; } public async Task<PersonPhone> GetPersonPhoneById(int id) { return await _personPhoneService.GetPersonPhoneById(id); } public async Task<IList<PersonPhone>> GetTotalPhone(int idPerson) { return await _personPhoneService.GetAllAsync(d=> d.PersonId == idPerson); } } }
e2e70eea54b57fb37a3acf6b8ee6a693d463e54a
C#
ktilk/FeedApp
/DAL/DataContext.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.ServiceModel.Syndication; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; using DAL.Services; using Domain; using HtmlAgilityPack; namespace DAL { public class DataContext { private readonly ArticleService _articleFactory; public List<Article> Articles { get; set; } public DataContext() { _articleFactory = new ArticleService(); Articles = new List<Article>(); GetArticlesFromFeed(); } /// <summary> /// Creates Article objects from XML and puts them to a List /// </summary> public void GetArticlesFromFeed() { const string feedUri = "https://flipboard.com/@raimoseero/feed-nii8kd0sz?rss"; var reader = XmlReader.Create(feedUri); var feed = SyndicationFeed.Load(reader); foreach (var syndicationItem in feed.Items) { var articleId = 0; if (Articles.Count != 0) { articleId = Articles.OrderByDescending(x => x.ArticleId).FirstOrDefault().ArticleId++; } var article = _articleFactory.CreateArticle(syndicationItem, articleId); Articles.Add(article); } } } }
97e3bede4f5017e7cae41744e5465ec4c07d3959
C#
ostrichgull/WebApiMovie
/WebApiMovieTests/MovieDbContextTests.cs
2.8125
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using WebApiMovie.Models; using WebApiMovie.Controllers; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using Moq; namespace WebApiMovieTests { [TestClass] public class MovieDbContextTests { [TestMethod] public void TestGet() { var data = new List<Movie> { new Movie { Title = "Movie 1" }, new Movie { Title = "Movie 2" }, new Movie { Title = "Movie 3" }, }.AsQueryable(); var mockSet = new Mock<DbSet<Movie>>(); mockSet.As<IQueryable<Movie>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<Movie>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Movie>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Movie>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<MovieDBContext>(); mockContext.Setup(c => c.Movies).Returns(mockSet.Object); var service = new MoviesController(mockContext.Object); var movies = service.Get(); Assert.AreEqual(3, movies.Count()); Assert.AreEqual("Movie 1", movies.ElementAt(0).Title); Assert.AreEqual("Movie 2", movies.ElementAt(1).Title); Assert.AreEqual("Movie 3", movies.ElementAt(2).Title); } } }
4b366e7bd781d86526fa9d8edee897c28562d0e4
C#
harbinger965/ProcGenRPG
/Assets/Scripts/MapGen/Chest.cs
2.625
3
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; /** * Chests can hold subclasses of Item */ public class Chest : Interactable { /** * The number of items all chests can store */ private static readonly int SLOTS = 10; private static readonly int minBytes = 10000; private static readonly int maxBytes = 1000000; private bool dropItems = false; /** * List of items in the chest. Cannot be more than SLOTS */ private List<Item> items; private static GameObject byteObject; // Use this for initialization void Start () { if(byteObject == null) { byteObject = Resources.Load<GameObject>("Info/Byte"); } items = new List<Item>(SLOTS); } // Update is called once per frame void Update () { transform.GetChild(0).rotation = Quaternion.RotateTowards(transform.GetChild(0).rotation, Quaternion.Euler(new Vector3(transform.GetChild(0).eulerAngles.x, FollowPlayer.rotate, transform.GetChild(0).eulerAngles.z)), Time.deltaTime*50f); if (this.CanInteract()) { transform.GetChild(0).gameObject.SetActive(true); transform.GetChild(0).GetChild(0).GetComponent<Text>().text = "Press " + Player.useKey + " to open"; } else { transform.GetChild(0).gameObject.SetActive(false); } } // KARTIK do the thing! protected override void Interact() { if (Player.useKey != KeyCode.None && Input.GetKeyDown(Player.useKey)) { int tempByteVal = (int)(Random.value*(maxBytes-minBytes) + minBytes); int curByteVal = 0; int byteVal = Mathf.Max(tempByteVal/5, 5000); while (curByteVal < tempByteVal) { GameObject tmp = (GameObject)Instantiate(byteObject, transform.position, Quaternion.identity); tmp.GetComponent<Byte>().val = byteVal; curByteVal += byteVal; } Destroy(this.gameObject); } } /** * Adds an item to the chest and returns true if there are enough slots. * returns false otherwise. */ public bool AddToChest(Item i) { if (items.Count < SLOTS) { items.Add(i); return true; } else { return false; } } /** * Removes an item to the chest and returns true if item was there. * returns false otherwise. */ public bool RemoveFromChest(Item i) { return items.Remove(i); } /** * Gets the Collections.Generic.List of items in the chest */ public List<Item> GetList() { return items; } }
6f87d122de1b94cfa4140fa1d19b8db690452394
C#
CrypToolProject/CrypTool-2
/CrypPlugins/ChaCha/Helper/Converter/MultiSequentialValueConverter.cs
2.671875
3
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Windows.Data; namespace CrypTool.Plugins.ChaCha.Helper.Converter { /// <summary> /// Extension of SequentialValueConverter. /// First converter is IMultiValueConverter. Next converters are IValueConverter and modify the output. /// </summary> /// <remarks> /// https://stackoverflow.com/a/5534535/13555687 /// </remarks> public class MultiSequentialValueConverter : List<IValueConverter>, IValueConverter, IMultiValueConverter { public IMultiValueConverter MultiValueConverter { get; set; } #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return GroupConvert(value, this); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return GroupConvertBack(value, ToArray().Reverse()); } private static object GroupConvert(object value, IEnumerable<IValueConverter> converters) { return converters.Aggregate(value, (acc, conv) => { return conv.Convert(acc, typeof(object), null, null); }); } private static object GroupConvertBack(object value, IEnumerable<IValueConverter> converters) { return converters.Aggregate(value, (acc, conv) => { return conv.ConvertBack(acc, typeof(object), null, null); }); } #endregion IValueConverter Members #region IMultiValueConverter Members private readonly InvalidOperationException _multiValueConverterUnsetException = new InvalidOperationException("To use the converter as a MultiValueConverter the MultiValueConverter property needs to be set."); public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (MultiValueConverter == null) { throw _multiValueConverterUnsetException; } object firstConvertedValue = MultiValueConverter.Convert(values, targetType, parameter, culture); return GroupConvert(firstConvertedValue, this); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { if (MultiValueConverter == null) { throw _multiValueConverterUnsetException; } object tailConverted = GroupConvertBack(value, ToArray().Reverse()); return MultiValueConverter.ConvertBack(tailConverted, targetTypes, parameter, culture); } #endregion IMultiValueConverter Members } }
1913c8adacd233545f4bb3f3793fb5f233da69b5
C#
mbohekale/CShape-Programming
/LoopingArrays/Integers.cs
3.640625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Looping.cs { class Program { static void Main(string[] args) { for (int i=0; i<10; i++) { if (i==7) { Console.WriteLine("Not Found! "); break; } } for (int y = 0; y < 12; y++) { Console.WriteLine(y); } int[] numbers = new int[5]; numbers[0] = 7; numbers[1] = 17; numbers[2] = 19; numbers[3] = 0; numbers[4] = 8; Console.WriteLine(numbers.Length); Console.ReadLine(); } } }
7ca284d768816d4fcbdd910e8447d709a493366e
C#
guivern/ApiTest
/Data/DataContext.cs
2.796875
3
using ApiTest.Models; using Microsoft.EntityFrameworkCore; namespace ApiTest.Data { /// <summary> /// Aqui configuramos el contexto de nuestra bd. /// </summary> public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) {} protected override void OnModelCreating(ModelBuilder modelBuilder) { // on delete restrict modelBuilder.Entity<Ciudad>() .HasOne(c => c.Pais) .WithMany(p => p.Ciudades) .OnDelete(DeleteBehavior.Restrict); } // entidades que seran mapeadas a la bd public DbSet<Pais> Paises { get; set; } public DbSet<Ciudad> Ciudades { get; set; } } }
360f580c020d2865afb52bd3db9499a32107e8d7
C#
jackrust/AFLTipper
/Utilities.Tests/StringyTests.cs
3.046875
3
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Utilities.Tests { [TestClass] public class StringyTests { [TestMethod] public void ShouldReturnOneHundredCharacterSpacePaddedString() { //Arrange const string inString = "Just 10 characters long"; const int requiredLength = 100; //Act string result = Stringy.Lengthen(inString, requiredLength); //assert Assert.AreEqual(100, result.Length); Assert.AreEqual(' ', result[99]); } [TestMethod] public void ShouldReturnOneForExactMatch() { //Arrange const string original = "string"; //Act var result = Stringy.Compare(original, original); //Assert Assert.AreEqual(1, result); } [TestMethod] public void ShouldReturnNegativeOneForExactNull() { //Arrange const string original = "string"; //Act var result = Stringy.Compare(original, null); //Assert Assert.AreEqual(-1, result); } [TestMethod] public void ShouldPreferExactMatchToPartialToNoMatchToBlank() { //Arrange const string original = "string"; const string partial = "strizang"; const string noMatch = "qweyuop"; const string blank = ""; //Act var exactResult = Stringy.Compare(original, original); var partialResult = Stringy.Compare(original, partial); var noMatchResult = Stringy.Compare(original, noMatch); var blankResult = Stringy.Compare(original, blank); //Assert Assert.IsTrue(exactResult > partialResult); Assert.IsTrue(partialResult > noMatchResult); Assert.AreEqual(0, noMatchResult); Assert.AreEqual(0, blankResult); } } }
74bce25fd918c9239756bae4671e41cce597c077
C#
oxalorg/scratch
/gtk-ui/BookView.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Gtk; using Barrkel.ScratchPad; using System.IO; namespace Barrkel.GtkScratchPad { public static class Stringhelper { public static string EscapeMarkup(this string text) { return (text ?? "").Replace("&", "&amp;").Replace("<", "&lt;"); } } public class BookView : Frame { DateTime _lastModification; DateTime _lastSave; bool _dirty; int _currentPage; string _textContents; // If non-null, then browsing history. ScratchIterator _currentIterator; TextView _textView; bool _settingText; Label _titleLabel; Label _dateLabel; Label _pageLabel; Label _versionLabel; public BookView(ScratchBook book, Settings appSettings) { AppSettings = appSettings; Book = book; InitComponent(); _currentPage = book.Pages.Count > 0 ? book.Pages.Count - 1 : 0; UpdateViewLabels(); UpdateTextBox(); } public Settings AppSettings { get; private set; } private void UpdateTextBox() { _settingText = true; try { if (_currentPage >= Book.Pages.Count) _textView.Buffer.Text = ""; else if (_currentIterator != null) _textView.Buffer.Text = _currentIterator.Text; else _textView.Buffer.Text = Book.Pages[_currentPage].Text; TextIter iter = _textView.Buffer.GetIterAtOffset(0); _textView.Buffer.SelectRange(iter, iter); _textView.ScrollToIter(iter, 0, false, 0, 0); } finally { _settingText = false; } } private void UpdateTitle() { _titleLabel.Markup = GetTitleMarkup(new StringReader(_textView.Buffer.Text).ReadLine()); } private void UpdateViewLabels() { if (_currentPage >= Book.Pages.Count) { _dateLabel.Text = ""; _pageLabel.Text = ""; _versionLabel.Text = ""; } else { _pageLabel.Markup = GetPageMarkup(_currentPage + 1, Book.Pages.Count); if (_currentIterator == null) { _versionLabel.Markup = GetInfoMarkup("Latest"); _dateLabel.Markup = GetInfoMarkup( Book.Pages[_currentPage].ChangeStamp.ToLocalTime().ToString("F")); } else { _versionLabel.Markup = GetInfoMarkup(string.Format("Version {0} of {1}", _currentIterator.Position, _currentIterator.Count)); _dateLabel.Markup = GetInfoMarkup(_currentIterator.Stamp.ToLocalTime().ToString("F")); } } } public void EnsureSaved() { if (!_dirty) return; if (_currentPage >= Book.Pages.Count) { Book.AddPage(); UpdateViewLabels(); } Book.Pages[_currentPage].Text = _textContents; Book.SaveLatest(); _lastSave = DateTime.UtcNow; _dirty = false; _currentPage = Book.MoveToEnd(_currentPage); UpdateViewLabels(); } private void SetTextBoxFocus() { // ??? } private static string GetTitleMarkup(string title) { return string.Format("<span weight='ultrabold'>{0}</span>", title.EscapeMarkup()); } private static string GetPageMarkup(int page, int total) { return string.Format("<span font='16'>Page {0} of {1}</span>", page, total); } private static string GetInfoMarkup(string info) { return string.Format("<span font='11'>{0}</span>", info.EscapeMarkup()); } private void InitComponent() { Gdk.Color grey = new Gdk.Color(0xA0, 0xA0, 0xA0); Gdk.Color lightBlue = new Gdk.Color(207, 207, 239); var infoFont = Pango.FontDescription.FromString(AppSettings.Get("info-font", "Verdana")); var textFont = Pango.FontDescription.FromString(AppSettings.Get("text-font", "Courier New")); _textView = new TextView(); _textView.WrapMode = WrapMode.Word; _textView.ModifyBase(StateType.Normal, lightBlue); _textView.Buffer.Changed += _text_TextChanged; _textView.KeyPressEvent += _textView_KeyPressEvent; _textView.ModifyFont(textFont); ScrolledWindow scrolledTextView = new ScrolledWindow(); scrolledTextView.Add(_textView); _titleLabel = new Label(); _titleLabel.SetAlignment(0, 0); _titleLabel.Justify = Justification.Left; _titleLabel.SetPadding(0, 5); _titleLabel.ModifyFont(textFont); GLib.Timeout.Add((uint) TimeSpan.FromSeconds(3).TotalMilliseconds, () => { return SaveTimerTick(); }); EventBox titleContainer = new EventBox(); titleContainer.Add(_titleLabel); // hbox // vbox // dateLabel // versionLabel // pageLabel HBox locationInfo = new HBox(); VBox locationLeft = new VBox(); _dateLabel = new Label(); _dateLabel.SetAlignment(0, 0); _dateLabel.Justify = Justification.Left; _dateLabel.SetPadding(5, 5); _dateLabel.ModifyFont(infoFont); locationLeft.PackStart(_dateLabel, false, false, 0); _versionLabel = new Label(); _versionLabel.SetAlignment(0, 0); _versionLabel.Justify = Justification.Left; _versionLabel.SetPadding(5, 5); _versionLabel.ModifyFont(infoFont); locationLeft.PackStart(_versionLabel, false, false, 0); locationInfo.PackStart(locationLeft, true, true, 0); _pageLabel = new Label(); _pageLabel.Markup = GetPageMarkup(1, 5); _pageLabel.SetAlignment(1, 0.5f); _pageLabel.Justify = Justification.Right; _pageLabel.SetPadding(5, 5); _pageLabel.ModifyFont(infoFont); locationInfo.PackEnd(_pageLabel, true, true, 0); Pango.Context ctx = _pageLabel.PangoContext; VBox outerVertical = new VBox(); outerVertical.PackStart(titleContainer, false, false, 0); outerVertical.PackStart(scrolledTextView, true, true, 0); outerVertical.PackEnd(locationInfo, false, false, 0); Add(outerVertical); BorderWidth = 5; } void _textView_KeyPressEvent(object o, KeyPressEventArgs args) { // Mod1 => alt var state = args.Event.State & (Gdk.ModifierType.ShiftMask | Gdk.ModifierType.Mod1Mask | Gdk.ModifierType.ControlMask); if (state == Gdk.ModifierType.Mod1Mask) { switch (args.Event.Key) { case Gdk.Key.Home: case Gdk.Key.Up: PreviousVersion(); break; case Gdk.Key.End: case Gdk.Key.Down: NextVersion(); break; case Gdk.Key.Page_Up: case Gdk.Key.Left: PreviousPage(); break; case Gdk.Key.Page_Down: case Gdk.Key.Right: NextPage(); break; default: return; } } } private void _text_TextChanged(object sender, EventArgs e) { UpdateTitle(); if (_settingText) return; if (!_dirty) _lastSave = DateTime.UtcNow; _lastModification = DateTime.UtcNow; if (_textView.Buffer.Text == "") EnsureSaved(); _textContents = _textView.Buffer.Text; if (_textContents == "") { _currentPage = Book.Pages.Count; Book.AddPage(); UpdateViewLabels(); } _currentIterator = null; _dirty = true; } private bool SaveTimerTick() { if (!_dirty) return true; TimeSpan span = DateTime.UtcNow - _lastModification; if (span > TimeSpan.FromSeconds(5)) { EnsureSaved(); return true; } span = DateTime.UtcNow - _lastSave; if (span > TimeSpan.FromSeconds(20)) EnsureSaved(); return true; } void PreviousVersion() { EnsureSaved(); if (_currentPage >= Book.Pages.Count) return; if (_currentIterator == null) { _currentIterator = Book.Pages[_currentPage].GetIterator(); _currentIterator.MoveToEnd(); } if (_currentIterator.MovePrevious()) { UpdateTextBox(); UpdateViewLabels(); } } void NextVersion() { EnsureSaved(); if (_currentPage >= Book.Pages.Count) return; if (_currentIterator == null) return; if (_currentIterator.MoveNext()) { UpdateTextBox(); UpdateViewLabels(); } } void PreviousPage() { _currentIterator = null; if (_currentPage > 0) { EnsureSaved(); --_currentPage; UpdateTextBox(); UpdateViewLabels(); } } void NextPage() { _currentIterator = null; EnsureSaved(); if (_currentPage < Book.Pages.Count && Book.Pages[_currentPage].Text != "") { ++_currentPage; UpdateTextBox(); UpdateViewLabels(); } } public void JumpToPage(int pageIndex) { if (pageIndex < 0 || pageIndex >= Book.Pages.Count) return; EnsureSaved(); _currentIterator = null; _currentPage = pageIndex; UpdateTextBox(); UpdateTitle(); UpdateViewLabels(); } public ScratchBook Book { get; private set; } } }
3a013210c1b6a5950f4530a352308c28708eaf5b
C#
thirty25/commandline-mediatr
/src/CommandLineApp/CommitOptions.cs
2.984375
3
using System; using System.Threading; using System.Threading.Tasks; using CommandLine; using MediatR; namespace CommandLineApp { [Verb("commit", HelpText = "Record changes to the repository.")] public class CommitOptions : IRequest<int> { [Option('m', "Message", HelpText = "Message for commit")] public string Message { get; set; } } public class CommitHandler : IRequestHandler<CommitOptions, int> { public Task<int> Handle(CommitOptions request, CancellationToken cancellationToken) { Console.WriteLine($"Commiting with a message of \"{request.Message}\""); return Task.FromResult(0); } } }
dfbe551fc8f859f31c218595fc0dc9182d8221aa
C#
YourGamesBeOver/LEDControllerUWP
/LEDControllerUWP/DeviceListEntry.cs
2.75
3
using Windows.Devices.Enumeration; namespace LEDControllerUWP { public class DeviceListEntry { public string DisplayName => DeviceInformation.Properties["System.ItemNameDisplay"] as string; public DeviceInformation DeviceInformation { get; } public string DeviceSelector { get; } /// <summary> /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these. /// </summary> /// <param name="deviceInformation"></param> /// <param name="deviceSelector">The AQS used to find this device</param> public DeviceListEntry(DeviceInformation deviceInformation, string deviceSelector) { this.DeviceInformation = deviceInformation; this.DeviceSelector = deviceSelector; } } }
e152ba1bd1fea977e6deee472936e3b2f9b945a7
C#
pixey/Pixey.DhcpClient
/LibDHCPServer/HardwareAddressTypes/GenericClientHardwareAddress.cs
2.59375
3
/// The MIT License(MIT) /// /// Copyright(c) 2017 Conscia Norway AS /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in all /// copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. using System; using System.Linq; using System.Text; namespace LibDHCPServer.HardwareAddressTypes { public class GenericClientHardwareAddress : ClientHardwareAddress { public byte[] HardwareAddress; public GenericClientHardwareAddress(byte [] buffer, long offset, long length) { HardwareAddress = new byte[length]; Array.Copy(buffer, offset, HardwareAddress, 0, length); } public GenericClientHardwareAddress(byte[] buffer) { HardwareAddress = new byte[buffer.Length]; Array.Copy(buffer, 0, HardwareAddress, 0, buffer.Length); } public override int AddressLength { get { return HardwareAddress.Length; } } public override string ToString() { if (Encoding.ASCII.GetChars(HardwareAddress, 0, HardwareAddress.Length).Select(x => Char.IsControl(x)).Where(x => x).FirstOrDefault()) return "Generic - " + String.Join(",", (HardwareAddress.Select(x => x.ToString("X2")))); else return "Generic - " + Encoding.ASCII.GetString(HardwareAddress); } public override byte[] GetBytes() { return HardwareAddress; } public override bool Equals(object obj) { var other = obj as GenericClientHardwareAddress; if (other == null) return false; return HardwareAddress.SequenceEqual(other.HardwareAddress); } public override int GetHashCode() { return HardwareAddress.GetHashCode(); } public override ClientHardwareAddress Clone() { return new GenericClientHardwareAddress(GetBytes()); } } }
c440cdaa38854a1020450d06de87e4219469e99c
C#
shendongnian/download4
/code2/351641-7532994-16654269-2.cs
2.609375
3
private Dictionary<object, Func<TrackingRecord, DbCommand>> conversionFunctions = new Dictionary<object, Func<TrackingRecord, DbCommand>>(); public void RegisterConversionFunction<T>(Func<T, DbCommand> conversionFunction) where T : TrackingRecord { conversionFunctions.Add(typeof(T), tr => conversionFunction(tr as T)); } public DbCommand GetConverstion<T>(T trackingRecord) where T : TrackingRecord { DbCommand command = null; if (conversionFunctions.ContainsKey(typeof(T))) { Func<TrackingRecord, DbCommand> conversionFunction; if (conversionFunctions.TryGetValue(trackingRecord.GetType(), out conversionFunction)) { command = conversionFunction.Invoke(trackingRecord); } } else { command = DefaultConversion(trackingRecord); } return command; }
2f4d12bdabc89ef8371488dda4c2640434b904f8
C#
ztodorova/Telerik-Academy
/C#OOP/OOP_PrinciplesPart1/AnimalHierarchy/Tomcat.cs
2.5625
3
 namespace AnimalHierarchy { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Tomcat : Cat { public Tomcat(string name, int age) : base(name,age,Sex.male) { } } }
946e3995b0679babbeca57c9f963b6ddcbeacf12
C#
noptran/pcm
/Common_Objects/Models/GradeModel.cs
3.109375
3
using System; using System.Collections.Generic; using System.Linq; namespace Common_Objects.Models { public class GradeModel { public Grade GetSpecificGrade(int gradeId) { Grade grade; var dbContext = new SDIIS_DatabaseEntities(); try { var gradeList = (from r in dbContext.Grades where r.Grade_Id.Equals(gradeId) select r).ToList(); grade = (from r in gradeList select r).FirstOrDefault(); } catch (Exception) { return null; } return grade; } public List<Grade> GetListOfGrades() { List<Grade> grades; using (var dbContext = new SDIIS_DatabaseEntities()) { try { var gradeList = (from r in dbContext.Grades select r).ToList(); grades = (from r in gradeList select r).ToList(); } catch (Exception) { return null; } } return grades; } } }
3936e55a288ee3c7247a60b91a6efcb0170c0882
C#
dnsk83/curecon
/curecon/curecon.Models/CurrencyListModel.cs
2.546875
3
using curecon.Core; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace curecon.Models { public class CurrencyListModel { ICountriesService CountriesService; public List<CurrencyModel> CurrencyModels { get; set; } public CurrencyListModel() { CurrencyModels = new List<CurrencyModel>(); // CountriesService = new CountriesService(); CountriesService = new CachedCountriesService(); } public async Task LoadCurrenciesAsync() { var countryDtos = await CountriesService.GetCountriesAsync(); foreach (var dto in countryDtos) { foreach (var currency in dto.Currencies) { CurrencyModels.Add(new CurrencyModel() { Code = currency.Code, Name = currency.Name, FlagUri = CurrencyModel.SetFlagUri(dto.Alpha2Code) }); } } } } }
72021b3b28b8e28fb2e9ae6cd02e1e80e4cf12cd
C#
Foggyy/Software-development-labworks
/Лабораторная работа №3/Лабораторная работа №3/Лабораторная работа №3/Program.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace Лабораторная_работа__3 { class Program { static void Main(string[] args) { double x, Y, shag,shag2,SN=0, SE=0,SE1=0; double b = 1, a = 0.1; //максимальное и минимальное значение x int n, k = 10; double E = 0.0001,e=0; shag = (b - a) / k; //шаг x for (x = a; x <=b; x = x + shag) //цикл для изменения x в заданном диапазоне { Y = Math.Atan(x); //точное значение функции for (n = 0; n<=40; n++) //цикл подсчета суммы для n=40 { shag2 = Math.Pow(-1, n) * Math.Pow(x, 2 * n + 1) / (2 * n + 1); SN+=shag2; } while (Math.Abs(Math.Pow(-1, e) * Math.Pow(x, 2 * e + 1) / (2 * e + 1)) > E) { SE =SE+ Math.Pow(-1, e) * Math.Pow(x, 2 * e + 1) / (2 * e + 1); // сумма с заданной точностью //SE1 =SE1+ Math.Pow(-1, e + 1) * Math.Pow(x, 2 * (e + 1) + 1) / (2 * (e + 1) + 1); e = e + 1; } //|Sn+1-Sn|<E Console.WriteLine("X = {0} SN = {1} SE = {2} Y = {3}",x,SN,SE,Y); SN = 0; // возвращение к исходному значению SE = 0; SE1 = 0; e = 0; } Console.ReadLine(); } } }
f62866bd42bbe716d2a40b3d236df3242c649df8
C#
CrazyMachine2/FriendOrganizer
/FriendOrganizer.DataAccess/Configurations/ProgrammingLanguageConfiguration.cs
2.53125
3
using FriendOrganizer.Model; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace FriendOrganizer.DataAccess.Configurations { class ProgrammingLanguageConfiguration : IEntityTypeConfiguration<ProgrammingLanguage> { public void Configure(EntityTypeBuilder<ProgrammingLanguage> builder) { builder.HasData( new ProgrammingLanguage { ID = 1, Name = "C#" }, new ProgrammingLanguage { ID = 2, Name = "Java" }, new ProgrammingLanguage { ID = 3, Name = "JavaScript" }, new ProgrammingLanguage { ID = 4, Name = "PHP" }, new ProgrammingLanguage { ID = 5, Name = "Python" } ); } } }
a33d531c1f65803849526a59f126ed9271847e43
C#
robert-adrian99/Restaurant
/Restaurant/ViewModels/SignInViewModel.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Restaurant.Helps; using Restaurant.Models; using Restaurant.Models.BusinessLogicLayer; using Restaurant.Views; namespace Restaurant.ViewModels { public class SignInViewModel : NotifyPropertyChangedHelp { #region DataMembers private string email; public string Email { get { return email; } set { email = value; ErrorMessage = ""; Regex regex = new Regex(@"^[A-Za-z0-9._]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"); if (regex.Match(Email) == Match.Empty) { ErrorMessage = "INVALID EMAIL FORMAT"; CanExecuteCommand = false; } else { CanExecuteCommand = true; } NotifyPropertyChanged("Email"); } } private string errorMessage; public string ErrorMessage { get { return errorMessage; } set { errorMessage = value; NotifyPropertyChanged("ErrorMessage"); } } #endregion #region CommandMembers public bool CanExecuteCommand { get; set; } = false; private ICommand signInCommand; public ICommand SignInCommand { get { if (signInCommand == null) { signInCommand = new RelayCommand(SignIn, param => CanExecuteCommand); } return signInCommand; } } public void SignIn(object param) { string password = (param as PasswordBox).Password; if (password.Length == 0) { MessageBox.Show("Enter your password"); } else { UserBLL user = new UserBLL(); try { user.SignIn(Email, password); Regex regex = new Regex(@"@steak-house.com$|@steakhouse.com$"); if (regex.Match(Email) != Match.Empty) { EmployeeStartWindow employeeStartWindow = new EmployeeStartWindow(); App.Current.MainWindow.Close(); App.Current.MainWindow = employeeStartWindow; App.Current.MainWindow.Show(); } else { MenuWindow menuWindow = new MenuWindow(); App.Current.MainWindow.Close(); App.Current.MainWindow = menuWindow; App.Current.MainWindow.Show(); } } catch { MessageBox.Show("Incorrect email or password!"); } } } #endregion } }
751746218efa54fceb6068811a5f9cacef1647f4
C#
maratovS/CarDealerCore
/CarDealerCore/Controllers/SaleController.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CarDealerCore.Data; using CarDealerCore.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace CarDealerCore.Controllers { public class SaleController : Controller { private ApplicationContext _db; public SaleController(ApplicationContext db) { _db = db; } // GET [Authorize(Policy = "User")] public async Task<IActionResult> MySales() { List<Sale> mySales = await _db.Sales .Where(x => x.User.UserName == HttpContext.User.Identity.Name) .ToListAsync(); return View(mySales); } [Authorize(Policy = "Admin")] public async Task<IActionResult> AllSales(int Year) { Year = Year == 0 || Year < 2017 ? DateTime.Now.Year : Year; ViewBag.Year = Year; var sales = _db.Sales.ToList() .Where(x=>x.Date_Sold.Year == Year) .GroupBy(x => x.Date_Sold.Month) .Select(x => new { x.Key, Sum = x.Sum(s => s.Car.Price) }) .OrderBy(x => x.Key); //DateTime dateTime = new DateTime(2021,12, 12); Dictionary<int, decimal> proceed = new Dictionary<int, decimal>(); int counter = 1; foreach (var sale in sales) { if (counter < sale.Key) { for (; counter < sale.Key; ++counter) proceed[counter] = 0.0m; proceed[sale.Key] = sale.Sum; ++counter; } else proceed[sale.Key] = sale.Sum; } while (counter <= 12) proceed[counter++] = 0.0m; ViewBag.sales = proceed; return View(await _db.Sales.ToListAsync()); } public async Task<IActionResult> ChangeStatus(int id) { Sale sale = await _db.Sales.FindAsync(id); sale.Status = "Продано"; _db.Update(sale); await _db.SaveChangesAsync(); return RedirectToAction("AllSales", "Sale"); } } }
e7f79f0e4393656553f7dd3c8cebe7ef1d510ade
C#
dartagnanjr/TesteVscodeFluenteHibernate
/Program.cs
2.84375
3
using System; using MyProjectNHibernate2.Entities; namespace MyProjectNHibernate2 { class Program { static void Main(string[] args) { Person per = new Person(); PersonProject dao = new PersonProject(); Console.WriteLine("Iniciando a inserção"); per.Id = 1; per.Name = "Junior"; per.CreationDate = DateTime.Today; per.UpdatedDate = DateTime.Now; dao.Inserir(per); Console.WriteLine("Ok, operação realizada."); } } }
9e887d8b99cf871b619fca5746fe6bc84787a3eb
C#
karthik-Undi/ComplaintsAPI
/ComplaintsAPI/Repositories/CompRepos.cs
2.90625
3
using ComplaintsAPI.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ComplaintsAPI.Repositories { public class CompRepos : ICompRepos { private readonly CommunityGateDatabaseContext _context; public CompRepos() { } public CompRepos(CommunityGateDatabaseContext context) { _context = context; } public IEnumerable<Complaints> GetAllComplaints() { return _context.Complaints.ToList(); } public Complaints GetComplaintById(int id) { Complaints item = _context.Complaints.Find(id); return item; } public IEnumerable<Complaints> GetComplaintsByResidentId(int id) { var item = _context.Complaints.Where(t => t.ResidentId == id && t.ComplaintStatus == "Unresolved").ToList(); return item; } public async Task<Complaints> PostComplaint(Complaints item) { Complaints complaint = null; if(item==null) { throw new NullReferenceException(); } else { complaint = new Complaints() { ResidentId = item.ResidentId, ComplaintRegarding = item.ComplaintRegarding, ComplaintStatus = "Unresolved" }; await _context.Complaints.AddAsync(complaint); await _context.SaveChangesAsync(); } return complaint; } public async Task<Complaints> UpdateComplaint(int id) { Complaints complaint = await _context.Complaints.FindAsync(id); complaint.ComplaintStatus = "Resolved"; await _context.SaveChangesAsync(); return complaint; } } }
c5486439528b26fc1cf3d7209cb67301864df88f
C#
QualiSystems/Toscana
/Toscana/ToscaTopologyTemplate.cs
2.84375
3
using System.Collections.Generic; namespace Toscana { /// <summary> /// A Topology Template defines the structure of a service in the context of a Service Template. /// A Topology Template consists of a set of Node Template and Relationship Template definitions /// that together define the topology model of a service as a (not necessarily connected) directed graph. /// </summary> public class ToscaTopologyTemplate { /// <summary> /// Initializes an instance of ToscaTopologyTemplate /// </summary> public ToscaTopologyTemplate() { NodeTemplates = new Dictionary<string, ToscaNodeTemplate>(); Inputs = new Dictionary<string, ToscaParameter>(); Outputs = new Dictionary<string, ToscaParameter>(); } /// <summary> /// The optional description for the Topology Template. /// </summary> public string Description { get; set; } /// <summary> /// An optional list of input parameters (i.e., as parameter definitions) for the Topology Template. /// </summary> public Dictionary<string, ToscaParameter> Inputs { get; set; } /// <summary> /// An optional list of node template definitions for the Topology Template. /// </summary> public Dictionary<string, ToscaNodeTemplate> NodeTemplates { get; set; } /// <summary> /// An optional list of relationship templates for the Topology Template. /// </summary> public Dictionary<string, ToscaRelationshipTemplate> RelationshipTemplates { get; set; } /// <summary> /// An optional list of Group definitions whose members are node templates defined within this same Topology Template. /// </summary> public Dictionary<string, ToscaGroup> Groups { get; set; } /// <summary> /// An optional list of Policy definitions for the Topology Template. /// </summary> public Dictionary<string, ToscaPolicy> Policies { get; set; } /// <summary> /// An optional list of output parameters (i.e., as parameter definitions) for the Topology Template. /// </summary> public Dictionary<string, ToscaParameter> Outputs { get; set; } /// <summary> /// An optional declaration that exports the topology template as an implementation of a Node type. /// This also includes the mappings between the external Node Types named capabilities and requirements /// to existing implementations of those capabilities and requirements on Node templates declared within the topology template. /// </summary> public object SubstitutionMappings { get; set; } } }
495c4ebbbd24da7dcca89aa9991aeaf00ce17264
C#
shendongnian/download4
/code4/706475-17037374-41977186-2.cs
2.671875
3
namespace _17036954 { class Program { static void Main(string[] args) { AppDomain testApp = AppDomain.CreateDomain("testApp"); try { args = new string[] { }; string path = ConfigurationManager.AppSettings.Get("testApp"); //subscribe to ProcessExit before executing the assembly testApp.ProcessExit += (sender, e) => { //do nothing or do anything Console.WriteLine("The appdomain ended"); Console.WriteLine("Press any key to end this program"); Console.ReadKey(); }; testApp.ExecuteAssembly(path); } catch (Exception ex) { //Catch process here } finally { AppDomain.Unload(testApp); } } } }
40a53f51a4396111cf8efc967baa90c01f85e71c
C#
guih2127/c--poo-classes
/POOclasses/POOexercices/FinalExercice01/FinalExercice01/Program.cs
3.609375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FinalExercice01 { class Program { static void Main(string[] args) { Conta c; Console.WriteLine("Vamos criar a sua conta! Deseja fazer um depósito inicial? Digite 1 se Sim ou outro número se não."); int escolha = int.Parse(Console.ReadLine()); if (escolha == 1) { Console.Write("Informe o número da conta: "); int numero = int.Parse(Console.ReadLine()); Console.Write("Informe seu nome: "); string nome = Console.ReadLine(); Console.Write("Agora, informe o valor do depósito inicial: "); double valor = double.Parse(Console.ReadLine()); c = new Conta(valor, numero, nome); } else { Console.Write("Informe o número da conta: "); int numero = int.Parse(Console.ReadLine()); Console.Write("Informe seu nome: "); string nome = Console.ReadLine(); c = new Conta(numero, nome); } Console.WriteLine(c); Console.Write("Agora, vamos fazer um depósito, digite o valor: "); double valorDep = double.Parse(Console.ReadLine()); c.Deposito(valorDep); Console.WriteLine(c); Console.Write("Agora, vamos fazer um saque, digite o valor: "); double valorSaq = double.Parse(Console.ReadLine()); c.Saque(valorSaq); Console.WriteLine(c); } } }
7818c15e7f9af002ea0d4bad13e2a225805a5dff
C#
crazybaz/r2d2
/Assets/src/tools/ComponentExtention.cs
2.953125
3
using System.Collections.Generic; using UnityEngine; public class ComponentExtention { public static T CopyComponent<T>(Component sourceComponent, GameObject target) where T : Component { var type = sourceComponent.GetType(); var targetComponent = target.AddComponent(type); foreach (var field in type.GetFields()) { // Debug.Log("FIELD " + field.Name + " VALUE " + field.GetValue(sourceComponent)); field.SetValue(targetComponent, field.GetValue(sourceComponent)); } return targetComponent as T; } public static List<T> CopyComponents<T>(GameObject source, GameObject target) where T : Component { var res = new List<T>(); foreach (var component in source.GetComponents<T>()) res.Add(CopyComponent<T>(component, target)); return res; } }
5a55af916298aa528820ace7a241beba63c01a59
C#
kodomcnuggets/TicTacNeo
/TicTacNeo/TicTacToeContract/TicTacToeContract.cs
2.90625
3
using Neo.SmartContract.Framework; using Neo.SmartContract.Framework.Services.Neo; using System.Numerics; namespace TicTacToeContract { public class TicTacToeContract : SmartContract { #region Models - Do not change here; Change in TicTacToe project, then copy here public enum LocationMarker { Empty, O, X } public class GameBoard { public LocationMarker[] Board { get; protected set; } protected GameBoard() { } public static GameBoard NewGameBoard() { return new GameBoard() { Board = new LocationMarker[9] { LocationMarker.Empty, LocationMarker.Empty, LocationMarker.Empty, LocationMarker.Empty, LocationMarker.Empty, LocationMarker.Empty, LocationMarker.Empty, LocationMarker.Empty, LocationMarker.Empty } }; } public bool MarkLocation(int row, int column, LocationMarker playerMarker) { if (row > 2 || column > 2 || playerMarker == LocationMarker.Empty) return false; var index = row * 3 + column; if (Board[index] != LocationMarker.Empty) return false; Board[index] = playerMarker; return true; } public bool IsWinner(LocationMarker playerMarker) { for (int i = 0; i < 2; i++) { var rowOffset = i * 3; if (Board[rowOffset] == playerMarker && Board[rowOffset + 1] == playerMarker && Board[rowOffset + 2] == playerMarker) return true; if (Board[i] == playerMarker && Board[3 + i] == playerMarker && Board[6 + i] == playerMarker) return true; } if (Board[0] == playerMarker && Board[4] == playerMarker && Board[8] == playerMarker) return true; if (Board[6] == playerMarker && Board[4] == playerMarker && Board[2] == playerMarker) return true; return false; } public bool IsALocationEmpty() { for (int i = 0; i < 9; i++) { if (Board[i] == LocationMarker.Empty) return true; } return false; } } public class Player { public string Id { get; protected set; } protected Player() { } public static Player NewPlayer(string id) { return new Player { Id = id }; } } public class TicTacToePlayer : Player { public LocationMarker Marker { get; private set; } public int TurnOrder { get; private set; } private TicTacToePlayer() { } public static TicTacToePlayer NewTicTacToePlayer(Player player, LocationMarker marker, int turnOrder) { return new TicTacToePlayer { Id = player.Id, Marker = marker, TurnOrder = turnOrder }; } } public class TicTacToeGame { public string Id { get; private set; } public TicTacToePlayer[] Players { get; private set; } public GameBoard GameBoard { get; private set; } public int CurrentPlayerIndex { get; private set; } public TicTacToePlayer CurrentPlayer { get { return Players[CurrentPlayerIndex]; } } public bool IsGameFull { get; private set; } public bool IsGameOver { get; private set; } public bool IsGameDraw { get; private set; } private TicTacToeGame() { } public static TicTacToeGame NewTicTacToeGame(string gameId, Player playerOne) { return new TicTacToeGame { Id = gameId, Players = new TicTacToePlayer[2] { TicTacToePlayer.NewTicTacToePlayer(playerOne, LocationMarker.O, 0), null }, GameBoard = GameBoard.NewGameBoard() }; } public bool MarkLocation(int row, int column) { if (!IsGameFull || IsGameOver) return false; if (!GameBoard.MarkLocation(row, column, CurrentPlayer.Marker)) return false; if (GameBoard.IsWinner(CurrentPlayer.Marker)) { IsGameOver = true; return true; } if (!GameBoard.IsALocationEmpty()) { IsGameOver = true; IsGameDraw = true; return true; } CurrentPlayerIndex = (CurrentPlayer.TurnOrder + 1) % 2; return true; } public bool Update(TicTacToeGame updateGame) { if (Id != updateGame.Id) return false; Players = updateGame.Players; CurrentPlayerIndex = updateGame.CurrentPlayerIndex; GameBoard = updateGame.GameBoard; IsGameOver = updateGame.IsGameOver; IsGameDraw = updateGame.IsGameDraw; return true; } public bool JoinGame(Player playerTwo) { if (IsGameFull) return false; Players[1] = TicTacToePlayer.NewTicTacToePlayer(playerTwo, LocationMarker.X, 1); IsGameFull = true; return true; } } public class ContractResult { public bool OperationResult { get; private set; } public string Error { get; private set; } public TicTacToeGame Game { get; private set; } private ContractResult() { } public static ContractResult NewContractResult(bool operationResult, string error) { return new ContractResult { OperationResult = operationResult, Error = error }; } public static ContractResult NewContractResult(bool operationResult, string error, TicTacToeGame game) { return new ContractResult { OperationResult = operationResult, Error = error, Game = game }; } } #endregion public static string Main(string operation, params object[] args) { string error = "null"; if (Runtime.Trigger == TriggerType.Application) { if (operation == "creategame") { if (args.Length == 1) return CreateGame((string)args[0]); error = "Incorrect number of args (" + args.Length + ") for operation (" + operation + ")"; } else if (operation == "joingame") { if (args.Length == 1) return JoinGame((string)args[1]); error = "Incorrect number of args (" + args.Length + ") for operation (" + operation + ")"; } else if (operation == "marklocation") { if (args.Length == 4) return MarkLocation((string)args[0], (string)args[1], (int)args[2], (int)args[3]); error = "Incorrect number of args (" + args.Length + ") for operation (" + operation + ")"; } else if (operation == "fetchgame") { if (args.Length == 1) return FetchGame((string)args[0]); error = "Incorrect number of args (" + args.Length + ") for operation (" + operation + ")"; } else { error = "Invalid operation (" + operation + ")"; } } return ContractResult.NewContractResult(false, error).Serialize().AsString(); } #region Helpers private static string GetNextGameId() { var gameIdBytes = Storage.Get(Storage.CurrentContext, "GameId"); BigInteger gameId; if (gameIdBytes == null || gameIdBytes.Length == 0) { gameId = 1; } else { gameId = gameIdBytes.AsBigInteger(); gameId = gameId + 1; } Storage.Put(Storage.CurrentContext, "GameId", gameId); return gameId.AsByteArray().AsString(); } private static void OpenGame(TicTacToeGame game) { Storage.Put(Storage.CurrentContext, "o-" + game.Id, game.Serialize()); } private static void SaveGame(TicTacToeGame game) { Storage.Put(Storage.CurrentContext, game.Id, game.Serialize()); } private static void CloseGame(TicTacToeGame game) { Storage.Delete(Storage.CurrentContext, "o-" + game.Id); SaveGame(game); } private static TicTacToeGame GetGame(string gameId) { var gameBytes = Storage.Get(Storage.CurrentContext, gameId); if (gameBytes == null || gameBytes.Length == 0) return null; return (TicTacToeGame)gameBytes.Deserialize(); } private static Player CastPlayer(string playerJson) { if (playerJson == null || playerJson == "") return null; var playerBytes = playerJson.AsByteArray(); if (playerBytes == null || playerBytes.Length == 0) return null; return (Player)playerBytes.Deserialize(); } private static TicTacToeGame FindOpenGame() { var openGames = Storage.Find(Storage.CurrentContext, "o-"); return (TicTacToeGame)openGames.Value.Deserialize(); } #endregion #region Operations private static string CreateGame(string playerOneJson) { var playerOne = CastPlayer(playerOneJson); bool operationResult; string error; TicTacToeGame game; if (playerOne == null) { operationResult = false; error = "Invalid Player JSON (" + playerOneJson + ")"; game = null; } else { operationResult = true; error = null; game = TicTacToeGame.NewTicTacToeGame(GetNextGameId(), playerOne); OpenGame(game); } return ContractResult.NewContractResult(operationResult, error, game).Serialize().AsString(); } private static string JoinGame(string playerTwoJson) { var game = FindOpenGame(); var playerTwo = CastPlayer(playerTwoJson); bool operationResult; string error; if (game == null) { operationResult = false; error = "No games available"; } else if (playerTwo == null) { operationResult = false; error = "Invalid Player JSON (" + playerTwo + ")"; } else { if(game.JoinGame(playerTwo)) { operationResult = true; error = null; CloseGame(game); } else { operationResult = false; error = "Game full (" + game.Id + ")"; } } return ContractResult.NewContractResult(operationResult, error, game).Serialize().AsString(); } private static string MarkLocation(string gameId, string playerId, int row, int column) { var game = GetGame(gameId); bool operationResult; string error; if (game == null) { operationResult = false; error = "Game not found (" + gameId + ")"; } else if (game.CurrentPlayer.Id != playerId) { operationResult = false; error = "Not player's turn (" + playerId + ")"; } else { operationResult = true; error = null; game.MarkLocation(row, column); SaveGame(game); } return ContractResult.NewContractResult(operationResult, error, game).Serialize().AsString(); } private static string FetchGame(string gameId) { var game = GetGame(gameId); bool operationResult; string error; if (game == null) { operationResult = false; error = "Game not found (" + gameId + ")"; } else { operationResult = true; error = null; } return ContractResult.NewContractResult(operationResult, error, game).Serialize().AsString(); } #endregion } }
557fb69c0db53fc18dbe4131e94b12fbb10ee60b
C#
tomkerkhove/azure-databricks-client
/csharp/Microsoft.Azure.Databricks.Client/EventsRequest.cs
2.8125
3
using System; using System.Collections.Generic; using System.ComponentModel; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Microsoft.Azure.Databricks.Client { public class EventsRequest { /// <summary> /// The ID of the cluster to retrieve events about. This field is required. /// </summary> [JsonProperty(PropertyName= "cluster_id")] public string ClusterId { get; set; } /// <summary> /// The start time in epoch milliseconds. If empty, returns events starting from the beginning of time. /// </summary> [JsonProperty(PropertyName = "start_time")] [JsonConverter(typeof(MillisecondEpochDateTimeConverter))] public DateTimeOffset? StartTime { get; set; } /// <summary> /// The end time in epoch milliseconds. If empty, returns events up to the current time. /// </summary> [JsonProperty(PropertyName = "end_time")] [JsonConverter(typeof(MillisecondEpochDateTimeConverter))] public DateTimeOffset? EndTime { get; set; } /// <summary> /// The order to list events in; either ASC or DESC. Defaults to DESC. /// </summary> [JsonProperty(PropertyName = "order")] [JsonConverter(typeof(StringEnumConverter))] public ListOrder? Order { get; set; } /// <summary> /// An optional set of event types to filter on. If empty, all event types are returned. /// </summary> [JsonProperty(PropertyName = "event_types", ItemConverterType = typeof(StringEnumConverter))] public IEnumerable<ClusterEventType> EventTypes { get; set; } /// <summary> /// The offset in the result set. Defaults to 0 (no offset). When an offset is specified and the results are requested in descending order, the end_time field is required. /// </summary> [JsonProperty(PropertyName = "offset")] public long? Offset { get; set; } /// <summary> /// The maximum number of events to include in a page of events. Defaults to 50, and maximum allowed value is 500. /// </summary> [JsonProperty(PropertyName = "limit")] public long? Limit { get; set; } } }
4e53b27b86752af59c82833098b9c8b82d642c87
C#
NServiceKit/NServiceKit.Logging
/src/NServiceKit.Logging.NLog/NLogFactory.cs
2.625
3
using System; using NServiceKit.Logging; namespace NServiceKit.Logging.NLogger { /// <summary> /// ILogFactory that creates an NLog ILog logger /// </summary> public class NLogFactory : NServiceKit.Logging.ILogFactory { /// <summary> /// Initializes a new instance of the <see cref="NLogFactory"/> class. /// </summary> public NLogFactory() { } /// <summary> /// Gets the logger. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public ILog GetLogger(Type type) { return new NLogLogger(type); } /// <summary> /// Gets the logger. /// </summary> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public ILog GetLogger(string typeName) { return new NLogLogger(typeName); } } }
bc64108a219e808a66310abeb86f16c6a6a503ee
C#
LQVinh9/ApplicationSellsPhones
/dao/OrderDetailDao.cs
2.703125
3
using ProjectNhom.dto; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectNhom.dao { class OrderDetailDao { string strConnection; public string getConnectionString() { //string strConnection = @"server=DESKTOP-9L0KUCO\SQLEXPRESS;database=ShopPhone;uid=sa;pwd=123"; //Amazon string strConnection = @"server=testdatabaseaws.c3lyzgwnjxrk.ap-southeast-1.rds.amazonaws.com;database=ShopPhone;uid=admin;pwd=12345678"; return strConnection; } public OrderDetailDao() { strConnection = getConnectionString(); } public List<OrderDetail> getAllOrderDetail() { List<OrderDetail> listOrderDetail = new List<OrderDetail>(); string sql = "select orderDetailID,price,quantity,orderID,productID from OrderDetail"; SqlConnection cnn = new SqlConnection(strConnection); try { if (cnn.State == ConnectionState.Closed) { cnn.Open(); } SqlCommand cmd = new SqlCommand(sql, cnn); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { string orderDetailID = reader.GetString(0); float price = (float)reader.GetDouble(1); int quantity = reader.GetInt32(2); string orderID = reader.GetString(3); string productID = reader.GetString(4); OrderDetail orderDetail = new OrderDetail(orderDetailID, price, quantity, orderID, productID); listOrderDetail.Add(orderDetail); } } } catch (SqlException se) { throw new Exception(se.Message); } finally { cnn.Close(); } return listOrderDetail; } } }
cd966ed3986fdc52d1af8c4e56ed6fe83c57a3c8
C#
mstresses/DeliveryCORE
/BLL/Validators/ProdutoValidator.cs
2.71875
3
using Common; using DTO; using FluentValidation; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace BLL.Validators { public class ProdutoValidator : AbstractValidator<ProdutoDTO> { public ProdutoValidator() { List<Error> error = new List<Error>(); RuleFor(r => r.Nome).NotNull().WithMessage("O nome deve ser informado."); RuleFor(r => r.Nome).MaximumLength(60).WithMessage("O nome deve ter no máximo 30 caracteres."); error.Add(new Error() { FieldName = "Nome", Message = "Problema com o nome, verifique." }); RuleFor(r => r.Restaurante).NotNull().WithMessage("O restaurante deve ser informado."); error.Add(new Error() { FieldName = "Restaurante", Message = "Problema com o Restaurante, verifique." }); RuleFor(r => r.Valor).NotNull().WithMessage("O Valor deve ser informado."); error.Add(new Error() { FieldName = "Valor", Message = "Problema com o Valor, verifique." }); //if (error.Count > 0) //{ // File.WriteAllText("log.txt", error.ToString()); // throw new Exception(); //} } } }