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
f3c8c8a66865797bca1b5d18c7a5aa67be2d357f
Remove coded North Glenden Prison position adjustments (#2311)
LtRipley36706/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE,ACEmulator/ACE
Source/ACE.Server/Physics/Util/AdjustPos.cs
Source/ACE.Server/Physics/Util/AdjustPos.cs
using System.Collections.Generic; using System.Numerics; using ACE.Entity; namespace ACE.Server.Physics.Util { /// <summary> /// Some dungeons require position adjustments, as well as cell adjustments /// </summary> public class AdjustPos { public static Dictionary<uint, AdjustPosProfile> DungeonProfiles; static AdjustPos() { DungeonProfiles = new Dictionary<uint, AdjustPosProfile>(); // Burial Temple var burialTemple = new AdjustPosProfile(); burialTemple.BadPosition = new Vector3(30.389999f, -37.439999f, 0.000000f); burialTemple.BadRotation = new Quaternion(-0f, 0, 0, -1f); burialTemple.GoodPosition = new Vector3(30f, -146.30799865723f, 0.0049999998882413f); burialTemple.GoodRotation = new Quaternion(1, 0, 0, 0); DungeonProfiles.Add(0x13e, burialTemple); // Nuhmudira's Dungeon var nuhmudirasDungeon = new AdjustPosProfile(); nuhmudirasDungeon.BadPosition = new Vector3(149.242996f, -49.946301f, -5.995000f); nuhmudirasDungeon.BadRotation = new Quaternion(-0.707107f, 0, 0, -0.707107f); nuhmudirasDungeon.GoodPosition = new Vector3(149.24299621582f, -129.94599914551f, -5.9949998855591f); nuhmudirasDungeon.GoodRotation = new Quaternion(0.6967059969902f, 0, 0, 0.71735697984695f); DungeonProfiles.Add(0x536d, nuhmudirasDungeon); } public static bool Adjust(uint dungeonID, Position pos) { if (!DungeonProfiles.TryGetValue(dungeonID, out var profile)) return false; pos.Pos += profile.GoodPosition - profile.BadPosition; //pos.Rotation *= profile.GoodRotation * Quaternion.Inverse(profile.BadRotation); return true; } } }
using System.Collections.Generic; using System.Numerics; using ACE.Entity; namespace ACE.Server.Physics.Util { /// <summary> /// Some dungeons require position adjustments, as well as cell adjustments /// </summary> public class AdjustPos { public static Dictionary<uint, AdjustPosProfile> DungeonProfiles; static AdjustPos() { DungeonProfiles = new Dictionary<uint, AdjustPosProfile>(); // Burial Temple var burialTemple = new AdjustPosProfile(); burialTemple.BadPosition = new Vector3(30.389999f, -37.439999f, 0.000000f); burialTemple.BadRotation = new Quaternion(-0f, 0, 0, -1f); burialTemple.GoodPosition = new Vector3(30f, -146.30799865723f, 0.0049999998882413f); burialTemple.GoodRotation = new Quaternion(1, 0, 0, 0); DungeonProfiles.Add(0x13e, burialTemple); // North Glenden Prison var glendenPrison = new AdjustPosProfile(); glendenPrison.BadPosition = new Vector3(38.400002f, -18.600000f, 6.000000f); glendenPrison.BadRotation = new Quaternion(-0.782608f, 0, 0, -0.622514f); glendenPrison.GoodPosition = new Vector3(61, -20, -17.995000839233f); glendenPrison.GoodRotation = new Quaternion(-0.70710700750351f, 0, 0, -0.70710700750351f); DungeonProfiles.Add(0x1e4, glendenPrison); // Nuhmudira's Dungeon var nuhmudirasDungeon = new AdjustPosProfile(); nuhmudirasDungeon.BadPosition = new Vector3(149.242996f, -49.946301f, -5.995000f); nuhmudirasDungeon.BadRotation = new Quaternion(-0.707107f, 0, 0, -0.707107f); nuhmudirasDungeon.GoodPosition = new Vector3(149.24299621582f, -129.94599914551f, -5.9949998855591f); nuhmudirasDungeon.GoodRotation = new Quaternion(0.6967059969902f, 0, 0, 0.71735697984695f); DungeonProfiles.Add(0x536d, nuhmudirasDungeon); } public static bool Adjust(uint dungeonID, Position pos) { if (!DungeonProfiles.TryGetValue(dungeonID, out var profile)) return false; pos.Pos += profile.GoodPosition - profile.BadPosition; //pos.Rotation *= profile.GoodRotation * Quaternion.Inverse(profile.BadRotation); return true; } } }
agpl-3.0
C#
7a770fa12f8f5678266b87e9acd1a930555cf840
Teste nao assincrono
Rafael-Miceli/PriceStoresBack,Rafael-Miceli/PriceStoresBack
tests/Integration/NewProductQueueTests.cs
tests/Integration/NewProductQueueTests.cs
using Api.ApplicationServices; using Api.Data; using Api.Controllers; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; using System.Threading.Tasks; using System; using Api.ViewModels; using RabbitMQ.Client; using System.Text; namespace tests.Integration { [TestClass] public class NewProductQueueTests { private string productQueueConnection = "tcp://localhost:25672"; [TestMethod] public void Smoke_Connection_To_Queue() { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); string message = "Hello World!"; var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body); Console.WriteLine(" [x] Sent {0}", message); } } } } }
using Api.ApplicationServices; using Api.Data; using Api.Controllers; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; using System.Threading.Tasks; using System; using Api.ViewModels; using RabbitMQ.Client; using System.Text; namespace tests.Integration { [TestClass] public class NewProductQueueTests { private string productQueueConnection = "tcp://localhost:25672"; [TestMethod] public async Task Smoke_Connection_To_Queue() { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); string message = "Hello World!"; var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body); Console.WriteLine(" [x] Sent {0}", message); } } } } }
apache-2.0
C#
237c98318d1f89e3b1d3a8af9e422883edb27889
Add XML comments to IPropertySettings
atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata
src/Atata/IPropertySettings.cs
src/Atata/IPropertySettings.cs
namespace Atata { /// <summary> /// Defines functionality that provides the properties bag. /// </summary> public interface IPropertySettings { /// <summary> /// Gets the properties bag. /// </summary> PropertyBag Properties { get; } } }
namespace Atata { public interface IPropertySettings { PropertyBag Properties { get; } } }
apache-2.0
C#
662f8b6c06e943988dacd31ec448008c61677df5
change label type on sensor
LagoVista/DeviceAdmin
src/LagoVista.IoT.DeviceAdmin/Models/Sensor.cs
src/LagoVista.IoT.DeviceAdmin/Models/Sensor.cs
using LagoVista.Core.Attributes; using LagoVista.Core.Validation; using LagoVista.IoT.DeviceAdmin.Resources; using System; using System.Collections.ObjectModel; namespace LagoVista.IoT.DeviceAdmin.Models { [EntityDescription(DeviceAdminDomain.DeviceAdmin, DeviceLibraryResources.Names.Sensor_Title, DeviceLibraryResources.Names.Sensor_Description, DeviceLibraryResources.Names.Sensor_Help, EntityDescriptionAttribute.EntityTypes.SimpleModel, typeof(DeviceLibraryResources))] public class Sensor : KeyOwnedDeviceAdminBase, IValidateable { public Sensor() { States = new ObservableCollection<State>(); Units = new ObservableCollection<UnitSet>(); } public enum SensorTypes { [EnumLabel("state", DeviceLibraryResources.Names.Sensor_Type_State, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.Sensor_Type_State_Help)] States, [EnumLabel("discrete", DeviceLibraryResources.Names.Sensor_Type_Discrete, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.Sensor_Type_Discrete_Help)] Discrete, [EnumLabel("discrete-units", DeviceLibraryResources.Names.Sensor_Type_Discrete_Units, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.Sensor_Type_Discrete_Units_Help)] DiscreteUnits } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Sensor_Type, EnumType:typeof(SensorTypes), HelpResource: Resources.DeviceLibraryResources.Names.Sensor_Type_Help, FieldType:FieldTypes.Picker, ResourceType: typeof(DeviceLibraryResources), IsRequired: true)] public SensorTypes SensorType { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Sensor_SetScript, HelpResource: Resources.DeviceLibraryResources.Names.Sensor_SetScript_Help, FieldType: FieldTypes.MultiLineText, ResourceType: typeof(DeviceLibraryResources), IsRequired: true, IsUserEditable: true)] public String Script { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Sensor_Units, HelpResource: Resources.DeviceLibraryResources.Names.Sensor_Units_Help, ResourceType: typeof(DeviceLibraryResources))] public ObservableCollection<UnitSet> Units { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Sensor_States, HelpResource: Resources.DeviceLibraryResources.Names.Sensor_States_Help, ResourceType: typeof(DeviceLibraryResources))] public ObservableCollection<State> States { get; set; } public Point DiagramLocation { get; set; } } }
using LagoVista.Core.Attributes; using LagoVista.Core.Validation; using LagoVista.IoT.DeviceAdmin.Resources; using System; using System.Collections.ObjectModel; namespace LagoVista.IoT.DeviceAdmin.Models { [EntityDescription(DeviceAdminDomain.DeviceAdmin, DeviceLibraryResources.Names.Attribute_Title, DeviceLibraryResources.Names.Attribute_Description, DeviceLibraryResources.Names.Attribute_Help, EntityDescriptionAttribute.EntityTypes.SimpleModel, typeof(DeviceLibraryResources))] public class Sensor : KeyOwnedDeviceAdminBase, IValidateable { public Sensor() { States = new ObservableCollection<State>(); Units = new ObservableCollection<UnitSet>(); } public enum SensorTypes { [EnumLabel("state", DeviceLibraryResources.Names.Sensor_Type_State, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.Sensor_Type_State_Help)] States, [EnumLabel("discrete", DeviceLibraryResources.Names.Sensor_Type_Discrete, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.Sensor_Type_Discrete_Help)] Discrete, [EnumLabel("discrete-units", DeviceLibraryResources.Names.Sensor_Type_Discrete_Units, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.Sensor_Type_Discrete_Units_Help)] DiscreteUnits } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Sensor_Type, EnumType:typeof(SensorTypes), HelpResource: Resources.DeviceLibraryResources.Names.Sensor_Type_Help, FieldType:FieldTypes.Picker, ResourceType: typeof(DeviceLibraryResources), IsRequired: true)] public SensorTypes SensorType { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Sensor_SetScript, HelpResource: Resources.DeviceLibraryResources.Names.Sensor_SetScript_Help, FieldType: FieldTypes.MultiLineText, ResourceType: typeof(DeviceLibraryResources), IsRequired: true, IsUserEditable: true)] public String Script { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Sensor_Units, HelpResource: Resources.DeviceLibraryResources.Names.Sensor_Units_Help, ResourceType: typeof(DeviceLibraryResources))] public ObservableCollection<UnitSet> Units { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Sensor_States, HelpResource: Resources.DeviceLibraryResources.Names.Sensor_States_Help, ResourceType: typeof(DeviceLibraryResources))] public ObservableCollection<State> States { get; set; } public Point DiagramLocation { get; set; } } }
mit
C#
19616c1bc97537247b32318b2d31794fdd6328cf
Remove deprecated extension method
khellang/Middleware,khellang/Middleware
src/ProblemDetails/ProblemDetailsExtensions.cs
src/ProblemDetails/ProblemDetailsExtensions.cs
using System; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; namespace Hellang.Middleware.ProblemDetails { public static class ProblemDetailsExtensions { public static IServiceCollection AddProblemDetails(this IServiceCollection services) { return services.AddProblemDetails(configure: null); } public static IServiceCollection AddProblemDetails(this IServiceCollection services, Action<ProblemDetailsOptions> configure) { if (configure != null) { services.Configure(configure); } services.TryAddSingleton<ProblemDetailsMarkerService, ProblemDetailsMarkerService>(); services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<ProblemDetailsOptions>, ProblemDetailsOptionsSetup>()); return services; } public static IApplicationBuilder UseProblemDetails(this IApplicationBuilder app) { var markerService = app.ApplicationServices.GetService<ProblemDetailsMarkerService>(); if (markerService is null) { throw new InvalidOperationException( $"Please call {nameof(IServiceCollection)}.{nameof(AddProblemDetails)} in ConfigureServices before adding the middleware."); } return app.UseMiddleware<ProblemDetailsMiddleware>(); } /// <summary> /// A marker class used to determine if the required services were added /// to the <see cref="IServiceCollection"/> before the middleware is configured. /// </summary> private class ProblemDetailsMarkerService { } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; namespace Hellang.Middleware.ProblemDetails { public static class ProblemDetailsExtensions { public static IServiceCollection AddProblemDetails(this IServiceCollection services) { return services.AddProblemDetails(configure: null); } public static IServiceCollection AddProblemDetails(this IServiceCollection services, Action<ProblemDetailsOptions> configure) { if (configure != null) { services.Configure(configure); } services.TryAddSingleton<ProblemDetailsMarkerService, ProblemDetailsMarkerService>(); services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<ProblemDetailsOptions>, ProblemDetailsOptionsSetup>()); return services; } public static IApplicationBuilder UseProblemDetails(this IApplicationBuilder app) { var markerService = app.ApplicationServices.GetService<ProblemDetailsMarkerService>(); if (markerService is null) { throw new InvalidOperationException( $"Please call {nameof(IServiceCollection)}.{nameof(AddProblemDetails)} in ConfigureServices before adding the middleware."); } return app.UseMiddleware<ProblemDetailsMiddleware>(); } [Obsolete("This overload is deprecated. Please call " + nameof(IServiceCollection) + "." + nameof(AddProblemDetails) + " and use the parameterless overload instead.")] public static IApplicationBuilder UseProblemDetails(this IApplicationBuilder app, Action<ProblemDetailsOptions> configure) { var options = new ProblemDetailsOptions(); configure?.Invoke(options); // Try to pull the IConfigureOptions<ProblemDetailsOptions> service from the container // in case the user has called AddProblemDetails and still use this overload. // If the setup hasn't been configured. Create an instance explicitly and use that. var setup = app.ApplicationServices.GetService<IConfigureOptions<ProblemDetailsOptions>>() ?? new ProblemDetailsOptionsSetup(); setup.Configure(options); return app.UseMiddleware<ProblemDetailsMiddleware>(Options.Create(options)); } /// <summary> /// A marker class used to determine if the required services were added /// to the <see cref="IServiceCollection"/> before the middleware is configured. /// </summary> private class ProblemDetailsMarkerService { } } }
mit
C#
fd518c33cf58d84c799f3c852fa17d93f1489b08
Improve AppSettings slightly
canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor
src/SyncTrayzor/Services/Config/AppSettings.cs
src/SyncTrayzor/Services/Config/AppSettings.cs
using System.Configuration; using System.IO; using System.Xml; using System.Xml.Serialization; namespace SyncTrayzor.Services.Config { public class XmlConfigurationSection : ConfigurationSection { private XmlReader reader; protected override void DeserializeSection(XmlReader reader) { this.reader = reader; } protected override object GetRuntimeObject() { return this.reader; } } public class AppSettings { private const string sectionName = "settings"; private static readonly XmlSerializer serializer = new XmlSerializer(typeof(AppSettings), new XmlRootAttribute(sectionName)); public static readonly AppSettings Instance; static AppSettings() { var reader = (XmlReader)ConfigurationManager.GetSection(sectionName); Instance = (AppSettings)serializer.Deserialize(reader); } public string UpdateApiUrl { get; set; } = "http://synctrayzor.antonymale.co.uk/version-check"; public string HomepageUrl { get; set; } = "http://github.com/canton7/SyncTrayzor"; public int DirectoryWatcherBackoffMilliseconds { get; set; } = 2000; public int DirectoryWatcherFolderExistenceCheckMilliseconds { get; set; } = 3000; public string IssuesUrl { get; set; } = "http://github.com/canton7/SyncTrayzor/issues"; public bool EnableAutostartOnFirstStart { get; set; } = false; public int CefRemoteDebuggingPort { get; set; } = 0; public SyncTrayzorVariant Variant { get; set; } = SyncTrayzorVariant.Portable; public int UpdateCheckIntervalSeconds { get; set; } = 43200; public int SyncthingConnectTimeoutSeconds { get; set; } = 600; public bool EnforceSingleProcessPerUser { get; set; } = true; public PathConfiguration PathConfiguration { get; set; } = new PathConfiguration(); public Configuration DefaultUserConfiguration { get; set; } = new Configuration(); public override string ToString() { using (var writer = new StringWriter()) { serializer.Serialize(writer, this); return writer.ToString(); } } } }
using System.Configuration; using System.IO; using System.Xml; using System.Xml.Serialization; namespace SyncTrayzor.Services.Config { public class XmlConfigurationSection : ConfigurationSection { private XmlReader reader; protected override void DeserializeSection(XmlReader reader) { this.reader = reader; } protected override object GetRuntimeObject() { return this.reader; } } public class AppSettings { private const string sectionName = "settings"; public static readonly AppSettings Instance; static AppSettings() { var reader = (XmlReader)ConfigurationManager.GetSection(sectionName); var serializer = new XmlSerializer(typeof(AppSettings), new XmlRootAttribute(sectionName)); Instance = (AppSettings)serializer.Deserialize(reader); } public string UpdateApiUrl { get; set; } = "http://synctrayzor.antonymale.co.uk/version-check"; public string HomepageUrl { get; set; } = "http://github.com/canton7/SyncTrayzor"; public int DirectoryWatcherBackoffMilliseconds { get; set; } = 2000; public int DirectoryWatcherFolderExistenceCheckMilliseconds { get; set; } = 3000; public string IssuesUrl { get; set; } = "http://github.com/canton7/SyncTrayzor/issues"; public bool EnableAutostartOnFirstStart { get; set; } = false; public int CefRemoteDebuggingPort { get; set; } = 0; public SyncTrayzorVariant Variant { get; set; } = SyncTrayzorVariant.Portable; public int UpdateCheckIntervalSeconds { get; set; } = 43200; public int SyncthingConnectTimeoutSeconds { get; set; } = 600; public bool EnforceSingleProcessPerUser { get; set; } = true; public PathConfiguration PathConfiguration { get; set; } = new PathConfiguration(); public Configuration DefaultUserConfiguration { get; set; } = new Configuration(); public override string ToString() { var serializer = new XmlSerializer(typeof(AppSettings)); using (var writer = new StringWriter()) { serializer.Serialize(writer, this); return writer.ToString(); } } } }
mit
C#
8dc5be38e2f27ba786d09ad35245e26836d2f560
add comment
TryStatsN/StatsN
src/StatsN/TplExtensions.cs
src/StatsN/TplExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace StatsN { /// <summary> /// Class that provides Task.FromResult functions for dotnet 4+ /// </summary> public static class TplFactory { public static Task<Result> FromResult<Result>(Result result) { #if net40 var taskSource = new TaskCompletionSource<Result>(); taskSource.SetResult(result); return taskSource.Task; #else return Task.FromResult<Result>(result); #endif } public static Task FromResult() { #if net40 //gross but .net 4 return System.Threading.Tasks.Task.Factory.StartNew(() => { }); #else return Task.FromResult(0); #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace StatsN { public static class TplFactory { public static Task<Result> FromResult<Result>(Result result) { #if net40 var taskSource = new TaskCompletionSource<Result>(); taskSource.SetResult(result); return taskSource.Task; #else return Task.FromResult<Result>(result); #endif } public static Task FromResult() { #if net40 //gross but .net 4 return System.Threading.Tasks.Task.Factory.StartNew(() => { }); #else return Task.FromResult(0); #endif } } }
mit
C#
c28dc6c615c0e4ddceccbe4b18fe701b4ca6065a
hide version in heaer
irresolution/vivianClothing,irresolution/vivianClothing
vivianClothing/vivianClothing/Global.asax.cs
vivianClothing/vivianClothing/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace vivianClothing { // 注意: 如需啟用 IIS6 或 IIS7 傳統模式的說明, // 請造訪 http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { MvcHandler.DisableMvcResponseHeader = true; //hide version in heaer System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<vivianClothing.Models.VivianclothingContext>()); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace vivianClothing { // 注意: 如需啟用 IIS6 或 IIS7 傳統模式的說明, // 請造訪 http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<vivianClothing.Models.VivianclothingContext>()); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }
mit
C#
70093de50cfd8dd369f1f9d392bff1da47fc5d0b
Fix typo.
Mikuz/Battlezeppelins,Mikuz/Battlezeppelins
Battlezeppelins/Controllers/PollController.cs
Battlezeppelins/Controllers/PollController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public class PollController : Controller { public ActionResult UpdateLastSeen() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int? id = Int32.Parse(idStr); Player player = new Player(id); player.StatusUpdate(); return Json(true, JsonRequestBehavior.AllowGet); } return Json(false, JsonRequestBehavior.AllowGet); } public ActionResult ChallengeInbox() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int? id = Int32.Parse(idStr); Player player = new Player(id); Player challenger = Challenge.RetrieveChallenge(player); if (challenger != null) { string message = challenger.name + " wants to challenge you"; return Json(message, JsonRequestBehavior.AllowGet); } } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public class PollController : Controller { public ActionResult UpdateLastSeen() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int? id = Int32.Parse(idStr); Player player = new Player(id); player.StatusUpdate(); return Json(true, JsonRequestBehavior.AllowGet); } return Json(false, JsonRequestBehavior.AllowGet); } public ActionResult ChallengeInbox() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int? id = Int32.Parse(idStr); Player player = new Player(id); Player challenger = Challenge.RetrieveChallenge(player); if (challenger != null) { string message = challenger.name + "wants to challenge you"; return Json(message, JsonRequestBehavior.AllowGet); } } return null; } } }
apache-2.0
C#
52f3e9968e9d8726eb74c54726141f00966ff514
Update version to 1.0.1
gabornemeth/restsharp.portable
RestSharp.Portable/Properties/AssemblyInfo.cs
RestSharp.Portable/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über folgende // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("RestSharp.Portable")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RestSharp.Portable")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("de")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // durch Einsatz von '*', wie in nachfolgendem Beispiel: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.1.0")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über folgende // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("RestSharp.Portable")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RestSharp.Portable")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("de")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // durch Einsatz von '*', wie in nachfolgendem Beispiel: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bsd-2-clause
C#
4b7114590f9451832ffa0e652190cc7f13befeb3
Generalize verification
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Crypto/ZeroKnowledge/Verifier.cs
WalletWasabi/Crypto/ZeroKnowledge/Verifier.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge { public static class Verifier { public static bool Verify(KnowledgeOfRepresentation proof, GroupElement publicPoint, IEnumerable<GroupElement> generators) { Guard.False($"{nameof(publicPoint)}.{nameof(publicPoint.IsInfinity)}", publicPoint.IsInfinity); if (publicPoint == proof.Nonce) { throw new InvalidOperationException($"{nameof(publicPoint)} and {nameof(proof.Nonce)} should not be equal."); } foreach (var generator in generators) { Guard.False($"{nameof(generator)}.{nameof(generator.IsInfinity)}", generator.IsInfinity); } var nonce = proof.Nonce; var responses = proof.Responses; var challenge = Challenge.Build(publicPoint, nonce, generators); var a = challenge * publicPoint + nonce; var b = GroupElement.Infinity; foreach (var (response, generator) in responses.TupleWith(generators)) { b += response * generator; } return a == b; } public static bool Verify(KnowledgeOfDiscreteLog proof, GroupElement publicPoint, GroupElement generator) => Verify(proof, publicPoint, generator); public static bool Verify(KnowledgeOfRepresentation proof, GroupElement publicPoint, params GroupElement[] generators) => Verify(proof, publicPoint, generators as IEnumerable<GroupElement>); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge { public static class Verifier { public static bool Verify(KnowledgeOfDiscreteLog proof, GroupElement publicPoint, GroupElement generator) { Guard.False($"{nameof(generator)}.{nameof(generator.IsInfinity)}", generator.IsInfinity); Guard.False($"{nameof(publicPoint)}.{nameof(publicPoint.IsInfinity)}", publicPoint.IsInfinity); if (publicPoint == proof.Nonce) { throw new InvalidOperationException($"{nameof(publicPoint)} and {nameof(proof.Nonce)} should not be equal."); } return Verify(proof, publicPoint, new[] { generator }); } public static bool Verify(KnowledgeOfRepresentation proof, GroupElement publicPoint, IEnumerable<GroupElement> generators) { foreach (var generator in generators) { Guard.False($"{nameof(generator)}.{nameof(generator.IsInfinity)}", generator.IsInfinity); } var nonce = proof.Nonce; var responses = proof.Responses; var challenge = Challenge.Build(publicPoint, nonce, generators); var a = challenge * publicPoint + nonce; var b = GroupElement.Infinity; foreach (var (response, generator) in responses.TupleWith(generators)) { b += response * generator; } return a == b; } } }
mit
C#
16f8089acbb802bb65d7077daaede7ea20cc6ba5
Remove unused code from quick-start guide example project.
Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net
LearnosityDemo/Pages/ItemsAPIDemo.cshtml.cs
LearnosityDemo/Pages/ItemsAPIDemo.cshtml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using LearnositySDK.Request; using LearnositySDK.Utils; // static LearnositySDK.Credentials; namespace LearnosityDemo.Pages { public class ItemsAPIDemoModel : PageModel { public void OnGet() { // prepare all the params string service = "items"; JsonObject security = new JsonObject(); security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey); security.set("domain", LearnositySDK.Credentials.Domain); security.set("user_id", Uuid.generate()); string secret = LearnositySDK.Credentials.ConsumerSecret; //JsonObject config = new JsonObject(); JsonObject request = new JsonObject(); request.set("user_id", Uuid.generate()); request.set("activity_template_id", "quickstart_examples_activity_template_001"); request.set("session_id", Uuid.generate()); request.set("activity_id", "quickstart_examples_activity_001"); request.set("rendering_type", "assess"); request.set("type", "submit_practice"); request.set("name", "Items API Quickstart"); //request.set("config", config); // Instantiate Init class Init init = new Init(service, security, secret, request); // Call the generate() method to retrieve a JavaScript object ViewData["InitJSON"] = init.generate(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using LearnositySDK.Request; using LearnositySDK.Utils; // static LearnositySDK.Credentials; namespace LearnosityDemo.Pages { public class ItemsAPIDemoModel : PageModel { public void OnGet() { // prepare all the params string service = "items"; JsonObject security = new JsonObject(); security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey); security.set("domain", LearnositySDK.Credentials.Domain); security.set("user_id", Uuid.generate()); string secret = LearnositySDK.Credentials.ConsumerSecret; JsonObject config = new JsonObject(); JsonObject request = new JsonObject(); request.set("user_id", Uuid.generate()); request.set("activity_template_id", "quickstart_examples_activity_template_001"); request.set("session_id", Uuid.generate()); request.set("activity_id", "quickstart_examples_activity_001"); request.set("rendering_type", "assess"); request.set("type", "submit_practice"); request.set("name", "Items API Quickstart"); request.set("config", config); // Instantiate Init class Init init = new Init(service, security, secret, request); // Call the generate() method to retrieve a JavaScript object ViewData["InitJSON"] = init.generate(); } } }
apache-2.0
C#
eaa0d656ef7aac779ea380ea1a4f073a9fd7e47f
Fix compile break
mcosand/KCSARA-Database,mcosand/KCSARA-Database,mcosand/KCSARA-Database
tests/Website.UnitTests/AlwaysYesAuth.cs
tests/Website.UnitTests/AlwaysYesAuth.cs
/* * Copyright 2013-2014 Matthew Cosand */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using Kcsara.Database.Services; namespace Internal.Website { public class AlwaysYesAuth : IAuthService { public Guid UserId { get { throw new NotImplementedException(); } } public bool IsSelf(Guid id) { return true; } public bool IsAdmin { get { return true; } } public bool IsAuthenticated { get { return true; } } public bool IsUser { get { return true; } } public string Username { get { throw new NotImplementedException(); } } public bool IsInRole(params string[] group) { return true; } public bool IsMembershipForPerson(Guid id) { return true; } public bool IsMembershipForUnit(Guid id) { return true; } public bool IsUserOrLocal(HttpRequestBase request) { return true; } public bool IsRoleForPerson(string role, Guid personId) { return true; } public bool IsRoleForUnit(string role, Guid unitId) { return true; } public bool IsSelf(string username) { return true; } public IEnumerable<string> GetGroupsForUser(string username) { return new string[0]; } public IEnumerable<string> GetGroupsForGroup(string group) { return new string[0]; } public bool ValidateUser(string username, string password) { return true; } public IEnumerable<string> GetGroupsIManage() { return new string[0]; } } }
/* * Copyright 2013-2014 Matthew Cosand */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using Kcsara.Database.Services; namespace Internal.Website { public class AlwaysYesAuth : IAuthService { public Guid UserId { get { throw new NotImplementedException(); } } public bool IsSelf(Guid id) { return true; } public bool IsAdmin { get { return true; } } public bool IsAuthenticated { get { return true; } } public bool IsUser { get { return true; } } public bool IsInRole(params string[] group) { return true; } public bool IsMembershipForPerson(Guid id) { return true; } public bool IsMembershipForUnit(Guid id) { return true; } public bool IsUserOrLocal(HttpRequestBase request) { return true; } public bool IsRoleForPerson(string role, Guid personId) { return true; } public bool IsRoleForUnit(string role, Guid unitId) { return true; } public bool IsSelf(string username) { return true; } public IEnumerable<string> GetGroupsForUser(string username) { return new string[0]; } public IEnumerable<string> GetGroupsForGroup(string group) { return new string[0]; } public bool ValidateUser(string username, string password) { return true; } } }
agpl-3.0
C#
e12e32ec946cb84c24278b591063e8265f2ed287
Fix memory patterns saving when not playing.
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
osu!StreamCompanion/Code/Modules/MapDataGetters/FileMap/FileMapDataGetter.cs
osu!StreamCompanion/Code/Modules/MapDataGetters/FileMap/FileMapDataGetter.cs
using osu_StreamCompanion.Code.Core.DataTypes; using osu_StreamCompanion.Code.Interfaces; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.FileMap { public class FileMapDataGetter : IModule, IMapDataGetter { public bool Started { get; set; } private readonly FileMapManager _fileMapManager = new FileMapManager(); public void Start(ILogger logger) { Started = true; } public void SetNewMap(MapSearchResult map) { foreach (var s in map.FormatedStrings) { if(s.IsMemoryFormat) continue;//memory pattern saving is handled elsewhere, not in this codebase. var name = s.Name; if ((s.SaveEvent & map.Action) != 0) _fileMapManager.Write("SC-" + name, s.GetFormatedPattern()); else _fileMapManager.Write("SC-" + name, " ");//spaces so object rect displays on obs preview window. } } } }
using osu_StreamCompanion.Code.Core.DataTypes; using osu_StreamCompanion.Code.Interfaces; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.FileMap { public class FileMapDataGetter : IModule, IMapDataGetter { public bool Started { get; set; } private readonly FileMapManager _fileMapManager = new FileMapManager(); public void Start(ILogger logger) { Started = true; } public void SetNewMap(MapSearchResult map) { foreach (var s in map.FormatedStrings) { var name = s.Name; if ((s.SaveEvent & map.Action) != 0) _fileMapManager.Write("SC-" + name, s.GetFormatedPattern()); else _fileMapManager.Write("SC-" + name, " ");//spaces so object rect displays on obs preview window. } } } }
mit
C#
880f6d495e058b864f5d617ff2fd952453d5b7af
Fix previous merge error
signumsoftware/framework,avifatal/framework,avifatal/framework,AlejandroCano/framework,AlejandroCano/framework,signumsoftware/framework
Signum.Web/TypeContext/TypeContextHelper.cs
Signum.Web/TypeContext/TypeContextHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using Signum.Utilities.Reflection; using Signum.Entities; using Signum.Utilities.ExpressionTrees; using Signum.Utilities; using System.Web.Mvc; using System.Web.Mvc.Html; namespace Signum.Web { public static class TypeContextHelper { public static TypeContext<T> TypeContext<T>(this HtmlHelper helper) where T : class { TypeContext<T> tc = helper.ViewData.Model as TypeContext<T>; if (tc != null) return tc; T element = helper.ViewData.Model as T; if (element != null) return new TypeContext<T>(element, null); TypeContext stc = helper.ViewData.Model as TypeContext; if (stc != null) { if (!typeof(T).IsAssignableFrom(stc.Type)) throw new InvalidOperationException("{0} is not convertible to {1}".FormatWith(stc.GetType().TypeName(), typeof(TypeContext<T>).TypeName())); return new TypeContext<T>((T)stc.UntypedValue, stc, "", stc.PropertyRoute); } throw new InvalidCastException("Impossible to convert object {0} of type {1} to {2}".FormatWith( helper.ViewData.Model, helper.ViewData.Model.GetType().TypeName(), typeof(TypeContext<T>).TypeName())); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using Signum.Utilities.Reflection; using Signum.Entities; using Signum.Utilities.ExpressionTrees; using Signum.Utilities; using System.Web.Mvc; using System.Web.Mvc.Html; namespace Signum.Web { public static class TypeContextHelper { public static TypeContext<T> TypeContext<T>(this HtmlHelper helper) where T : class { TypeContext<T> tc = helper.ViewData.Model as TypeContext<T>; if (tc != null) return tc; T element = helper.ViewData.Model as T; if (element != null) return new TypeContext<T>(element, null); TypeContext stc = helper.ViewData.Model as TypeContext; if (stc != null) { if (!typeof(T).IsAssignableFrom(stc.Type)) throw new InvalidOperationException("{0} is not convertible to {1}".FormatWith(stc.GetType().TypeName(), typeof(TypeContext<T>).TypeName())); return new TypeContext<T>((T)stc.UntypedValue, stc, "", stc.PropertyRoute); } throw new InvalidCastException("Impossible to convert object '{0}' of type '{1}' to '{2}'".FormatWith( helper.ViewData.Model.TryToString() ?? "null", helper.ViewData.Model == null ? "object" : helper.ViewData.Model.GetType().TypeName(), typeof(TypeContext<T>).TypeName())); } } }
mit
C#
bb3b226389f1d82bed5cb65b18da2f8f5f8cd9c4
Add more InterpolatingFunctions.
Damnae/storybrew
common/Animations/InterpolatingFunctions.cs
common/Animations/InterpolatingFunctions.cs
using OpenTK; using StorybrewCommon.Storyboarding.CommandValues; using System; namespace StorybrewCommon.Animations { public static class InterpolatingFunctions { public static Func<float, float, double, float> Float = (from, to, progress) => from + (to - from) * (float)progress; public static Func<float, float, double, float> FloatAngle = (from, to, progress) => from + (float)(getShortestAngleDelta(from, to) * progress); public static Func<double, double, double, double> Double = (from, to, progress) => from + (to - from) * progress; public static Func<double, double, double, double> DoubleAngle = (from, to, progress) => from + getShortestAngleDelta(from, to) * progress; public static Func<Vector2, Vector2, double, Vector2> Vector2 = (from, to, progress) => from + (to - from) * (float)progress; public static Func<Vector3, Vector3, double, Vector3> Vector3 = (from, to, progress) => from + (to - from) * (float)progress; public static Func<Quaternion, Quaternion, double, Quaternion> QuaternionSlerp = (from, to, progress) => OpenTK.Quaternion.Slerp(from, to, (float)progress); public static Func<CommandColor, CommandColor, double, CommandColor> CommandColor = (from, to, progress) => from + (to - from) * (float)progress; private static double getShortestAngleDelta(double from, double to) { var rotationDelta = to - from; return rotationDelta - (Math.Floor((rotationDelta + MathHelper.Pi) / MathHelper.TwoPi) * MathHelper.TwoPi); } } }
using OpenTK; using StorybrewCommon.Storyboarding.CommandValues; using System; namespace StorybrewCommon.Animations { public static class InterpolatingFunctions { public static Func<float, float, double, float> Float = (from, to, progress) => from + (to - from) * (float)progress; public static Func<Vector3, Vector3, double, Vector3> Vector3 = (from, to, progress) => from + (to - from) * (float)progress; public static Func<Quaternion, Quaternion, double, Quaternion> QuaternionSlerp = (from, to, progress) => Quaternion.Slerp(from, to, (float)progress); public static Func<CommandColor, CommandColor, double, CommandColor> CommandColor = (from, to, progress) => from + (to - from) * (float)progress; } }
mit
C#
1f30e7b8bdfa67be0b3f69e2bc36db0630f9a01e
Update MandateStatus.cs
Viincenttt/MollieApi,Viincenttt/MollieApi
Mollie.Api/Models/Mandate/MandateStatus.cs
Mollie.Api/Models/Mandate/MandateStatus.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Mollie.Api.Models.Mandate { public enum MandateStatus { [EnumMember(Value = "valid")] Valid, [EnumMember(Value = "invalid")] Invalid, [EnumMember(Value = "pending")] Pending } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Mollie.Api.Models.Mandate { public enum MandateStatus { [EnumMember(Value = "valid")] Valid, [EnumMember(Value = "invalid")] Invalid } }
mit
C#
2a8e2df54fd04ab8872b9064af67a3dc8467daab
Add deprecated to UI
RSuter/NSwag,RSuter/NSwag,RSuter/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,RSuter/NSwag,quails4Eva/NSwag,RSuter/NSwag
src/NSwagStudio/Views/SwaggerGenerators/WebApiToSwaggerGeneratorView.xaml.cs
src/NSwagStudio/Views/SwaggerGenerators/WebApiToSwaggerGeneratorView.xaml.cs
using System.Linq; using System.Threading.Tasks; using System.Windows.Controls; using MyToolkit.Mvvm; using NSwag.Commands; using NSwag.Commands.Generation.WebApi; using NSwagStudio.ViewModels.SwaggerGenerators; namespace NSwagStudio.Views.SwaggerGenerators { public partial class WebApiToSwaggerGeneratorView : ISwaggerGeneratorView { public WebApiToSwaggerGeneratorView(WebApiToSwaggerCommand command, NSwagDocument document) { InitializeComponent(); ViewModelHelper.RegisterViewModel(Model, this); Model.Command = command; Model.Document = document; ControllersList.SelectedItems.Clear(); foreach (var controller in Model.ControllerNames) ControllersList.SelectedItems.Add(controller); } private WebApiToSwaggerGeneratorViewModel Model => (WebApiToSwaggerGeneratorViewModel)Resources["ViewModel"]; public string Title => "Web API via reflection (deprecated)"; public IOutputCommand Command => Model.Command; public Task<string> GenerateSwaggerAsync() { return Model.GenerateSwaggerAsync(); } public override string ToString() { return Title; } private void ControllersListSelectionChanged(object sender, SelectionChangedEventArgs e) { Model.ControllerNames = ((ListBox)sender).SelectedItems.OfType<string>().ToArray(); } } }
using System.Linq; using System.Threading.Tasks; using System.Windows.Controls; using MyToolkit.Mvvm; using NSwag.Commands; using NSwag.Commands.Generation.WebApi; using NSwagStudio.ViewModels.SwaggerGenerators; namespace NSwagStudio.Views.SwaggerGenerators { public partial class WebApiToSwaggerGeneratorView : ISwaggerGeneratorView { public WebApiToSwaggerGeneratorView(WebApiToSwaggerCommand command, NSwagDocument document) { InitializeComponent(); ViewModelHelper.RegisterViewModel(Model, this); Model.Command = command; Model.Document = document; ControllersList.SelectedItems.Clear(); foreach (var controller in Model.ControllerNames) ControllersList.SelectedItems.Add(controller); } private WebApiToSwaggerGeneratorViewModel Model => (WebApiToSwaggerGeneratorViewModel)Resources["ViewModel"]; public string Title => "Web API via reflection"; public IOutputCommand Command => Model.Command; public Task<string> GenerateSwaggerAsync() { return Model.GenerateSwaggerAsync(); } public override string ToString() { return Title; } private void ControllersListSelectionChanged(object sender, SelectionChangedEventArgs e) { Model.ControllerNames = ((ListBox)sender).SelectedItems.OfType<string>().ToArray(); } } }
mit
C#
37b49a4c45843c85c36dfec419825b28342326be
Add using statement for Swashbuckle 4.0
mattfrear/Swashbuckle.AspNetCore.Examples
src/Swashbuckle.AspNetCore.Filters/Extensions/SwaggerGenOptionsExtensions.cs
src/Swashbuckle.AspNetCore.Filters/Extensions/SwaggerGenOptionsExtensions.cs
using Microsoft.Extensions.DependencyInjection; using Swashbuckle.AspNetCore.SwaggerGen; namespace Swashbuckle.AspNetCore.Filters { public static class SwaggerGenOptionsExtensions { public static void ExampleFilters(this SwaggerGenOptions swaggerGenOptions) { swaggerGenOptions.OperationFilter<ExamplesOperationFilter>(); swaggerGenOptions.OperationFilter<ServiceProviderExamplesOperationFilter>(); } } }
using Swashbuckle.AspNetCore.SwaggerGen; namespace Swashbuckle.AspNetCore.Filters { public static class SwaggerGenOptionsExtensions { public static void ExampleFilters(this SwaggerGenOptions swaggerGenOptions) { swaggerGenOptions.OperationFilter<ExamplesOperationFilter>(); swaggerGenOptions.OperationFilter<ServiceProviderExamplesOperationFilter>(); } } }
mit
C#
ab8c03f9600d49028cbed614f220b4ad31355acc
use rel=stylesheet instead of type=text/css to find css links
mwrock/RequestReduce,mwrock/RequestReduce,mwrock/RequestReduce
RequestReduce/ResourceTypes/CssResource.cs
RequestReduce/ResourceTypes/CssResource.cs
using System.Collections.Generic; using System.Text.RegularExpressions; using System; namespace RequestReduce.ResourceTypes { public class CssResource : IResourceType { private const string CssFormat = @"<link href=""{0}"" rel=""Stylesheet"" type=""text/css"" />"; private readonly Regex cssPattern = new Regex(@"<link[^>]+rel=""?stylesheet""?[^>]+>(?![\s]*<!\[endif]-->)", RegexOptions.Compiled | RegexOptions.IgnoreCase); public string FileName { get { return "RequestReducedStyle.css"; } } public IEnumerable<string> SupportedMimeTypes { get { return new[] { "text/css" }; } } public string TransformedMarkupTag(string url) { return string.Format(CssFormat, url); } public Regex ResourceRegex { get { return cssPattern; } } public Func<string, string, bool> TagValidator { get; set; } } }
using System.Collections.Generic; using System.Text.RegularExpressions; using System; namespace RequestReduce.ResourceTypes { public class CssResource : IResourceType { private const string CssFormat = @"<link href=""{0}"" rel=""Stylesheet"" type=""text/css"" />"; private readonly Regex cssPattern = new Regex(@"<link[^>]+type=""?text/css""?[^>]+>(?![\s]*<!\[endif]-->)", RegexOptions.Compiled | RegexOptions.IgnoreCase); public string FileName { get { return "RequestReducedStyle.css"; } } public IEnumerable<string> SupportedMimeTypes { get { return new[] { "text/css" }; } } public string TransformedMarkupTag(string url) { return string.Format(CssFormat, url); } public Regex ResourceRegex { get { return cssPattern; } } public Func<string, string, bool> TagValidator { get; set; } } }
apache-2.0
C#
a6b130e8436ce33ba9a6844ee3da94fe36748c26
Use slug for single search result
sboulema/Hops,sboulema/Hops,sboulema/Hops
src/Hops/Controllers/SearchController.cs
src/Hops/Controllers/SearchController.cs
using Hops.Repositories; using Microsoft.AspNet.Mvc; using System.Collections.Generic; using System.Linq; namespace Hops.Controllers { [Route("[controller]")] public class SearchController : Controller { private ISqliteRepository sqliteRepository; public SearchController(ISqliteRepository sqliteRepository) { this.sqliteRepository = sqliteRepository; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet("{searchTerm}/{page:int?}")] public IActionResult Results(string searchTerm, int page = 1) { var results = sqliteRepository.Search(searchTerm, page); if (results.List.Count == 0) { return View("NoResults", sqliteRepository.GetRandomHop()); } if (results.List.Count == 1) { return Redirect($"/hop/{results.List.First().Hop.Slug()}"); } return View(results); } [HttpGet("inventory/{page:int?}")] public IActionResult Inventory(string searchTerm, int page = 1) { return View(page); } [HttpGet("aroma/{profile:int}/{page:int?}")] public IActionResult Results(int profile, int page = 1) { var results = sqliteRepository.Search(profile, page); return View(results); } [HttpGet("autocomplete/{searchTerm}")] public List<string> AutoComplete(string searchTerm) { return sqliteRepository.Autocomplete(searchTerm); } } }
using Hops.Repositories; using Microsoft.AspNet.Mvc; using System.Collections.Generic; using System.Linq; namespace Hops.Controllers { [Route("[controller]")] public class SearchController : Controller { private ISqliteRepository sqliteRepository; public SearchController(ISqliteRepository sqliteRepository) { this.sqliteRepository = sqliteRepository; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet("{searchTerm}/{page:int?}")] public IActionResult Results(string searchTerm, int page = 1) { var results = sqliteRepository.Search(searchTerm, page); if (results.List.Count == 0) { return View("NoResults", sqliteRepository.GetRandomHop()); } if (results.List.Count == 1) { return Redirect($"/Hop/{results.List.First().Hop.Id}"); } return View(results); } [HttpGet("inventory/{page:int?}")] public IActionResult Inventory(string searchTerm, int page = 1) { return View(page); } [HttpGet("aroma/{profile:int}/{page:int?}")] public IActionResult Results(int profile, int page = 1) { var results = sqliteRepository.Search(profile, page); return View(results); } [HttpGet("autocomplete/{searchTerm}")] public List<string> AutoComplete(string searchTerm) { return sqliteRepository.Autocomplete(searchTerm); } } }
mit
C#
a1639c2490e0bf294ba1ef002ceb39fbb63b4726
Improve FileLogWriterConfig + make it abstract.
logjam2/logjam,logjam2/logjam
src/LogJam/Config/FileLogWriterConfig.cs
src/LogJam/Config/FileLogWriterConfig.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FileLogWriterConfig.cs"> // Copyright (c) 2011-2016 https://github.com/logjam2. // </copyright> // Licensed under the <a href="https://github.com/logjam2/logjam/blob/master/LICENSE.txt">Apache License, Version 2.0</a>; // you may not use this file except in compliance with the License. // -------------------------------------------------------------------------------------------------------------------- namespace LogJam.Config { using System; using LogJam.Trace; using LogJam.Writer; /// <summary> /// Configures a log writer that writes to a file. /// </summary> public abstract class FileLogWriterConfig : LogWriterConfig { private bool? _append; /// <summary> /// The default filename, used if both <see cref="Filename"/> and <see cref="FilenameFunc"/> are not set. /// </summary> public const string DefaultFilename = "LogJam.log"; /// <summary> /// The default directory to create log files in, used if both <see cref="Directory"/> and <see cref="DirectoryFunc"/> are not set. /// </summary> public static readonly string DefaultDirectory = Environment.CurrentDirectory; public string Directory { get; set; } public Func<string> DirectoryFunc { get; set; } public string Filename { get {} set; } public Func<string> FilenameFunc { get; set; } /// <summary> /// Set to <c>true</c> to append to an existing log file; set to <c>false</c> to overwrite an existing log file. /// Default is <c>true</c>. /// </summary> public bool Append { get; set; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FileLogWriterConfig.cs"> // Copyright (c) 2011-2016 https://github.com/logjam2. // </copyright> // Licensed under the <a href="https://github.com/logjam2/logjam/blob/master/LICENSE.txt">Apache License, Version 2.0</a>; // you may not use this file except in compliance with the License. // -------------------------------------------------------------------------------------------------------------------- namespace LogJam.Config { using LogJam.Trace; using LogJam.Writer; /// <summary> /// Configures a log writer that writes to the specified <see cref="File" />. /// </summary> public sealed class FileLogWriterConfig : LogWriterConfig { public string Directory { get; set; } public string File { get; set; } public override ILogWriter CreateLogWriter(ITracerFactory setupTracerFactory) { throw new System.NotImplementedException(); } } }
apache-2.0
C#
e12c9860cbca34ff341d4fb0cb09a949477a1585
Add CLS complaint attribute
cjbhaines/MemBroker
src/MemBroker/Properties/AssemblyInfo.cs
src/MemBroker/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("MemBroker")] [assembly: AssemblyProduct("MemBroker")] [assembly: AssemblyCopyright("Copyright © Chris Haines 2014. - All rights reserved.")] [assembly: AssemblyVersion("1.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)]
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("MemBroker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MemBroker")] [assembly: AssemblyCopyright("Copyright © Chris Haines 2014")] [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("4e486649-2ab2-4466-89ed-1c6235f25d9c")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
mit
C#
337378ddf0950701a0e436ab101997fd17174c44
Update ErrorLog
novuslogic/NovuscodeLibrary.NET
Source/NovusCodeLibrary4.Elmah/ErrorLog.cs
Source/NovusCodeLibrary4.Elmah/ErrorLog.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using Elmah; namespace NovusCodeLibrary4.Elmah { public static class ErrorLog { public static void LogMessage(string aMessage) { try { ErrorSignal.FromCurrentContext().Raise(new Exception(aMessage)); } catch (Exception) { } } public static void LogError(Exception ex, string aMessage = null) { try { if (aMessage != null) { var annotatedException = new Exception(aMessage, ex); ErrorSignal.FromCurrentContext().Raise(annotatedException, HttpContext.Current); } else { ErrorSignal.FromCurrentContext().Raise(ex, HttpContext.Current); } } catch (Exception) { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using Elmah; namespace NovusCodeLibrary4.Elmah { public static class ErrorLog { /// <summary> /// Log error to Elmah /// </summary> public static void LogError(Exception ex, string contextualMessage = null) { try { // log error to Elmah if (contextualMessage != null) { // log exception with contextual information that's visible when // clicking on the error in the Elmah log var annotatedException = new Exception(contextualMessage, ex); ErrorSignal.FromCurrentContext().Raise(annotatedException, HttpContext.Current); } else { ErrorSignal.FromCurrentContext().Raise(ex, HttpContext.Current); } // send errors to ErrorWS (my own legacy service) // using (ErrorWSSoapClient client = new ErrorWSSoapClient()) // { // client.LogErrors(...); // } } catch (Exception) { // uh oh! just keep going } } } }
apache-2.0
C#
9aeaef093d0f151b85d0f76b63ff97e77207d1f3
Update CraftingTests.cs
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
UnityProject/Assets/Tests/CraftingTests.cs
UnityProject/Assets/Tests/CraftingTests.cs
using System.Text; using Systems.Cargo; using Systems.CraftingV2; using NUnit.Framework; using UnityEditor; using UnityEngine; namespace Tests { public class CraftingTests { [Test] public void CheckCraftingIndex() { var report = new StringBuilder(); if (Utils.TryGetScriptableObjectGUID(typeof(CraftingRecipeSingleton), report, out string guid) == false) { Assert.Fail(report.ToString()); return; } var prefabGUIDS = AssetDatabase.FindAssets("t:CraftingRecipe"); foreach (var prefabGUID in prefabGUIDS) { var path = AssetDatabase.GUIDToAssetPath(prefabGUID); var toCheck = AssetDatabase.LoadMainAssetAtPath(path) as CraftingRecipe; if(toCheck == null) continue; if (toCheck.IndexInSingleton > CraftingRecipeSingleton.Instance.CountTotalStoredRecipes() || CraftingRecipeSingleton.Instance.GetRecipeByIndex(toCheck.IndexInSingleton) != toCheck) { report.AppendLine($"The recipe: {toCheck.name} has incorrect index. " + "Perhaps this recipe has wrong indexInSingleton that doesn't match a real index in " + "the singleton. Regenerate the indexes in the CraftingRecipeSingleton to fix"); } } Logger.Log(report.ToString(), Category.Tests); Assert.IsEmpty(report.ToString()); } } }
using System.Text; using Systems.Cargo; using Systems.CraftingV2; using NUnit.Framework; using UnityEditor; using UnityEngine; namespace Tests { public class CraftingTests { [Test] public void CheckCraftingIndex() { var report = new StringBuilder(); if (Utils.TryGetScriptableObjectGUID(typeof(CraftingRecipeSingleton), report, out string guid) == false) { Assert.Fail(report.ToString()); return; } var prefabGUIDS = AssetDatabase.FindAssets("t:CraftingRecipe"); foreach (var prefabGUID in prefabGUIDS) { var path = AssetDatabase.GUIDToAssetPath(prefabGUID); var toCheck = AssetDatabase.LoadMainAssetAtPath(path) as CraftingRecipe; if(toCheck == null) continue; if (toCheck.IndexInSingleton > CraftingRecipeSingleton.Instance.CountTotalStoredRecipes() || CraftingRecipeSingleton.Instance.GetRecipeByIndex(toCheck.IndexInSingleton) != toCheck) { report.AppendLine($"The recipe: {toCheck.name} has incorrect index. " + "Perhaps this recipe has wrong indexInSingleton that doesn't match a real index in " + "the singleton. Regenerate the indexes on the singleton to fix"); } } Logger.Log(report.ToString(), Category.Tests); Assert.IsEmpty(report.ToString()); } } }
agpl-3.0
C#
ee5118dd0bd3f786861c9f28dd0e1624b3b2f153
fix release build
Microsoft/ApplicationInsights-SDK-Labs
AggregateMetrics/AggregateMetrics.Tests/AzureWebApp/CPUPercenageGaugeTests.cs
AggregateMetrics/AggregateMetrics.Tests/AzureWebApp/CPUPercenageGaugeTests.cs
namespace AggregateMetrics.Tests.AzureWebApp { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.ApplicationInsights.Extensibility.AggregateMetrics.AzureWebApp; using System.Threading; using System.Globalization; [TestClass] public class CPUPercenageGaugeTests { [TestMethod] public void BasicValidation() { CPUPercenageGauge gauge = new CPUPercenageGauge( "CPU", new PerformanceCounterFromJsonGauge(@"\Process(??APP_WIN32_PROC??)\Private Bytes * 2", "userTime", AzureWebApEnvironmentVariables.App, new CacheHelperTests())); var value1 = gauge.GetValueAndReset(); Assert.IsTrue(Math.Abs(value1.Value) < 0.000001); Thread.Sleep(TimeSpan.FromSeconds(10)); var value2 = gauge.GetValueAndReset(); Assert.IsTrue(Math.Abs(value2.Value - ((24843750 - 24062500.0) / TimeSpan.FromSeconds(10).Ticks * 100.0)) < 0.0001, string.Format(CultureInfo.InvariantCulture, "Actual: {0}, Expected: {1}", value2.Value, (24843750 - 24062500.0) / TimeSpan.FromSeconds(10).Ticks)); } } }
namespace AggregateMetrics.Tests.AzureWebApp { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.ApplicationInsights.Extensibility.AggregateMetrics.AzureWebApp; using System.Threading; [TestClass] public class CPUPercenageGaugeTests { [TestMethod] public void BasicValidation() { CPUPercenageGauge gauge = new CPUPercenageGauge( "CPU", new PerformanceCounterFromJsonGauge(@"\Process(??APP_WIN32_PROC??)\Private Bytes * 2", "userTime", AzureWebApEnvironmentVariables.App, new CacheHelperTests())); var value1 = gauge.GetValueAndReset(); Assert.IsTrue(Math.Abs(value1.Value) < 0.000001); Thread.Sleep(TimeSpan.FromSeconds(10)); var value2 = gauge.GetValueAndReset(); Assert.IsTrue(Math.Abs(value2.Value - ((24843750 - 24062500.0) / TimeSpan.FromSeconds(10).Ticks * 100.0)) < 0.0001, string.Format("Actual: {0}, Expected: {1}", value2.Value, (24843750 - 24062500.0) / TimeSpan.FromSeconds(10).Ticks)); } } }
mit
C#
0797e144c42eb96fd81db6d9d436dc430b86d0d9
Fix compilation error introduced with last minute cleanup added when looking at the diff.
blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon
Parser/Resolver/LocaleIdAllocator.cs
Parser/Resolver/LocaleIdAllocator.cs
using System.Collections.Generic; namespace Parser { // Assigns each locale an ID from 0 to n - 1 internal static class LocaleIdAllocator { // TODO: merge this with the current ID allocator in ParserContext. public static void Run(ParserContext parser, IList<CompilationScope> scopes) { /* foreach (CompilationScope scope in scopes) { if (!parser.LocaleIds.ContainsKey(scope.Locale)) { parser.LocaleIds.Add(scope.Locale, parser.LocaleIds.Count); } }//*/ } } }
using System.Collections.Generic; namespace Parser { // Assigns each locale an ID from 0 to n - 1 internal static class LocaleIdAllocator { public static void Run(ParserContext parser, IList<CompilationScope> scopes) { foreach (CompilationScope scope in scopes) { if (!parser.LocaleIds.ContainsKey(scope.Locale)) { parser.LocaleIds.Add(scope.Locale, parser.LocaleIds.Count); } } } } }
mit
C#
b5629d654d8079b01df5b34f3011fd39646fc2fd
fix bug in try.catch
sebastus/AzureFunctionForSplunk
shared/sendToSplunk.csx
shared/sendToSplunk.csx
#r "Newtonsoft.Json" using System; using System.Dynamic; using System.Net; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; public class SingleHttpClientInstance { private static readonly HttpClient HttpClient; static SingleHttpClientInstance() { HttpClient = new HttpClient(); } public static async Task<HttpResponseMessage> SendToSplunk(HttpRequestMessage req) { HttpResponseMessage response = await HttpClient.SendAsync(req); return response; } } static async Task SendMessagesToSplunk(string[] messages, TraceWriter log) { var converter = new ExpandoObjectConverter(); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback( delegate { return true; }); var client = new SingleHttpClientInstance(); string newClientContent = ""; foreach (var message in messages) { try { dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(message, converter); foreach (var record in obj.records) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(record); newClientContent += "{\"event\": " + json + "}"; } } catch (Exception e) { log.Info($"Error {e} caught while parsing message: {message}"); } } HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "https://asplunktest.westus.cloudapp.azure.com:8088/services/collector/event"); req.Headers.Accept.Clear(); req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); req.Headers.Add("Authorization", "Splunk 73A24AB7-60DD-4235-BF71-D892AE47F49D"); req.Content = new StringContent(newClientContent, Encoding.UTF8, "application/json"); HttpResponseMessage response = await SingleHttpClientInstance.SendToSplunk(req); }
#r "Newtonsoft.Json" using System; using System.Dynamic; using System.Net; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; public class SingleHttpClientInstance { private static readonly HttpClient HttpClient; static SingleHttpClientInstance() { HttpClient = new HttpClient(); } public static async Task<HttpResponseMessage> SendToSplunk(HttpRequestMessage req) { HttpResponseMessage response = await HttpClient.SendAsync(req); return response; } } static async Task SendMessagesToSplunk(string[] messages, TraceWriter log) { var converter = new ExpandoObjectConverter(); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback( delegate { return true; }); var client = new SingleHttpClientInstance(); string newClientContent = ""; foreach (var message in messages) { bool parsedOk = true; dynamic obj = ""; try { obj = JsonConvert.DeserializeObject<ExpandoObject>(message, converter); } catch (Exception e) { parsedOk = false; log.Info($"Error {e} caught while parsing message: {message}"); } if (parsedOk) { foreach (var record in obj.records) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(record); newClientContent += "{\"event\": " + json + "}"; } } } HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "https://asplunktest.westus.cloudapp.azure.com:8088/services/collector/event"); req.Headers.Accept.Clear(); req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); req.Headers.Add("Authorization", "Splunk 73A24AB7-60DD-4235-BF71-D892AE47F49D"); req.Content = new StringContent(newClientContent, Encoding.UTF8, "application/json"); HttpResponseMessage response = await SingleHttpClientInstance.SendToSplunk(req); }
mit
C#
eb065286ae5b17081910d708fc1deb2421c969bd
fix ci
ppy/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,2yangk23/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,NeoAdonis/osu,johnneijzen/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,2yangk23/osu,UselessToucan/osu
osu.Game.Rulesets.Osu/Skinning/LegacyCursor.cs
osu.Game.Rulesets.Osu/Skinning/LegacyCursor.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.Skinning; using osuTK; namespace osu.Game.Rulesets.Osu.Skinning { public class LegacyCursor : CompositeDrawable { public LegacyCursor(bool spin = true) { Size = new Vector2(50); Anchor = Anchor.Centre; Origin = Anchor.Centre; rotate = spin; } private NonPlayfieldSprite cursor; private readonly bool rotate; [BackgroundDependencyLoader] private void load(ISkinSource skin) { InternalChildren = new Drawable[] { new NonPlayfieldSprite { Texture = skin.GetTexture("cursormiddle"), Anchor = Anchor.Centre, Origin = Anchor.Centre, }, cursor = new NonPlayfieldSprite { Texture = skin.GetTexture("cursor"), Anchor = Anchor.Centre, Origin = Anchor.Centre, } }; } protected override void LoadComplete() { if (rotate) cursor.Spin(10000, RotationDirection.Clockwise); } } }
// 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.Skinning; using osuTK; namespace osu.Game.Rulesets.Osu.Skinning { public class LegacyCursor : CompositeDrawable { public LegacyCursor(bool spin = true) { Size = new Vector2(50); Anchor = Anchor.Centre; Origin = Anchor.Centre; rotate = spin; } private NonPlayfieldSprite cursor; private bool rotate; [BackgroundDependencyLoader] private void load(ISkinSource skin) { InternalChildren = new Drawable[] { new NonPlayfieldSprite { Texture = skin.GetTexture("cursormiddle"), Anchor = Anchor.Centre, Origin = Anchor.Centre, }, cursor = new NonPlayfieldSprite { Texture = skin.GetTexture("cursor"), Anchor = Anchor.Centre, Origin = Anchor.Centre, } }; } protected override void LoadComplete() { if (rotate) cursor.Spin(10000, RotationDirection.Clockwise); } } }
mit
C#
ae609b9d48c50ae6f7ad291f191ee76309fda123
Remove unnecessary local variable
peppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,peppy/osu-new
osu.Game/Screens/Menu/MenuLogoVisualisation.cs
osu.Game/Screens/Menu/MenuLogoVisualisation.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 osuTK.Graphics; using osu.Game.Skinning; using osu.Game.Online.API; using osu.Game.Users; using osu.Framework.Allocation; using osu.Framework.Bindables; namespace osu.Game.Screens.Menu { internal class MenuLogoVisualisation : LogoVisualisation { private Bindable<User> user; private Bindable<Skin> skin; [BackgroundDependencyLoader] private void load(IAPIProvider api, SkinManager skinManager) { user = api.LocalUser.GetBoundCopy(); skin = skinManager.CurrentSkin.GetBoundCopy(); user.ValueChanged += _ => updateColour(); skin.BindValueChanged(_ => updateColour(), true); } private void updateColour() { if (user.Value?.IsSupporter ?? false) Colour = skin.Value.GetConfig<GlobalSkinColours, Color4>(GlobalSkinColours.MenuGlow)?.Value ?? Color4.White; else Colour = Color4.White; } } }
// 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 osuTK.Graphics; using osu.Game.Skinning; using osu.Game.Online.API; using osu.Game.Users; using osu.Framework.Allocation; using osu.Framework.Bindables; namespace osu.Game.Screens.Menu { internal class MenuLogoVisualisation : LogoVisualisation { private Bindable<User> user; private Bindable<Skin> skin; [BackgroundDependencyLoader] private void load(IAPIProvider api, SkinManager skinManager) { user = api.LocalUser.GetBoundCopy(); skin = skinManager.CurrentSkin.GetBoundCopy(); user.ValueChanged += _ => updateColour(); skin.BindValueChanged(_ => updateColour(), true); } private void updateColour() { Color4 defaultColour = Color4.White; if (user.Value?.IsSupporter ?? false) Colour = skin.Value.GetConfig<GlobalSkinColours, Color4>(GlobalSkinColours.MenuGlow)?.Value ?? defaultColour; else Colour = defaultColour; } } }
mit
C#
d5a3df62d0e8ca74883affa58de6aa5345fba533
Add Integer Vectors, WIP
ajlopez/TensorSharp
Src/TensorSharp.Tests/Operations/AddIntegerOperationTests.cs
Src/TensorSharp.Tests/Operations/AddIntegerOperationTests.cs
namespace TensorSharp.Tests.Operations { using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using TensorSharp.Operations; [TestClass] public class AddIntegerOperationTests { [TestMethod] public void AddSingleValues() { INode<int> left = new SingleValue<int>(1); INode<int> right = new SingleValue<int>(41); var add = new AddIntegerOperation(left, right); Assert.AreEqual(left.Rank, add.Rank); Assert.IsTrue(left.Shape.SequenceEqual(right.Shape)); var result = add.Evaluate(); Assert.IsNotNull(result); Assert.AreEqual(left.Rank, result.Rank); Assert.IsTrue(left.Shape.SequenceEqual(result.Shape)); Assert.AreEqual(42, result.GetValue()); } [TestMethod] public void AddVectors() { INode<int> left = new Vector<int>(new int[] { 1, 2, 3 }); INode<int> right = new Vector<int>(new int[] { 4, 5, 6 }); var add = new AddIntegerOperation(left, right); Assert.AreEqual(left.Rank, add.Rank); Assert.IsTrue(left.Shape.SequenceEqual(right.Shape)); var result = add.Evaluate(); Assert.IsNotNull(result); Assert.AreEqual(left.Rank, result.Rank); Assert.IsTrue(left.Shape.SequenceEqual(result.Shape)); Assert.AreEqual(5, result.GetValue(0)); Assert.AreEqual(7, result.GetValue(0)); Assert.AreEqual(9, result.GetValue(0)); } } }
namespace TensorSharp.Tests.Operations { using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using TensorSharp.Operations; [TestClass] public class AddIntegerOperationTests { [TestMethod] public void AddSingleValues() { INode<int> left = new SingleValue<int>(1); INode<int> right = new SingleValue<int>(41); var add = new AddIntegerOperation(left, right); Assert.AreEqual(left.Rank, add.Rank); Assert.IsTrue(left.Shape.SequenceEqual(right.Shape)); var result = add.Evaluate(); Assert.IsNotNull(result); Assert.AreEqual(left.Rank, result.Rank); Assert.IsTrue(left.Shape.SequenceEqual(result.Shape)); Assert.AreEqual(42, result.GetValue()); } } }
mit
C#
212ca1b836f4bcc2f265d0c49475cc75ef281756
Bump version up to reflect a change of the API in R.NET, and avoid confusions.
jmp75/metaheuristics,jmp75/metaheuristics,jmp75/metaheuristics,jmp75/metaheuristics
CSIRO.Metaheuristics/Properties/SolutionInfo.cs
CSIRO.Metaheuristics/Properties/SolutionInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCompany( "CSIRO" )] [assembly: AssemblyCopyright( "Copyright © CSIRO 2010-2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: AssemblyConfiguration("")] // 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( "0.7.0.6" )] [assembly: AssemblyFileVersion( "0.7.0.6" )]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCompany( "CSIRO" )] [assembly: AssemblyCopyright( "Copyright © CSIRO 2010-2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: AssemblyConfiguration("")] // 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( "0.7.0.5" )] [assembly: AssemblyFileVersion( "0.7.0.5" )]
lgpl-2.1
C#
794e0aeaf4f0d97d9d22a3e7f20ffec40dfcb7f2
Remove explicit default value initialization.
GGG-KILLER/GUtils.NET
GUtils.Testing/DelegateInvocationCounter.cs
GUtils.Testing/DelegateInvocationCounter.cs
using System; using System.Runtime.CompilerServices; using System.Threading; namespace GUtils.Testing { /// <summary> /// A class that tracks the amount of times its <see cref="WrappedDelegate" /> was invoked. /// </summary> /// <typeparam name="T"></typeparam> public class DelegateInvocationCounter<T> where T : Delegate { private Int32 _invocationCount; /// <summary> /// The number of times <see cref="WrappedDelegate" /> was invoked. /// </summary> public Int32 InvocationCount => this._invocationCount; /// <summary> /// The wrapper delegate that increments the invocation count when invoked. /// </summary> public T WrappedDelegate { get; internal set; } = null!; /// <summary> /// Atomically increments the number of invocations of this delegate. /// </summary> [MethodImpl ( MethodImplOptions.AggressiveInlining )] internal void Increment ( ) => Interlocked.Increment ( ref this._invocationCount ); /// <summary> /// Resets the number of invocations of this counter. /// </summary> public void Reset ( ) => this._invocationCount = 0; } }
using System; using System.Runtime.CompilerServices; using System.Threading; namespace GUtils.Testing { /// <summary> /// A class that tracks the amount of times its <see cref="WrappedDelegate" /> was invoked. /// </summary> /// <typeparam name="T"></typeparam> public class DelegateInvocationCounter<T> where T : Delegate { private Int32 _invocationCount = 0; /// <summary> /// The number of times <see cref="WrappedDelegate" /> was invoked. /// </summary> public Int32 InvocationCount => this._invocationCount; /// <summary> /// The wrapper delegate that increments the invocation count when invoked. /// </summary> public T WrappedDelegate { get; internal set; } = null!; /// <summary> /// Atomically increments the number of invocations of this delegate. /// </summary> [MethodImpl ( MethodImplOptions.AggressiveInlining )] internal void Increment ( ) => Interlocked.Increment ( ref this._invocationCount ); /// <summary> /// Resets the number of invocations of this counter. /// </summary> public void Reset ( ) => this._invocationCount = 0; } }
mit
C#
3118869e11c4a928fce75b9cafa1dc05bc4f94c0
Fix inspection
ParticularLabs/APIComparer,modernist/APIComparer,ParticularLabs/APIComparer,modernist/APIComparer
APIComparer.Backend/CompareSetReporter.cs
APIComparer.Backend/CompareSetReporter.cs
namespace APIComparer.Backend { using System; using System.IO; using Reporting; public class CompareSetReporter { public void Report(PackageDescription description, DiffedCompareSet[] diffedCompareSets) { var resultPath = DetermineAndCreateResultPathIfNotExistant(description); using (var fileStream = File.OpenWrite(resultPath)) { using (var into = new StreamWriter(fileStream)) { var formatter = new APIUpgradeToHtmlFormatter(); formatter.Render(into, description, diffedCompareSets); @into.Flush(); @into.Close(); fileStream.Close(); } } RemoveTemporaryWorkFiles(resultPath); } static string DetermineAndCreateResultPathIfNotExistant(PackageDescription description) { var resultFile = $"{description.PackageId}-{description.Versions.LeftVersion}...{description.Versions.RightVersion}.html"; var rootPath = Environment.GetEnvironmentVariable("HOME"); // TODO: use AzureEnvironment if (rootPath != null) { rootPath = Path.Combine(rootPath, @".\site\wwwroot"); } else { rootPath = Environment.GetEnvironmentVariable("APICOMPARER_WWWROOT", EnvironmentVariableTarget.User); } if (string.IsNullOrEmpty(rootPath)) { throw new Exception("No root path could be found. If in development please set the `APICOMPARER_WWWROOT` env variable to the root folder of the webproject"); } var directoryPath = Path.Combine(rootPath, "Comparisons"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var resultPath = Path.Combine(directoryPath, resultFile); return resultPath; } static void RemoveTemporaryWorkFiles(string resultPath) { File.Delete(Path.ChangeExtension(resultPath, ".running.html")); } } }
namespace APIComparer.Backend { using System; using System.IO; using APIComparer.Backend.Reporting; public class CompareSetReporter { public void Report(PackageDescription description, DiffedCompareSet[] diffedCompareSets) { var resultPath = DetermineAndCreateResultPathIfNotExistant(description); using (var fileStream = File.OpenWrite(resultPath)) { using (var into = new StreamWriter(fileStream)) { var formatter = new APIUpgradeToHtmlFormatter(); formatter.Render(into, description, diffedCompareSets); @into.Flush(); @into.Close(); fileStream.Close(); } } RemoveTemporaryWorkFiles(resultPath); } static string DetermineAndCreateResultPathIfNotExistant(PackageDescription description) { var resultFile = $"{description.PackageId}-{description.Versions.LeftVersion}...{description.Versions.RightVersion}.html"; var rootPath = Environment.GetEnvironmentVariable("HOME"); // TODO: use AzureEnvironment if (rootPath != null) { rootPath = Path.Combine(rootPath, @".\site\wwwroot"); } else { rootPath = Environment.GetEnvironmentVariable("APICOMPARER_WWWROOT", EnvironmentVariableTarget.User); } if (string.IsNullOrEmpty(rootPath)) { throw new Exception("No root path could be found. If in development please set the `APICOMPARER_WWWROOT` env variable to the root folder of the webproject"); } var directoryPath = Path.Combine(rootPath, "Comparisons"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var resultPath = Path.Combine(directoryPath, resultFile); return resultPath; } static void RemoveTemporaryWorkFiles(string resultPath) { File.Delete(Path.ChangeExtension(resultPath, ".running.html")); } } }
mit
C#
f3afca8c34dd9b6c067ff78680a6c852e271e1b8
Update BasicAssocItem.cs
willrawls/xlg,willrawls/xlg
MetX/MetX.Standard.XDString/BasicAssocItem.cs
MetX/MetX.Standard.XDString/BasicAssocItem.cs
using System; using System.Text; using System.Xml.Serialization; using MetX.Standard.XDString.Interfaces; namespace MetX.Standard.XDString; [Serializable] public class AssocItemWithChildren : BasicAssocItem { public AssocArray Children = new(); public AssocItemWithChildren(string key, string value = null, Guid? id = null, string name = null, string category = null) : base(key, value, id, name, category) { } public AssocItemWithChildren() { } } [Serializable] public class BasicAssocItem : IAssocItem { [XmlAttribute] public string Key { get; set; } [XmlAttribute] public string Value { get; set; } [XmlAttribute] public string Name { get; set; } [XmlAttribute] public Guid ID { get; set; } [XmlAttribute] public int Number { get; set; } [XmlAttribute] public string Category { get; set; } public BasicAssocItem(string key, string value = null, Guid? id = null, string name = null, string category = null) { Value = value; Name = name; Category = category; ID = id ?? Guid.NewGuid(); Key = key ?? ID.ToString("N"); } public BasicAssocItem() { ID = Guid.NewGuid(); Key = ID.ToString("N"); } public override string ToString() { var sb = new StringBuilder(); sb.AppendLine($" {Key}={Value ?? "nil"}, {ID:N}, {Name ?? "nil"}"); return sb.ToString(); } }
using System; using System.Text; using System.Xml.Serialization; using MetX.Standard.XDString.Interfaces; namespace MetX.Standard.XDString; [Serializable] public class BasicAssocItem : IAssocItem { [XmlAttribute] public string Key { get; set; } [XmlAttribute] public string Value { get; set; } [XmlAttribute] public string Name { get; set; } [XmlAttribute] public Guid ID { get; set; } [XmlAttribute] public int Number { get; set; } [XmlAttribute] public string Category { get; set; } public BasicAssocItem(string key, string value = null, Guid? id = null, string name = null, string category = null) { Value = value; Name = name; Category = category; ID = id ?? Guid.NewGuid(); Key = key ?? ID.ToString("N"); } public BasicAssocItem() { ID = Guid.NewGuid(); Key = ID.ToString("N"); } public override string ToString() { var sb = new StringBuilder(); sb.AppendLine($" {Key}={Value ?? "nil"}, {ID:N}, {Name ?? "nil"}"); return sb.ToString(); } }
mit
C#
d81daee5946f622e91004f1736c242d347b60f9e
Fix tag helpers namespace
martincostello/api,martincostello/api,martincostello/api
src/API/Views/_ViewImports.cshtml
src/API/Views/_ViewImports.cshtml
@using System.Globalization; @using MartinCostello.Api @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@using System.Globalization; @using MartinCostello.Api @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
mit
C#
0f7f2570b107ec77ca0569a0d8478ca2defa5b24
Support sequential statements with value loading at last.
modulexcite/msgpack-cli,undeadlabs/msgpack-cli,modulexcite/msgpack-cli,undeadlabs/msgpack-cli,msgpack/msgpack-cli,msgpack/msgpack-cli
src/MsgPack/Serialization/EmittingSerializers/SequenceILConstruct.cs
src/MsgPack/Serialization/EmittingSerializers/SequenceILConstruct.cs
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2013 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization.EmittingSerializers { internal class SequenceILConstruct : ILConstruct { private readonly ILConstruct[] _statements; public SequenceILConstruct( Type contextType, IEnumerable<ILConstruct> statements ) : base( contextType ) { this._statements = statements.ToArray(); } public override void Evaluate( TracingILGenerator il ) { il.TraceWriteLine( "// Eval->: {0}", this ); foreach ( var statement in this._statements ) { statement.Evaluate( il ); } il.TraceWriteLine( "// ->Eval: {0}", this ); } public override void LoadValue( TracingILGenerator il, bool shouldBeAddress ) { if ( this._statements.Length == 0 ) { base.LoadValue( il, shouldBeAddress ); return; } il.TraceWriteLine( "// Eval(Load)->: {0}", this ); for ( var i = 0; i < this._statements.Length - 1; i++ ) { this._statements[ i ].Evaluate( il ); } this._statements.Last().LoadValue( il, shouldBeAddress ); il.TraceWriteLine( "// ->Eval(Load): {0}", this ); } public override string ToString() { return String.Format( CultureInfo.InvariantCulture, "Sequence[{0}]", this._statements.Length ); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2013 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using MsgPack.Serialization.Reflection; namespace MsgPack.Serialization.EmittingSerializers { internal class SequenceILConstruct : ILConstruct { private readonly ILConstruct[] _statements; public SequenceILConstruct( Type contextType, IEnumerable<ILConstruct> statements ) : base( contextType ) { this._statements = statements.ToArray(); } public override void Evaluate( TracingILGenerator il ) { il.TraceWriteLine( "// Eval->: {0}", this ); foreach ( var statement in this._statements ) { statement.Evaluate( il ); } il.TraceWriteLine( "// ->Eval: {0}", this ); } public override string ToString() { return String.Format( CultureInfo.InvariantCulture, "Sequence[{0}]", this._statements.Length ); } } }
apache-2.0
C#
db3f0ed409516c6a322720fcf988a375dce8924d
Add Sector to PublicSectorOrganisation Client
SkillsFundingAgency/das-referencedata,SkillsFundingAgency/das-referencedata
src/SFA.DAS.ReferenceData.Api.Client/Dto/PublicSectorOrganisation.cs
src/SFA.DAS.ReferenceData.Api.Client/Dto/PublicSectorOrganisation.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SFA.DAS.ReferenceData.Api.Client.Dto { public class PublicSectorOrganisation { public string Name { get; set; } public DataSource Source { get; set; } public string Sector { get; set; } } public enum DataSource { Ons = 1, Nhs = 2, Police = 3 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SFA.DAS.ReferenceData.Api.Client.Dto { public class PublicSectorOrganisation { public string Name { get; set; } public DataSource Source { get; set; } } public enum DataSource { Ons = 1, Nhs = 2, Police = 3 } }
mit
C#
d0b56dcd48467aea63a82b3edf464cfdee9706ba
Remove set's on ActionResultTypes
peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype
src/Glimpse.Agent.AspNet/Internal/Inspectors/Mvc/Proxies/ActionResultTypes.cs
src/Glimpse.Agent.AspNet/Internal/Inspectors/Mvc/Proxies/ActionResultTypes.cs
using System; using System.Collections.Generic; namespace Glimpse.Agent.Internal.Inspectors.Mvc.Proxies { public class ActionResultTypes { public interface IViewResult { int? StatusCode { get; } string ViewName { get; } IDictionary<string, object> TempData { get; } IDictionary<string, object> ViewData { get; } object ContentType { get; } } public interface IContentResult { int? StatusCode { get; } string Content { get; } object ContentType { get; } } public interface IObjectResult { int? StatusCode { get; } object Value { get; } IList<object> Formatters { get; } IList<string> ContentTypes { get; } Type DeclaredType { get; } } public interface IFileResult { string FileDownloadName { get; } string ContentType { get; } } } }
using System; using System.Collections.Generic; namespace Glimpse.Agent.Internal.Inspectors.Mvc.Proxies { public class ActionResultTypes { public interface IViewResult { int? StatusCode { get; } string ViewName { get; } IDictionary<string, object> TempData { get; } IDictionary<string, object> ViewData { get; } object ContentType { get; } } public interface IContentResult { int? StatusCode { get; } string Content { get; } object ContentType { get; } } public interface IObjectResult { int? StatusCode { get; set; } object Value { get; set; } IList<object> Formatters { get; set; } IList<string> ContentTypes { get; set; } Type DeclaredType { get; set; } } public interface IFileResult { string FileDownloadName { get; set; } string ContentType { get; set; } } } }
mit
C#
0b7802a58ffbc3181a91a93c1262fe5515b649d8
Use login/getting started background image.
Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving
src/MobileApps/MyDriving/MyDriving.iOS/GettingStartedContentViewController.cs
src/MobileApps/MyDriving/MyDriving.iOS/GettingStartedContentViewController.cs
using Foundation; using System; using UIKit; namespace MyDriving.iOS { public partial class GettingStartedContentViewController : UIViewController { public UIImage Image { get; set; } public int PageIndex { get; set; } public GettingStartedContentViewController (IntPtr handle) : base (handle) { } public static GettingStartedContentViewController ControllerForPageIndex(int pageIndex) { var imagePath = string.Format($"screen_{pageIndex+1}.png"); var image = UIImage.FromBundle(imagePath); var page = (GettingStartedContentViewController)UIStoryboard.FromName("Main", null).InstantiateViewController("gettingStartedContentViewController"); page.Image = image; page.PageIndex = pageIndex; return page; } public override void ViewDidLoad() { base.ViewDidLoad(); View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle("background_started.png")); imageView.Image = Image; } } }
using Foundation; using System; using UIKit; namespace MyDriving.iOS { public partial class GettingStartedContentViewController : UIViewController { public UIImage Image { get; set; } public int PageIndex { get; set; } public GettingStartedContentViewController (IntPtr handle) : base (handle) { } public static GettingStartedContentViewController ControllerForPageIndex(int pageIndex) { var imagePath = string.Format($"screen_{pageIndex+1}.png"); var image = UIImage.FromBundle(imagePath); var page = (GettingStartedContentViewController)UIStoryboard.FromName("Main", null).InstantiateViewController("gettingStartedContentViewController"); page.Image = image; page.PageIndex = pageIndex; return page; } public override void ViewDidLoad() { base.ViewDidLoad(); imageView.Image = Image; } } }
mit
C#
61d2fc0a4eba1d3a0118e8fcdaa152c7807b27fb
Fix arguments to SelectListItem constructor
ucdavis/Purchasing,ucdavis/Purchasing,ucdavis/Purchasing
Purchasing.Mvc/Models/WorkgroupModifyModel.cs
Purchasing.Mvc/Models/WorkgroupModifyModel.cs
using System.Collections.Generic; using System.Linq; using Purchasing.Core; using Purchasing.Core.Domain; using UCDArch.Core.PersistanceSupport; using UCDArch.Core.Utils; using System.Linq.Expressions; using Microsoft.AspNetCore.Mvc.Rendering; namespace Purchasing.Mvc.Models { /// <summary> /// ModifyModel for the Workgroup class /// </summary> public class WorkgroupModifyModel { public Workgroup Workgroup { get; set; } public List<SelectListItem> Organizations { get; set; } public static WorkgroupModifyModel Create(User user, IQueryRepositoryFactory queryRepositoryFactory, Workgroup workgroup = null) { var modifyModel = new WorkgroupModifyModel { Workgroup = workgroup ?? new Workgroup() }; modifyModel.Organizations = workgroup != null ? workgroup.Organizations.Select(x => new SelectListItem(x.Name + " (" + x.Id + ")", x.Id) {Selected = true}).ToList() : new List<SelectListItem>(); var userOrgs = user.Organizations.Where(x => !modifyModel.Organizations.Select(y => y.Value).Contains(x.Id)); modifyModel.Organizations.AddRange(userOrgs.Select(x => new SelectListItem(x.Name + " (" + x.Id + ")", x.Id))); var ids = modifyModel.Organizations.Select(y => y.Value).ToList(); var decendantOrgs = queryRepositoryFactory.OrganizationDescendantRepository.Queryable.Where(a => ids.Contains(a.RollupParentId)).ToList(); modifyModel.Organizations.AddRange(decendantOrgs.Select(x => new SelectListItem(x.Name + " (" + x.OrgId + ")", x.OrgId))); modifyModel.Organizations = modifyModel.Organizations.Distinct().OrderBy(a => a.Text).ToList(); return modifyModel; } } }
using System.Collections.Generic; using System.Linq; using Purchasing.Core; using Purchasing.Core.Domain; using UCDArch.Core.PersistanceSupport; using UCDArch.Core.Utils; using System.Linq.Expressions; using Microsoft.AspNetCore.Mvc.Rendering; namespace Purchasing.Mvc.Models { /// <summary> /// ModifyModel for the Workgroup class /// </summary> public class WorkgroupModifyModel { public Workgroup Workgroup { get; set; } public List<SelectListItem> Organizations { get; set; } public static WorkgroupModifyModel Create(User user, IQueryRepositoryFactory queryRepositoryFactory, Workgroup workgroup = null) { var modifyModel = new WorkgroupModifyModel { Workgroup = workgroup ?? new Workgroup() }; modifyModel.Organizations = workgroup != null ? workgroup.Organizations.Select(x => new SelectListItem(x.Name + " (" + x.Id + ")", x.Id, true) {Selected = true}).ToList() : new List<SelectListItem>(); var userOrgs = user.Organizations.Where(x => !modifyModel.Organizations.Select(y => y.Value).Contains(x.Id)); modifyModel.Organizations.AddRange(userOrgs.Select(x => new SelectListItem(x.Name + " (" + x.Id + ")", x.Id, true))); var ids = modifyModel.Organizations.Select(y => y.Value).ToList(); var decendantOrgs = queryRepositoryFactory.OrganizationDescendantRepository.Queryable.Where(a => ids.Contains(a.RollupParentId)).ToList(); modifyModel.Organizations.AddRange(decendantOrgs.Select(x => new SelectListItem(x.Name + " (" + x.OrgId + ")", x.OrgId, true))); modifyModel.Organizations = modifyModel.Organizations.Distinct().OrderBy(a => a.Text).ToList(); return modifyModel; } } }
mit
C#
2412390981cd724b08019430c1cf81bb16ec602d
add test
kurema/PlaneProject
RhinoCommonBasic/RhinoCommonBasic/Class1.cs
RhinoCommonBasic/RhinoCommonBasic/Class1.cs
using Rhino; using Rhino.Geometry; using Rhino.DocObjects; using Rhino.Collections; using System; using System.IO; using System.Xml; using System.Xml.Linq; using System.Linq; using System.Data; using System.Drawing; using System.Reflection; using System.Collections; using System.Windows.Forms; using System.Collections.Generic; using System.Runtime.InteropServices; namespace RhinoCommonBasic { public class Class1 { public static void Test() { //Write Test Code Here } } }
using Rhino; using Rhino.Geometry; using Rhino.DocObjects; using Rhino.Collections; using System; using System.IO; using System.Xml; using System.Xml.Linq; using System.Linq; using System.Data; using System.Drawing; using System.Reflection; using System.Collections; using System.Windows.Forms; using System.Collections.Generic; using System.Runtime.InteropServices; namespace RhinoCommonBasic { public class Class1 { } }
mit
C#
48e5b61fba96481a12eb6ca1da0e1f8c0015bce1
Update KeystrokeDatum.cs
predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus
Sensus.Shared/Probes/Apps/KeystrokeDatum.cs
Sensus.Shared/Probes/Apps/KeystrokeDatum.cs
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Sensus.Anonymization; using Sensus.Anonymization.Anonymizers; using Sensus.Probes.User.Scripts.ProbeTriggerProperties; using System; namespace Sensus.Probes.Apps { public class KeystrokeDatum : Datum { private string _key; private string _app; /// <summary> /// For JSON deserialization. /// </summary> public KeystrokeDatum() { } public KeystrokeDatum(DateTimeOffset timestamp, string key, string app) : base(timestamp) { _key = key == null ? "" : key; _app = app == null ? "" : app; } public override string DisplayDetail { get { return _key; } } /// <summary> /// The key pressed. /// </summary> [StringProbeTriggerProperty] [Anonymizable(null, new[] { typeof(StringHashAnonymizer), typeof(RegExAnonymizer) }, -1)] public string Key { get => _key; set => _key = value; } /// <summary> /// The app that received the keystroke. /// </summary> [StringProbeTriggerProperty] [Anonymizable(null, typeof(StringHashAnonymizer), false)] public string App { get => _app; set => _app = value; } public override object StringPlaceholderValue { get { throw new NotImplementedException(); } } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString() + Environment.NewLine + "Key: " + _key + Environment.NewLine + "App: " + _app + Environment.NewLine; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Sensus.Anonymization; using Sensus.Anonymization.Anonymizers; using Sensus.Probes.User.Scripts.ProbeTriggerProperties; using System; namespace Sensus.Probes.Apps { public class KeystrokeDatum : Datum { private string _key; private string _app; /// <summary> /// For JSON deserialization. /// </summary> public KeystrokeDatum() { } public KeystrokeDatum(DateTimeOffset timestamp, string key, string app) : base(timestamp) { _key = key == null ? "" : key; _app = app == null ? "" : app; } public override string DisplayDetail { get { return "(Keystroke Data)"; } } /// <summary> /// The key pressed. /// </summary> [StringProbeTriggerProperty] [Anonymizable(null, new[] { typeof(StringHashAnonymizer), typeof(RegExAnonymizer) }, -1)] public string Key { get => _key; set => _key = value; } /// <summary> /// The app that received the keystroke. /// </summary> [StringProbeTriggerProperty] [Anonymizable(null, typeof(StringHashAnonymizer), false)] public string App { get => _app; set => _app = value; } public override object StringPlaceholderValue { get { throw new NotImplementedException(); } } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString() + Environment.NewLine + "Key: " + _key + Environment.NewLine + "App: " + _app + Environment.NewLine; } } }
apache-2.0
C#
9466b1d2390f548e4f928924ea6dd8bec229aa54
Fix integration test project
devlead/cake,patriksvensson/cake,daveaglick/cake,gep13/cake,Sam13/cake,Julien-Mialon/cake,thomaslevesque/cake,mholo65/cake,gep13/cake,ferventcoder/cake,phrusher/cake,devlead/cake,ferventcoder/cake,cake-build/cake,RehanSaeed/cake,Sam13/cake,phenixdotnet/cake,Julien-Mialon/cake,vlesierse/cake,thomaslevesque/cake,robgha01/cake,mholo65/cake,DixonD-git/cake,adamhathcock/cake,robgha01/cake,michael-wolfenden/cake,phenixdotnet/cake,vlesierse/cake,adamhathcock/cake,phrusher/cake,michael-wolfenden/cake,patriksvensson/cake,daveaglick/cake,cake-build/cake,RehanSaeed/cake
tests/integration/resources/Cake.Common/Tools/DotNetCore/hwapp.tests/Tests.cs
tests/integration/resources/Cake.Common/Tools/DotNetCore/hwapp.tests/Tests.cs
using System; using Xunit; using HWApp.Common; namespace HWApp.Tests { public sealed class GreeterTests { public sealed class TheGreaterMethod { [Fact] public void Should_Not_Fail_Test() { Assert.NotEqual("true", Environment.GetEnvironmentVariable("hwapp_fail_test")); } [Fact] public void Should_Greet_World() { // Given var name = "World"; var expect = "Hello World!"; // When var result = Greeter.GetGreeting(name); // Then Assert.Equal(expect, result); } [Fact] public void Should_Throw_On_Null_Name() { // Given string name = null; // When var result = Record.Exception(() => Greeter.GetGreeting(name)); // Then Assert.NotNull(result); Assert.IsType<ArgumentNullException>(result); Assert.Equal($"Value cannot be null.{Environment.NewLine}Parameter name: name", result.Message); } } } }
using System; using Xunit; using HWApp.Common; namespace HWApp.Tests { public sealed class GreeterTests { public sealed class TheGreaterMethod { [Fact] public void Should_Not_Fail_Test() { Assert.NotEqual("true", Environment.GetEnvironmentVariable("hwapp_fail_test")); } [Fact] public void Should_Greet_World() { // Given var name = "World"; var expect = "Hello World!"; // When var result = Greeter.GetGreeting(name); // Then Assert.Equal(expect, result); } [Fact] public void Should_Throw_On_Null_Name() { // Given string name = null; // When var result = Record.Exception(() => Greeter.GetGreeting(name)); // Then Assert.NotNull(result); Assert.IsType<ArgumentNullException>(result); Assert.Equal("Value cannot be null.\r\nParameter name: name", result.Message); } } } }
mit
C#
2bd94336212cc579cbf80800cf0c094a85bd4922
Use the correct delegate. Fixes #547
mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp
binding/Binding/SKManagedPixelSerializer.cs
binding/Binding/SKManagedPixelSerializer.cs
// // Bindings for SKPixelSerializer // // Author: // Matthew Leibowitz // // Copyright 2017 Xamarin Inc // using System; using System.Runtime.InteropServices; namespace SkiaSharp { public abstract class SKManagedPixelSerializer : SKPixelSerializer { // delegate declarations [UnmanagedFunctionPointer (CallingConvention.Cdecl)] internal delegate bool use_delegate (IntPtr serializer, IntPtr buffer, IntPtr size); [UnmanagedFunctionPointer (CallingConvention.Cdecl)] internal delegate IntPtr encode_delegate (IntPtr serializer, IntPtr pixmap); // so the GC doesn't collect the delegate private static readonly use_delegate fUse; private static readonly encode_delegate fEncode; static SKManagedPixelSerializer () { fUse = new use_delegate (UseInternal); fEncode = new encode_delegate (EncodeInternal); SkiaApi.sk_managedpixelserializer_set_delegates ( Marshal.GetFunctionPointerForDelegate (fUse), Marshal.GetFunctionPointerForDelegate (fEncode)); } [Preserve] internal SKManagedPixelSerializer (IntPtr x, bool owns) : base (x, owns) { } public SKManagedPixelSerializer () : base (SkiaApi.sk_managedpixelserializer_new (), true) { } protected abstract bool OnUseEncodedData (IntPtr data, IntPtr length); protected abstract SKData OnEncode (SKPixmap pixmap); // internal proxy [MonoPInvokeCallback (typeof (use_delegate))] private static bool UseInternal (IntPtr cserializer, IntPtr buffer, IntPtr size) { var serializer = GetObject<SKManagedPixelSerializer> (cserializer, false); return serializer.OnUseEncodedData (buffer, size); } [MonoPInvokeCallback (typeof (encode_delegate))] private static IntPtr EncodeInternal (IntPtr cserializer, IntPtr pixmap) { var serializer = GetObject<SKManagedPixelSerializer> (cserializer, false); var data = serializer.OnEncode (GetObject<SKPixmap> (pixmap, false)); return data == null ? IntPtr.Zero : data.Handle; } } }
// // Bindings for SKPixelSerializer // // Author: // Matthew Leibowitz // // Copyright 2017 Xamarin Inc // using System; using System.Runtime.InteropServices; namespace SkiaSharp { public abstract class SKManagedPixelSerializer : SKPixelSerializer { // delegate declarations [UnmanagedFunctionPointer (CallingConvention.Cdecl)] internal delegate bool use_delegate (IntPtr serializer, IntPtr buffer, IntPtr size); [UnmanagedFunctionPointer (CallingConvention.Cdecl)] internal delegate IntPtr encode_delegate (IntPtr serializer, IntPtr pixmap); // so the GC doesn't collect the delegate private static readonly use_delegate fUse; private static readonly encode_delegate fEncode; static SKManagedPixelSerializer () { fUse = new use_delegate (UseInternal); fEncode = new encode_delegate (EncodeInternal); SkiaApi.sk_managedpixelserializer_set_delegates ( Marshal.GetFunctionPointerForDelegate (fUse), Marshal.GetFunctionPointerForDelegate (fEncode)); } [Preserve] internal SKManagedPixelSerializer (IntPtr x, bool owns) : base (x, owns) { } public SKManagedPixelSerializer () : base (SkiaApi.sk_managedpixelserializer_new (), true) { } protected abstract bool OnUseEncodedData (IntPtr data, IntPtr length); protected abstract SKData OnEncode (SKPixmap pixmap); // internal proxy [MonoPInvokeCallback (typeof (use_delegate))] private static bool UseInternal (IntPtr cserializer, IntPtr buffer, IntPtr size) { var serializer = GetObject<SKManagedPixelSerializer> (cserializer, false); return serializer.OnUseEncodedData (buffer, size); } [MonoPInvokeCallback (typeof (SKBitmapReleaseDelegateInternal))] private static IntPtr EncodeInternal (IntPtr cserializer, IntPtr pixmap) { var serializer = GetObject<SKManagedPixelSerializer> (cserializer, false); var data = serializer.OnEncode (GetObject<SKPixmap> (pixmap, false)); return data == null ? IntPtr.Zero : data.Handle; } } }
mit
C#
80834ed4d4cddbc48da21ba7b4b6c0e037f6e45e
Add volatile keyword accroding to the doc
gyrosworkshop/Wukong,gyrosworkshop/Wukong
src/Wukong/Services/Storage.cs
src/Wukong/Services/Storage.cs
using System; using System.Linq; using System.Collections.Generic; using Wukong.Models; namespace Wukong.Services { public sealed class Storage { static readonly Lazy<Storage> instance = new Lazy<Storage>(() => new Storage()); volatile IDictionary<string, User> userMap = new Dictionary<string, User>(); volatile IDictionary<string, Channel> channelMap = new Dictionary<string, Channel>(); public static Storage Instance { get { return instance.Value; } } Storage() { } public User GetUser(string userId) { if (!userMap.ContainsKey(userId)) { userMap.Add(userId, new User(userId)); } return userMap[userId]; } public Channel GetChannel(string channelId) { if (channelId == null || !channelMap.ContainsKey(channelId)) { return null; } return channelMap[channelId]; } public void RemoveChannel(string channelId) { channelMap.Remove(channelId); } public List<Channel> GetAllChannelsWithUserId(string userId) { return channelMap.Values.Where(x => x.HasUser(userId)).ToList(); } public Channel CreateChannel(string channelId, ISocketManager socketManager, IProvider provider) { channelMap[channelId] = new Channel(channelId, socketManager, provider); return channelMap[channelId]; } } }
using System; using System.Linq; using System.Collections.Generic; using Wukong.Models; namespace Wukong.Services { public sealed class Storage { static readonly Lazy<Storage> instance = new Lazy<Storage>(() => new Storage()); IDictionary<string, User> userMap = new Dictionary<string, User>(); IDictionary<string, Channel> channelMap = new Dictionary<string, Channel>(); public static Storage Instance { get { return instance.Value; } } Storage() { } public User GetUser(string userId) { if (!userMap.ContainsKey(userId)) { userMap.Add(userId, new User(userId)); } return userMap[userId]; } public Channel GetChannel(string channelId) { if (channelId == null || !channelMap.ContainsKey(channelId)) { return null; } return channelMap[channelId]; } public void RemoveChannel(string channelId) { channelMap.Remove(channelId); } public List<Channel> GetAllChannelsWithUserId(string userId) { return channelMap.Values.Where(x => x.HasUser(userId)).ToList(); } public Channel CreateChannel(string channelId, ISocketManager socketManager, IProvider provider) { channelMap[channelId] = new Channel(channelId, socketManager, provider); return channelMap[channelId]; } } }
mit
C#
2380635e603a9946a8361b319134fceaa2e6767e
fix compiling error
NDark/ndinfrastructure,NDark/ndinfrastructure
Unity/Platform/Region/Plugins/PlatformRegion.cs
Unity/Platform/Region/Plugins/PlatformRegion.cs
/** MIT License Copyright (c) 2017 - 2021 NDark 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. */ /** * https://wenrongdev.com/unity53-native-system-language/ */ using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Runtime.InteropServices; public static class PlatformRegion { public static string CheckUnityApplicationSystemLanguage() { string ret = string.Empty; SystemLanguage unitySystemLangauge = Application.systemLanguage; ret = unitySystemLangauge.ToString(); Debug.Log("CheckApplicationSystemLanguage() ret=" + ret); return ret ; } #if UNITY_ANDROID public static string CurrentAndroidLanguage() { string result = ""; using (AndroidJavaClass cls = new AndroidJavaClass("java.util.Locale")) { if (cls != null) { using (AndroidJavaObject locale = cls.CallStatic<AndroidJavaObject>("getDefault")) { if (locale != null) { result = locale.Call<string>("getLanguage") + "_" + locale.Call<string>("getDefault"); Debug.Log("CurrentAndroidLanguage() Android lang: " + result); } else { Debug.LogError("CurrentAndroidLanguage() locale null"); } } } else { Debug.LogError("CurrentAndroidLanguage() cls null"); } } Debug.LogWarning("CurrentAndroidLanguage() result" + result); return result; } #endif #if UNITY_IPHONE [DllImport("__Internal")] private static extern string CurIOSLang(); public static string CurrentiOSLanguage() { string ret = CurIOSLang(); Debug.LogWarning("CurrentAndroidLanguage() ret" + ret); return ret; } #endif }
/** MIT License Copyright (c) 2017 - 2021 NDark 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. */ /** * https://wenrongdev.com/unity53-native-system-language/ */ using System.Collections; using System.Collections.Generic; using UnityEngine; public static class PlatformRegion { public static string CheckUnityApplicationSystemLanguage() { string ret = string.Empty; SystemLanguage unitySystemLangauge = Application.systemLanguage; ret = unitySystemLangauge.ToString(); Debug.Log("CheckApplicationSystemLanguage() ret=" + ret); return ret ; } #if UNITY_ANDROID public static string CurrentAndroidLanguage() { string result = ""; using (AndroidJavaClass cls = new AndroidJavaClass("java.util.Locale")) { if (cls != null) { using (AndroidJavaObject locale = cls.CallStatic<AndroidJavaObject>("getDefault")) { if (locale != null) { result = locale.Call<string>("getLanguage") + "_" + locale.Call<string>("getDefault"); Debug.Log("CurrentAndroidLanguage() Android lang: " + result); } else { Debug.LogError("CurrentAndroidLanguage() locale null"); } } } else { Debug.LogError("CurrentAndroidLanguage() cls null"); } } Debug.LogWarning("CurrentAndroidLanguage() result" + result); return result; } #endif #if UNITY_IPHONE [DllImport("__Internal")] private static extern string CurIOSLang(); public static string CurrentiOSLanguage() { string ret = CurIOSLang(); Debug.LogWarning("CurrentAndroidLanguage() result" + result); return ret; } #endif }
mit
C#
2209afd0e8c82405701b8b6807d9a280cbf1aacc
Mark `Live` methods as `InstantHandleAttribute`
ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu
osu.Game/Database/Live.cs
osu.Game/Database/Live.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 JetBrains.Annotations; namespace osu.Game.Database { /// <summary> /// A wrapper to provide access to database backed classes in a thread-safe manner. /// </summary> /// <typeparam name="T">The databased type.</typeparam> public abstract class Live<T> : IEquatable<Live<T>> where T : class, IHasGuidPrimaryKey { public Guid ID { get; } /// <summary> /// Perform a read operation on this live object. /// </summary> /// <param name="perform">The action to perform.</param> public abstract void PerformRead([InstantHandle] Action<T> perform); /// <summary> /// Perform a read operation on this live object. /// </summary> /// <param name="perform">The action to perform.</param> public abstract TReturn PerformRead<TReturn>([InstantHandle] Func<T, TReturn> perform); /// <summary> /// Perform a write operation on this live object. /// </summary> /// <param name="perform">The action to perform.</param> public abstract void PerformWrite([InstantHandle] Action<T> perform); /// <summary> /// Whether this instance is tracking data which is managed by the database backing. /// </summary> public abstract bool IsManaged { get; } /// <summary> /// Resolve the value of this instance on the update thread. /// </summary> /// <remarks> /// After resolving, the data should not be passed between threads. /// </remarks> public abstract T Value { get; } protected Live(Guid id) { ID = id; } public bool Equals(Live<T>? other) => ID == other?.ID; public override string ToString() => PerformRead(i => i.ToString()); } }
// 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; namespace osu.Game.Database { /// <summary> /// A wrapper to provide access to database backed classes in a thread-safe manner. /// </summary> /// <typeparam name="T">The databased type.</typeparam> public abstract class Live<T> : IEquatable<Live<T>> where T : class, IHasGuidPrimaryKey { public Guid ID { get; } /// <summary> /// Perform a read operation on this live object. /// </summary> /// <param name="perform">The action to perform.</param> public abstract void PerformRead(Action<T> perform); /// <summary> /// Perform a read operation on this live object. /// </summary> /// <param name="perform">The action to perform.</param> public abstract TReturn PerformRead<TReturn>(Func<T, TReturn> perform); /// <summary> /// Perform a write operation on this live object. /// </summary> /// <param name="perform">The action to perform.</param> public abstract void PerformWrite(Action<T> perform); /// <summary> /// Whether this instance is tracking data which is managed by the database backing. /// </summary> public abstract bool IsManaged { get; } /// <summary> /// Resolve the value of this instance on the update thread. /// </summary> /// <remarks> /// After resolving, the data should not be passed between threads. /// </remarks> public abstract T Value { get; } protected Live(Guid id) { ID = id; } public bool Equals(Live<T>? other) => ID == other?.ID; public override string ToString() => PerformRead(i => i.ToString()); } }
mit
C#
ca36cad2ad65715271bbd8330acf53acadbfc306
fix behaviour
WojcikMike/docs.particular.net
samples/unit-of-work/using-childcontainers/Version_6/Sample/RavenUnitOfWork.cs
samples/unit-of-work/using-childcontainers/Version_6/Sample/RavenUnitOfWork.cs
using System; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Pipeline; using Raven.Client; #region RavenUnitOfWork class RavenUnitOfWork : Behavior<PhysicalMessageProcessingContext> { IDocumentSession session; public RavenUnitOfWork(IDocumentSession session) { this.session = session; } public override async Task Invoke(PhysicalMessageProcessingContext context, Func<Task> next) { await next(); session.SaveChanges(); } public class Registration:RegisterStep { public Registration() : base( "MyRavenDBUoW", typeof(RavenUnitOfWork), "Manages the RavenDB IDocumentSession for my handlers") { } } } #endregion
using System; using System.Threading.Tasks; using NServiceBus.Pipeline; using NServiceBus.Pipeline.Contexts; using Raven.Client; #region RavenUnitOfWork class RavenUnitOfWork : Behavior<IncomingContext> { IDocumentSession session; public RavenUnitOfWork(IDocumentSession session) { this.session = session; } public override async Task Invoke(IncomingContext context, Func<Task> next) { await next(); session.SaveChanges(); } public class Registration:RegisterStep { public Registration() : base( "MyRavenDBUoW", typeof(RavenUnitOfWork), "Manages the RavenDB IDocumentSession for my handlers") { } } } #endregion
apache-2.0
C#
51b414988ac5aec6cdd8e0ab14b2288c165b6919
change version
Poket-Jony/TS3ChromaHeadset
TS3ChromaHeadset/Properties/AssemblyInfo.cs
TS3ChromaHeadset/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("TS3ChromaHeadset")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TS3ChromaHeadset")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("34454c83-1c0c-42d5-a5fe-355677150591")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.*")] [assembly: AssemblyFileVersion("0.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("TS3ChromaHeadset")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TS3ChromaHeadset")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("34454c83-1c0c-42d5-a5fe-355677150591")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
d8591f82bdf36173158c139c95f57c7c75aabd76
bump to 1.7.2
Siliconrob/DotNetGeoJson,Terradue/DotNetGeoJson
Terradue.GeoJson/Properties/AssemblyInfo.cs
Terradue.GeoJson/Properties/AssemblyInfo.cs
/* * Copyright (C) 2010-2014 Terradue S.r.l. * * This file is part of Terradue.GeoJson. * * Foobar is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with Terradue.OpenSearch. * If not, see http://www.gnu.org/licenses/. */ /*! \namespace Terradue.GeoJson @{ Terradue .NET GeoJson Library. Initially developed to provide an easy way to manage Geometry objects with serialization and deserialization functions and transformation functions from/to GeoJson, it also supports GML, georss and Well Known Text (WKT) \xrefitem sw_version "Versions" "Software Package Version" 1.7.2 \xrefitem sw_link "Links" "Software Package List" [DotNetGeoJson](https://github.com/Terradue/DotNetGeoJson) \xrefitem sw_license "License" "Software License" [GPLv3](https://github.com/Terradue/DotNetGeoJson/blob/master/LICENSE.txt) \ingroup Data @} */ using System.Reflection; using System.Runtime.CompilerServices; using NuGet4Mono.Extensions; [assembly: AssemblyDescription("Terradue.GeoJson is a library targeting .NET 4.0 and above that provides an easy way to manage Geometry objects with serialization and deserialization functions and transformation functions from/to GeoJson, GML, georss and Well Known Text (WKT)")] [assembly: AssemblyTitle("Terradue.GeoJson")] [assembly: AssemblyCompany("Terradue")] [assembly: AssemblyProduct("Terradue.GeoJson")] [assembly: AssemblyAuthors("Emmanuel Mathot")] [assembly: AssemblyProjectUrl("https://github.com/Terradue/DotNetGeoJson")] [assembly: AssemblyLicenseUrl("https://github.com/Terradue/DotNetGeoJson/blob/master/LICENSE")] [assembly: AssemblyCopyright("Terradue")] [assembly: AssemblyVersion("1.7.2.*")] [assembly: AssemblyInformationalVersion("1.7.2")]
/* * Copyright (C) 2010-2014 Terradue S.r.l. * * This file is part of Terradue.GeoJson. * * Foobar is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with Terradue.OpenSearch. * If not, see http://www.gnu.org/licenses/. */ /*! \namespace Terradue.GeoJson @{ Terradue .NET GeoJson Library. Initially developed to provide an easy way to manage Geometry objects with serialization and deserialization functions and transformation functions from/to GeoJson, it also supports GML, georss and Well Known Text (WKT) \xrefitem sw_version "Versions" "Software Package Version" 1.7.1 \xrefitem sw_link "Links" "Software Package List" [DotNetGeoJson](https://github.com/Terradue/DotNetGeoJson) \xrefitem sw_license "License" "Software License" [GPLv3](https://github.com/Terradue/DotNetGeoJson/blob/master/LICENSE.txt) \ingroup Data @} */ using System.Reflection; using System.Runtime.CompilerServices; using NuGet4Mono.Extensions; [assembly: AssemblyDescription("Terradue.GeoJson is a library targeting .NET 4.0 and above that provides an easy way to manage Geometry objects with serialization and deserialization functions and transformation functions from/to GeoJson, GML, georss and Well Known Text (WKT)")] [assembly: AssemblyTitle("Terradue.GeoJson")] [assembly: AssemblyCompany("Terradue")] [assembly: AssemblyProduct("Terradue.GeoJson")] [assembly: AssemblyAuthors("Emmanuel Mathot")] [assembly: AssemblyProjectUrl("https://github.com/Terradue/DotNetGeoJson")] [assembly: AssemblyLicenseUrl("https://github.com/Terradue/DotNetGeoJson/blob/master/LICENSE")] [assembly: AssemblyCopyright("Terradue")] [assembly: AssemblyVersion("1.7.1.*")] [assembly: AssemblyInformationalVersion("1.7.1")]
agpl-3.0
C#
a5a13f1e5c52e306ac6a0bc9ea575e53624df4ab
Make the private field readonly.
smoogipooo/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework
osu.Framework.Android/AndroidGameView.cs
osu.Framework.Android/AndroidGameView.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using Android.Content; using Android.Runtime; using Android.Util; using osuTK.Graphics; namespace osu.Framework.Android { public class AndroidGameView : osuTK.Android.AndroidGameView { private AndroidGameHost host; private readonly Game game; public AndroidGameView(Context context, Game game) : base(context) { this.game = game; init(); } public AndroidGameView(Context context, IAttributeSet attrs) : base(context, attrs) { init(); } public AndroidGameView(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { init(); } private void init() { AutoSetContextOnRenderFrame = true; ContextRenderingApi = GLVersion.ES3; } protected override void CreateFrameBuffer() { try { base.CreateFrameBuffer(); Log.Verbose("AndroidGameView", "Successfully created the framebuffer"); } catch (Exception e) { Log.Verbose("AndroidGameView", "{0}", e); throw new Exception("Can't load egl, aborting", e); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); RenderGame(); } [STAThread] public void RenderGame() { host = new AndroidGameHost(this); host.Run(game); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using Android.Content; using Android.Runtime; using Android.Util; using osuTK.Graphics; namespace osu.Framework.Android { public class AndroidGameView : osuTK.Android.AndroidGameView { private AndroidGameHost host; private Game game; public AndroidGameView(Context context, Game game) : base(context) { this.game = game; init(); } public AndroidGameView(Context context, IAttributeSet attrs) : base(context, attrs) { init(); } public AndroidGameView(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { init(); } private void init() { AutoSetContextOnRenderFrame = true; ContextRenderingApi = GLVersion.ES3; } protected override void CreateFrameBuffer() { try { base.CreateFrameBuffer(); Log.Verbose("AndroidGameView", "Successfully created the framebuffer"); } catch (Exception e) { Log.Verbose("AndroidGameView", "{0}", e); throw new Exception("Can't load egl, aborting", e); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); RenderGame(); } [STAThread] public void RenderGame() { host = new AndroidGameHost(this); host.Run(game); } } }
mit
C#
e13c1254e5211c459c00a4a84a4a63151d66035a
make perfect incompatible with autopilot
peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu
osu.Game.Rulesets.Osu/Mods/OsuModPerfect.cs
osu.Game.Rulesets.Osu/Mods/OsuModPerfect.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. #nullable disable using System; using System.Linq; using osu.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModPerfect : ModPerfect { public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new Type[] { typeof(OsuModAutopilot) }).ToArray(); } }
// 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. #nullable disable using osu.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModPerfect : ModPerfect { } }
mit
C#
5736b7d978521ebc2010f295ee238f55b1d78356
Fix cursors sent to osu-web being potentially string formatted in incorrect culture
NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu
osu.Game/Extensions/WebRequestExtensions.cs
osu.Game/Extensions/WebRequestExtensions.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.Globalization; using Newtonsoft.Json.Linq; using osu.Framework.IO.Network; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Game.Online.API.Requests; namespace osu.Game.Extensions { public static class WebRequestExtensions { /// <summary> /// Add a pagination cursor to the web request in the format required by osu-web. /// </summary> public static void AddCursor(this WebRequest webRequest, Cursor cursor) { cursor?.Properties.ForEach(x => { webRequest.AddParameter("cursor[" + x.Key + "]", (x.Value as JValue)?.ToString(CultureInfo.InvariantCulture) ?? x.Value.ToString()); }); } } }
// 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.IO.Network; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Game.Online.API.Requests; namespace osu.Game.Extensions { public static class WebRequestExtensions { /// <summary> /// Add a pagination cursor to the web request in the format required by osu-web. /// </summary> public static void AddCursor(this WebRequest webRequest, Cursor cursor) { cursor?.Properties.ForEach(x => { webRequest.AddParameter("cursor[" + x.Key + "]", x.Value.ToString()); }); } } }
mit
C#
c6d265b7f1321438012ba37d14e2e8dcddc3c80e
replace bad regex which makes app hang when processing output from msbuild
juankakode/Drone
src/Drone/Drone.Lib/Compilers/MSBuildHelper.cs
src/Drone/Drone.Lib/Compilers/MSBuildHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Drone.Lib.Compilers { public class MSBuildHelper { public static readonly string OutputPattern = @"^(?<origin>.*)\:\s+(?<subcategory>.*)(?<category>error|warning)\s+(?<code>[a-zA-Z]+\d+)\:(?<text>.*)$"; public static readonly Regex OutputRegex = new Regex(OutputPattern, RegexOptions.Compiled | RegexOptions.Singleline); public static MSBuildOutputLevel GetOutputLevel(string data) { if (string.IsNullOrWhiteSpace(data)) return MSBuildOutputLevel.Normal; var match = OutputRegex.Match(data); if(!match.Success) return MSBuildOutputLevel.Normal; var category = match.Groups["error"].Value; if(category == "warning") return MSBuildOutputLevel.Warning; else if(category == "error") return MSBuildOutputLevel.Error; else return MSBuildOutputLevel.Normal; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Drone.Lib.Compilers { public class MSBuildHelper { public static readonly string NormalErrorPattern = @"(?<file>.*)\((?<line>\d+),(?<column>\d+)\):\s+(?<error>\w+)\s+(?<number>[\d\w]+):\s+(?<message>.*)"; public static readonly string GeneralErrorPattern = @"(?<error>.+?)\s+(?<number>[\d\w]+?):\s+(?<message>.*)"; public static readonly Regex NormalErrorRegex = new Regex(NormalErrorPattern, RegexOptions.Compiled); public static readonly Regex GeneralErrorRegex = new Regex(GeneralErrorPattern, RegexOptions.Compiled); public static MSBuildOutputLevel GetOutputLevel(string data) { if (string.IsNullOrWhiteSpace(data)) return MSBuildOutputLevel.Normal; var match = NormalErrorRegex.Match(data); if (!match.Success) { match = GeneralErrorRegex.Match(data); } if (!match.Success) return MSBuildOutputLevel.Normal; var category = match.Groups["error"].Value; if(category == "warning") return MSBuildOutputLevel.Warning; else if(category == "error") return MSBuildOutputLevel.Error; else return MSBuildOutputLevel.Normal; } } }
mit
C#
356a33a0f500fe6d632a88b056bdb1123f40f7c7
Build fix
rainersigwald/msbuild,AndyGerlicher/msbuild,mono/msbuild,AndyGerlicher/msbuild,cdmihai/msbuild,cdmihai/msbuild,rainersigwald/msbuild,cdmihai/msbuild,rainersigwald/msbuild,rainersigwald/msbuild,AndyGerlicher/msbuild,sean-gilliam/msbuild,mono/msbuild,sean-gilliam/msbuild,sean-gilliam/msbuild,AndyGerlicher/msbuild,mono/msbuild,cdmihai/msbuild,mono/msbuild,sean-gilliam/msbuild
src/Build/BackEnd/Node/RarNode.cs
src/Build/BackEnd/Node/RarNode.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.BackEnd; using Microsoft.Build.Framework; using Microsoft.Build.Internal; using Microsoft.Build.Tasks.ResolveAssemblyReferences.Server; namespace Microsoft.Build.Execution { public sealed class RarNode : INode { private readonly OutOfProcNode _msBuildNode; private Task _rarTask; //private int _rarResult; private Task _msBuildTask; private Exception shutdownException; private NodeEngineShutdownReason shutdownReason; public RarNode() { _msBuildNode = new OutOfProcNode(); } public NodeEngineShutdownReason Run(bool nodeReuse, bool lowPriority, out Exception shutdownException) { using CancellationTokenSource cts = new CancellationTokenSource(); string pipeName = CommunicationsUtilities.GetRarPipeName(nodeReuse, lowPriority); RarController controller = new RarController(pipeName); _rarTask = Task.Run(async () => /*_rarResult = */await controller.StartAsync(cts.Token).ConfigureAwait(false)); // Exits in 15 mins (by default), if don't have any active connection _msBuildTask = Task.Run(() => shutdownReason = _msBuildNode.Run(nodeReuse, lowPriority, specialNode: true, out this.shutdownException), cts.Token); Task.WaitAny(_msBuildTask, _rarTask); cts.Cancel(); shutdownException = this.shutdownException; return shutdownReason; } public NodeEngineShutdownReason Run(out Exception shutdownException) { return Run(false, false, out shutdownException); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.BackEnd; using Microsoft.Build.Internal; using Microsoft.Build.Tasks.ResolveAssemblyReferences.Server; using Microsoft.VisualStudio.Threading; namespace Microsoft.Build.Execution { public sealed class RarNode : INode { private readonly OutOfProcNode _msBuildNode; private Task _rarTask; private int _rarResult; private Task _msBuildTask; private Exception shutdownException; private NodeEngineShutdownReason shutdownReason; public RarNode() { _msBuildNode = new OutOfProcNode(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD002:Avoid problematic synchronous waits", Justification = "We need to wait for completion of async method in synchronous method (required by interface)")] public NodeEngineShutdownReason Run(bool nodeReuse, bool lowPriority, out Exception shutdownException) { var cancellationTokenSource = new CancellationTokenSource(); string pipeName = CommunicationsUtilities.GetRarPipeName(nodeReuse, lowPriority); RarController controller = new RarController(pipeName); _msBuildTask = Task.Run(() => shutdownReason = _msBuildNode.Run(nodeReuse, lowPriority, specialNode: true, out this.shutdownException), cts.Token); Task.WaitAny(_msBuildTask, _rarTask); cancellationTokenSource.Cancel(); shutdownException = this.shutdownException; return shutdownReason; } public NodeEngineShutdownReason Run(out Exception shutdownException) { return Run(false, false, out shutdownException); } } }
mit
C#
f0ae8c96bcf932ebf93877dab21917e64c552f83
change to map "Transitional" model
Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017
PhotoArtSystem/Web/PhotoArtSystem.Web/ViewModels/PhotocourseModels/PhotocourseDetailsViewModel.cs
PhotoArtSystem/Web/PhotoArtSystem.Web/ViewModels/PhotocourseModels/PhotocourseDetailsViewModel.cs
namespace PhotoArtSystem.Web.ViewModels.PhotocourseModels { using System; using System.Collections.Generic; using Data.Models.TransitionalModels; using Infrastructure.Mapping; public class PhotocourseDetailsViewModel : BaseDbKeyViewModel<Guid>, IMapFrom<PhotocourseTransitional> { public string OtherInfo { get; set; } public IEnumerable<ImageTransitional> Images { get; set; } public IEnumerable<StudentTransitional> Groups { get; set; } } }
namespace PhotoArtSystem.Web.ViewModels.PhotocourseModels { using System; using System.Collections.Generic; using Data.Models; using Data.Models.TransitionalModels; using Infrastructure.Mapping; public class PhotocourseDetailsViewModel : BaseDbKeyViewModel<Guid>, IMapFrom<Photocourse> { public string OtherInfo { get; set; } public IEnumerable<ImageTransitional> Images { get; set; } public IEnumerable<StudentTransitional> Groups { get; set; } } }
mit
C#
d0199c6fc561d35c938aad1016a569863f532a8a
fix RECS0133
icsharpcode/RefactoringEssentials,cstick/RefactoringEssentials,Rpinski/RefactoringEssentials,olathunberg/RefactoringEssentials,SSkovboiSS/RefactoringEssentials,olathunberg/RefactoringEssentials,Rpinski/RefactoringEssentials,cstick/RefactoringEssentials,icsharpcode/RefactoringEssentials,SSkovboiSS/RefactoringEssentials
RefactoringEssentials/CSharp/Diagnostics/Custom/BaseMethodParameterNameMismatchCodeFixProvider.cs
RefactoringEssentials/CSharp/Diagnostics/Custom/BaseMethodParameterNameMismatchCodeFixProvider.cs
using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Rename; namespace RefactoringEssentials.CSharp.Diagnostics { [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared] public class BaseMethodParameterNameMismatchCodeFixProvider : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(CSharpDiagnosticIDs.BaseMethodParameterNameMismatchAnalyzerID); } } public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public async override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var diagnostics = context.Diagnostics; var root = await document.GetSyntaxRootAsync(cancellationToken); var diagnostic = diagnostics.First(); var parameter = root.FindNode(context.Span); if (!parameter.IsKind(SyntaxKind.Parameter)) return; var newName = diagnostic.Descriptor.CustomTags.First(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var parameterSymbol = semanticModel.GetDeclaredSymbol(parameter, cancellationToken); var solution = document.Project.Solution; if (parameterSymbol == null || solution == null) return; context.RegisterCodeFix(CodeAction.Create($"Rename to '{newName}'", ct => Renamer.RenameSymbolAsync(solution, parameterSymbol, newName, solution.Workspace.Options, ct), CSharpDiagnosticIDs.BaseMethodParameterNameMismatchAnalyzerID), diagnostic); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeFixes; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Linq; namespace RefactoringEssentials.CSharp.Diagnostics { [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared] public class BaseMethodParameterNameMismatchCodeFixProvider : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(CSharpDiagnosticIDs.BaseMethodParameterNameMismatchAnalyzerID); } } public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public async override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var diagnostics = context.Diagnostics; var root = await document.GetSyntaxRootAsync(cancellationToken); var diagnostic = diagnostics.First(); var node = root.FindNode(context.Span); if (!node.IsKind(SyntaxKind.Parameter)) return; var renamedParameter = ((ParameterSyntax)node).WithIdentifier(SyntaxFactory.Identifier(diagnostic.Descriptor.CustomTags.First())); var newRoot = root.ReplaceNode((SyntaxNode)node, renamedParameter); context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, string.Format("Rename to '{0}'", diagnostic.Descriptor.CustomTags.First()), document.WithSyntaxRoot(newRoot)), diagnostic); } } }
mit
C#
7680635b28ba340fbc698ee40a69e8a69e8931ee
Set AssemblyInformationalVersion
rdingwall/sqlmsbuildtasks
src/SqlMsBuildTasks/Properties/AssemblyInfo.cs
src/SqlMsBuildTasks/Properties/AssemblyInfo.cs
// Copyright 2011 Richard Dingwall - http://richarddingwall.name // // 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.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("SqlMsBuildTasks")] [assembly: AssemblyDescription("MSBuild Tasks for Microsoft SQL Server")] [assembly: AssemblyProduct("SqlMsBuildTasks")] [assembly: AssemblyCopyright("Copyright © Richard Dingwall 2011")] // 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("ec5d4692-0d62-4ff1-8954-6668fd71f612")] // 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")] [assembly: AssemblyInformationalVersion("HEAD")]
// Copyright 2011 Richard Dingwall - http://richarddingwall.name // // 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.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("SqlMsBuildTasks")] [assembly: AssemblyDescription("MSBuild Tasks for Microsoft SQL Server")] [assembly: AssemblyProduct("SqlMsBuildTasks")] [assembly: AssemblyCopyright("Copyright © Richard Dingwall 2011")] // 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("ec5d4692-0d62-4ff1-8954-6668fd71f612")] // 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#
85ac938f6819e92b2b5689a34388eef97114491d
Update script of ShadowHostLayerScopeContextResolver to return single element instead of array
YevgeniyShunevych/Atata,atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata
src/Atata/ScopeSearch/ShadowHostLayerScopeContextResolver.cs
src/Atata/ScopeSearch/ShadowHostLayerScopeContextResolver.cs
using OpenQA.Selenium; namespace Atata { public class ShadowHostLayerScopeContextResolver : ILayerScopeContextResolver { private const string GetShadowRootChildElementsScript = @"if (!arguments[0].shadowRoot) { throw 'Element doesn\'t have shadowRoot value. Element: ' + arguments[0].outerHTML.replace(arguments[0].innerHTML, '...'); } var shadowChildren = arguments[0].shadowRoot.children; for (var i = 0; i < shadowChildren.length; i++) { var nodeName = shadowChildren[i].nodeName; if (nodeName !== 'STYLE' && nodeName !== 'SCRIPT') { return shadowChildren[i]; } } throw 'Element\'s shadowRoot doesn\'t contain any elements.';"; public string DefaultOuterXPath => "..//"; public ISearchContext Resolve(IWebElement element) { return (IWebElement)AtataContext.Current.Driver.ExecuteScriptWithLogging( GetShadowRootChildElementsScript, element); } } }
using System.Collections.ObjectModel; using System.Linq; using OpenQA.Selenium; namespace Atata { public class ShadowHostLayerScopeContextResolver : ILayerScopeContextResolver { private const string GetShadowRootChildElementsScript = @"if (!arguments[0].shadowRoot) { throw 'Element doesn\'t have shadowRoot value. Element: ' + arguments[0].outerHTML.replace(arguments[0].innerHTML, '...'); } var shadowChildren = arguments[0].shadowRoot.children; var filteredChildren = []; for (var i = 0; i < shadowChildren.length; i++) { var nodeName = shadowChildren[i].nodeName; if (nodeName !== 'STYLE' && nodeName !== 'SCRIPT') { filteredChildren.push(shadowChildren[i]); } } return filteredChildren;"; public string DefaultOuterXPath => "..//"; public ISearchContext Resolve(IWebElement element) { var shadowChildren = (ReadOnlyCollection<IWebElement>)AtataContext.Current.Driver.ExecuteScriptWithLogging( GetShadowRootChildElementsScript, element); return shadowChildren.First(); } } }
apache-2.0
C#
925d28acfbc0f5423fc09f87e370fdff44792d60
add MongoDbTransaction to DI
dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP
src/DotNetCore.CAP.MongoDB/CAP.MongoDBCapOptionsExtension.cs
src/DotNetCore.CAP.MongoDB/CAP.MongoDBCapOptionsExtension.cs
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using DotNetCore.CAP.Processor; using Microsoft.Extensions.DependencyInjection; namespace DotNetCore.CAP.MongoDB { // ReSharper disable once InconsistentNaming public class MongoDBCapOptionsExtension : ICapOptionsExtension { private readonly Action<MongoDBOptions> _configure; public MongoDBCapOptionsExtension(Action<MongoDBOptions> configure) { _configure = configure; } public void AddServices(IServiceCollection services) { services.AddSingleton<CapDatabaseStorageMarkerService>(); services.AddSingleton<IStorage, MongoDBStorage>(); services.AddSingleton<IStorageConnection, MongoDBStorageConnection>(); services.AddScoped<ICapPublisher, CapPublisher>(); services.AddScoped<ICallbackPublisher, CapPublisher>(); services.AddTransient<ICollectProcessor, MongoDBCollectProcessor>(); services.AddTransient<CapTransactionBase, MongoDBCapTransaction>(); var options = new MongoDBOptions(); _configure?.Invoke(options); services.AddSingleton(options); } } }
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using DotNetCore.CAP.Processor; using Microsoft.Extensions.DependencyInjection; namespace DotNetCore.CAP.MongoDB { // ReSharper disable once InconsistentNaming public class MongoDBCapOptionsExtension : ICapOptionsExtension { private readonly Action<MongoDBOptions> _configure; public MongoDBCapOptionsExtension(Action<MongoDBOptions> configure) { _configure = configure; } public void AddServices(IServiceCollection services) { services.AddSingleton<CapDatabaseStorageMarkerService>(); services.AddSingleton<IStorage, MongoDBStorage>(); services.AddSingleton<IStorageConnection, MongoDBStorageConnection>(); services.AddScoped<ICapPublisher, CapPublisher>(); services.AddScoped<ICallbackPublisher, CapPublisher>(); services.AddTransient<ICollectProcessor, MongoDBCollectProcessor>(); var options = new MongoDBOptions(); _configure?.Invoke(options); services.AddSingleton(options); } } }
mit
C#
8f4a326e681ca0cd7c35d81ba197e37e5c44c6a2
Update CreatedIssueRepository.cs
CaptiveAire/Seq.App.YouTrack
src/Seq.App.YouTrack/CreatedIssues/CreatedIssueRepository.cs
src/Seq.App.YouTrack/CreatedIssues/CreatedIssueRepository.cs
// Copyright 2014-2019 CaptiveAire Systems // // 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.Linq; using JsonFlatFileDataStore; namespace Seq.App.YouTrack.CreatedIssues { public class CreatedIssueRepository : IDisposable { readonly DataStore _dataStore; public CreatedIssueRepository(string storagePath) { this._dataStore = new DataStore(Path.Combine(storagePath, "Seq-App-YouTrack.json")); } public void Dispose() { this._dataStore?.Dispose(); } public CreatedIssueEvent Insert(CreatedIssueEvent issueEvent) { var issues = GetCreatedIssueCollection(); issues.InsertOne(issueEvent); // cleanup CleanupOldIssues(); return issueEvent; } void CleanupOldIssues() { var issues = GetCreatedIssueCollection(); issues.DeleteMany(s => s.Created < DateTime.Now.AddMonths(-1)); } public CreatedIssueEvent BySeqId(string seqId) { var issues = GetCreatedIssueCollection(); return issues.AsQueryable().FirstOrDefault(s => s.SeqId.Equals(seqId, StringComparison.OrdinalIgnoreCase)); } IDocumentCollection<CreatedIssueEvent> GetCreatedIssueCollection() { return this._dataStore.GetCollection<CreatedIssueEvent>(); } } }
// Seq.App.YouTrack - Copyright (c) 2019 CaptiveAire using System; using System.IO; using System.Linq; using JsonFlatFileDataStore; namespace Seq.App.YouTrack.CreatedIssues { public class CreatedIssueRepository : IDisposable { readonly DataStore _dataStore; public CreatedIssueRepository(string storagePath) { this._dataStore = new DataStore(Path.Combine(storagePath, "Seq-App-YouTrack.json")); } public void Dispose() { this._dataStore?.Dispose(); } public CreatedIssueEvent Insert(CreatedIssueEvent issueEvent) { var issues = GetCreatedIssueCollection(); issues.InsertOne(issueEvent); // cleanup CleanupOldIssues(); return issueEvent; } void CleanupOldIssues() { var issues = GetCreatedIssueCollection(); issues.DeleteMany(s => s.Created < DateTime.Now.AddMonths(-1)); } public CreatedIssueEvent BySeqId(string seqId) { var issues = GetCreatedIssueCollection(); return issues.AsQueryable().FirstOrDefault(s => s.SeqId.Equals(seqId, StringComparison.OrdinalIgnoreCase)); } IDocumentCollection<CreatedIssueEvent> GetCreatedIssueCollection() { return this._dataStore.GetCollection<CreatedIssueEvent>(); } } }
apache-2.0
C#
84427e5ee9b0de06a6bc808d1f8fa123cd74992d
Update AssemblyInfo.cs
WebApiContrib/WebApiContrib.Formatting.Html,WebApiContrib/WebApiContrib.Formatting.Html
src/WebApiContrib.Formatting.Html/Properties/AssemblyInfo.cs
src/WebApiContrib.Formatting.Html/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("WebApiContrib.Formatting.Html")] [assembly: AssemblyDescription("Foundational HttpMediaTypeFormatter to provide generated HTML markup from ASP.NET Web API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebApiContrib.Formatting.Html")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("99263f2c-5f64-494a-814f-bfb1743e6d66")] // 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("2.0.0")] [assembly: AssemblyFileVersion("2.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("WebApiContrib.Formatting.Html")] [assembly: AssemblyDescription("Description")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebApiContrib.Formatting.Html")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("99263f2c-5f64-494a-814f-bfb1743e6d66")] // 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("0.9.8")] [assembly: AssemblyFileVersion("0.9.8")]
mit
C#
599a2528a38490c4216de6d3433d3c73a72e7dc0
Set assembly metadata
cameronism/Cameronism.Csv
Cameronism.CSV/Properties/AssemblyInfo.cs
Cameronism.CSV/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("Cameronism.Csv")] [assembly: AssemblyDescription("CSV serializer based on expression trees")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cameron Jordan")] [assembly: AssemblyProduct("Cameronism.Csv")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("1e616db0-1e15-442f-8dad-40948d3bc203")] // 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("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.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("Cameronism.CSV")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Cameronism.CSV")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("1e616db0-1e15-442f-8dad-40948d3bc203")] // 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#
feb36326dfda6271e6e76d97e2594a1340bc5c2b
Update Tests.cs
medarchon/CodingChallenge
CodingChallenge.FamilyTree.Tests/Tests.cs
CodingChallenge.FamilyTree.Tests/Tests.cs
using Given.Common; using Given.NUnit; namespace CodingChallenge.FamilyTree.Tests { public class person_exists_in_tree : Scenario { static Person _tree; static string _result; given a_family_tree = () => _tree = FamilyTreeGenerator.Make(); when searching_the_tree_for_joes_birthday = () => _result = new Solution().GetBirthMonth(_tree, "Joe"); [then] public void the_result_should_be_january() { _result.ShouldEqual("January"); } } public class person_exists_at_the_top_tree : Scenario { static Person _tree; static string _result; given a_family_tree = () => _tree = FamilyTreeGenerator.Make(); when searching_the_tree_for_joes_birthday = () => _result = new Solution().GetBirthMonth(_tree, "Ted"); [then] public void the_result_should_be_may() { _result.ShouldEqual("May"); } } public class person_does_not_exist_in_the_tree : Scenario { static Person _tree; static string _result; given a_family_tree = () => _tree = FamilyTreeGenerator.Make(); when searching_the_tree_for_joes_birthday = () => _result = new Solution().GetBirthMonth(_tree, "Jeebus"); [then] public void the_result_should_be_empty() { _result.ShouldEqual(""); } } }
using Given.Common; using Given.NUnit; namespace CodingChallenge.FamilyTree.Tests { public class person_exists_in_tree : Scenario { static Person _tree; static string _result; given a_family_tree = () => _tree = FamilyTreeGenerator.Make(); when searching_the_tree_for_joes_birthday = () => _result = new Solution().GetBirthMonth(_tree, "Joe"); [then] public void the_result_should_be_january() { _result.ShouldEqual("January"); } } public class person_exists_at_the_top_tree : Scenario { static Person _tree; static string _result; given a_family_tree = () => _tree = FamilyTreeGenerator.Make(); when searching_the_tree_for_joes_birthday = () => _result = new Solution().GetBirthMonth(_tree, "Ted"); [then] public void the_result_should_be_may() { _result.ShouldEqual("May"); } } public class person_does_not_exist_in_the_tree : Scenario { static Person _tree; static string _result; given a_family_tree = () => _tree = FamilyTreeGenerator.Make(); when searching_the_tree_for_joes_birthday = () => _result = new Solution().GetBirthMonth(_tree, "Jeebus"); [then] public void the_result_should_be_may() { _result.ShouldEqual(""); } } }
mit
C#
34cbb0d9f9a673ebc2f422c1a7a8f27d8bdd077d
Update ObservableExtensions.cs
keith-hall/Extensions,keith-hall/Extensions
src/ObservableExtensions.cs
src/ObservableExtensions.cs
using System; using System.Reactive.Linq; namespace HallLibrary.Extensions { /// <summary> /// Contains extension methods for working with observables. /// </summary> public static class ObservableExtensions { /// <summary> /// Returns the current value of an observable with the previous value. /// </summary> /// <typeparam name="TSource">The source type.</typeparam> /// <typeparam name="TOutput">The output type after the <paramref name="projection" /> has been applied.</typeparam> /// <param name="source">The observable.</param> /// <param name="projection">The projection to apply.</param> /// <returns>The current observable value with the previous value.</returns> public static IObservable<TOutput> WithPrevious<TSource, TOutput>(this IObservable<TSource> source, Func<TSource, TSource, TOutput> projection) { // http://www.zerobugbuild.com/?p=213 return source.Scan(Tuple.Create(default(TSource), default(TSource)), (previous, current) => Tuple.Create(previous.Item2, current)) .Select(t => projection(t.Item1, t.Item2)); } /// <summary> /// Ensure that the subscription to the <paramref name="observable" /> is re-subscribed to on error. /// </summary> /// <typeparam name="T">The type of data the observable contains.</typeparam> /// <param name="observable">The observable to re-subscribe to on error.</param> /// <param name="onNext">Action to invoke for each element in the <paramref name="observable" /> sequence.</param> /// <param name="onError">Action to invoke for each error that occurs in the <paramref name="observable" /> sequence.</param> public static void ReSubscribeOnError<T> (this IObservable<T> observable, Action<T> onNext, Action<Exception> onError = null) { Action sub = null; sub = () => observable.Subscribe(onNext, ex => { if (onError != null) onError(ex); sub(); }); sub(); } } }
using System; using System.Reactive.Linq; namespace HallLibrary.Extensions { /// <summary> /// Contains extension methods for working with observables. /// </summary> public static class ObservableExtensions { /// <summary> /// Returns the current value of an observable with the previous value. /// </summary> /// <typeparam name="TSource">The source type.</typeparam> /// <typeparam name="TOutput">The output type after the <paramref name="projection" /> has been applied.</typeparam> /// <param name="source">The observable.</param> /// <param name="projection">The projection to apply.</param> /// <returns>The current observable value with the previous value.</returns> public static IObservable<TOutput> WithPrevious<TSource, TOutput>(this IObservable<TSource> source, Func<TSource, TSource, TOutput> projection) { // http://www.zerobugbuild.com/?p=213 return source.Scan(Tuple.Create(default(TSource), default(TSource)), (previous, current) => Tuple.Create(previous.Item2, current)) .Select(t => projection(t.Item1, t.Item2)); } } }
apache-2.0
C#
1b4568edbead2beda09b782a25b3818392522e80
add UIHint for symmetric key
rfavillejr/Thinktecture.IdentityServer.v2,kjnilsson/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,rfavillejr/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,kjnilsson/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,kjnilsson/Thinktecture.IdentityServer.v2
src/Libraries/Thinktecture.IdentityServer.Core/Models/Configuration/AdfsIntegrationConfiguration.cs
src/Libraries/Thinktecture.IdentityServer.Core/Models/Configuration/AdfsIntegrationConfiguration.cs
/* * Copyright (c) Dominick Baier, Brock Allen. All rights reserved. * see license.txt */ using System; using System.ComponentModel.DataAnnotations; using System.Security.Cryptography.X509Certificates; namespace Thinktecture.IdentityServer.Models.Configuration { public class AdfsIntegrationConfiguration : ProtocolConfiguration { // general settings - authentication [Display(Name = "Enable username/password authentication", Description = "Enables the OAuth2 to ADFS authentication bridge")] public bool AuthenticationEnabled { get; set; } [Display(Name = "Pass-through authentication token", Description = "If enabled, the original token from ADFS will be passed back")] public bool PassThruAuthenticationToken { get; set; } [Display(Name = "Lifetime of the authentication token", Description = "Specifies the lifetime of the authentication token (in minutes)")] public int AuthenticationTokenLifetime { get; set; } // general settings - federation [Display(Name = "Enable delegation", Description = "Enables the OAuth2 to ADFS delegation bridge")] public bool FederationEnabled { get; set; } [Display(Name = "Pass-through delegation token", Description = "If enabled, the original token from ADFS will be passed back")] public bool PassThruFederationToken { get; set; } [Display(Name = "Lifetime of the delegation token", Description = "Specifies the lifetime of the delegation token (in minutes)")] public int FederationTokenLifetime { get; set; } // general settings [Display(Name = "Symmetric signing key", Description = "The symmetric singing key for the newly created token, empty if you want to use the default signing key")] [UIHint("SymmetricKey")] public string SymmetricSigningKey { get; set; } // adfs settings [Display(Name = "ADFS UserName Endpoint", Description = "Address of the ADFS UserNameMixed endoint.")] public string UserNameAuthenticationEndpoint { get; set; } [Display(Name = "ADFS Delegation Endpoint", Description = "Address of the ADFS federation endpoint (mixed/symmetric/basic256).")] public string FederationEndpoint { get; set; } [Display(Name = "ADFS Signing Certificate Thumbprint", Description = "Thumbprint of the ADFS signing certificate.")] public string IssuerThumbprint { get; set; } [Display(Name = "ADFS Issuer URI", Description = "ADFS Issuer URI")] public string IssuerUri { get; set; } [Display(Name = "ADFS Encryption certificate", Description = "ADFS Issuer URI")] public X509Certificate2 EncryptionCertificate { get; set; } } }
/* * Copyright (c) Dominick Baier, Brock Allen. All rights reserved. * see license.txt */ using System; using System.ComponentModel.DataAnnotations; using System.Security.Cryptography.X509Certificates; namespace Thinktecture.IdentityServer.Models.Configuration { public class AdfsIntegrationConfiguration : ProtocolConfiguration { // general settings - authentication [Display(Name = "Enable username/password authentication", Description = "Enables the OAuth2 to ADFS authentication bridge")] public bool AuthenticationEnabled { get; set; } [Display(Name = "Pass-through authentication token", Description = "If enabled, the original token from ADFS will be passed back")] public bool PassThruAuthenticationToken { get; set; } [Display(Name = "Lifetime of the authentication token", Description = "Specifies the lifetime of the authentication token (in minutes)")] public int AuthenticationTokenLifetime { get; set; } // general settings - federation [Display(Name = "Enable delegation", Description = "Enables the OAuth2 to ADFS delegation bridge")] public bool FederationEnabled { get; set; } [Display(Name = "Pass-through delegation token", Description = "If enabled, the original token from ADFS will be passed back")] public bool PassThruFederationToken { get; set; } [Display(Name = "Lifetime of the delegation token", Description = "Specifies the lifetime of the delegation token (in minutes)")] public int FederationTokenLifetime { get; set; } // general settings [Display(Name = "Symmetric signing key", Description = "The symmetric singing key for the newly created token, empty if you want to use the default signing key")] public string SymmetricSigningKey { get; set; } // adfs settings [Display(Name = "ADFS UserName Endpoint", Description = "Address of the ADFS UserNameMixed endoint.")] public string UserNameAuthenticationEndpoint { get; set; } [Display(Name = "ADFS Delegation Endpoint", Description = "Address of the ADFS federation endpoint (mixed/symmetric/basic256).")] public string FederationEndpoint { get; set; } [Display(Name = "ADFS Signing Certificate Thumbprint", Description = "Thumbprint of the ADFS signing certificate.")] public string IssuerThumbprint { get; set; } [Display(Name = "ADFS Issuer URI", Description = "ADFS Issuer URI")] public string IssuerUri { get; set; } [Display(Name = "ADFS Encryption certificate", Description = "ADFS Issuer URI")] public X509Certificate2 EncryptionCertificate { get; set; } } }
bsd-3-clause
C#
a1ba1f0f862f37910944f6cfe49bd3fb9fb6c431
Add more diagnostics to FileThumbPrint
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNetCore.Razor.Design.Test/IntegrationTests/FIleThumbPrint.cs
test/Microsoft.AspNetCore.Razor.Design.Test/IntegrationTests/FIleThumbPrint.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.IO; using System.Security.Cryptography; namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests { public class FileThumbPrint : IEquatable<FileThumbPrint> { private FileThumbPrint(string path, DateTime lastWriteTimeUtc, string hash) { Path = path; LastWriteTimeUtc = lastWriteTimeUtc; Hash = hash; } public string Path { get; } public DateTime LastWriteTimeUtc { get; } public string Hash { get; } public static FileThumbPrint Create(string path) { byte[] hashBytes; using (var sha1 = SHA1.Create()) using (var fileStream = File.OpenRead(path)) { hashBytes = sha1.ComputeHash(fileStream); } var hash = Convert.ToBase64String(hashBytes); var lastWriteTimeUtc = File.GetLastWriteTimeUtc(path); return new FileThumbPrint(path, lastWriteTimeUtc, hash); } public bool Equals(FileThumbPrint other) { return string.Equals(Path, other.Path, StringComparison.Ordinal) && LastWriteTimeUtc == other.LastWriteTimeUtc && string.Equals(Hash, other.Hash, StringComparison.Ordinal); } public override int GetHashCode() => LastWriteTimeUtc.GetHashCode(); } }
// 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.IO; using System.Security.Cryptography; namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests { public class FileThumbPrint : IEquatable<FileThumbPrint> { private FileThumbPrint(DateTime lastWriteTimeUtc, string hash) { LastWriteTimeUtc = lastWriteTimeUtc; Hash = hash; } public DateTime LastWriteTimeUtc { get; } public string Hash { get; } public static FileThumbPrint Create(string path) { byte[] hashBytes; using (var sha1 = SHA1.Create()) using (var fileStream = File.OpenRead(path)) { hashBytes = sha1.ComputeHash(fileStream); } var hash = Convert.ToBase64String(hashBytes); var lastWriteTimeUtc = File.GetLastWriteTimeUtc(path); return new FileThumbPrint(lastWriteTimeUtc, hash); } public bool Equals(FileThumbPrint other) { return LastWriteTimeUtc == other.LastWriteTimeUtc && string.Equals(Hash, other.Hash, StringComparison.Ordinal); } public override int GetHashCode() => LastWriteTimeUtc.GetHashCode(); } }
apache-2.0
C#
b272559b285d87393beeeb918f7e87ad8feb95f6
Fix broken implementation of static HttpClient
stevejgordon/allReady,dpaquette/allReady,mipre100/allReady,arst/allReady,mipre100/allReady,bcbeatty/allReady,mgmccarthy/allReady,bcbeatty/allReady,c0g1t8/allReady,stevejgordon/allReady,GProulx/allReady,mipre100/allReady,arst/allReady,jonatwabash/allReady,gitChuckD/allReady,anobleperson/allReady,HamidMosalla/allReady,mgmccarthy/allReady,dpaquette/allReady,binaryjanitor/allReady,BillWagner/allReady,VishalMadhvani/allReady,BillWagner/allReady,VishalMadhvani/allReady,chinwobble/allReady,mipre100/allReady,anobleperson/allReady,chinwobble/allReady,binaryjanitor/allReady,MisterJames/allReady,mgmccarthy/allReady,GProulx/allReady,HTBox/allReady,dpaquette/allReady,BillWagner/allReady,HamidMosalla/allReady,c0g1t8/allReady,GProulx/allReady,BillWagner/allReady,arst/allReady,jonatwabash/allReady,HTBox/allReady,arst/allReady,stevejgordon/allReady,bcbeatty/allReady,chinwobble/allReady,VishalMadhvani/allReady,mgmccarthy/allReady,MisterJames/allReady,binaryjanitor/allReady,c0g1t8/allReady,anobleperson/allReady,stevejgordon/allReady,c0g1t8/allReady,jonatwabash/allReady,HamidMosalla/allReady,bcbeatty/allReady,gitChuckD/allReady,anobleperson/allReady,GProulx/allReady,dpaquette/allReady,jonatwabash/allReady,MisterJames/allReady,gitChuckD/allReady,MisterJames/allReady,chinwobble/allReady,HTBox/allReady,HamidMosalla/allReady,binaryjanitor/allReady,gitChuckD/allReady,VishalMadhvani/allReady,HTBox/allReady
AllReadyApp/Web-App/AllReady/Hangfire/Jobs/SendRequestStatusToGetASmokeAlarm.cs
AllReadyApp/Web-App/AllReady/Hangfire/Jobs/SendRequestStatusToGetASmokeAlarm.cs
using System; using System.Net.Http; using System.Net.Http.Headers; using Microsoft.Extensions.Options; namespace AllReady.Hangfire.Jobs { public class SendRequestStatusToGetASmokeAlarm : ISendRequestStatusToGetASmokeAlarm { private static HttpClient httpClient; public SendRequestStatusToGetASmokeAlarm(IOptions<GetASmokeAlarmApiSettings> getASmokeAlarmApiSettings) { CreateStaticHttpClient(getASmokeAlarmApiSettings); } public void Send(string serial, string status, bool acceptance) { var updateRequestMessage = new { acceptance, status }; var response = httpClient.PostAsJsonAsync($"admin/requests/status/{serial}", updateRequestMessage).Result; //throw HttpRequestException if response is not a success code. response.EnsureSuccessStatusCode(); } private void CreateStaticHttpClient(IOptions<GetASmokeAlarmApiSettings> getASmokeAlarmApiSettings) { if (httpClient == null) { httpClient = new HttpClient { BaseAddress = new Uri(getASmokeAlarmApiSettings.Value.BaseAddress)}; httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //TODO mgmccarthy: the one drawback here is if GASA were to give us a new authorization token, we'd have to reload the web app to get it to update b/c this is now static httpClient.DefaultRequestHeaders.Add("Authorization", getASmokeAlarmApiSettings.Value.Token); } } } public interface ISendRequestStatusToGetASmokeAlarm { void Send(string serial, string status, bool acceptance); } }
using System; using System.Net.Http; using System.Net.Http.Headers; using Microsoft.Extensions.Options; namespace AllReady.Hangfire.Jobs { public class SendRequestStatusToGetASmokeAlarm : ISendRequestStatusToGetASmokeAlarm { private readonly IOptions<GetASmokeAlarmApiSettings> getASmokeAlarmApiSettings; private static readonly HttpClient HttpClient = new HttpClient(); public SendRequestStatusToGetASmokeAlarm(IOptions<GetASmokeAlarmApiSettings> getASmokeAlarmApiSettings) { this.getASmokeAlarmApiSettings = getASmokeAlarmApiSettings; } public void Send(string serial, string status, bool acceptance) { var baseAddress = getASmokeAlarmApiSettings.Value.BaseAddress; var token = getASmokeAlarmApiSettings.Value.Token; var updateRequestMessage = new { acceptance, status }; HttpClient.BaseAddress = new Uri(baseAddress); HttpClient.DefaultRequestHeaders.Accept.Clear(); HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpClient.DefaultRequestHeaders.Add("Authorization", token); var response = HttpClient.PostAsJsonAsync($"admin/requests/status/{serial}", updateRequestMessage).Result; //throw HttpRequestException if response is not a success code. response.EnsureSuccessStatusCode(); } } public interface ISendRequestStatusToGetASmokeAlarm { void Send(string serial, string status, bool acceptance); } }
mit
C#
9f13880f91a743a1f07446593763d56391550c36
Remove unnecessary constructor
aspnetboilerplate/sample-odata,aspnetboilerplate/sample-odata,aspnetboilerplate/sample-odata
AbpODataDemo-Core-vNext/aspnet-core/src/AbpODataDemo.Web.Host/ResultWrapping/ODataWrapResultFilter.cs
AbpODataDemo-Core-vNext/aspnet-core/src/AbpODataDemo.Web.Host/ResultWrapping/ODataWrapResultFilter.cs
using Abp.Web.Results.Filters; using System; namespace AbpODataDemo.ResultWrapping { public class ODataWrapResultFilter : IWrapResultFilter { public bool HasFilterForWrapOnError(string url, out bool wrapOnError) { wrapOnError = false; return new Uri(url).AbsolutePath.StartsWith("/odata", StringComparison.InvariantCultureIgnoreCase); } public bool HasFilterForWrapOnSuccess(string url, out bool wrapOnSuccess) { wrapOnSuccess = false; return new Uri(url).AbsolutePath.StartsWith("/odata", StringComparison.InvariantCultureIgnoreCase); } } }
using Abp.Web.Results.Filters; using System; namespace AbpODataDemo.ResultWrapping { public class ODataWrapResultFilter : IWrapResultFilter { public ODataWrapResultFilter() { } public bool HasFilterForWrapOnError(string url, out bool wrapOnError) { wrapOnError = false; return new Uri(url).AbsolutePath.StartsWith("/odata", StringComparison.InvariantCultureIgnoreCase); } public bool HasFilterForWrapOnSuccess(string url, out bool wrapOnSuccess) { wrapOnSuccess = false; return new Uri(url).AbsolutePath.StartsWith("/odata", StringComparison.InvariantCultureIgnoreCase); } } }
mit
C#
f7dcef9e09085289ac24f343b0e52867c8144153
Add comment
dsharlet/LiveSPICE
LiveSPICE/Controls/Scope/SignalDisplay.cs
LiveSPICE/Controls/Scope/SignalDisplay.cs
using System; using System.ComponentModel; using System.Threading; using System.Windows; using System.Windows.Controls; namespace LiveSPICE { public class SignalDisplay : Control, INotifyPropertyChanged { static SignalDisplay() { DefaultStyleKeyProperty.OverrideMetadata(typeof(SignalDisplay), new FrameworkPropertyMetadata(typeof(SignalDisplay))); } protected SignalCollection signals = new SignalCollection(); public SignalCollection Signals { get { return signals; } set { signals = value; InvalidateVisual(); NotifyChanged("Signals"); } } private System.Timers.Timer refreshTimer; public SignalDisplay() { refreshTimer = new System.Timers.Timer() { Interval = 16, // 60 Hz AutoReset = true, Enabled = true, }; refreshTimer.Elapsed += (o, e) => Dispatcher.InvokeAsync(() => InvalidateVisual(), System.Windows.Threading.DispatcherPriority.ApplicationIdle); refreshTimer.Start(); } private Signal selected; public Signal SelectedSignal { get { return selected; } set { selected = value; NotifyChanged("SelectedSignal"); } } public void Clear() { signals.Clear(); InvalidateVisual(); } // INotifyPropertyChanged interface. protected void NotifyChanged(string p) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(p)); } public event PropertyChangedEventHandler PropertyChanged; } }
using System; using System.ComponentModel; using System.Threading; using System.Windows; using System.Windows.Controls; namespace LiveSPICE { public class SignalDisplay : Control, INotifyPropertyChanged { static SignalDisplay() { DefaultStyleKeyProperty.OverrideMetadata(typeof(SignalDisplay), new FrameworkPropertyMetadata(typeof(SignalDisplay))); } protected SignalCollection signals = new SignalCollection(); public SignalCollection Signals { get { return signals; } set { signals = value; InvalidateVisual(); NotifyChanged("Signals"); } } private System.Timers.Timer refreshTimer; public SignalDisplay() { refreshTimer = new System.Timers.Timer() { Interval = 16, AutoReset = true, Enabled = true, }; refreshTimer.Elapsed += (o, e) => Dispatcher.InvokeAsync(() => InvalidateVisual(), System.Windows.Threading.DispatcherPriority.ApplicationIdle); refreshTimer.Start(); } private Signal selected; public Signal SelectedSignal { get { return selected; } set { selected = value; NotifyChanged("SelectedSignal"); } } public void Clear() { signals.Clear(); InvalidateVisual(); } // INotifyPropertyChanged interface. protected void NotifyChanged(string p) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(p)); } public event PropertyChangedEventHandler PropertyChanged; } }
mit
C#
3a0e777837cc44a658cf0423e4797955791ef7df
reset port num in authorize controller
solomobro/Instagram,solomobro/Instagram,solomobro/Instagram
src/Solomobro.Instagram.WebApiDemo/Controllers/AuthorizeController.cs
src/Solomobro.Instagram.WebApiDemo/Controllers/AuthorizeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Results; using Solomobro.Instagram.WebApiDemo.Settings; namespace Solomobro.Instagram.WebApiDemo.Controllers { public class AuthorizeController : ApiController { [HttpGet] [Route("api/login")] public IHttpActionResult GetLoginUri(HttpRequestMessage req) { var auth = GetInstagramAuthenticator(); return Ok(auth.AuthenticationUri); } [HttpGet] [Route("api/authorize")] public async Task<IHttpActionResult> AuthorizeAsync(HttpRequestMessage req) { try { var uri = req.RequestUri; var auth = GetInstagramAuthenticator(); var result = await auth.ValidateAuthenticationAsync(uri); if (result.Success) { return Redirect("http://localhost:56841/LoggedIn.html"); } else { return Redirect("http://localhost:56841/Failed.html"); } } catch (Exception) { return Redirect("http://localhost:56841/Failed.html"); } } private OAuth GetInstagramAuthenticator() { return new OAuth(AuthSettings.InstaClientID, AuthSettings.InstaClientSecret, AuthSettings.InstaRedirectUrl, AuthenticationMethod.Implicit); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Results; using Solomobro.Instagram.WebApiDemo.Settings; namespace Solomobro.Instagram.WebApiDemo.Controllers { public class AuthorizeController : ApiController { [HttpGet] [Route("api/login")] public IHttpActionResult GetLoginUri(HttpRequestMessage req) { var auth = GetInstagramAuthenticator(); return Ok(auth.AuthenticationUri); } [HttpGet] [Route("api/authorize")] public async Task<IHttpActionResult> AuthorizeAsync(HttpRequestMessage req) { try { var uri = req.RequestUri; var auth = GetInstagramAuthenticator(); var result = await auth.ValidateAuthenticationAsync(uri); if (result.Success) { return Redirect("http://localhost:8012/LoggedIn.html"); } else { return Redirect("http://localhost:8012/Failed.html"); } } catch (Exception) { return Redirect("http://localhost:8012/Failed.html"); } } private OAuth GetInstagramAuthenticator() { return new OAuth(AuthSettings.InstaClientID, AuthSettings.InstaClientSecret, AuthSettings.InstaRedirectUrl, AuthenticationMethod.Implicit); } } }
apache-2.0
C#
7d3afd5da7a5cad356a3f485810c16d5ce997548
Update SimpleBinaryBondDeserializer.cs
tiksn/TIKSN-Framework
TIKSN.Core/Serialization/Bond/SimpleBinaryBondDeserializer.cs
TIKSN.Core/Serialization/Bond/SimpleBinaryBondDeserializer.cs
using Bond.IO.Safe; using Bond.Protocols; namespace TIKSN.Serialization.Bond { public class SimpleBinaryBondDeserializer : DeserializerBase<byte[]> { protected override T DeserializeInternal<T>(byte[] serial) { var input = new InputBuffer(serial); var reader = new SimpleBinaryReader<InputBuffer>(input); return global::Bond.Deserialize<T>.From(reader); } } }
using Bond.IO.Safe; using Bond.Protocols; namespace TIKSN.Serialization.Bond { public class SimpleBinaryBondDeserializer : DeserializerBase<byte[]> { protected override T DeserializeInternal<T>(byte[] serial) { var input = new InputBuffer(serial); var reader = new SimpleBinaryReader<InputBuffer>(input); return global::Bond.Deserialize<T>.From(reader); } } }
mit
C#
786935e4bcfee46fd23d2d16486d2e1baab952b6
Fix default icon path when add new web search
Megasware128/Wox,JohnTheGr8/Wox,jondaniels/Wox,zlphoenix/Wox,yozora-hitagi/Saber,danisein/Wox,Launchify/Launchify,danisein/Wox,JohnTheGr8/Wox,medoni/Wox,zlphoenix/Wox,Launchify/Launchify,yozora-hitagi/Saber,jondaniels/Wox,medoni/Wox,Megasware128/Wox
Plugins/Wox.Plugin.WebSearch/WebSearch.cs
Plugins/Wox.Plugin.WebSearch/WebSearch.cs
using System.IO; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Wox.Plugin.WebSearch { public class WebSearch { public const string DefaultIcon = "web_search.png"; public string Title { get; set; } public string ActionKeyword { get; set; } [NotNull] private string _icon = DefaultIcon; [NotNull] public string Icon { get { return _icon; } set { _icon = value; IconPath = Path.Combine(WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, value); } } /// <summary> /// All icon should be put under Images directory /// </summary> [NotNull] [JsonIgnore] internal string IconPath { get; private set; } = Path.Combine ( WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, DefaultIcon ); public string Url { get; set; } public bool Enabled { get; set; } } }
using System.IO; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Wox.Plugin.WebSearch { public class WebSearch { public const string DefaultIcon = "web_search.png"; public string Title { get; set; } public string ActionKeyword { get; set; } [NotNull] private string _icon = DefaultIcon; [NotNull] public string Icon { get { return _icon; } set { _icon = value; IconPath = Path.Combine(WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, value); } } /// <summary> /// All icon should be put under Images directory /// </summary> [NotNull] [JsonIgnore] internal string IconPath { get; private set; } public string Url { get; set; } public bool Enabled { get; set; } } }
mit
C#
6bf6f60a05032c4ef01659e7b96ece1e4896f212
Update 'CmDdsPatchSiteNameValidator' success message
Sitecore/Sitecore-Instance-Manager
src/SIM.Sitecore9Installer/Validation/Validators/CmDdsPatchSiteNameValidator.cs
src/SIM.Sitecore9Installer/Validation/Validators/CmDdsPatchSiteNameValidator.cs
using System; using System.Collections.Generic; using System.Linq; using SIM.Sitecore9Installer.Tasks; namespace SIM.Sitecore9Installer.Validation.Validators { public class CmDdsPatchSiteNameValidator : IValidator { protected virtual string DdsPatchValidationResultMessage => "Value of the '{0}' parameter differs in the '{1}' and '{2}' tasks. To fix: set the same value for each mentioned task in Advanced installation parameters."; public Dictionary<string, string> Data { get; set; } public virtual string SuccessMessage => "'SiteName' value was set properly for 'sitecore-xp1-cm' and 'sitecore-XP1-cm-dds-patch' installation tasks."; public CmDdsPatchSiteNameValidator() { this.Data = new Dictionary<string, string>(); } public IEnumerable<ValidationResult> Evaluate(IEnumerable<Task> tasks) { string sitecoreXp1Cm = this.Data["SitecoreXp1Cm"]; string sitecoreXp1CmDdsPatch = this.Data["SitecoreXp1CmDdsPatch"]; string siteName = this.Data["SiteName"]; bool errors = false; Task cmTask = tasks.FirstOrDefault(t => t.Name.Equals(sitecoreXp1Cm, StringComparison.InvariantCultureIgnoreCase) && t.LocalParams.Any(p => p.Name.Equals(siteName, StringComparison.InvariantCultureIgnoreCase))); if (cmTask != null) { Task ddsPatchTask = tasks.FirstOrDefault(t => t.Name.Equals(sitecoreXp1CmDdsPatch, StringComparison.InvariantCultureIgnoreCase) && t.LocalParams.Any(p => p.Name.Equals(siteName, StringComparison.InvariantCultureIgnoreCase))); if (ddsPatchTask != null) { string cmSiteName = cmTask.LocalParams.Single(p => p.Name.Equals(siteName, StringComparison.InvariantCultureIgnoreCase)).Value; string ddsPatchSiteName = ddsPatchTask.LocalParams.Single(p => p.Name.Equals(siteName, StringComparison.InvariantCultureIgnoreCase)).Value; if (!cmSiteName.Equals(ddsPatchSiteName, StringComparison.InvariantCultureIgnoreCase)) { errors = true; yield return new ValidationResult(ValidatorState.Error, string.Format(DdsPatchValidationResultMessage, siteName, cmTask.Name, ddsPatchTask.Name), null); } } } if (!errors) { yield return new ValidationResult(ValidatorState.Success, this.SuccessMessage, null); } } } }
using System; using System.Collections.Generic; using System.Linq; using SIM.Sitecore9Installer.Tasks; namespace SIM.Sitecore9Installer.Validation.Validators { public class CmDdsPatchSiteNameValidator : IValidator { protected virtual string DdsPatchValidationResultMessage => "Value of the '{0}' parameter differs in the '{1}' and '{2}' tasks. To fix: set the same value for each mentioned task in Advanced installation parameters."; public Dictionary<string, string> Data { get; set; } public virtual string SuccessMessage => "'SiteName' value was set properly for 'cm-dds-patch' installation task."; public CmDdsPatchSiteNameValidator() { this.Data = new Dictionary<string, string>(); } public IEnumerable<ValidationResult> Evaluate(IEnumerable<Task> tasks) { string sitecoreXp1Cm = this.Data["SitecoreXp1Cm"]; string sitecoreXp1CmDdsPatch = this.Data["SitecoreXp1CmDdsPatch"]; string siteName = this.Data["SiteName"]; bool errors = false; Task cmTask = tasks.FirstOrDefault(t => t.Name.Equals(sitecoreXp1Cm, StringComparison.InvariantCultureIgnoreCase) && t.LocalParams.Any(p => p.Name.Equals(siteName, StringComparison.InvariantCultureIgnoreCase))); if (cmTask != null) { Task ddsPatchTask = tasks.FirstOrDefault(t => t.Name.Equals(sitecoreXp1CmDdsPatch, StringComparison.InvariantCultureIgnoreCase) && t.LocalParams.Any(p => p.Name.Equals(siteName, StringComparison.InvariantCultureIgnoreCase))); if (ddsPatchTask != null) { string cmSiteName = cmTask.LocalParams.Single(p => p.Name.Equals(siteName, StringComparison.InvariantCultureIgnoreCase)).Value; string ddsPatchSiteName = ddsPatchTask.LocalParams.Single(p => p.Name.Equals(siteName, StringComparison.InvariantCultureIgnoreCase)).Value; if (!cmSiteName.Equals(ddsPatchSiteName, StringComparison.InvariantCultureIgnoreCase)) { errors = true; yield return new ValidationResult(ValidatorState.Error, string.Format(DdsPatchValidationResultMessage, siteName, cmTask.Name, ddsPatchTask.Name), null); } } } if (!errors) { yield return new ValidationResult(ValidatorState.Success, this.SuccessMessage, null); } } } }
mit
C#
6cad7301d4dbbdd759c813fc16fbacf35979a645
Update ConfigReader.cs
AnkRaiza/cordova-plugin-config-reader,AnkRaiza/cordova-plugin-config-reader,AnkRaiza/cordova-plugin-config-reader
src/wp8/ConfigReader.cs
src/wp8/ConfigReader.cs
using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Microsoft.Phone.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; using Windows.Storage; using System.Diagnostics; using System.IO; using System.IO.IsolatedStorage; namespace WPCordovaClassLib.Cordova.Commands { public class ConfigReader : BaseCommand { public void get(string options) { string[] args = JSON.JsonHelper.Deserialize<string[]>(options); string preferenceName = args[0]; try { // Get the pref. IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings; if (!appSettings.Contains("googleAnalyticsId")) { appSettings.Add("googleAnalyticsId", "Y2bIJ376+2iNg4wlmYlyLAgI64J0QgjaofaOP1JNTY8="); appSettings.Add("raygunId", "2z3Tj0FuQwsqyt1RahR5xogLA1vGeL7IwMdv+6Pxoj9jOFPCpdKD69HlRUc6U4Jg"); appSettings.Add("llave", "0123456789abcdef"); appSettings.Add("salt", "fedcba9876543210"); appSettings.Save(); } string val = (string)appSettings[preferenceName]; DispatchCommandResult(new PluginResult(PluginResult.Status.OK, val)); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), "error"); } } } }
using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Microsoft.Phone.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; using Windows.Storage; using System.Diagnostics; using System.IO; using System.IO.IsolatedStorage; namespace WPCordovaClassLib.Cordova.Commands { public class ConfigReader : BaseCommand { public void get(string options) { string[] args = JSON.JsonHelper.Deserialize<string[]>(options); string preferenceName = args[0]; try { // Get the pref. IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings; string val = (string)appSettings[preferenceName]; DispatchCommandResult(new PluginResult(PluginResult.Status.OK, val)); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), "error"); } } } }
mit
C#
2ce5d80003c0c6bf241d0ea257576e57cb183228
Add better validation of command line arguments (#22)
GoogleCloudPlatform/google-cloud-dotnet-debugger,GoogleCloudPlatform/google-cloud-dotnet-debugger,GoogleCloudPlatform/google-cloud-dotnet-debugger,GoogleCloudPlatform/google-cloud-dotnet-debugger
Google.Cloud.Diagnostics.Debug/Google.Cloud.Diagnostics.Debug/DebugletOptions.cs
Google.Cloud.Diagnostics.Debug/Google.Cloud.Diagnostics.Debug/DebugletOptions.cs
// Copyright 2015-2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using CommandLine; using Google.Api.Gax; using System.IO; namespace Google.Cloud.Diagnostics.Debug { /// <summary> /// Options for starting a <see cref="Debuglet"/>. /// </summary> internal class DebugletOptions { [Option("module", Required = true, HelpText = "The name of the application to debug.")] public string Module { get; set; } [Option("version", Required = true, HelpText = "The version of the application to debug.")] public string Version { get; set; } [Option("debugger", Required = true, HelpText = "A path to the debugger to use.")] public string Debugger { get; set; } [Option("process-id", Required = true, HelpText = "The id of the process to debug.")] public string ProcessId { get; set; } [Option("project-id", HelpText = "The Google Cloud Console project the debuggee is associated with")] public string ProjectId { get; set; } [Option("wait-time", Default = 2, HelpText = "The amount of time to wait before checking for new breakpoints in seconds.")] public int WaitTime { get; set; } /// <summary> /// Parse a <see cref="DebugletOptions"/> from command line arguments. /// </summary> public static DebugletOptions Parse(string[] args) { var result = Parser.Default.ParseArguments<DebugletOptions>(args); var options = new DebugletOptions(); result.WithParsed((o) => { GaxPreconditions.CheckNotNullOrEmpty(o.Module, nameof(o.Module)); GaxPreconditions.CheckNotNullOrEmpty(o.Version, nameof(o.Version)); GaxPreconditions.CheckNotNullOrEmpty(o.Debugger, nameof(o.Debugger)); GaxPreconditions.CheckNotNullOrEmpty(o.ProcessId, nameof(o.ProcessId)); GaxPreconditions.CheckNotNullOrEmpty(o.ProjectId, nameof(o.ProjectId)); GaxPreconditions.CheckArgumentRange(o.WaitTime, nameof(o.WaitTime), 0, int.MaxValue); if (!File.Exists(o.Debugger)) { throw new FileNotFoundException($"Debugger file not found: '{o.Debugger}'"); } options = o; }); return options; } } }
// Copyright 2015-2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using CommandLine; namespace Google.Cloud.Diagnostics.Debug { /// <summary> /// Options for starting a <see cref="Debuglet"/>. /// </summary> internal class DebugletOptions { [Option("module", Required = true, HelpText = "The name of the application to debug.")] public string Module { get; set; } [Option("version", Required = true, HelpText = "The version of the application to debug.")] public string Version { get; set; } [Option("debugger", Required = true, HelpText = "A path to the debugger to use.")] public string Debugger { get; set; } [Option("process-id", Required = true, HelpText = "The id of the process to debug.")] public string ProcessId { get; set; } [Option("project-id", HelpText = "The Google Cloud Console project the debuggee is associated with")] public string ProjectId { get; set; } [Option("wait-time", Default = 2, HelpText = "The amount of time to wait before checking for new breakpoints in seconds.")] public int WaitTime { get; set; } /// <summary> /// Parse a <see cref="DebugletOptions"/> from command line arguments. /// </summary> public static DebugletOptions Parse(string[] args) { var result = Parser.Default.ParseArguments<DebugletOptions>(args); var options = new DebugletOptions(); // TODO(talarico): Add better validation, file exists, ect. result.WithParsed((o) => options = o); return options; } } }
apache-2.0
C#
7a3f6e24dd839acebf2a883a0f4f98aaa87fb282
Align url invalid char unit tests with changes done to the validation logic
vnathalye/PnP,ebbypeter/PnP,rroman81/PnP,hildabarbara/PnP,vman/PnP,jlsfernandez/PnP,lamills1/PnP,OzMakka/PnP,timothydonato/PnP,gavinbarron/PnP,Anil-Lakhagoudar/PnP,OneBitSoftware/PnP,timschoch/PnP,darei-fr/PnP,rbarten/PnP,ebbypeter/PnP,GSoft-SharePoint/PnP,Claire-Hindhaugh/PnP,joaopcoliveira/PnP,yagoto/PnP,vman/PnP,edrohler/PnP,worksofwisdom/PnP,patrick-rodgers/PnP,baldswede/PnP,8v060htwyc/PnP,comblox/PnP,yagoto/PnP,jeroenvanlieshout/PnP,sandhyagaddipati/PnPSamples,JBeerens/PnP,Anil-Lakhagoudar/PnP,nishantpunetha/PnP,spdavid/PnP,vnathalye/PnP,SimonDoy/PnP,spdavid/PnP,OzMakka/PnP,yagoto/PnP,8v060htwyc/PnP,svarukala/PnP,JilleFloridor/PnP,r0ddney/PnP,jeroenvanlieshout/PnP,srirams007/PnP,PieterVeenstra/PnP,pdfshareforms/PnP,SteenMolberg/PnP,hildabarbara/PnP,worksofwisdom/PnP,russgove/PnP,worksofwisdom/PnP,chrisobriensp/PnP,edrohler/PnP,afsandeberg/PnP,aammiitt2/PnP,werocool/PnP,mauricionr/PnP,Claire-Hindhaugh/PnP,gautekramvik/PnP,PaoloPia/PnP,dalehhirt/PnP,darei-fr/PnP,OfficeDev/PnP,comblox/PnP,biste5/PnP,gavinbarron/PnP,jeroenvanlieshout/PnP,SuryaArup/PnP,afsandeberg/PnP,baldswede/PnP,briankinsella/PnP,IvanTheBearable/PnP,joaopcoliveira/PnP,hildabarbara/PnP,biste5/PnP,bhoeijmakers/PnP,chrisobriensp/PnP,briankinsella/PnP,afsandeberg/PnP,MaurizioPz/PnP,sandhyagaddipati/PnPSamples,chrisobriensp/PnP,SimonDoy/PnP,NavaneethaDev/PnP,tomvr2610/PnP,perolof/PnP,jlsfernandez/PnP,sandhyagaddipati/PnPSamples,Rick-Kirkham/PnP,werocool/PnP,Chowdarysandhya/PnPTest,PieterVeenstra/PnP,Claire-Hindhaugh/PnP,sjuppuh/PnP,patrick-rodgers/PnP,Rick-Kirkham/PnP,andreasblueher/PnP,rgueldenpfennig/PnP,OfficeDev/PnP,timothydonato/PnP,PaoloPia/PnP,durayakar/PnP,OneBitSoftware/PnP,sjuppuh/PnP,erwinvanhunen/PnP,nishantpunetha/PnP,selossej/PnP,IvanTheBearable/PnP,lamills1/PnP,gautekramvik/PnP,srirams007/PnP,valt83/PnP,dalehhirt/PnP,selossej/PnP,comblox/PnP,tomvr2610/PnP,patrick-rodgers/PnP,andreasblueher/PnP,zrahui/PnP,Chowdarysandhya/PnPTest,IDTimlin/PnP,SuryaArup/PnP,bstenberg64/PnP,lamills1/PnP,machadosantos/PnP,Chowdarysandhya/PnPTest,spdavid/PnP,Rick-Kirkham/PnP,erwinvanhunen/PnP,MaurizioPz/PnP,sjuppuh/PnP,8v060htwyc/PnP,briankinsella/PnP,markcandelora/PnP,valt83/PnP,selossej/PnP,IDTimlin/PnP,tomvr2610/PnP,brennaman/PnP,OzMakka/PnP,vnathalye/PnP,jlsfernandez/PnP,BartSnyckers/PnP,sndkr/PnP,gautekramvik/PnP,timschoch/PnP,machadosantos/PnP,Anil-Lakhagoudar/PnP,SteenMolberg/PnP,darei-fr/PnP,JBeerens/PnP,SimonDoy/PnP,pascalberger/PnP,ebbypeter/PnP,perolof/PnP,erwinvanhunen/PnP,pascalberger/PnP,sndkr/PnP,mauricionr/PnP,joaopcoliveira/PnP,pascalberger/PnP,srirams007/PnP,svarukala/PnP,aammiitt2/PnP,rgueldenpfennig/PnP,rbarten/PnP,mauricionr/PnP,NexploreDev/PnP-PowerShell,OfficeDev/PnP,sndkr/PnP,GSoft-SharePoint/PnP,GSoft-SharePoint/PnP,PieterVeenstra/PnP,bstenberg64/PnP,JilleFloridor/PnP,vman/PnP,zrahui/PnP,timothydonato/PnP,andreasblueher/PnP,svarukala/PnP,IDTimlin/PnP,valt83/PnP,brennaman/PnP,nishantpunetha/PnP,weshackett/PnP,IvanTheBearable/PnP,rgueldenpfennig/PnP,r0ddney/PnP,perolof/PnP,russgove/PnP,NavaneethaDev/PnP,bhoeijmakers/PnP,NavaneethaDev/PnP,aammiitt2/PnP,OneBitSoftware/PnP,MaurizioPz/PnP,PaoloPia/PnP,werocool/PnP,pdfshareforms/PnP,weshackett/PnP,yagoto/PnP,markcandelora/PnP,rroman81/PnP,biste5/PnP,OfficeDev/PnP,durayakar/PnP,bhoeijmakers/PnP,durayakar/PnP,r0ddney/PnP,timschoch/PnP,machadosantos/PnP,brennaman/PnP,JilleFloridor/PnP,bstenberg64/PnP,weshackett/PnP,NexploreDev/PnP-PowerShell,BartSnyckers/PnP,dalehhirt/PnP,rroman81/PnP,SuryaArup/PnP,NexploreDev/PnP-PowerShell,PaoloPia/PnP,rbarten/PnP,zrahui/PnP,SteenMolberg/PnP,JBeerens/PnP,OneBitSoftware/PnP,russgove/PnP,BartSnyckers/PnP,markcandelora/PnP,gavinbarron/PnP,edrohler/PnP,pdfshareforms/PnP,baldswede/PnP,8v060htwyc/PnP
OfficeDevPnP.Core/OfficeDevPnP.Core.Tests/Utilities/UrlUtilityTests.cs
OfficeDevPnP.Core/OfficeDevPnP.Core.Tests/Utilities/UrlUtilityTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OfficeDevPnP.Core.Utilities; using System.Collections.Generic; namespace OfficeDevPnP.Core.Tests.AppModelExtensions { [TestClass] public class UrlUtilityTests { [TestMethod] public void ContainsInvalidCharsReturnsFalseForValidString() { string validString = "abd-123"; Assert.IsFalse(validString.ContainsInvalidUrlChars()); } [TestMethod] public void ContainsInvalidUrlCharsReturnsTrueForInvalidString() { #if !CLIENTSDKV15 var targetVals = new List<char> { '#', '%', '*', '\\', ':', '<', '>', '?', '/', '+', '|', '"' }; #else var targetVals = new List<char> { '#', '~', '%', '&', '*', '{', '}', '\\', ':', '<', '>', '?', '/', '+', '|', '"' }; #endif targetVals.ForEach(v => Assert.IsTrue((string.Format("abc{0}abc", v).ContainsInvalidUrlChars()))); } [TestMethod] public void StripInvalidUrlCharsReturnsStrippedString() { #if !CLIENTSDKV15 var invalidString = "a#%*\\:<>?/+|b"; #else var invalidString = "a#~%&*{}\\:<>?/+|b"; #endif Assert.AreEqual("ab", invalidString.StripInvalidUrlChars()); } [TestMethod] public void ReplaceInvalidUrlCharsReturnsStrippedString() { #if !CLIENTSDKV15 var invalidString = "a#%*\\:<>?/+|b"; #else var invalidString = "a#~%&*{}\\:<>?/+|b"; #endif Assert.AreEqual("a------------------------------------------b", invalidString.ReplaceInvalidUrlChars("---")); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OfficeDevPnP.Core.Utilities; using System.Collections.Generic; namespace OfficeDevPnP.Core.Tests.AppModelExtensions { [TestClass] public class UrlUtilityTests { [TestMethod] public void ContainsInvalidCharsReturnsFalseForValidString() { string validString = "abd-123"; Assert.IsFalse(validString.ContainsInvalidUrlChars()); } [TestMethod] public void ContainsInvalidUrlCharsReturnsTrueForInvalidString() { var targetVals = new List<char> { '#', '%', '&', '*', '{', '}', '\\', ':', '<', '>', '?', '/', '+', '|', '"' }; targetVals.ForEach(v => Assert.IsTrue((string.Format("abc{0}abc", v).ContainsInvalidUrlChars()))); } [TestMethod] public void StripInvalidUrlCharsReturnsStrippedString() { var invalidString = "a#%&*{}\\:<>?/+|b"; Assert.AreEqual("ab", invalidString.StripInvalidUrlChars()); } [TestMethod] public void ReplaceInvalidUrlCharsReturnsStrippedString() { var invalidString = "a#%&*{}\\:<>?/+|b"; Assert.AreEqual("a------------------------------------------b", invalidString.ReplaceInvalidUrlChars("---")); } } }
mit
C#
bec833e7c3bbdc00a13476290ae47fba5346c26e
Add support for removing okanshi instances
mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard
src/Okanshi.Dashboard/IConfiguration.cs
src/Okanshi.Dashboard/IConfiguration.cs
using System.Collections.Generic; namespace Okanshi.Dashboard { public interface IConfiguration { void Add(OkanshiServer server); IEnumerable<OkanshiServer> GetAll(); void Remove(string name); } }
using System.Collections.Generic; namespace Okanshi.Dashboard { public interface IConfiguration { void Add(OkanshiServer server); IEnumerable<OkanshiServer> GetAll(); } }
mit
C#
fa08376c9a438d628cf0b771cc53238696f566d5
Fix token expiration check
1and1/TypedRest-DotNet,TypedRest/TypedRest-DotNet,1and1/TypedRest-DotNet,TypedRest/TypedRest-DotNet
src/TypedRest.OAuth/Http/AccessToken.cs
src/TypedRest.OAuth/Http/AccessToken.cs
using System; namespace TypedRest.Http { internal class AccessToken { public string Value { get; } private readonly DateTime _expiration; public bool IsExpired => DateTime.Now >= _expiration; public AccessToken(string value, DateTime expiration) { Value = value; _expiration = expiration; } } }
using System; using IdentityModel.Client; namespace TypedRest.Http { internal class AccessToken { public string Value { get; } private readonly DateTime _expiration; public bool IsExpired => _expiration >= DateTime.Now; public AccessToken(string value, DateTime expiration) { Value = value; _expiration = expiration; } } }
mit
C#
3b2d2193f29ea2710e1b616b51d7fb3d2b376664
Change MathProblemModel to return Queue
Kakarot/CITS
CITS/Models/MathProblemModel.cs
CITS/Models/MathProblemModel.cs
using System; namespace CITS.Models { public class MathProblemModel : ProblemModel { public MathProblemModel(string Problem, string Solution):base(Problem,Solution){} public override Boolean IsSolutionCorrect(String candidateSolution) { return Solution.Equals(candidateSolution.Trim()); } } }
using System; namespace CITS.Models { public class MathProblemModel : ProblemModel { public MathProblemModel(string Problem, string Solution):base(Problem,Solution){} public override Boolean IsSolutionCorrect(String candidateSolution) { return candidateSolution.Equals(Solution); } } }
mit
C#
0c34c5adc6db05634a214ae5fd5cc54064724910
Change signature
sakapon/Bellona.Analysis
Bellona/UnitTest/TestData.cs
Bellona/UnitTest/TestData.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Reflection; using Bellona.Core; namespace UnitTest { static class TestData { public static Color[] GetColors() { return typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static) .Where(p => p.PropertyType == typeof(Color)) .Select(p => (Color)p.GetValue(null)) .Where(c => c.A == 255) // Exclude Transparent. .ToArray(); } public static SamplePoint[] GetRandomPoints(int points) { return Enumerable.Range(0, points) .Select(i => new SamplePoint { Id = i, Point = Enumerable.Range(1, 3).Select(j => RandomHelper.NextDouble(j)).ToArray(), }) .ToArray(); } } class SamplePoint { public int Id { get; set; } public double[] Point { get; set; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Reflection; using Bellona.Core; namespace UnitTest { static class TestData { public static Color[] GetColors() { return typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static) .Where(p => p.PropertyType == typeof(Color)) .Select(p => (Color)p.GetValue(null)) .Where(c => c.A == 255) // Exclude Transparent. .ToArray(); } public static SamplePoint[] GetRandomPoints() { return Enumerable.Range(0, 100) .Select(i => new SamplePoint { Id = i, Point = Enumerable.Range(1, 3).Select(j => RandomHelper.NextDouble(j)).ToArray(), }) .ToArray(); } } class SamplePoint { public int Id { get; set; } public double[] Point { get; set; } } }
mit
C#
5531eaaebd921d44f7a5963e81a08ce0aea04ee5
Handle all relevant change types
tomwarner13/FileListenerService
FileListenerService/Listener.cs
FileListenerService/Listener.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Net.Http; using log4net; namespace FileListenerService { public class Listener { private readonly Uri _endpoint; private FileSystemWatcher _watcher; private string _rootDir; private List<string> _dirsToIgnore; private readonly ILog log; //may need this //[PermissionSet(SecurityAction.Demand, Name="FullTrust")] public Listener(string rootDir, string endpoint, List<string> dirsToIgnore) { log4net.Config.XmlConfigurator.Configure(); log = LogManager.GetLogger(typeof(Listener)); _rootDir = rootDir; _endpoint = new Uri(endpoint); _dirsToIgnore = dirsToIgnore; _watcher = new FileSystemWatcher(_rootDir); _watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.FileName; _watcher.IncludeSubdirectories = true; _watcher.Changed += new FileSystemEventHandler(OnChanged); _watcher.Created += new FileSystemEventHandler(OnChanged); _watcher.EnableRaisingEvents = true; } private void NotifyEndpoint(Dictionary<string, string> values) { log.Debug($"Notifying endpoint at {_endpoint.AbsoluteUri}"); using (var client = new HttpClient()) { var response = client.PostAsync(_endpoint.AbsoluteUri, new FormUrlEncodedContent(values)).Result; } } private void OnChanged(object source, FileSystemEventArgs e) { log.Debug($"File change observed: path {e.FullPath} with change {e.ChangeType}"); var relativePath = e.FullPath.Replace(_rootDir, ""); var topDirectory = relativePath.Contains('\\') ? relativePath.Split('\\')[0] : ""; //FileSystemWatcher can only take a filter of which directories to watch; no whitelist/blacklist //thanks obama if (_dirsToIgnore.Contains(topDirectory)) { log.Debug($"File change ignored: {topDirectory} is blacklisted"); } else { var values = new Dictionary<string, string> { { "Path", relativePath }, { "Event", e.ChangeType.ToString() } }; NotifyEndpoint(values); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Net.Http; using log4net; namespace FileListenerService { public class Listener { private readonly Uri _endpoint; private FileSystemWatcher _watcher; private string _rootDir; private List<string> _dirsToIgnore; private readonly ILog log; //may need this //[PermissionSet(SecurityAction.Demand, Name="FullTrust")] public Listener(string rootDir, string endpoint, List<string> dirsToIgnore) { log4net.Config.XmlConfigurator.Configure(); log = LogManager.GetLogger(typeof(Listener)); _rootDir = rootDir; _endpoint = new Uri(endpoint); _dirsToIgnore = dirsToIgnore; _watcher = new FileSystemWatcher(_rootDir); _watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite; _watcher.IncludeSubdirectories = true; _watcher.Changed += new FileSystemEventHandler(OnChanged); _watcher.Created += new FileSystemEventHandler(OnChanged); _watcher.EnableRaisingEvents = true; } private void NotifyEndpoint(Dictionary<string, string> values) { log.Debug($"Notifying endpoint at {_endpoint.AbsoluteUri}"); using (var client = new HttpClient()) { var response = client.PostAsync(_endpoint.AbsoluteUri, new FormUrlEncodedContent(values)).Result; } } private void OnChanged(object source, FileSystemEventArgs e) { log.Debug($"File change observed: path {e.FullPath} with change {e.ChangeType}"); var relativePath = e.FullPath.Replace(_rootDir, ""); var topDirectory = relativePath.Contains('\\') ? relativePath.Split('\\')[0] : ""; //FileSystemWatcher can only take a filter of which directories to watch; no whitelist/blacklist //thanks obama if (_dirsToIgnore.Contains(topDirectory)) { log.Debug($"File change ignored: {topDirectory} is blacklisted"); } else { var values = new Dictionary<string, string> { { "Path", relativePath }, { "Event", e.ChangeType.ToString() } }; NotifyEndpoint(values); } } } }
mit
C#
25e26a26ed04743aecf36ecc2a8fc68607d6705b
Copy changes
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Home/Index.cshtml
src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Home/Index.cshtml
@{ ViewBag.Title = "Add and update apprentice records as a training provider"; ViewBag.PageId = "home-page"; } <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge">Add and update apprentice records as a training provider</h1> <p>This service is for training providers registered with the apprenticeship service to work with employers to:</p> <ul class="list list-bullet"> <li>add details of the apprentices they're going to train</li> <li>manage details of the apprentices they're currently training</li> </ul> <div class="form-group"> <a href="/signin" class="button button-start" title="Start now" aria-label="Start now">Start now</a> </div> <h2 class="heading-medium">Before you start</h2> <p>You need to have an account with the government’s Information Management Services system (IdAMS) to use this.</p> <p>If your organisation doesn't already have an IdAMS account, you’ll get your account details when you <a href="https://www.gov.uk/guidance/register-of-apprenticeship-training-providers" target="_blank" rel="external">register as an apprenticeship training provider</a>.</p> <p>If your organisation does already have an IdAMS account, an account super user from your organisation will need to give you access to the apprenticeship service.</p> <h3 class="heading-medium">Help</h3> <p>You can contact the National Apprenticeship Service for advice or help using the service.</p> <h4 class="heading-small">National Apprenticeship Service</h4> <p>Telephone: 0800 015 0600 <br /> <a href="https://www.gov.uk/call-charges" target="_blank">Find out about call charges</a></p> </div> </div>
@{ ViewBag.Title = "Add and update apprentice records as a training provider"; ViewBag.PageId = "home-page"; } <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge">Add and update apprentice records as a training provider</h1> <p>This service is for training providers registered with the apprenticeship service to work with employers to:</p> <ul class="list list-bullet"> <li>add details of the apprentices they're going to train</li> <li>manage details of the apprentices they're currently training</li> </ul> <div class="form-group"> <a href="/signin" class="button button-start" title="Start now" aria-label="Start now">Start now</a> </div> <h2 class="heading-medium">Before you start</h2> <p>You need to have an account with the government’s Information Management Services system (IdAMS) to use this.</p> <p>If your organisation doesn't already have an IdAMS account, you’ll get your account details when you <a href="https://www.gov.uk/guidance/register-of-apprenticeship-training-providers" target="_blank" rel="external">register as an apprenticeship training provider</a>.</p> <p>If your organisation does already have an IdAMS account, an account super user from your organisation will need to give you access to the apprenticeship service.</p> <h3 class="heading-medium">Help</h3> <p>You can contact the Apprenticeship Service for advice or help using the service.</p> <h4 class="heading-small">Apprenticeship Service</h4> <p>Telephone: 0800 015 0600 <a href="https://www.gov.uk/call-charges" target="_blank">Find out about call charges</a></p> </div> </div>
mit
C#
621cc2fc743bf464912efc4c2e08a13f0fb9b492
Update comment in Player.cs
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 = new UnityEngine.Vector3(0, 0, 0); void Start() { rb = this.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 (this.transform.position.y < -6) { // Reset the player's velocity and their position rb.velocity = stationary; this.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 = this.GetComponent<UnityEngine.Rigidbody>(); StartCoroutine(CheckOutOfBounds()); } public System.Collections.IEnumerator CheckOutOfBounds() { // This checks the boundaries always. Eventually, we'll want to turn this off // under certain conditions, like when the player doesn't have control over // the player's movement. while(true) { if (this.transform.position.y < -6) { // Reset the player's velocity and their position rb.velocity = stationary; this.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#
8dbccd0836c88dd928a602dc01e01393f571746a
Comment out
alvivar/Hasten
EditorTools/PlayTools.cs
EditorTools/PlayTools.cs
// #if UNITY_EDITOR // using UnityEditor; // Experimental, unfinished, but useful menu item commands to Play and Dev // scenes. // public static class PlayTools // { // [MenuItem("Game/Play")] // public static void Play() // { // if (EditorApplication.isPlaying == true) // { // EditorApplication.isPlaying = false; // return; // } // EditorApplication.SaveCurrentSceneIfUserWantsTo(); // EditorApplication.OpenScene("Assets/Game/Scenes/Multiplayer/01-Lobby.unity"); // EditorApplication.isPlaying = true; // } // [MenuItem("Game/Dev")] // public static void Dev() // { // if (EditorApplication.isPlaying == true) // { // EditorApplication.isPlaying = false; // return; // } // EditorApplication.SaveCurrentSceneIfUserWantsTo(); // EditorApplication.OpenScene("Assets/Game/Scenes/Multiplayer/02-City.unity"); // } // } // #endif
#if UNITY_EDITOR using UnityEditor; // Experimental, unfinished, but useful menu item commands to Play and Dev // scenes. public static class PlayTools { [MenuItem("Game/Play")] public static void Play() { if (EditorApplication.isPlaying == true) { EditorApplication.isPlaying = false; return; } EditorApplication.SaveCurrentSceneIfUserWantsTo(); EditorApplication.OpenScene("Assets/Game/Scenes/Multiplayer/01-Lobby.unity"); EditorApplication.isPlaying = true; } [MenuItem("Game/Dev")] public static void Dev() { if (EditorApplication.isPlaying == true) { EditorApplication.isPlaying = false; return; } EditorApplication.SaveCurrentSceneIfUserWantsTo(); EditorApplication.OpenScene("Assets/Game/Scenes/Multiplayer/02-City.unity"); } } #endif
mit
C#
71b50b6280e9d60b7428c311015b0b497f456802
Make an enum public to ease store plugins
mdesalvo/RDFSharp
RDFSharp/Store/RDFStoreEnums.cs
RDFSharp/Store/RDFStoreEnums.cs
/* Copyright 2012-2019 Marco De Salvo 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. */ namespace RDFSharp.Store { /// <summary> /// RDFStoreEnums represents a collector for all the enumerations used by the "RDFSharp.Store" namespace /// </summary> public static class RDFStoreEnums { /// <summary> /// RDFStoreSQLErrors represents an enumeration for situations which can be found on a SQL-backing store /// </summary> public enum RDFStoreSQLErrors { /// <summary> /// Indicates that diagnostics on the selected database has passed /// </summary> NoErrors = 0, /// <summary> /// Indicates that diagnostics on the selected database has not passed because of a connection error /// </summary> InvalidDataSource = 1, /// <summary> /// Indicates that diagnostics on the selected database has not passed because it's not ready for use with RDFSharp /// </summary> QuadruplesTableNotFound = 2 }; /// <summary> /// RDFFormats represents an enumeration for supported RDF store serialization data formats. /// </summary> public enum RDFFormats { /// <summary> /// N-Quads serialization /// </summary> NQuads = 1, /// <summary> /// TriX serialization /// </summary> TriX = 2 }; } }
/* Copyright 2012-2019 Marco De Salvo 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. */ namespace RDFSharp.Store { /// <summary> /// RDFStoreEnums represents a collector for all the enumerations used by the "RDFSharp.Store" namespace /// </summary> public static class RDFStoreEnums { /// <summary> /// RDFStoreSQLErrors represents an enumeration for situations which can be found on a SQL-backing store /// </summary> internal enum RDFStoreSQLErrors { /// <summary> /// Indicates that diagnostics on the selected database has passed /// </summary> NoErrors = 0, /// <summary> /// Indicates that diagnostics on the selected database has not passed because of a connection error /// </summary> InvalidDataSource = 1, /// <summary> /// Indicates that diagnostics on the selected database has not passed because it's not ready for use with RDFSharp /// </summary> QuadruplesTableNotFound = 2 }; /// <summary> /// RDFFormats represents an enumeration for supported RDF store serialization data formats. /// </summary> public enum RDFFormats { /// <summary> /// N-Quads serialization /// </summary> NQuads = 1, /// <summary> /// TriX serialization /// </summary> TriX = 2 }; } }
apache-2.0
C#
6e4de8e552ff3e59488cb0a800c96a97a946f262
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.Bam/ValuesOut.cs
RegistryPlugin.Bam/ValuesOut.cs
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.BamDam { public class ValuesOut:IValueOut { public ValuesOut(string program, DateTimeOffset executionTime) { Program = program; ExecutionTime = executionTime; } public string Program { get; } public DateTimeOffset ExecutionTime { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Program: {Program}"; public string BatchValueData2 => $"Execution time: {ExecutionTime.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}"; public string BatchValueData3 { get; } } }
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.BamDam { public class ValuesOut:IValueOut { public ValuesOut(string program, DateTimeOffset executionTime) { Program = program; ExecutionTime = executionTime; } public string Program { get; } public DateTimeOffset ExecutionTime { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Program: {Program}"; public string BatchValueData2 => $"Execution time: {ExecutionTime.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})"; public string BatchValueData3 { get; } } }
mit
C#
3953ea281218f583732000309d4b850151a56814
Fix merge conflict
gdkchan/SPICA
SPICA/Formats/GFL2/GFSection.cs
SPICA/Formats/GFL2/GFSection.cs
using SPICA.Formats.Common; using System.IO; namespace SPICA.Formats.GFL2 { class GFSection { public string Magic; public uint Length; private uint Padding; public GFSection() { Padding = 0xffffffff; } public GFSection(string Magic) : this() { this.Magic = Magic; } public GFSection(string Magic, uint Length) : this() { this.Magic = Magic; this.Length = Length; } public GFSection(BinaryReader Reader) { Magic = Reader.ReadPaddedString(8); Length = Reader.ReadUInt32(); Padding = Reader.ReadUInt32(); } public void Write(BinaryWriter Writer) { Writer.WritePaddedString(Magic, 8); Writer.Write(Length); Writer.Write(0xffffffffu); } public static void SkipPadding(Stream BaseStream) { if ((BaseStream.Position & 0xf) != 0) { BaseStream.Seek(0x10 - (BaseStream.Position & 0xf), SeekOrigin.Current); } } } }
using SPICA.Formats.Common; using System.IO; namespace SPICA.Formats.GFL2 { class GFSection { public string Magic; public uint Length; private uint Padding; public GFSection() { Padding = 0xffffffff; } <<<<<<< HEAD public GFSection(string Magic) : this() ======= public GFSection(string magic, uint length) >>>>>>> ca59ba8d42bfa4bd096e4061f63acd01a77a125c { Magic = magic; Length = length; } public GFSection(BinaryReader Reader) { Magic = Reader.ReadPaddedString(8); Length = Reader.ReadUInt32(); Padding = Reader.ReadUInt32(); } public void Write(BinaryWriter Writer) { Writer.WritePaddedString(Magic, 8); Writer.Write(Length); Writer.Write(0xffffffffu); } public static void SkipPadding(Stream BaseStream) { if ((BaseStream.Position & 0xf) != 0) { BaseStream.Seek(0x10 - (BaseStream.Position & 0xf), SeekOrigin.Current); } } } }
unlicense
C#
7d49e830708cd57783fe0fe42099003146ed65dd
Save an allocation in RewriteIter
benjamin-hodgson/Sawmill
Sawmill/Rewriter.RewriteIter.cs
Sawmill/Rewriter.RewriteIter.cs
using System; namespace Sawmill { public static partial class Rewriter { /// <summary> /// Rebuild a tree by repeatedly applying a transformation function to every node in the tree, /// until <paramref name="transformer"/> returns <see cref="IterResult.Done{T}"/> for all nodes. /// (In other words, <c>rewriter.DescendantsAndSelf(rewriter.RewriteIter(f, x)).Any(n => f(n).Continue) == false</c>.) /// <para> /// This is typically useful when you want to put your tree into a normal form /// by applying a collection of rewrite rules until none of them can fire any more. /// </para> /// </summary> /// <typeparam name="T">The rewritable tree type</typeparam> /// <param name="rewriter">The rewriter</param> /// <param name="transformer"> /// A transformation function to apply to every node in <paramref name="value"/> repeatedly until it returns <see cref="IterResult.Done{T}"/>. /// </param> /// <param name="value">The value to rewrite</param> /// <returns> /// The result of applying <paramref name="transformer"/> to every node in the tree /// represented by <paramref name="value"/> until it returns <see cref="IterResult.Done{T}"/>. /// </returns> public static T RewriteIter<T>(this IRewriter<T> rewriter, Func<T, IterResult<T>> transformer, T value) where T : class { if (rewriter == null) { throw new ArgumentNullException(nameof(rewriter)); } if (transformer == null) { throw new ArgumentNullException(nameof(transformer)); } Func<T, T> transformerDelegate = null; transformerDelegate = Transformer; T Transformer(T x) { var newX = transformer(x); if (newX.Continue) { return Go(newX.Result); } return x; } T Go(T x) => rewriter.Rewrite(transformerDelegate, x); return Go(value); } } }
using System; namespace Sawmill { public static partial class Rewriter { /// <summary> /// Rebuild a tree by repeatedly applying a transformation function to every node in the tree, /// until <paramref name="transformer"/> returns <see cref="IterResult.Done{T}"/> for all nodes. /// (In other words, <c>rewriter.DescendantsAndSelf(rewriter.RewriteIter(f, x)).Any(n => f(n).Continue) == false</c>.) /// <para> /// This is typically useful when you want to put your tree into a normal form /// by applying a collection of rewrite rules until none of them can fire any more. /// </para> /// </summary> /// <typeparam name="T">The rewritable tree type</typeparam> /// <param name="rewriter">The rewriter</param> /// <param name="transformer"> /// A transformation function to apply to every node in <paramref name="value"/> repeatedly until it returns <see cref="IterResult.Done{T}"/>. /// </param> /// <param name="value">The value to rewrite</param> /// <returns> /// The result of applying <paramref name="transformer"/> to every node in the tree /// represented by <paramref name="value"/> until it returns <see cref="IterResult.Done{T}"/>. /// </returns> public static T RewriteIter<T>(this IRewriter<T> rewriter, Func<T, IterResult<T>> transformer, T value) where T : class { if (rewriter == null) { throw new ArgumentNullException(nameof(rewriter)); } if (transformer == null) { throw new ArgumentNullException(nameof(transformer)); } Func<T, T> transformerDelegate = null; transformerDelegate = Transformer; T Transformer(T x) { var newX = transformer(x); if (newX.Continue) { return Go(newX.Result); } return x; } T Go(T x) => rewriter.Rewrite(Transformer, x); return Go(value); } } }
mit
C#
9cb155c55282feec0d207bdad3deaffa4903725d
Make a quadtree generic.
taylorhutchison/Geode
Geode/Structures/QuadTree.cs
Geode/Structures/QuadTree.cs
using System; using System.Collections.Generic; using System.Text; using Geode.Geometry; namespace Geode.Structures { public class QuadTree<T> where T: IPosition { public QuadTree(IEnumerable<T> positions) { } public QuadTree<T> Add(IPosition position) { return this; } public QuadTree<T> Add(IEnumerable<IPosition> positions) { return this; } } }
using System; using System.Collections.Generic; using System.Text; using Geode.Geometry; namespace Geode.Structures { public class QuadTree { public QuadTree(IEnumerable<IPosition> positions) { } public QuadTree Add(IPosition position) { return this; } public QuadTree Add(IEnumerable<IPosition> position) { return this; } } }
mit
C#
a2166aa7fe90432bdc2579a0536b0af7fb868896
Add symmetric key to sign tokens
denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs
src/Diploms.WebUI/Startup.cs
src/Diploms.WebUI/Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Diploms.DataLayer; using Diploms.WebUI.Configuration; using FluentValidation.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.Webpack; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using AutoMapper; using Diploms.WebUI.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.IdentityModel.Tokens; using System.Text; namespace Diploms.WebUI { public class Startup { private const string SecretKey = "someverystrongkey"; private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey)); public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services .AddMvc() .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>()); services.AddAutoMapper(); services.AddDepartments(); services.AddDbContext<DiplomContext>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Diploms.DataLayer; using Diploms.WebUI.Configuration; using FluentValidation.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.Webpack; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using AutoMapper; namespace Diploms.WebUI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services .AddMvc() .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>()); services.AddAutoMapper(); services.AddDepartments(); services.AddDbContext<DiplomContext>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); } } }
mit
C#
5e19f29121079e65252e20a461e3c82aa616f907
add connection string
jefking/King.Service
King.Service.Demo/Program.cs
King.Service.Demo/Program.cs
namespace King.Service.Demo { using King.Service.Demo.Factories; using System; using System.Threading; public class Program { public static void Main(string[] args) { // Load Config var config = new AppConfig { ConnectionString = Environment.GetEnvironmentVariable("conString"), TableName = "table", GenericQueueName = "queue", ContainerName = "container", FastQueueName = "fast", ModerateQueueName = "moderate", SlowQueueName = "slow", ShardQueueName = "shard" }; // Construct runtime using (var manager = new RoleTaskManager<AppConfig>(new Factory(), new DataGenerationFactory(), new TaskFinderFactory<AppConfig>())) { // Start runtime manager.OnStart(config); // Run manager.Run(); // Hang on loaded thread while (true) { Thread.Sleep(1500); } } } } }
namespace King.Service.Demo { using King.Service.Demo.Factories; using System.Threading; public class Program { public static void Main(string[] args) { // Load Config var config = new AppConfig() { ConnectionString = "UseDevelopmentStorage=true;", TableName = "table", GenericQueueName = "queue", ContainerName = "container", FastQueueName = "fast", ModerateQueueName = "moderate", SlowQueueName = "slow", ShardQueueName = "shard" }; // Construct runtime using (var manager = new RoleTaskManager<AppConfig>(new Factory(), new DataGenerationFactory(), new TaskFinderFactory<AppConfig>())) { // Start runtime manager.OnStart(config); // Run manager.Run(); // Hang on loaded thread while (true) { Thread.Sleep(1500); } } } } }
mit
C#
e3a21bd7a9e53d7e79c5dd5a26702e2a9de8954d
change exit to enter key
airmanx86/docker-mono-owinsampleapp,airmanx86/docker-mono-owinsampleapp
src/OwinSampleApp/Program.cs
src/OwinSampleApp/Program.cs
namespace OwinSampleApp { using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Owin; using Microsoft.Owin.Hosting; class Program { static void Main(string[] args) { const string baseAddress = "http://*:9000/"; // Start OWIN host using (WebApp.Start<Startup>(url: baseAddress)) { using (var timer = new Timer( state => Console.WriteLine("[{0}] Press ENTER to exit.", DateTime.UtcNow.ToString("s")), null, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 3))) { Console.ReadLine(); Console.WriteLine("Stopping host and exiting application."); } } } } }
namespace OwinSampleApp { using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Owin; using Microsoft.Owin.Hosting; class Program { private static volatile bool stop = false; static void Main(string[] args) { const string baseAddress = "http://*:9000/"; // Start OWIN host using (WebApp.Start<Startup>(url: baseAddress)) { using (var timer = new Timer( state => Console.WriteLine("[{0}] Press any key to exit.", DateTime.UtcNow.ToString("s")), null, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 3))) { Console.ReadKey(); Console.WriteLine("Stopping host and exiting application."); } } } } }
mit
C#
fc55765bebf6c4d566e6aeb4691b02f664aa27bc
Update TextSpeachPage
jxug/PrismAndMoqHansOn
before/TextSpeaker/TextSpeaker/TextSpeaker/Views/TextSpeachPage.xaml.cs
before/TextSpeaker/TextSpeaker/TextSpeaker/Views/TextSpeachPage.xaml.cs
using Xamarin.Forms; namespace TextSpeaker.Views { public partial class TextSpeachPage : ContentPage { public TextSpeachPage() { InitializeComponent(); } } }
namespace TextSpeaker.Views { public partial class TextSpeachPage { public TextSpeachPage() { InitializeComponent(); } } }
mit
C#
e57cb1af8300136c03a9668c000fed2b90afd8ed
Make assemblies servicesable
Skylertodd/RESTier,karataliu/RESTier
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")] [assembly: AssemblyInformationalVersion("0.2.0-pre")] [assembly: AssemblyMetadata("Serviceable", "True")]
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")] [assembly: AssemblyInformationalVersion("0.2.0-pre")]
mit
C#
ce030e23f72f9908183e7c65f0f3bd2dd54a74ef
Update tests to use explicit globals
Rohansi/Mond,SirTony/Mond,Rohansi/Mond,Rohansi/Mond,SirTony/Mond,SirTony/Mond
Mond.Tests/MondStateTests.cs
Mond.Tests/MondStateTests.cs
using NUnit.Framework; namespace Mond.Tests { [TestFixture] public class MondStateTests { [Test] public void MultiplePrograms() { const string source1 = @" global.hello = fun (x) { return 'hi ' + x; }; global.a = global.hello('nerd'); "; const string source2 = @" global.b = global.hello('brian'); "; var state = Script.Load(source1, source2); var result1 = state["a"]; var result2 = state["b"]; Assert.True(result1 == "hi nerd"); Assert.True(result2 == "hi brian"); } [Test] public void NativeFunction() { var state = new MondState(); state["function"] = new MondFunction((_, args) => args[0]); var program = MondProgram.Compile(@" return global.function('arg'); "); var result = state.Load(program); Assert.True(result == "arg"); } [Test] public void NativeInstanceFunction() { var state = new MondState(); state["value"] = 123; state["function"] = new MondInstanceFunction((_, instance, arguments) => instance[arguments[0]]); var program = MondProgram.Compile(@" return global.function('value'); "); var result = state.Load(program); Assert.True(result == 123); } } }
using NUnit.Framework; namespace Mond.Tests { [TestFixture] public class MondStateTests { [Test] public void MultiplePrograms() { const string source1 = @" hello = fun (x) { return 'hi ' + x; }; a = hello('nerd'); "; const string source2 = @" b = hello('brian'); "; var state = Script.Load(source1, source2); var result1 = state["a"]; var result2 = state["b"]; Assert.True(result1 == "hi nerd"); Assert.True(result2 == "hi brian"); } [Test] public void NativeFunction() { var state = new MondState(); state["function"] = new MondFunction((_, args) => args[0]); var program = MondProgram.Compile(@" return function('arg'); "); var result = state.Load(program); Assert.True(result == "arg"); } [Test] public void NativeInstanceFunction() { var state = new MondState(); state["value"] = 123; state["function"] = new MondInstanceFunction((_, instance, arguments) => instance[arguments[0]]); var program = MondProgram.Compile(@" return function('value'); "); var result = state.Load(program); Assert.True(result == 123); } } }
mit
C#
080c8ac947390e7dbc6f4989d40d00fc12a7cd4a
Allow blank/root route to be configured
grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation
NavigationMvc/RouteConfig.cs
NavigationMvc/RouteConfig.cs
using System.Web.Mvc; using System.Web.Routing; namespace Navigation.Mvc { public class RouteConfig { public static void AddStateRoutes() { if (StateInfoConfig.Dialogs == null) return; ValueProviderFactories.Factories.Insert(0, new NavigationDataValueProviderFactory()); string controller, action; Route route; using (RouteTable.Routes.GetWriteLock()) { foreach (Dialog dialog in StateInfoConfig.Dialogs) { foreach (State state in dialog.States) { controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty; action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty; if (controller.Length != 0 && action.Length != 0) { state.StateHandler = new MvcStateHandler(); route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route); route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route); route.Defaults["controller"] = controller; route.Defaults["action"] = action; route.DataTokens = new RouteValueDictionary() { { NavigationSettings.Config.StateIdKey, state.Id } }; route.RouteHandler = new MvcStateRouteHandler(state); } } } } } } }
using System.Web.Mvc; using System.Web.Routing; namespace Navigation.Mvc { public class RouteConfig { public static void AddStateRoutes() { if (StateInfoConfig.Dialogs == null) return; ValueProviderFactories.Factories.Insert(0, new NavigationDataValueProviderFactory()); string controller, action; Route route; using (RouteTable.Routes.GetWriteLock()) { foreach (Dialog dialog in StateInfoConfig.Dialogs) { foreach (State state in dialog.States) { controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty; action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty; if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0) { state.StateHandler = new MvcStateHandler(); route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route); route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route); route.Defaults["controller"] = controller; route.Defaults["action"] = action; route.DataTokens = new RouteValueDictionary() { { NavigationSettings.Config.StateIdKey, state.Id } }; route.RouteHandler = new MvcStateRouteHandler(state); } } } } } } }
apache-2.0
C#
835f0e4926045069bf21795c2bc36dc50946ddc4
Fix for build
Ar3sDevelopment/Caelan.Frameworks.Common
Caelan.Frameworks.Common/Classes/BaseBuilder.cs
Caelan.Frameworks.Common/Classes/BaseBuilder.cs
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Caelan.Frameworks.Common.Extenders; namespace Caelan.Frameworks.Common.Classes { public class BaseBuilder<TSource, TDestination> : Profile { sealed protected override void Configure() { base.Configure(); var mappingExpression = Mapper.CreateMap<TSource, TDestination>(); mappingExpression.AfterMap((source, destination) => AfterBuild(source, ref destination)); AddMappingConfigurations(mappingExpression); } protected virtual void AddMappingConfigurations(IMappingExpression<TSource, TDestination> mappingExpression) { mappingExpression.IgnoreAllNonExisting(); } public TDestination Build(TSource source) { if (source == null || source.Equals(default(TSource))) return default(TDestination); var dest = typeof(TDestination).IsValueType ? default(TDestination) : Activator.CreateInstance<TDestination>(); Build(source, ref dest); return dest; } public IEnumerable<TDestination> BuildList(IEnumerable<TSource> sourceList) { return sourceList == null ? null : sourceList.Select(Build); } public void Build(TSource source, ref TDestination destination) { if (source == null || source.Equals(default(TSource))) { destination = default(TDestination); return; } Mapper.DynamicMap(source, destination); } public virtual void AfterBuild(TSource source, ref TDestination destination) { } } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Caelan.Frameworks.Common.Extenders; namespace Caelan.Frameworks.Common.Classes { public class BaseBuilder<TSource, TDestination> : Profile { sealed protected override void Configure() { base.Configure(); var mappingExpression = Mapper.CreateMap<TSource, TDestination>(); mappingExpression.AfterMap((source, destination) => AfterBuild(source, ref destination)); AddMappingConfigurations(mappingExpression); } protected virtual void AddMappingConfigurations(IMappingExpression<TSource, TDestination> mappingExpression) { mappingExpression.IgnoreAllNonExisting(); } public TDestination Build(TSource source) { if (source == null || source.Equals(default(TSource))) return default(TDestination); var dest = typeof(TDestination).IsValueType ? default(TDestination) : Activator.CreateInstance<TDestination>(); Build(source, ref dest); return dest; } public IEnumerable<TDestination> BuildList(IEnumerable<TSource> sourceList) { return sourceList == null ? null : sourceList.Select(Build); } public void Build(TSource source, ref TDestination destination) { if (source == null || source.Equals(default(TSource))) { destination = default(TDestination); } else { Mapper.DynamicMap(source, destination); } } public virtual void AfterBuild(TSource source, ref TDestination destination) { } } }
mit
C#
547c76cdd3b2b659dce74750a2d6b86417e60b8c
Move pack to it's own step
Azure/azure-mobile-apps,Azure/azure-mobile-apps,Azure/azure-mobile-apps
sdk/dotnet/build.cake
sdk/dotnet/build.cake
/////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var nugetVersion = Argument("nugetVersion", EnvironmentVariable("NUGET_VERSION") ?? "1.0.0"); var baseVersion = nugetVersion.Contains("-") ? nugetVersion.Substring(0, nugetVersion.IndexOf("-")) : nugetVersion; var outputDirectory = Argument("artifactsPath", "../../output"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Build").Does(() => { Information("Building with NuGet version: {0}", nugetVersion); Information("Building with assembly version: {0}", baseVersion); MSBuild("./Datasync.Framework.sln", c => c .SetConfiguration(configuration) .EnableBinaryLogger($"./output/build.binlog") .WithRestore() .WithTarget("Build") .WithProperty("PackageOutputPath", MakeAbsolute((DirectoryPath)"./output").FullPath) .WithProperty("PackageVersion", nugetVersion) .WithProperty("Version", baseVersion)); }); Task("Test").IsDependentOn("Build").Does(() => { var settings = new DotNetCoreTestSettings { Configuration = configuration, NoBuild = true, NoRestore = true, ResultsDirectory = $"./output/unittests-results" }; var failCount = 0; var projectFiles = GetFiles("./test/Microsoft.*/Microsoft.*.csproj"); foreach(var file in projectFiles) { settings.Logger = "trx;LogFileName=" + file.GetFilenameWithoutExtension() + "-Results.trx"; try { DotNetCoreTest(file.FullPath, settings); } catch { failCount++; } } if (failCount > 0) throw new Exception($"There were {failCount} test failures."); }); Task("Pack").IsDependentOn("Build").Does(() => { var settings = new DotNetCorePackSettings { Configuration = configuration, NoBuild = true, NoRestore = true, IncludeSource = true, IncludeSymbols = true, OutputDirectory = "./output" }; var projectFiles = GetFiles("./src/**/*.csproj"); foreach (var file in profileFiles) { DotNetCorePack(file.FullPath, settings); } }); Task("Copy").IsDependentOn("Pack").IsDependentOn("Test").Does(() => { CopyFiles("./output/**", (DirectoryPath)"../../output/"); }); /////////////////////////////////////////////////////////////////////////////// // ENTRYPOINTS /////////////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Pack") .IsDependentOn("Copy"); Task("ci") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Pack") .IsDependentOn("Copy"); RunTarget(target);
/////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var nugetVersion = Argument("nugetVersion", EnvironmentVariable("NUGET_VERSION") ?? "1.0.0"); var baseVersion = nugetVersion.Contains("-") ? nugetVersion.Substring(0, nugetVersion.IndexOf("-")) : nugetVersion; var outputDirectory = Argument("artifactsPath", "../../output"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Build").Does(() => { Information("Building with NuGet version: {0}", nugetVersion); Information("Building with assembly version: {0}", baseVersion); MSBuild("./Datasync.Framework.sln", c => c .SetConfiguration(configuration) .EnableBinaryLogger($"./output/build.binlog") .WithRestore() .WithTarget("Pack") .WithProperty("PackageOutputPath", MakeAbsolute((DirectoryPath)"./output").FullPath) .WithProperty("PackageVersion", nugetVersion) .WithProperty("Version", baseVersion)); }); Task("Test").IsDependentOn("Build").Does(() => { var settings = new DotNetCoreTestSettings { Configuration = configuration, NoBuild = true, NoRestore = true, ResultsDirectory = $"./output/unittests-results" }; var failCount = 0; var projectFiles = GetFiles("./test/Microsoft.*/Microsoft.*.csproj"); foreach(var file in projectFiles) { settings.Logger = "trx;LogFileName=" + file.GetFilenameWithoutExtension() + "-Results.trx"; try { DotNetCoreTest(file.FullPath, settings); } catch { failCount++; } } if (failCount > 0) throw new Exception($"There were {failCount} test failures."); }); Task("Copy").Does(() => { CopyFiles("./output/**", (DirectoryPath)"../../output/"); }); /////////////////////////////////////////////////////////////////////////////// // ENTRYPOINTS /////////////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Copy"); Task("ci") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Copy"); RunTarget(target);
mit
C#