commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
042cb082ff79fdd538316d4bd1653b464fdd175b
Update DisposableProgress.cs
tiksn/TIKSN-Framework
TIKSN.Core/Progress/DisposableProgress.cs
TIKSN.Core/Progress/DisposableProgress.cs
using System; namespace TIKSN.Progress { public class DisposableProgress<T> : Progress<T>, IDisposable { public virtual void Dispose() { } } }
using System; namespace TIKSN.Progress { public class DisposableProgress<T> : Progress<T>, IDisposable { public virtual void Dispose() { } } }
mit
C#
45ea870f0619877693bef39f9b71612b48575c8e
Complete reading of rom header by reading rom size
eightlittlebits/elbsms
elbsms_core/Memory/CartridgeHeader.cs
elbsms_core/Memory/CartridgeHeader.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; namespace elbsms_core.Memory { public enum RegionCode { [Description("SMS Japan")] SMSJapan = 0x03, [Description("SMS Export")] SMSExport = 0x04, [Description("GG Japan")] GGJapan = 0x05, [Description("GG Export")] GGExport = 0x06, [Description("GG International")] GGInternational = 0x07, } public class CartridgeHeader { private static readonly Dictionary<int, (string Description, uint Size)> RomSizes = new Dictionary<int, (string, uint)> { { 0x0A, ("8KB", 0x2000) }, { 0x0B, ("16KB", 0x4000) }, { 0x0C, ("32KB", 0x8000) }, { 0x0D, ("48KB", 0xC000) }, { 0x0E, ("64KB", 0x10000) }, { 0x0F, ("128KB", 0x20000) }, { 0x00, ("256KB", 0x40000) }, { 0x01, ("512KB", 0x80000) }, { 0x02, ("1MB", 0x100000) }, }; public string Header; public int Checksum; public int ProductCode; public int Version; public RegionCode Region; public int RomSize; public int ActualRomSize; public bool RomSizeValid => RomSizes[RomSize].Size == ActualRomSize; public string RomSizeDescription => RomSizes[RomSize].Description; public CartridgeHeader(byte[] romData) { Header = Encoding.ASCII.GetString(romData, 0x7FF0, 8); Checksum = BitConverter.ToUInt16(romData, 0x7FFA); ProductCode = ReadProductCode(romData, 0x7FFC); Version = romData[0x7FFE] & 0x0F; Region = (RegionCode)(romData[0x7FFF] >> 4); RomSize = romData[0x7FFF] & 0x0F; ActualRomSize = romData.Length; } private int ReadProductCode(byte[] romData, int index) { return DecodeBCD(new byte[] { romData[index], romData[index + 1], (byte)(romData[index + 2] >> 4) }); } // https://stackoverflow.com/a/11701256/223708 private int DecodeBCD(byte[] data) { int result = 0; for (int i = data.Length - 1; i >= 0; i--) { result *= 100; result += (10 * (data[i] >> 4)); result += data[i] & 0x0F; } return result; } } }
using System; using System.ComponentModel; using System.Text; namespace elbsms_core.Memory { public enum RegionCode { [Description("SMS Japan")] SMSJapan = 0x03, [Description("SMS Export")] SMSExport = 0x04, [Description("GG Japan")] GGJapan = 0x05, [Description("GG Export")] GGExport = 0x06, [Description("GG International")] GGInternational = 0x07, } public class CartridgeHeader { public string Header; public int Checksum; public int ProductCode; public int Version; public RegionCode Region; public int HeaderRomSize; public int ActualRomSize; public CartridgeHeader(byte[] romData) { Header = Encoding.ASCII.GetString(romData, 0x7FF0, 8); Checksum = BitConverter.ToUInt16(romData, 0x7FFA); ProductCode = ReadProductCode(romData, 0x7FFC); Version = romData[0x7FFE] & 0x0F; Region = (RegionCode)(romData[0x7FFF] >> 4); // TODO(david): Read size from the cartridge header ActualRomSize = romData.Length; } private int ReadProductCode(byte[] romData, int index) { return DecodeBCD(new byte[] { romData[index], romData[index + 1], (byte)(romData[index + 2] >> 4) }); } // https://stackoverflow.com/a/11701256/223708 private int DecodeBCD(byte[] data) { int result = 0; for (int i = data.Length - 1; i >= 0; i--) { result *= 100; result += (10 * (data[i] >> 4)); result += data[i] & 0x0F; } return result; } } }
mit
C#
da461e83aeaf144da8cda17fd333fd37639d4371
Initialize log4net in MVC app base class
djMax/AlienForce
Utilities/Web/AlienForceMvcApplication.cs
Utilities/Web/AlienForceMvcApplication.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using System.Web.Routing; using System.Reflection; using AlienForce.Utilities.DataAnnotations; using AlienForce.Utilities.DataAnnotations.Resources; using AlienForce.Utilities.Billing; using System.ComponentModel; namespace AlienForce.Utilities.Web { public class AlienForceMvcApplication : System.Web.HttpApplication { public virtual void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoutes(Assembly.GetCallingAssembly()); } public virtual void RegisterRoutes(RouteCollection routes, Assembly assembly) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoutes(assembly); } protected virtual void Application_Start() { Logging.LogFramework.Framework.Initialize(); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(System.Web.Mvc.RequiredAttributeAdapter)); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthAttribute), typeof(System.Web.Mvc.StringLengthAttributeAdapter)); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(System.Web.Mvc.RegularExpressionAttributeAdapter)); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute), typeof(System.Web.Mvc.RangeAttributeAdapter)); System.ComponentModel.TypeDescriptor.AddAttributes(typeof(CreditCardNumber), new TypeConverterAttribute(typeof(CreditCardNumberTypeConverter))); System.ComponentModel.TypeDescriptor.AddAttributes(typeof(ExpirationDate), new TypeConverterAttribute(typeof(ExpirationDateTypeConverter))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using System.Web.Routing; using System.Reflection; using AlienForce.Utilities.DataAnnotations; using AlienForce.Utilities.DataAnnotations.Resources; using AlienForce.Utilities.Billing; using System.ComponentModel; namespace AlienForce.Utilities.Web { public class AlienForceMvcApplication : System.Web.HttpApplication { public virtual void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoutes(Assembly.GetCallingAssembly()); } public virtual void RegisterRoutes(RouteCollection routes, Assembly assembly) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoutes(assembly); } protected virtual void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(System.Web.Mvc.RequiredAttributeAdapter)); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthAttribute), typeof(System.Web.Mvc.StringLengthAttributeAdapter)); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(System.Web.Mvc.RegularExpressionAttributeAdapter)); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute), typeof(System.Web.Mvc.RangeAttributeAdapter)); System.ComponentModel.TypeDescriptor.AddAttributes(typeof(CreditCardNumber), new TypeConverterAttribute(typeof(CreditCardNumberTypeConverter))); System.ComponentModel.TypeDescriptor.AddAttributes(typeof(ExpirationDate), new TypeConverterAttribute(typeof(ExpirationDateTypeConverter))); } } }
mit
C#
a9aaa64f625b26da62cae500c17a75cbbd3b63b4
Update ColorPair.cs (#2086)
ButchersBoy/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit
MaterialDesignColors.Wpf/ColorPair.cs
MaterialDesignColors.Wpf/ColorPair.cs
using System.Windows.Media; using MaterialDesignColors.ColorManipulation; namespace MaterialDesignColors { public struct ColorPair { public Color Color { get; set; } /// <summary> /// The foreground or opposite color. If left null, this will be calculated for you. /// Calculated by calling ColorAssist.ContrastingForegroundColor() /// </summary> public Color? ForegroundColor { get; set; } public static implicit operator ColorPair(Color color) => new ColorPair(color); public ColorPair(Color color) { Color = color; ForegroundColor = null; } public ColorPair(Color color, Color? foreground) { Color = color; ForegroundColor = foreground; } public Color GetForegroundColor() => ForegroundColor ?? Color.ContrastingForegroundColor(); } }
using System.Windows.Media; using MaterialDesignColors.ColorManipulation; namespace MaterialDesignColors { public struct ColorPair { public Color Color { get; set; } /// <summary> /// The foreground or opposite color. If left null, this will be calculated for you. /// Calculated by calling ColorAssist.ContrastingForegroundColor() /// </summary> public Color? ForegroundColor { get; set; } public static implicit operator ColorPair(Color color) => new ColorPair(color); public ColorPair(Color color) { Color = color; ForegroundColor = null; } public ColorPair(Color color, Color? foreground) { Color = color; ForegroundColor = foreground; } public Color GetForegroundColor() => ForegroundColor ?? Color.ContrastingForegroundColor(); } }
mit
C#
ad69ef4330a0211bb02aac35fe324c05c2e8307a
Return type tidy
xcitestudios/csharp-network
com/xcitestudios/Network/Server/Connection/AMQPConnection.cs
com/xcitestudios/Network/Server/Connection/AMQPConnection.cs
namespace com.xcitestudios.Network.Server.Connection { using com.xcitestudios.Network.Server.Configuration; using RabbitMQ.Client; using System.Collections.Generic; /// <summary> /// Helper to connect to AMQP servers. /// </summary> public class AMQPConnection { private static Dictionary<string, object> Connections = new Dictionary<string, object>(); /// <summary> /// Create a connection using the RabbitMQ library /// </summary> /// <param name="configuration"></param> /// <returns>RabbitMQ.Client.IConnection</returns> public static IConnection createConnectionUsingRabbitMQ(AMQPServerConfiguration configuration) { if (!Connections.ContainsKey("RabbitMQ" + configuration.SerializeJSON())) { var factory = new ConnectionFactory(); factory.HostName = configuration.Host; factory.Port = configuration.Port; factory.UserName = configuration.Username; factory.Password = configuration.Password; factory.VirtualHost = configuration.VHost; factory.Protocol = Protocols.AMQP_0_9_1; Connections["RabbitMQ" + configuration.SerializeJSON()] = factory; } return (Connections["RabbitMQ" + configuration.SerializeJSON()] as ConnectionFactory).CreateConnection(); } } }
namespace com.xcitestudios.Network.Server.Connection { using com.xcitestudios.Network.Server.Configuration; using RabbitMQ.Client; using System.Collections.Generic; /// <summary> /// Helper to connect to AMQP servers. /// </summary> public class AMQPConnection { private static Dictionary<string, object> Connections = new Dictionary<string, object>(); /// <summary> /// Create a connection using the RabbitMQ library /// </summary> /// <param name="configuration"></param> /// <returns>IConnection</returns> public static IConnection createConnectionUsingRabbitMQ(AMQPServerConfiguration configuration) { if (!Connections.ContainsKey("RabbitMQ" + configuration.SerializeJSON())) { var factory = new ConnectionFactory(); factory.HostName = configuration.Host; factory.Port = configuration.Port; factory.UserName = configuration.Username; factory.Password = configuration.Password; factory.VirtualHost = configuration.VHost; factory.Protocol = Protocols.AMQP_0_9_1; Connections["RabbitMQ" + configuration.SerializeJSON()] = factory; } return (Connections["RabbitMQ" + configuration.SerializeJSON()] as ConnectionFactory).CreateConnection(); } } }
mit
C#
84521c09041b22b805daea18dae19a1f2e297931
Update SwaggerResultType.cs
quails4Eva/NSwag,quails4Eva/NSwag,aelbatal/NSwag,RSuter/NSwag,RSuter/NSwag,RSuter/NSwag,quails4Eva/NSwag,NSwag/NSwag,NSwag/NSwag,aelbatal/NSwag,RSuter/NSwag,NSwag/NSwag,aelbatal/NSwag,RSuter/NSwag,aelbatal/NSwag,quails4Eva/NSwag,NSwag/NSwag
src/NSwag.Annotations/SwaggerResultType.cs
src/NSwag.Annotations/SwaggerResultType.cs
//----------------------------------------------------------------------- // <copyright file="SwaggerResultTypeAttribute.cs" company="NSwag"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- using System; namespace NSwag.Annotations { /// <summary>Specifies the result type of a web service method to correctly generate a Swagger definition.</summary> public class SwaggerResultTypeAttribute : Attribute { /// <summary>Initializes a new instance of the <see cref="SwaggerResultTypeAttribute"/> class.</summary> /// <param name="resultType">The JSON result type of the MVC or Web API action method.</param> public SwaggerResultTypeAttribute(Type resultType) { ResultType = resultType; // TODO: Check for this attribute on WebAPI methods } /// <summary>Gets or sets the JSON result type of the MVC or Web API action method.</summary> public Type ResultType { get; set; } } }
//----------------------------------------------------------------------- // <copyright file="SwaggerResultTypeAttribute.cs" company="NSwag"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- using System; namespace NSwag.Annotations { /// <summary>Specifies the result type of a web service method to correctly generate a Swagger definition.</summary> public class SwaggerResultTypeAttribute : Attribute { /// <summary>Initializes a new instance of the <see cref="SwaggerResultTypeAttribute"/> class.</summary> /// <param name="resultType">The operation result type.</param> public SwaggerResultTypeAttribute(Type resultType) { ResultType = resultType; // TODO: Check for this attribute on WebAPI methods } /// <summary>Gets or sets the JSON result type of an MVC or Web API action method.</summary> public Type ResultType { get; set; } } }
mit
C#
99b59674615128bd05b75b0586d67a2fa89848ee
Fix code review feedback
skbkontur/NuGetGallery,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,mtian/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,ScottShingler/NuGetGallery,JetBrains/ReSharperGallery,projectkudu/SiteExtensionGallery,JetBrains/ReSharperGallery,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,projectkudu/SiteExtensionGallery,JetBrains/ReSharperGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch
src/NuGetGallery/Views/Users/Thanks.cshtml
src/NuGetGallery/Views/Users/Thanks.cshtml
@{ ViewBag.Title = "Thanks"; } <h1 class="page-heading"> Thank you for registering, @CurrentUser.Username! </h1> <h2>Now that you have a NuGet.org account you might like to...</h2> <ul> <li> <p> <a href="@Url.Action("Account", "Users")">View your profile</a> to update your email address or get your API key. </p> </li> <li> <p> <a href="@Url.ConfirmationRequired()">Confirm your account</a> so that you can upload packages or contact package owners. </p> </li> <li> <p> <a href="@Url.UploadPackage()">Upload a package</a>. </p> </li> </ul>
@{ ViewBag.Title = "Thanks"; } <h1 class="page-heading"> Thank you for registering, @CurrentUser.Username! </h1> <h2>Now that you have a NuGet.org account you might like to...</h2> <ul> <li> <p> <a href="@Url.Action("Account", "Users")">View your profile</a> to update your email address or get your API key for pushing packages. </p> </li> <li> <p> <a href="@Url.ConfirmationRequired()">Confirm your account</a> so that you can upload packages or contact package owners. </p> </li> <li> <p> <a href="@Url.UploadPackage()">Upload a package</a>. </p> </li> </ul>
apache-2.0
C#
be477df44b1418631dfc447ddadf5036c4aecb6c
Fix some stuff I missed
chraft/c-raft
Chraft.Plugins.SamplePlugin/SamplePlugin.cs
Chraft.Plugins.SamplePlugin/SamplePlugin.cs
using System; using Chraft.Plugins.Events; namespace Chraft.Plugins.SamplePlugin { [Plugin] public class SamplePlugin : IPlugin { private SamplePluginPlayerListener playerListener; private SamplePluginEntitiyListener entitiyListener; public string Name { get { return "SamplePlugin"; } } public string Author { get { return "C#raft Team"; } } public string Description { get { return "Sample Plugin"; } } public string Website { get { return "http://www.c-raft.com"; } } public Version Version { get; private set; } public Server Server { get; set; } public PluginManager PluginManager { get; set; } public bool IsPluginEnabled { get; set; } public void Initialize() { playerListener = new SamplePluginPlayerListener(this); entitiyListener = new SamplePluginEntitiyListener(this); } public void Associate(Server server, PluginManager pluginManager) { Server = server; PluginManager = pluginManager; } public void OnEnabled() { IsPluginEnabled = true; PluginManager.RegisterEvent(Event.PLAYER_CHAT, playerListener, this); PluginManager.RegisterEvent(Event.PLAYER_DIED, playerListener, this); PluginManager.RegisterEvent(Event.ENTITY_SPAWN, entitiyListener, this); Console.WriteLine(Name + " " + Version + " Enabled"); } public void OnDisabled() { IsPluginEnabled = false; PluginManager.UnregisterEvent(Event.PLAYER_CHAT, playerListener, this); PluginManager.UnregisterEvent(Event.PLAYER_DIED, playerListener, this); PluginManager.UnregisterEvent(Event.ENTITY_SPAWN, entitiyListener, this); Console.WriteLine(Name + " " + Version + " Disabled"); } } }
using System; using Chraft.Plugins.Events; namespace Chraft.Plugins.SamplePlugin { [Plugin] public class SamplePlugin : IPlugin { private SamplePluginPlayerListener playerListener; private SamplePluginEntitiyListener entitiyListener; public string Name { get { return "SamplePlugin"; } } public string Author { get { return "C#raft Team"; } } public string Description { get { return "Sample Plugin"; } } public string Website { get { return "http://www.c-raft.com"; } } public Version Version { get; private set; } public Server Server { get; set; } public PluginManager PluginManager { get; set; } public bool IsPluginEnabled { get; set; } public void Initialize() { playerListener = new SamplePluginPlayerListener(this); } public void Associate(Server server, PluginManager pluginManager) { Server = server; PluginManager = pluginManager; } public void OnEnabled() { PluginManager.RegisterEvent(Event.PLAYER_CHAT, playerListener, this); PluginManager.RegisterEvent(Event.PLAYER_DIED, playerListener, this); PluginManager.RegisterEvent(Event.ENTITY_SPAWN, entitiyListener, this); Console.WriteLine(Name + " " + Version + " Enabled"); } public void OnDisabled() { PluginManager.UnregisterEvent(Event.PLAYER_CHAT, playerListener, this); PluginManager.UnregisterEvent(Event.PLAYER_DIED, playerListener, this); PluginManager.UnregisterEvent(Event.ENTITY_SPAWN, entitiyListener, this); Console.WriteLine(Name + " " + Version + " Disabled"); } } }
agpl-3.0
C#
cef5a9ac4310c378bb9f63acce7e01534cb8b839
Bump version
LouisMT/TeleBotDotNet,Naxiz/TeleBotDotNet
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TeleBotDotNet")] [assembly: AssemblyDescription("Telegram Bot API wrapper for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("U5R")] [assembly: AssemblyProduct("TeleBotDotNet")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdc2c81d-c3e9-40b1-8b21-69796411ad56")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2015.10.4.1")] [assembly: AssemblyFileVersion("2015.10.4.1")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TeleBotDotNet")] [assembly: AssemblyDescription("Telegram Bot API wrapper for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("U5R")] [assembly: AssemblyProduct("TeleBotDotNet")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdc2c81d-c3e9-40b1-8b21-69796411ad56")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2015.9.18.1")] [assembly: AssemblyFileVersion("2015.9.18.1")]
mit
C#
7f123c9d2062d628537d30b2895af11f383c2ebe
Make GameObject.SetEnabled extension method more generic
thijser/ARGAME,thijser/ARGAME,thijser/ARGAME
ARGame/Assets/Scripts/GameObjectUtilities.cs
ARGame/Assets/Scripts/GameObjectUtilities.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace Assets.Scripts { public static class GameObjectUtilities { public static void SetEnabled(this GameObject obj, bool enabled) { // Disable rendering of this component obj.GetComponent<Renderer>().enabled = enabled; // And of its children var subComponents = obj.GetComponentsInChildren<Renderer>(); foreach (var renderer in subComponents) { renderer.enabled = enabled; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace Assets.Scripts { public static class GameObjectUtilities { public static void SetEnabled(this GameObject obj, bool enabled) { // Disable rendering of this component obj.GetComponent<MeshRenderer>().enabled = enabled; // And of its children var subComponents = obj.GetComponentsInChildren<MeshRenderer>(); foreach (var renderer in subComponents) { renderer.enabled = enabled; } } } }
mit
C#
1be42f3c93ad5b49ba5677677918f74044da7016
Remove `UseBundledOnly` MSBuild Option.
OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
src/OmniSharp.MSBuild/Options/MSBuildOptions.cs
src/OmniSharp.MSBuild/Options/MSBuildOptions.cs
namespace OmniSharp.Options { public class MSBuildOptions { public string ToolsVersion { get; set; } public string VisualStudioVersion { get; set; } public string Configuration { get; set; } public string Platform { get; set; } public bool EnablePackageAutoRestore { get; set; } /// <summary> /// If true, MSBuild project system will only be loading projects for files that were opened in the editor /// as well as referenced projects, recursively. /// </summary> public bool LoadProjectsOnDemand { get; set; } /// <summary> /// When set to true, the MSBuild project system will attempt to resolve the path to the MSBuild /// SDKs for a project by running 'dotnet --info' and retrieving the path. This is only needed /// for older versions of the .NET Core SDK. /// </summary> public bool UseLegacySdkResolver { get; set; } public string MSBuildExtensionsPath { get; set; } public string TargetFrameworkRootPath { get; set; } public string MSBuildSDKsPath { get; set; } public string RoslynTargetsPath { get; set; } public string CscToolPath { get; set; } public string CscToolExe { get; set; } /// <summary> /// When set to true, the MSBuild project system will generate binary logs for each project that /// it loads. /// </summary> public bool GenerateBinaryLogs { get; set; } // TODO: Allow loose properties // public IConfiguration Properties { get; set; } } }
namespace OmniSharp.Options { public class MSBuildOptions { public bool UseBundledOnly { get; set; } = false; public string ToolsVersion { get; set; } public string VisualStudioVersion { get; set; } public string Configuration { get; set; } public string Platform { get; set; } public bool EnablePackageAutoRestore { get; set; } /// <summary> /// If true, MSBuild project system will only be loading projects for files that were opened in the editor /// as well as referenced projects, recursively. /// </summary> public bool LoadProjectsOnDemand { get; set; } /// <summary> /// When set to true, the MSBuild project system will attempt to resolve the path to the MSBuild /// SDKs for a project by running 'dotnet --info' and retrieving the path. This is only needed /// for older versions of the .NET Core SDK. /// </summary> public bool UseLegacySdkResolver { get; set; } public string MSBuildExtensionsPath { get; set; } public string TargetFrameworkRootPath { get; set; } public string MSBuildSDKsPath { get; set; } public string RoslynTargetsPath { get; set; } public string CscToolPath { get; set; } public string CscToolExe { get; set; } /// <summary> /// When set to true, the MSBuild project system will generate binary logs for each project that /// it loads. /// </summary> public bool GenerateBinaryLogs { get; set; } // TODO: Allow loose properties // public IConfiguration Properties { get; set; } } }
mit
C#
bf8708d4c80789c93e43faa636eceddfc3fa19da
Update IGraphXEdge.cs to support new ReversePath property
jorgensigvardsson/GraphX,edgardozoppi/GraphX,slate56/GraphX,slate56/GraphX,panthernet/GraphX,perturbare/GraphX
GraphX.PCL.Common/Interfaces/IGraphXEdge.cs
GraphX.PCL.Common/Interfaces/IGraphXEdge.cs
namespace GraphX.PCL.Common.Interfaces { /// <summary> /// Core GraphX edge data interface /// </summary> /// <typeparam name="TVertex">Vertex data type</typeparam> public interface IGraphXEdge<TVertex> : IGraphXCommonEdge, IWeightedEdge<TVertex> { /// <summary> /// Gets or sets source vertex /// </summary> new TVertex Source { get; set; } /// <summary> /// Gets or sets target vertex /// </summary> new TVertex Target { get; set; } } /// <summary> /// Core edge data interface /// </summary> public interface IGraphXCommonEdge: IIdentifiableGraphDataObject, IRoutingInfo { /// <summary> /// Gets if edge is self-looped /// </summary> bool IsSelfLoop { get; } /// <summary> /// Optional parameter to bind edge to static vertex connection point /// </summary> int? SourceConnectionPointId { get; } /// <summary> /// Optional parameter to bind edge to static vertex connection point /// </summary> int? TargetConnectionPointId { get; } /// <summary> /// Reverse the calculated routing path points. /// </summary> bool ReversePath { get; set; }} }
namespace GraphX.PCL.Common.Interfaces { /// <summary> /// Core GraphX edge data interface /// </summary> /// <typeparam name="TVertex">Vertex data type</typeparam> public interface IGraphXEdge<TVertex> : IGraphXCommonEdge, IWeightedEdge<TVertex> { /// <summary> /// Gets or sets source vertex /// </summary> new TVertex Source { get; set; } /// <summary> /// Gets or sets target vertex /// </summary> new TVertex Target { get; set; } } /// <summary> /// Core edge data interface /// </summary> public interface IGraphXCommonEdge: IIdentifiableGraphDataObject, IRoutingInfo { /// <summary> /// Gets if edge is self-looped /// </summary> bool IsSelfLoop { get; } /// <summary> /// Optional parameter to bind edge to static vertex connection point /// </summary> int? SourceConnectionPointId { get; } /// <summary> /// Optional parameter to bind edge to static vertex connection point /// </summary> int? TargetConnectionPointId { get; } } }
apache-2.0
C#
6e3022546102ec0cd8c79a3570a9cbcce6aff9b3
indent Xml by default.
signumsoftware/framework,signumsoftware/framework,avifatal/framework,AlejandroCano/framework,avifatal/framework,AlejandroCano/framework
Signum.Utilities/Extensions/XmlExtensions.cs
Signum.Utilities/Extensions/XmlExtensions.cs
using System; using System.IO; using System.Xml; using System.Xml.Serialization; namespace Signum.Utilities { public static class XmlExtensions { /// <summary> /// Returns an XML document representing the given object. /// </summary> /// <param name="obj">Any object.</param> /// <returns>A XML string, representing the given object on success.</returns> public static string SerializeToXml<T>(T obj) { if (obj == null) return string.Empty; try { var serializer = new XmlSerializer(typeof(T)); var stringWriter = new StringWriter(); using (var writer = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true })) { serializer.Serialize(writer, obj); return stringWriter.ToString(); } } catch (Exception e) { throw new Exception("An error occurred during serialization.", e); } } /// <summary> /// Returns a deserialized object from the given string. /// </summary> /// <param name="obj">The XML string.</param> /// <returns>The deserialized object from the string.</returns> public static T DeserializeFromXml<T>(string str) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(str)) { return (T)serializer.Deserialize(reader); } } } }
using System; using System.IO; using System.Xml; using System.Xml.Serialization; namespace Signum.Utilities { public static class XmlExtensions { /// <summary> /// Returns an XML document representing the given object. /// </summary> /// <param name="obj">Any object.</param> /// <returns>A XML string, representing the given object on success.</returns> public static string SerializeToXml<T>(T obj) { if (obj == null) return string.Empty; try { var serializer = new XmlSerializer(typeof(T)); var stringWriter = new StringWriter(); using (var writer = XmlWriter.Create(stringWriter)) { serializer.Serialize(writer, obj); return stringWriter.ToString(); } } catch (Exception e) { throw new Exception("An error occurred during serialization.", e); } } /// <summary> /// Returns a deserialized object from the given string. /// </summary> /// <param name="obj">The XML string.</param> /// <returns>The deserialized object from the string.</returns> public static T DeserializeFromXml<T>(string str) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(str)) { return (T)serializer.Deserialize(reader); } } } }
mit
C#
aead990106accb0d6bd8936a3f51d150e72b4afd
fix mis-spelled Ethnicity
SnapMD/connectedcare-sdk,dhawalharsora/connectedcare-sdk
SnapMD.VirtualCare.ApiModels/FamilyMember.cs
SnapMD.VirtualCare.ApiModels/FamilyMember.cs
#region Copyright // Copyright 2016 SnapMD, Inc. // 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. #endregion using System; namespace SnapMD.VirtualCare.ApiModels { public class FamilyMember { public int PatientId { get; set; } public string PatientName { get; set; } public string ProfileImagePath { get; set; } public int RelationCode { get; set; } public bool IsAuthorized { get; set; } public DateTime? Birthdate { get; set; } public string[] Addresses { get; set; } public string PatientFirstName { get; set; } public string PatientLastName { get; set; } public string GuardianFirstName { get; set; } public string GuardianLastName { get; set; } public string GuardianName { get; set; } public Guid? PersonId { get; set; } public string EmailId { get; set; } public string Gender { get; set; } public int? Ethnicity { get; set; } public int? BloodType { get; set; } public int? HairColor { get; set; } public int? EyeColor { get; set; } public string Height { get; set; } public string Weight { get; set; } public int? HeightUnit { get; set; } public int? WeightUnit { get; set; } public string HomePhone { get; set; } public string MobilePhone { get; set; } public int? OrganationId { get; set; } public int? LocationId { get; set; } } }
#region Copyright // Copyright 2016 SnapMD, Inc. // 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. #endregion using System; namespace SnapMD.VirtualCare.ApiModels { public class FamilyMember { public int PatientId { get; set; } public string PatientName { get; set; } public string ProfileImagePath { get; set; } public int RelationCode { get; set; } public bool IsAuthorized { get; set; } public DateTime? Birthdate { get; set; } public string[] Addresses { get; set; } public string PatientFirstName { get; set; } public string PatientLastName { get; set; } public string GuardianFirstName { get; set; } public string GuardianLastName { get; set; } public string GuardianName { get; set; } public Guid? PersonId { get; set; } public string EmailId { get; set; } public string Gender { get; set; } public int? Enthicity { get; set; } public int? BloodType { get; set; } public int? HairColor { get; set; } public int? EyeColor { get; set; } public string Height { get; set; } public string Weight { get; set; } public int? HeightUnit { get; set; } public int? WeightUnit { get; set; } public string HomePhone { get; set; } public string MobilePhone { get; set; } public int? OrganationId { get; set; } public int? LocationId { get; set; } } }
apache-2.0
C#
0c0d6b3169413fe1282c3fa7a5e9f098454a5709
Bump version number
regisbsb/FluentValidation,cecilphillip/FluentValidation,IRlyDontKnow/FluentValidation,olcayseker/FluentValidation,roend83/FluentValidation,deluxetiky/FluentValidation,GDoronin/FluentValidation,robv8r/FluentValidation,pacificIT/FluentValidation,ruisebastiao/FluentValidation,glorylee/FluentValidation,mgmoody42/FluentValidation,roend83/FluentValidation
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; [assembly : AssemblyTitle("FluentValidation")] [assembly : AssemblyDescription("FluentValidation")] [assembly : AssemblyProduct("FluentValidation")] [assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2011")] [assembly : ComVisible(false)] [assembly : AssemblyVersion("3.0.0.0")] [assembly : AssemblyFileVersion("0.0.0.0")] [assembly: CLSCompliant(true)] #if !SILVERLIGHT [assembly: AllowPartiallyTrustedCallers] #endif
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; [assembly : AssemblyTitle("FluentValidation")] [assembly : AssemblyDescription("FluentValidation")] [assembly : AssemblyProduct("FluentValidation")] [assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2010")] [assembly : ComVisible(false)] [assembly : AssemblyVersion("2.0.0.0")] [assembly : AssemblyFileVersion("2.0.0.0")] [assembly: CLSCompliant(true)] #if !SILVERLIGHT [assembly: AllowPartiallyTrustedCallers] #endif
apache-2.0
C#
620e2ebd85999396e501a2106e4af98458a8a86a
Document ShavianCharacter class
lambdacasserole/shaver
Shaver/ShavianCharacter.cs
Shaver/ShavianCharacter.cs
using System.Text; namespace Shaver { /// <summary> /// Represents a character in the Shaw alphabet. /// </summary> public class ShavianCharacter { private string character; /// <summary> /// Gets the character as a string. /// </summary> public string Character { get { return character; } } /// <summary> /// Gets the length of the character in bytes. /// </summary> public int Length { get { return Encoding.UTF8.GetBytes(character).Length; } } /// <summary> /// Initializes a new instance of a character of the Shaw alphabet. /// </summary> /// <param name="character">The character as a string.</param> public ShavianCharacter(string character) { this.character = character; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shaver { class ShavianCharacter { private string character; public string Character { get { return character; } } public int Length { get { return Encoding.UTF8.GetBytes(character).Length; } } public ShavianCharacter(string character) { this.character = character; } } }
mit
C#
58fa6bbe0a894e11e8f79b0262e1cdaa6a074e88
Rename ParseException -> ParsingException and inherit from FormatException
MetacoSA/NBitcoin,NicolasDorier/NBitcoin,MetacoSA/NBitcoin
NBitcoin/Scripting/Parser/ParseException.cs
NBitcoin/Scripting/Parser/ParseException.cs
using System; namespace NBitcoin.Scripting.Parser { /// <summary> /// Represents an error that occurs during parsing. /// </summary> public class ParsingException : FormatException { /// <summary> /// Initializes a new instance of the <see cref="ParsingException" /> class. /// </summary> public ParsingException() { } /// <summary> /// Initializes a new instance of the <see cref="ParsingException" /> class with a specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public ParsingException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class with a specified error message /// and the position where the error occured. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="position">The position where the error occured.</param> public ParsingException(string message, int position) : base(message) { Position = position; } /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class with a specified error message /// and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, /// or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public ParsingException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Gets the position of the parsing failure if one is available; otherwise, null. /// </summary> public int Position { get; } } }
using System; namespace NBitcoin.Scripting.Parser { /// <summary> /// Represents an error that occurs during parsing. /// </summary> public class ParseException : Exception { /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class. /// </summary> public ParseException() { } /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class with a specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public ParseException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class with a specified error message /// and the position where the error occured. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="position">The position where the error occured.</param> public ParseException(string message, int position) : base(message) { Position = position; } /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class with a specified error message /// and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, /// or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public ParseException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Gets the position of the parsing failure if one is available; otherwise, null. /// </summary> public int Position { get; } } }
mit
C#
509eca1cc586eb7c9fec46bb4bbfd5e6b8f61715
Fix broken integration tests; wrong DB upgrade impl was being used
csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil
Agiil.Bootstrap/Data/DataModule.cs
Agiil.Bootstrap/Data/DataModule.cs
using System; using System.Collections.Generic; using System.Linq; using Agiil.Data; using Agiil.Data.Sqlite; using Agiil.Domain.Data; using Autofac; using Autofac.Core; using CSF.DecoratorBuilder; namespace Agiil.Bootstrap.Data { public class DataModule : Module { protected override void Load(ContainerBuilder builder) { base.Load(builder); builder .RegisterType<SnapshotStore>() .SingleInstance(); builder.RegisterDecoratedService<IPerformsDatabaseUpgrades>(d => d .UsingInitialImpl<DbUpDatabaseUpgrader>() .ThenWrapWith<BackupTakingUpgrader>()); builder.RegisterType<DbUpDatabaseUpgrader>().As<ICreatesDatabaseSchema>(); builder .RegisterConfiguration<DataDirectoryConfigurationSection>() .AsSelf() .As<IGetsDataDirectory>(); builder.RegisterDecoratedService<IResetsDatabase>(d => d .UsingInitialImpl<DevelopmentDatabaseResetter>() .ThenWrapWith<SnapshottingDatabaseResetter>()); builder.Register(GetConnectionStringAdapter); } IGetsDatabaseFilePath GetConnectionStringAdapter(IComponentContext ctx, IEnumerable<Parameter> @params) { var connectionStringParam = @params .OfType<TypedParameter>() .FirstOrDefault(x => x.Type == typeof(string)); if(connectionStringParam != null) return ctx.Resolve<ConnectionStringAdapter>(connectionStringParam); if(@params.OfType<TypedParameter>().FirstOrDefault(x => x.Type == typeof(IConnectionStringProvider))?.Value is IConnectionStringProvider provider) return ctx.Resolve<ConnectionStringAdapter>(TypedParameter.From(provider.GetConnectionString())); throw new DependencyResolutionException($"Cannot resolve an instance of {nameof(IGetsDatabaseFilePath)}, either a {nameof(String)} or a {nameof(IConnectionStringProvider)} parameter must be provided."); } } }
using System; using System.Collections.Generic; using System.Linq; using Agiil.Data; using Agiil.Data.Sqlite; using Agiil.Domain.Data; using Autofac; using Autofac.Core; using CSF.DecoratorBuilder; namespace Agiil.Bootstrap.Data { public class DataModule : Module { protected override void Load(ContainerBuilder builder) { base.Load(builder); builder .RegisterType<SnapshotStore>() .SingleInstance(); builder.RegisterDecoratedService<IPerformsDatabaseUpgrades>(d => d .UsingInitialImpl<DbUpDatabaseUpgrader>() .ThenWrapWith<BackupTakingUpgrader>()); builder .RegisterConfiguration<DataDirectoryConfigurationSection>() .AsSelf() .As<IGetsDataDirectory>(); builder.RegisterDecoratedService<IResetsDatabase>(d => d .UsingInitialImpl<DevelopmentDatabaseResetter>() .ThenWrapWith<SnapshottingDatabaseResetter>()); builder.Register(GetConnectionStringAdapter); } IGetsDatabaseFilePath GetConnectionStringAdapter(IComponentContext ctx, IEnumerable<Parameter> @params) { var connectionStringParam = @params .OfType<TypedParameter>() .FirstOrDefault(x => x.Type == typeof(string)); if(connectionStringParam != null) return ctx.Resolve<ConnectionStringAdapter>(connectionStringParam); if(@params.OfType<TypedParameter>().FirstOrDefault(x => x.Type == typeof(IConnectionStringProvider))?.Value is IConnectionStringProvider provider) return ctx.Resolve<ConnectionStringAdapter>(TypedParameter.From(provider.GetConnectionString())); throw new DependencyResolutionException($"Cannot resolve an instance of {nameof(IGetsDatabaseFilePath)}, either a {nameof(String)} or a {nameof(IConnectionStringProvider)} parameter must be provided."); } } }
mit
C#
9ada5f1f3668773ebb5f7039131682035e965990
Update AnimationPathCurvesDebug class with ease curve
bartlomiejwolk/AnimationPathAnimator
AnimationPathCurvesDebug.cs
AnimationPathCurvesDebug.cs
using UnityEngine; using System.Collections; using ATP.AnimationPathTools; [ExecuteInEditMode] public class AnimationPathCurvesDebug : MonoBehaviour { private AnimationPathAnimator animator; [Header("Rotation curves")] public AnimationCurve curveX; public AnimationCurve curveY; public AnimationCurve curveZ; [Header("Ease curve")] public AnimationCurve easeCurve; // Use this for initialization void Awake() { } void OnEnable() { animator = GetComponent<AnimationPathAnimator>(); curveX = animator.RotationCurves[0]; curveY = animator.RotationCurves[1]; curveZ = animator.RotationCurves[2]; easeCurve = animator.EaseCurve; } void Start() { } // Update is called once per frame void Update() { } }
using UnityEngine; using System.Collections; using ATP.AnimationPathTools; [ExecuteInEditMode] public class AnimationPathCurvesDebug : MonoBehaviour { private AnimationPathAnimator animator; public AnimationCurve curveX; public AnimationCurve curveY; public AnimationCurve curveZ; // Use this for initialization void Awake() { } void OnEnable() { } void Start() { } // Update is called once per frame void Update() { animator = GetComponent<AnimationPathAnimator>(); curveX = animator.RotationCurves[0]; curveY = animator.RotationCurves[1]; curveZ = animator.RotationCurves[2]; } }
mit
C#
07ec413884cc6b509acc6d8a28b10880fa7c9c47
update shard sample to use CommandExecuted, Log
AntiTcb/Discord.Net,RogueException/Discord.Net
samples/03_sharded_client/Services/CommandHandlingService.cs
samples/03_sharded_client/Services/CommandHandlingService.cs
using System; using System.Reflection; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Discord; using Discord.Commands; using Discord.WebSocket; namespace _03_sharded_client.Services { public class CommandHandlingService { private readonly CommandService _commands; private readonly DiscordShardedClient _discord; private readonly IServiceProvider _services; public CommandHandlingService(IServiceProvider services) { _commands = services.GetRequiredService<CommandService>(); _discord = services.GetRequiredService<DiscordShardedClient>(); _services = services; _commands.CommandExecuted += CommandExecutedAsync; _commands.Log += LogAsync; _discord.MessageReceived += MessageReceivedAsync; } public async Task InitializeAsync() { await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services); _discord.MessageReceived += MessageReceivedAsync; } public async Task MessageReceivedAsync(SocketMessage rawMessage) { // Ignore system messages, or messages from other bots if (!(rawMessage is SocketUserMessage message)) return; if (message.Source != MessageSource.User) return; // This value holds the offset where the prefix ends var argPos = 0; if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos)) return; // A new kind of command context, ShardedCommandContext can be utilized with the commands framework var context = new ShardedCommandContext(_discord, message); await _commands.ExecuteAsync(context, argPos, _services); } public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result) { // command is unspecified when there was a search failure (command not found); we don't care about these errors if (!command.IsSpecified) return; // the command was succesful, we don't care about this result, unless we want to log that a command succeeded. if (result.IsSuccess) return; // the command failed, let's notify the user that something happened. await context.Channel.SendMessageAsync($"error: {result.ToString()}"); } private Task LogAsync(LogMessage log) { Console.WriteLine(log.ToString()); return Task.CompletedTask; } } }
using System; using System.Reflection; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Discord; using Discord.Commands; using Discord.WebSocket; namespace _03_sharded_client.Services { public class CommandHandlingService { private readonly CommandService _commands; private readonly DiscordShardedClient _discord; private readonly IServiceProvider _services; public CommandHandlingService(IServiceProvider services) { _commands = services.GetRequiredService<CommandService>(); _discord = services.GetRequiredService<DiscordShardedClient>(); _services = services; } public async Task InitializeAsync() { await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services); _discord.MessageReceived += MessageReceivedAsync; } public async Task MessageReceivedAsync(SocketMessage rawMessage) { // Ignore system messages, or messages from other bots if (!(rawMessage is SocketUserMessage message)) return; if (message.Source != MessageSource.User) return; // This value holds the offset where the prefix ends var argPos = 0; if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos)) return; // A new kind of command context, ShardedCommandContext can be utilized with the commands framework var context = new ShardedCommandContext(_discord, message); var result = await _commands.ExecuteAsync(context, argPos, _services); if (result.Error.HasValue && result.Error.Value != CommandError.UnknownCommand) // it's bad practice to send 'unknown command' errors await context.Channel.SendMessageAsync(result.ToString()); } } }
mit
C#
a7c6ee7237e2637b1f08f9edf6fa376005206eeb
Update to use Vector3.zero
jmeas/simple-tower
Assets/Scripts/Player.cs
Assets/Scripts/Player.cs
public class Player : UnityEngine.MonoBehaviour { public UnityEngine.Rigidbody rb; UnityEngine.Vector3 startPosition = new UnityEngine.Vector3(0f, 17f, 0f); UnityEngine.Vector3 stationary = UnityEngine.Vector3.zero; void Start() { rb = GetComponent<UnityEngine.Rigidbody>(); StartCoroutine(CheckOutOfBounds()); } public System.Collections.IEnumerator CheckOutOfBounds() { // This checks the boundaries continuously. Eventually, we'll want to turn // this off at certain times, like when the player doesn't have control over // the character's movement. while(true) { if (transform.position.y < -6) { // Reset the player's velocity and their position rb.velocity = stationary; transform.position = startPosition; } // The player bounds are pretty loosely defined, so it's fine to check on // them a little less frequently. yield return new UnityEngine.WaitForSeconds(0.1f); } } }
public class Player : UnityEngine.MonoBehaviour { public UnityEngine.Rigidbody rb; UnityEngine.Vector3 startPosition = new UnityEngine.Vector3(0f, 17f, 0f); UnityEngine.Vector3 stationary = new UnityEngine.Vector3(0, 0, 0); void Start() { rb = GetComponent<UnityEngine.Rigidbody>(); StartCoroutine(CheckOutOfBounds()); } public System.Collections.IEnumerator CheckOutOfBounds() { // This checks the boundaries continuously. Eventually, we'll want to turn // this off at certain times, like when the player doesn't have control over // the character's movement. while(true) { if (transform.position.y < -6) { // Reset the player's velocity and their position rb.velocity = stationary; transform.position = startPosition; } // The player bounds are pretty loosely defined, so it's fine to check on // them a little less frequently. yield return new UnityEngine.WaitForSeconds(0.1f); } } }
mit
C#
6e472fab60d516f62762ef1076bd3997ab0a172d
Update Factory.cs
hprose/hprose-dotnet
src/Hprose.IO/Deserializers/Factory.cs
src/Hprose.IO/Deserializers/Factory.cs
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Factory.cs * * * * Factory class for C#. * * * * LastModified: May 5, 2018 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ using System; using System.Linq.Expressions; namespace Hprose.IO.Deserializers { public static class Factory<T> { private static readonly Func<T> constructor = GetConstructor(); private static Func<T> GetConstructor() { try { return Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile(); } catch { return () => (T)Activator.CreateInstance(typeof(T), true); } } public static T New() { return constructor(); } } }
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Factory.cs * * * * Factory class for C#. * * * * LastModified: Apr 29, 2018 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ using System; using System.Linq.Expressions; namespace Hprose.IO.Deserializers { public static class Factory<T> { private static readonly Func<T> constructor; static Factory() { try { constructor = Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile(); } catch { constructor = () => (T)Activator.CreateInstance(typeof(T), true); } } public static T New() { return constructor(); } } }
mit
C#
45dc6b1549a6c0138a1e443eb36db70a69c797d0
Add UnityEngine.Object to known types
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/src/resharper-unity/KnownTypes.cs
resharper/src/resharper-unity/KnownTypes.cs
using JetBrains.Metadata.Reader.API; using JetBrains.Metadata.Reader.Impl; namespace JetBrains.ReSharper.Plugins.Unity { public static class KnownTypes { // UnityEngine public static readonly IClrTypeName Object = new ClrTypeName("UnityEngine.Object"); public static readonly IClrTypeName Component = new ClrTypeName("UnityEngine.Component"); public static readonly IClrTypeName GameObject = new ClrTypeName("UnityEngine.GameObject"); public static readonly IClrTypeName MonoBehaviour = new ClrTypeName("UnityEngine.MonoBehaviour"); public static readonly IClrTypeName RuntimeInitializeOnLoadMethodAttribute = new ClrTypeName("UnityEngine.RuntimeInitializeOnLoadMethodAttribute"); public static readonly IClrTypeName ScriptableObject = new ClrTypeName("UnityEngine.ScriptableObject"); public static readonly IClrTypeName SerializeField = new ClrTypeName("UnityEngine.SerializeField"); // UnityEngine.Networking public static readonly IClrTypeName NetworkBehaviour = new ClrTypeName("UnityEngine.Networking.NetworkBehaviour"); public static readonly IClrTypeName SyncVarAttribute = new ClrTypeName("UnityEngine.Networking.SyncVarAttribute"); // UnityEditor public static readonly IClrTypeName InitializeOnLoadAttribute = new ClrTypeName("UnityEditor.InitializeOnLoadAttribute"); public static readonly IClrTypeName InitializeOnLoadMethodAttribute = new ClrTypeName("UnityEditor.InitializeOnLoadMethodAttribute"); public static readonly IClrTypeName DidReloadScripts = new ClrTypeName("UnityEditor.Callbacks.DidReloadScripts"); public static readonly IClrTypeName OnOpenAssetAttribute = new ClrTypeName("UnityEditor.Callbacks.OnOpenAssetAttribute"); public static readonly IClrTypeName PostProcessBuildAttribute = new ClrTypeName("UnityEditor.Callbacks.PostProcessBuildAttribute"); public static readonly IClrTypeName PostProcessSceneAttribute = new ClrTypeName("UnityEditor.Callbacks.PostProcessSceneAttribute"); } }
using JetBrains.Metadata.Reader.API; using JetBrains.Metadata.Reader.Impl; namespace JetBrains.ReSharper.Plugins.Unity { public static class KnownTypes { // UnityEngine public static readonly IClrTypeName Component = new ClrTypeName("UnityEngine.Component"); public static readonly IClrTypeName GameObject = new ClrTypeName("UnityEngine.GameObject"); public static readonly IClrTypeName MonoBehaviour = new ClrTypeName("UnityEngine.MonoBehaviour"); public static readonly IClrTypeName RuntimeInitializeOnLoadMethodAttribute = new ClrTypeName("UnityEngine.RuntimeInitializeOnLoadMethodAttribute"); public static readonly IClrTypeName ScriptableObject = new ClrTypeName("UnityEngine.ScriptableObject"); public static readonly IClrTypeName SerializeField = new ClrTypeName("UnityEngine.SerializeField"); // UnityEngine.Networking public static readonly IClrTypeName NetworkBehaviour = new ClrTypeName("UnityEngine.Networking.NetworkBehaviour"); public static readonly IClrTypeName SyncVarAttribute = new ClrTypeName("UnityEngine.Networking.SyncVarAttribute"); // UnityEditor public static readonly IClrTypeName InitializeOnLoadAttribute = new ClrTypeName("UnityEditor.InitializeOnLoadAttribute"); public static readonly IClrTypeName InitializeOnLoadMethodAttribute = new ClrTypeName("UnityEditor.InitializeOnLoadMethodAttribute"); public static readonly IClrTypeName DidReloadScripts = new ClrTypeName("UnityEditor.Callbacks.DidReloadScripts"); public static readonly IClrTypeName OnOpenAssetAttribute = new ClrTypeName("UnityEditor.Callbacks.OnOpenAssetAttribute"); public static readonly IClrTypeName PostProcessBuildAttribute = new ClrTypeName("UnityEditor.Callbacks.PostProcessBuildAttribute"); public static readonly IClrTypeName PostProcessSceneAttribute = new ClrTypeName("UnityEditor.Callbacks.PostProcessSceneAttribute"); } }
apache-2.0
C#
5663f5c15d437d5d709704359573037c7663a639
Update index.cshtml
reactiveui/website,reactiveui/website,reactiveui/website,reactiveui/website
input/slack/index.cshtml
input/slack/index.cshtml
<meta http-equiv="refresh" content="1;url=mailto:hello@reactiveui.net?subject%3D%22Howdy%2C%20can%20you%20send%20me%20an%20invite%20to%20Slack%3F%22" /> Send an email to <a href="mailto:hello@reactiveui.net?subject%3D%22Howdy%2C%20can%20you%20send%20me%20an%20invite%20to%20Slack%3F%22">hello@reactiveui.net</a> to obtain an invitation to our Slack organization. Sit tight, it's worth it.
<meta http-equiv="refresh" content="1;url=mailto:hello@reactiveui.net?subject%3D%22Howdy%2C%20can%20you%20send%20me%20an%20invite%20to%20Slack%3F%22" />
mit
C#
b6f845bf53d13b84bda7812bb3d609539a4e0863
fix build
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
src/ScriptBuilderTask.Tests/InnerTaskTests.cs
src/ScriptBuilderTask.Tests/InnerTaskTests.cs
using System; using System.IO; using System.Linq; using NUnit.Framework; using ObjectApproval; [TestFixture] class InnerTaskTests { [Test] public void IntegrationTest() { var testDirectory = TestContext.CurrentContext.TestDirectory; var temp = Path.Combine(testDirectory, "InnerTaskTemp"); DirectoryExtensions.Delete(temp); var assemblyPath = Path.Combine(testDirectory, "ScriptBuilderTask.Tests.Target.dll"); var intermediatePath = Path.Combine(temp, "IntermediatePath"); var promotePath = Path.Combine(temp, "PromotePath"); Directory.CreateDirectory(temp); Directory.CreateDirectory(intermediatePath); Action<string, string> logError = (error, s1) => { throw new Exception(error); }; var innerTask = new InnerTask(assemblyPath, intermediatePath, "TheProjectDir", promotePath, logError); innerTask.Execute(); var files = Directory.EnumerateFiles(temp, "*.*", SearchOption.AllDirectories).Select(s => s.Replace(temp, "temp")).ToList(); ObjectApprover.VerifyWithJson(files); } }
using System; using System.IO; using System.Linq; using NUnit.Framework; using ObjectApproval; [TestFixture] class InnerTaskTests { [Test] public void IntegrationTest() { var testDirectory = TestContext.CurrentContext.TestDirectory; var temp = Path.Combine(testDirectory, "InnerTaskTemp"); DirectoryExtentions.Delete(temp); var assemblyPath = Path.Combine(testDirectory, "ScriptBuilderTask.Tests.Target.dll"); var intermediatePath = Path.Combine(temp, "IntermediatePath"); var promotePath = Path.Combine(temp, "PromotePath"); Directory.CreateDirectory(temp); Directory.CreateDirectory(intermediatePath); Action<string, string> logError = (error, s1) => { throw new Exception(error); }; var innerTask = new InnerTask(assemblyPath, intermediatePath, "TheProjectDir", promotePath, logError); innerTask.Execute(); var files = Directory.EnumerateFiles(temp, "*.*", SearchOption.AllDirectories).Select(s => s.Replace(temp, "temp")).ToList(); ObjectApprover.VerifyWithJson(files); } }
mit
C#
1390e4237abcc567228806720de9b810d80a35a2
Update CompositeCrossCurrencyConverterTests.cs
tiksn/TIKSN-Framework
TIKSN.UnitTests.Shared/Finance/CompositeCrossCurrencyConverterTests.cs
TIKSN.UnitTests.Shared/Finance/CompositeCrossCurrencyConverterTests.cs
using System; using System.Linq; using System.Threading.Tasks; using Xunit; namespace TIKSN.Finance.Tests { public class CompositeCrossCurrencyConverterTests { [Fact] public async Task GetCurrencyPairsAsync001Async() { var converter = new CompositeCrossCurrencyConverter(new AverageCurrencyConversionCompositionStrategy()); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("EUR")), 1.12m)); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("GBP")), 1.13m)); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("CHF")), 1.14m)); var pairs = await converter.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); Assert.Equal(3, pairs.Count()); } [Fact] public async Task GetExchangeRateAsync001Async() { var converter = new CompositeCrossCurrencyConverter(new AverageCurrencyConversionCompositionStrategy()); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("EUR")), 1.12m)); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("GBP")), 1.13m)); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("CHF")), 1.14m)); var rate = await converter.GetExchangeRateAsync(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("EUR")), DateTimeOffset.Now, default).ConfigureAwait(true); Assert.Equal(1.12m, rate); } } }
using System; using System.Linq; using System.Threading.Tasks; using Xunit; namespace TIKSN.Finance.Tests { public class CompositeCrossCurrencyConverterTests { [Fact] public async Task GetCurrencyPairsAsync001() { var converter = new CompositeCrossCurrencyConverter(new AverageCurrencyConversionCompositionStrategy()); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("EUR")), 1.12m)); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("GBP")), 1.13m)); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("CHF")), 1.14m)); var pairs = await converter.GetCurrencyPairsAsync(DateTimeOffset.Now, default); Assert.Equal(3, pairs.Count()); } [Fact] public async Task GetExchangeRateAsync001() { var converter = new CompositeCrossCurrencyConverter(new AverageCurrencyConversionCompositionStrategy()); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("EUR")), 1.12m)); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("GBP")), 1.13m)); converter.Add(new FixedRateCurrencyConverter(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("CHF")), 1.14m)); var rate = await converter.GetExchangeRateAsync(new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("EUR")), DateTimeOffset.Now, default); Assert.Equal(1.12m, rate); } } }
mit
C#
0410f0bcce4da52a543ea1820952eeced9a824de
Fix error thrown by a Disable method
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
Test/AdventureWorksFunctionalModel/Sales/SalesOrderDetail_Functions.cs
Test/AdventureWorksFunctionalModel/Sales/SalesOrderDetail_Functions.cs
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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. using System; using NakedFunctions; using AW.Types; namespace AW.Functions { public static class SalesOrderDetail_Functions { //Call this from any function that updates a SalesOrderDetail public static (SalesOrderDetail, IContext) Recalculate(this SalesOrderDetail sod) { throw new NotImplementedException(); //UnitPrice = SpecialOfferProduct.Product.ListPrice; //UnitPriceDiscount = (SpecialOfferProduct.SpecialOffer.DiscountPct * UnitPrice); //LineTotal = (UnitPrice - UnitPriceDiscount) * OrderQty; //SalesOrderHeader.Recalculate(); } public static (SalesOrderDetail, IContext) ChangeQuantity(this SalesOrderDetail sod, short newQuantity, IContext context) { throw new NotImplementedException(); //OrderQty = newQuantity; // IQueryable<SpecialOfferProduct> sops //SpecialOfferProduct = ProductFunctions2.BestSpecialOfferProduct(Product, newQuantity, sops); //Recalculate(); } public static string DisableChangeQuantity() { return null; //return SalesOrderHeader.DisableAddNewDetail(); } } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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. using System; using NakedFunctions; using AW.Types; namespace AW.Functions { public static class SalesOrderDetail_Functions { //Call this from any function that updates a SalesOrderDetail public static (SalesOrderDetail, IContext) Recalculate(this SalesOrderDetail sod) { throw new NotImplementedException(); //UnitPrice = SpecialOfferProduct.Product.ListPrice; //UnitPriceDiscount = (SpecialOfferProduct.SpecialOffer.DiscountPct * UnitPrice); //LineTotal = (UnitPrice - UnitPriceDiscount) * OrderQty; //SalesOrderHeader.Recalculate(); } public static (SalesOrderDetail, IContext) ChangeQuantity(this SalesOrderDetail sod, short newQuantity, IContext context) { throw new NotImplementedException(); //OrderQty = newQuantity; // IQueryable<SpecialOfferProduct> sops //SpecialOfferProduct = ProductFunctions2.BestSpecialOfferProduct(Product, newQuantity, sops); //Recalculate(); } public static string DisableChangeQuantity() { throw new NotImplementedException(); //return SalesOrderHeader.DisableAddNewDetail(); } } }
apache-2.0
C#
6860ecbd45def6d2525ee14e64705cc22b4f3f8d
Comment out Email Generics
kylegregory/EmmaSharp,MikeSmithDev/EmmaSharp
EmmaSharp/Models/Generics/Email.cs
EmmaSharp/Models/Generics/Email.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EmmaSharp.Models.Generics { class Email { /*[JsonProperty("email")] public string Email { get; set; }*/ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EmmaSharp.Models.Generics { class Email { [JsonProperty("email")] public string Email { get; set; } } }
mit
C#
564b61644b5fb29b689b6f5d4ad2c13797456887
implement loading and saving events
Pondidum/Ledger.Stores.Fs,Pondidum/Ledger.Stores.Fs
Ledger.Stores.Fs/FileEventStore.cs
Ledger.Stores.Fs/FileEventStore.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ledger.Infrastructure; using Newtonsoft.Json; namespace Ledger.Stores.Fs { public class FileEventStore : IEventStore { private readonly string _directory; public FileEventStore(string directory) { _directory = directory; } private string EventFile<TKey>() { return Path.Combine(_directory, typeof(TKey).Name + ".events.json"); } private string SnapshotFile<TKey>() { return Path.Combine(_directory, typeof(TKey).Name + ".snapshots.json"); } private void AppendTo(string filepath, Action<StreamWriter> action) { using(var fs = new FileStream(filepath, FileMode.Append)) using (var sw = new StreamWriter(fs)) { action(sw); } } private IEnumerable<TDto> ReadFrom<TDto>(string filepath) { using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(fs)) { string line; while ((line = sr.ReadLine()) != null) { yield return JsonConvert.DeserializeObject<TDto>(line); } } } public void SaveEvents<TKey>(TKey aggegateID, IEnumerable<DomainEvent> changes) { AppendTo(EventFile<TKey>(), file => { changes.ForEach(change => { var dto = new EventDto<TKey> {ID = aggegateID, Event = change}; var json = JsonConvert.SerializeObject(dto); file.WriteLine(json); }); }); } public void SaveSnapshot<TKey>(TKey aggregateID, ISequenced snapshot) { AppendTo(SnapshotFile<TKey>(), file => { var dto = new SnapshotDto<TKey> {ID = aggregateID, Snapshot = snapshot}; var json = JsonConvert.SerializeObject(dto); file.WriteLine(json); }); } public int? GetLatestSequenceIDFor<TKey>(TKey aggegateID) { return LoadEvents(aggegateID) .Select(e => (int?) e.SequenceID) .Max(); } public IEnumerable<DomainEvent> LoadEvents<TKey>(TKey aggegateID) { return ReadFrom<EventDto<TKey>>(EventFile<TKey>()) .Where(dto => Equals(dto.ID, aggegateID)) .Select(dto => dto.Event); } public IEnumerable<DomainEvent> LoadEventsSince<TKey>(TKey aggegateID, int sequenceID) { return LoadEvents(aggegateID) .Where(e => e.SequenceID > sequenceID); } public ISequenced GetLatestSnapshotFor<TKey>(TKey aggegateID) { return ReadFrom<SnapshotDto<TKey>>(SnapshotFile<TKey>()) .Where(dto => Equals(dto.ID, aggegateID)) .Select(dto => dto.Snapshot) .Cast<ISequenced>() .Last(); } } }
using System; using System.Collections.Generic; using System.IO; using Ledger.Infrastructure; using Newtonsoft.Json; namespace Ledger.Stores.Fs { public class FileEventStore : IEventStore { private readonly string _directory; public FileEventStore(string directory) { _directory = directory; } private string EventFile<TKey>() { return Path.Combine(_directory, typeof(TKey).Name + ".events.json"); } private string SnapshotFile<TKey>() { return Path.Combine(_directory, typeof(TKey).Name + ".snapshots.json"); } private void AppendTo(string filepath, Action<StreamWriter> action) { using(var fs = new FileStream(filepath, FileMode.Append)) using (var sw = new StreamWriter(fs)) { action(sw); } } public void SaveEvents<TKey>(TKey aggegateID, IEnumerable<DomainEvent> changes) { AppendTo(EventFile<TKey>(), file => { changes.ForEach(change => { var dto = new EventDto<TKey> {ID = aggegateID, Event = change}; var json = JsonConvert.SerializeObject(dto); file.WriteLine(json); }); }); } public void SaveSnapshot<TKey>(TKey aggregateID, ISequenced snapshot) { AppendTo(SnapshotFile<TKey>(), file => { var dto = new SnapshotDto<TKey> {ID = aggregateID, Snapshot = snapshot}; var json = JsonConvert.SerializeObject(dto); file.WriteLine(json); }); } public int? GetLatestSequenceIDFor<TKey>(TKey aggegateID) { throw new System.NotImplementedException(); } public IEnumerable<DomainEvent> LoadEvents<TKey>(TKey aggegateID) { throw new System.NotImplementedException(); } public IEnumerable<DomainEvent> LoadEventsSince<TKey>(TKey aggegateID, int sequenceID) { throw new System.NotImplementedException(); } public ISequenced GetLatestSnapshotFor<TKey>(TKey aggegateID) { throw new System.NotImplementedException(); } } }
lgpl-2.1
C#
420da9b7c5cea1fae46d58c1f303695d529b2813
Make assert looser.
Bartmax/Foundatio,exceptionless/Foundatio,wgraham17/Foundatio,FoundatioFx/Foundatio,vebin/Foundatio
src/Core/Tests/Locks/ThrottlingLockTests.cs
src/Core/Tests/Locks/ThrottlingLockTests.cs
using System; using System.Diagnostics; using Foundatio.Caching; using Foundatio.Extensions; using Foundatio.Lock; using Foundatio.Utility; using Xunit; namespace Foundatio.Tests { public class ThrottlingLockTests : LockTestBase { private readonly TimeSpan _period = TimeSpan.FromSeconds(2); protected override ILockProvider GetLockProvider() { return new ThrottlingLockProvider(new InMemoryCacheClient(), 5, _period); } [Fact] public void WillThrottleCalls() { var locker = GetLockProvider(); if (locker == null) return; Trace.WriteLine(DateTime.UtcNow.Subtract(DateTime.UtcNow.Floor(_period)).TotalMilliseconds); Trace.WriteLine(DateTime.UtcNow.ToString("mm:ss.fff")); // wait until we are at the beginning of our time bucket Run.UntilTrue(() => DateTime.UtcNow.Subtract(DateTime.UtcNow.Floor(_period)).TotalMilliseconds < 100, null, TimeSpan.FromMilliseconds(50)); Trace.WriteLine(DateTime.UtcNow.Subtract(DateTime.UtcNow.Floor(_period)).TotalMilliseconds); Trace.WriteLine(DateTime.UtcNow.ToString("mm:ss.fff")); var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 5; i++) locker.AcquireLock("test"); sw.Stop(); Assert.True(sw.Elapsed.TotalSeconds < 1); sw.Reset(); sw.Start(); locker.AcquireLock("test"); sw.Stop(); Trace.WriteLine(sw.Elapsed); Assert.InRange(sw.Elapsed.TotalSeconds, 1.2, 2.2); } } }
using System; using System.Diagnostics; using Foundatio.Caching; using Foundatio.Extensions; using Foundatio.Lock; using Foundatio.Utility; using Xunit; namespace Foundatio.Tests { public class ThrottlingLockTests : LockTestBase { private readonly TimeSpan _period = TimeSpan.FromSeconds(2); protected override ILockProvider GetLockProvider() { return new ThrottlingLockProvider(new InMemoryCacheClient(), 5, _period); } [Fact] public void WillThrottleCalls() { var locker = GetLockProvider(); if (locker == null) return; Trace.WriteLine(DateTime.UtcNow.Subtract(DateTime.UtcNow.Floor(_period)).TotalMilliseconds); Trace.WriteLine(DateTime.UtcNow.ToString("mm:ss.fff")); // wait until we are at the beginning of our time bucket Run.UntilTrue(() => DateTime.UtcNow.Subtract(DateTime.UtcNow.Floor(_period)).TotalMilliseconds < 100, null, TimeSpan.FromMilliseconds(50)); Trace.WriteLine(DateTime.UtcNow.Subtract(DateTime.UtcNow.Floor(_period)).TotalMilliseconds); Trace.WriteLine(DateTime.UtcNow.ToString("mm:ss.fff")); var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 5; i++) locker.AcquireLock("test"); sw.Stop(); Assert.True(sw.Elapsed.TotalSeconds < 1); sw.Reset(); sw.Start(); locker.AcquireLock("test"); sw.Stop(); Trace.WriteLine(sw.Elapsed); Assert.InRange(sw.Elapsed.TotalSeconds, 1.2, 2); } } }
apache-2.0
C#
fa705a68d3a9c9b0fcc974d7bc82738c473692bb
Update EllipseMarker.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Modules/Renderer/Avalonia/Nodes/Markers/EllipseMarker.cs
src/Core2D/Modules/Renderer/Avalonia/Nodes/Markers/EllipseMarker.cs
#nullable enable using Core2D.Modules.Renderer.Avalonia.Media; using AP = Avalonia.Platform; using AM = Avalonia.Media; namespace Core2D.Modules.Renderer.Avalonia.Nodes.Markers; internal class EllipseMarker : MarkerBase { public AM.EllipseGeometry? EllipseGeometry { get; set; } public override void Draw(object? dc) { if (dc is not AP.IDrawingContextImpl context) { return; } if (ShapeViewModel is { } && EllipseGeometry?.PlatformImpl is { }) { using var rotationDisposable = context.PushPreTransform(Rotation); context.DrawGeometry(ShapeViewModel.IsFilled ? Brush : null, ShapeViewModel.IsStroked ? Pen : null, EllipseGeometry.PlatformImpl); } } }
#nullable enable using Core2D.Modules.Renderer.Avalonia.Media; using AP = Avalonia.Platform; using AM = Avalonia.Media; namespace Core2D.Modules.Renderer.Avalonia.Nodes.Markers; internal class EllipseMarker : MarkerBase { public AM.EllipseGeometry? EllipseGeometry { get; set; } public override void Draw(object? dc) { if (dc is not AP.IDrawingContextImpl context) { return; } if (EllipseGeometry is { }) { using var rotationDisposable = context.PushPreTransform(Rotation); context.DrawGeometry(ShapeViewModel.IsFilled ? Brush : null, ShapeViewModel.IsStroked ? Pen : null, EllipseGeometry.PlatformImpl); } } }
mit
C#
c786e3209a854dea2756e7c8c18333e92f3cfb75
Remove unnecessary license header
dsbenghe/Novell.Directory.Ldap.NETStandard,dsbenghe/Novell.Directory.Ldap.NETStandard
src/Novell.Directory.Ldap.NETStandard/Utilclass/StringExtensions.cs
src/Novell.Directory.Ldap.NETStandard/Utilclass/StringExtensions.cs
using System; namespace Novell.Directory.Ldap.Utilclass { public static class StringExtensions { /// <summary> /// Replaces string.Substring(offset).StartsWith(value) and avoids memory allocations /// </summary> public static bool StartsWithStringAtOffset(this string baseString, string value, int offset) { if (value == null) throw new ArgumentNullException(nameof(value)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offset + value.Length > baseString.Length) { return false; } for (int i = 0; i < value.Length; i++) { if (baseString[offset + i] != value[i]) return false; } return true; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc., www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.Utilclass.TokenType.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap.Utilclass { public static class StringExtensions { /// <summary> /// Replaces string.Substring(offset).StartsWith(value) and avoids memory allocations /// </summary> public static bool StartsWithStringAtOffset(this string baseString, string value, int offset) { if (value == null) throw new ArgumentNullException(nameof(value)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offset + value.Length > baseString.Length) { return false; } for (int i = 0; i < value.Length; i++) { if (baseString[offset + i] != value[i]) return false; } return true; } } }
mit
C#
dbfaaf615a53e50c21cd9872801a50f14cc5f728
Disable test.
sjp/Schematic,sjp/Schematic,sjp/Schematic,sjp/Schematic,sjp/SJP.Schema
src/SJP.Schematic.Serialization.Tests/SnakeCaseNameProviderTests.cs
src/SJP.Schematic.Serialization.Tests/SnakeCaseNameProviderTests.cs
using System.IO; using System.Threading.Tasks; using NUnit.Framework; using SJP.Schematic.Core; using SJP.Schematic.Sqlite; namespace SJP.Schematic.Serialization.Tests { [TestFixture] internal static class SnakeCaseNameProviderTests { [Test] public static void SchemaToNamespace_GivenNullName_ThrowsArgumentNullException() { Assert.Pass(); } //[Test] //public static async Task Export_Test() //{ // const string connectionString = @"Data Source=C:\Users\sjp\Downloads\Northwind_large.sqlite"; // var connection = await SqliteDialect.CreateConnectionAsync(connectionString).ConfigureAwait(false); // var dialect = new SqliteDialect(connection); // var identifierDefaults = new IdentifierDefaultsBuilder() // .WithSchema("main") // .Build(); // try // { // var database = new SqliteRelationalDatabase(dialect, connection, identifierDefaults); // var serializer = new JsonRelationalDatabaseSerializer(); // const string outFilePath = @"C:\Users\sjp\Downloads\northwind_dump.json"; // var dtoText = await serializer.SerializeAsync(database).ConfigureAwait(false); // await File.WriteAllTextAsync(outFilePath, dtoText).ConfigureAwait(false); // _ = await serializer.DeserializeAsync(dtoText).ConfigureAwait(false); // } // finally // { // connection.Dispose(); // } //} } }
using System.IO; using System.Threading.Tasks; using NUnit.Framework; using SJP.Schematic.Core; using SJP.Schematic.Sqlite; namespace SJP.Schematic.Serialization.Tests { [TestFixture] internal static class SnakeCaseNameProviderTests { [Test] public static void SchemaToNamespace_GivenNullName_ThrowsArgumentNullException() { Assert.Pass(); } [Test] public static async Task Export_Test() { const string connectionString = @"Data Source=C:\Users\sjp\Downloads\Northwind_large.sqlite"; var connection = await SqliteDialect.CreateConnectionAsync(connectionString).ConfigureAwait(false); var dialect = new SqliteDialect(connection); var identifierDefaults = new IdentifierDefaultsBuilder() .WithSchema("main") .Build(); try { var database = new SqliteRelationalDatabase(dialect, connection, identifierDefaults); var serializer = new JsonRelationalDatabaseSerializer(); const string outFilePath = @"C:\Users\sjp\Downloads\northwind_dump.json"; var dtoText = await serializer.SerializeAsync(database).ConfigureAwait(false); await File.WriteAllTextAsync(outFilePath, dtoText).ConfigureAwait(false); _ = await serializer.DeserializeAsync(dtoText).ConfigureAwait(false); } finally { connection.Dispose(); } } } }
mit
C#
e9689d6e2a472946a1478067d3fc6bfedd1d3209
Update font-awesome
martincostello/website,martincostello/website,martincostello/website,martincostello/website
src/Website/Pages/Shared/_StylesBody.cshtml
src/Website/Pages/Shared/_StylesBody.cshtml
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch@5.1.3/dist/flatly/bootstrap.min.css" integrity="sha384-JJl14kOPjuUj+o0fDTJGBSCDKpu1A4BuCmARIetHUvTVmopvVZITFd4AhRMJIlz7" crossorigin="anonymous" referrerpolicy="no-referrer"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="~/assets/css/site.css" asp-append-version="true" asp-inline="true" asp-minify-inlined="true" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch@5.1.3/dist/flatly/bootstrap.min.css" integrity="sha384-JJl14kOPjuUj+o0fDTJGBSCDKpu1A4BuCmARIetHUvTVmopvVZITFd4AhRMJIlz7" crossorigin="anonymous" referrerpolicy="no-referrer"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="~/assets/css/site.css" asp-append-version="true" asp-inline="true" asp-minify-inlined="true" />
apache-2.0
C#
ff5baa1993478ce5860621d7444d6b02e7373513
Add the enum value for BindingFlags.DoNotWrapExceptions (#4433)
gregkalapos/corert,shrah/corert,gregkalapos/corert,gregkalapos/corert,shrah/corert,shrah/corert,shrah/corert,gregkalapos/corert
src/System.Private.CoreLib/shared/System/Reflection/BindingFlags.cs
src/System.Private.CoreLib/shared/System/Reflection/BindingFlags.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Reflection { [Flags] public enum BindingFlags { // NOTES: We have lookup masks defined in RuntimeType and Activator. If we // change the lookup values then these masks may need to change also. // a place holder for no flag specifed Default = 0x00, // These flags indicate what to search for when binding IgnoreCase = 0x01, // Ignore the case of Names while searching DeclaredOnly = 0x02, // Only look at the members declared on the Type Instance = 0x04, // Include Instance members in search Static = 0x08, // Include Static members in search Public = 0x10, // Include Public members in search NonPublic = 0x20, // Include Non-Public members in search FlattenHierarchy = 0x40, // Rollup the statics into the class. // These flags are used by InvokeMember to determine // what type of member we are trying to Invoke. // BindingAccess = 0xFF00; InvokeMethod = 0x0100, CreateInstance = 0x0200, GetField = 0x0400, SetField = 0x0800, GetProperty = 0x1000, SetProperty = 0x2000, // These flags are also used by InvokeMember but they should only // be used when calling InvokeMember on a COM object. PutDispProperty = 0x4000, PutRefDispProperty = 0x8000, ExactBinding = 0x010000, // Bind with Exact Type matching, No Change type SuppressChangeType = 0x020000, // DefaultValueBinding will return the set of methods having ArgCount or // more parameters. This is used for default values, etc. OptionalParamBinding = 0x040000, // These are a couple of misc attributes used IgnoreReturn = 0x01000000, // This is used in COM Interop DoNotWrapExceptions = 0x02000000, // Disables wrapping exceptions in TargetInvocationException } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Reflection { [Flags] public enum BindingFlags { // NOTES: We have lookup masks defined in RuntimeType and Activator. If we // change the lookup values then these masks may need to change also. // a place holder for no flag specifed Default = 0x00, // These flags indicate what to search for when binding IgnoreCase = 0x01, // Ignore the case of Names while searching DeclaredOnly = 0x02, // Only look at the members declared on the Type Instance = 0x04, // Include Instance members in search Static = 0x08, // Include Static members in search Public = 0x10, // Include Public members in search NonPublic = 0x20, // Include Non-Public members in search FlattenHierarchy = 0x40, // Rollup the statics into the class. // These flags are used by InvokeMember to determine // what type of member we are trying to Invoke. // BindingAccess = 0xFF00; InvokeMethod = 0x0100, CreateInstance = 0x0200, GetField = 0x0400, SetField = 0x0800, GetProperty = 0x1000, SetProperty = 0x2000, // These flags are also used by InvokeMember but they should only // be used when calling InvokeMember on a COM object. PutDispProperty = 0x4000, PutRefDispProperty = 0x8000, ExactBinding = 0x010000, // Bind with Exact Type matching, No Change type SuppressChangeType = 0x020000, // DefaultValueBinding will return the set of methods having ArgCount or // more parameters. This is used for default values, etc. OptionalParamBinding = 0x040000, // These are a couple of misc attributes used IgnoreReturn = 0x01000000, // This is used in COM Interop } }
mit
C#
782c3c42f90fc2c0b498f91005073a32a4866db3
Define 'Environment.NewLine'
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
stdlib/corlib/Environment.cs
stdlib/corlib/Environment.cs
namespace System { /// <summary> /// Defines logic that allows an application to interact with its environment. /// </summary> public static class Environment { /// <summary> /// Initializes the environment. /// </summary> /// <param name="argc"> /// The number of command-line arguments. /// </param> /// <param name="argv"> /// An array of command-line arguments, each represented as a C-style string. /// </param> /// <returns>An array of strings that can be passed to an entry point.</returns> /// <remarks> /// Only code generated by the compiler should touch this method; it is inaccessible to user code. /// </remarks> [#builtin_hidden] public static string[] Initialize(int argc, byte* * argv) { int newArgc = Math.Max(0, argc - 1); var stringArray = new string[newArgc]; for (int i = 1; i < argc; i++) { stringArray[i - 1] = String.FromCString(argv[i]); } return stringArray; } /// <summary> /// Gets the newline string. /// </summary> public static string NewLine => "\n"; } }
namespace System { /// <summary> /// Defines logic that allows an application to interact with its environment. /// </summary> public static class Environment { /// <summary> /// Initializes the environment. /// </summary> /// <param name="argc"> /// The number of command-line arguments. /// </param> /// <param name="argv"> /// An array of command-line arguments, each represented as a C-style string. /// </param> /// <returns>An array of strings that can be passed to an entry point.</returns> /// <remarks> /// Only code generated by the compiler should touch this method; it is inaccessible to user code. /// </remarks> [#builtin_hidden] public static string[] Initialize(int argc, byte* * argv) { int newArgc = Math.Max(0, argc - 1); var stringArray = new string[newArgc]; for (int i = 1; i < argc; i++) { stringArray[i - 1] = String.FromCString(argv[i]); } return stringArray; } } }
mit
C#
715d0aaca91a9687544787b4561b248d1b859181
Change initialize process.
ijufumi/garbage_calendar
garbage_calendar/App.xaml.cs
garbage_calendar/App.xaml.cs
using System; using garbage_calendar.Views; using Prism.Navigation; using Prism.Unity; using Xamarin.Forms; namespace garbage_calendar { public partial class App : PrismApplication { public App(IPlatformInitializer initializer = null) : base(initializer) { } protected override void OnInitialized() { InitializeComponent(); var dateTime = DateTime.Now; var parameters = new NavigationParameters {{"year", dateTime.Year}, {"month", dateTime.Month}}; NavigationService.NavigateAsync("NavigationPage/CalendarPage", parameters); } protected override void RegisterTypes() { Container.RegisterTypeForNavigation<NavigationPage>(); Container.RegisterTypeForNavigation<CalendarPage>(); } } }
using System; using garbage_calendar.Views; using Prism.Navigation; using Prism.Unity; using Xamarin.Forms; namespace garbage_calendar { public partial class App : PrismApplication { public App(IPlatformInitializer initializer = null) : base(initializer) { } protected override void OnInitialized() { InitializeComponent(); var dateTime = DateTime.Now; var parameters = new NavigationParameters(); parameters.Add("year", dateTime.Year); parameters.Add("month", dateTime.Month); NavigationService.NavigateAsync("NavigationPage/CalendarPage", parameters); } protected override void RegisterTypes() { Container.RegisterTypeForNavigation<NavigationPage>(); Container.RegisterTypeForNavigation<CalendarPage>(); } } }
mit
C#
365db953f357a146ac050be9ceed197fff064a88
Fix for help blowing up if a module or command lacks a summary
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX
Modix/Modules/InfoModule.cs
Modix/Modules/InfoModule.cs
using System.Linq; using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; namespace Modix.Modules { [Name("Info"), Summary("General helper module")] public sealed class InfoModule : ModuleBase { private CommandService commandService; public InfoModule(CommandService cs) { commandService = cs; } [Command("help"), Summary("Prints a neat list of all commands.")] public async Task HelpAsync() { var eb = new EmbedBuilder(); var userDm = await Context.User.GetOrCreateDMChannelAsync(); foreach (var module in commandService.Modules) { eb = eb.WithTitle($"Module: {module.Name ?? "Unknown"}") .WithDescription(module.Summary ?? "Unknown"); foreach(var command in module.Commands) { eb.AddField(new EmbedFieldBuilder().WithName($"Command: !{module.Name ?? ""} {command.Name ?? ""} {GetParams(command)}").WithValue(command.Summary ?? "Unknown")); } await userDm.SendMessageAsync(string.Empty, embed: eb.Build()); eb = new EmbedBuilder(); } await ReplyAsync($"Check your private messages, {Context.User.Mention}"); } private string GetParams(CommandInfo info) { var sb = new StringBuilder(); info.Parameters.ToList().ForEach(x => { if (x.IsOptional) sb.Append("[Optional(" + x.Name + ")]"); else sb.Append("[" + x.Name + "]"); }); return sb.ToString(); } } }
using System.Linq; using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; namespace Modix.Modules { [Name("Info"), Summary("General helper module")] public sealed class InfoModule : ModuleBase { private CommandService commandService; public InfoModule(CommandService cs) { commandService = cs; } [Command("help"), Summary("Prints a neat list of all commands.")] public async Task HelpAsync() { var eb = new EmbedBuilder(); var userDm = await Context.User.GetOrCreateDMChannelAsync(); foreach (var module in commandService.Modules) { eb = eb.WithTitle($"Module: {module.Name ?? ""}") .WithDescription(module.Summary ?? ""); foreach(var command in module.Commands) { eb.AddField(new EmbedFieldBuilder().WithName($"Command: !{module.Name ?? ""} {command.Name ?? ""} {GetParams(command)}").WithValue(command.Summary ?? "")); } await userDm.SendMessageAsync(string.Empty, embed: eb.Build()); eb = new EmbedBuilder(); } await ReplyAsync($"Check your private messages, {Context.User.Mention}"); } private string GetParams(CommandInfo info) { var sb = new StringBuilder(); info.Parameters.ToList().ForEach(x => { if (x.IsOptional) sb.Append("[Optional(" + x.Name + ")]"); else sb.Append("[" + x.Name + "]"); }); return sb.ToString(); } } }
mit
C#
bbc7393d221ab2c37ea1fbdc1100d99b8f8f2e72
Fix docs in 'SessionOptions'
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNet.Session/SessionOptions.cs
src/Microsoft.AspNet.Session/SessionOptions.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.AspNet.Session { public class SessionOptions { /// <summary> /// Determines the cookie name used to persist the session ID. /// Defaults to <see cref="SessionDefaults.CookieName"/>. /// </summary> public string CookieName { get; set; } = SessionDefaults.CookieName; /// <summary> /// Determines the domain used to create the cookie. Is not provided by default. /// </summary> public string CookieDomain { get; set; } /// <summary> /// Determines the path used to create the cookie. /// Defaults to <see cref="SessionDefaults.CookiePath"/>. /// </summary> public string CookiePath { get; set; } = SessionDefaults.CookiePath; /// <summary> /// Determines if the browser should allow the cookie to be accessed by client-side JavaScript. The /// default is true, which means the cookie will only be passed to HTTP requests and is not made available /// to script on the page. /// </summary> public bool CookieHttpOnly { get; set; } = true; /// <summary> /// The IdleTimeout indicates how long the session can be idle before its contents are abandoned. Each session access /// resets the timeout. Note this only applies to the content of the session, not the cookie. /// </summary> public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromMinutes(20); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.AspNet.Session { public class SessionOptions { /// <summary> /// Determines the cookie name used to persist the session ID. The default value is ".AspNet.Session". /// </summary> public string CookieName { get; set; } = SessionDefaults.CookieName; /// <summary> /// Determines the domain used to create the cookie. Is not provided by default. /// </summary> public string CookieDomain { get; set; } /// <summary> /// Determines the path used to create the cookie. The default value is "/" for highest browser compatibility. /// </summary> public string CookiePath { get; set; } = SessionDefaults.CookiePath; /// <summary> /// Determines if the browser should allow the cookie to be accessed by client-side JavaScript. The /// default is true, which means the cookie will only be passed to HTTP requests and is not made available /// to script on the page. /// </summary> public bool CookieHttpOnly { get; set; } = true; /// <summary> /// The IdleTimeout indicates how long the session can be idle before its contents are abandoned. Each session access /// resets the timeout. Note this only applies to the content of the session, not the cookie. /// </summary> public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromMinutes(20); } }
apache-2.0
C#
24f6d4dd8762166eb648a63a2f712b0140e32991
Fix Markdown test
octokit-net-test/octokit.net,M-Zuber/octokit.net,fffej/octokit.net,editor-tools/octokit.net,shiftkey/octokit.net,octokit-net-test-org/octokit.net,kolbasov/octokit.net,Sarmad93/octokit.net,takumikub/octokit.net,SamTheDev/octokit.net,fake-organization/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,nsnnnnrn/octokit.net,shana/octokit.net,octokit/octokit.net,thedillonb/octokit.net,rlugojr/octokit.net,shana/octokit.net,kdolan/octokit.net,khellang/octokit.net,naveensrinivasan/octokit.net,shiftkey-tester/octokit.net,hitesh97/octokit.net,forki/octokit.net,octokit-net-test-org/octokit.net,magoswiat/octokit.net,ivandrofly/octokit.net,geek0r/octokit.net,mminns/octokit.net,cH40z-Lord/octokit.net,michaKFromParis/octokit.net,shiftkey-tester/octokit.net,adamralph/octokit.net,alfhenrik/octokit.net,eriawan/octokit.net,nsrnnnnn/octokit.net,Sarmad93/octokit.net,chunkychode/octokit.net,thedillonb/octokit.net,TattsGroup/octokit.net,ivandrofly/octokit.net,dampir/octokit.net,shiftkey/octokit.net,daukantas/octokit.net,SamTheDev/octokit.net,SLdragon1989/octokit.net,alfhenrik/octokit.net,bslliw/octokit.net,hahmed/octokit.net,ChrisMissal/octokit.net,darrelmiller/octokit.net,hahmed/octokit.net,chunkychode/octokit.net,dampir/octokit.net,eriawan/octokit.net,gdziadkiewicz/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,M-Zuber/octokit.net,brramos/octokit.net,gabrielweyer/octokit.net,mminns/octokit.net,rlugojr/octokit.net,khellang/octokit.net,gdziadkiewicz/octokit.net,SmithAndr/octokit.net,SmithAndr/octokit.net,editor-tools/octokit.net,Red-Folder/octokit.net,devkhan/octokit.net,dlsteuer/octokit.net,TattsGroup/octokit.net,gabrielweyer/octokit.net,octokit/octokit.net,devkhan/octokit.net
Octokit.Tests.Integration/Clients/MiscellaneousClientTests.cs
Octokit.Tests.Integration/Clients/MiscellaneousClientTests.cs
using System.Threading.Tasks; using Octokit; using Octokit.Tests.Integration; using Xunit; public class MiscellaneousClientTests { public class TheGetEmojisMethod { [IntegrationTest] public async Task GetsAllTheEmojis() { var github = new GitHubClient(new ProductHeaderValue("OctokitTests")) { Credentials = Helper.Credentials }; var emojis = await github.Miscellaneous.GetEmojis(); Assert.True(emojis.Count > 1); } } public class TheRenderRawMarkdownMethod { [IntegrationTest] public async Task CanRenderGitHubFlavoredMarkdown() { var github = new GitHubClient(new ProductHeaderValue("OctokitTests")) { Credentials = Helper.Credentials }; var result = await github.Miscellaneous.RenderRawMarkdown("This is\r\n a **test**"); Assert.Equal("<p>This is\n a <strong>test</strong></p>\n", result); } } }
using System.Threading.Tasks; using Octokit; using Octokit.Tests.Integration; using Xunit; public class MiscellaneousClientTests { public class TheGetEmojisMethod { [IntegrationTest] public async Task GetsAllTheEmojis() { var github = new GitHubClient(new ProductHeaderValue("OctokitTests")) { Credentials = Helper.Credentials }; var emojis = await github.Miscellaneous.GetEmojis(); Assert.True(emojis.Count > 1); } } public class TheRenderRawMarkdownMethod { [IntegrationTest] public async Task CanRenderGitHubFlavoredMarkdown() { var github = new GitHubClient(new ProductHeaderValue("OctokitTests")) { Credentials = Helper.Credentials }; var result = await github.Miscellaneous.RenderRawMarkdown("This is a **test**"); Assert.Equal("<p>This is a <strong>test</strong></p>", result); } } }
mit
C#
6a12f641a997de7df1e24fe8138758c0a60213ae
Fix ACU sensors (#7599)
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/Objects/Atmospherics/AcuSensor.cs
UnityProject/Assets/Scripts/Objects/Atmospherics/AcuSensor.cs
using UnityEngine; namespace Objects.Atmospherics { /// <summary> /// Simple device that samples the ambient atmosphere for reporting to a connected <see cref="AirController"/>. /// </summary> public class AcuSensor : MonoBehaviour, IServerSpawn, IAcuControllable { public AcuSample AtmosphericSample => atmosphericSample.FromGasMix(metaNode.GasMix); private readonly AcuSample atmosphericSample = new AcuSample(); private MetaDataNode metaNode; public void OnSpawnServer(SpawnInfo info) { var registerTile = gameObject.RegisterTile(); metaNode = MatrixManager.GetMetaDataAt(registerTile.WorldPosition); registerTile.OnLocalPositionChangedServer.AddListener((newLocalPosition) => { metaNode = MatrixManager.GetMetaDataAt(registerTile.WorldPosition); }); } // Don't care about the ACU operating mode. public void SetOperatingMode(AcuMode mode) { } } }
using UnityEngine; namespace Objects.Atmospherics { /// <summary> /// Simple device that samples the ambient atmosphere for reporting to a connected <see cref="AirController"/>. /// </summary> public class AcuSensor : MonoBehaviour, IServerSpawn, IAcuControllable { public AcuSample AtmosphericSample => atmosphericSample.FromGasMix(metaNode.GasMix); private readonly AcuSample atmosphericSample = new AcuSample(); private MetaDataNode metaNode; public void OnSpawnServer(SpawnInfo info) { var registerTile = gameObject.RegisterTile(); var metaDataLayer = MatrixManager.AtPoint(registerTile.WorldPositionServer, true).MetaDataLayer; metaNode = metaDataLayer.Get(registerTile.LocalPositionServer, false); } // Don't care about the ACU operating mode. public void SetOperatingMode(AcuMode mode) { } } }
agpl-3.0
C#
3ff3165a42d9afc9a2d45d51e7fac7c7070a89a4
add exception throw test
TerribleDev/UriBuilder.Fluent
src/UriBuilder.Fluent.UnitTests/ThrowsTests.cs
src/UriBuilder.Fluent.UnitTests/ThrowsTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace FluentUriBuilder.Tests { public class ThrowsTests { [Fact] public void ThrowsArgNull() { var tstObj = new UriBuilder(); Assert.Throws<ArgumentNullException>(() => tstObj.WithParameter(string.Empty, string.Empty)); Assert.Throws<ArgumentNullException>(() => tstObj.WithPathSegment(null)); Assert.Throws<ArgumentNullException>(() => tstObj.WithScheme(null)); Assert.Throws<ArgumentNullException>(() => tstObj.WithHost(null)); Assert.Throws<ArgumentNullException>(() => tstObj.WithParameter(parameterDictionary: null)); Assert.Throws<ArgumentOutOfRangeException>(() => tstObj.WithPort(-1)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace FluentUriBuilder.Tests { public class ThrowsTests { [Fact] public void ThrowsArgNull() { var tstObj = new UriBuilder(); Assert.Throws<ArgumentNullException>(() => tstObj.WithParameter(string.Empty, string.Empty)); Assert.Throws<ArgumentNullException>(() => tstObj.WithPathSegment(null)); Assert.Throws<ArgumentNullException>(() => tstObj.WithScheme(null)); Assert.Throws<ArgumentNullException>(() => tstObj.WithHost(null)); Assert.Throws<ArgumentOutOfRangeException>(() => tstObj.WithPort(-1)); } } }
mit
C#
52a17806f8f8d631e12bd20d19465741b61ce154
Improve and document Message.
CaptainHayashi/ironfrost
libironfrost/Message.cs
libironfrost/Message.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ironfrost { /// <summary> /// A Bifrost message. /// /// <para> /// <c>Message</c> can be constructed from, and used as, /// a string enumerator. /// </para> /// </summary> public class Message : IEnumerable<string> { /// <summary> /// The Message's unique identifier. /// /// <para> /// Tags can also be used for routing. /// </para> /// </summary> public string Tag { get; } /// <summary> /// The message word, which identifies the type of message. /// </summary> public string Word { get; } /// <summary> /// The message arguments. /// </summary> public string[] Args { get; } /// <summary> /// Constructs a message from a tag, word, and argument list. /// </summary> /// <param name="tag"> /// The new message's tag. /// </param> /// <param name="word"> /// The new message's message word. /// </param> /// <param name="args"> /// The new message's argument list. /// </param> public Message(string tag, string word, IEnumerable<string> args) { Tag = tag; Word = word; Args = args.ToArray(); } /// <summary> /// Constructs a message from a word list. /// /// <para> /// The first word is used as the message's tag. /// The second word is used as the message word. /// All further words are used as arguments. /// </para> /// </summary> /// <param name="words"> /// The list of words. /// There must be at least 2 words. /// </param> public Message(IEnumerable<string> words) : this(words.First(), words.ElementAt(1), words.Skip(2)) { } /// <summary> /// Gets a string enumerator for this <c>Message</c>. /// </summary> /// <returns> /// A string <c>IEnumerator</c>. /// The enumerator yields the <c>Message</c>'s tag, word, /// and arguments. /// </returns> public IEnumerator<string> GetEnumerator() { yield return Tag; yield return Word; foreach (var arg in Args) { yield return arg; } } /// <summary> /// Gets a string enumerator for this <c>Message</c>. /// </summary> /// <returns> /// A string <c>IEnumerator</c>. /// The enumerator yields the <c>Message</c>'s tag, word, /// and arguments. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using System.Collections.Generic; using System.Linq; namespace ironfrost { public class Message { public string Tag { get; } public string Word { get; } public string[] Args { get; } public Message(IEnumerable<string> words) { Tag = words.First(); Word = words.Skip(1).First(); Args = words.Skip(2).ToArray(); } } }
mit
C#
9d603be64b031c159bc2d94c2093e2ac92ac24c5
Allow properties to be nullable to support V12 databases
Linq2Azure/API,Linq2Azure/API
SqlDatabases/Database.cs
SqlDatabases/Database.cs
using System; using System.Xml.Linq; namespace Linq2Azure.SqlDatabases { public class Database { internal Database(XElement xml, DatabaseServer databaseServer) { xml.HydrateObject(XmlNamespaces.WindowsAzure, this); DatabaseServer = databaseServer; } public DatabaseServer DatabaseServer { get; private set; } public string Name { get; private set; } public string Type { get; private set; } public string State { get; private set; } public Uri SelfLink { get; private set; } public Uri ParentLink { get; private set; } public int Id { get; private set; } public string Edition { get; private set; } public string CollationName { get; private set; } public DateTimeOffset CreationDate { get; private set; } public bool IsFederationRoot { get; private set; } public bool IsSystemObject { get; private set; } public decimal? SizeMB { get; private set; } public long MaxSizeBytes { get; private set; } public Guid ServiceObjectiveId { get; private set; } public Guid AssignedServiceObjectiveId { get; private set; } public int? ServiceObjectiveAssignmentState { get; private set; } public string ServiceObjectiveAssignmentStateDescription { get; private set; } public int ServiceObjectiveAssignmentErrorCode { get; private set; } public string ServiceObjectiveAssignmentErrorDescription { get; private set; } public DateTimeOffset? ServiceObjectiveAssignmentSuccessDate { get; private set; } public DateTimeOffset? RecoveryPeriodStartDate { get; private set; } public bool IsSuspended { get; private set; } } }
using System; using System.Xml.Linq; namespace Linq2Azure.SqlDatabases { public class Database { internal Database(XElement xml, DatabaseServer databaseServer) { xml.HydrateObject(XmlNamespaces.WindowsAzure, this); DatabaseServer = databaseServer; } public DatabaseServer DatabaseServer { get; private set; } public string Name { get; private set; } public string Type { get; private set; } public string State { get; private set; } public Uri SelfLink { get; private set; } public Uri ParentLink { get; private set; } public int Id { get; private set; } public string Edition { get; private set; } public string CollationName { get; private set; } public DateTimeOffset CreationDate { get; private set; } public bool IsFederationRoot { get; private set; } public bool IsSystemObject { get; private set; } public decimal? SizeMB { get; private set; } public long MaxSizeBytes { get; private set; } public Guid ServiceObjectiveId { get; private set; } public Guid AssignedServiceObjectiveId { get; private set; } public int ServiceObjectiveAssignmentState { get; private set; } public string ServiceObjectiveAssignmentStateDescription { get; private set; } public int ServiceObjectiveAssignmentErrorCode { get; private set; } public string ServiceObjectiveAssignmentErrorDescription { get; private set; } public DateTimeOffset ServiceObjectiveAssignmentSuccessDate { get; private set; } public DateTimeOffset? RecoveryPeriodStartDate { get; private set; } public bool IsSuspended { get; private set; } } }
mit
C#
7d69a9827d099cc2a8d39b5255dfbc739ab20411
Fix SendTimeout initialization
takenet/messaginghub-client-csharp
src/Takenet.MessagingHub.Client.WebHost/HttpMessagingHubConnection.cs
src/Takenet.MessagingHub.Client.WebHost/HttpMessagingHubConnection.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Web; using Lime.Protocol.Client; using Takenet.MessagingHub.Client.Connection; using Takenet.MessagingHub.Client.Host; using Lime.Protocol.Serialization; namespace Takenet.MessagingHub.Client.WebHost { public class HttpMessagingHubConnection : IMessagingHubConnection { public bool IsConnected { get; private set; } public TimeSpan SendTimeout { get; private set; } public int MaxConnectionRetries { get; set; } public IOnDemandClientChannel OnDemandClientChannel { get; } public HttpMessagingHubConnection(IEnvelopeBuffer envelopeBuffer, IEnvelopeSerializer serializer, Application applicationSettings) { OnDemandClientChannel = new HttpOnDemandClientChannel(envelopeBuffer, serializer, applicationSettings); SendTimeout = TimeSpan.FromMilliseconds(applicationSettings.SendTimeout <= 0 ? 10000 : applicationSettings.SendTimeout); } public Task ConnectAsync(CancellationToken cancellationToken = default(CancellationToken)) { IsConnected = true; return Task.CompletedTask; } public Task DisconnectAsync(CancellationToken cancellationToken = default(CancellationToken)) { IsConnected = false; return Task.CompletedTask; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Web; using Lime.Protocol.Client; using Takenet.MessagingHub.Client.Connection; using Takenet.MessagingHub.Client.Host; using Lime.Protocol.Serialization; namespace Takenet.MessagingHub.Client.WebHost { public class HttpMessagingHubConnection : IMessagingHubConnection { public bool IsConnected { get; private set; } public TimeSpan SendTimeout { get; } public int MaxConnectionRetries { get; set; } public IOnDemandClientChannel OnDemandClientChannel { get; } public HttpMessagingHubConnection(IEnvelopeBuffer envelopeBuffer, IEnvelopeSerializer serializer, Application applicationSettings) { OnDemandClientChannel = new HttpOnDemandClientChannel(envelopeBuffer, serializer, applicationSettings); } public Task ConnectAsync(CancellationToken cancellationToken = default(CancellationToken)) { IsConnected = true; return Task.CompletedTask; } public Task DisconnectAsync(CancellationToken cancellationToken = default(CancellationToken)) { IsConnected = false; return Task.CompletedTask; } } }
apache-2.0
C#
6159e93620460ce25987d2a4c67dbb757ca7c2bf
Fix for React "colSpan" (not "colspan") attribute - fixes #1
ProductiveRage/Bridge.React,ProductiveRage/Bridge.React
Bridge.React/Attributes/TableCellAttributes.cs
Bridge.React/Attributes/TableCellAttributes.cs
using Bridge.Html5; namespace Bridge.React { [ObjectLiteral] public sealed class TableCellAttributes : ReactDomElementAttributes<TableCellElement> { public int ColSpan { private get; set; } public int RowSpan { private get; set; } public int CellIndex { private get; set; } } }
using Bridge.Html5; namespace Bridge.React { [ObjectLiteral] public sealed class TableCellAttributes : ReactDomElementAttributes<TableCellElement> { [Name("colspan")] public int ColSpan { private get; set; } [Name("rowspan")] public string RowSpan { private get; set; } public int CellIndex { private get; set; } } }
mit
C#
969ab2161760077d3b7f2347851c6bfc1e12b709
Remove ClientID
xamarin/google-apis,michael-jia-sage/google-apis
samples/Google.Apis.iOS.Sample/AppDelegate.cs
samples/Google.Apis.iOS.Sample/AppDelegate.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Google.Apis.Authentication.OAuth2; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; using MonoTouch.Dialog; using MonoTouch.Foundation; using MonoTouch.UIKit; using Xamarin.Auth; namespace Google.Apis.iOS.Sample { [Register("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { public const string ClientID = "Your Client ID"; public const string RedirectUrl = "Your redirect URL"; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); this.auth = new GoogleAuthenticator (ClientID, new Uri (RedirectUrl), TasksService.Scopes.Tasks.GetStringValue()); this.auth.Completed += (sender, e) => { if (e.IsAuthenticated) BeginInvokeOnMainThread (Setup); else BeginInvokeOnMainThread (ShowLogin); }; ShowLogin(); window.MakeKeyAndVisible(); return true; } private void ShowLogin() { UIViewController loginController = this.auth.GetUI(); window.RootViewController = loginController; } private void Setup() { this.service = new TasksService (this.auth); window.RootViewController = new UINavigationController (new TaskListsViewController (this.service)); } private TasksService service; private GoogleAuthenticator auth; private UIWindow window; private static int busy; public static void AddActivity() { UIApplication.SharedApplication.InvokeOnMainThread (() => { if (busy++ < 1) UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; }); } public static void FinishActivity() { UIApplication.SharedApplication.InvokeOnMainThread(() => { if (--busy < 1) UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Google.Apis.Authentication.OAuth2; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; using MonoTouch.Dialog; using MonoTouch.Foundation; using MonoTouch.UIKit; using Xamarin.Auth; namespace Google.Apis.iOS.Sample { [Register("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { public const string ClientID = "546770234068-1qtjfqjoad3pmp1blo2ndvp7cc8lscvb.apps.googleusercontent.com"; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); this.auth = new GoogleAuthenticator (ClientID, new Uri ("http://www.facebook.com/connect/login_success.html"), TasksService.Scopes.Tasks.GetStringValue()); this.auth.Completed += (sender, e) => { if (e.IsAuthenticated) BeginInvokeOnMainThread (Setup); else BeginInvokeOnMainThread (ShowLogin); }; ShowLogin(); window.MakeKeyAndVisible(); return true; } private void ShowLogin() { UIViewController loginController = this.auth.GetUI(); window.RootViewController = loginController; } private void Setup() { this.service = new TasksService (this.auth); window.RootViewController = new UINavigationController (new TaskListsViewController (this.service)); } private TasksService service; private GoogleAuthenticator auth; private UIWindow window; private static int busy; public static void AddActivity() { UIApplication.SharedApplication.InvokeOnMainThread (() => { if (busy++ < 1) UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; }); } public static void FinishActivity() { UIApplication.SharedApplication.InvokeOnMainThread(() => { if (--busy < 1) UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; }); } } }
apache-2.0
C#
7707beb3734949974261ec7e9486441eb75f9c6a
improve printf sample
altimesh/hybridizer-basic-samples,altimesh/hybridizer-basic-samples
HybridizerBasicSamples_CUDA100/1.Simple/Printf/SimplePrintf/Program.cs
HybridizerBasicSamples_CUDA100/1.Simple/Printf/SimplePrintf/Program.cs
using Hybridizer.Runtime.CUDAImports; using System; namespace HelloWorld { class Program { [EntryPoint] public static void Run(int N, int[] a) { for (int i = threadIdx.x + blockDim.x * blockIdx.x; i < N; i += blockDim.x * gridDim.x) { Console.Out.Write("hello from thread = {0} in block = {1} a[i] = {2}\n", threadIdx.x, blockIdx.x, a[i]); }; } static void Main(string[] args) { int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; // create an instance of HybRunner object to wrap calls on GPU HybRunner runner = HybRunner.Cuda().SetDistrib(4,4); // create a wrapper object to call GPU methods instead of C# dynamic wrapped = runner.Wrap(new Program()); // run the method on GPU wrapped.Run(a.Length, a); // synchronize the GPU to flush stdout on the device // add error checking cuda.ERROR_CHECK(cuda.DeviceSynchronize()); } } }
using Hybridizer.Runtime.CUDAImports; using System; using System.Threading.Tasks; namespace HelloWorld { class Program { [EntryPoint("run")] public static void Run(int N, int[] a) { for (int i = threadIdx.x + blockDim.x * blockIdx.x; i < N; i += blockDim.x * gridDim.x) { Console.Out.Write("hello from thread = {0} in block = {1} a[i] = {2}\n", threadIdx.x, blockIdx.x, a[i]); }; } static void Main(string[] args) { int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; // create an instance of HybRunner object to wrap calls on GPU HybRunner runner = HybRunner.Cuda().SetDistrib(4,4); // create a wrapper object to call GPU methods instead of C# dynamic wrapped = runner.Wrap(new Program()); // run the method on GPU wrapped.Run(a.Length, a); } } }
mit
C#
5f4f34f9dd5357dd0dd654eb6f2c01d233a2dad1
Fix paths in ISkillManagementApi
stoiveyp/Alexa.NET.Management
Alexa.NET.Management/ISkillManagementApi.cs
Alexa.NET.Management/ISkillManagementApi.cs
using System.Threading.Tasks; using Refit; namespace Alexa.NET.Management { public interface ISkillManagementApi { [Get("skills/{skillId}"), Headers("Authorization: Bearer")] Task<Skill> Get(string skillId); [Post("skills/{vendorId}"), Headers("Authorization: Bearer")] Task<SkillId> Create(string vendorId, [Body]Skill skill); [Put("skills/{skillId}"), Headers("Authorization: Bearer")] Task<SkillId> Update(string skillId, [Body] Skill skill); [Get("skills/{skillId}/status"), Headers("Authorization: Bearer")] Task<SkillStatus> Status(string skillId); } }
using System.Threading.Tasks; using Refit; namespace Alexa.NET.Management { public interface ISkillManagementApi { [Get("{skillId}"), Headers("Authorization: Bearer")] Task<Skill> Get(string skillId); [Post("{vendorId}"), Headers("Authorization: Bearer")] Task<SkillId> Create(string vendorId, [Body]Skill skill); [Put("{skillId}"), Headers("Authorization: Bearer")] Task<SkillId> Update(string skillId, [Body] Skill skill); [Get("{skillId}/status"), Headers("Authorization: Bearer")] Task<SkillStatus> Status(string skillId); } }
mit
C#
91b98a2ddc541b7df50c8230c1b21b5b66881862
fix IManner
angeldnd/dap.core.csharp
Scripts/DapCore/context_/IManner.cs
Scripts/DapCore/context_/IManner.cs
using System; namespace angeldnd.dap { public interface IManner : IInDictElement { Properties Properties { get; } Channels Channels { get; } Handlers Handlers { get; } Bus Bus { get; } Vars Vars { get; } Manners Manners { get; } } }
using System; namespace angeldnd.dap { public interface IManner { Properties Properties { get; } Channels Channels { get; } Handlers Handlers { get; } Bus Bus { get; } Vars Vars { get; } Manners Manners { get; } } }
mit
C#
c10a91a33ed488bdc57d219224fb86355b9c6266
Add odd/even type to test scenes
smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new
osu.Game.Rulesets.Mania.Tests/Skinning/ColumnTestContainer.cs
osu.Game.Rulesets.Mania.Tests/Skinning/ColumnTestContainer.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.Framework.Graphics.Containers; using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Mania.UI; using osuTK.Graphics; namespace osu.Game.Rulesets.Mania.Tests.Skinning { /// <summary> /// A container to be used in a <see cref="ManiaSkinnableTestScene"/> to provide a resolvable <see cref="Column"/> dependency. /// </summary> public class ColumnTestContainer : Container { protected override Container<Drawable> Content => content; private readonly Container content; [Cached] private readonly Column column; public ColumnTestContainer(int column, ManiaAction action) { this.column = new Column(column) { Action = { Value = action }, AccentColour = Color4.Orange, ColumnType = column % 2 == 0 ? ColumnType.Even : ColumnType.Odd }; InternalChild = content = new ManiaInputManager(new ManiaRuleset().RulesetInfo, 4) { RelativeSizeAxes = Axes.Both }; } } }
// 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.Framework.Graphics.Containers; using osu.Game.Rulesets.Mania.UI; using osuTK.Graphics; namespace osu.Game.Rulesets.Mania.Tests.Skinning { /// <summary> /// A container to be used in a <see cref="ManiaSkinnableTestScene"/> to provide a resolvable <see cref="Column"/> dependency. /// </summary> public class ColumnTestContainer : Container { protected override Container<Drawable> Content => content; private readonly Container content; [Cached] private readonly Column column; public ColumnTestContainer(int column, ManiaAction action) { this.column = new Column(column) { Action = { Value = action }, AccentColour = Color4.Orange }; InternalChild = content = new ManiaInputManager(new ManiaRuleset().RulesetInfo, 4) { RelativeSizeAxes = Axes.Both }; } } }
mit
C#
a4b001d4764f3883903c627f6814911b462b6636
Fix Swagger UI empty Path #2510 (#2517) (#2561)
RSuter/NSwag,RSuter/NSwag,RSuter/NSwag,RSuter/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,RSuter/NSwag,quails4Eva/NSwag
src/NSwag.AspNetCore/Middlewares/RedirectToIndexMiddleware.cs
src/NSwag.AspNetCore/Middlewares/RedirectToIndexMiddleware.cs
//----------------------------------------------------------------------- // <copyright file="RedirectMiddleware.cs" company="NSwag"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/RicoSuter/NSwag/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace NSwag.AspNetCore.Middlewares { internal class RedirectToIndexMiddleware { private readonly RequestDelegate _nextDelegate; private readonly string _swaggerUiRoute; private readonly string _swaggerRoute; private readonly Func<string, HttpRequest, string> _transformToExternal; public RedirectToIndexMiddleware(RequestDelegate nextDelegate, string internalSwaggerUiRoute, string internalSwaggerRoute, Func<string, HttpRequest, string> transformToExternal) { _nextDelegate = nextDelegate; _swaggerUiRoute = internalSwaggerUiRoute; _swaggerRoute = internalSwaggerRoute; _transformToExternal = transformToExternal; } public async Task Invoke(HttpContext context) { if (context.Request.Path.HasValue && string.Equals(context.Request.Path.Value.Trim('/'), _swaggerUiRoute.Trim('/'), StringComparison.OrdinalIgnoreCase)) { context.Response.StatusCode = StatusCodes.Status302Found; var suffix = !string.IsNullOrWhiteSpace(_swaggerRoute) ? "?url=" + _transformToExternal(_swaggerRoute, context.Request) : ""; var path = _transformToExternal(_swaggerUiRoute, context.Request); context.Response.Headers.Add("Location", (path != "/" ? path : "") + "/index.html" + suffix); } else { await _nextDelegate.Invoke(context); } } } }
//----------------------------------------------------------------------- // <copyright file="RedirectMiddleware.cs" company="NSwag"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/RicoSuter/NSwag/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace NSwag.AspNetCore.Middlewares { internal class RedirectToIndexMiddleware { private readonly RequestDelegate _nextDelegate; private readonly string _swaggerUiRoute; private readonly string _swaggerRoute; private readonly Func<string, HttpRequest, string> _transformToExternal; public RedirectToIndexMiddleware(RequestDelegate nextDelegate, string internalSwaggerUiRoute, string internalSwaggerRoute, Func<string, HttpRequest, string> transformToExternal) { _nextDelegate = nextDelegate; _swaggerUiRoute = internalSwaggerUiRoute; _swaggerRoute = internalSwaggerRoute; _transformToExternal = transformToExternal; } public async Task Invoke(HttpContext context) { if (context.Request.Path.HasValue && string.Equals(context.Request.Path.Value.Trim('/'), _swaggerUiRoute.Trim('/'), StringComparison.OrdinalIgnoreCase)) { context.Response.StatusCode = 302; var suffix = !string.IsNullOrWhiteSpace(_swaggerRoute) ? "?url=" + _transformToExternal(_swaggerRoute, context.Request) : ""; var path = _transformToExternal(_swaggerUiRoute, context.Request); context.Response.Headers.Add("Location", (path != "/" ? path : "") + "/index.html" + suffix); } else { await _nextDelegate.Invoke(context); } } } }
mit
C#
9b51ad854b00f4329ff5ab9ee042fe42f2c8ddf7
Update MyProductsController.cs
amantur/DurandalTest,amantur/DurandalTest
ddlTest/Controllers/MyProductsController.cs
ddlTest/Controllers/MyProductsController.cs
using System.Linq; using System.Web.Mvc; using Newtonsoft.Json; using System.Collections.Generic; using System; using ddlTest.Models; namespace Nop.Plugin.NopCustom.MyProductList.Controllers { public class MyProductsController : Controller { public ViewResult Index(int pageIndex = 0, int pageSize = 10) { return View(); } public ViewResult Test() { return View(); } public JsonResult SearchProduct(string query, int pageIndex = 0, int pageSize = 10) { var ret = new JsonResult() { Data = Service.SearchProduct(query), ContentType = "text/json", ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet, MaxJsonLength = int.MaxValue }; return ret; } public JsonResult Products(int pageIndex = 0, int pageSize = 10) { return new JsonResult { Data = Service.SearchMyProduct(new SearchCriteria(), pageIndex, pageSize), ContentType = "text/json", ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet, MaxJsonLength = int.MaxValue }; } } }
using System.Linq; using System.Web.Mvc; using Newtonsoft.Json; using System.Collections.Generic; using System; using ddlTest.Models; namespace Nop.Plugin.NopCustom.MyProductList.Controllers { public class MyProductsController : Controller { public ViewResult Index(int pageIndex = 0, int pageSize = 10) { return View(); } public ViewResult Add() { return View(); } public JsonResult SearchProduct(string query, int pageIndex = 0, int pageSize = 10) { var ret = new JsonResult() { Data = Service.SearchProduct(query), ContentType = "text/json", ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet, MaxJsonLength = int.MaxValue }; return ret; } public JsonResult Products(int pageIndex = 0, int pageSize = 10) { return new JsonResult { Data = Service.SearchMyProduct(new SearchCriteria(), pageIndex, pageSize), ContentType = "text/json", ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet, MaxJsonLength = int.MaxValue }; } } }
mpl-2.0
C#
814da021806679f88d0d5b6dc970b97100d007d3
fix creation of pregenerated asset queue
LykkeCity/bitcoinservice,LykkeCity/bitcoinservice
src/AzureRepositories/TransactionOutputs/PregeneratedOutputsQueueFactory.cs
src/AzureRepositories/TransactionOutputs/PregeneratedOutputsQueueFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AzureStorage.Queue; using Common; using Core; using Core.Repositories.TransactionOutputs; namespace AzureRepositories.TransactionOutputs { public class PregeneratedOutputsQueueFactory : IPregeneratedOutputsQueueFactory { private readonly Func<string, IQueueExt> _queueFactory; public PregeneratedOutputsQueueFactory(Func<string, IQueueExt> queueFactory) { _queueFactory = queueFactory; } private string CreateQueueName(string assetId) { return "po-" + assetId.Replace(".", "-").Replace("_", "-").ToLower(); } public IPregeneratedOutputsQueue Create(string assetId) { var queue = CreateQueueName(assetId); return new PregeneratedOutputsQueue(_queueFactory(queue), queue); } public IPregeneratedOutputsQueue CreateFeeQueue() { return new PregeneratedOutputsQueue(_queueFactory(Constants.PregeneratedFeePoolQueue), Constants.PregeneratedFeePoolQueue); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AzureStorage.Queue; using Common; using Core; using Core.Repositories.TransactionOutputs; namespace AzureRepositories.TransactionOutputs { public class PregeneratedOutputsQueueFactory : IPregeneratedOutputsQueueFactory { private readonly Func<string, IQueueExt> _queueFactory; public PregeneratedOutputsQueueFactory(Func<string, IQueueExt> queueFactory) { _queueFactory = queueFactory; } private string CreateQueueName(string assetId) { return "po-" + assetId.ToLower(); } public IPregeneratedOutputsQueue Create(string assetId) { var queue = CreateQueueName(assetId); return new PregeneratedOutputsQueue(_queueFactory(queue), queue); } public IPregeneratedOutputsQueue CreateFeeQueue() { return new PregeneratedOutputsQueue(_queueFactory(Constants.PregeneratedFeePoolQueue), Constants.PregeneratedFeePoolQueue); } } }
mit
C#
0c31382508aa8ab0b4f739fb25116872cee6c795
Increment SC version (#2911)
Neurosploit/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode
src/Stratis.Bitcoin.Features.SmartContracts/SmartContractVersionProvider.cs
src/Stratis.Bitcoin.Features.SmartContracts/SmartContractVersionProvider.cs
using Stratis.Bitcoin.Interfaces; namespace Stratis.Bitcoin.Features.SmartContracts { public class SmartContractVersionProvider : IVersionProvider { public string GetVersion() { return "0.13.0"; } } }
using Stratis.Bitcoin.Interfaces; namespace Stratis.Bitcoin.Features.SmartContracts { public class SmartContractVersionProvider : IVersionProvider { public string GetVersion() { return "0.11.0"; } } }
mit
C#
3b78bede053072c3a6ceeffd0b2c5674624f8986
add using
elyen3824/myfinanalysis-data
data-provider/run.csx
data-provider/run.csx
using System.Net; using System.Net.Http; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); // parse query parameter string name = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0) .Value; string symbol = GetValueFromQuery(req, "symbol"); string start = GetValueFromQuery(req, "start"); string end = GetValueFromQuery(req, "end"); // Get request body dynamic data = await req.Content.ReadAsAsync<object>(); // Set name to query string or body data string[] symbols = data?.symbols; HttpResponseMessage result = GetResponse(req, symbol, symbols, start, end); return result; } private static string GetValueFromQuery(HttpRequestMessage req, string key) { return req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, key, true) == 0) .Value; } private static HttpResponseMessage GetResponse(HttpRequestMessage req, string symbol, string[] symbols, string start, string end) { if(symbol == null && symbols == null) return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body"); dynamic urls = GetUrls(symbol, symbols, start, end); return req.CreateResponse(HttpStatusCode.OK, urls); } private static dynamic GetUrls(string symbol, string[] symbols, string start, string end) { if(symbol !=null) return $"https://www.quandl.com/api/v3/datasets/WIKI/{symbol}/data.json?start_date={start}&end_date={end}&collapse=daily&transform=cumul"; return string.Empty; }
using System.Net; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); // parse query parameter string name = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0) .Value; string symbol = GetValueFromQuery(req, "symbol"); string start = GetValueFromQuery(req, "start"); string end = GetValueFromQuery(req, "end"); // Get request body dynamic data = await req.Content.ReadAsAsync<object>(); // Set name to query string or body data string[] symbols = data?.symbols; HttpResponseMessage result = GetResponse(req, symbol, symbols, start, end); return result; } private static string GetValueFromQuery(HttpRequestMessage req, string key) { return req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, key, true) == 0) .Value; } private static HttpResponseMessage GetResponse(HttpRequestMessage req, string symbol, string[] symbols, string start, string end) { if(symbol == null && symbols == null) return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body"); dynamic urls = GetUrls(symbol, symbols, start, end); return req.CreateResponse(HttpStatusCode.OK, urls); } private static dynamic GetUrls(string symbol, string[] symbols, string start, string end) { if(symbol !=null) return $"https://www.quandl.com/api/v3/datasets/WIKI/{symbol}/data.json?start_date={start}&end_date={end}&collapse=daily&transform=cumul"; return string.Empty; }
mit
C#
a9d48a3ea1f6723f7c766924a19e4df4afc388ab
change the description
xyting/NPOI.Extension
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NPOI.Extension")] [assembly: AssemblyDescription("Extension of NPOI, that use attributes to control enumerable objects export to excel behaviors.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("RigoFunc (xuyingting)")] [assembly: AssemblyProduct("NPOI.Extension")] [assembly: AssemblyCopyright("Copyright © RigoFunc (xuyingting). All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5addd29d-b3af-4966-b730-5e5192d0e9df")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NPOI.Extension")] [assembly: AssemblyDescription("The extension of NPOI, that use attributes to control enumerable objects export to excel behaviors.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("RigoFunc (xuyingting)")] [assembly: AssemblyProduct("NPOI.Extension")] [assembly: AssemblyCopyright("Copyright © RigoFunc (xuyingting). All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5addd29d-b3af-4966-b730-5e5192d0e9df")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
389438b5bd545c4a2d387f5c7b6f367890882ec6
Set new version
0xd4d/dnlib
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
// dnlib: See LICENSE.txt for more info using System.Reflection; using System.Runtime.InteropServices; #if THREAD_SAFE [assembly: AssemblyTitle("dnlib (thread safe)")] #else [assembly: AssemblyTitle("dnlib")] #endif [assembly: AssemblyDescription(".NET assembly reader/writer")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("dnlib")] [assembly: AssemblyCopyright("Copyright (C) 2012-2018 de4dot@gmail.com")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")]
// dnlib: See LICENSE.txt for more info using System.Reflection; using System.Runtime.InteropServices; #if THREAD_SAFE [assembly: AssemblyTitle("dnlib (thread safe)")] #else [assembly: AssemblyTitle("dnlib")] #endif [assembly: AssemblyDescription(".NET assembly reader/writer")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("dnlib")] [assembly: AssemblyCopyright("Copyright (C) 2012-2018 de4dot@gmail.com")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
mit
C#
1e13efc668e186e637207bc5a9093d64d53f91b1
fix batteries in src/tests
PKRoma/SQLitePCL.raw,ericsink/SQLitePCL.raw
src/tests/my_batteries_v2.cs
src/tests/my_batteries_v2.cs
/* Copyright 2014-2019 SourceGear, LLC 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. */ using System; using System.Collections.Generic; using System.Reflection; using System.IO; namespace SQLitePCL { public static class Batteries_V2 { class MyGetFunctionPointer : IGetFunctionPointer { readonly IntPtr _dll; public MyGetFunctionPointer(IntPtr dll) { _dll = dll; } public IntPtr GetFunctionPointer(string name) { if (NativeLibrary.TryGetExport(_dll, name, out var f)) { //System.Console.WriteLine("{0}.{1} : {2}", _dll, name, f); return f; } else { return IntPtr.Zero; } } } static IGetFunctionPointer MakeDynamic(string name, int flags) { // TODO should this be GetExecutingAssembly()? var assy = typeof(SQLitePCL.raw).Assembly; var dll = SQLitePCL.NativeLibrary.Load(name, assy, flags); var gf = new MyGetFunctionPointer(dll); return gf; } static void DoDynamic_cdecl(string name, int flags) { var gf = MakeDynamic(name, flags); SQLitePCL.SQLite3Provider_Cdecl.Setup(gf); SQLitePCL.raw.SetProvider(new SQLite3Provider_Cdecl()); } public static void Init() { DoDynamic_cdecl("e_sqlite3", NativeLibrary.WHERE_PLAIN); } } }
/* Copyright 2014-2019 SourceGear, LLC 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. */ using System; using System.Collections.Generic; using System.Reflection; using System.IO; namespace SQLitePCL { #if false class GetFunctionPointer_dotnetcore3 : IGetFunctionPointer { readonly IntPtr _dll; public GetFunctionPointer_dotnetcore3(IntPtr dll) { _dll = dll; } public IntPtr GetFunctionPointer(string name) { if (System.Runtime.InteropServices.NativeLibrary.TryGetExport(_dll, name, out var f)) { //System.Console.WriteLine("{0}.{1} : {2}", _dll, name, f); return f; } else { return IntPtr.Zero; } } } #endif public static class Batteries_V2 { public static void Init() { #if false var dll = System.Runtime.InteropServices.NativeLibrary.Load("e_sqlite3"); var gf = new GetFunctionPointer_dotnetcore3(dll); SQLitePCL.Setup.Load(gf); #else SQLitePCL.Setup.Load("e_sqlite3", s => File.AppendAllLines("log.txt", new string[] { s })); #endif } } }
apache-2.0
C#
79db769ae3e9027cbee0ee1d692c06e02c30f273
rename class
ctolkien/vnext-ground-up,ctolkien/vnext-ground-up
part3/Models/GroundUpDbContext.cs
part3/Models/GroundUpDbContext.cs
using Microsoft.Data.Entity; public class GroundUpDbContext : DbContext { DbSet<TodoItem> Todos {get; set;} protected override void OnConfiguring(DbContextOptions builder) { builder.UseSqlServer(@"Server=(localdb)\v11.0;Database=TodoItems;Trusted_Connection=True;"); } } public class TodoItem { public int Id {get; set;} public string Description {get; set;} }
using Microsoft.Data.Entity; public class Part3DbContext : DbContext { DbSet<TodoItem> Todos {get; set;} protected override void OnConfiguring(DbContextOptions builder) { builder.UseSqlServer(@"Server=(localdb)\v11.0;Database=TodoItems;Trusted_Connection=True;"); } } public class TodoItem { public int Id {get; set;} public string Description {get; set;} }
mit
C#
6938595818a35eef641bee48ab0bade9ac43b799
Fix failing tier deserialization (#91)
commercetools/commercetools-dotnet-sdk
commercetools.NET/ShippingMethods/ShippingRate.cs
commercetools.NET/ShippingMethods/ShippingRate.cs
using System.Collections.Generic; using commercetools.Common; using commercetools.ShippingMethods.Tiers; using Newtonsoft.Json; namespace commercetools.ShippingMethods { /// <summary> /// ShippingRate /// </summary> /// <see href="https://dev.commercetools.com/http-api-projects-shippingMethods.html#shippingrate"/> public class ShippingRate { #region Properties [JsonProperty(PropertyName = "price")] public Money Price { get; set; } [JsonProperty(PropertyName = "freeAbove")] public Money FreeAbove { get; set; } [JsonProperty(PropertyName = "tiers")] public List<Tier> Tiers { get; set; } #endregion #region Constructors /// <summary> /// Constructor. /// </summary> public ShippingRate() { } /// <summary> /// Initializes this instance with JSON data from an API response. /// </summary> /// <param name="data">JSON object</param> public ShippingRate(dynamic data) { if (data == null) { return; } this.Price = new Money(data.price); this.FreeAbove = new Money(data.freeAbove); // We do not use Helper.GetListFromJsonArray here, due to the JsonConverter property on Tier class. // Using GetListFromJsonArray ignores the JsonConverter property and fails to deserialize properly. this.Tiers = JsonConvert.DeserializeObject<List<Tier>>(data.tiers.ToString()); } #endregion } }
using System.Collections.Generic; using commercetools.Common; using commercetools.ShippingMethods.Tiers; using Newtonsoft.Json; namespace commercetools.ShippingMethods { /// <summary> /// ShippingRate /// </summary> /// <see href="https://dev.commercetools.com/http-api-projects-shippingMethods.html#shippingrate"/> public class ShippingRate { #region Properties [JsonProperty(PropertyName = "price")] public Money Price { get; set; } [JsonProperty(PropertyName = "freeAbove")] public Money FreeAbove { get; set; } [JsonProperty(PropertyName = "tiers")] public List<Tier> Tiers { get; set; } #endregion #region Constructors /// <summary> /// Constructor. /// </summary> public ShippingRate() { } /// <summary> /// Initializes this instance with JSON data from an API response. /// </summary> /// <param name="data">JSON object</param> public ShippingRate(dynamic data) { if (data == null) { return; } this.Price = new Money(data.price); this.FreeAbove = new Money(data.freeAbove); this.Tiers = Helper.GetListFromJsonArray<Tier>(data.tiers); } #endregion } }
mit
C#
53e60be03f476b2255f099367650265ec5a91e85
remove build again
IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates
build.cake
build.cake
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var buildArtifacts = Directory("./artifacts/packages"); var packageVersion = "2.5.0"; /////////////////////////////////////////////////////////////////////////////// // Clean /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts, Directory("./feed/content/UI") }); }); /////////////////////////////////////////////////////////////////////////////// // Build /////////////////////////////////////////////////////////////////////////////// Task("Build") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration, }; var projects = GetFiles("./src/**/*.csproj"); foreach(var project in projects) { DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); /////////////////////////////////////////////////////////////////////////////// // Copy /////////////////////////////////////////////////////////////////////////////// Task("Copy") .IsDependentOn("Clean") .Does(() => { CreateDirectory("./feed/content"); // copy the singel csproj templates var files = GetFiles("./src/**/*.*"); CopyFiles(files, "./feed/content", true); // copy the UI files files = GetFiles("./ui/**/*.*"); CopyFiles(files, "./feed/content/ui", true); }); /////////////////////////////////////////////////////////////////////////////// // Pack /////////////////////////////////////////////////////////////////////////////// Task("Pack") .IsDependentOn("Clean") .IsDependentOn("Copy") .Does(() => { var settings = new NuGetPackSettings { Version = packageVersion, OutputDirectory = buildArtifacts }; if (AppVeyor.IsRunningOnAppVeyor) { settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0'); } NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings); }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var buildArtifacts = Directory("./artifacts/packages"); var packageVersion = "2.5.0"; /////////////////////////////////////////////////////////////////////////////// // Clean /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts, Directory("./feed/content/UI") }); }); /////////////////////////////////////////////////////////////////////////////// // Build /////////////////////////////////////////////////////////////////////////////// Task("Build") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration, }; var projects = GetFiles("./src/**/*.csproj"); foreach(var project in projects) { DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); /////////////////////////////////////////////////////////////////////////////// // Copy /////////////////////////////////////////////////////////////////////////////// Task("Copy") .IsDependentOn("Clean") .IsDependentOn("Build") .Does(() => { CreateDirectory("./feed/content"); // copy the singel csproj templates var files = GetFiles("./src/**/*.*"); CopyFiles(files, "./feed/content", true); // copy the UI files files = GetFiles("./ui/**/*.*"); CopyFiles(files, "./feed/content/ui", true); }); /////////////////////////////////////////////////////////////////////////////// // Pack /////////////////////////////////////////////////////////////////////////////// Task("Pack") .IsDependentOn("Clean") .IsDependentOn("Copy") .Does(() => { var settings = new NuGetPackSettings { Version = packageVersion, OutputDirectory = buildArtifacts }; if (AppVeyor.IsRunningOnAppVeyor) { settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0'); } NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings); }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
apache-2.0
C#
a45915079dffc1d4437f55e762ccd212e6ebf513
Fix issue with no role assigned.
enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api
Infopulse.EDemocracy.Web/Auth/Providers/SimpleAuthorizationServerProvider.cs
Infopulse.EDemocracy.Web/Auth/Providers/SimpleAuthorizationServerProvider.cs
using System; using System.Data.Entity; using System.Linq; using Infopulse.EDemocracy.Data.Repositories; using Microsoft.Owin.Security.OAuth; using System.Security.Claims; using System.Threading.Tasks; using Infopulse.EDemocracy.Common.Extensions; using Infopulse.EDemocracy.Model.Enum; namespace Infopulse.EDemocracy.Web.Auth.Providers { public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (AuthRepository _repo = new AuthRepository()) { var user = await _repo.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName)); AddRoleClaim(identity, context.UserName); context.Validated(identity); } private void AddRoleClaim(ClaimsIdentity identity, string userEmail) { var roleClaim = GetUserRoleClaim(userEmail); if (roleClaim != null) { identity.AddClaim(roleClaim); } } private Claim GetUserRoleClaim(string userEmail) { var roleClaimValue = this.GetUserRolesAsString(userEmail); return new Claim(ClaimTypes.Role, roleClaimValue ?? string.Empty); } private string GetUserRolesAsString(string userEmail) { using (var db = new AuthContext()) { var user = db.Users.Include(u => u.Roles).SingleOrDefault(u => u.Email == userEmail); if (user == null || !user.Roles.Any()) return null; var userRoles = user.Roles.Select(r => r.RoleId.AsRoleText()); var roles = string.Join(",", userRoles); return roles; } } } }
using System; using System.Data.Entity; using System.Linq; using Infopulse.EDemocracy.Data.Repositories; using Microsoft.Owin.Security.OAuth; using System.Security.Claims; using System.Threading.Tasks; using Infopulse.EDemocracy.Common.Extensions; using Infopulse.EDemocracy.Model.Enum; namespace Infopulse.EDemocracy.Web.Auth.Providers { public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (AuthRepository _repo = new AuthRepository()) { var user = await _repo.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName)); AddRoleClaim(identity, context.UserName); context.Validated(identity); } private void AddRoleClaim(ClaimsIdentity identity, string userEmail) { var roleClaim = GetUserRoleClaim(userEmail); if (roleClaim != null) { identity.AddClaim(roleClaim); } } private Claim GetUserRoleClaim(string userEmail) { var roleClaimValue = this.GetUserRolesAsString(userEmail); return new Claim(ClaimTypes.Role, roleClaimValue); } private string GetUserRolesAsString(string userEmail) { using (var db = new AuthContext()) { var user = db.Users.Include(u => u.Roles).SingleOrDefault(u => u.Email == userEmail); if (user == null || !user.Roles.Any()) return null; var userRoles = user.Roles.Select(r => r.RoleId.AsRoleText()); var roles = string.Join(",", userRoles); return roles; } } } }
cc0-1.0
C#
12290addfd4ec47f08b0ff9fb946fc7e54a49447
Handle null values in setter
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
NakedLegacy/NakedLegacy.Reflector/Facet/PropertySetterFacetViaValueHolder.cs
NakedLegacy/NakedLegacy.Reflector/Facet/PropertySetterFacetViaValueHolder.cs
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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. using System; using System.Reflection; using NakedFramework.Architecture.Adapter; using NakedFramework.Architecture.Framework; using NakedFramework.Architecture.Spec; using NakedFramework.Core.Util; using NakedFramework.Metamodel.Facet; namespace NakedLegacy.Reflector.Facet; [Serializable] public sealed class PropertySetterFacetViaValueHolder<T, TU> : PropertySetterFacetAbstract where T : class, IValueHolder<TU> { private readonly PropertyInfo property; public PropertySetterFacetViaValueHolder(PropertyInfo property, ISpecification holder) : base(holder) => this.property = property; public override string PropertyName { get => property.Name; protected set { } } public override void SetProperty(INakedObjectAdapter nakedObjectAdapter, INakedObjectAdapter value, INakedFramework framework) { try { var valueHolder = (T)property.GetValue(nakedObjectAdapter.Object); valueHolder.Value = value.GetDomainObject() is T obj ? obj.Value : default; } catch (NullReferenceException e) { InvokeUtils.InvocationException($"Unexpected null valueholder on {property}", e); } catch (TargetInvocationException e) { InvokeUtils.InvocationException($"Exception executing {property}", e); } } protected override string ToStringValues() => $"property={property}"; }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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. using System; using System.Reflection; using NakedFramework.Architecture.Adapter; using NakedFramework.Architecture.Framework; using NakedFramework.Architecture.Spec; using NakedFramework.Core.Util; using NakedFramework.Metamodel.Facet; namespace NakedLegacy.Reflector.Facet; [Serializable] public sealed class PropertySetterFacetViaValueHolder<T, TU> : PropertySetterFacetAbstract where T : class, IValueHolder<TU> { private readonly PropertyInfo property; public PropertySetterFacetViaValueHolder(PropertyInfo property, ISpecification holder) : base(holder) => this.property = property; public override string PropertyName { get => property.Name; protected set { } } public override void SetProperty(INakedObjectAdapter nakedObjectAdapter, INakedObjectAdapter value, INakedFramework framework) { try { var vh = (T) property.GetValue(nakedObjectAdapter.Object); vh.Value = value.GetDomainObject<T>().Value; } catch (TargetInvocationException e) { InvokeUtils.InvocationException($"Exception executing {property}", e); } } protected override string ToStringValues() => $"property={property}"; }
apache-2.0
C#
789330f8aab3af26cd80f390c2ed4dfdd208cea3
resolve #40
estorski/langlay
Langlay.App/Services/TrayService.cs
Langlay.App/Services/TrayService.cs
using System; using System.Diagnostics; using System.Drawing; using System.IO; using System.Reflection; using System.Windows.Forms; using Product.Common; namespace Product { public class TrayService { private IConfigService ConfigService { get; set; } private ISettingsService SettingsService { get; set; } private ContextMenu ContextMenu { get; set; } private NotifyIcon Icon { get; set; } private bool IsStarted { get; set; } public Action OnExit { get; set; } public TrayService(IConfigService configService, ISettingsService settingsService) { ConfigService = configService; SettingsService = settingsService; } public void Start() { if (!IsStarted) { IsStarted = true; ContextMenu = new ContextMenu(new[] { new MenuItem("Settings", delegate { SettingsService.ShowSettings(); }), new MenuItem("-"), new MenuItem("Quit", delegate { if (OnExit != null) OnExit(); }) }); Icon = new NotifyIcon() { Text = Application.ProductName, Icon = new Icon(typeof(Program), "Keyboard-Filled-2-16.ico"), Visible = true, ContextMenu = ContextMenu, }; Icon.MouseDoubleClick += delegate { SettingsService.ShowSettings(); }; } } public void Stop() { if (IsStarted) { IsStarted = false; if (ContextMenu != null) ContextMenu.Dispose(); if (Icon != null) Icon.Dispose(); } } } }
using System; using System.Diagnostics; using System.Drawing; using System.IO; using System.Reflection; using System.Windows.Forms; using Product.Common; namespace Product { public class TrayService { private IConfigService ConfigService { get; set; } private ISettingsService SettingsService { get; set; } private ContextMenu ContextMenu { get; set; } private NotifyIcon Icon { get; set; } private bool IsStarted { get; set; } public Action OnExit { get; set; } public TrayService(IConfigService configService, ISettingsService settingsService) { ConfigService = configService; SettingsService = settingsService; } public void Start() { if (!IsStarted) { IsStarted = true; ContextMenu = new ContextMenu(new[] { new MenuItem("Settings", delegate { SettingsService.ShowSettings(); }), new MenuItem("-"), new MenuItem("Quit", delegate { if (OnExit != null) OnExit(); }) }); Icon = new NotifyIcon() { Text = Application.ProductName, Icon = new Icon(typeof(Program), "Keyboard-Filled-2-16.ico"), Visible = true, ContextMenu = ContextMenu }; } } public void Stop() { if (IsStarted) { IsStarted = false; if (ContextMenu != null) ContextMenu.Dispose(); if (Icon != null) Icon.Dispose(); } } } }
mit
C#
4e62070aa9f8219f4e9ed0ba78b54b6133b44477
Remove lastforkheight assert
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
HiddenWallet.Tests/ExternalApiTests.cs
HiddenWallet.Tests/ExternalApiTests.cs
using HiddenWallet.WebClients.BlockCypher; using HiddenWallet.WebClients.SmartBit; using NBitcoin; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace HiddenWallet.Tests { public class ExternalApiTests { [Theory] [InlineData("test")] [InlineData("main")] public async Task SmartBitTestsAsync(string networkString) { var network = Network.GetNetwork(networkString); using (var client = new SmartBitClient(network)) { var rates = (await client.GetExchangeRatesAsync(CancellationToken.None)); Assert.Contains("AUD", rates.Select(x => x.Code)); Assert.Contains("USD", rates.Select(x => x.Code)); await Assert.ThrowsAsync<HttpRequestException>(async()=> await client.PushTransactionAsync(new Transaction(), CancellationToken.None)); } } [Theory] [InlineData("test")] [InlineData("main")] public async Task BlockCypherTestsAsync(string networkString) { var network = Network.GetNetwork(networkString); using (var client = new BlockCypherClient(network)) { var response = await client.GetGeneralInformationAsync(CancellationToken.None); Assert.NotNull(response.Hash); Assert.NotNull(response.LastForkHash); Assert.NotNull(response.PreviousHash); Assert.True(response.UnconfirmedCount > 0); Assert.InRange(response.LowFee.FeePerK, Money.Zero, response.MediumFee.FeePerK); Assert.InRange(response.MediumFee.FeePerK, response.LowFee.FeePerK, response.HighFee.FeePerK); Assert.InRange(response.HighFee.FeePerK, response.MediumFee.FeePerK, new Money(0.1m, MoneyUnit.BTC)); Assert.True(response.Height >= 491999); Assert.Equal(new Uri(client.BaseAddress.ToString().Replace("http", "https") + "/blocks/" + response.Hash.ToString()), response.LatestUrl); Assert.Equal(new Uri(client.BaseAddress.ToString().Replace("http", "https") + "/blocks/" + response.PreviousHash.ToString()), response.PreviousUrl); if(network == Network.Main) { Assert.Equal("BTC.main", response.Name); } else { Assert.Equal("BTC.test3", response.Name); } Assert.True(response.PeerCount > 0); } } } }
using HiddenWallet.WebClients.BlockCypher; using HiddenWallet.WebClients.SmartBit; using NBitcoin; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace HiddenWallet.Tests { public class ExternalApiTests { [Theory] [InlineData("test")] [InlineData("main")] public async Task SmartBitTestsAsync(string networkString) { var network = Network.GetNetwork(networkString); using (var client = new SmartBitClient(network)) { var rates = (await client.GetExchangeRatesAsync(CancellationToken.None)); Assert.Contains("AUD", rates.Select(x => x.Code)); Assert.Contains("USD", rates.Select(x => x.Code)); await Assert.ThrowsAsync<HttpRequestException>(async()=> await client.PushTransactionAsync(new Transaction(), CancellationToken.None)); } } [Theory] [InlineData("test")] [InlineData("main")] public async Task BlockCypherTestsAsync(string networkString) { var network = Network.GetNetwork(networkString); using (var client = new BlockCypherClient(network)) { var response = await client.GetGeneralInformationAsync(CancellationToken.None); Assert.NotNull(response.Hash); Assert.NotNull(response.LastForkHash); Assert.NotNull(response.PreviousHash); Assert.True(response.UnconfirmedCount > 0); Assert.InRange(response.LowFee.FeePerK, Money.Zero, response.MediumFee.FeePerK); Assert.InRange(response.MediumFee.FeePerK, response.LowFee.FeePerK, response.HighFee.FeePerK); Assert.InRange(response.HighFee.FeePerK, response.MediumFee.FeePerK, new Money(0.1m, MoneyUnit.BTC)); Assert.True(response.Height >= 491999); Assert.True(response.LastForkHeight >= 491362); Assert.Equal(new Uri(client.BaseAddress.ToString().Replace("http", "https") + "/blocks/" + response.Hash.ToString()), response.LatestUrl); Assert.Equal(new Uri(client.BaseAddress.ToString().Replace("http", "https") + "/blocks/" + response.PreviousHash.ToString()), response.PreviousUrl); if(network == Network.Main) { Assert.Equal("BTC.main", response.Name); } else { Assert.Equal("BTC.test3", response.Name); } Assert.True(response.PeerCount > 0); } } } }
mit
C#
9224151ad6b072e404aa5893da569516e45caf4e
Remove "public" access modifier from test class
shaynevanasperen/Quarks
Quarks.Tests/PluralizeForCountTests.cs
Quarks.Tests/PluralizeForCountTests.cs
using Machine.Specifications; namespace Quarks.Tests { [Subject(typeof(Inflector))] class When_using_pluralize_for_count { It should_pluralize_when_count_is_greater_than_two = () => "item".PluralizeForCount(2).ShouldEqual("items"); It should_pluralize_when_count_is_zero = () => "item".PluralizeForCount(0).ShouldEqual("items"); It should_not_pluralize_when_count_is_one = () => "item".PluralizeForCount(1).ShouldEqual("item"); } }
using Machine.Specifications; namespace Quarks.Tests { [Subject(typeof(Inflector))] public class When_using_pluralize_for_count { It should_pluralize_when_count_is_greater_than_two = () => "item".PluralizeForCount(2).ShouldEqual("items"); It should_pluralize_when_count_is_zero = () => "item".PluralizeForCount(0).ShouldEqual("items"); It should_not_pluralize_when_count_is_one = () => "item".PluralizeForCount(1).ShouldEqual("item"); } }
mit
C#
5f4f9e3a2d3381700f73e963c2834526f490f7be
comment box
karitasolafs/TextDoc,karitasolafs/TextDoc
TextDuck/Views/Home/ViewComment.cshtml
TextDuck/Views/Home/ViewComment.cshtml
@model IQueryable<TextDuck.Models.CommentItem> <link href="/Content/Table.css" rel="stylesheet" /> <h1>Latest Comments</h1> @foreach (var item in Model) { <div class="jumbotron"> <p class="Date"> @Html.DisplayFor(modelItem => item.DateCreated) <span class="glyphicon glyphicon-time"></span> </p> <h2 class="Title">@Html.ActionLink(item.Title, "AddComment", new { id = item.Id })</h2> <p class="Text">@Html.DisplayFor(modelItem => item.Text)</p> <p class="Text">@Html.DisplayFor(modelItem => item.UserName)</p> @Html.ActionLink("Ny athugasemd", "AddComment", new { Id = item.Id, Title = item.Title }, null) </div> } <div> @Html.ActionLink("Aftur a forsidu", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
@model IQueryable<TextDuck.Models.CommentItem> <link href="/Content/Table.css" rel="stylesheet" /> <div> @Html.ActionLink("Bæta við athugasemd", "AddComment", "Home") </div> <h1>Latest Comments</h1> @foreach (var item in Model) { <div class="jumbotron"> <p class="Date"> @Html.DisplayFor(modelItem => item.DateCreated) <span class="glyphicon glyphicon-time"></span> </p> <h2 class="Title">@Html.ActionLink(item.Title, "AddComment", new { id = item.Id })</h2> <p class="Text">@Html.DisplayFor(modelItem => item.Text)</p> <p class="Text">@Html.DisplayFor(modelItem => item.UserName)</p> </div> } <div> @Html.ActionLink("Aftur a forsidu", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
mit
C#
c80125a2dc9c256d32eab6c38748b0db9856de5d
Update version to 8.0.0
Weingartner/XUnitRemote
XUnitRemote/Properties/AssemblyInfo.cs
XUnitRemote/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XUnitRemote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Weingartner")] [assembly: AssemblyProduct("XUnitRemote")] [assembly: AssemblyCopyright("Copyright © Weingartner Machinenbau Gmbh 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("21248cf4-3629-4cfa-8632-9e4468a0526e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("8.0.0.0")] [assembly: AssemblyFileVersion("8.0.0.0")] [assembly: AssemblyInformationalVersion("8.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XUnitRemote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Weingartner")] [assembly: AssemblyProduct("XUnitRemote")] [assembly: AssemblyCopyright("Copyright © Weingartner Machinenbau Gmbh 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("21248cf4-3629-4cfa-8632-9e4468a0526e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("7.99.0.0")] [assembly: AssemblyFileVersion("7.99.0.0")] [assembly: AssemblyInformationalVersion("8.0.0-beta-007")]
mit
C#
baf8300233133218a86ed091fe7df98ddf2a3d82
Increment the version to 1.4.0.0
ladimolnar/BitcoinDatabaseGenerator
Sources/BitcoinDatabaseGenerator/Properties/AssemblyInfo.cs
Sources/BitcoinDatabaseGenerator/Properties/AssemblyInfo.cs
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs"> // Copyright © Ladislau Molnar. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BitcoinDatabaseGenerator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BitcoinDatabaseGenerator")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("372a7f52-b038-43aa-a42c-3ff0ecab1124")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs"> // Copyright © Ladislau Molnar. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BitcoinDatabaseGenerator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BitcoinDatabaseGenerator")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("372a7f52-b038-43aa-a42c-3ff0ecab1124")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")]
apache-2.0
C#
ae5f517c81d0e76fd9a341a695ea6aff76bfd125
Fix path to testsnotfound.js
ymorozov/Sitecore.TestRunnerJS,ymorozov/Sitecore.TestRunnerJS,ymorozov/Sitecore.TestRunnerJS
code/Sitecore.TestRunnerJS/TestFixtureController.cs
code/Sitecore.TestRunnerJS/TestFixtureController.cs
namespace Sitecore.TestRunnerJS { using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Web; using System.Web.Hosting; using System.Web.Http; public class TestFixtureController : ApiController { private const string TestFixtureParameterName = "sc_testfixture"; [HttpGet] public HttpResponseMessage GetByUrl(string url) { var uri = new Uri(url); var queryParameters = HttpUtility.ParseQueryString(uri.Query); var normalizedUrl = uri.LocalPath.ToLowerInvariant(); var applicationUrlParts = normalizedUrl.Split(new[] { @"/sitecore/client/applications/" }, StringSplitOptions.None); if (applicationUrlParts.Length == 2) { var applicationUrlPart = applicationUrlParts[1]; var applicationUrlParameterParts = applicationUrlPart.Split('/'); if (applicationUrlParameterParts.Length >= 2) { var testFixtureParameter = queryParameters.Get(TestFixtureParameterName); if (!string.IsNullOrEmpty(testFixtureParameter)) { applicationUrlParameterParts[applicationUrlParameterParts.Length - 1] = testFixtureParameter; } var pageRelativePath = string.Join(@"/", applicationUrlParameterParts); var testFixturePath = HostingEnvironment.MapPath( "~/" + ConfigSettings.RootTestFixturesFolder + "/" + pageRelativePath + ".js"); if (File.Exists(testFixturePath)) { return this.GetResponseMessage(testFixturePath); } } } var notFoundPath = HostingEnvironment.MapPath("~/sitecore/TestRunnerJS/assets/testsnotfound.js"); return this.GetResponseMessage(notFoundPath); } private HttpResponseMessage GetResponseMessage(string testFixturePath) { var result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(testFixturePath, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/javascript"); return result; } } }
namespace Sitecore.TestRunnerJS { using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Web; using System.Web.Hosting; using System.Web.Http; public class TestFixtureController : ApiController { private const string TestFixtureParameterName = "sc_testfixture"; [HttpGet] public HttpResponseMessage GetByUrl(string url) { var uri = new Uri(url); var queryParameters = HttpUtility.ParseQueryString(uri.Query); var normalizedUrl = uri.LocalPath.ToLowerInvariant(); var applicationUrlParts = normalizedUrl.Split(new[] { @"/sitecore/client/applications/" }, StringSplitOptions.None); if (applicationUrlParts.Length == 2) { var applicationUrlPart = applicationUrlParts[1]; var applicationUrlParameterParts = applicationUrlPart.Split('/'); if (applicationUrlParameterParts.Length >= 2) { var testFixtureParameter = queryParameters.Get(TestFixtureParameterName); if (!string.IsNullOrEmpty(testFixtureParameter)) { applicationUrlParameterParts[applicationUrlParameterParts.Length - 1] = testFixtureParameter; } var pageRelativePath = string.Join(@"/", applicationUrlParameterParts); var testFixturePath = HostingEnvironment.MapPath( "~/" + ConfigSettings.RootTestFixturesFolder + "/" + pageRelativePath + ".js"); if (File.Exists(testFixturePath)) { return this.GetResponseMessage(testFixturePath); } } } var notFoundPath = HostingEnvironment.MapPath("~/TestRunnerJS/assets/testsnotfound.js"); return this.GetResponseMessage(notFoundPath); } private HttpResponseMessage GetResponseMessage(string testFixturePath) { var result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(testFixturePath, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/javascript"); return result; } } }
mit
C#
3ad8ce59dd3203f8a72febf5c5e56c742de49fad
Change missed while mirroring (#28955)
wtgodbe/corefx,BrennanConroy/corefx,Jiayili1/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,ptoonen/corefx,ViktorHofer/corefx,BrennanConroy/corefx,shimingsg/corefx,ericstj/corefx,ptoonen/corefx,Jiayili1/corefx,ViktorHofer/corefx,ptoonen/corefx,ericstj/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx,ericstj/corefx,mmitche/corefx,ViktorHofer/corefx,ptoonen/corefx,ptoonen/corefx,ericstj/corefx,shimingsg/corefx,Jiayili1/corefx,shimingsg/corefx,ptoonen/corefx,wtgodbe/corefx,mmitche/corefx,mmitche/corefx,ptoonen/corefx,BrennanConroy/corefx,ericstj/corefx,mmitche/corefx,wtgodbe/corefx,Jiayili1/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,Jiayili1/corefx,Jiayili1/corefx,mmitche/corefx,ViktorHofer/corefx,wtgodbe/corefx,mmitche/corefx,wtgodbe/corefx,mmitche/corefx,ViktorHofer/corefx,Jiayili1/corefx,shimingsg/corefx
src/Common/src/CoreLib/System/Buffers/MemoryHandle.cs
src/Common/src/CoreLib/System/Buffers/MemoryHandle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Runtime.InteropServices; namespace System.Buffers { /// <summary> /// A handle for the memory. /// </summary> public unsafe struct MemoryHandle : IDisposable { private void* _pointer; private GCHandle _handle; private IPinnable _pinnable; /// <summary> /// Creates a new memory handle for the memory. /// </summary> /// <param name="pointer">pointer to memory</param> /// <param name="pinnable">reference to manually managed object, or default if there is no memory manager</param> /// <param name="handle">handle used to pin array buffers</param> [CLSCompliant(false)] public MemoryHandle(void* pointer, GCHandle handle = default, IPinnable pinnable = default) { _pointer = pointer; _handle = handle; _pinnable = pinnable; } /// <summary> /// Returns the pointer to memory, where the memory is assumed to be pinned and hence the address won't change. /// </summary> [CLSCompliant(false)] public void* Pointer => _pointer; /// <summary> /// Frees the pinned handle and releases IPinnable. /// </summary> public void Dispose() { if (_handle.IsAllocated) { _handle.Free(); } if (_pinnable != null) { _pinnable.Unpin(); _pinnable = null; } _pointer = null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Runtime.InteropServices; namespace System.Buffers { /// <summary> /// A handle for the memory. /// </summary> public unsafe struct MemoryHandle : IDisposable { private void* _pointer; private GCHandle _handle; private IPinnable _pinnable; /// <summary> /// Creates a new memory handle for the memory. /// </summary> /// <param name="pointer">pointer to memory</param> /// <param name="pinnable">reference to manually managed object, or default if there is no memory manager</param> /// <param name="handle">handle used to pin array buffers</param> [CLSCompliant(false)] public MemoryHandle(void* pointer, GCHandle handle = default, IPinnable pinnable = default) { _pointer = pointer; _handle = handle; _pinnable = pinnable; } /// <summary> /// Returns the pointer to memory, where the memory is assumed to be pinned and hence the address won't change. /// </summary> [CLSCompliant(false)] public void* Pointer => _pointer; /// <summary> /// Frees the pinned handle and releases IPinnable. /// </summary> public void Dispose() { if (_handle.IsAllocated) { _handle.Free(); } if (_pinnable != null) { _pinnable.Unpin(); _pinnable = null; } _pointer = null; } } }
mit
C#
b5d313b6995262b4377f149df5669c3f3ffe020b
Remove unused OrchardCore.Title dependency from OrchardCore.Media (#3266)
xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2
src/OrchardCore.Modules/OrchardCore.Media/Manifest.cs
src/OrchardCore.Modules/OrchardCore.Media/Manifest.cs
using OrchardCore.Modules.Manifest; [assembly: Module( Name = "Media", Author = "The Orchard Team", Website = "https://orchardproject.net", Version = "2.0.0" )] [assembly: Feature( Id = "OrchardCore.Media", Name = "Media", Description = "The media module adds media management support.", Dependencies = new [] { "OrchardCore.ContentTypes" }, Category = "Content Management" )]
using OrchardCore.Modules.Manifest; [assembly: Module( Name = "Media", Author = "The Orchard Team", Website = "https://orchardproject.net", Version = "2.0.0" )] [assembly: Feature( Id = "OrchardCore.Media", Name = "Media", Description = "The media module adds media management support.", Dependencies = new [] { "OrchardCore.ContentTypes", "OrchardCore.Title" }, Category = "Content Management" )]
bsd-3-clause
C#
1969c5b89bccc3788a295d14ecc8e83412b58da7
Apply suggetsted changes
johnneijzen/osu,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,ZLima12/osu,peppy/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,ZLima12/osu,NeoAdonis/osu,EVAST9919/osu,2yangk23/osu,peppy/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,2yangk23/osu,EVAST9919/osu,NeoAdonis/osu
osu.Game.Tests/Visual/Online/TestSceneRankingsScopeSelector.cs
osu.Game.Tests/Visual/Online/TestSceneRankingsScopeSelector.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 System.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Bindables; using osu.Game.Overlays; using osu.Framework.Graphics.Shapes; using osu.Framework.Allocation; using osu.Game.Graphics; namespace osu.Game.Tests.Visual.Online { public class TestSceneRankingsScopeSelector : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(RankingsScopeSelector), }; private readonly Box background; public TestSceneRankingsScopeSelector() { var scope = new Bindable<RankingsScope>(); AddRange(new Drawable[] { background = new Box { RelativeSizeAxes = Axes.Both }, new RankingsScopeSelector { Anchor = Anchor.Centre, Origin = Anchor.Centre, Current = { BindTarget = scope } } }); AddStep(@"Select country", () => scope.Value = RankingsScope.Country); AddStep(@"Select performance", () => scope.Value = RankingsScope.Performance); AddStep(@"Select score", () => scope.Value = RankingsScope.Score); AddStep(@"Select spotlights", () => scope.Value = RankingsScope.Spotlights); } [BackgroundDependencyLoader] private void load(OsuColour colours) { background.Colour = colours.GreySeafoam; } } }
// 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 System.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Bindables; using osu.Game.Overlays; using osu.Framework.Graphics.Shapes; using osu.Framework.Allocation; using osu.Game.Graphics; using osu.Framework.Extensions.Color4Extensions; namespace osu.Game.Tests.Visual.Online { public class TestSceneRankingsScopeSelector : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(RankingsScopeSelector), }; private readonly Box background; public TestSceneRankingsScopeSelector() { Bindable<RankingsScope> scope = new Bindable<RankingsScope>(); Add(background = new Box { RelativeSizeAxes = Axes.Both }); Add(new RankingsScopeSelector { Anchor = Anchor.Centre, Origin = Anchor.Centre, Current = { BindTarget = scope } }); AddStep(@"Select country", () => scope.Value = RankingsScope.Country); AddStep(@"Select performance", () => scope.Value = RankingsScope.Performance); AddStep(@"Select score", () => scope.Value = RankingsScope.Score); AddStep(@"Select spotlights", () => scope.Value = RankingsScope.Spotlights); } [BackgroundDependencyLoader] private void load(OsuColour colours) { background.Colour = colours.Yellow.Opacity(50); } } }
mit
C#
05c17b52cd614b5ad14480002c3908772e556013
Remove redundant address
jmptrader/WampSharp,jmptrader/WampSharp,jmptrader/WampSharp
src/WampSharp.Default/WampChannelFactoryExtensions.cs
src/WampSharp.Default/WampChannelFactoryExtensions.cs
using Newtonsoft.Json.Linq; using WampSharp.Core.Serialization; using WampSharp.Newtonsoft; using WampSharp.WebSocket4Net; using WebSocket4Net; namespace WampSharp { public static class WampChannelFactoryExtensions { public static IWampChannel<JToken> CreateChannel(this IWampChannelFactory<JToken> factory, string address) { return factory.CreateChannel(address, new JTokenMessageParser()); } public static IWampChannel<TMessage> CreateChannel<TMessage>(this IWampChannelFactory<TMessage> factory, string address, IWampMessageParser<TMessage> parser) { return factory.CreateChannel(new WebSocket4NetConnection<TMessage>(address, parser)); } public static IWampChannel<JToken> CreateChannel(this IWampChannelFactory<JToken> factory, WebSocket socket) { return factory.CreateChannel(new WebSocket4NetConnection<JToken>(socket, new JTokenMessageParser())); } } }
using Newtonsoft.Json.Linq; using WampSharp.Core.Serialization; using WampSharp.Newtonsoft; using WampSharp.WebSocket4Net; using WebSocket4Net; namespace WampSharp { public static class WampChannelFactoryExtensions { public static IWampChannel<JToken> CreateChannel(this IWampChannelFactory<JToken> factory, string address) { return factory.CreateChannel(address, new JTokenMessageParser()); } public static IWampChannel<TMessage> CreateChannel<TMessage>(this IWampChannelFactory<TMessage> factory, string address, IWampMessageParser<TMessage> parser) { return factory.CreateChannel(new WebSocket4NetConnection<TMessage>(address, parser)); } public static IWampChannel<JToken> CreateChannel(this IWampChannelFactory<JToken> factory, string address, WebSocket socket) { return factory.CreateChannel(new WebSocket4NetConnection<JToken>(socket, new JTokenMessageParser())); } } }
bsd-2-clause
C#
38a102fb15e5945c826a699f989a5dd5c25bbc07
Return corner points from EdgeArea
davidaramant/buddhabrot,davidaramant/buddhabrot
src/Buddhabrot/Edges/EdgeArea.cs
src/Buddhabrot/Edges/EdgeArea.cs
using System.Collections.Generic; using System.Drawing; namespace Buddhabrot.Edges { public sealed class EdgeArea { public Point GridLocation { get; } public Corners CornersInSet { get; } public EdgeArea(Point location, Corners cornersInSet) { GridLocation = location; CornersInSet = cornersInSet; } public IEnumerable<Corners> GetCornersInSet() { if (CornersInSet.HasFlag(Corners.TopRight)) yield return Corners.TopRight; if (CornersInSet.HasFlag(Corners.TopLeft)) yield return Corners.TopLeft; if (CornersInSet.HasFlag(Corners.BottomRight)) yield return Corners.BottomRight; if (CornersInSet.HasFlag(Corners.BottomLeft)) yield return Corners.BottomLeft; } public IEnumerable<Corners> GetCornersNotInSet() { if (!CornersInSet.HasFlag(Corners.TopRight)) yield return Corners.TopRight; if (!CornersInSet.HasFlag(Corners.TopLeft)) yield return Corners.TopLeft; if (!CornersInSet.HasFlag(Corners.BottomRight)) yield return Corners.BottomRight; if (!CornersInSet.HasFlag(Corners.BottomLeft)) yield return Corners.BottomLeft; } } }
using System.Drawing; namespace Buddhabrot.Edges { public sealed class EdgeArea { public Point GridLocation { get; } public Corners CornersInSet { get; } public EdgeArea(Point location, Corners cornersInSet) { GridLocation = location; CornersInSet = cornersInSet; } } }
bsd-2-clause
C#
4a3b1f5f8258ce497b40b9de21762f538aa87dcf
Add GetSystemEduForm method
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University/Models/ModelHelper.cs
R7.University/Models/ModelHelper.cs
// // ModelHelper.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2015 Roman M. Yagodin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace R7.University { public static class ModelHelper { public static bool IsPublished (DateTime? startDate, DateTime? endDate) { var now = DateTime.Now; return (startDate == null || now >= startDate) && (endDate == null || now < endDate); } #region Extension methods public static bool IsPublished (this IDocument document) { return IsPublished (document.StartDate, document.EndDate); } public static SystemDocumentType GetSystemDocumentType (this IDocumentType documentType) { SystemDocumentType result; return Enum.TryParse<SystemDocumentType> (documentType.Type, out result)? result : SystemDocumentType.Custom; } public static SystemEduForm GetSystemEduForm (this IEduForm eduForm) { SystemEduForm result; return Enum.TryParse<SystemEduForm> (eduForm.Title, out result)? result : SystemEduForm.Custom; } #endregion } }
// // ModelHelper.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2015 Roman M. Yagodin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace R7.University { public static class ModelHelper { public static bool IsPublished (DateTime? startDate, DateTime? endDate) { var now = DateTime.Now; return (startDate == null || now >= startDate) && (endDate == null || now < endDate); } #region Extension methods public static bool IsPublished (this IDocument document) { return IsPublished (document.StartDate, document.EndDate); } public static SystemDocumentType GetSystemDocumentType (this IDocumentType documentType) { SystemDocumentType result; return Enum.TryParse<SystemDocumentType> (documentType.Type, out result)? result : SystemDocumentType.Custom; } #endregion } }
agpl-3.0
C#
ffa1e1ad648464901dba5cbb21a6c6de45c83ace
Add XML documentation to EditFileEventArgs class
Radnen/spherestudio,Radnen/spherestudio
Sphere.Plugins/EditFileEventArgs.cs
Sphere.Plugins/EditFileEventArgs.cs
using System; using System.ComponentModel; using System.IO; namespace Sphere.Plugins { /// <summary> /// Provides data for Sphere Studio 'edit file' events. /// </summary> public class EditFileEventArgs : HandledEventArgs { /// <summary> /// Initializes a new instance of the EditFileEventArgs class, which provides data for Sphere Studio 'edit file' events. /// </summary> /// <param name="path">The full path of the file to be edited.</param> /// <param name="useWildcard">If true, reports a wildcard ('*') in place of the file's actual extension.</param> public EditFileEventArgs(string path, bool useWildcard = false) { Path = (path != null && path[0] == '?') ? null : path; string fileExtension = System.IO.Path.GetExtension(path); if (fileExtension != null) Extension = useWildcard ? "*" : fileExtension.ToLower(); } /// <summary> /// The file extension of the file to be edited, including the dot ('.'). /// </summary> public string Extension { get; private set; } /// <summary> /// The full path of the file to be edited. /// </summary> public string Path { get; private set; } } public delegate void EditFileEventHandler(object sender, EditFileEventArgs e); }
using System; using System.IO; namespace Sphere.Plugins { public class EditFileEventArgs : EventArgs { public EditFileEventArgs(string path, bool useWildcard = false) { Path = (path != null && path[0] == '?') ? null : path; string extension = System.IO.Path.GetExtension(path); if (extension != null) Extension = useWildcard ? "*" : extension.ToLower(); Handled = false; } public string Path { get; private set; } public string Extension { get; private set; } public bool Handled { get; set; } } public delegate void EditFileEventHandler(object sender, EditFileEventArgs e); }
mit
C#
735b7da93dba63a5763f83d0bec5fef23ab6c170
Bump v1.0.13
karronoli/tiny-sato
TinySato/Properties/AssemblyInfo.cs
TinySato/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.0.13.*")] [assembly: AssemblyFileVersion("1.0.13")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.0.12.4803")] [assembly: AssemblyFileVersion("1.0.12")]
apache-2.0
C#
0d2237849df0b565c5619c33c904fc4ee914620c
Add WriteAllText overload for IEnumerable.
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/IO/TextTasks.cs
source/Nuke.Common/IO/TextTasks.cs
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using JetBrains.Annotations; using Nuke.Core; using Nuke.Core.IO; namespace Nuke.Common.IO { [PublicAPI] public static class TextTasks { private static UTF8Encoding UTF8NoBom => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); public static void WriteAllText (string path, IEnumerable<string> lines, Encoding encoding = null) { WriteAllText(path, lines.ToArray(), encoding); } public static void WriteAllText (string path, string[] lines, Encoding encoding = null) { WriteAllText(path, string.Join(EnvironmentInfo.NewLine, lines), encoding); } public static void WriteAllText (string path, string content, Encoding encoding = null) { FileSystemTasks.EnsureExistingParentDirectory(path); File.WriteAllText(path, content, encoding ?? UTF8NoBom); } public static void WriteAllBytes (string path, byte[] bytes) { FileSystemTasks.EnsureExistingParentDirectory(path); File.WriteAllBytes(path, bytes); } public static string ReadAllText (string path, Encoding encoding = null) { return File.ReadAllText(path, encoding ?? Encoding.UTF8); } public static string[] ReadAllLines (string path, Encoding encoding = null) { return File.ReadAllLines(path, encoding ?? Encoding.UTF8); } public static byte[] ReadAllBytes (string path) { return File.ReadAllBytes(path); } } }
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.IO; using System.Linq; using System.Text; using JetBrains.Annotations; using Nuke.Core; using Nuke.Core.IO; namespace Nuke.Common.IO { [PublicAPI] public static class TextTasks { private static UTF8Encoding UTF8NoBom => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); public static void WriteAllText (string path, string[] lines, Encoding encoding = null) { WriteAllText(path, string.Join(EnvironmentInfo.NewLine, lines), encoding); } public static void WriteAllText (string path, string content, Encoding encoding = null) { FileSystemTasks.EnsureExistingParentDirectory(path); File.WriteAllText(path, content, encoding ?? UTF8NoBom); } public static void WriteAllBytes (string path, byte[] bytes) { FileSystemTasks.EnsureExistingParentDirectory(path); File.WriteAllBytes(path, bytes); } public static string ReadAllText (string path, Encoding encoding = null) { return File.ReadAllText(path, encoding ?? Encoding.UTF8); } public static string[] ReadAllLines (string path, Encoding encoding = null) { return File.ReadAllLines(path, encoding ?? Encoding.UTF8); } public static byte[] ReadAllBytes (string path) { return File.ReadAllBytes(path); } } }
mit
C#
86d8910e56eebcdab1ec6f9c12774638b7ff6287
Add message debugger display to show the message type
FoundatioFx/Foundatio,exceptionless/Foundatio
src/Foundatio/Messaging/Message.cs
src/Foundatio/Messaging/Message.cs
using System; using System.Collections.Generic; using System.Diagnostics; namespace Foundatio.Messaging { public interface IMessage { string Type { get; } Type ClrType { get; } byte[] Data { get; } object GetBody(); IReadOnlyDictionary<string, string> Properties { get; } } [DebuggerDisplay("Type: {Type}")] public class Message : IMessage { private Lazy<object> _getBody; public Message(Func<object> getBody) { if (getBody == null) throw new ArgumentNullException("getBody"); _getBody = new Lazy<object>(getBody); } public string Type { get; set; } public Type ClrType { get; set; } public byte[] Data { get; set; } public object GetBody() => _getBody.Value; public IReadOnlyDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>(); } }
using System; using System.Collections.Generic; namespace Foundatio.Messaging { public interface IMessage { string Type { get; } Type ClrType { get; } byte[] Data { get; } object GetBody(); IReadOnlyDictionary<string, string> Properties { get; } } public class Message : IMessage { private Lazy<object> _getBody; public Message(Func<object> getBody) { if (getBody == null) throw new ArgumentNullException("getBody"); _getBody = new Lazy<object>(getBody); } public string Type { get; set; } public Type ClrType { get; set; } public byte[] Data { get; set; } public object GetBody() => _getBody.Value; public IReadOnlyDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>(); } }
apache-2.0
C#
5e6bd92b73a808ebb39cec96015a116eb09e4e26
Fix NativeInstantiation sample/test * sample/NativeInstantiationTest.cs: pinvoke the correct soname.
sillsdev/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp
sample/NativeInstantiationTest.cs
sample/NativeInstantiationTest.cs
// Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2009 Novell, Inc. namespace GtkSharp { using Gtk; using System; using System.Runtime.InteropServices; public class InstantiationTest : Gtk.Window { [DllImport ("libgobject-2.0.so.0")] static extern IntPtr g_object_new (IntPtr gtype, string prop, string val, IntPtr dummy); [DllImport ("libgtk-3.so.0")] static extern void gtk_widget_show (IntPtr handle); public static int Main (string[] args) { Application.Init (); GLib.GType gtype = LookupGType (typeof (InstantiationTest)); GLib.GType.Register (gtype, typeof (InstantiationTest)); Console.WriteLine ("Instantiating using managed constructor"); new InstantiationTest ("Managed Instantiation Test").ShowAll (); Console.WriteLine ("Managed Instantiation complete"); Console.WriteLine ("Instantiating using unmanaged construction"); IntPtr handle = g_object_new (gtype.Val, "title", "Unmanaged Instantiation Test", IntPtr.Zero); gtk_widget_show (handle); Console.WriteLine ("Unmanaged Instantiation complete"); Application.Run (); return 0; } public InstantiationTest (IntPtr raw) : base (raw) { Console.WriteLine ("IntPtr ctor invoked"); DefaultWidth = 400; DefaultHeight = 200; } public InstantiationTest (string title) : base (title) { DefaultWidth = 200; DefaultHeight = 400; } protected override bool OnDeleteEvent (Gdk.Event ev) { Application.Quit (); return true; } } }
// Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2009 Novell, Inc. namespace GtkSharp { using Gtk; using System; using System.Runtime.InteropServices; public class InstantiationTest : Gtk.Window { [DllImport ("libgobject-2.0.so.0")] static extern IntPtr g_object_new (IntPtr gtype, string prop, string val, IntPtr dummy); [DllImport ("libgtk-3.0.so.0")] static extern void gtk_widget_show (IntPtr handle); public static int Main (string[] args) { Application.Init (); GLib.GType gtype = LookupGType (typeof (InstantiationTest)); GLib.GType.Register (gtype, typeof (InstantiationTest)); Console.WriteLine ("Instantiating using managed constructor"); new InstantiationTest ("Managed Instantiation Test").ShowAll (); Console.WriteLine ("Managed Instantiation complete"); Console.WriteLine ("Instantiating using unmanaged construction"); IntPtr handle = g_object_new (gtype.Val, "title", "Unmanaged Instantiation Test", IntPtr.Zero); gtk_widget_show (handle); Console.WriteLine ("Unmanaged Instantiation complete"); Application.Run (); return 0; } public InstantiationTest (IntPtr raw) : base (raw) { Console.WriteLine ("IntPtr ctor invoked"); DefaultWidth = 400; DefaultHeight = 200; } public InstantiationTest (string title) : base (title) { DefaultWidth = 200; DefaultHeight = 400; } protected override bool OnDeleteEvent (Gdk.Event ev) { Application.Quit (); return true; } } }
lgpl-2.1
C#
9f5ffdcad55f3da4663f4b95e9647825247c03ff
update version
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
unity/library/UtyMap.Unity/Properties/AssemblyInfo.cs
unity/library/UtyMap.Unity/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("UtyMap.Unity")] [assembly: AssemblyDescription("UtyMap for Unity3D")] [assembly: AssemblyProduct("UtyMap.Unity")] [assembly: AssemblyCopyright("Copyright © Ilya Builuk, 2014-2016")] [assembly: AssemblyVersion("2.0.*")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("97791a51-a81b-45d4-a6fc-5dfa9ebcc603")] [assembly: InternalsVisibleTo("UtyMap.Unity.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("UtyMap.Unity")] [assembly: AssemblyDescription("UtyMap for Unity3D")] [assembly: AssemblyProduct("UtyMap.Unity")] [assembly: AssemblyCopyright("Copyright © Ilya Builuk, 2014-2016")] [assembly: AssemblyVersion("1.3.*")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("97791a51-a81b-45d4-a6fc-5dfa9ebcc603")] [assembly: InternalsVisibleTo("UtyMap.Unity.Tests")]
apache-2.0
C#
ce42f0ae2ac73f419db1588933ef2f44200268c1
add bufferText to display series of lastRcvd
yasokada/unity-151117-linemonitor-UI
Assets/lineMonitorUI.cs
Assets/lineMonitorUI.cs
using UnityEngine; using System.Collections; using UnityEngine.UI; // for Text using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using NS_MyNetUtil; // for MyNetUtil.getMyIPAddress() /* * v0.1 2015/11/19 * - * --------- converted from UdpEchoServer to line monitor ---------- * v0.4 2015/08/30 * - separate IP address get method to MyNetUtil.cs * v0.3 2015/08/30 * - show version info * - correct .gitignore file * v0.2 2015/08/29 * - fix for negative value for delay_msec * - fix for string to int * - fix for android (splash freeze) * v0.1 2015/08/29 * following features have been implemented. * - delay before echo back * - echo back */ public class lineMonitorUI : MonoBehaviour { Thread rcvThr; UdpClient client; public int port = 9000; public const string kAppName = "line monitor UI"; public const string kVersion = "v0.1"; public string lastRcvd; private string bufferText; public Text myipText; // to show my IP address(port) public Text recvdText; public Text versionText; private bool stopThr = false; int getDelay() { return 0; } void Start () { bufferText = ""; versionText.text = kAppName + " " + kVersion; myipText.text = MyNetUtil.getMyIPAddress() + " (" + port.ToString () + ")"; startTread (); } string getTextMessage(string rcvd) { if (rcvd.Length == 0) { return ""; } string msg = "rx: " + rcvd + System.Environment.NewLine + "tx: " + rcvd; return msg; } void Update() { // recvdText.text = getTextMessage (lastRcvd); if (lastRcvd.Length > 0) { bufferText = bufferText + lastRcvd; lastRcvd = ""; recvdText.text = bufferText; } } void startTread() { Debug.Log ("init"); rcvThr = new Thread( new ThreadStart(FuncRcvData)); rcvThr.Start (); } void OnApplicationQuit() { stopThr = true; rcvThr.Abort (); } private void FuncRcvData() { client = new UdpClient (port); client.Client.ReceiveTimeout = 300; // msec client.Client.Blocking = false; while (stopThr == false) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); string text = Encoding.ASCII.GetString(data); lastRcvd = text; // if (lastRcvd.Length > 0) { // client.Send(data, data.Length, anyIP); // echo // } } catch (Exception err) { // print(err.ToString()); } // without this sleep, on adnroid, the app will not start (freeze at Unity splash) Thread.Sleep(20); // 200 } client.Close (); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; // for Text using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using NS_MyNetUtil; // for MyNetUtil.getMyIPAddress() /* * v0.1 2015/11/19 * - * --------- converted from UdpEchoServer to line monitor ---------- * v0.4 2015/08/30 * - separate IP address get method to MyNetUtil.cs * v0.3 2015/08/30 * - show version info * - correct .gitignore file * v0.2 2015/08/29 * - fix for negative value for delay_msec * - fix for string to int * - fix for android (splash freeze) * v0.1 2015/08/29 * following features have been implemented. * - delay before echo back * - echo back */ public class lineMonitorUI : MonoBehaviour { Thread rcvThr; UdpClient client; public int port = 9000; public const string kAppName = "line monitor UI"; public const string kVersion = "v0.1"; public string lastRcvd; public Text myipText; // to show my IP address(port) public Text recvdText; public Text versionText; private bool stopThr = false; int getDelay() { return 0; } void Start () { versionText.text = kAppName + " " + kVersion; myipText.text = MyNetUtil.getMyIPAddress() + " (" + port.ToString () + ")"; startTread (); } string getTextMessage(string rcvd) { if (rcvd.Length == 0) { return ""; } string msg = "rx: " + rcvd + System.Environment.NewLine + "tx: " + rcvd; return msg; } void Update() { recvdText.text = getTextMessage (lastRcvd); } void startTread() { Debug.Log ("init"); rcvThr = new Thread( new ThreadStart(FuncRcvData)); rcvThr.Start (); } void OnApplicationQuit() { stopThr = true; rcvThr.Abort (); } private void FuncRcvData() { client = new UdpClient (port); client.Client.ReceiveTimeout = 300; // msec client.Client.Blocking = false; while (stopThr == false) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); string text = Encoding.ASCII.GetString(data); lastRcvd = text; // if (lastRcvd.Length > 0) { // client.Send(data, data.Length, anyIP); // echo // } } catch (Exception err) { // print(err.ToString()); } // without this sleep, on adnroid, the app will not start (freeze at Unity splash) Thread.Sleep(20); // 200 } client.Close (); } }
mit
C#
985b1ca19a9966a331e18d52f3de83887f5f9fa7
make Write() async, closes #88
OrleansContrib/OrleansDashboard,OrleansContrib/OrleansDashboard,OrleansContrib/OrleansDashboard
OrleansDashboard/TraceWriter.cs
OrleansDashboard/TraceWriter.cs
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace OrleansDashboard { public class TraceWriter : IDisposable { private readonly DashboardTraceListener traceListener; private readonly HttpContext context; public TraceWriter(DashboardTraceListener traceListener, HttpContext context) { this.traceListener = traceListener; this.traceListener.Add(Write); this.context = context; } private void Write(string message) { var task = WriteAsync(message); task.ConfigureAwait(false); task.ContinueWith(_ => { /* noop */ }); } public async Task WriteAsync(string message) { await context.Response.WriteAsync(message).ConfigureAwait(false); await context.Response.Body.FlushAsync().ConfigureAwait(false); } public void Dispose() { traceListener.Remove(Write); } } }
using Microsoft.AspNetCore.Http; using System; using System.Threading.Tasks; namespace OrleansDashboard { public class TraceWriter : IDisposable { private readonly DashboardTraceListener traceListener; private readonly HttpContext context; public TraceWriter(DashboardTraceListener traceListener, HttpContext context) { this.traceListener = traceListener; this.traceListener.Add(Write); this.context = context; } private void Write(string message) { WriteAsync(message).Wait(); } public async Task WriteAsync(string message) { await context.Response.WriteAsync(message).ConfigureAwait(false); await context.Response.Body.FlushAsync().ConfigureAwait(false); } public void Dispose() { traceListener.Remove(Write); } } }
mit
C#
02901cbab71f45c285437a4872241fe88950a57b
Update RuleUpdater.cs
win120a/ACClassRoomUtil,win120a/ACClassRoomUtil
ProcessBlockUtil/RuleUpdater.cs
ProcessBlockUtil/RuleUpdater.cs
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) 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. */ using System; using System.IO; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using NetUtil; namespace ACProcessBlockUtil { class RuleUpdater { public static void Main(String[] a){ /* Stop The Service. */ ServiceController pbuSC = new ServiceController("pbuService"); pbuSC.stop(); /* Obtain some path. */ String userProfile = Environment.GetEnvironmentVariable("UserProfile"); String systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); /* Delete Exist file. */ if(File.Exists(userProfile + "\\ACRules.txt")){ File.Delete(userProfile + "\\ACRules.txt"); } /* Download File. */ NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt"); /* Restart the Service. */ Process.Start(systemRoot + "\\System32\\sc.exe", "start pbuService"); } } }
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) 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. */ using System; using System.IO; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using NetUtil; namespace ACProcessBlockUtil { class RuleUpdater { public static void Main(String[] a){ /* Stop The Service. */ ServiceController pbuSC = new ServiceController("pbuService"); pbuSC.stop(); /* Obtain some path. */ String userProfile = Environment.GetEnvironmentVariable("UserProfile"); String systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); /* Delete Exist file. */ if(File.Exists(userProfile + "\\ACRules.txt")){ File.Delete(userProfile + "\\ACRules.txt"); } /* Download File. */ NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt"); /* Restart the Service. */ Process.Start(systemRoot + "\\System32\\sc.exe", "start pbuService"); } } }
apache-2.0
C#
d2e048c405a9e47bab82a211305bfff118edd26b
Revert "Instance isn't found if class is on a disabled GameObject."
paseb/MixedRealityToolkit-Unity,NeerajW/HoloToolkit-Unity,paseb/HoloToolkit-Unity,out-of-pixel/HoloToolkit-Unity,HattMarris1/HoloToolkit-Unity,willcong/HoloToolkit-Unity
Assets/HoloToolkit/Utilities/Scripts/SingleInstance.cs
Assets/HoloToolkit/Utilities/Scripts/SingleInstance.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake /// </summary> /// <typeparam name="T"></typeparam> public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T> { private static T _Instance; public static T Instance { get { if (_Instance == null) { T[] objects = FindObjectsOfType<T>(); if (objects.Length != 1) { Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length); } else { _Instance = objects[0]; } } return _Instance; } } /// <summary> /// Called by Unity when destroying a MonoBehaviour. Scripts that extend /// SingleInstance should be sure to call base.OnDestroy() to ensure the /// underlying static _Instance reference is properly cleaned up. /// </summary> protected virtual void OnDestroy() { _Instance = null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake /// </summary> /// <typeparam name="T"></typeparam> public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T> { private static T _Instance; public static T Instance { get { if (_Instance == null) { T[] objects = Resources.FindObjectsOfTypeAll<T>(); if (objects.Length != 1) { Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length); } else { _Instance = objects[0]; } } return _Instance; } } /// <summary> /// Called by Unity when destroying a MonoBehaviour. Scripts that extend /// SingleInstance should be sure to call base.OnDestroy() to ensure the /// underlying static _Instance reference is properly cleaned up. /// </summary> protected virtual void OnDestroy() { _Instance = null; } } }
mit
C#
91667f2c44a59c4aa3204b6f1c8cdf128e4bb19d
Delete some dead TODO's
blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon
Compiler/Common/TODO.cs
Compiler/Common/TODO.cs
namespace Common { public static class TODO { // TODO: Group these by priority/severity public static void LibrariesNeedVersionNumber() { } public static void ThrowErrorIfKeywordThisIsUsedInBaseArgsOrDefaultArgsAnywhereInConstructor() { } public static void VerifyDefaultArgumentsAreAtTheEnd() { } public static void VerifyNoDuplicateKeysInDictionaryDefinition() { } public static void MakeSwitchStatementFallthroughsErrors() { } public static void BuildFileShouldIndicateWhichResourcesAreTextVsBinary() { } public static void GetImageDimensionsFromFirstFewBytesInsteadOfLoadingIntoMemory() { } public static void PutImageWidthAndHeightIntoFileOutputPropertiesSoThatBitmapDoesntNeedToBePersistedInMemory() { } public static void MoveCbxParserIntoTranslatedPastelCode() { } // TODO: resolve before releasing locale stuff public static void GetCoreNameFromMetadataWithLocale() { } public static void IsValidLibraryNameIsWrong() { } public static void ThisErrorMessageIsNotVeryHelpeful() { } public static void CheckForUnusedAnnotations() { } public static void MoreExtensibleFormOfParsingAnnotations() { } } }
namespace Common { public static class TODO { // TODO: Group these by priority/severity public static void LibrariesNeedVersionNumber() { } public static void ThrowErrorIfKeywordThisIsUsedInBaseArgsOrDefaultArgsAnywhereInConstructor() { } public static void VerifyDefaultArgumentsAreAtTheEnd() { } public static void VerifyNoDuplicateKeysInDictionaryDefinition() { } public static void VerifyAllDictionaryKeysAreCorrectType() { } public static void MakeSwitchStatementFallthroughsErrors() { } public static void BuildFileShouldIndicateWhichResourcesAreTextVsBinary() { } public static void GetImageDimensionsFromFirstFewBytesInsteadOfLoadingIntoMemory() { } public static void PutImageWidthAndHeightIntoFileOutputPropertiesSoThatBitmapDoesntNeedToBePersistedInMemory() { } public static void JavaScriptDeGamification() { } public static void ExplicitlyDisallowThisAtCompileTime() { } public static void MoveCbxParserIntoTranslatedPastelCode() { } public static void CompileTimeConstantConsolidationTypeLookupIsVeryUgly() { } // TODO: resolve before releasing locale stuff public static void GetCoreNameFromMetadataWithLocale() { } public static void IsValidLibraryNameIsWrong() { } public static void ThisErrorMessageIsNotVeryHelpeful() { } public static void CheckForUnusedAnnotations() { } public static void MoreExtensibleFormOfParsingAnnotations() { } } }
mit
C#
9b0f5e8120cc8c104baa3361a9f5141f565b2868
Add a timer for all puzzles
martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode
src/AdventOfCode2015/Program.cs
src/AdventOfCode2015/Program.cs
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode2015 { using System; using System.Diagnostics; using System.Globalization; using System.Linq; /// <summary> /// A console application that solves puzzles for <c>http://adventofcode.com</c>. This class cannot be inherited. /// </summary> internal static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns>The exit code from the application.</returns> internal static int Main(string[] args) { if (args == null || args.Length < 1) { Console.Error.WriteLine("No day specified."); return -1; } int day; if (!int.TryParse(args[0], NumberStyles.Integer & ~NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out day) || day < 1 || day > 25) { Console.Error.WriteLine("The day specified is invalid."); return -1; } Console.WriteLine(); Console.WriteLine("Advent of Code - Day {0}", day); Console.WriteLine(); IPuzzle puzzle = GetPuzzle(day); args = args.Skip(1).ToArray(); Stopwatch stopwatch = Stopwatch.StartNew(); int result = puzzle.Solve(args); stopwatch.Stop(); Console.WriteLine(); Console.WriteLine("Took {0:N2} seconds.", stopwatch.Elapsed.TotalSeconds); return result; } /// <summary> /// Gets the puzzle to use for the specified day. /// </summary> /// <param name="day">The day to get the puzzle for.</param> /// <returns>The <see cref="IPuzzle"/> for the specified day.</returns> private static IPuzzle GetPuzzle(int day) { string typeName = string.Format( CultureInfo.InvariantCulture, "MartinCostello.AdventOfCode2015.Puzzles.Day{0:00}", day); return Activator.CreateInstance(Type.GetType(typeName), nonPublic: true) as IPuzzle; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode2015 { using System; using System.Globalization; using System.Linq; /// <summary> /// A console application that solves puzzles for <c>http://adventofcode.com</c>. This class cannot be inherited. /// </summary> internal static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns>The exit code from the application.</returns> internal static int Main(string[] args) { if (args == null || args.Length < 1) { Console.Error.WriteLine("No day specified."); return -1; } int day; if (!int.TryParse(args[0], NumberStyles.Integer & ~NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out day) || day < 1 || day > 25) { Console.Error.WriteLine("The day specified is invalid."); return -1; } Console.WriteLine(); Console.WriteLine("Advent of Code - Day {0}", day); Console.WriteLine(); IPuzzle puzzle = GetPuzzle(day); return puzzle.Solve(args.Skip(1).ToArray()); } /// <summary> /// Gets the puzzle to use for the specified day. /// </summary> /// <param name="day">The day to get the puzzle for.</param> /// <returns>The <see cref="IPuzzle"/> for the specified day.</returns> private static IPuzzle GetPuzzle(int day) { string typeName = string.Format( CultureInfo.InvariantCulture, "MartinCostello.AdventOfCode2015.Puzzles.Day{0:00}", day); return Activator.CreateInstance(Type.GetType(typeName), nonPublic: true) as IPuzzle; } } }
apache-2.0
C#
96cf80bb93746b44ac25a6e3561229f754986a51
Fix invisible window after restoring from tray the second time
szarvas/fanduino,szarvas/fanduino
FanduinoWindow/Form1.cs
FanduinoWindow/Form1.cs
/* Copyright 2016 Attila Szarvas 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. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Win32; using System.IO; namespace FanduinoWindow { public partial class Form1 : Form { public Form1() { InitializeComponent(); if (Fanduino.Config.startMinimized) { WindowState = FormWindowState.Minimized; Form1_Resize(this, null); } } delegate void SetTextCallback(string text); public void SetText(String msg) { if (this.label1.InvokeRequired) { this.Invoke(new SetTextCallback(SetText), new object[] { msg }); } else { this.label1.Text = msg; } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; notifyIcon1.Visible = false; } private void Form1_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { notifyIcon1.Visible = true; this.ShowInTaskbar = false; } } } }
/* Copyright 2016 Attila Szarvas 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. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Win32; using System.IO; namespace FanduinoWindow { public partial class Form1 : Form { public Form1() { InitializeComponent(); if (Fanduino.Config.startMinimized) { WindowState = FormWindowState.Minimized; Form1_Resize(this, null); } } delegate void SetTextCallback(string text); public void SetText(String msg) { if (this.label1.InvokeRequired) { this.Invoke(new SetTextCallback(SetText), new object[] { msg }); } else { this.label1.Text = msg; } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; Show(); notifyIcon1.Visible = false; } private void Form1_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { notifyIcon1.Visible = true; Hide(); this.ShowInTaskbar = false; } } } }
apache-2.0
C#
ba5ef38ec8b21711b4d94d57c7b049cff6ef064f
update cake
predictive-technology-laboratory/Xamarin.Plugins,jamesmontemagno/Xamarin.Plugins,monostefan/Xamarin.Plugins
Settings/build.cake
Settings/build.cake
#addin "Cake.FileHelpers" var TARGET = Argument ("target", Argument ("t", "Build")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); Task ("Build").Does (() => { const string sln = "./Refractored.XamPlugins.Settings.sln"; const string cfg = "Release"; NuGetRestore (sln); if (!IsRunningOnWindows ()) DotNetBuild (sln, c => c.Configuration = cfg); else MSBuild (sln, c => { c.Configuration = cfg; c.MSBuildPlatform = MSBuildPlatform.x86; }); }); Task ("NuGetPack") .IsDependentOn ("Build") .Does (() => { NuGetPack ("./Common/Xam.Plugins.Settings.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./", BasePath = "./", }); }); RunTarget (TARGET);
#addin "Cake.FileHelpers" var TARGET = Argument ("target", Argument ("t", "Build")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); Task ("Build").Does (() => { const string sln = "./Refractored.XamPlugins.Settings.sln"; const string cfg = "Release"; NuGetRestore (sln); if (!IsRunningOnWindows ()) DotNetBuild (sln, c => c.Configuration = cfg); else MSBuild ("./Battery.", c => { c.Configuration = cfg; c.MSBuildPlatform = MSBuildPlatform.x86; }); }); Task ("NuGetPack") .IsDependentOn ("Build") .Does (() => { NuGetPack ("./Common/Xam.Plugins.Settings.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./", BasePath = "./", }); }); RunTarget (TARGET);
mit
C#
49702ee0e7c4ad497ba96698f2281d0038245e93
Replace HasCustomAttribute with IsInternalCall (#1992)
tijoytom/corert,tijoytom/corert,shrah/corert,krytarowski/corert,botaberg/corert,gregkalapos/corert,gregkalapos/corert,botaberg/corert,gregkalapos/corert,yizhang82/corert,sandreenko/corert,yizhang82/corert,shrah/corert,botaberg/corert,krytarowski/corert,shrah/corert,sandreenko/corert,krytarowski/corert,shrah/corert,botaberg/corert,gregkalapos/corert,tijoytom/corert,krytarowski/corert,sandreenko/corert,tijoytom/corert,yizhang82/corert,yizhang82/corert,sandreenko/corert
src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs
src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { public sealed class RyuJitNodeFactory : NodeFactory { public RyuJitNodeFactory(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup) : base(context, compilationModuleGroup) { } protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method) { if (method.IsInternalCall) { // The only way to locate the entrypoint for an internal call is through the RuntimeImportAttribute. // If this is a method that doesn't have it (e.g. a string constructor), the method should never // have reached this code path. Debug.Assert(method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute")); return new RuntimeImportMethodNode(method); } if (CompilationModuleGroup.ContainsMethod(method)) { return new MethodCodeNode(method); } else { return new ExternMethodSymbolNode(method); } } protected override IMethodNode CreateUnboxingStubNode(MethodDesc method) { return new UnboxingStubNode(method); } protected override ISymbolNode CreateReadyToRunHelperNode(Tuple<ReadyToRunHelperId, object> helperCall) { return new ReadyToRunHelperNode(helperCall.Item1, helperCall.Item2); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { public sealed class RyuJitNodeFactory : NodeFactory { public RyuJitNodeFactory(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup) : base(context, compilationModuleGroup) { } protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method) { if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute")) { return new RuntimeImportMethodNode(method); } if (CompilationModuleGroup.ContainsMethod(method)) { return new MethodCodeNode(method); } else { return new ExternMethodSymbolNode(method); } } protected override IMethodNode CreateUnboxingStubNode(MethodDesc method) { return new UnboxingStubNode(method); } protected override ISymbolNode CreateReadyToRunHelperNode(Tuple<ReadyToRunHelperId, object> helperCall) { return new ReadyToRunHelperNode(helperCall.Item1, helperCall.Item2); } } }
mit
C#
a35ef538916b89cdce5339399a14a58dd14f1144
Fix mef attributes project path provider
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.VisualStudio.Editor.Razor/DefaultProjectPathProviderFactory.cs
src/Microsoft.VisualStudio.Editor.Razor/DefaultProjectPathProviderFactory.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.Editor.Razor { [Shared] [ExportWorkspaceServiceFactory(typeof(ProjectPathProvider), ServiceLayer.Default)] internal class DefaultProjectPathProviderFactory : IWorkspaceServiceFactory { private readonly TextBufferProjectService _projectService; [ImportingConstructor] public DefaultProjectPathProviderFactory(TextBufferProjectService projectService) { if (projectService == null) { throw new ArgumentNullException(nameof(projectService)); } _projectService = projectService; } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (workspaceServices == null) { throw new ArgumentNullException(nameof(workspaceServices)); } return new DefaultProjectPathProvider(_projectService); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Razor; namespace Microsoft.VisualStudio.Editor.Razor { [System.Composition.Shared] [ExportWorkspaceService(typeof(ProjectPathProvider), ServiceLayer.Default)] internal class DefaultProjectPathProviderFactory : IWorkspaceServiceFactory { private readonly TextBufferProjectService _projectService; [ImportingConstructor] public DefaultProjectPathProviderFactory(TextBufferProjectService projectService) { if (projectService == null) { throw new ArgumentNullException(nameof(projectService)); } _projectService = projectService; } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (workspaceServices == null) { throw new ArgumentNullException(nameof(workspaceServices)); } return new DefaultProjectPathProvider(_projectService); } } }
apache-2.0
C#
7d1ef646b4e0bbf0f53b0ab4140450f17853693c
Implement GetPagedList (filtered by locationviewID) for Locations
cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,MagedAlNaamani/DynThings
DynThings.Data.Repositories/Repositories/LocationsRepository.cs
DynThings.Data.Repositories/Repositories/LocationsRepository.cs
///////////////////////////////////////////////////////////////// // Created by : Caesar Moussalli // // TimeStamp : 31-1-2016 // // Content : Handle Locations CRUD // // Notes : // ///////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DynThings.Data.Models; using PagedList; namespace DynThings.Data.Repositories { public class LocationsRepository { private DynThingsEntities db = new DynThingsEntities(); #region GetList /// <summary> /// Get list of Locations /// </summary> /// <returns>List of Locations </returns> public List<Location> GetList() { List<Location> locs = db.Locations.ToList(); return locs; } public List<Location> GetList(string search) { List<Location> locs = db.Locations .Where(e => search == null || e.Title.Contains(search)) .ToList(); return locs; } public IPagedList GetPagedList(string search, int pageNumber, int recordsPerPage) { IPagedList locs = db.Locations .Where(e => search == null || e.Title.Contains(search)) .OrderBy(e => e.Title).ToList() .ToPagedList(pageNumber, recordsPerPage); return locs; } public IPagedList GetPagedList(string search,long locationViewID, int pageNumber, int recordsPerPage) { IPagedList locs = db.Locations .Where(e => search == null || e.Title.Contains(search) && e.LinkLocationsLocationViews.Any(l => l.LocationViewID.Equals(locationViewID)) ) .OrderBy(e => e.Title).ToList() .ToPagedList(pageNumber, recordsPerPage); return locs; } #endregion #region Find /// <summary> /// Find Location by Location ID /// </summary> /// <param name="id">Location ID</param> /// <returns>Location object</returns> public Location Find(int id) { Location loc = new Location(); List<Location> locs = db.Locations.Where(l => l.ID == id).ToList(); if (locs.Count == 1) { loc = locs[0]; } else { throw new Exception("Not Found"); } return loc; } #endregion } }
///////////////////////////////////////////////////////////////// // Created by : Caesar Moussalli // // TimeStamp : 31-1-2016 // // Content : Handle Locations CRUD // // Notes : // ///////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DynThings.Data.Models; namespace DynThings.Data.Repositories { public class LocationsRepository { private DynThingsEntities db = new DynThingsEntities(); /// <summary> /// Find Location by Location ID /// </summary> /// <param name="id">Location ID</param> /// <returns>Location object</returns> public Location Find(int id) { Location loc = new Location(); List<Location> locs = db.Locations.Where(l => l.ID == id).ToList(); if (locs.Count == 1) { loc = locs[0]; } else { throw new Exception("Not Found"); } return loc; } } }
mit
C#
5967f5d90c3e3b4fe395882dadca1c7c2c1676be
Use ISO 8601 format for logger timestamps
AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet
src/ADAL.PCL/Platform/LoggerBase.cs
src/ADAL.PCL/Platform/LoggerBase.cs
//---------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; using System.Globalization; namespace Microsoft.IdentityModel.Clients.ActiveDirectory { internal abstract class LoggerBase { internal abstract void Verbose(CallState callState, string message, [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = ""); internal abstract void Information(CallState callState, string message, [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = ""); internal abstract void Warning(CallState callState, string message, [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = ""); internal abstract void Error(CallState callState, Exception ex, [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = ""); internal static string GetCallerFilename(string callerFilePath) { return callerFilePath.Substring(callerFilePath.LastIndexOf("\\", StringComparison.Ordinal) + 1); } internal static string PrepareLogMessage(CallState callState, string classOrComponent, string message) { string correlationId = (callState != null) ? callState.CorrelationId.ToString() : string.Empty; return string.Format(CultureInfo.InvariantCulture, "{0:O}: {1} - {2}: {3}", DateTime.UtcNow, correlationId, classOrComponent, message); } } }
//---------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; using System.Globalization; namespace Microsoft.IdentityModel.Clients.ActiveDirectory { internal abstract class LoggerBase { internal abstract void Verbose(CallState callState, string message, [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = ""); internal abstract void Information(CallState callState, string message, [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = ""); internal abstract void Warning(CallState callState, string message, [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = ""); internal abstract void Error(CallState callState, Exception ex, [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = ""); internal static string GetCallerFilename(string callerFilePath) { return callerFilePath.Substring(callerFilePath.LastIndexOf("\\", StringComparison.Ordinal) + 1); } internal static string PrepareLogMessage(CallState callState, string classOrComponent, string message) { string correlationId = (callState != null) ? callState.CorrelationId.ToString() : string.Empty; return string.Format(CultureInfo.CurrentCulture, "{0}: {1} - {2}: {3}", DateTime.UtcNow, correlationId, classOrComponent, message); } } }
mit
C#
c99b48f9342189ba0290702893fbdcc1a7b72f2f
Bring up-to-date and use IApplicableFailOverride
2yangk23/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,johnneijzen/osu,ZLima12/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu,johnneijzen/osu,ZLima12/osu
osu.Game/Rulesets/Mods/ModEasy.cs
osu.Game/Rulesets/Mods/ModEasy.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.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModEasy : Mod, IApplicableToDifficulty, IApplicableFailOverride, IApplicableToScoreProcessor { public override string Name => "Easy"; public override string Acronym => "EZ"; public override IconUsage Icon => OsuIcon.ModEasy; public override ModType Type => ModType.DifficultyReduction; public override double ScoreMultiplier => 0.5; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModHardRock) }; private int retries = 2; private BindableNumber<double> health; public void ApplyToDifficulty(BeatmapDifficulty difficulty) { const float ratio = 0.5f; difficulty.CircleSize *= ratio; difficulty.ApproachRate *= ratio; difficulty.DrainRate *= ratio; difficulty.OverallDifficulty *= ratio; } public bool AllowFail { get { if (retries == 0) return true; health.Value = health.MaxValue; retries--; return false; } } public bool RestartOnFail => false; public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { health = scoreProcessor.Health.GetBoundCopy(); } public ScoreRank AdjustRank(ScoreRank rank, double accuracy) => rank; } }
// 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.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModEasy : Mod, IApplicableToDifficulty, IApplicableToScoreProcessor { private int lives; public override string Name => "Easy"; public override string Acronym => "EZ"; public override IconUsage Icon => OsuIcon.ModEasy; public override ModType Type => ModType.DifficultyReduction; public override double ScoreMultiplier => 0.5; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModHardRock) }; public void ApplyToDifficulty(BeatmapDifficulty difficulty) { const float ratio = 0.5f; difficulty.CircleSize *= ratio; difficulty.ApproachRate *= ratio; difficulty.DrainRate *= ratio; difficulty.OverallDifficulty *= ratio; } public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { //Note : The lives has to be instaciated here in order to prevent the values from different plays to interfear //with each other / not reseting after a restart , as this method is called once a play starts (to my knowlegde). //This will be better implemented with a List<double> once I know how to reliably get the game time and update it. //If you know any information about that, please contact me because I didn't find a sollution to that. lives = 2; scoreProcessor.Health.ValueChanged += valueChanged => { if (scoreProcessor.Health.Value == scoreProcessor.Health.MinValue && lives > 0) { lives--; scoreProcessor.Health.Value = scoreProcessor.Health.MaxValue; } }; } } }
mit
C#
d065b7788972d97a21d2ccce8a5adbf7a5364a86
improve test error reporting
gasparnagy/berp,gasparnagy/berp,gasparnagy/berp
src/Berp.Specs/StepDefinitions/GenerationStepDefinitions.cs
src/Berp.Specs/StepDefinitions/GenerationStepDefinitions.cs
using System; using System.IO; using Berp.BerpGrammar; using Berp.Specs.Support; using FluentAssertions; using TechTalk.SpecFlow; using Xunit.Abstractions; namespace Berp.Specs.StepDefinitions { [Binding] public class GenerationStepDefinitions { private string grammarDefinition; private string outputFile; private Exception generationError; private readonly ITestOutputHelper _testOutputHelper; public GenerationStepDefinitions(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } [Given("there is a complex grammar")] public void GivenThereIsAComplexGrammar() { var fullPath = TestFolders.GetInputFilePath(@"BerpGrammarParserForTest\BerpGrammar.berp"); grammarDefinition = File.ReadAllText(fullPath); } [When("the parser generation is performed using {string}")] public void WhenTheParserGenerationIsPerformedUsing(string templateName) { var parser = new BerpGrammar.Parser(); var ruleSet = parser.Parse(new TokenScanner(new StringReader(grammarDefinition))); var states = StateCalculator.CalculateStates(ruleSet); try { var generator = new Generator(ruleSet.Settings); outputFile = TestFolders.GetTempFilePath("output.txt"); generator.Generate(Path.Combine("GeneratorTemplates", templateName), ruleSet, states, outputFile); _testOutputHelper.WriteLine($"Result saved to: {outputFile}"); } catch (Exception ex) { generationError = ex; } } [Then("then the generation should be successful")] public void ThenThenTheGenerationShouldBeSuccessful() { generationError.Should().BeNull(); File.Exists(outputFile).Should().BeTrue(); } } }
using System; using System.IO; using Berp.BerpGrammar; using Berp.Specs.Support; using FluentAssertions; using TechTalk.SpecFlow; namespace Berp.Specs.StepDefinitions { [Binding] public class GenerationStepDefinitions { private string grammarDefinition; private string outputFile; private Exception generationError; [Given("there is a complex grammar")] public void GivenThereIsAComplexGrammar() { var fullPath = TestFolders.GetInputFilePath(@"BerpGrammarParserForTest\BerpGrammar.berp"); grammarDefinition = File.ReadAllText(fullPath); } [When("the parser generation is performed using {string}")] public void WhenTheParserGenerationIsPerformedUsing(string templateName) { var parser = new BerpGrammar.Parser(); var ruleSet = parser.Parse(new TokenScanner(new StringReader(grammarDefinition))); var states = StateCalculator.CalculateStates(ruleSet); try { var generator = new Generator(ruleSet.Settings); outputFile = TestFolders.GetTempFilePath("output.txt"); generator.Generate(Path.Combine("GeneratorTemplates", templateName), ruleSet, states, outputFile); } catch (Exception ex) { generationError = ex; } } [Then("then the generation should be successful")] public void ThenThenTheGenerationShouldBeSuccessful() { generationError.Should().BeNull(); File.Exists(outputFile).Should().BeTrue(); } } }
apache-2.0
C#
bfc4879e9af4c509ceabb015e3998dd928b5d634
Update DbSetExtensions.cs
chunk1ty/TeachersDiary,chunk1ty/TeachersDiary,chunk1ty/TeachersDiary
src/Data/TeacherDiary.Data.Ef/Extensions/DbSetExtensions.cs
src/Data/TeacherDiary.Data.Ef/Extensions/DbSetExtensions.cs
using System.Collections.Generic; using System.Data.Entity; namespace TeacherDiary.Data.Ef.Extensions { public static class DbSetExtensions { public static IEnumerable<TEntity> AddRange<TEntity>(this IDbSet<TEntity> dbset, IEnumerable<TEntity> entitiesToAdd) where TEntity : class { return ((DbSet<TEntity>)dbset).AddRange(entitiesToAdd); } public static IEnumerable<TEntity> RemoveRange<TEntity>(this IDbSet<TEntity> dbset, IEnumerable<TEntity> entitiesToDelete) where TEntity : class { return ((DbSet<TEntity>)dbset).RemoveRange(entitiesToDelete); } } }
using System.Collections.Generic; using System.Data.Entity; namespace TeacherDiary.Data.Ef.Extensions { public static class DbSetExtensions { public static IEnumerable<TEntity> AddRange<TEntity>(this IDbSet<TEntity> dbset, IEnumerable<TEntity> entitiesToAdd) where TEntity : class { return ((DbSet<TEntity>)dbset).AddRange(entitiesToAdd); } public static IEnumerable<TEntity> RemoveRange<TEntity>(this IDbSet<TEntity> dbset, IEnumerable<TEntity> entitiesToDelete) where TEntity : class { return ((DbSet<TEntity>)dbset).RemoveRange(entitiesToDelete); } } }
mit
C#
ded8af3269f9899308d85bfe46eea50df0b08180
Add googlebot and bingbot to list of crawler user agents
dingyuliang/prerender-dotnet,dingyuliang/prerender-dotnet,dingyuliang/prerender-dotnet
src/DotNetPrerender/DotNetOpen.PrerenderModule/Constants.cs
src/DotNetPrerender/DotNetOpen.PrerenderModule/Constants.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotNetOpen.PrerenderModule { public static class Constants { #region Const public const string PrerenderIOServiceUrl = "http://service.prerender.io/"; public const int DefaultPort = 80; public const string CrawlerUserAgentPattern = "(bingbot)|(googlebot)|(google)|(bing)|(Slurp)|(DuckDuckBot)|(YandexBot)|(baiduspider)|(Sogou)|(Exabot)|(ia_archiver)|(facebot)|(facebook)|(twitterbot)|(rogerbot)|(linkedinbot)|(embedly)|(quora)|(pinterest)|(slackbot)|(redditbot)|(Applebot)|(WhatsApp)|(flipboard)|(tumblr)|(bitlybot)|(Discordbot)"; public const string EscapedFragment = "_escaped_fragment_"; public const string HttpProtocol = "http://"; public const string HttpsProtocol = "https://"; public const string HttpHeader_XForwardedProto = "X-Forwarded-Proto"; public const string HttpHeader_XPrerenderToken = "X-Prerender-Token"; public const string AppSetting_UsePrestartForPrenderModule = "UsePrestartForPrenderModule"; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotNetOpen.PrerenderModule { public static class Constants { #region Const public const string PrerenderIOServiceUrl = "http://service.prerender.io/"; public const int DefaultPort = 80; public const string CrawlerUserAgentPattern = "(google)|(bing)|(Slurp)|(DuckDuckBot)|(YandexBot)|(baiduspider)|(Sogou)|(Exabot)|(ia_archiver)|(facebot)|(facebook)|(twitterbot)|(rogerbot)|(linkedinbot)|(embedly)|(quora)|(pinterest)|(slackbot)|(redditbot)|(Applebot)|(WhatsApp)|(flipboard)|(tumblr)|(bitlybot)|(Discordbot)"; public const string EscapedFragment = "_escaped_fragment_"; public const string HttpProtocol = "http://"; public const string HttpsProtocol = "https://"; public const string HttpHeader_XForwardedProto = "X-Forwarded-Proto"; public const string HttpHeader_XPrerenderToken = "X-Prerender-Token"; public const string AppSetting_UsePrestartForPrenderModule = "UsePrestartForPrenderModule"; #endregion } }
mit
C#
a362b346caf79117a5d9f551ebb0b36bd5092992
remove perf scope wrapper since the scope is small (#858)
hellosnow/docfx,DuncanmaMSFT/docfx,pascalberger/docfx,dotnet/docfx,hellosnow/docfx,LordZoltan/docfx,LordZoltan/docfx,LordZoltan/docfx,superyyrrzz/docfx,superyyrrzz/docfx,pascalberger/docfx,928PJY/docfx,DuncanmaMSFT/docfx,LordZoltan/docfx,928PJY/docfx,dotnet/docfx,pascalberger/docfx,superyyrrzz/docfx,hellosnow/docfx,928PJY/docfx,dotnet/docfx
src/Microsoft.DocAsCode.Build.Common/HtmlDocumentHandler.cs
src/Microsoft.DocAsCode.Build.Common/HtmlDocumentHandler.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.Common { using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Plugins; using HtmlAgilityPack; public abstract class HtmlDocumentHandler : IHtmlDocumentHandler { public abstract void Handle(HtmlDocument document, ManifestItem manifestItem, string inputFile, string outputFile); public abstract Manifest PostHandle(Manifest manifest); public abstract Manifest PreHandle(Manifest manifest); public void HandleWithScopeWrapper(HtmlDocument document, ManifestItem manifestItem, string inputFile, string outputFile) { string phase = this.GetType().Name; using (new LoggerPhaseScope(phase, false)) { Handle(document, manifestItem, inputFile, outputFile); } } public Manifest PostHandleWithScopeWrapper(Manifest manifest) { string phase = this.GetType().Name; using (new LoggerPhaseScope(phase, false)) { return PostHandle(manifest); } } public Manifest PreHandleWithScopeWrapper(Manifest manifest) { string phase = this.GetType().Name; using (new LoggerPhaseScope(phase, false)) { return PreHandle(manifest); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.Common { using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Plugins; using HtmlAgilityPack; public abstract class HtmlDocumentHandler : IHtmlDocumentHandler { public abstract void Handle(HtmlDocument document, ManifestItem manifestItem, string inputFile, string outputFile); public abstract Manifest PostHandle(Manifest manifest); public abstract Manifest PreHandle(Manifest manifest); public void HandleWithScopeWrapper(HtmlDocument document, ManifestItem manifestItem, string inputFile, string outputFile) { string phase = this.GetType().Name; using (new LoggerPhaseScope(phase, false)) using (new PerformanceScope(phase, LogLevel.Verbose)) { Handle(document, manifestItem, inputFile, outputFile); } } public Manifest PostHandleWithScopeWrapper(Manifest manifest) { string phase = this.GetType().Name; using (new LoggerPhaseScope(phase, false)) using (new PerformanceScope(phase, LogLevel.Verbose)) { return PostHandle(manifest); } } public Manifest PreHandleWithScopeWrapper(Manifest manifest) { string phase = this.GetType().Name; using (new LoggerPhaseScope(phase, false)) using (new PerformanceScope(phase, LogLevel.Verbose)) { return PreHandle(manifest); } } } }
mit
C#