commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
7bec8226cc515339e4cb1a98a27e62d6bca3c5a4
PickemApp/Global.asax.cs
PickemApp/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace PickemApp { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using PickemApp.Models; using PickemApp.Migrations; namespace PickemApp { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<PickemDBContext, Configuration>()); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }
Enable migrations on app start
Enable migrations on app start
C#
isc
chrisofspades/PickemApp,chrisofspades/PickemApp,chrisofspades/PickemApp
9fdd5f6a760ce3519f9ba7402c364629b663a5cc
Portfolio/Global.asax.cs
Portfolio/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Portfolio { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Portfolio { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Runs Code First database update on each restart... // handy for deploy via GitHub. #if !DEBUG var migrator = new DbMigrator(new Configuration()); migrator.Update(); #endif } } }
Enable CF migrations on restart
Enable CF migrations on restart
C#
isc
dev-academy-phase4/cs-portfolio,dev-academy-phase4/cs-portfolio
a62770b39df18615939fa7366ff868b0feef2c18
src/Demo/DemoDistributor/Program.cs
src/Demo/DemoDistributor/Program.cs
using System; using DemoDistributor.Endpoints.FileSystem; using DemoDistributor.Endpoints.Sharepoint; using Delivered; namespace DemoDistributor { internal class Program { private static void Main(string[] args) { //Configure the distributor var distributor = new Distributor<File, Vendor>(); //distributor.RegisterEndpointRepository(new FileSystemEndpointRepository()); distributor.RegisterEndpointRepository(new SharepointEndpointRepository()); distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService()); distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService()); distributor.MaximumConcurrentDeliveries(3); //Distribute a file to a vendor try { var task = distributor.DistributeAsync(FakeFile, FakeVendor); task.Wait(); Console.WriteLine("\nDistribution succeeded."); } catch(AggregateException aggregateException) { Console.WriteLine("\nDistribution failed."); foreach (var exception in aggregateException.Flatten().InnerExceptions) { Console.WriteLine($"* {exception.Message}"); } } Console.WriteLine("\nPress enter to exit."); Console.ReadLine(); } private static File FakeFile => new File { Name = @"test.pdf", Contents = new byte[1024] }; private static Vendor FakeVendor => new Vendor { Name = @"Mark's Pool Supplies" }; private static Vendor FakeVendor2 => new Vendor { Name = @"Kevin's Art Supplies" }; } }
using System; using DemoDistributor.Endpoints.FileSystem; using DemoDistributor.Endpoints.Sharepoint; using Delivered; namespace DemoDistributor { internal class Program { private static void Main(string[] args) { //Configure the distributor var distributor = new Distributor<File, Vendor>(); distributor.RegisterEndpointRepository(new FileSystemEndpointRepository()); distributor.RegisterEndpointRepository(new SharepointEndpointRepository()); distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService()); distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService()); distributor.MaximumConcurrentDeliveries(3); //Distribute a file to a vendor try { var task = distributor.DistributeAsync(FakeFile, FakeVendor); task.Wait(); Console.WriteLine("\nDistribution succeeded."); } catch(AggregateException aggregateException) { Console.WriteLine("\nDistribution failed."); foreach (var exception in aggregateException.Flatten().InnerExceptions) { Console.WriteLine($"* {exception.Message}"); } } Console.WriteLine("\nPress enter to exit."); Console.ReadLine(); } private static File FakeFile => new File { Name = @"test.pdf", Contents = new byte[1024] }; private static Vendor FakeVendor => new Vendor { Name = @"Mark's Pool Supplies" }; private static Vendor FakeVendor2 => new Vendor { Name = @"Kevin's Art Supplies" }; } }
Fix demo by uncommenting line accidentally left commented
Fix demo by uncommenting line accidentally left commented
C#
mit
justinjstark/Verdeler,justinjstark/Delivered
d6765899f4dea2bbb922d8b5f3c781ac144e0415
Battlezeppelins/Controllers/BaseController.cs
Battlezeppelins/Controllers/BaseController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public abstract class BaseController : Controller { private static List<Player> playerList = new List<Player>(); public Player GetPlayer() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int id = Int32.Parse(idStr); Player player = SearchPlayer(id); if (player != null) return player; lock (playerList) { player = SearchPlayer(id); if (player != null) return player; Player newPlayer = Player.GetInstance(id); playerList.Add(newPlayer); return newPlayer; } } return null; } private Player SearchPlayer(int id) { if (!playerList.Any()) return null; foreach (Player listPlayer in playerList) { if (listPlayer.id == id) { return listPlayer; } } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public abstract class BaseController : Controller { private static List<Player> playerList = new List<Player>(); public Player GetPlayer() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int id = Int32.Parse(idStr); Player player = SearchPlayer(id); if (player != null) return player; lock (playerList) { player = SearchPlayer(id); if (player != null) return player; Player newPlayer = Player.GetInstance(id); if (newPlayer != null) playerList.Add(newPlayer); return newPlayer; } } return null; } private Player SearchPlayer(int id) { if (!playerList.Any()) return null; foreach (Player listPlayer in playerList) { if (listPlayer.id == id) { return listPlayer; } } return null; } } }
Fix null players in player list.
Fix null players in player list.
C#
apache-2.0
Mikuz/Battlezeppelins,Mikuz/Battlezeppelins
934d41fc92e122ecdfc2bb22e254aca1620809d3
PlantUmlEditor/View/DiagramEditorView.xaml.cs
PlantUmlEditor/View/DiagramEditorView.xaml.cs
using System.Windows.Controls; namespace PlantUmlEditor.View { public partial class DiagramEditorView : UserControl { public DiagramEditorView() { InitializeComponent(); } } }
using System; using System.Windows.Controls; namespace PlantUmlEditor.View { public partial class DiagramEditorView : UserControl { public DiagramEditorView() { InitializeComponent(); ContentEditor.IsEnabledChanged += ContentEditor_IsEnabledChanged; } void ContentEditor_IsEnabledChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { // Maintain focus on the text editor. if ((bool)e.NewValue) Dispatcher.BeginInvoke(new Action(() => ContentEditor.Focus())); } } }
Maintain focus on the text editor after saving.
Maintain focus on the text editor after saving.
C#
apache-2.0
mthamil/PlantUMLStudio,mthamil/PlantUMLStudio
a457b3d8484f3bbcceef453e29c89beb861eec44
src/SharpGraphEditor/ViewModels/TextViewerViewModel.cs
src/SharpGraphEditor/ViewModels/TextViewerViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Caliburn.Micro; namespace SharpGraphEditor.ViewModels { public class TextViewerViewModel : PropertyChangedBase { private string _text; private bool _canCopy; private bool _canCancel; private bool _isReadOnly; public TextViewerViewModel(string text, bool canCopy, bool canCancel, bool isReadOnly) { Text = text; CanCopy = CanCopy; CanCancel = canCancel; IsReadOnly = isReadOnly; } public void Ok(IClose closableWindow) { closableWindow.TryClose(true); } public void Cancel(IClose closableWindow) { closableWindow.TryClose(false); } public void CopyText() { Clipboard.SetText(Text); } public string Text { get { return _text; } set { _text = value; NotifyOfPropertyChange(() => Text); } } public bool CanCopy { get { return _canCopy; } set { _canCopy = value; NotifyOfPropertyChange(() => CanCopy); } } public bool CanCancel { get { return _canCancel; } set { _canCancel = value; NotifyOfPropertyChange(() => CanCancel); } } public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; NotifyOfPropertyChange(() => IsReadOnly); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Caliburn.Micro; namespace SharpGraphEditor.ViewModels { public class TextViewerViewModel : PropertyChangedBase { private string _text; private bool _canCopy; private bool _canCancel; private bool _isReadOnly; public TextViewerViewModel(string text, bool canCopy, bool canCancel, bool isReadOnly) { Text = text; CanCopy = canCopy; CanCancel = canCancel; IsReadOnly = isReadOnly; } public void Ok(IClose closableWindow) { closableWindow.TryClose(true); } public void Cancel(IClose closableWindow) { closableWindow.TryClose(false); } public void CopyText() { Clipboard.SetText(Text); } public string Text { get { return _text; } set { _text = value; NotifyOfPropertyChange(() => Text); } } public bool CanCopy { get { return _canCopy; } set { _canCopy = value; NotifyOfPropertyChange(() => CanCopy); } } public bool CanCancel { get { return _canCancel; } set { _canCancel = value; NotifyOfPropertyChange(() => CanCancel); } } public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; NotifyOfPropertyChange(() => IsReadOnly); } } } }
Fix bug: "Copy" button don't show in TextView during saving
Fix bug: "Copy" button don't show in TextView during saving
C#
apache-2.0
AceSkiffer/SharpGraphEditor
647e2c297cb91288df121bf4577a792537ce4012
osu.iOS/Application.cs
osu.iOS/Application.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using UIKit; namespace osu.iOS { public class Application { public static void Main(string[] args) { UIApplication.Main(args, null, "AppDelegate"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using UIKit; namespace osu.iOS { public class Application { public static void Main(string[] args) { UIApplication.Main(args, "GameUIApplication", "AppDelegate"); } } }
Fix iOS app entry for raw keyboard input
Fix iOS app entry for raw keyboard input
C#
mit
EVAST9919/osu,ZLima12/osu,UselessToucan/osu,2yangk23/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,ppy/osu,ppy/osu,peppy/osu,2yangk23/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,smoogipooo/osu,EVAST9919/osu,UselessToucan/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu
3e3b4d8af5fd1302a77add38f262c3c74fb303f7
Mindscape.Raygun4Net/Breadcrumbs/HttpBreadcrumbStorage.cs
Mindscape.Raygun4Net/Breadcrumbs/HttpBreadcrumbStorage.cs
using System.Collections; using System.Collections.Generic; using System.Web; namespace Mindscape.Raygun4Net.Breadcrumbs { internal class HttpBreadcrumbStorage : IRaygunBreadcrumbStorage { private const string ItemsKey = "Raygun.Breadcrumbs.Storage"; public IEnumerator<RaygunBreadcrumb> GetEnumerator() { return GetList().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Store(RaygunBreadcrumb breadcrumb) { GetList().Add(breadcrumb); } public void Clear() { GetList().Clear(); } private List<RaygunBreadcrumb> GetList() { SetupStorage(); return (List<RaygunBreadcrumb>) HttpContext.Current.Items[ItemsKey]; } private void SetupStorage() { if (HttpContext.Current != null && !HttpContext.Current.Items.Contains(ItemsKey)) { HttpContext.Current.Items[ItemsKey] = new List<RaygunBreadcrumb>(); } } } }
using System.Collections; using System.Collections.Generic; using System.Web; namespace Mindscape.Raygun4Net.Breadcrumbs { internal class HttpBreadcrumbStorage : IRaygunBreadcrumbStorage { private const string ItemsKey = "Raygun.Breadcrumbs.Storage"; public IEnumerator<RaygunBreadcrumb> GetEnumerator() { return GetList().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Store(RaygunBreadcrumb breadcrumb) { GetList().Add(breadcrumb); } public void Clear() { GetList().Clear(); } private List<RaygunBreadcrumb> GetList() { if (HttpContext.Current == null) { return new List<RaygunBreadcrumb>(); } SetupStorage(); return (List<RaygunBreadcrumb>) HttpContext.Current.Items[ItemsKey]; } private void SetupStorage() { if (HttpContext.Current != null && !HttpContext.Current.Items.Contains(ItemsKey)) { HttpContext.Current.Items[ItemsKey] = new List<RaygunBreadcrumb>(); } } } }
Return empty list if HttpContext.Current is null
Return empty list if HttpContext.Current is null
C#
mit
MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net
bbe17cf6eaa16b06dce1861450d63ed8f827a996
Source/MTW_AncestorSpirits/RoomRoleWorker_ShrineRoom.cs
Source/MTW_AncestorSpirits/RoomRoleWorker_ShrineRoom.cs
using RimWorld; using Verse; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { class RoomRoleWorker_ShrineRoom : RoomRoleWorker { public override float GetScore(Room room) { // I don't know if there should be some "If it's full of joy objects/work benches, *don't* classify it as // a Shrine - if you Shrine room wall gets broken down by a bug, this will probably push all the attached // rooms into the "Shrine Room" - is that a desired behaviour? Thing shrine = room.AllContainedThings.FirstOrDefault<Thing>(t => t is Building_Shrine); if (shrine == null) { return 0.0f; } else { return 9999.0f; } } } }
using RimWorld; using Verse; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { class RoomRoleWorker_ShrineRoom : RoomRoleWorker { public override float GetScore(Room room) { // I don't know if there should be some "If it's full of joy objects/work benches, *don't* classify it as // a Shrine - if you Shrine room wall gets broken down by a bug, this will probably push all the attached // rooms into the "Shrine Room" - is that a desired behaviour? var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner; if (room.AllContainedThings.Contains<Thing>(shrine)) { return 9999.0f; } else { return 0.0f; } } } }
Fix ShrineRoom to always be current spawner
Fix ShrineRoom to always be current spawner
C#
mit
MoyTW/MTW_AncestorSpirits
41b94c962a2aecb8b9a2c0a7606b1cc7c9b61a5e
EOLib/Net/Translators/PacketTranslatorContainer.cs
EOLib/Net/Translators/PacketTranslatorContainer.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EOLib.Data.Protocol; using Microsoft.Practices.Unity; namespace EOLib.Net.Translators { public class PacketTranslatorContainer : IDependencyContainer { public void RegisterDependencies(IUnityContainer container) { container.RegisterType<IPacketTranslator<IInitializationData>, InitDataTranslator>(); } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EOLib.Data.Login; using EOLib.Data.Protocol; using Microsoft.Practices.Unity; namespace EOLib.Net.Translators { public class PacketTranslatorContainer : IDependencyContainer { public void RegisterDependencies(IUnityContainer container) { container.RegisterType<IPacketTranslator<IInitializationData>, InitDataTranslator>(); container.RegisterType<IPacketTranslator<IAccountLoginData>, AccountLoginPacketTranslator>(); } } }
Add IoC registration for login data translator
Add IoC registration for login data translator
C#
mit
ethanmoffat/EndlessClient
7de732361e35815e3ff6aed2e41c96542108ce03
src/Yio/Program.cs
src/Yio/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Yio.Utilities; namespace Yio { public class Program { private static int _port { get; set; } public static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.Unicode; StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan); if (!File.Exists("appsettings.json")) { StartupUtilities.WriteFailure("configuration is missing"); Environment.Exit(1); } StartupUtilities.WriteInfo("setting port"); if(args == null || args.Length == 0) { _port = 5100; StartupUtilities.WriteSuccess("port set to " + _port + " (default)"); } else { _port = args[0] == null ? 5100 : Int32.Parse(args[0]); StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)"); } StartupUtilities.WriteInfo("starting App"); BuildWebHost(args).Run(); Console.ResetColor(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseUrls("http://0.0.0.0:" + _port.ToString() + "/") .UseStartup<Startup>() .Build(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Yio.Utilities; namespace Yio { public class Program { private static int _port { get; set; } public static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.Unicode; StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan); if (!File.Exists("appsettings.json")) { StartupUtilities.WriteFailure("configuration is missing"); Environment.Exit(1); } StartupUtilities.WriteInfo("setting port"); if(args == null || args.Length == 0) { _port = 5100; StartupUtilities.WriteSuccess("port set to " + _port + " (default)"); } else { _port = args[0] == null ? 5100 : Int32.Parse(args[0]); StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)"); } StartupUtilities.WriteInfo("starting App"); BuildWebHost().Run(); Console.ResetColor(); } public static IWebHost BuildWebHost() => WebHost.CreateDefaultBuilder() .UseUrls("http://0.0.0.0:" + _port.ToString() + "/") .UseStartup<Startup>() .Build(); } }
Fix port in arguments crashing app
Fix port in arguments crashing app
C#
mit
Zyrio/ictus,Zyrio/ictus
1a6e88d9b2919f98ba77a42d8a54be84d95c66b6
MarcelloDB/Helpers/DataHelper.cs
MarcelloDB/Helpers/DataHelper.cs
using System; namespace MarcelloDB.Helpers { internal class DataHelper { internal static void CopyData( Int64 sourceAddress, byte[] sourceData, Int64 targetAddress, byte[] targetData) { var lengthToCopy = sourceData.Length; var sourceIndex = 0; var targetIndex = 0; if (sourceAddress < targetAddress) { sourceIndex = (int)(targetAddress - sourceAddress); lengthToCopy = sourceData.Length - sourceIndex; } if (sourceAddress > targetAddress) { targetIndex = (int)(sourceAddress - targetAddress); lengthToCopy = targetData.Length - targetIndex; } //max length to copy to not overrun the target array lengthToCopy = Math.Min(lengthToCopy, targetData.Length - targetIndex); //max length to copy to not overrrude the source array lengthToCopy = Math.Min(lengthToCopy, sourceData.Length - sourceIndex); if (lengthToCopy > 0) { Array.Copy(sourceData, sourceIndex, targetData, targetIndex, lengthToCopy); } } } }
using System; namespace MarcelloDB.Helpers { internal class DataHelper { internal static void CopyData( Int64 sourceAddress, byte[] sourceData, Int64 targetAddress, byte[] targetData) { Int64 lengthToCopy = sourceData.Length; Int64 sourceIndex = 0; Int64 targetIndex = 0; if (sourceAddress < targetAddress) { sourceIndex = (targetAddress - sourceAddress); lengthToCopy = sourceData.Length - sourceIndex; } if (sourceAddress > targetAddress) { targetIndex = (sourceAddress - targetAddress); lengthToCopy = targetData.Length - targetIndex; } //max length to copy to not overrun the target array lengthToCopy = Math.Min(lengthToCopy, targetData.Length - targetIndex); //max length to copy to not overrrun the source array lengthToCopy = Math.Min(lengthToCopy, sourceData.Length - sourceIndex); if (lengthToCopy > 0) { Array.Copy(sourceData, (int)sourceIndex, targetData, (int)targetIndex, (int)lengthToCopy); } } } }
Fix integer overflow on large collection files
Fix integer overflow on large collection files
C#
mit
markmeeus/MarcelloDB
8d0017fd031473ab7df1b883d1b08a9e471bcc2a
Web/Html/Navigator.cs
Web/Html/Navigator.cs
using System.Html.Media; using System.Runtime.CompilerServices; namespace System.Html { public partial class Navigator { [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozUserMedia || navigator.msGetUserMedia)({params}, {onsuccess})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess) {} [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozUserMedia || navigator.msGetUserMedia)({params}, {onsuccess}, {onerror})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess, Action<string> onerror) {} } }
using System.Html.Media; using System.Runtime.CompilerServices; namespace System.Html { public partial class Navigator { [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia).call(navigator, {params}, {onsuccess})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess) {} [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia).call(navigator, {params}, {onsuccess}, {onerror})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess, Action<string> onerror) {} } }
Fix navigator.getUserMedia webkit(TypeError: Illegal invocation) + moz(typo)
Fix navigator.getUserMedia webkit(TypeError: Illegal invocation) + moz(typo)
C#
apache-2.0
n9/SaltarelleWeb,n9/SaltarelleWeb,Saltarelle/SaltarelleWeb,n9/SaltarelleWeb,n9/SaltarelleWeb,Saltarelle/SaltarelleWeb
c9fd13950a468d8e6b6f82343217b74d2d0ea8e1
DeviceMetadataInstallTool/Program.cs
DeviceMetadataInstallTool/Program.cs
using System; using System.IO; using System.Collections; namespace DeviceMetadataInstallTool { /// <summary> /// see https://support.microsoft.com/en-us/kb/303974 /// </summary> class MetadataFinder { public System.Collections.Generic.List<String> Files = new System.Collections.Generic.List<String>(); public void SearchDirectory(string dir) { try { foreach (var d in Directory.GetDirectories(dir)) { foreach (var f in Directory.GetFiles(d, "*.devicemetadata-ms")) { Files.Add(f); } SearchDirectory(d); } } catch (System.Exception excpt) { Console.WriteLine(excpt.Message); } } } class Program { static void Main(string[] args) { var files = new System.Collections.Generic.List<String>(); //Console.WriteLine("Args size is {0}", args.Length); if (args.Length == 0) { var assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); var finder = new MetadataFinder(); finder.SearchDirectory(assemblyDir); files = finder.Files; } else { files.AddRange(files); } var store = new Sensics.DeviceMetadataInstaller.MetadataStore(); foreach (var fn in files) { var pkg = new Sensics.DeviceMetadataInstaller.MetadataPackage(fn); Console.WriteLine("{0} - {1} - Default locale: {2}", pkg.ExperienceGUID, pkg.ModelName, pkg.DefaultLocale); store.InstallPackage(pkg); } } } }
using System; using System.IO; using System.Collections; namespace DeviceMetadataInstallTool { class Program { static void Main(string[] args) { var files = new System.Collections.Generic.List<String>(); //Console.WriteLine("Args size is {0}", args.Length); if (args.Length == 0) { var assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); files = Sensics.DeviceMetadataInstaller.Util.GetMetadataFilesRecursive(assemblyDir); } else { files.AddRange(args); } var store = new Sensics.DeviceMetadataInstaller.MetadataStore(); foreach (var fn in files) { var pkg = new Sensics.DeviceMetadataInstaller.MetadataPackage(fn); Console.WriteLine("{0} - {1} - Default locale: {2}", pkg.ExperienceGUID, pkg.ModelName, pkg.DefaultLocale); store.InstallPackage(pkg); } } } }
Use glob-recurse and fix the program when you pass it file names
Use glob-recurse and fix the program when you pass it file names
C#
apache-2.0
sensics/DeviceMetadataTools
f247d2aa216e1cf3a50aa7519eb80b3b6fbb3044
osu.Framework/Platform/Linux/LinuxGameHost.cs
osu.Framework/Platform/Linux/LinuxGameHost.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE namespace osu.Framework.Platform.Linux { using Native; public class LinuxGameHost : DesktopGameHost { internal LinuxGameHost(string gameName, bool bindIPC = false) : base(gameName, bindIPC) { Window = new LinuxGameWindow(); Window.WindowStateChanged += (sender, e) => { if (Window.WindowState != OpenTK.WindowState.Minimized) OnActivated(); else OnDeactivated(); }; Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); } protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this); public override Clipboard GetClipboard() => new LinuxClipboard(); } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Platform.Linux.Native; namespace osu.Framework.Platform.Linux { public class LinuxGameHost : DesktopGameHost { internal LinuxGameHost(string gameName, bool bindIPC = false) : base(gameName, bindIPC) { Window = new LinuxGameWindow(); Window.WindowStateChanged += (sender, e) => { if (Window.WindowState != OpenTK.WindowState.Minimized) OnActivated(); else OnDeactivated(); }; Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); } protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this); public override Clipboard GetClipboard() => new LinuxClipboard(); } }
Use more standard namespace formatting
Use more standard namespace formatting
C#
mit
smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework
f8f93d87866634a5e14c4c038001b1b112b470e5
src/OpenSage.Game/Data/Sav/GameStateMap.cs
src/OpenSage.Game/Data/Sav/GameStateMap.cs
using System.IO; using OpenSage.Network; namespace OpenSage.Data.Sav { internal static class GameStateMap { internal static void Load(SaveFileReader reader, Game game) { reader.ReadVersion(2); var mapPath1 = reader.ReadAsciiString(); var mapPath2 = reader.ReadAsciiString(); var gameType = reader.ReadEnum<GameType>(); var mapSize = reader.BeginSegment(); // TODO: Delete this temporary map when ending the game. var mapPathInSaveFolder = Path.Combine( game.ContentManager.UserMapsFileSystem.RootDirectory, mapPath1); using (var mapOutputStream = File.OpenWrite(mapPathInSaveFolder)) { reader.ReadBytesIntoStream(mapOutputStream, (int)mapSize); } reader.EndSegment(); var unknown2 = reader.ReadUInt32(); // 586 var unknown3 = reader.ReadUInt32(); // 3220 if (gameType == GameType.Skirmish) { game.SkirmishManager = new LocalSkirmishManager(game); game.SkirmishManager.Settings.Load(reader); game.SkirmishManager.Settings.MapName = mapPath1; game.SkirmishManager.StartGame(); } else { game.StartSinglePlayerGame(mapPathInSaveFolder); } } } }
using System.IO; using OpenSage.Network; namespace OpenSage.Data.Sav { internal static class GameStateMap { internal static void Load(SaveFileReader reader, Game game) { reader.ReadVersion(2); var mapPath1 = reader.ReadAsciiString(); var mapPath2 = reader.ReadAsciiString(); var gameType = reader.ReadEnum<GameType>(); var mapSize = reader.BeginSegment(); // TODO: Delete this temporary map when ending the game. var mapPathInSaveFolder = Path.Combine( game.ContentManager.UserMapsFileSystem.RootDirectory, mapPath1); using (var mapOutputStream = File.OpenWrite(mapPathInSaveFolder)) { reader.ReadBytesIntoStream(mapOutputStream, (int)mapSize); } reader.EndSegment(); var unknown2 = reader.ReadUInt32(); // 586 var unknown3 = reader.ReadUInt32(); // 3220 if (gameType == GameType.Skirmish) { game.SkirmishManager = new LocalSkirmishManager(game); game.SkirmishManager.Settings.Load(reader); game.SkirmishManager.Settings.MapName = mapPath1; game.SkirmishManager.StartGame(); } else { game.StartSinglePlayerGame(mapPath1); } } } }
Fix map path for single player maps
Fix map path for single player maps
C#
mit
feliwir/openSage,feliwir/openSage
3bd3e41661eea6e3649dca30bb7a6e3dadeafb89
Papyrus/Papyrus/Extensions/EbookExtensions.cs
Papyrus/Papyrus/Extensions/EbookExtensions.cs
namespace Papyrus { public static class EBookExtensions { } }
using System; using System.Threading.Tasks; using Windows.Storage; namespace Papyrus { public static class EBookExtensions { public static async Task<bool> VerifyMimetypeAsync(this EBook ebook) { var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype"); if (mimetypeFile == null) // Make sure file exists. return false; var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile); if (fileContents != "application/epub+zip") // Make sure file contents are correct. return false; return true; } } }
Add extension to verify mimetype.
Add extension to verify mimetype.
C#
mit
TastesLikeTurkey/Papyrus
66c96fe5001ba98bb7f47baad383a35c5bf0ff0f
src/AppGet/PackageRepository/AppGetServerClient.cs
src/AppGet/PackageRepository/AppGetServerClient.cs
using System.Collections.Generic; using System.Net; using AppGet.Http; using NLog; namespace AppGet.PackageRepository { public class AppGetServerClient : IPackageRepository { private readonly IHttpClient _httpClient; private readonly Logger _logger; private readonly HttpRequestBuilder _requestBuilder; private const string API_ROOT = "https://appget.net/api/v1/"; public AppGetServerClient(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; _logger = logger; _requestBuilder = new HttpRequestBuilder(API_ROOT); } public PackageInfo GetLatest(string name) { _logger.Info("Getting package " + name); var request = _requestBuilder.Build("packages/{package}/latest"); request.AddSegment("package", name); try { var package = _httpClient.Get<PackageInfo>(request); return package.Resource; } catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.NotFound) { return null; } throw; } } public List<PackageInfo> Search(string term) { _logger.Info("Searching for " + term); var request = _requestBuilder.Build("packages"); request.UriBuilder.SetQueryParam("q", term.Trim()); var package = _httpClient.Get<List<PackageInfo>>(request); return package.Resource; } } }
using System.Collections.Generic; using System.Net; using AppGet.Http; using NLog; namespace AppGet.PackageRepository { public class AppGetServerClient : IPackageRepository { private readonly IHttpClient _httpClient; private readonly Logger _logger; private readonly HttpRequestBuilder _requestBuilder; private const string API_ROOT = "https://appget.azurewebsites.net/v1/"; public AppGetServerClient(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; _logger = logger; _requestBuilder = new HttpRequestBuilder(API_ROOT); } public PackageInfo GetLatest(string name) { _logger.Info("Getting package " + name); var request = _requestBuilder.Build("packages/{package}/latest"); request.AddSegment("package", name); try { var package = _httpClient.Get<PackageInfo>(request); return package.Resource; } catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.NotFound) { return null; } throw; } } public List<PackageInfo> Search(string term) { _logger.Info("Searching for " + term); var request = _requestBuilder.Build("packages"); request.UriBuilder.SetQueryParam("q", term.Trim()); var package = _httpClient.Get<List<PackageInfo>>(request); return package.Resource; } } }
Use azure hosted server for now
Use azure hosted server for now
C#
apache-2.0
AppGet/AppGet
a5c96fe96e4cb4b8bc1539eee24e6f6c37fda2f4
ConsoleApps/FunWithSpikes/FunWithNewtonsoft/ListTests.cs
ConsoleApps/FunWithSpikes/FunWithNewtonsoft/ListTests.cs
using NUnit.Framework; using System.Collections.Generic; namespace FunWithNewtonsoft { [TestFixture] public class ListTests { [Test] public void Deserialize_PartialList_ReturnsList() { // Assemble string json = @" {'Number':'1','Letter':'A'}, {'Number':'2','Letter':'B'}, {'Number':'3','Letter':'C'},"; // Act List<Data> actual = null; // Assert Assert.AreEqual(1, actual[0].Number); Assert.AreEqual("A", actual[0].Letter); Assert.AreEqual(2, actual[1].Number); Assert.AreEqual("B", actual[1].Letter); Assert.AreEqual(3, actual[2].Number); Assert.AreEqual("C", actual[2].Letter); } } }
using Newtonsoft.Json; using NUnit.Framework; using System.Collections.Generic; namespace FunWithNewtonsoft { [TestFixture] public class ListTests { [Test] public void DeserializeObject_JsonList_ReturnsList() { // Assemble string json = @" [ {'Number':'1','Letter':'A'}, {'Number':'2','Letter':'B'}, {'Number':'3','Letter':'C'} ]"; // Act List<Data> actual = JsonConvert.DeserializeObject<List<Data>>(json); // Assert Assert.AreEqual(1, actual[0].Number); Assert.AreEqual("A", actual[0].Letter); Assert.AreEqual(2, actual[1].Number); Assert.AreEqual("B", actual[1].Letter); Assert.AreEqual(3, actual[2].Number); Assert.AreEqual("C", actual[2].Letter); } [Test] public void DeserializeObject_MissingSquareBracesAroundJsonList_Throws() { // Assemble string json = @" {'Number':'1','Letter':'A'}, {'Number':'2','Letter':'B'}, {'Number':'3','Letter':'C'}"; // Act Assert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<List<Data>>(json)); } [Test] public void DeserializeObject_TrailingCommaAtEndOfJsonList_ReturnsList() { // Assemble string json = @" [ {'Number':'1','Letter':'A'}, {'Number':'2','Letter':'B'}, {'Number':'3','Letter':'C'}, ]"; // Act List<Data> actual = JsonConvert.DeserializeObject<List<Data>>(json); // Assert Assert.AreEqual(1, actual[0].Number); Assert.AreEqual("A", actual[0].Letter); Assert.AreEqual(2, actual[1].Number); Assert.AreEqual("B", actual[1].Letter); Assert.AreEqual(3, actual[2].Number); Assert.AreEqual("C", actual[2].Letter); } } }
Add tests for json lists.
Add tests for json lists.
C#
mit
jquintus/spikes,jquintus/spikes,jquintus/spikes,jquintus/spikes
249b713dc3a5cdeee35cc0460ec2efbe734cad1d
GekkoAssembler.Common/Optimizers/IRMultiUnitOptimizer.cs
GekkoAssembler.Common/Optimizers/IRMultiUnitOptimizer.cs
using System.Collections.Generic; using System.Linq; using GekkoAssembler.IntermediateRepresentation; namespace GekkoAssembler.Optimizers { public class IRMultiUnitOptimizer : IOptimizer { public IRCodeBlock Optimize(IRCodeBlock block) { var units = block.Units; var newUnits = units .Select(x => x is IRCodeBlock ? Optimize(x as IRCodeBlock) : x) .SelectMany(x => x is IRMultiUnit ? (x as IRMultiUnit).Inner : (IEnumerable<IIRUnit>)new[] { x }); return new IRCodeBlock(newUnits); } } }
using System.Collections.Generic; using System.Linq; using GekkoAssembler.IntermediateRepresentation; namespace GekkoAssembler.Optimizers { public class IRMultiUnitOptimizer : IOptimizer { public IRCodeBlock Optimize(IRCodeBlock block) { var units = block.Units; var newUnits = units .SelectMany(x => x is IRMultiUnit ? (x as IRMultiUnit).Inner : (IEnumerable<IIRUnit>)new[] { x }) .Select(x => x is IRCodeBlock ? Optimize(x as IRCodeBlock) : x); return new IRCodeBlock(newUnits); } } }
Change the Order for Inlining Multi Units
Change the Order for Inlining Multi Units
C#
mit
CryZe/GekkoAssembler
d2650fc1a05e012a58a2283a59ce4dfdc6e634e3
osu.Game/Collections/DeleteCollectionDialog.cs
osu.Game/Collections/DeleteCollectionDialog.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.Sprites; using osu.Game.Overlays.Dialog; namespace osu.Game.Collections { public class DeleteCollectionDialog : PopupDialog { public DeleteCollectionDialog(BeatmapCollection collection, Action deleteAction) { HeaderText = "Confirm deletion of"; BodyText = collection.Name.Value; Icon = FontAwesome.Regular.TrashAlt; Buttons = new PopupDialogButton[] { new PopupDialogOkButton { Text = @"Yes. Go for it.", Action = deleteAction }, new PopupDialogCancelButton { Text = @"No! Abort mission!", }, }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using Humanizer; using osu.Framework.Graphics.Sprites; using osu.Game.Overlays.Dialog; namespace osu.Game.Collections { public class DeleteCollectionDialog : PopupDialog { public DeleteCollectionDialog(BeatmapCollection collection, Action deleteAction) { HeaderText = "Confirm deletion of"; BodyText = $"{collection.Name.Value} ({"beatmap".ToQuantity(collection.Beatmaps.Count)})"; Icon = FontAwesome.Regular.TrashAlt; Buttons = new PopupDialogButton[] { new PopupDialogOkButton { Text = @"Yes. Go for it.", Action = deleteAction }, new PopupDialogCancelButton { Text = @"No! Abort mission!", }, }; } } }
Add count to deletion dialog
Add count to deletion dialog
C#
mit
NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu
43c650a9430280ea48266333614b79754a5e8d2d
Assets/Scripts/Planet.cs
Assets/Scripts/Planet.cs
using UnityEngine; public class Planet : MonoBehaviour { [SerializeField] private float _radius; public float Radius { get { return _radius; } set { _radius = value; } } public float Permieter { get { return 2 * Mathf.PI * Radius; } } public void SampleOrbit2D( float angle, float distance, out Vector3 position, out Vector3 normal ) { // Polar to cartesian coordinates float x = Mathf.Cos( angle ) * distance; float y = Mathf.Sin( angle ) * distance; Vector3 dispalcement = new Vector3( x, 0, y ); Vector3 center = transform.position; position = center + dispalcement; normal = dispalcement.normalized; } }
using UnityEngine; public class Planet : MonoBehaviour { [SerializeField] private float _radius; public float Radius { get { return _radius; } set { _radius = value; } } public float Permieter { get { return 2 * Mathf.PI * Radius; } } public void SampleOrbit2D( float angle, float distance, out Vector3 position, out Vector3 normal ) { angle = angle * Mathf.Deg2Rad; // Polar to cartesian coordinates float x = Mathf.Cos( angle ) * distance; float y = Mathf.Sin( angle ) * distance; Vector3 dispalcement = new Vector3( x, 0, y ); Vector3 center = transform.position; position = center + dispalcement; normal = dispalcement.normalized; } }
Change orbit angles to degree
Change orbit angles to degree
C#
mit
dirty-casuals/LD38-A-Small-World
fde47de2a44c9becfc6ef45b56f475b0d77930b0
src/ExternalTemplates.AspNet/IGeneratorOptions.Default.cs
src/ExternalTemplates.AspNet/IGeneratorOptions.Default.cs
using System; namespace ExternalTemplates { /// <summary> /// Default generator options. /// </summary> public class GeneratorOptions : IGeneratorOptions { /// <summary> /// Gets the path relative to the web root where the templates are stored. /// Default is "/Content/templates". /// </summary> public string VirtualPath { get; set; } /// <summary> /// Gets the extension of the templates. /// Default is ".tmpl.html". /// </summary> public string Extension { get; set; } /// <summary> /// Gets the post string to add to the end of the script tag's id following its name. /// Default is "-tmpl". /// </summary> public string PostString { get; set; } } }
using System; namespace ExternalTemplates { /// <summary> /// Default generator options. /// </summary> public class GeneratorOptions : IGeneratorOptions { /// <summary> /// Gets the path relative to the web root where the templates are stored. /// Default is "/Content/templates". /// </summary> public string VirtualPath { get; set; } = "/Content/templates"; /// <summary> /// Gets the extension of the templates. /// Default is ".tmpl.html". /// </summary> public string Extension { get; set; } = ".tmpl.html"; /// <summary> /// Gets the post string to add to the end of the script tag's id following its name. /// Default is "-tmpl". /// </summary> public string PostString { get; set; } = "-tmpl"; } }
Add the defaults for GeneratorOptions
Add the defaults for GeneratorOptions
C#
mit
mrahhal/ExternalTemplates
7515dfefa45a889d7a6626cdae3ac3123b19c300
src/FluentMigrator.Runner/Generators/MySql/MySqlQuoter.cs
src/FluentMigrator.Runner/Generators/MySql/MySqlQuoter.cs
using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.MySql { public class MySqlQuoter : GenericQuoter { public override string OpenQuote { get { return "`"; } } public override string CloseQuote { get { return "`"; } } public override string QuoteValue(object value) { return base.QuoteValue(value).Replace(@"\", @"\\"); } public override string FromTimeSpan(System.TimeSpan value) { return System.String.Format("{0}{1}:{2}:{3}.{4}{0}" , ValueQuote , value.Hours + (value.Days * 24) , value.Minutes , value.Seconds , value.Milliseconds); } } }
using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.MySql { public class MySqlQuoter : GenericQuoter { public override string OpenQuote { get { return "`"; } } public override string CloseQuote { get { return "`"; } } public override string QuoteValue(object value) { return base.QuoteValue(value).Replace(@"\", @"\\"); } public override string FromTimeSpan(System.TimeSpan value) { return System.String.Format("{0}{1:00}:{2:00}:{3:00}{0}" , ValueQuote , value.Hours + (value.Days * 24) , value.Minutes , value.Seconds); } } }
Fix MySql do not support Milliseconds
Fix MySql do not support Milliseconds
C#
apache-2.0
barser/fluentmigrator,schambers/fluentmigrator,lcharlebois/fluentmigrator,amroel/fluentmigrator,mstancombe/fluentmig,mstancombe/fluentmigrator,tommarien/fluentmigrator,alphamc/fluentmigrator,amroel/fluentmigrator,KaraokeStu/fluentmigrator,bluefalcon/fluentmigrator,istaheev/fluentmigrator,lcharlebois/fluentmigrator,IRlyDontKnow/fluentmigrator,drmohundro/fluentmigrator,jogibear9988/fluentmigrator,vgrigoriu/fluentmigrator,wolfascu/fluentmigrator,drmohundro/fluentmigrator,itn3000/fluentmigrator,IRlyDontKnow/fluentmigrator,daniellee/fluentmigrator,barser/fluentmigrator,daniellee/fluentmigrator,alphamc/fluentmigrator,akema-fr/fluentmigrator,daniellee/fluentmigrator,eloekset/fluentmigrator,spaccabit/fluentmigrator,eloekset/fluentmigrator,igitur/fluentmigrator,igitur/fluentmigrator,KaraokeStu/fluentmigrator,mstancombe/fluentmig,bluefalcon/fluentmigrator,vgrigoriu/fluentmigrator,mstancombe/fluentmigrator,spaccabit/fluentmigrator,wolfascu/fluentmigrator,istaheev/fluentmigrator,MetSystem/fluentmigrator,stsrki/fluentmigrator,MetSystem/fluentmigrator,fluentmigrator/fluentmigrator,FabioNascimento/fluentmigrator,dealproc/fluentmigrator,istaheev/fluentmigrator,mstancombe/fluentmig,jogibear9988/fluentmigrator,modulexcite/fluentmigrator,akema-fr/fluentmigrator,fluentmigrator/fluentmigrator,schambers/fluentmigrator,FabioNascimento/fluentmigrator,stsrki/fluentmigrator,modulexcite/fluentmigrator,tommarien/fluentmigrator,dealproc/fluentmigrator,itn3000/fluentmigrator
a2839acd1680be52f57587aea524976fc74d9088
Dominion.Cards/Actions/Chancellor.cs
Dominion.Cards/Actions/Chancellor.cs
using System; using Dominion.Rules; using Dominion.Rules.Activities; using Dominion.Rules.CardTypes; namespace Dominion.Cards.Actions { public class Chancellor : Card, IActionCard { public Chancellor() : base(3) { } public void Play(TurnContext context) { context.MoneyToSpend += 2; context.AddEffect(new ChancellorEffect()); } public class ChancellorEffect : CardEffectBase { public override void Resolve(TurnContext context) { _activities.Add(new ChancellorActivity(context.Game.Log, context.ActivePlayer, "Do you wish to put your deck into your discard pile?")); } public class ChancellorActivity : YesNoChoiceActivity { public ChancellorActivity(IGameLog log, Player player, string message) : base(log, player, message) { } public override void Execute(bool choice) { if (choice) { Log.LogMessage("{0} put his deck in his discard pile", Player.Name); this.Player.Deck.MoveAll(this.Player.Discards); } } } } } }
using System; using Dominion.Rules; using Dominion.Rules.Activities; using Dominion.Rules.CardTypes; namespace Dominion.Cards.Actions { public class Chancellor : Card, IActionCard { public Chancellor() : base(3) { } public void Play(TurnContext context) { context.MoneyToSpend += 2; context.AddEffect(new ChancellorEffect()); } public class ChancellorEffect : CardEffectBase { public override void Resolve(TurnContext context) { if(context.ActivePlayer.Deck.CardCount > 0) _activities.Add(new ChancellorActivity(context.Game.Log, context.ActivePlayer, "Do you wish to put your deck into your discard pile?")); } public class ChancellorActivity : YesNoChoiceActivity { public ChancellorActivity(IGameLog log, Player player, string message) : base(log, player, message) { } public override void Execute(bool choice) { if (choice) { Log.LogMessage("{0} put his deck in his discard pile", Player.Name); this.Player.Deck.MoveAll(this.Player.Discards); } } } } } }
Stop chancellor from prompting the player when they have no cards in their deck.
Stop chancellor from prompting the player when they have no cards in their deck.
C#
mit
paulbatum/Dominion,paulbatum/Dominion
b1704a4c06c581a5b18126740dbe92bb018b35f2
tests/Core.UnitTests/AppSettingsConfigurationProviderTests.cs
tests/Core.UnitTests/AppSettingsConfigurationProviderTests.cs
using System; using System.Collections.Specialized; using Xunit; namespace GV.AspNet.Configuration.ConfigurationManager.UnitTests { public class AppSettingsConfigurationProviderTests { [Theory] [InlineData("Key1", "Value1")] [InlineData("Key2", "Value2")] public void LoadsKeyValuePairsFromAppSettings(string key, string value) { var appSettings = new NameValueCollection { { key, value } }; var source = new AppSettingsConfigurationProvider(appSettings, ":", string.Empty); source.Load(); string outValue; Assert.True(source.TryGet(key, out outValue)); Assert.Equal(value, outValue); } } }
using System; using System.Collections.Specialized; using Microsoft.Extensions.Configuration; using Xunit; namespace GV.AspNet.Configuration.ConfigurationManager.UnitTests { public class AppSettingsConfigurationProviderTests { public class Load { [Theory] [InlineData("", "Value")] [InlineData("Key", "Value")] public void AddsAppSettings(string key, string value) { var appSettings = new NameValueCollection { { key, value } }; var keyDelimiter = Constants.KeyDelimiter; var keyPrefix = string.Empty; var source = new AppSettingsConfigurationProvider(appSettings, keyDelimiter, keyPrefix); source.Load(); string configurationValue; Assert.True(source.TryGet(key, out configurationValue)); Assert.Equal(value, configurationValue); } [Theory] [InlineData("Parent.Key", "", "Parent.Key", "Value")] [InlineData("Parent.Key", ".", "Parent:Key", "Value")] public void ReplacesKeyDelimiter(string appSettingsKey, string keyDelimiter, string configurationKey, string value) { var appSettings = new NameValueCollection { { appSettingsKey, value } }; var keyPrefix = string.Empty; var source = new AppSettingsConfigurationProvider(appSettings, keyDelimiter, keyPrefix); source.Load(); string configurationValue; Assert.True(source.TryGet(configurationKey, out configurationValue)); Assert.Equal(value, configurationValue); } } } }
Add support for custom key delimiter
Add support for custom key delimiter
C#
mit
gusztavvargadr/aspnet-Configuration.Contrib
cfc8873ff4adf209dc26b5927561e633c229613c
tests/Bugsnag.Tests/Payload/ExceptionTests.cs
tests/Bugsnag.Tests/Payload/ExceptionTests.cs
using System.Linq; using Bugsnag.Payload; using Xunit; namespace Bugsnag.Tests.Payload { public class ExceptionTests { [Fact] public void CorrectNumberOfExceptions() { var exception = new System.Exception("oh noes!"); var exceptions = new Exceptions(exception, 5); Assert.Single(exceptions); } [Fact] public void IncludeInnerExceptions() { var innerException = new System.Exception(); var exception = new System.Exception("oh noes!", innerException); var exceptions = new Exceptions(exception, 5); Assert.Equal(2, exceptions.Count()); } } }
using System.Linq; using System.Threading.Tasks; using Bugsnag.Payload; using Xunit; namespace Bugsnag.Tests.Payload { public class ExceptionTests { [Fact] public void CorrectNumberOfExceptions() { var exception = new System.Exception("oh noes!"); var exceptions = new Exceptions(exception, 5); Assert.Single(exceptions); } [Fact] public void IncludeInnerExceptions() { var innerException = new System.Exception(); var exception = new System.Exception("oh noes!", innerException); var exceptions = new Exceptions(exception, 5); Assert.Equal(2, exceptions.Count()); } [Fact] public void HandleAggregateExceptions() { Exceptions exceptions = null; var exceptionsToThrow = new[] { new System.Exception(), new System.DllNotFoundException() }; var tasks = exceptionsToThrow.Select(e => Task.Run(() => { throw e; })).ToArray(); try { Task.WaitAll(tasks); } catch (System.Exception exception) { exceptions = new Exceptions(exception, 0); } var results = exceptions.ToArray(); Assert.Contains(results, exception => exception.ErrorClass == "System.DllNotFoundException"); Assert.Contains(results, exception => exception.ErrorClass == "System.Exception"); Assert.Contains(results, exception => exception.ErrorClass == "System.AggregateException"); } } }
Test for aggregate exception handling
Test for aggregate exception handling
C#
mit
bugsnag/bugsnag-dotnet,bugsnag/bugsnag-dotnet
be881ba9ca7261d9a4a85a95338406025f5682e5
src/Umbraco.Web/Routing/RedirectTrackingComposer.cs
src/Umbraco.Web/Routing/RedirectTrackingComposer.cs
using Umbraco.Core; using Umbraco.Core.Components; namespace Umbraco.Web.Routing { /// <summary> /// Implements an Application Event Handler for managing redirect urls tracking. /// </summary> /// <remarks> /// <para>when content is renamed or moved, we want to create a permanent 301 redirect from it's old url</para> /// <para>not managing domains because we don't know how to do it - changing domains => must create a higher level strategy using rewriting rules probably</para> /// <para>recycle bin = moving to and from does nothing: to = the node is gone, where would we redirect? from = same</para> /// </remarks> [RuntimeLevel(MinLevel = RuntimeLevel.Run)] public class RedirectTrackingComposer : ComponentComposer<RelateOnCopyComponent>, ICoreComposer { } }
using Umbraco.Core; using Umbraco.Core.Components; namespace Umbraco.Web.Routing { /// <summary> /// Implements an Application Event Handler for managing redirect urls tracking. /// </summary> /// <remarks> /// <para>when content is renamed or moved, we want to create a permanent 301 redirect from it's old url</para> /// <para>not managing domains because we don't know how to do it - changing domains => must create a higher level strategy using rewriting rules probably</para> /// <para>recycle bin = moving to and from does nothing: to = the node is gone, where would we redirect? from = same</para> /// </remarks> [RuntimeLevel(MinLevel = RuntimeLevel.Run)] public class RedirectTrackingComposer : ComponentComposer<RedirectTrackingComponent>, ICoreComposer { } }
Fix the redirect tracking composer
Fix the redirect tracking composer
C#
mit
hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,rasmuseeg/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS
047a2b289fcedd5cb481f1583be7ddafa5c9bc97
Pdf/PdfPageExtensions.cs
Pdf/PdfPageExtensions.cs
using System; using System.Collections.Generic; using System.Drawing; using PdfSharp.Pdf.Advanced; // ReSharper disable once CheckNamespace namespace PdfSharp.Pdf { /// <summary> /// Extension methods for the PdfSharp library PdfItem object. /// </summary> public static class PdfPageExtensions { /// <summary> /// Get's all of the images from the specified page. /// </summary> /// <param name="page">The page to extract or retrieve images from.</param> /// <param name="filter">An optional filter to perform additional modifications or actions on the image.</param> /// <returns>An enumeration of images contained on the page.</returns> public static IEnumerable<Image> GetImages(this PdfPage page, Func<PdfPage, int, Image, Image> filter = null) { if (page == null) throw new ArgumentNullException("item", "The provided PDF page was null."); if (filter == null) filter = (pg, idx, img) => img; int index = 0; PdfDictionary resources = page.Elements.GetDictionary("/Resources"); if (resources != null) { PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject"); if (xObjects != null) { ICollection<PdfItem> items = xObjects.Elements.Values; foreach (PdfItem item in items) { PdfReference reference = item as PdfReference; if (reference != null) { PdfDictionary xObject = reference.Value as PdfDictionary; if (xObject.IsImage()) { yield return filter.Invoke(page, index++, xObject.ToImage()); } } } } } } } }
using System; using System.Collections.Generic; using System.Drawing; using PdfSharp.Pdf.Advanced; // ReSharper disable once CheckNamespace namespace PdfSharp.Pdf { /// <summary> /// Extension methods for the PdfSharp library PdfItem object. /// </summary> public static class PdfPageExtensions { /// <summary> /// Get's all of the images from the specified page. /// </summary> /// <param name="page">The page to extract or retrieve images from.</param> /// <param name="filter">An optional filter to perform additional modifications or actions on the image.</param> /// <returns>An enumeration of images contained on the page.</returns> public static IEnumerable<Image> GetImages(this PdfPage page, Func<PdfPage, int, Image, Image> filter = null) { if (page == null) throw new ArgumentNullException("page", "The provided PDF page was null."); if (filter == null) filter = (pg, idx, img) => img; int index = 0; var resources = page.Elements.GetDictionary("/Resources"); if (resources != null) { var xObjects = resources.Elements.GetDictionary("/XObject"); if (xObjects != null) { var items = xObjects.Elements.Values; foreach (PdfItem item in items) { var reference = item as PdfReference; if (reference != null) { var xObject = reference.Value as PdfDictionary; if (xObject.IsImage()) { yield return filter.Invoke(page, index++, xObject.ToImage()); } } } } } } } }
Use var declaration. Fix ArgumentNullException parameter name.
Use var declaration. Fix ArgumentNullException parameter name.
C#
mit
gheeres/PDFSharp.Extensions
c94db0af6b58712c6deb2f9f1249e8345b60688b
Portal.CMS.Web/Areas/Admin/Views/Dashboard/_QuickAccess.cshtml
Portal.CMS.Web/Areas/Admin/Views/Dashboard/_QuickAccess.cshtml
@model Portal.CMS.Web.Areas.Admin.ViewModels.Dashboard.QuickAccessViewModel <div class="page-admin-wrapper admin-wrapper"> @foreach (var category in Model.Categories) { <a href="@category.Link" class="button @category.CssClass @(category.LaunchModal ? "launch-modal" : "")" data-toggle="popover" data-placement="top" data-trigger="click" data-title="@(!string.IsNullOrWhiteSpace(category.Link) ? category.DesktopText : "")" data-container="body"><span class="click-through"><span class="@category.Icon" style="float: left;"></span><span class="hidden-xs visible-sm visible-md visible-lg" style="float: left;">@category.DesktopText</span><span class="visible-xs hidden-sm hidden-md hidden-lg" style="float: left;">@category.MobileText</span></span></a> } @foreach (var category in Model.Categories) { <div id="popover-@category.CssClass" class="list-group" style="display: none;"> <div class="popover-menu"> @foreach (var action in category.Actions) { <a class="list-group-item @(action.LaunchModal ? "launch-modal" : "")" onclick="@action.JavaScript" href="@action.Link" data-title="@action.Text"><span class="@action.Icon"></span>@action.Text</a> } </div> </div> } </div>
@model Portal.CMS.Web.Areas.Admin.ViewModels.Dashboard.QuickAccessViewModel <div class="page-admin-wrapper admin-wrapper animated zoomInUp"> @foreach (var category in Model.Categories) { <a href="@category.Link" class="button @category.CssClass @(category.LaunchModal ? "launch-modal" : "")" data-toggle="popover" data-placement="top" data-trigger="click" data-title="@(!string.IsNullOrWhiteSpace(category.Link) ? category.DesktopText : "")" data-container="body"><span class="click-through"><span class="@category.Icon" style="float: left;"></span><span class="hidden-xs visible-sm visible-md visible-lg" style="float: left;">@category.DesktopText</span><span class="visible-xs hidden-sm hidden-md hidden-lg" style="float: left;">@category.MobileText</span></span></a> } @foreach (var category in Model.Categories) { <div id="popover-@category.CssClass" class="list-group" style="display: none;"> <div class="popover-menu"> @foreach (var action in category.Actions) { <a class="list-group-item @(action.LaunchModal ? "launch-modal" : "")" onclick="@action.JavaScript" href="@action.Link" data-title="@action.Text"><span class="@action.Icon"></span>@action.Text</a> } </div> </div> } </div>
Bring Attention to the Quick Access Panel On Page Load
Bring Attention to the Quick Access Panel On Page Load
C#
mit
tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS
45ff0924a71287acb5860084e4ffd578d9759641
XamarinApp/MyTrips/MyTrips.DataStore.Azure/Stores/TripStore.cs
XamarinApp/MyTrips/MyTrips.DataStore.Azure/Stores/TripStore.cs
using System; using MyTrips.DataObjects; using MyTrips.DataStore.Abstractions; using System.Threading.Tasks; using MyTrips.Utils; using System.Collections.Generic; namespace MyTrips.DataStore.Azure.Stores { public class TripStore : BaseStore<Trip>, ITripStore { IPhotoStore photoStore; public TripStore() { photoStore = ServiceLocator.Instance.Resolve<IPhotoStore>(); } public override async Task<IEnumerable<Trip>> GetItemsAsync(int skip = 0, int take = 100, bool forceRefresh = false) { var items = await base.GetItemsAsync(skip, take, forceRefresh); foreach (var item in items) { item.Photos = new List<Photo>(); var photos = await photoStore.GetTripPhotos(item.Id); foreach(var photo in photos) item.Photos.Add(photo); } return items; } public override async Task<Trip> GetItemAsync(string id) { var item = await base.GetItemAsync(id); if (item.Photos == null) item.Photos = new List<Photo>(); else item.Photos.Clear(); var photos = await photoStore.GetTripPhotos(item.Id); foreach(var photo in photos) item.Photos.Add(photo); return item; } } }
using System; using MyTrips.DataObjects; using MyTrips.DataStore.Abstractions; using System.Threading.Tasks; using MyTrips.Utils; using System.Collections.Generic; using System.Linq; namespace MyTrips.DataStore.Azure.Stores { public class TripStore : BaseStore<Trip>, ITripStore { IPhotoStore photoStore; public TripStore() { photoStore = ServiceLocator.Instance.Resolve<IPhotoStore>(); } public override async Task<IEnumerable<Trip>> GetItemsAsync(int skip = 0, int take = 100, bool forceRefresh = false) { var items = await base.GetItemsAsync(skip, take, forceRefresh); foreach (var item in items) { item.Photos = new List<Photo>(); var photos = await photoStore.GetTripPhotos(item.Id); foreach(var photo in photos) item.Photos.Add(photo); } return items; } public override async Task<Trip> GetItemAsync(string id) { var item = await base.GetItemAsync(id); if (item.Photos == null) item.Photos = new List<Photo>(); else item.Photos.Clear(); var photos = await photoStore.GetTripPhotos(item.Id); foreach(var photo in photos) item.Photos.Add(photo); item.Points = item.Points.OrderBy(p => p.Sequence).ToArray(); return item; } } }
Make sure we order by sequence
Make sure we order by sequence
C#
mit
Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving
a72aa1fdecb7ad4ffcbed2346ae6f7aa6c9df59d
src/VisualStudio/PackageSource/AggregatePackageSource.cs
src/VisualStudio/PackageSource/AggregatePackageSource.cs
using System.Collections.Generic; using System.Linq; namespace NuGet.VisualStudio { public static class AggregatePackageSource { public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName); public static bool IsAggregate(this PackageSource source) { return source == Instance; } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) { return Enumerable.Repeat(Instance, 1).Concat(provider.LoadPackageSources()); } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() { return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>()); } } }
using System.Collections.Generic; using System.Linq; namespace NuGet.VisualStudio { public static class AggregatePackageSource { public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName); public static bool IsAggregate(this PackageSource source) { return source == Instance; } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) { return new[] { Instance }.Concat(provider.LoadPackageSources()); } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() { return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>()); } } }
Replace Enumerable.Repeat call with an one-element array.
Replace Enumerable.Repeat call with an one-element array.
C#
apache-2.0
mdavid/nuget,mdavid/nuget
cf645e2bf87dc941dacb5b82dbe61f96802e1295
CIV/Program.cs
CIV/Program.cs
using static System.Console; using System.Linq; using CIV.Ccs; using CIV.Hml; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var hmlText = "[[ack]][[ack]][[ack]](<<ack>>tt and [[freeAll]]ff)"; var prova = HmlFacade.ParseAll(hmlText); WriteLine(prova.Check(processes["Prison"])); } } }
using static System.Console; using CIV.Ccs; using CIV.Interfaces; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var trace = CcsFacade.RandomTrace(processes["Prison"], 450); foreach (var action in trace) { WriteLine(action); } } } }
Revert "Remove RandomTrace stuff from main"
Revert "Remove RandomTrace stuff from main" This reverts commit f4533db6c2eb955d5433cf52e85d32a223a7bba8.
C#
mit
lou1306/CIV,lou1306/CIV
5a81898cc05e6b00d0f35e8d49417b448732c209
EOBot/Interpreter/States/StatementEvaluator.cs
EOBot/Interpreter/States/StatementEvaluator.cs
using EOBot.Interpreter.Extensions; using System.Collections.Generic; using System.Linq; namespace EOBot.Interpreter.States { public class StatementEvaluator : IScriptEvaluator { private readonly IEnumerable<IScriptEvaluator> _evaluators; public StatementEvaluator(IEnumerable<IScriptEvaluator> evaluators) { _evaluators = evaluators; } public bool Evaluate(ProgramState input) { while (input.Current().TokenType == BotTokenType.NewLine) input.Expect(BotTokenType.NewLine); return (Evaluate<AssignmentEvaluator>(input) || Evaluate<KeywordEvaluator>(input) || Evaluate<LabelEvaluator>(input) || Evaluate<FunctionEvaluator>(input)) && input.Expect(BotTokenType.NewLine); } private bool Evaluate<T>(ProgramState input) where T : IScriptEvaluator { return _evaluators .OfType<T>() .Single() .Evaluate(input); } } }
using EOBot.Interpreter.Extensions; using System.Collections.Generic; using System.Linq; namespace EOBot.Interpreter.States { public class StatementEvaluator : IScriptEvaluator { private readonly IEnumerable<IScriptEvaluator> _evaluators; public StatementEvaluator(IEnumerable<IScriptEvaluator> evaluators) { _evaluators = evaluators; } public bool Evaluate(ProgramState input) { while (input.Current().TokenType == BotTokenType.NewLine) input.Expect(BotTokenType.NewLine); return (Evaluate<AssignmentEvaluator>(input) || Evaluate<KeywordEvaluator>(input) || Evaluate<LabelEvaluator>(input) || Evaluate<FunctionEvaluator>(input)) && (input.Expect(BotTokenType.NewLine) || input.Expect(BotTokenType.EOF)); } private bool Evaluate<T>(ProgramState input) where T : IScriptEvaluator { return _evaluators .OfType<T>() .Single() .Evaluate(input); } } }
Allow statements to end with EOF instead of forcing a newline for every evaluated statement
Allow statements to end with EOF instead of forcing a newline for every evaluated statement
C#
mit
ethanmoffat/EndlessClient
50f8d5c6d819af00166e61fb7db0024b497eada5
src/Sharpy.Core/src/IGenerator.cs
src/Sharpy.Core/src/IGenerator.cs
namespace Sharpy.Core { /// <summary> /// <para>Represent a generator which can generate any amount of elements by invoking method <see cref="Generate" />.</para> /// </summary> /// <typeparam name="T"></typeparam> public interface IGenerator<out T> { /// <summary> /// <para>Generate next element.</para> /// </summary> /// <returns> /// A generated element. /// </returns> new T Generate(); } }
namespace Sharpy.Core { /// <summary> /// <para>Represent a generator which can generate any amount of elements by invoking method <see cref="Generate" />.</para> /// </summary> /// <typeparam name="T"></typeparam> public interface IGenerator<out T> { /// <summary> /// <para>Generate next element.</para> /// </summary> /// <returns> /// A generated element. /// </returns> T Generate(); } }
Remove new keyword from interface
Remove new keyword from interface Former-commit-id: e271328ab161d18c97babd8a011a6806ce7b1981
C#
mit
inputfalken/Sharpy
19c663da110cf62ceda4cf4df8f608c7f1917e41
osu.Game/Screens/Edit/Screens/EditorScreen.cs
osu.Game/Screens/Edit/Screens/EditorScreen.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; namespace osu.Game.Screens.Edit.Screens { public class EditorScreen : Container { public readonly Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>(); protected override Container<Drawable> Content => content; private readonly Container content; public EditorScreen() { Anchor = Anchor.Centre; Origin = Anchor.Centre; RelativeSizeAxes = Axes.Both; InternalChild = content = new Container { RelativeSizeAxes = Axes.Both }; } protected override void LoadComplete() { base.LoadComplete(); this.ScaleTo(0.75f).FadeTo(0) .Then() .ScaleTo(1f, 500, Easing.OutQuint).FadeTo(1f, 250, Easing.OutQuint); } public void Exit() { this.ScaleTo(1.25f, 500).FadeOut(250).Expire(); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; namespace osu.Game.Screens.Edit.Screens { public class EditorScreen : Container { public readonly Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>(); protected override Container<Drawable> Content => content; private readonly Container content; public EditorScreen() { Anchor = Anchor.Centre; Origin = Anchor.Centre; RelativeSizeAxes = Axes.Both; InternalChild = content = new Container { RelativeSizeAxes = Axes.Both }; } protected override void LoadComplete() { base.LoadComplete(); this.FadeTo(0) .Then() .FadeTo(1f, 250, Easing.OutQuint); } public void Exit() { this.FadeOut(250).Expire(); } } }
Remove scale effect on editor screen switches
Remove scale effect on editor screen switches
C#
mit
peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,2yangk23/osu,EVAST9919/osu,smoogipoo/osu,DrabWeb/osu,NeoAdonis/osu,ZLima12/osu,smoogipoo/osu,naoey/osu,smoogipooo/osu,johnneijzen/osu,Frontear/osuKyzer,peppy/osu,Drezi126/osu,Nabile-Rahmani/osu,peppy/osu,2yangk23/osu,peppy/osu-new,ZLima12/osu,naoey/osu,johnneijzen/osu,ppy/osu,DrabWeb/osu,NeoAdonis/osu,ppy/osu,ppy/osu,naoey/osu,DrabWeb/osu,EVAST9919/osu,smoogipoo/osu,UselessToucan/osu
bce576864407ea3507f87fee8b3e79f0d830060c
test/ConfigHelper.cs
test/ConfigHelper.cs
using System.Configuration; namespace SchemaZen.test { public class ConfigHelper { public static string TestDB { get { return ConfigurationManager.AppSettings["testdb"]; } } public static string TestSchemaDir { get { return ConfigurationManager.AppSettings["test_schema_dir"]; } } public static string SqlDbDiffPath { get { return ConfigurationManager.AppSettings["SqlDbDiffPath"]; } } } }
using System; using System.Configuration; namespace SchemaZen.test { public class ConfigHelper { public static string TestDB { get { return GetSetting("testdb"); } } public static string TestSchemaDir { get { return GetSetting("test_schema_dir"); } } public static string SqlDbDiffPath { get { return GetSetting("SqlDbDiffPath"); } } private static string GetSetting(string key) { var val = Environment.GetEnvironmentVariable(key); return val ?? ConfigurationManager.AppSettings[key]; } } }
Read environment variables for test settings.
Read environment variables for test settings. Allows me to specify a different testdb on the build server.
C#
mit
keith-hall/schemazen,Zocdoc/schemazen,sethreno/schemazen,sethreno/schemazen
c4eecf2480fa0cb1924df562024c4a3d580333de
MiX.Integrate.Shared/Entities/Messages/SendJobMessageCarrier.cs
MiX.Integrate.Shared/Entities/Messages/SendJobMessageCarrier.cs
using System; using System.Collections.Generic; using System.Text; using MiX.Integrate.Shared.Entities.Communications; namespace MiX.Integrate.Shared.Entities.Messages { public class SendJobMessageCarrier { public SendJobMessageCarrier() { } public short VehicleId { get; set; } public string Description { get; set; } public string UserDescription { get; set; } public string Body { get; set; } public DateTime? StartDate { get; set; } public DateTime? ExpiryDate { get; set; } public bool RequiresAddress { get; set; } public bool AddAddressSummary { get; set; } public bool UseFirstAddressForSummary { get; set; } public JobMessageActionNotifications NotificationSettings { get; set; } public long[] AddressList { get; set; } public CommsTransports Transport { get; set; } public bool Urgent { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using MiX.Integrate.Shared.Entities.Communications; namespace MiX.Integrate.Shared.Entities.Messages { public class SendJobMessageCarrier { public SendJobMessageCarrier() { } public short VehicleId { get; set; } public string Description { get; set; } public string UserDescription { get; set; } public string Body { get; set; } public DateTime? StartDate { get; set; } public DateTime? ExpiryDate { get; set; } public bool RequiresAddress { get; set; } public bool AddAddressSummary { get; set; } public bool UseFirstAddressForSummary { get; set; } public JobMessageActionNotifications NotificationSettings { get; set; } public int[] AddressList { get; set; } public long[] LocationList { get; set; } public CommsTransports Transport { get; set; } public bool Urgent { get; set; } } }
Add extra property to use new long Id's
FLEET-9992: Add extra property to use new long Id's
C#
mit
MiXTelematics/MiX.Integrate.Api.Client
f5c12cf18b616a76961062361dd1932f2c17d853
SpotiPeek/SpotiPeek.App/TrackModel.cs
SpotiPeek/SpotiPeek.App/TrackModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpotiPeek.App { class TrackModel { public string SongTitle; public string ArtistName; public string AlbumTitle; public string AlbumYear; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpotiPeek.App { class TrackModel { public string SongTitle; public string ArtistName; public string AlbumTitle; } }
Remove unused property from Track model
Remove unused property from Track model
C#
mit
gusper/Peekify,gusper/SpotiPeek
c2d4672b8deadc8ddfc471b31cada648cbf837ed
osu.Game/GameModes/Play/PlayMode.cs
osu.Game/GameModes/Play/PlayMode.cs
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; namespace osu.Game.GameModes.Play { public enum PlayMode { [Description(@"osu!")] Osu = 0, [Description(@"taiko")] Taiko = 1, [Description(@"catch")] Catch = 2, [Description(@"mania")] Mania = 3 } }
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; namespace osu.Game.GameModes.Play { public enum PlayMode { [Description(@"osu!")] Osu = 0, [Description(@"osu!taiko")] Taiko = 1, [Description(@"osu!catch")] Catch = 2, [Description(@"osu!mania")] Mania = 3 } }
Add osu! prefix to mode descriptions.
Add osu! prefix to mode descriptions.
C#
mit
EVAST9919/osu,peppy/osu-new,smoogipoo/osu,naoey/osu,NeoAdonis/osu,EVAST9919/osu,DrabWeb/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,DrabWeb/osu,theguii/osu,naoey/osu,UselessToucan/osu,NeoAdonis/osu,tacchinotacchi/osu,Drezi126/osu,smoogipoo/osu,2yangk23/osu,johnneijzen/osu,NotKyon/lolisu,ZLima12/osu,naoey/osu,ppy/osu,peppy/osu,nyaamara/osu,ppy/osu,2yangk23/osu,Nabile-Rahmani/osu,Frontear/osuKyzer,default0/osu,johnneijzen/osu,ZLima12/osu,UselessToucan/osu,RedNesto/osu,DrabWeb/osu,Damnae/osu,osu-RP/osu-RP
50ce4a5225e1f62c622001a02c9f66e2e86012a3
src/Runners/Giles.Runner.NUnit/NUnitRunner.cs
src/Runners/Giles.Runner.NUnit/NUnitRunner.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Giles.Core.Runners; using Giles.Core.Utility; using NUnit.Core; using NUnit.Core.Filters; namespace Giles.Runner.NUnit { public class NUnitRunner : IFrameworkRunner { IEnumerable<string> filters; public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters) { this.filters = filters; var remoteTestRunner = new RemoteTestRunner(0); var package = SetupTestPackager(assembly); remoteTestRunner.Load(package); var listener = new GilesNUnitEventListener(); remoteTestRunner.Run(listener, GetFilters()); return listener.SessionResults; } ITestFilter GetFilters() { var simpleNameFilter = new SimpleNameFilter(filters.ToArray()); return simpleNameFilter; } public IEnumerable<string> RequiredAssemblies() { return new[] { Assembly.GetAssembly(typeof(NUnitRunner)).Location, "nunit.core.dll", "nunit.core.interfaces.dll" }; } private static TestPackage SetupTestPackager(Assembly assembly) { return new TestPackage(assembly.FullName, new[] { assembly.Location }); } } }
using System.Collections.Generic; using System.Linq; using System.Reflection; using Giles.Core.Runners; using NUnit.Core; using NUnit.Core.Filters; namespace Giles.Runner.NUnit { public class NUnitRunner : IFrameworkRunner { IEnumerable<string> filters; public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters) { this.filters = filters; var remoteTestRunner = new RemoteTestRunner(0); var package = SetupTestPackager(assembly); remoteTestRunner.Load(package); var listener = new GilesNUnitEventListener(); if (filters.Count() == 0) remoteTestRunner.Run(listener); else remoteTestRunner.Run(listener, GetFilters()); return listener.SessionResults; } ITestFilter GetFilters() { var simpleNameFilter = new SimpleNameFilter(filters.ToArray()); return simpleNameFilter; } public IEnumerable<string> RequiredAssemblies() { return new[] { Assembly.GetAssembly(typeof(NUnitRunner)).Location, "nunit.core.dll", "nunit.core.interfaces.dll" }; } private static TestPackage SetupTestPackager(Assembly assembly) { return new TestPackage(assembly.FullName, new[] { assembly.Location }); } } }
Fix to not use a test filter in NUnit when no filters has been declared in Giles. This was causing NUnit to not run the tests
Fix to not use a test filter in NUnit when no filters has been declared in Giles. This was causing NUnit to not run the tests
C#
mit
michaelsync/Giles,codereflection/Giles,codereflection/Giles,codereflection/Giles,michaelsync/Giles,michaelsync/Giles,michaelsync/Giles
cfc4b118c8fb90a938c33990508f8507d97dadc8
dot10/dotNET/StringsStream.cs
dot10/dotNET/StringsStream.cs
using System.Text; using dot10.IO; namespace dot10.dotNET { /// <summary> /// Represents the #Strings stream /// </summary> public class StringsStream : DotNetStream { /// <inheritdoc/> public StringsStream(IImageStream imageStream, StreamHeader streamHeader) : base(imageStream, streamHeader) { } /// <summary> /// Read a <see cref="string"/> /// </summary> /// <param name="offset">Offset of string</param> /// <returns>The UTF-8 decoded string or null if invalid offset</returns> public string Read(uint offset) { var data = imageStream.ReadBytesUntilByte(0); if (data == null) return null; return Encoding.UTF8.GetString(data); } } }
using System.Text; using dot10.IO; namespace dot10.dotNET { /// <summary> /// Represents the #Strings stream /// </summary> public class StringsStream : DotNetStream { /// <inheritdoc/> public StringsStream(IImageStream imageStream, StreamHeader streamHeader) : base(imageStream, streamHeader) { } /// <summary> /// Read a <see cref="string"/> /// </summary> /// <param name="offset">Offset of string</param> /// <returns>The UTF-8 decoded string or null if invalid offset</returns> public string Read(uint offset) { if (offset >= imageStream.Length) return null; imageStream.Position = offset; var data = imageStream.ReadBytesUntilByte(0); if (data == null) return null; return Encoding.UTF8.GetString(data); } } }
Return null if invalid offset and seek to the offset
Return null if invalid offset and seek to the offset
C#
mit
0xd4d/dnlib,kiootic/dnlib,modulexcite/dnlib,ZixiangBoy/dnlib,picrap/dnlib,Arthur2e5/dnlib,yck1509/dnlib,ilkerhalil/dnlib,jorik041/dnlib
c1c0b9a9db1c9a35114fd0535fc49ed3b5671e9d
osu.Game/Online/Multiplayer/RoomCategory.cs
osu.Game/Online/Multiplayer/RoomCategory.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.Multiplayer { public enum RoomCategory { Normal, Spotlight } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.Multiplayer { public enum RoomCategory { Normal, Spotlight, Realtime, } }
Add realtime to room categories
Add realtime to room categories
C#
mit
peppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,smoogipooo/osu,peppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu
fb07b49b71366d8fba0bd656a7c9471bf587217e
Components/TemplateHelpers/Images/Ratio.cs
Components/TemplateHelpers/Images/Ratio.cs
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height); } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height; } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
Fix issue where ratio was always returning "1"
Fix issue where ratio was always returning "1"
C#
mit
janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent
9a7ef5cea13402ca632c4cc0b2621906273ca4fd
Stratis.Bitcoin/Features/Wallet/FeeType.cs
Stratis.Bitcoin/Features/Wallet/FeeType.cs
using System; namespace Stratis.Bitcoin.Features.Wallet { /// <summary> /// An indicator on how fast a transaction will be accepted in a block /// </summary> public enum FeeType { /// <summary> /// Slow. /// </summary> Low = 0, /// <summary> /// Avarage. /// </summary> Medium = 1, /// <summary> /// Fast. /// </summary> High = 105 } public static class FeeParser { public static FeeType Parse(string value) { if (Enum.TryParse<FeeType>(value, true, out var ret)) return ret; return FeeType.Medium; } /// <summary> /// Map a fee type to the number of confirmations /// </summary> public static int ToConfirmations(this FeeType fee) { switch (fee) { case FeeType.Low: return 50; case FeeType.Medium: return 20; case FeeType.High: return 5; } throw new WalletException("Invalid fee"); } } }
using System; namespace Stratis.Bitcoin.Features.Wallet { /// <summary> /// An indicator of how fast a transaction will be accepted in a block. /// </summary> public enum FeeType { /// <summary> /// Slow. /// </summary> Low = 0, /// <summary> /// Avarage. /// </summary> Medium = 1, /// <summary> /// Fast. /// </summary> High = 105 } public static class FeeParser { public static FeeType Parse(string value) { bool isParsed = Enum.TryParse<FeeType>(value, true, out var result); if (!isParsed) { throw new FormatException($"FeeType {value} is not a valid FeeType"); } return result; } /// <summary> /// Map a fee type to the number of confirmations /// </summary> public static int ToConfirmations(this FeeType fee) { switch (fee) { case FeeType.Low: return 50; case FeeType.Medium: return 20; case FeeType.High: return 5; } throw new WalletException("Invalid fee"); } } }
Make FeeParser throw if the fee parsed is not low, medium or high (previously defaulted to medium0
Make FeeParser throw if the fee parsed is not low, medium or high (previously defaulted to medium0
C#
mit
mikedennis/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode
62e72aa2008e4cbe2c62817e1d5e835150e6e74d
Infusion.EngineScripts/Scripts/ScriptEngine.cs
Infusion.EngineScripts/Scripts/ScriptEngine.cs
using System; using System.Threading; using System.Threading.Tasks; namespace Infusion.EngineScripts { public sealed class ScriptEngine { private readonly IScriptEngine[] engines; private string scriptRootPath; public ScriptEngine(params IScriptEngine[] engines) { this.engines = engines; } public string ScriptRootPath { get => scriptRootPath; set { scriptRootPath = value; ForeachEngine(engine => engine.ScriptRootPath = value); } } public async Task ExecuteScript(string scriptPath, CancellationTokenSource cancellationTokenSource) { await ForeachEngineAsync(engine => engine.ExecuteScript(scriptPath, cancellationTokenSource)); } public void Reset() => ForeachEngine(engine => engine.Reset()); private void ForeachEngine(Action<IScriptEngine> engineAction) { foreach (var engine in engines) engineAction(engine); } private async Task ForeachEngineAsync(Func<IScriptEngine, Task> engineAction) { foreach (var engine in engines) await engineAction(engine); } } }
using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Infusion.EngineScripts { public sealed class ScriptEngine { private readonly IScriptEngine[] engines; private string scriptRootPath; public ScriptEngine(params IScriptEngine[] engines) { this.engines = engines; } public string ScriptRootPath { get => scriptRootPath; set { scriptRootPath = value; ForeachEngine(engine => engine.ScriptRootPath = value); } } public Task ExecuteInitialScript(string scriptPath, CancellationTokenSource cancellationTokenSource) { var currentRoot = Path.GetDirectoryName(scriptPath); Directory.SetCurrentDirectory(currentRoot); ScriptRootPath = currentRoot; return ExecuteScript(scriptPath, cancellationTokenSource); } public async Task ExecuteScript(string scriptPath, CancellationTokenSource cancellationTokenSource) { if (!File.Exists(scriptPath)) throw new FileNotFoundException($"Script file not found: {scriptPath}", scriptPath); await ForeachEngineAsync(engine => engine.ExecuteScript(scriptPath, cancellationTokenSource)); } public void Reset() => ForeachEngine(engine => engine.Reset()); private void ForeachEngine(Action<IScriptEngine> engineAction) { foreach (var engine in engines) engineAction(engine); } private async Task ForeachEngineAsync(Func<IScriptEngine, Task> engineAction) { foreach (var engine in engines) await engineAction(engine); } } }
Set current directory for initial script.
Set current directory for initial script.
C#
mit
uoinfusion/Infusion
56578d797aa35b96ee1fe72400b52a9374e7871c
LazyLibrary/Storage/Memory/MemoryRepository.cs
LazyLibrary/Storage/Memory/MemoryRepository.cs
using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace LazyLibrary.Storage.Memory { internal class MemoryRepository<T> : IRepository<T> where T : IStorable { private List<T> repository = new List<T>(); public T GetById(int id) { return this.repository.Where(x => x.Id == id).SingleOrDefault(); } public IQueryable<T> Get(System.Func<T, bool> exp = null) { return exp != null ? repository.Where(exp).AsQueryable<T>() : repository.AsQueryable<T>(); } public void Upsert(T item) { var obj = GetById(item.Id); if (obj != null) { // Update this.repository.Remove(obj); this.repository.Add(item); } else { // Insert var nextId = this.repository.Any() ? this.repository.Max(x => x.Id) + 1 : 1; item.Id = nextId; this.repository.Add(item); } } public void Delete(T item) { var obj = GetById(item.Id); this.repository.Remove(obj); } } }
using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace LazyLibrary.Storage.Memory { internal class MemoryRepository<T> : IRepository<T> where T : IStorable { private List<T> repository = new List<T>(); public T GetById(int id) { return this.repository.SingleOrDefault(x => x.Id == id); } public IQueryable<T> Get(System.Func<T, bool> exp = null) { return exp != null ? repository.Where(exp).AsQueryable<T>() : repository.AsQueryable<T>(); } public void Upsert(T item) { if (repository.Contains(item)) { // Update var obj = repository.Single(x => x.Equals(item)); this.repository.Remove(obj); this.repository.Add(item); } else { // Insert var nextId = this.repository.Any() ? this.repository.Max(x => x.Id) + 1 : 1; item.Id = nextId; this.repository.Add(item); } } public void Delete(T item) { var obj = GetById(item.Id); this.repository.Remove(obj); } } }
Check for objects existing using their equals operation rather than Ids
Check for objects existing using their equals operation rather than Ids
C#
mit
TheEadie/LazyStorage,TheEadie/LazyStorage,TheEadie/LazyLibrary
7d107e726bce4abe72923291350f054a2e04f21a
TestServices/ElectricBlobs/Shark/WorkerRole.cs
TestServices/ElectricBlobs/Shark/WorkerRole.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Diagnostics; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.Storage; using Microsoft.Experimental.Azure.Spark; using System.Collections.Immutable; using System.IO; using Microsoft.Experimental.Azure.CommonTestUtilities; namespace Shark { public class WorkerRole : SharkNodeBase { protected override ImmutableDictionary<string, string> GetHadoopConfigProperties() { return WasbConfiguration.GetWasbConfigKeys(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Diagnostics; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.Storage; using Microsoft.Experimental.Azure.Spark; using System.Collections.Immutable; using System.IO; using Microsoft.Experimental.Azure.CommonTestUtilities; namespace Shark { public class WorkerRole : SharkNodeBase { protected override ImmutableDictionary<string, string> GetHadoopConfigProperties() { var rootFs = String.Format("wasb://shark@{0}.blob.core.windows.net", WasbConfiguration.ReadWasbAccountsFile().First()); return WasbConfiguration.GetWasbConfigKeys() .Add("hive.exec.scratchdir", rootFs + "/scratch") .Add("hive.metastore.warehouse.dir", rootFs + "/warehouse"); } } }
Put the scratch and warehouse directories up on WASB in the Shark test service. This gets CTAS to work.
Put the scratch and warehouse directories up on WASB in the Shark test service. This gets CTAS to work.
C#
mit
mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee
6a10ff93af584050988f69b5e069839474639e3e
oberon0/Expressions/Arithmetic/SubExpression.cs
oberon0/Expressions/Arithmetic/SubExpression.cs
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using Oberon0.Compiler.Definitions; using Oberon0.Compiler.Solver; namespace Oberon0.Compiler.Expressions.Arithmetic { [Export(typeof(ICalculatable))] class SubExpression: BinaryExpression, ICalculatable { public SubExpression() { Operator = TokenType.Sub; } public override Expression Calc(Block block) { if (this.BinaryConstChecker(block) == null) { return null; } // 1. Easy as int var lhi = (ConstantExpression)LeftHandSide; var rhi = (ConstantExpression)RightHandSide; if (rhi.BaseType == lhi.BaseType && lhi.BaseType == BaseType.IntType) { return new ConstantIntExpression(lhi.ToInt32() - rhi.ToInt32()); } // at least one of them is double return new ConstantDoubleExpression(lhi.ToDouble() - lhi.ToDouble()); } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using Oberon0.Compiler.Definitions; using Oberon0.Compiler.Solver; namespace Oberon0.Compiler.Expressions.Arithmetic { [Export(typeof(ICalculatable))] class SubExpression: BinaryExpression, ICalculatable { public SubExpression() { Operator = TokenType.Sub; } public override Expression Calc(Block block) { if (this.BinaryConstChecker(block) == null) { return null; } // 1. Easy as int var leftHandSide = (ConstantExpression)LeftHandSide; var rightHandSide = (ConstantExpression)RightHandSide; if (rightHandSide.BaseType == leftHandSide.BaseType && leftHandSide.BaseType == BaseType.IntType) { return new ConstantIntExpression(leftHandSide.ToInt32() - rightHandSide.ToInt32()); } // at least one of them is double return new ConstantDoubleExpression(leftHandSide.ToDouble() - rightHandSide.ToDouble()); } } }
Fix sonarqube markup that sub has lhs and rhs identical
Fix sonarqube markup that sub has lhs and rhs identical
C#
mit
steven-r/Oberon0Compiler
e23b52d59ff6323e7aae7a1948c05bb57f425c2a
osu.Framework.Benchmarks/BenchmarkBindableInstantiation.cs
osu.Framework.Benchmarks/BenchmarkBindableInstantiation.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { public class BenchmarkBindableInstantiation { [Benchmark(Baseline = true)] public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy(); [Benchmark] public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy(); private class BindableOld<T> : Bindable<T> { public BindableOld(T defaultValue = default) : base(defaultValue) { } protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { [MemoryDiagnoser] public class BenchmarkBindableInstantiation { [Benchmark] public Bindable<int> Instantiate() => new Bindable<int>(); [Benchmark] public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy(); [Benchmark(Baseline = true)] public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy(); private class BindableOld<T> : Bindable<T> { public BindableOld(T defaultValue = default) : base(defaultValue) { } protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value); } } }
Add basic bindable instantiation benchmark
Add basic bindable instantiation benchmark
C#
mit
ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework
c7cf8a55b8964d2671d8e84a9474142bd247625f
src/dotnet/commands/dotnet-nuget/Program.cs
src/dotnet/commands/dotnet-nuget/Program.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.InternalAbstractions; using Microsoft.DotNet.Tools; namespace Microsoft.DotNet.Tools.NuGet { public class NuGetCommand { public static int Run(string[] args) { return Run(args, new NuGetCommandRunner()); } public static int Run(string[] args, ICommandRunner nugetCommandRunner) { DebugHelper.HandleDebugSwitch(ref args); if (nugetCommandRunner == null) { throw new ArgumentNullException(nameof(nugetCommandRunner)); } return nugetCommandRunner.Run(args); } private class NuGetCommandRunner : ICommandRunner { public int Run(string[] args) { var nugetApp = new NuGetForwardingApp(args); return nugetApp.Execute(); } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.InternalAbstractions; using Microsoft.DotNet.Tools; namespace Microsoft.DotNet.Tools.NuGet { public class NuGetCommand { public static int Run(string[] args) { return Run(args, new NuGetCommandRunner()); } public static int Run(string[] args, ICommandRunner nugetCommandRunner) { DebugHelper.HandleDebugSwitch(ref args); if (nugetCommandRunner == null) { throw new ArgumentNullException(nameof(nugetCommandRunner)); } return nugetCommandRunner.Run(args); } private class NuGetCommandRunner : ICommandRunner { public int Run(string[] args) { var nugetApp = new NuGetForwardingApp(args); nugetApp.WithEnvironmentVariable("DOTNET_HOST_PATH", GetDotnetPath()); return nugetApp.Execute(); } } private static string GetDotnetPath() { return new Muxer().MuxerPath; } } }
Add DOTNET_HOST_PATH for dotnet nuget commands
Add DOTNET_HOST_PATH for dotnet nuget commands
C#
mit
dasMulli/cli,livarcocc/cli-1,johnbeisner/cli,dasMulli/cli,johnbeisner/cli,dasMulli/cli,johnbeisner/cli,livarcocc/cli-1,livarcocc/cli-1
38cdb6690dc8bfa70bda3ba19b092ad58d449cb3
src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishWindow.cs
src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishWindow.cs
using UnityEditor; using UnityEngine; namespace GitHub.Unity { public class PublishWindow : EditorWindow { private const string PublishTitle = "Publish this repository to GitHub"; private string repoName = ""; private string repoDescription = ""; private bool togglePrivate = false; static void Init() { PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow)); window.Show(); } void OnGUI() { GUILayout.Label(PublishTitle, EditorStyles.boldLabel); GUILayout.Space(5); repoName = EditorGUILayout.TextField("Name", repoName); repoDescription = EditorGUILayout.TextField("Description", repoDescription); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private"); } GUILayout.EndHorizontal(); GUILayout.Space(5); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.Button("Create"); } GUILayout.EndHorizontal(); } } }
using UnityEditor; using UnityEngine; namespace GitHub.Unity { public class PublishWindow : EditorWindow { private const string PublishTitle = "Publish this repository to GitHub"; private string repoName = ""; private string repoDescription = ""; private int selectedOrg = 0; private bool togglePrivate = false; private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" }; static void Init() { PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow)); window.Show(); } void OnGUI() { GUILayout.Label(PublishTitle, EditorStyles.boldLabel); GUILayout.Space(5); repoName = EditorGUILayout.TextField("Name", repoName); repoDescription = EditorGUILayout.TextField("Description", repoDescription); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private"); } GUILayout.EndHorizontal(); selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs); GUILayout.Space(5); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.Button("Create"); } GUILayout.EndHorizontal(); } } }
Add a dropdown for selecting organizations
Add a dropdown for selecting organizations
C#
mit
github-for-unity/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity,mpOzelot/Unity
7fbeb9ecc7a78fed1ef88d45b42eed54d13a19d7
osu.Game.Tournament.Tests/Screens/TestSceneGameplayScreen.cs
osu.Game.Tournament.Tests/Screens/TestSceneGameplayScreen.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Gameplay; using osu.Game.Tournament.Screens.Gameplay.Components; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneGameplayScreen : TournamentTestScene { [Cached] private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f }; [BackgroundDependencyLoader] private void load() { Add(new GameplayScreen()); Add(chat); } [Test] public void TestWarmup() { checkScoreVisibility(false); toggleWarmup(); checkScoreVisibility(true); toggleWarmup(); checkScoreVisibility(false); } private void checkScoreVisibility(bool visible) => AddUntilStep($"scores {(visible ? "shown" : "hidden")}", () => this.ChildrenOfType<TeamScore>().All(score => score.Alpha == (visible ? 1 : 0))); private void toggleWarmup() => AddStep("toggle warmup", () => this.ChildrenOfType<TourneyButton>().First().TriggerClick()); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Tournament.Components; using osu.Game.Tournament.IPC; using osu.Game.Tournament.Screens.Gameplay; using osu.Game.Tournament.Screens.Gameplay.Components; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneGameplayScreen : TournamentTestScene { [Cached] private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f }; [Test] public void TestStartupState([Values] TourneyState state) { AddStep("set state", () => IPCInfo.State.Value = state); createScreen(); } [Test] public void TestWarmup() { createScreen(); checkScoreVisibility(false); toggleWarmup(); checkScoreVisibility(true); toggleWarmup(); checkScoreVisibility(false); } private void createScreen() { AddStep("setup screen", () => { Remove(chat); Children = new Drawable[] { new GameplayScreen(), chat, }; }); } private void checkScoreVisibility(bool visible) => AddUntilStep($"scores {(visible ? "shown" : "hidden")}", () => this.ChildrenOfType<TeamScore>().All(score => score.Alpha == (visible ? 1 : 0))); private void toggleWarmup() => AddStep("toggle warmup", () => this.ChildrenOfType<TourneyButton>().First().TriggerClick()); } }
Add failing test coverage for tournament startup states
Add failing test coverage for tournament startup states
C#
mit
smoogipoo/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,smoogipoo/osu
541512b26445bcf02ecc04b57b1886ddf4bffb6d
source/Calamari/Integration/Substitutions/FileSubstituter.cs
source/Calamari/Integration/Substitutions/FileSubstituter.cs
using System; using System.IO; using System.Text; using Calamari.Deployment; using Calamari.Integration.FileSystem; using Octostache; namespace Calamari.Integration.Substitutions { public class FileSubstituter : IFileSubstituter { readonly ICalamariFileSystem fileSystem; public FileSubstituter(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; } public void PerformSubstitution(string sourceFile, VariableDictionary variables) { PerformSubstitution(sourceFile, variables, sourceFile); } public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile) { var source = fileSystem.ReadFile(sourceFile); var encoding = GetEncoding(sourceFile, variables); var result = variables.Evaluate(source); fileSystem.OverwriteFile(targetFile, result, encoding); } private Encoding GetEncoding(string sourceFile, VariableDictionary variables) { var requestedEncoding = variables.Get(SpecialVariables.Package.SubstituteInFilesOutputEncoding); if (requestedEncoding == null) { return fileSystem.GetFileEncoding(sourceFile); } try { return Encoding.GetEncoding(requestedEncoding); } catch (ArgumentException) { return Encoding.GetEncoding(sourceFile); } } } }
using System; using System.IO; using System.Text; using Calamari.Deployment; using Calamari.Integration.FileSystem; using Octostache; namespace Calamari.Integration.Substitutions { public class FileSubstituter : IFileSubstituter { readonly ICalamariFileSystem fileSystem; public FileSubstituter(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; } public void PerformSubstitution(string sourceFile, VariableDictionary variables) { PerformSubstitution(sourceFile, variables, sourceFile); } public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile) { var source = fileSystem.ReadFile(sourceFile); var encoding = GetEncoding(sourceFile, variables); var result = variables.Evaluate(source); fileSystem.OverwriteFile(targetFile, result, encoding); } private Encoding GetEncoding(string sourceFile, VariableDictionary variables) { var requestedEncoding = variables.Get(SpecialVariables.Package.SubstituteInFilesOutputEncoding); if (requestedEncoding == null) { return fileSystem.GetFileEncoding(sourceFile); } try { return Encoding.GetEncoding(requestedEncoding); } catch (ArgumentException) { return fileSystem.GetFileEncoding(sourceFile); } } } }
Use existing file encoding if provided override is invalid
Use existing file encoding if provided override is invalid
C#
apache-2.0
allansson/Calamari,allansson/Calamari
0e7bb8b42f0d903a67f1121d09aeb14352c8a159
src/NQuery/Optimization/Condition.cs
src/NQuery/Optimization/Condition.cs
using System; using System.Collections.Generic; using System.Linq; using NQuery.Binding; namespace NQuery.Optimization { internal static class Condition { public static BoundExpression And(BoundExpression left, BoundExpression right) { if (left == null) return right; if (right == null) return left; var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type); return new BoundBinaryExpression(left, result, right); } public static BoundExpression And(IEnumerable<BoundExpression> conditions) { return conditions.Aggregate<BoundExpression, BoundExpression>(null, (c, n) => c == null ? n : And(c, n)); } public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression) { var stack = new Stack<BoundExpression>(); stack.Push(expression); while (stack.Count > 0) { var current = stack.Pop(); var binary = current as BoundBinaryExpression; if (binary != null && binary.OperatorKind == BinaryOperatorKind.LogicalAnd) { stack.Push(binary.Left); stack.Push(binary.Right); } else { yield return binary; } } } public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots) { var finder = new ValueSlotDependencyFinder(); finder.VisitExpression(expression); return finder.ValueSlots.Overlaps(valueSlots); } } }
using System; using System.Collections.Generic; using System.Linq; using NQuery.Binding; namespace NQuery.Optimization { internal static class Condition { public static BoundExpression And(BoundExpression left, BoundExpression right) { if (left == null) return right; if (right == null) return left; var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type); return new BoundBinaryExpression(left, result, right); } public static BoundExpression And(IEnumerable<BoundExpression> conditions) { return conditions.Aggregate<BoundExpression, BoundExpression>(null, (c, n) => c == null ? n : And(c, n)); } public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression) { var stack = new Stack<BoundExpression>(); stack.Push(expression); while (stack.Count > 0) { var current = stack.Pop(); var binary = current as BoundBinaryExpression; if (binary != null && binary.OperatorKind == BinaryOperatorKind.LogicalAnd) { stack.Push(binary.Left); stack.Push(binary.Right); } else { yield return current; } } } public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots) { var finder = new ValueSlotDependencyFinder(); finder.VisitExpression(expression); return finder.ValueSlots.Overlaps(valueSlots); } } }
Fix bug when splitting conjunctions
Fix bug when splitting conjunctions
C#
mit
terrajobst/nquery-vnext
b3f1c92f68f18add95d8ea034b82f7981e90d6aa
src/UserInteraction/Core/ProgressHelper.cs
src/UserInteraction/Core/ProgressHelper.cs
using Cirrious.CrossCore.Core; using System; using System.Threading.Tasks; namespace codestuffers.MvvmCrossPlugins.UserInteraction { /// <summary> /// Helper class that executes a task with a progress bar /// </summary> public class ProgressHelper { private readonly IMvxMainThreadDispatcher _dispatcher; public ProgressHelper(IMvxMainThreadDispatcher dispatcher) { _dispatcher = dispatcher; } /// <summary> /// Setup the execution of the task with a progress indicator /// </summary> /// <typeparam name="T">Type of task return value</typeparam> /// <param name="task">Task that is executing</param> /// <param name="onCompletion">Action that will be executed when the task is complete</param> /// <param name="startProgressAction">Action that will show the progress indicator</param> /// <param name="stopProgressAction">Action that will hide the progress indicator</param> public void SetupTask<T>(Task<T> task, Action<Task<T>> onCompletion, Action startProgressAction, Action stopProgressAction) { _dispatcher.RequestMainThreadAction(startProgressAction); task.ContinueWith(x => { onCompletion(task); _dispatcher.RequestMainThreadAction(stopProgressAction); }); } } }
using Cirrious.CrossCore.Core; using System; using System.Threading.Tasks; namespace codestuffers.MvvmCrossPlugins.UserInteraction { /// <summary> /// Helper class that executes a task with a progress bar /// </summary> public class ProgressHelper { private readonly IMvxMainThreadDispatcher _dispatcher; private int _progressIndicatorCount; public ProgressHelper(IMvxMainThreadDispatcher dispatcher) { _dispatcher = dispatcher; } /// <summary> /// Setup the execution of the task with a progress indicator /// </summary> /// <typeparam name="T">Type of task return value</typeparam> /// <param name="task">Task that is executing</param> /// <param name="onCompletion">Action that will be executed when the task is complete</param> /// <param name="startProgressAction">Action that will show the progress indicator</param> /// <param name="stopProgressAction">Action that will hide the progress indicator</param> public void SetupTask<T>(Task<T> task, Action<Task<T>> onCompletion, Action startProgressAction, Action stopProgressAction) { _progressIndicatorCount++; _dispatcher.RequestMainThreadAction(startProgressAction); task.ContinueWith(x => { onCompletion(task); if (--_progressIndicatorCount == 0) { _dispatcher.RequestMainThreadAction(stopProgressAction); } }); } } }
Modify progress helper so that activity indicator stops after last call ends
Modify progress helper so that activity indicator stops after last call ends
C#
mit
codestuffers/MvvmCrossPlugins
ccd9726170370faa0a0dd531fdcb6949ef59f4ba
SteamAccountSwitcher/Options.xaml.cs
SteamAccountSwitcher/Options.xaml.cs
#region using System.Windows; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for Options.xaml /// </summary> public partial class Options : Window { public Options() { InitializeComponent(); } private void btnOK_Click(object sender, RoutedEventArgs e) { Settings.Default.Save(); DialogResult = true; } private void btnCancel_Click(object sender, RoutedEventArgs e) { Settings.Default.Reload(); DialogResult = true; } } }
#region using System.Windows; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for Options.xaml /// </summary> public partial class Options : Window { public Options() { InitializeComponent(); Settings.Default.Save(); } private void btnOK_Click(object sender, RoutedEventArgs e) { Settings.Default.Save(); DialogResult = true; } private void btnCancel_Click(object sender, RoutedEventArgs e) { Settings.Default.Reload(); DialogResult = true; } } }
Fix settings not saving when opening "Options"
Fix settings not saving when opening "Options"
C#
mit
danielchalmers/SteamAccountSwitcher
6d33a867a82ca8811a562ee4c59804bdb8ddee03
Tests/GeneratorAPI/GeneratorTests.cs
Tests/GeneratorAPI/GeneratorTests.cs
using GeneratorAPI; using NUnit.Framework; using NUnit.Framework.Internal; namespace Tests.GeneratorAPI { [TestFixture] internal class GeneratorTests { [SetUp] public void Initiate() { _generator = new Generator<Randomizer>(new Randomizer(Seed)); } [TearDown] public void Dispose() { _generator = null; } private Generator<Randomizer> _generator; private const int Seed = 100; [Test( Author = "Robert", Description = "Checks that the result from Generate is not null" )] public void Test() { var result = _generator.Generate(randomizer => randomizer.GetString()); Assert.IsNotNull(result); } [Test( Author = "Robert", Description = "Checks that provider is assigned in the constructor." )] public void Test_Provider_Is_not_Null() { Assert.IsNotNull(_generator); } } }
using System; using GeneratorAPI; using NUnit.Framework; using NUnit.Framework.Internal; namespace Tests.GeneratorAPI { [TestFixture] internal class GeneratorTests { [SetUp] public void Initiate() { _generator = new Generator<Randomizer>(new Randomizer(Seed)); } [TearDown] public void Dispose() { _generator = null; } private Generator<Randomizer> _generator; private const int Seed = 100; [Test( Author = "Robert", Description = "Check that constructor throws exception if argument is null" )] public void Constructor_Null_Argument() { Assert.Throws<ArgumentNullException>(() => new Generator<Randomizer>(null)); } [Test( Author = "Robert", Description = "Checks that the result from Generate is not null" )] public void Generate_Does_Not_Return_With_Valid_Arg() { var result = _generator.Generate(randomizer => randomizer.GetString()); Assert.IsNotNull(result); } [Test( Author = "Robert", Description = "Checks that an exception is thrown when generate argument is null" )] public void Generate_With_Null() { Assert.Throws<ArgumentNullException>(() => _generator.Generate<string>(randomizer => null)); } [Test( Author = "Robert", Description = "Checks that provider is assigned in the constructor." )] public void Provider_Is_not_Null() { var result = _generator.Provider; Assert.IsNotNull(result); } } }
Add tests for null checking
Add tests for null checking Former-commit-id: 093d57674ed09329af065f5df3615d2d2c511f8f
C#
mit
inputfalken/Sharpy
619977a0e745a8d237bcccbe87b67db1d4875859
src/Glimpse.Server/Configuration/DefaultMetadataProvider.cs
src/Glimpse.Server/Configuration/DefaultMetadataProvider.cs
using System.Collections.Generic; using System.Linq; using Glimpse.Server.Internal; using Glimpse.Internal.Extensions; using Microsoft.AspNet.Http; using Microsoft.Extensions.OptionsModel; namespace Glimpse.Server.Configuration { public class DefaultMetadataProvider : IMetadataProvider { private readonly IResourceManager _resourceManager; private readonly IHttpContextAccessor _httpContextAccessor; private readonly GlimpseServerOptions _serverOptions; private Metadata _metadata; public DefaultMetadataProvider(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor, IOptions<GlimpseServerOptions> serverOptions) { _resourceManager = resourceManager; _httpContextAccessor = httpContextAccessor; _serverOptions = serverOptions.Value; } public Metadata BuildInstance() { if (_metadata != null) return _metadata; var request = _httpContextAccessor.HttpContext.Request; var baseUrl = $"{request.Scheme}://{request.Host}/{_serverOptions.BasePath}/"; IDictionary<string, string> resources = _resourceManager.RegisteredUris.ToDictionary(kvp => kvp.Key.KebabCase(), kvp => $"{baseUrl}{kvp.Key}/{kvp.Value}"); if (_serverOptions.OverrideResources != null) _serverOptions.OverrideResources(resources); return new Metadata(resources); } } }
using System.Collections.Generic; using System.Linq; using Glimpse.Server.Internal; using Glimpse.Internal.Extensions; using Microsoft.AspNet.Http; using Microsoft.Extensions.OptionsModel; namespace Glimpse.Server.Configuration { public class DefaultMetadataProvider : IMetadataProvider { private readonly IResourceManager _resourceManager; private readonly IHttpContextAccessor _httpContextAccessor; private readonly GlimpseServerOptions _serverOptions; private Metadata _metadata; public DefaultMetadataProvider(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor, IOptions<GlimpseServerOptions> serverOptions) { _resourceManager = resourceManager; _httpContextAccessor = httpContextAccessor; _serverOptions = serverOptions.Value; } public Metadata BuildInstance() { if (_metadata != null) return _metadata; var request = _httpContextAccessor.HttpContext.Request; var baseUrl = $"{request.Scheme}://{request.Host}/{_serverOptions.BasePath}/"; var resources = _resourceManager.RegisteredUris.ToDictionary(kvp => kvp.Key.KebabCase(), kvp => $"{baseUrl}{kvp.Key}/{kvp.Value}"); if (_serverOptions.OverrideResources != null) _serverOptions.OverrideResources(resources); _metadata = new Metadata(resources); return _metadata; } } }
Make sure metadata is set before being returned
Make sure metadata is set before being returned
C#
mit
Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype
90fdb46611e69f97f0e72690ab5749d353da3828
SolrNet.Cloud.Tests/UnityTests.cs
SolrNet.Cloud.Tests/UnityTests.cs
using Xunit; using Unity.SolrNetCloudIntegration; using Unity; namespace SolrNet.Cloud.Tests { public class UnityTests { private IUnityContainer Setup() { return new SolrNetContainerConfiguration().ConfigureContainer( new FakeProvider(), new UnityContainer()); } [Fact] public void ShouldResolveBasicOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrBasicOperations<FakeEntity>>()); } [Fact] public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>()); } [Fact] public void ShouldResolveOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrOperations<FakeEntity>>()); } [Fact] public void ShouldResolveReadOnlyOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>()); } } }
using Xunit; using Unity.SolrNetCloudIntegration; using Unity; namespace SolrNet.Cloud.Tests { public class UnityTests { private IUnityContainer Setup() { return new SolrNetContainerConfiguration().ConfigureContainer( new FakeProvider(), new UnityContainer()); } [Fact] public void ShouldResolveBasicOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrBasicOperations<FakeEntity>>()); } [Fact] public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>()); } [Fact] public void ShouldResolveOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrOperations<FakeEntity>>()); } [Fact] public void ShouldResolveReadOnlyOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>()); } [Fact] public void ShouldResolveIOperations () { using (var container = new UnityContainer()) { var cont = new Unity.SolrNetCloudIntegration.SolrNetContainerConfiguration().ConfigureContainer(new FakeProvider(), container); var obj = cont.Resolve<ISolrOperations<Camera>>(); } } public class Camera { [Attributes.SolrField("Name")] public string Name { get; set; } [Attributes.SolrField("UID")] public int UID { get; set; } [Attributes.SolrField("id")] public string Id { get; set; } } } }
Add test trying to recreate the issue
Add test trying to recreate the issue
C#
apache-2.0
SolrNet/SolrNet,mausch/SolrNet,SolrNet/SolrNet,mausch/SolrNet,mausch/SolrNet
1ceff6ebed4a72179da347b3769616fa4f04984e
VersionOne.ServerConnector/EntityFactory.cs
VersionOne.ServerConnector/EntityFactory.cs
using System; using System.Collections.Generic; using System.Linq; using VersionOne.SDK.APIClient; namespace VersionOne.ServerConnector { // TODO extract interface and inject into VersionOneProcessor internal class EntityFactory { private readonly IMetaModel metaModel; private readonly IServices services; private readonly IEnumerable<AttributeInfo> attributesToQuery; internal EntityFactory(IMetaModel metaModel, IServices services, IEnumerable<AttributeInfo> attributesToQuery) { this.metaModel = metaModel; this.services = services; this.attributesToQuery = attributesToQuery; } internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) { var assetType = metaModel.GetAssetType(assetTypeName); var asset = services.New(assetType, Oid.Null); foreach (var attributeValue in attributeValues) { if(attributeValue is SingleAttributeValue) { asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value); } else if(attributeValue is MultipleAttributeValue) { var values = ((MultipleAttributeValue) attributeValue).Values; var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name); foreach (var value in values) { asset.AddAttributeValue(attributeDefinition, value); } } else { throw new NotSupportedException("Unknown Attribute Value type."); } } foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) { asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr)); } services.Save(asset); return asset; } } }
using System; using System.Collections.Generic; using System.Linq; using VersionOne.SDK.APIClient; namespace VersionOne.ServerConnector { // TODO extract interface and inject into VersionOneProcessor internal class EntityFactory { private readonly IServices services; private readonly IEnumerable<AttributeInfo> attributesToQuery; internal EntityFactory(IServices services, IEnumerable<AttributeInfo> attributesToQuery) { this.services = services; this.attributesToQuery = attributesToQuery; } internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) { var assetType = services.Meta.GetAssetType(assetTypeName); var asset = services.New(assetType, Oid.Null); foreach (var attributeValue in attributeValues) { if(attributeValue is SingleAttributeValue) { asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value); } else if(attributeValue is MultipleAttributeValue) { var values = ((MultipleAttributeValue) attributeValue).Values; var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name); foreach (var value in values) { asset.AddAttributeValue(attributeDefinition, value); } } else { throw new NotSupportedException("Unknown Attribute Value type."); } } foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) { asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr)); } services.Save(asset); return asset; } } }
Use the new 15.0 SDK to access meta via IServices
S-54454: Use the new 15.0 SDK to access meta via IServices
C#
bsd-3-clause
versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla
2ad41fd040ef86903ea05a80588d1bf423f38216
AssemblyInfoCommon.cs
AssemblyInfoCommon.cs
// <copyright file="AssemblyInfoCommon.cs" company="natsnudasoft"> // Copyright (c) Adrian John Dunstan. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System.Reflection; using System.Resources; [assembly: NeutralResourcesLanguage("en-GB")] [assembly: AssemblyCompany("natsnudasoft")] [assembly: AssemblyCopyright("Copyright © Adrian John Dunstan 2016")] // Version is generated on the build server. [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0.0")]
// <copyright file="AssemblyInfoCommon.cs" company="natsnudasoft"> // Copyright (c) Adrian John Dunstan. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System.Reflection; using System.Resources; [assembly: NeutralResourcesLanguage("en-GB")] [assembly: AssemblyCompany("natsnudasoft")] [assembly: AssemblyCopyright("Copyright © Adrian John Dunstan 2016")] // Version is generated on the build server. #pragma warning disable MEN002 // Line is too long [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0.0")] #pragma warning restore MEN002 // Line is too long
Resolve line too long message on build server
Resolve line too long message on build server
C#
apache-2.0
natsnudasoft/AdiePlayground
a967ed6773c356ba080060e95f245866004b3ff0
Battlezeppelins/Models/PlayerTable/ZeppelinType.cs
Battlezeppelins/Models/PlayerTable/ZeppelinType.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; namespace Battlezeppelins.Models { public class ZeppelinType { public static readonly ZeppelinType MOTHER = new ZeppelinType("Mother", 5); public static readonly ZeppelinType LEET = new ZeppelinType("Leet", 3); public static readonly ZeppelinType NIBBLET = new ZeppelinType("Nibblet", 2); public static IEnumerable<ZeppelinType> Values { get { yield return MOTHER; yield return LEET; yield return NIBBLET; } } public static ZeppelinType getByName(string name) { foreach (ZeppelinType type in Values) { if (type.name == name) return type; } return null; } [JsonProperty] public string name { get; private set; } [JsonProperty] public int length { get; private set; } private ZeppelinType() { } ZeppelinType(string name, int length) { this.name = name; this.length = length; } public override string ToString() { return name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; namespace Battlezeppelins.Models { public class ZeppelinType { public static readonly ZeppelinType MOTHER = new ZeppelinType("Mother", 5); public static readonly ZeppelinType LEET = new ZeppelinType("Leet", 3); public static readonly ZeppelinType NIBBLET = new ZeppelinType("Nibblet", 2); public static IEnumerable<ZeppelinType> Values { get { yield return MOTHER; yield return LEET; yield return NIBBLET; } } public static ZeppelinType getByName(string name) { foreach (ZeppelinType type in Values) { if (type.name == name) return type; } return null; } [JsonProperty] public string name { get; private set; } [JsonProperty] public int length { get; private set; } private ZeppelinType() { } ZeppelinType(string name, int length) { this.name = name; this.length = length; } public override string ToString() { return name; } public override bool Equals(object zeppelin) { return this == (ZeppelinType)zeppelin; } public static bool operator==(ZeppelinType z1, ZeppelinType z2) { return z1.name == z2.name; } public static bool operator !=(ZeppelinType z1, ZeppelinType z2) { return z1.name != z2.name; } } }
Fix 'no multiple zeppelins of the same type' constraint server side.
Fix 'no multiple zeppelins of the same type' constraint server side.
C#
apache-2.0
Mikuz/Battlezeppelins,Mikuz/Battlezeppelins
a7c2b8bac8b3579a09bd3609974ca87e86a82da8
CefSharp.BrowserSubprocess/Program.cs
CefSharp.BrowserSubprocess/Program.cs
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows.Forms; using CefSharp.Internals; namespace CefSharp.BrowserSubprocess { public class Program { public static int Main(string[] args) { Kernel32.OutputDebugString("BrowserSubprocess starting up with command line: " + String.Join("\n", args)); int result; //MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information); var commandLineArgs = new List<string>(args) { "--renderer-startup-dialog" }; using (var subprocess = Create(commandLineArgs.ToArray())) { //if (subprocess is CefRenderProcess) //{ // MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information); //} result = subprocess.Run(); } Kernel32.OutputDebugString("BrowserSubprocess shutting down."); return result; } public static CefSubProcess Create(IEnumerable<string> args) { const string typePrefix = "--type="; var typeArgument = args.SingleOrDefault(arg => arg.StartsWith(typePrefix)); var type = typeArgument.Substring(typePrefix.Length); switch (type) { case "renderer": return new CefRenderProcess(args); case "gpu-process": return new CefGpuProcess(args); default: return new CefSubProcess(args); } } } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using CefSharp.Internals; namespace CefSharp.BrowserSubprocess { public class Program { public static int Main(string[] args) { Kernel32.OutputDebugString("BrowserSubprocess starting up with command line: " + String.Join("\n", args)); int result; using (var subprocess = Create(args)) { //if (subprocess is CefRenderProcess) //{ // MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information); //} result = subprocess.Run(); } Kernel32.OutputDebugString("BrowserSubprocess shutting down."); return result; } public static CefSubProcess Create(IEnumerable<string> args) { const string typePrefix = "--type="; var typeArgument = args.SingleOrDefault(arg => arg.StartsWith(typePrefix)); var type = typeArgument.Substring(typePrefix.Length); switch (type) { case "renderer": return new CefRenderProcess(args); case "gpu-process": return new CefGpuProcess(args); default: return new CefSubProcess(args); } } } }
Revert to previous debugging method as change wasn't working correctly.
Revert to previous debugging method as change wasn't working correctly.
C#
bsd-3-clause
joshvera/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,dga711/CefSharp,rover886/CefSharp,joshvera/CefSharp,ruisebastiao/CefSharp,Livit/CefSharp,gregmartinhtc/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,rover886/CefSharp,windygu/CefSharp,illfang/CefSharp,illfang/CefSharp,battewr/CefSharp,VioletLife/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,battewr/CefSharp,ITGlobal/CefSharp,NumbersInternational/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,Haraguroicha/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,VioletLife/CefSharp,Livit/CefSharp,haozhouxu/CefSharp,yoder/CefSharp,twxstar/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,twxstar/CefSharp,gregmartinhtc/CefSharp,joshvera/CefSharp,AJDev77/CefSharp,rlmcneary2/CefSharp,joshvera/CefSharp,Octopus-ITSM/CefSharp,Livit/CefSharp,zhangjingpu/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,gregmartinhtc/CefSharp,twxstar/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,jamespearce2006/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,Octopus-ITSM/CefSharp,wangzheng888520/CefSharp,illfang/CefSharp,ruisebastiao/CefSharp,dga711/CefSharp,rlmcneary2/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,ITGlobal/CefSharp,yoder/CefSharp,dga711/CefSharp,battewr/CefSharp,rover886/CefSharp,battewr/CefSharp,VioletLife/CefSharp,yoder/CefSharp,Octopus-ITSM/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,zhangjingpu/CefSharp,Livit/CefSharp,Octopus-ITSM/CefSharp,wangzheng888520/CefSharp,dga711/CefSharp,Haraguroicha/CefSharp,zhangjingpu/CefSharp,Haraguroicha/CefSharp,NumbersInternational/CefSharp,haozhouxu/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,AJDev77/CefSharp,NumbersInternational/CefSharp,windygu/CefSharp,AJDev77/CefSharp,gregmartinhtc/CefSharp,zhangjingpu/CefSharp,ruisebastiao/CefSharp
6552e002990d88dcc8ace02a4027fc3e0e48d857
Code/Luval.Common/ConsoleArguments.cs
Code/Luval.Common/ConsoleArguments.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Luval.Common { public class ConsoleArguments { private List<string> _args; public ConsoleArguments(IEnumerable<string> args) { _args = new List<string>(args); } public bool ContainsSwitch(string name) { return _args.Contains(name); } public string GetSwitchValue(string name) { if (!ContainsSwitch(name)) return null; var switchIndex = _args.IndexOf(name); if (_args.Count < switchIndex + 1) return null; return _args[switchIndex + 1]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Luval.Common { public class ConsoleArguments { private List<string> _args; public ConsoleArguments(IEnumerable<string> args) { _args = new List<string>(args); } public bool ContainsSwitch(string name) { return _args.Contains(name); } public string GetSwitchValue(string name) { if (!ContainsSwitch(name)) return null; var switchIndex = _args.IndexOf(name); if ((_args.Count - 1) < switchIndex + 1) return null; return _args[switchIndex + 1]; } } }
Fix a bug with the console arguments class
Fix a bug with the console arguments class
C#
apache-2.0
marinoscar/Luval
2ff0df6800e53b54bf163d8546413bcc5d9975fa
MultiMiner.Utility/ApplicationPaths.cs
MultiMiner.Utility/ApplicationPaths.cs
using System; using System.IO; namespace MultiMiner.Utility { public static class ApplicationPaths { public static string AppDataPath() { string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(rootPath, "MultiMiner"); } } }
using System; using System.IO; namespace MultiMiner.Utility { public static class ApplicationPaths { public static string AppDataPath() { //if running in "portable" mode if (IsRunningInPortableMode()) { //store files in the working directory rather than AppData return GetWorkingDirectory(); } else { string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(rootPath, "MultiMiner"); } } //simply check for a file named "portable" in the same folder private static bool IsRunningInPortableMode() { string assemblyDirectory = GetWorkingDirectory(); string portableFile = Path.Combine(assemblyDirectory, "portable"); return File.Exists(portableFile); } private static string GetWorkingDirectory() { string assemblyFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location; return Path.GetDirectoryName(assemblyFilePath); } } }
Support for running the app in a "portable" mode
Support for running the app in a "portable" mode
C#
mit
IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner,nwoolls/MultiMiner
44c1c93e816f683fe63af8e96f0aad6b827aebb5
Plugins/Wox.Plugin.Program/Settings.cs
Plugins/Wox.Plugin.Program/Settings.cs
using System.Collections.Generic; using System.IO; using Wox.Plugin.Program.Programs; namespace Wox.Plugin.Program { public class Settings { public List<ProgramSource> ProgramSources { get; set; } = new List<ProgramSource>(); public List<DisabledProgramSource> DisabledProgramSources { get; set; } = new List<DisabledProgramSource>(); public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"}; public bool EnableStartMenuSource { get; set; } = true; public bool EnableRegistrySource { get; set; } = true; internal const char SuffixSeperator = ';'; /// <summary> /// Contains user added folder location contents as well as all user disabled applications /// </summary> /// <remarks> /// <para>Win32 class applications sets UniqueIdentifier using their full path</para> /// <para>UWP class applications sets UniqueIdentifier using their Application User Model ID</para> /// </remarks> public class ProgramSource { private string name; public string Location { get; set; } public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; } public bool Enabled { get; set; } = true; public string UniqueIdentifier { get; set; } } public class DisabledProgramSource { private string name; public string Location { get; set; } public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; } public bool Enabled { get; set; } = true; public string UniqueIdentifier { get; set; } } } }
using System.Collections.Generic; using System.IO; using Wox.Plugin.Program.Programs; namespace Wox.Plugin.Program { public class Settings { public List<ProgramSource> ProgramSources { get; set; } = new List<ProgramSource>(); public List<DisabledProgramSource> DisabledProgramSources { get; set; } = new List<DisabledProgramSource>(); public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"}; public bool EnableStartMenuSource { get; set; } = true; public bool EnableRegistrySource { get; set; } = true; internal const char SuffixSeperator = ';'; /// <summary> /// Contains user added folder location contents as well as all user disabled applications /// </summary> /// <remarks> /// <para>Win32 class applications sets UniqueIdentifier using their full path</para> /// <para>UWP class applications sets UniqueIdentifier using their Application User Model ID</para> /// </remarks> public class ProgramSource { private string name; public string Location { get; set; } public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; } public bool Enabled { get; set; } = true; public string UniqueIdentifier { get; set; } } public class DisabledProgramSource : ProgramSource { } } }
Change DisabledProgramSource class to inherit ProgramSource
Change DisabledProgramSource class to inherit ProgramSource
C#
mit
qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox,qianlifeng/Wox,Wox-launcher/Wox
580b0a9b9fc15b026b02dfbc029c91535fbc838e
TAUtil/Gaf/Structures/GafFrameData.cs
TAUtil/Gaf/Structures/GafFrameData.cs
namespace TAUtil.Gaf.Structures { using System.IO; internal struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public byte TransparencyIndex; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(BinaryReader b, ref GafFrameData e) { e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.TransparencyIndex = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
namespace TAUtil.Gaf.Structures { using System.IO; internal struct GafFrameData { public ushort Width; public ushort Height; public short XPos; public short YPos; public byte TransparencyIndex; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(BinaryReader b, ref GafFrameData e) { e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadInt16(); e.YPos = b.ReadInt16(); e.TransparencyIndex = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
Allow negative GAF frame offsets
Allow negative GAF frame offsets
C#
mit
MHeasell/TAUtil,MHeasell/TAUtil
b635c564061eb1deee4eb0bb20b67ad9adc9fbd8
TAUtil.Gdi/Bitmap/BitmapSerializer.cs
TAUtil.Gdi/Bitmap/BitmapSerializer.cs
namespace TAUtil.Gdi.Bitmap { using System.Drawing; using System.Drawing.Imaging; using System.IO; using TAUtil.Gdi.Palette; /// <summary> /// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data. /// The mapping from color to index is done according to the given /// reverse palette lookup. /// </summary> public class BitmapSerializer { private readonly IPalette palette; public BitmapSerializer(IPalette palette) { this.palette = palette; } public byte[] ToBytes(Bitmap bitmap) { int length = bitmap.Width * bitmap.Height; byte[] output = new byte[length]; this.Serialize(new MemoryStream(output, true), bitmap); return output; } public void Serialize(Stream output, Bitmap bitmap) { Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, bitmap.PixelFormat); int length = bitmap.Width * bitmap.Height; unsafe { int* pointer = (int*)data.Scan0; for (int i = 0; i < length; i++) { Color c = Color.FromArgb(pointer[i]); output.WriteByte((byte)this.palette.LookUp(c)); } } bitmap.UnlockBits(data); } } }
namespace TAUtil.Gdi.Bitmap { using System.Drawing; using System.Drawing.Imaging; using System.IO; using TAUtil.Gdi.Palette; /// <summary> /// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data. /// The mapping from color to index is done according to the given /// reverse palette lookup. /// </summary> public class BitmapSerializer { private readonly IPalette palette; public BitmapSerializer(IPalette palette) { this.palette = palette; } public byte[] ToBytes(Bitmap bitmap) { int length = bitmap.Width * bitmap.Height; byte[] output = new byte[length]; this.Serialize(new MemoryStream(output, true), bitmap); return output; } public void Serialize(Stream output, Bitmap bitmap) { Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int length = bitmap.Width * bitmap.Height; unsafe { int* pointer = (int*)data.Scan0; for (int i = 0; i < length; i++) { Color c = Color.FromArgb(pointer[i]); output.WriteByte((byte)this.palette.LookUp(c)); } } bitmap.UnlockBits(data); } } }
Fix bitmap serialization with indexed format bitmaps
Fix bitmap serialization with indexed format bitmaps
C#
mit
MHeasell/TAUtil,MHeasell/TAUtil
fab09575ec30d2cec7aef5487f59b6b8fa10732a
osu.Game.Tests/Visual/Gameplay/TestSceneBeatmapOffsetControl.cs
osu.Game.Tests/Visual/Gameplay/TestSceneBeatmapOffsetControl.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Game.Screens.Play.PlayerSettings; using osu.Game.Tests.Visual.Ranking; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneBeatmapOffsetControl : OsuTestScene { [Test] public void TestDisplay() { Child = new PlayerSettingsGroup("Some settings") { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new BeatmapOffsetControl(TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents(-4.5)) } }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Overlays.Settings; using osu.Game.Scoring; using osu.Game.Screens.Play.PlayerSettings; using osu.Game.Tests.Visual.Ranking; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneBeatmapOffsetControl : OsuTestScene { private BeatmapOffsetControl offsetControl; [SetUpSteps] public void SetUpSteps() { AddStep("Create control", () => { Child = new PlayerSettingsGroup("Some settings") { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { offsetControl = new BeatmapOffsetControl() } }; }); } [Test] public void TestDisplay() { const double average_error = -4.5; AddAssert("Offset is neutral", () => offsetControl.Current.Value == 0); AddAssert("No calibration button", () => !offsetControl.ChildrenOfType<SettingsButton>().Any()); AddStep("Set reference score", () => { offsetControl.ReferenceScore.Value = new ScoreInfo { HitEvents = TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents(average_error) }; }); AddAssert("Has calibration button", () => offsetControl.ChildrenOfType<SettingsButton>().Any()); AddStep("Press button", () => offsetControl.ChildrenOfType<SettingsButton>().Single().TriggerClick()); AddAssert("Offset is adjusted", () => offsetControl.Current.Value == average_error); AddStep("Remove reference score", () => offsetControl.ReferenceScore.Value = null); AddAssert("No calibration button", () => !offsetControl.ChildrenOfType<SettingsButton>().Any()); } } }
Add full testing flow for `BeatmapOffsetControl`
Add full testing flow for `BeatmapOffsetControl`
C#
mit
NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu
29ba866ddc7dbd11e7eb0103c2744366ffc2701d
DesktopWidgets/Widgets/Search/ViewModel.cs
DesktopWidgets/Widgets/Search/ViewModel.cs
using System.Diagnostics; using System.Windows.Input; using DesktopWidgets.Classes; using DesktopWidgets.Helpers; using DesktopWidgets.ViewModelBase; using GalaSoft.MvvmLight.Command; namespace DesktopWidgets.Widgets.Search { public class ViewModel : WidgetViewModelBase { private string _searchText; public ViewModel(WidgetId id) : base(id) { Settings = id.GetSettings() as Settings; if (Settings == null) return; Go = new RelayCommand(GoExecute); OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute); } public Settings Settings { get; } public ICommand Go { get; set; } public ICommand OnKeyUp { get; set; } public string SearchText { get { return _searchText; } set { if (_searchText != value) { _searchText = value; RaisePropertyChanged(nameof(SearchText)); } } } private void GoExecute() { var searchText = SearchText; SearchText = string.Empty; Process.Start($"{Settings.BaseUrl}{searchText}"); } private void OnKeyUpExecute(KeyEventArgs args) { if (args.Key == Key.Enter) GoExecute(); } } }
using System.Diagnostics; using System.Windows; using System.Windows.Input; using DesktopWidgets.Classes; using DesktopWidgets.Helpers; using DesktopWidgets.ViewModelBase; using GalaSoft.MvvmLight.Command; namespace DesktopWidgets.Widgets.Search { public class ViewModel : WidgetViewModelBase { private string _searchText; public ViewModel(WidgetId id) : base(id) { Settings = id.GetSettings() as Settings; if (Settings == null) return; Go = new RelayCommand(GoExecute); OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute); } public Settings Settings { get; } public ICommand Go { get; set; } public ICommand OnKeyUp { get; set; } public string SearchText { get { return _searchText; } set { if (_searchText != value) { _searchText = value; RaisePropertyChanged(nameof(SearchText)); } } } private void GoExecute() { if (string.IsNullOrWhiteSpace(Settings.BaseUrl)) { Popup.Show("You must setup a base url first.", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } var searchText = SearchText; SearchText = string.Empty; Process.Start($"{Settings.BaseUrl}{searchText}"); } private void OnKeyUpExecute(KeyEventArgs args) { if (args.Key == Key.Enter) GoExecute(); } } }
Add "Search" widget no base url warning
Add "Search" widget no base url warning
C#
apache-2.0
danielchalmers/DesktopWidgets
e52400f7561e4932efe06857c2889e43a54a01e1
Sendgrid.Webhooks/Converters/WebhookCategoryConverter.cs
Sendgrid.Webhooks/Converters/WebhookCategoryConverter.cs
using System; using System.ComponentModel; using Newtonsoft.Json; using Sendgrid.Webhooks.Converters; namespace Sendgrid.Webhooks.Service { public class WebhookCategoryConverter : GenericListCreationJsonConverter<String> { } }
using System; using System.ComponentModel; using Newtonsoft.Json; using Sendgrid.Webhooks.Converters; namespace Sendgrid.Webhooks.Service { public class WebhookCategoryConverter : GenericListCreationJsonConverter<string> { } }
Use string instead of String
Use string instead of String
C#
apache-2.0
mirajavora/sendgrid-webhooks
1fec6ec2127de08cf234aaa61843bab899a69eb3
osu.Framework/Host.cs
osu.Framework/Host.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Platform.Linux; using osu.Framework.Platform.MacOS; using osu.Framework.Platform.Windows; using System; namespace osu.Framework { public static class Host { public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: return new MacOSGameHost(gameName, bindIPC); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(gameName, bindIPC); case RuntimeInfo.Platform.Windows: return new WindowsGameHost(gameName, bindIPC); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)})."); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Platform.Linux; using osu.Framework.Platform.MacOS; using osu.Framework.Platform.Windows; using System; namespace osu.Framework { public static class Host { public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: return new MacOSGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Windows: return new WindowsGameHost(gameName, bindIPC, portableInstallation); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)})."); } } } }
Add back incorrectly removed parameter
Add back incorrectly removed parameter
C#
mit
ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework
c9468cb0bcd3841d602b4a7b7bbf42176d730fcd
CertiPay.Services.PDF/Bootstrapper.cs
CertiPay.Services.PDF/Bootstrapper.cs
using CertiPay.PDF; using Nancy; using Nancy.TinyIoc; using System; using System.Configuration; namespace CertiPay.Services.PDF { public class Bootstrapper : DefaultNancyBootstrapper { private static String ABCPdfLicense { get { return ConfigurationManager.AppSettings["ABCPDF-License"]; } } protected override void ConfigureApplicationContainer(TinyIoCContainer container) { container.Register<IPDFService>(new PDFService(ABCPdfLicense)); } } }
using CertiPay.PDF; using Nancy; using Nancy.TinyIoc; using System; using System.Configuration; namespace CertiPay.Services.PDF { public class Bootstrapper : DefaultNancyBootstrapper { private static String ABCPdfLicense { get { // Check the environment variables for the license key String key = "ABCPDF-License"; if (!String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User))) { return Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User); } return ConfigurationManager.AppSettings[key]; } } protected override void ConfigureApplicationContainer(TinyIoCContainer container) { container.Register<IPDFService>(new PDFService(ABCPdfLicense)); } } }
Check the environment variable for the license key
Check the environment variable for the license key
C#
mit
kylebjones/CertiPay.Services.PDF
0b970b3de194463f81cb007fc3db74a40fc6dcd8
exercises/prime-factors/PrimeFactorsTest.cs
exercises/prime-factors/PrimeFactorsTest.cs
// This file was auto-generated based on version 1.0.0 of the canonical data. using Xunit; public class PrimeFactorsTest { [Fact] public void No_factors() { Assert.Empty(PrimeFactors.Factors(1)); } [Fact] public void Prime_number() { Assert.Equal(new[] { 2 }, PrimeFactors.Factors(2)); } [Fact] public void Square_of_a_prime() { Assert.Equal(new[] { 3, 3 }, PrimeFactors.Factors(9)); } [Fact] public void Cube_of_a_prime() { Assert.Equal(new[] { 2, 2, 2 }, PrimeFactors.Factors(8)); } [Fact] public void Product_of_primes_and_non_primes() { Assert.Equal(new[] { 2, 2, 3 }, PrimeFactors.Factors(12)); } [Fact] public void Product_of_primes() { Assert.Equal(new[] { 5, 17, 23, 461 }, PrimeFactors.Factors(901255)); } [Fact] public void Factors_include_a_large_prime() { Assert.Equal(new[] { 11, 9539, 894119 }, PrimeFactors.Factors(93819012551)); } }
// This file was auto-generated based on version 1.0.0 of the canonical data. using Xunit; public class PrimeFactorsTest { [Fact] public void No_factors() { Assert.Empty(PrimeFactors.Factors(1)); } [Fact(Skip = "Remove to run test")] public void Prime_number() { Assert.Equal(new[] { 2 }, PrimeFactors.Factors(2)); } [Fact(Skip = "Remove to run test")] public void Square_of_a_prime() { Assert.Equal(new[] { 3, 3 }, PrimeFactors.Factors(9)); } [Fact(Skip = "Remove to run test")] public void Cube_of_a_prime() { Assert.Equal(new[] { 2, 2, 2 }, PrimeFactors.Factors(8)); } [Fact(Skip = "Remove to run test")] public void Product_of_primes_and_non_primes() { Assert.Equal(new[] { 2, 2, 3 }, PrimeFactors.Factors(12)); } [Fact(Skip = "Remove to run test")] public void Product_of_primes() { Assert.Equal(new[] { 5, 17, 23, 461 }, PrimeFactors.Factors(901255)); } [Fact(Skip = "Remove to run test")] public void Factors_include_a_large_prime() { Assert.Equal(new[] { 11, 9539, 894119 }, PrimeFactors.Factors(93819012551)); } }
Add skips to prime factors test suite
Add skips to prime factors test suite
C#
mit
ErikSchierboom/xcsharp,ErikSchierboom/xcsharp,robkeim/xcsharp,exercism/xcsharp,robkeim/xcsharp,GKotfis/csharp,exercism/xcsharp,GKotfis/csharp
e8532f0ec8b72f94bf700d7d712d8d9a98f0a89b
src/HolzShots.Core.Tests/Net/Custom/CustomUploaderLoaderTests.cs
src/HolzShots.Core.Tests/Net/Custom/CustomUploaderLoaderTests.cs
using HolzShots.Net.Custom; using Xunit; namespace HolzShots.Core.Tests.Net.Custom { public class CustomUploaderLoaderTests { [Theory] [FileStringContentData("Files/DirectUpload.net.hsjson")] [FileStringContentData("Files/FotosHochladen.hsjson")] public void ValidateTest(string content) { var parseResult = CustomUploader.TryParse(content, out var result); Assert.True(parseResult); Assert.NotNull(result); Assert.NotNull(result.CustomData); Assert.NotNull(result.CustomData.Info); Assert.NotNull(result.CustomData.Uploader); Assert.NotNull(result.CustomData.SchemaVersion); } } }
using HolzShots.Net.Custom; using Xunit; namespace HolzShots.Core.Tests.Net.Custom { public class CustomUploaderLoaderTests { [Theory] [FileStringContentData("Files/DirectUpload.net.hsjson")] [FileStringContentData("Files/FotosHochladen.hsjson")] public void ValidateTest(string content) { var parseResult = CustomUploader.TryParse(content, out var result); Assert.True(parseResult); Assert.NotNull(result); Assert.NotNull(result.CustomData); Assert.NotNull(result.CustomData.Info); Assert.NotNull(result.CustomData.Uploader); Assert.NotNull(result.CustomData.SchemaVersion); Assert.True(result.CustomData.Info.Version == new Semver.SemVersion(1, 0, 0)); } } }
Add Test for SemVer Parsing
Add Test for SemVer Parsing
C#
agpl-3.0
nikeee/HolzShots
a26b0915b4047d61032dc7c0e9fc893502ac70ae
osu.Game.Rulesets.Osu.Tests/TestSceneShaking.cs
osu.Game.Rulesets.Osu.Tests/TestSceneShaking.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using osu.Framework.Utils; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Tests { public class TestSceneShaking : TestSceneHitCircle { protected override TestDrawableHitCircle CreateDrawableHitCircle(HitCircle circle, bool auto) { var drawableHitObject = base.CreateDrawableHitCircle(circle, auto); Debug.Assert(drawableHitObject.HitObject.HitWindows != null); double delay = drawableHitObject.HitObject.StartTime - (drawableHitObject.HitObject.HitWindows.WindowFor(HitResult.Miss) + RNG.Next(0, 300)) - Time.Current; Scheduler.AddDelayed(() => drawableHitObject.TriggerJudgement(), delay); return drawableHitObject; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Diagnostics; using osu.Framework.Threading; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Tests { public class TestSceneShaking : TestSceneHitCircle { private readonly List<ScheduledDelegate> scheduledTasks = new List<ScheduledDelegate>(); protected override IBeatmap CreateBeatmapForSkinProvider() { // best way to run cleanup before a new step is run foreach (var task in scheduledTasks) task.Cancel(); scheduledTasks.Clear(); return base.CreateBeatmapForSkinProvider(); } protected override TestDrawableHitCircle CreateDrawableHitCircle(HitCircle circle, bool auto) { var drawableHitObject = base.CreateDrawableHitCircle(circle, auto); Debug.Assert(drawableHitObject.HitObject.HitWindows != null); double delay = drawableHitObject.HitObject.StartTime - (drawableHitObject.HitObject.HitWindows.WindowFor(HitResult.Miss) + RNG.Next(0, 300)) - Time.Current; scheduledTasks.Add(Scheduler.AddDelayed(() => drawableHitObject.TriggerJudgement(), delay)); return drawableHitObject; } } }
Fix scheduled tasks not being cleaned up between test steps
Fix scheduled tasks not being cleaned up between test steps
C#
mit
smoogipoo/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,smoogipooo/osu,peppy/osu,UselessToucan/osu,peppy/osu,ppy/osu
b9944cce53442e8dc34bf55c49b22fc55ccbd9a9
SocketHelper.cs
SocketHelper.cs
using System; using System.Net.Sockets; using System.Net; using System.Threading; namespace NDeproxy { public static class SocketHelper { static readonly Logger log = new Logger("SocketHelper"); public static Socket Server(int port, int listenQueue=5) { var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Bind(new IPEndPoint(IPAddress.Any, port)); s.Listen(listenQueue); return s; } public static Socket Client(string remoteHost, int port) { var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(remoteHost, port); return s; } public static int GetLocalPort(this Socket socket) { return ((IPEndPoint)socket.LocalEndPoint).Port; } public static int GetRemotePort(this Socket socket) { return ((IPEndPoint)socket.RemoteEndPoint).Port; } } }
using System; using System.Net.Sockets; using System.Net; using System.Threading; namespace NDeproxy { public static class SocketHelper { static readonly Logger log = new Logger("SocketHelper"); public static Socket Server(int port, int listenQueue=5) { var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Bind(new IPEndPoint(IPAddress.Any, port)); s.Listen(listenQueue); return s; } public static Socket Client(string remoteHost, int port, int timeout=Timeout.Infinite) { var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (timeout == Timeout.Infinite) { s.Connect(remoteHost, port); return s; } else { var result = s.BeginConnect(remoteHost, port, (_result) => { s.EndConnect(_result); }, s); if (result.AsyncWaitHandle.WaitOne(timeout)) { return s; } else { throw new SocketException((int)SocketError.TimedOut); } } } public static int GetLocalPort(this Socket socket) { return ((IPEndPoint)socket.LocalEndPoint).Port; } public static int GetRemotePort(this Socket socket) { return ((IPEndPoint)socket.RemoteEndPoint).Port; } } }
Add an optional timeout for connection attempts.
Add an optional timeout for connection attempts.
C#
mit
izrik/NDeproxy
b3287e7b0d51023c57ffe07665b7e35de6880cf6
src/Lunet/Core/MetaManager.cs
src/Lunet/Core/MetaManager.cs
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System.Collections.Generic; namespace Lunet.Core { /// <summary> /// Manages the meta information associated to a site (from the `_meta` directory and `.lunet` directory) /// </summary> /// <seealso cref="ManagerBase" /> public class MetaManager : ManagerBase { public const string MetaDirectoryName = "_meta"; /// <summary> /// Initializes a new instance of the <see cref="MetaManager"/> class. /// </summary> /// <param name="site">The site.</param> public MetaManager(SiteObject site) : base(site) { Directory = Site.BaseDirectory.GetSubFolder(MetaDirectoryName); PrivateDirectory = Site.PrivateBaseDirectory.GetSubFolder(MetaDirectoryName); } public FolderInfo Directory { get; } public FolderInfo PrivateDirectory { get; } public IEnumerable<FolderInfo> Directories { get { yield return Directory; foreach (var theme in Site.Extends.CurrentList) { yield return theme.Directory.GetSubFolder(MetaDirectoryName); } } } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Reflection; namespace Lunet.Core { /// <summary> /// Manages the meta information associated to a site (from the `_meta` directory and `.lunet` directory) /// </summary> /// <seealso cref="ManagerBase" /> public class MetaManager : ManagerBase { public const string MetaDirectoryName = "_meta"; /// <summary> /// Initializes a new instance of the <see cref="MetaManager"/> class. /// </summary> /// <param name="site">The site.</param> public MetaManager(SiteObject site) : base(site) { Directory = Site.BaseDirectory.GetSubFolder(MetaDirectoryName); PrivateDirectory = Site.PrivateBaseDirectory.GetSubFolder(MetaDirectoryName); BuiltinDirectory = Path.GetDirectoryName(typeof(MetaManager).GetTypeInfo().Assembly.Location); } public FolderInfo Directory { get; } public FolderInfo BuiltinDirectory { get; } public FolderInfo PrivateDirectory { get; } public IEnumerable<FolderInfo> Directories { get { yield return Directory; foreach (var theme in Site.Extends.CurrentList) { yield return theme.Directory.GetSubFolder(MetaDirectoryName); } // Last one is the builtin directory yield return new DirectoryInfo(Path.Combine(BuiltinDirectory, MetaDirectoryName)); } } } }
Add support for builtins directory from the assembly folder/_meta
Add support for builtins directory from the assembly folder/_meta
C#
bsd-2-clause
lunet-io/lunet,lunet-io/lunet
77e74c3a10556ec5900db50e03c08a0e06f85a81
examples/hello/Startup.cs
examples/hello/Startup.cs
using System; using System.IO; using System.Collections.Generic; using System.Threading.Tasks; using Owin; namespace Connect.Owin.Examples.Hello { // OWIN application delegate using AppFunc = Func<IDictionary<string, object>, Task>; public class Startup { public void Configuration(IAppBuilder app) { app.Use(new Func<AppFunc, AppFunc>(next => async env => { env["owin.ResponseStatusCode"] = 200; ((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add( "Content-Type", new string[] { "text/html" }); StreamWriter w = new StreamWriter((Stream)env["owin.ResponseBody"]); w.Write("Hello, from C#. Time on server is " + DateTime.Now.ToString()); await w.FlushAsync(); })); } } }
using System; using System.IO; using System.Collections.Generic; using System.Threading.Tasks; using Owin; namespace Connect.Owin.Examples.Hello { // OWIN application delegate using AppFunc = Func<IDictionary<string, object>, Task>; public class Startup { public void Configuration(IAppBuilder app) { app.Use(new Func<AppFunc, AppFunc>(next => async env => { env["owin.ResponseStatusCode"] = 200; ((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add( "Content-Length", new string[] { "53" }); ((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add( "Content-Type", new string[] { "text/html" }); StreamWriter w = new StreamWriter((Stream)env["owin.ResponseBody"]); w.Write("Hello, from C#. Time on server is " + DateTime.Now.ToString()); await w.FlushAsync(); })); } } }
Set `Content-Length` in the `hello` sample
Set `Content-Length` in the `hello` sample
C#
apache-2.0
bbaia/connect-owin,sebgod/connect-owin,sebgod/connect-owin,bbaia/connect-owin
706fef3567d4c25e5154238018c0634d3805f68b
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/UnitOfWork.cs
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/UnitOfWork.cs
using System; using System.Data; using Dapper.FastCrud; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public class UnitOfWork : DbTransaction, IUnitOfWork { public SqlDialect SqlDialect { get; set; } private readonly Guid _guid = Guid.NewGuid(); public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) : base(factory) { Transaction = session.BeginTransaction(isolationLevel); } protected bool Equals(UnitOfWork other) { return _guid.Equals(other._guid); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((UnitOfWork) obj); } public override int GetHashCode() { return _guid.GetHashCode(); } public static bool operator ==(UnitOfWork left, UnitOfWork right) { return Equals(left, right); } public static bool operator !=(UnitOfWork left, UnitOfWork right) { return !Equals(left, right); } } }
using System; using System.Data; using Dapper.FastCrud; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public class UnitOfWork : DbTransaction, IUnitOfWork { public SqlDialect SqlDialect { get; set; } private readonly Guid _guid = Guid.NewGuid(); public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable, bool sessionOnlyForThisUnitOfWork = false) : base(factory) { if (sessionOnlyForThisUnitOfWork) { Session = session; } Transaction = session.BeginTransaction(isolationLevel); } protected bool Equals(UnitOfWork other) { return _guid.Equals(other._guid); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((UnitOfWork) obj); } public override int GetHashCode() { return _guid.GetHashCode(); } public static bool operator ==(UnitOfWork left, UnitOfWork right) { return Equals(left, right); } public static bool operator !=(UnitOfWork left, UnitOfWork right) { return !Equals(left, right); } } }
Add boolean to figure out is the uow is made with the session
Add boolean to figure out is the uow is made with the session
C#
mit
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
0a3ef1d0e2f27a63d0f9a1e893cf674ea4e37faa
CefSharp/Internals/IBrowserProcess.cs
CefSharp/Internals/IBrowserProcess.cs
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.ServiceModel; namespace CefSharp.Internals { [ServiceContract(CallbackContract = typeof(IRenderProcess), SessionMode = SessionMode.Required)] public interface IBrowserProcess { [OperationContract] BrowserProcessResponse CallMethod(long objectId, string name, object[] parameters); [OperationContract] BrowserProcessResponse GetProperty(long objectId, string name); [OperationContract] BrowserProcessResponse SetProperty(long objectId, string name, object value); [OperationContract] JavascriptRootObject GetRegisteredJavascriptObjects(); [OperationContract] void Connect(); } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Generic; using System.ServiceModel; namespace CefSharp.Internals { [ServiceContract(CallbackContract = typeof(IRenderProcess), SessionMode = SessionMode.Required)] [ServiceKnownType(typeof(object[]))] [ServiceKnownType(typeof(Dictionary<string, object>))] public interface IBrowserProcess { [OperationContract] BrowserProcessResponse CallMethod(long objectId, string name, object[] parameters); [OperationContract] BrowserProcessResponse GetProperty(long objectId, string name); [OperationContract] BrowserProcessResponse SetProperty(long objectId, string name, object value); [OperationContract] JavascriptRootObject GetRegisteredJavascriptObjects(); [OperationContract] void Connect(); } }
Add service ServiceKnownTypes for object[] and Dictionary<string, object> so that basic arrays can be passed two and from functions
Add service ServiceKnownTypes for object[] and Dictionary<string, object> so that basic arrays can be passed two and from functions
C#
bsd-3-clause
NumbersInternational/CefSharp,ruisebastiao/CefSharp,zhangjingpu/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,joshvera/CefSharp,joshvera/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,illfang/CefSharp,rover886/CefSharp,rlmcneary2/CefSharp,yoder/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,yoder/CefSharp,Livit/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,Livit/CefSharp,rover886/CefSharp,AJDev77/CefSharp,jamespearce2006/CefSharp,dga711/CefSharp,VioletLife/CefSharp,windygu/CefSharp,haozhouxu/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,Livit/CefSharp,VioletLife/CefSharp,AJDev77/CefSharp,illfang/CefSharp,windygu/CefSharp,VioletLife/CefSharp,rover886/CefSharp,ruisebastiao/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,gregmartinhtc/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,windygu/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,ITGlobal/CefSharp,gregmartinhtc/CefSharp,NumbersInternational/CefSharp,Livit/CefSharp,dga711/CefSharp,dga711/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,joshvera/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,Haraguroicha/CefSharp,ruisebastiao/CefSharp,joshvera/CefSharp,twxstar/CefSharp,gregmartinhtc/CefSharp,illfang/CefSharp,AJDev77/CefSharp,gregmartinhtc/CefSharp,NumbersInternational/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,rover886/CefSharp,zhangjingpu/CefSharp,haozhouxu/CefSharp,VioletLife/CefSharp,twxstar/CefSharp,battewr/CefSharp,windygu/CefSharp,haozhouxu/CefSharp
910f49764db7c9aa42116090b801cd6d8aac1440
supermarketkata/engine/rules/PercentageDiscount.cs
supermarketkata/engine/rules/PercentageDiscount.cs
using System; using engine.core; namespace engine.rules { public class PercentageDiscount : Rule { private readonly string m_ApplicableItemName; private readonly double m_Percentage; public PercentageDiscount(string applicableItemName, int percentage) { m_ApplicableItemName = applicableItemName; m_Percentage = percentage; } public override Basket Apply(Basket basket) { var discountedBasket = new Basket(); foreach (var item in basket) { discountedBasket.Add(item); if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer) { var discountToApply = -(int) Math.Ceiling(item.Price * m_Percentage / 100); discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply); } } return discountedBasket; } } }
using System; using engine.core; namespace engine.rules { public class PercentageDiscount : Rule { private readonly string m_ApplicableItemName; private readonly double m_Percentage; public PercentageDiscount(string applicableItemName, int percentage) { m_ApplicableItemName = applicableItemName; m_Percentage = percentage; } public override Basket Apply(Basket basket) { var discountedBasket = new Basket(); foreach (var item in basket) { discountedBasket.Add(item); if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer) { var discountToApply = Math.Ceiling(item.Price * m_Percentage / 100); discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), (int) -discountToApply); } } return discountedBasket; } } }
Tidy up sum a bit by moving where we cast and negate to the line below.
Tidy up sum a bit by moving where we cast and negate to the line below.
C#
mit
lukedrury/super-market-kata
f3ac49474c9f354c399e8f9d1b487829770b29aa
src/net45/WampSharp.Default/WAMP2/V2/DefaultWampChannelFactory.cs
src/net45/WampSharp.Default/WAMP2/V2/DefaultWampChannelFactory.cs
using WampSharp.Binding; using WampSharp.V2.Binding; using WampSharp.V2.Client; using WampSharp.WebSocket4Net; namespace WampSharp.V2 { public class DefaultWampChannelFactory : WampChannelFactory { public IWampChannel CreateChannel<TMessage>(string address, string realm, IWampTextBinding<TMessage> binding) { var connection = new WebSocket4NetTextConnection<TMessage>(address, binding); return this.CreateChannel(realm, connection, binding); } public IWampChannel CreateChannel<TMessage>(string address, string realm, IWampBinaryBinding<TMessage> binding) { var connection = new WebSocket4NetBinaryConnection<TMessage>(address, binding); return this.CreateChannel(realm, connection, binding); } public IWampChannel CreateJsonChannel(string address, string realm) { JTokenBinding binding = new JTokenBinding(); return this.CreateChannel(address, realm, binding); } public IWampChannel CreateMsgpackChannel(string address, string realm) { MessagePackObjectBinding binding = new MessagePackObjectBinding(); return this.CreateChannel(address, realm, binding); } } }
using WampSharp.Binding; using WampSharp.V2.Binding; using WampSharp.V2.Client; using WampSharp.WebSocket4Net; namespace WampSharp.V2 { public class DefaultWampChannelFactory : WampChannelFactory { private readonly MessagePackObjectBinding mMsgpackBinding = new MessagePackObjectBinding(); private readonly JTokenBinding mJsonBinding = new JTokenBinding(); public IWampChannel CreateChannel<TMessage>(string address, string realm, IWampTextBinding<TMessage> binding) { var connection = new WebSocket4NetTextConnection<TMessage>(address, binding); return this.CreateChannel(realm, connection, binding); } public IWampChannel CreateChannel<TMessage>(string address, string realm, IWampBinaryBinding<TMessage> binding) { var connection = new WebSocket4NetBinaryConnection<TMessage>(address, binding); return this.CreateChannel(realm, connection, binding); } public IWampChannel CreateJsonChannel(string address, string realm) { return this.CreateChannel(address, realm, mJsonBinding); } public IWampChannel CreateMsgpackChannel(string address, string realm) { return this.CreateChannel(address, realm, mMsgpackBinding); } } }
Use the same reference for all method calls
Use the same reference for all method calls
C#
bsd-2-clause
jmptrader/WampSharp,jmptrader/WampSharp,jmptrader/WampSharp
78df04213b87fde4f41ae7868a7ff3f6ec734cd9
ParallelWorkshopTests/Ex10WaitHalfWay/LimitedModeCharacterCounterTests.cs
ParallelWorkshopTests/Ex10WaitHalfWay/LimitedModeCharacterCounterTests.cs
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Lurchsoft.FileData; using Lurchsoft.ParallelWorkshop.Ex10WaitHalfWay; using NUnit.Framework; namespace Lurchsoft.ParallelWorkshopTests.Ex10WaitHalfWay { [TestFixture] public class LimitedModeCharacterCounterTests { [Test] public void GetCharCounts_ShouldSucceed_WhenSeveralInstancesRunConcurrently() { const int NumConcurrent = 10; ITextFile[] allFiles = EmbeddedFiles.AllFiles.ToArray(); IEnumerable<ITextFile> textFiles = Enumerable.Range(0, NumConcurrent).Select(i => allFiles[i % allFiles.Length]); // To solve the exercise, you may need to pass additional synchronisation information to the constructor. var counters = textFiles.Select(textFile => new LimitedModeCharacterCounter(textFile)).ToArray(); // When you've succeeded, try changing this to use AsParallel(). Does it still work? It didn't for me. Explain why! Task[] tasks = counters.Select(c => (Task)Task.Factory.StartNew(() => c.GetCharCounts())).ToArray(); Task.WaitAll(tasks); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Lurchsoft.FileData; using Lurchsoft.ParallelWorkshop.Ex10WaitHalfWay; using NUnit.Framework; namespace Lurchsoft.ParallelWorkshopTests.Ex10WaitHalfWay { [TestFixture] public class LimitedModeCharacterCounterTests { [Test] public void GetCharCounts_ShouldSucceed_WhenSeveralInstancesRunConcurrently() { LimitedModeCharacterCounter[] counters = CreateCounters(); Task[] tasks = counters.Select(c => (Task)Task.Factory.StartNew(() => c.GetCharCounts())).ToArray(); Task.WaitAll(tasks); } [Test, Explicit("This will probably hang, once you make it use your Barrier-based solution. Can you work out why?")] public void GetCharCounts_UsingAsParallel() { LimitedModeCharacterCounter[] counters = CreateCounters(); var results = counters.AsParallel().Select(c => c.GetCharCounts()).ToArray(); Assert.That(results, Is.Not.Empty); } private static LimitedModeCharacterCounter[] CreateCounters() { const int NumConcurrent = 10; ITextFile[] allFiles = EmbeddedFiles.AllFiles.ToArray(); IEnumerable<ITextFile> textFiles = Enumerable.Range(0, NumConcurrent).Select(i => allFiles[i % allFiles.Length]); // To solve the exercise, you may need to pass additional synchronisation information to the constructor. var counters = textFiles.Select(textFile => new LimitedModeCharacterCounter(textFile)).ToArray(); return counters; } } }
Add an Explicit test that tries to use AsParallel(). It will hang after the exercise is completed, if the solution is the same as mine.
Add an Explicit test that tries to use AsParallel(). It will hang after the exercise is completed, if the solution is the same as mine.
C#
apache-2.0
peterchase/parallel-workshop
75acaeb22853b5eb82077e11e7f21ec569e1f5cd
Creative/StatoBot/StatoBot.Analytics/AnalyzerBot.cs
Creative/StatoBot/StatoBot.Analytics/AnalyzerBot.cs
using System; using System.IO; using System.Timers; using StatoBot.Core; namespace StatoBot.Analytics { public class AnalyzerBot : TwitchBot { public ChatAnalyzer Analyzer; public AnalyzerBot(Credentials credentials, string channel) : base(credentials, channel) { Analyzer = new ChatAnalyzer(); OnMessageReceived += AnalyzeMessage; } private void AnalyzeMessage(object sender, OnMessageReceivedEventArgs args) { Analyzer .AnalyzeAsync(args) .Start(); } } }
using System; using System.IO; using System.Timers; using System.Threading.Tasks; using StatoBot.Core; namespace StatoBot.Analytics { public class AnalyzerBot : TwitchBot { public ChatAnalyzer Analyzer; public AnalyzerBot(Credentials credentials, string channel) : base(credentials, channel) { Analyzer = new ChatAnalyzer(); OnMessageReceived += AnalyzeMessage; } private void AnalyzeMessage(object sender, OnMessageReceivedEventArgs args) { Task.Run(() => Analyzer .AnalyzeAsync(args) ); } } }
Use Task.Run instead of .Start()
Use Task.Run instead of .Start()
C#
mit
FetzenRndy/Creative,FetzenRndy/Creative,FetzenRndy/Creative,FetzenRndy/Creative,FetzenRndy/Creative
7d76fcf2b64766c14dce7c54c6af03ab0cdb4b37
osu.Game.Rulesets.Catch/Edit/Blueprints/CatchPlacementBlueprint.cs
osu.Game.Rulesets.Catch/Edit/Blueprints/CatchPlacementBlueprint.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.UI.Scrolling; namespace osu.Game.Rulesets.Catch.Edit.Blueprints { public class CatchPlacementBlueprint<THitObject> : PlacementBlueprint where THitObject : CatchHitObject, new() { protected new THitObject HitObject => (THitObject)base.HitObject; protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer; [Resolved] private Playfield playfield { get; set; } public CatchPlacementBlueprint() : base(new THitObject()) { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Catch.Edit.Blueprints { public class CatchPlacementBlueprint<THitObject> : PlacementBlueprint where THitObject : CatchHitObject, new() { protected new THitObject HitObject => (THitObject)base.HitObject; protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer; [Resolved] private Playfield playfield { get; set; } public CatchPlacementBlueprint() : base(new THitObject()) { } public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true; } }
Fix hit object placement not receiving input when outside playfield
Fix hit object placement not receiving input when outside playfield The input area is vertical infinite, but horizontally restricted to the playfield due to `CatchPlayfield`'s `ReceivePositionalInputAt` override.
C#
mit
peppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new
8f375dc9eed097d9921deb60d03d829cba7a16ab
WTM.Api/Controllers/UserController.cs
WTM.Api/Controllers/UserController.cs
using System.Web.Http; using WTM.Core.Services; using WTM.Crawler; using WTM.Crawler.Services; using WTM.Domain; namespace WTM.Api.Controllers { public class UserController : ApiController { private readonly IUserService userService; public UserController() { var webClient = new WebClientWTM(); var htmlParser = new HtmlParser(); userService = new UserService(webClient, htmlParser); } public UserController(IUserService userService) { this.userService = userService; } // GET api/User/Login?username={username}&password={password} [Route("api/User/Login")] [HttpGet] public User Login([FromUri]string username, [FromUri]string password) { return userService.Login(username, password); } } }
using System.Collections.Generic; using System.Linq; using System.Web.Http; using WTM.Core.Services; using WTM.Crawler; using WTM.Crawler.Services; using WTM.Domain; namespace WTM.Api.Controllers { public class UserController : ApiController { private readonly IUserService userService; public UserController() { var webClient = new WebClientWTM(); var htmlParser = new HtmlParser(); userService = new UserService(webClient, htmlParser); } public UserController(IUserService userService) { this.userService = userService; } // GET api/User/Login?username={username}&password={password} [Route("api/User/Login")] [HttpGet] public User Login([FromUri]string username, [FromUri]string password) { return userService.Login(username, password); } [Route("api/User/{username}")] [HttpGet] public User Get(string username) { return userService.GetByUsername(username); } //[Route("api/User/Search")] [HttpGet] public List<UserSummary> Search(string search, [FromUri]int? page = null) { return userService.Search(search, page).ToList(); } } }
Add methods intto User Api
Add methods intto User Api
C#
mit
skacofonix/WhatTheMovie,skacofonix/WhatTheMovie,skacofonix/WhatTheMovie
0446d2d14e915956ae9e0d27ea2d229f53ed625d
src/Parsley/ReadOnlySpanExtensions.cs
src/Parsley/ReadOnlySpanExtensions.cs
namespace Parsley; public static class ReadOnlySpanExtensions { public static ReadOnlySpan<char> Peek(this ref ReadOnlySpan<char> input, int length) => length >= input.Length ? input.Slice(0) : input.Slice(0, length); public static void Advance(this ref ReadOnlySpan<char> input, ref int index, int length) { var traversed = input.Peek(length); input = input.Slice(traversed.Length); index += traversed.Length; } public static ReadOnlySpan<char> TakeWhile(this ref ReadOnlySpan<char> input, Predicate<char> test) { int i = 0; while (i < input.Length && test(input[i])) i++; return input.Peek(i); } }
namespace Parsley; public static class ReadOnlySpanExtensions { public static ReadOnlySpan<char> Peek(this ref ReadOnlySpan<char> input, int length) => length >= input.Length ? input.Slice(0) : input.Slice(0, length); public static void Advance(this ref ReadOnlySpan<char> input, ref int index, int length) { var traversed = length >= input.Length ? input.Length : length; input = input.Slice(traversed); index += traversed; } public static ReadOnlySpan<char> TakeWhile(this ref ReadOnlySpan<char> input, Predicate<char> test) { int i = 0; while (i < input.Length && test(input[i])) i++; return input.Peek(i); } }
Reduce the number of slice operations performed during an Advance, when those slices were used only for their length.
Reduce the number of slice operations performed during an Advance, when those slices were used only for their length.
C#
mit
plioi/parsley
2ef5aa84350f2ae3b72eddf1cecd2c53921d5372
src/Glimpse.Agent.Web/Framework/DefaultRequestIgnorerManager.cs
src/Glimpse.Agent.Web/Framework/DefaultRequestIgnorerManager.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Http; namespace Glimpse.Agent.Web { public class DefaultRequestIgnorerManager : IRequestIgnorerManager { public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor) { RequestIgnorers = requestIgnorerProvider.Instances; HttpContextAccessor = httpContextAccessor; } private IEnumerable<IRequestIgnorer> RequestIgnorers { get; } private IHttpContextAccessor HttpContextAccessor { get; } public bool ShouldIgnore() { return ShouldIgnore(HttpContextAccessor.HttpContext); } public bool ShouldIgnore(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (RequestIgnorers.Any()) { foreach (var policy in RequestIgnorers) { if (policy.ShouldIgnore(context)) { return true; } } } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Http; using Microsoft.AspNet.JsonPatch.Helpers; namespace Glimpse.Agent.Web { public class DefaultRequestIgnorerManager : IRequestIgnorerManager { public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor) { RequestIgnorers = requestIgnorerProvider.Instances; HttpContextAccessor = httpContextAccessor; } private IEnumerable<IRequestIgnorer> RequestIgnorers { get; } private IHttpContextAccessor HttpContextAccessor { get; } public bool ShouldIgnore() { return ShouldIgnore(HttpContextAccessor.HttpContext); } public bool ShouldIgnore(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var result = GetCachedResult(context); if (result == null) { if (RequestIgnorers.Any()) { foreach (var policy in RequestIgnorers) { if (policy.ShouldIgnore(context)) { result = true; break; } } } if (!result.HasValue) { result = false; } SetCachedResult(context, result); } return result.Value; } private bool? GetCachedResult(HttpContext context) { return context.Items["Glimpse.ShouldIgnoreRequest"] as bool?; } private void SetCachedResult(HttpContext context, bool? value) { context.Items["Glimpse.ShouldIgnoreRequest"] = value; } } }
Introduce caching of ShouldIgnore request so that the ignorer pipeline is only executed once per request
Introduce caching of ShouldIgnore request so that the ignorer pipeline is only executed once per request
C#
mit
peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype
e5631bb8ef7657a84529d72b571b9b41448a8b0c
Akavache/Portable/DependencyResolverMixin.cs
Akavache/Portable/DependencyResolverMixin.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Splat; namespace Akavache { internal interface IWantsToRegisterStuff { void Register(IMutableDependencyResolver resolverToUse); } public static class DependencyResolverMixin { /// <summary> /// Initializes a ReactiveUI dependency resolver with classes that /// Akavache uses internally. /// </summary> public static void InitializeAkavache(this IMutableDependencyResolver This) { var namespaces = new[] { "Akavache", "Akavache.Mac", "Akavache.Mobile", "Akavache.Sqlite3", }; var fdr = typeof(DependencyResolverMixin); var assmName = new AssemblyName( fdr.AssemblyQualifiedName.Replace(fdr.FullName + ", ", "")); foreach (var ns in namespaces) { var targetType = ns + ".Registrations"; string fullName = targetType + ", " + assmName.FullName.Replace(assmName.Name, ns); var registerTypeClass = Type.GetType(fullName, false); if (registerTypeClass == null) continue; var registerer = (IWantsToRegisterStuff)Activator.CreateInstance(registerTypeClass); registerer.Register(This); }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Splat; namespace Akavache { internal interface IWantsToRegisterStuff { void Register(IMutableDependencyResolver resolverToUse); } public static class DependencyResolverMixin { /// <summary> /// Initializes a ReactiveUI dependency resolver with classes that /// Akavache uses internally. /// </summary> public static void InitializeAkavache(this IMutableDependencyResolver This) { var namespaces = new[] { "Akavache", "Akavache.Mac", "Akavache.Deprecated", "Akavache.Mobile", "Akavache.Http", "Akavache.Sqlite3", }; var fdr = typeof(DependencyResolverMixin); var assmName = new AssemblyName( fdr.AssemblyQualifiedName.Replace(fdr.FullName + ", ", "")); foreach (var ns in namespaces) { var targetType = ns + ".Registrations"; string fullName = targetType + ", " + assmName.FullName.Replace(assmName.Name, ns); var registerTypeClass = Type.GetType(fullName, false); if (registerTypeClass == null) continue; var registerer = (IWantsToRegisterStuff)Activator.CreateInstance(registerTypeClass); registerer.Register(This); }; } } }
Make sure we register stuff
Make sure we register stuff
C#
mit
akavache/Akavache,MarcMagnin/Akavache,bbqchickenrobot/Akavache,gimsum/Akavache,jcomtois/Akavache,PureWeen/Akavache,Loke155/Akavache,christer155/Akavache,martijn00/Akavache,ghuntley/AkavacheSandpit,shana/Akavache,mms-/Akavache,shana/Akavache,MathieuDSTP/MyAkavache,kmjonmastro/Akavache
cad0aed18b445a24a65c1fb699eb8eec12c3d4bf
Krs.Ats.IBNet/Enums/SecurityType.cs
Krs.Ats.IBNet/Enums/SecurityType.cs
using System; using System.ComponentModel; namespace Krs.Ats.IBNet { /// <summary> /// Contract Security Types /// </summary> [Serializable()] public enum SecurityType { /// <summary> /// Stock /// </summary> [Description("STK")] Stock, /// <summary> /// Option /// </summary> [Description("OPT")] Option, /// <summary> /// Future /// </summary> [Description("FUT")] Future, /// <summary> /// Indice /// </summary> [Description("IND")] Index, /// <summary> /// FOP = options on futures /// </summary> [Description("FOP")] FutureOption, /// <summary> /// Cash /// </summary> [Description("CASH")] Cash, /// <summary> /// For Combination Orders - must use combo leg details /// </summary> [Description("BAG")] Bag, /// <summary> /// Bond /// </summary> [Description("BOND")] Bond, /// <summary> /// Undefined Security Type /// </summary> [Description("")] Undefined } }
using System; using System.ComponentModel; namespace Krs.Ats.IBNet { /// <summary> /// Contract Security Types /// </summary> [Serializable()] public enum SecurityType { /// <summary> /// Stock /// </summary> [Description("STK")] Stock, /// <summary> /// Option /// </summary> [Description("OPT")] Option, /// <summary> /// Future /// </summary> [Description("FUT")] Future, /// <summary> /// Indice /// </summary> [Description("IND")] Index, /// <summary> /// FOP = options on futures /// </summary> [Description("FOP")] FutureOption, /// <summary> /// Cash /// </summary> [Description("CASH")] Cash, /// <summary> /// For Combination Orders - must use combo leg details /// </summary> [Description("BAG")] Bag, /// <summary> /// Bond /// </summary> [Description("BOND")] Bond, /// <summary> /// Warrant /// </summary> [Description("WAR")] Warrant, /// <summary> /// Undefined Security Type /// </summary> [Description("")] Undefined } }
Add the warrant security type.
Add the warrant security type.
C#
mit
krs43/ib-csharp,qusma/ib-csharp,sebfia/ib-csharp
8afeb4d0943688ac267679c10e6c744e167275b2
Content.Shared/Utility/TemperatureHelpers.cs
Content.Shared/Utility/TemperatureHelpers.cs
using Content.Shared.Maths; namespace Content.Shared.Utility { public static class TemperatureHelpers { public static float CelsiusToKelvin(float celsius) { return celsius + PhysicalConstants.ZERO_CELCIUS; } public static float KelvinToCelsius(float kelvin) { return kelvin - PhysicalConstants.ZERO_CELCIUS; } } }
using Content.Shared.Maths; namespace Content.Shared.Utility { public static class TemperatureHelpers { public static float CelsiusToKelvin(float celsius) { return celsius + PhysicalConstants.ZERO_CELCIUS; } public static float CelsiusToFahrenheit(float celsius) { return celsius * 9 / 5 + 32; } public static float KelvinToCelsius(float kelvin) { return kelvin - PhysicalConstants.ZERO_CELCIUS; } public static float KelvinToFahrenheit(float kelvin) { var celsius = KelvinToCelsius(kelvin); return CelsiusToFahrenheit(celsius); } public static float FahrenheitToCelsius(float fahrenheit) { return (fahrenheit - 32) * 5 / 9; } public static float FahrenheitToKelvin(float fahrenheit) { var celsius = FahrenheitToCelsius(fahrenheit); return CelsiusToKelvin(celsius); } } }
Add helpers for converting to and from Fahrenheit
Add helpers for converting to and from Fahrenheit
C#
mit
space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
5496e7204acb157c400b15282cbeefa135aef48c
ElectronicCash.Tests/SecretSplittingTests.cs
ElectronicCash.Tests/SecretSplittingTests.cs
using NUnit.Framework; using SecretSplitting; namespace ElectronicCash.Tests { [TestFixture] class SecretSplittingTests { private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage"); private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char)); private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes); [Test] public void OnSplit_OriginalMessageShouldBeRecoverable() { _splitter.SplitSecretBetweenTwoPeople(); var r = _splitter.R; var s = _splitter.S; var m = Helpers.ExclusiveOr(r, s); Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message)); } } }
using NUnit.Framework; using SecretSplitting; namespace ElectronicCash.Tests { [TestFixture] class SecretSplittingTests { private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage"); private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char)); private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes); [Test] public void OnSplit_OriginalMessageShouldBeRecoverable() { _splitter.SplitSecretBetweenTwoPeople(); var r = _splitter.R; var s = _splitter.S; var m = Helpers.ExclusiveOr(r, s); Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message)); } [Test] public void OnSecretSplit_FlagsShouldBeTrue() { var splitter = new SecretSplittingProvider(Message, RandBytes); splitter.SplitSecretBetweenTwoPeople(); Assert.IsTrue(splitter.IsRProtected); Assert.IsTrue(splitter.IsSProtected); Assert.IsTrue(splitter.IsSecretMessageProtected); } } }
Write some more tests for secret splitting
Write some more tests for secret splitting
C#
mit
0culus/ElectronicCash
44af2f94d7bc5d07dc43e7d0f5e63eae8ca47c7e
Plugins/FileTypes/RtfFile/RtfFileExporter.cs
Plugins/FileTypes/RtfFile/RtfFileExporter.cs
#region using System; using System.Drawing; using System.Windows.Forms; using Tabster.Data; using Tabster.Data.Processing; #endregion namespace RtfFile { internal class RtfFileExporter : ITablatureFileExporter { private Font _font; private RichTextBox _rtb; #region Implementation of ITablatureFileExporter public FileType FileType { get; private set; } public Version Version { get { return new Version("1.0"); } } public void Export(ITablatureFile file, string fileName) { if (_font == null) _font = new Font("Courier New", 9F); if (_rtb == null) _rtb = new RichTextBox {Font = new Font("Courier New", 9F), Text = file.Contents}; _rtb.SaveFile(fileName); _rtb.SaveFile(fileName); //have to call method twice otherwise empty file is created } #endregion public RtfFileExporter() { FileType = new FileType("Rich Text Format File", ".rtf"); } ~RtfFileExporter() { if (_font != null) _font.Dispose(); if (_rtb != null && !_rtb.IsDisposed) _rtb.Dispose(); } } }
#region using System; using System.Drawing; using System.Windows.Forms; using Tabster.Data; using Tabster.Data.Processing; #endregion namespace RtfFile { internal class RtfFileExporter : ITablatureFileExporter { private RichTextBox _rtb; #region Implementation of ITablatureFileExporter public FileType FileType { get; private set; } public Version Version { get { return new Version("1.0"); } } public void Export(ITablatureFile file, string fileName, TablatureFileExportArguments args) { if (_rtb == null) _rtb = new RichTextBox {Font = args.Font, Text = file.Contents}; _rtb.SaveFile(fileName); _rtb.SaveFile(fileName); //have to call method twice otherwise empty file is created } #endregion public RtfFileExporter() { FileType = new FileType("Rich Text Format File", ".rtf"); } ~RtfFileExporter() { if (_rtb != null && !_rtb.IsDisposed) _rtb.Dispose(); } } }
Use specified font for RTF exporting
Use specified font for RTF exporting
C#
apache-2.0
GetTabster/Tabster
c084fb800a659f41ac7e86dc49d14122c43bd082
src/BuildingBlocks.CopyManagement/SmartClientApplicationIdentity.cs
src/BuildingBlocks.CopyManagement/SmartClientApplicationIdentity.cs
using System; namespace BuildingBlocks.CopyManagement { public class SmartClientApplicationIdentity : IApplicationIdentity { private static readonly Lazy<IApplicationIdentity> _current; static SmartClientApplicationIdentity() { _current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true); } public static IApplicationIdentity Current { get { return _current.Value; } } private static readonly Guid _instanceId = Guid.NewGuid(); private readonly string _applicationUid; private readonly string _mashineId; private readonly DateTime _instanceStartTime; private SmartClientApplicationIdentity() { _instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime; _applicationUid = ComputeApplicationId(); _mashineId = ComputerId.Value.ToFingerPrintMd5Hash(); } public Guid InstanceId { get { return _instanceId; } } public string ApplicationUid { get { return _applicationUid; } } public string MashineId { get { return _mashineId; } } public DateTime InstanceStartTime { get { return _instanceStartTime; } } public string LicenceKey { get; private set; } private static string ComputeApplicationId() { var exeFileName = System.Reflection.Assembly.GetEntryAssembly().Location; var value = "EXE_PATH >> " + exeFileName + "\n" + ComputerId.Value; return value.ToFingerPrintMd5Hash(); } } }
using System; namespace BuildingBlocks.CopyManagement { public class SmartClientApplicationIdentity : IApplicationIdentity { private static readonly Lazy<IApplicationIdentity> _current; static SmartClientApplicationIdentity() { _current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true); } public static IApplicationIdentity Current { get { return _current.Value; } } private static readonly Guid _instanceId = Guid.NewGuid(); private readonly string _applicationUid; private readonly string _mashineId; private readonly DateTime _instanceStartTime; private SmartClientApplicationIdentity() { _instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime; _applicationUid = ComputeApplicationId(); _mashineId = ComputerId.Value.ToFingerPrintMd5Hash(); } public Guid InstanceId { get { return _instanceId; } } public string ApplicationUid { get { return _applicationUid; } } public string MashineId { get { return _mashineId; } } public DateTime InstanceStartTime { get { return _instanceStartTime; } } public string LicenceKey { get; private set; } private static string ComputeApplicationId() { return ComputerId.Value.ToFingerPrintMd5Hash(); } } }
Disable adding redundant arguments for getting machine id
Disable adding redundant arguments for getting machine id
C#
apache-2.0
ifilipenko/Building-Blocks,ifilipenko/Building-Blocks,ifilipenko/Building-Blocks
38fcc693c01f0fde2c164e5cca616dd4fc88db38
ChamberLib.OpenTK/GlslShaderImporter.cs
ChamberLib.OpenTK/GlslShaderImporter.cs
using System; using ChamberLib.Content; using System.IO; namespace ChamberLib.OpenTK { public class GlslShaderImporter { public GlslShaderImporter(ShaderStageImporter next=null) { this.next = next; } readonly ShaderStageImporter next; public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer) { if (File.Exists(filename)) { } else if (type == ShaderType.Vertex && File.Exists(filename + ".vert")) { filename += ".vert"; } else if (type == ShaderType.Fragment && File.Exists(filename + ".frag")) { filename += ".frag"; } else if (next != null) { return next(filename, type, importer); } else { throw new FileNotFoundException( string.Format( "The {0} shader file could not be found: {1}", type, filename), filename); } var source = File.ReadAllText(filename); return new ShaderContent( vs: (type == ShaderType.Vertex ? source : null), fs: (type == ShaderType.Fragment ? source : null), name: filename, type: ShaderType.Vertex); } } }
using System; using ChamberLib.Content; using System.IO; namespace ChamberLib.OpenTK { public class GlslShaderImporter { public GlslShaderImporter(ShaderStageImporter next=null) { this.next = next; } readonly ShaderStageImporter next; public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer) { if (File.Exists(filename)) { } else if (type == ShaderType.Vertex && File.Exists(filename + ".vert")) { filename += ".vert"; } else if (type == ShaderType.Fragment && File.Exists(filename + ".frag")) { filename += ".frag"; } else if (next != null) { return next(filename, type, importer); } else { throw new FileNotFoundException( string.Format( "The {0} shader file could not be found: {1}", type, filename), filename); } var source = File.ReadAllText(filename); return new ShaderContent( vs: (type == ShaderType.Vertex ? source : null), fs: (type == ShaderType.Fragment ? source : null), name: filename, type: type); } } }
Set the right shader type.
Set the right shader type.
C#
lgpl-2.1
izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib
899942611fcb085fc09226c84a7bbbd47500450f
osu.Game.Tournament.Tests/Screens/TestSceneScheduleScreen.cs
osu.Game.Tournament.Tests/Screens/TestSceneScheduleScreen.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Schedule; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneScheduleScreen : TournamentTestScene { [BackgroundDependencyLoader] private void load() { Add(new TourneyVideo("main") { RelativeSizeAxes = Axes.Both }); Add(new ScheduleScreen()); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Schedule; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneScheduleScreen : TournamentTestScene { [BackgroundDependencyLoader] private void load() { Add(new TourneyVideo("main") { RelativeSizeAxes = Axes.Both }); Add(new ScheduleScreen()); } [Test] public void TestCurrentMatchTime() { setMatchDate(TimeSpan.FromDays(-1)); setMatchDate(TimeSpan.FromSeconds(5)); setMatchDate(TimeSpan.FromMinutes(4)); setMatchDate(TimeSpan.FromHours(3)); } private void setMatchDate(TimeSpan relativeTime) // Humanizer cannot handle negative timespans. => AddStep($"start time is {relativeTime}", () => { var match = CreateSampleMatch(); match.Date.Value = DateTimeOffset.Now + relativeTime; Ladder.CurrentMatch.Value = match; }); } }
Add tests for time display
Add tests for time display
C#
mit
ppy/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu
4f79d6d63cf6cdabd50f8ebf4e9b6acc709d08f2
uSync.Core/uSyncCapabilityChecker.cs
uSync.Core/uSyncCapabilityChecker.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Cms.Core.Configuration; namespace uSync.Core { /// <summary> /// a centralized way of telling if the current version of umbraco has /// certain features or not. /// </summary> public class uSyncCapabilityChecker { private readonly IUmbracoVersion _version; public uSyncCapabilityChecker(IUmbracoVersion version) { _version = version; } /// <summary> /// History cleanup was introduced in Umbraco 9.1 /// </summary> /// <remarks> /// anything above v9.1 has history cleanup. /// </remarks> public bool HasHistoryCleanup => _version.Version.Major != 9 || _version.Version.Minor >= 1; /// <summary> /// Has a runtime mode introduced in v10.1 /// </summary> /// <remarks> /// Runtime mode of Production means you can't update views etc. /// </remarks> public bool HasRuntimeMode => _version.Version.Major > 10 || _version.Version.Major == 10 && _version.Version.Minor > 1; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Cms.Core.Configuration; namespace uSync.Core { /// <summary> /// a centralized way of telling if the current version of umbraco has /// certain features or not. /// </summary> public class uSyncCapabilityChecker { private readonly IUmbracoVersion _version; public uSyncCapabilityChecker(IUmbracoVersion version) { _version = version; } /// <summary> /// History cleanup was introduced in Umbraco 9.1 /// </summary> /// <remarks> /// anything above v9.1 has history cleanup. /// </remarks> public bool HasHistoryCleanup => _version.Version.Major != 9 || _version.Version.Minor >= 1; /// <summary> /// Has a runtime mode introduced in v10.1 /// </summary> /// <remarks> /// Runtime mode of Production means you can't update views etc. /// </remarks> public bool HasRuntimeMode => _version.Version.Major > 10 || _version.Version.Major == 10 && _version.Version.Minor > 1; /// <summary> /// User groups has Language Permissions - introduced in Umbraco 10.2.0 /// </summary> public bool HasGroupLanguagePermissions => _version.Version >= new Version(10, 2, 0); } }
Update compatibility checks for user language permissions
Update compatibility checks for user language permissions
C#
mpl-2.0
KevinJump/uSync,KevinJump/uSync,KevinJump/uSync
07d9e864506794d93a03bc68efd825d935013e8f
samples/IdentitySample.Mvc/Views/Shared/_LoginPartial.cshtml
samples/IdentitySample.Mvc/Views/Shared/_LoginPartial.cshtml
@using System.Security.Principal @if (User.IsSignedIn()) { using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) { @Html.AntiForgeryToken() <ul class="nav navbar-nav navbar-right"> <li> @Html.ActionLink("Hello " + User.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" }) </li> <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li> </ul> } } else { <ul class="nav navbar-nav navbar-right"> <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li> <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> </ul> }
@using System.Security.Claims @if (User.IsSignedIn()) { using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) { @Html.AntiForgeryToken() <ul class="nav navbar-nav navbar-right"> <li> @Html.ActionLink("Hello " + User.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" }) </li> <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li> </ul> } } else { <ul class="nav navbar-nav navbar-right"> <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li> <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> </ul> }
Correct namespace to fix failure
Correct namespace to fix failure
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore