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
e57d9d091c5453eb27b6a8a1ad4ac27861401683
Add scope and break operation
lury-lang/lury-ir
LuryIR/Compiling/IR/Operation.cs
LuryIR/Compiling/IR/Operation.cs
// // Operation.cs // // Author: // Tomona Nanase <nanase@users.noreply.github.com> // // The MIT License (MIT) // // Copyright (c) 2015 Tomona Nanase // // 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. namespace Lury.Compiling.IR { public enum Operation { Nop, Load, Store, Scope, Break, Inc, Dec, Pos, Neg, Bnot, Pow, Mul, Div, Idiv, Mod, Add, Sub, Con, Shl, Shr, And, Xor, Or, Lt, Gt, Ltq, Gtq, Eq, Neq, Is, Isn, Lnot, Land, Lor, Ret, Yield, Throw, Call, Eval, Jmp, Jmpt, Jmpf, Jmpn, Catch, Ovlok, Func, Class, Annot, } }
// // Operation.cs // // Author: // Tomona Nanase <nanase@users.noreply.github.com> // // The MIT License (MIT) // // Copyright (c) 2015 Tomona Nanase // // 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. namespace Lury.Compiling.IR { public enum Operation { Nop, Load, Store, Inc, Dec, Pos, Neg, Bnot, Pow, Mul, Div, Idiv, Mod, Add, Sub, Con, Shl, Shr, And, Xor, Or, Lt, Gt, Ltq, Gtq, Eq, Neq, Is, Isn, Lnot, Land, Lor, Ret, Yield, Throw, Call, Eval, Jmp, Jmpt, Jmpf, Jmpn, Catch, Ovlok, Func, Class, Annot, } }
mit
C#
5ca7862c91245c4633c68d4f6a690fb54d185e3e
Fix hash code to use a tuple.
KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog
src/StructuredLogViewer.Core/ProjectImport.cs
src/StructuredLogViewer.Core/ProjectImport.cs
using System; namespace StructuredLogViewer { public struct ProjectImport : IEquatable<ProjectImport> { public ProjectImport(string importedProject, int line, int column) { ProjectPath = importedProject; Line = line; Column = column; } public string ProjectPath { get; set; } /// <summary> /// 0-based /// </summary> public int Line { get; set; } public int Column { get; set; } public bool Equals(ProjectImport other) { return ProjectPath == other.ProjectPath && Line == other.Line && Column == other.Column; } public override bool Equals(object obj) { if (obj is ProjectImport other) { return Equals(other); } return false; } public override int GetHashCode() { return (ProjectPath, Line, Column).GetHashCode(); } public override string ToString() { return $"{ProjectPath} ({Line},{Column})"; } } }
using System; namespace StructuredLogViewer { public struct ProjectImport : IEquatable<ProjectImport> { public ProjectImport(string importedProject, int line, int column) { ProjectPath = importedProject; Line = line; Column = column; } public string ProjectPath { get; set; } /// <summary> /// 0-based /// </summary> public int Line { get; set; } public int Column { get; set; } public bool Equals(ProjectImport other) { return ProjectPath == other.ProjectPath && Line == other.Line && Column == other.Column; } public override bool Equals(object obj) { if (obj is ProjectImport other) { return Equals(other); } return false; } public override int GetHashCode() { return ProjectPath.GetHashCode() ^ Line.GetHashCode() ^ Column.GetHashCode(); } public override string ToString() { return $"{ProjectPath} ({Line},{Column})"; } } }
mit
C#
7d26c47ef3c6000a9fe4dafa585fefe135ce093c
Improve test name and assertion
jagrem/slang,jagrem/slang,jagrem/slang
tests/Compiler/Clr.Tests/Compilation/CSharp/CSharpAssemblyGeneratorTests.cs
tests/Compiler/Clr.Tests/Compilation/CSharp/CSharpAssemblyGeneratorTests.cs
using System.Reflection; using FluentAssertions; using slang.Compiler.Clr.Compilation.Core.Builders; using slang.Compiler.Clr.Compilation.CSharp; using Xunit; namespace Clr.Tests.Compilation.CSharp { public class CSharpAssemblyGeneratorTests { [Fact] public void Given_a_defined_module_When_compiled_Then_a_corresponding_public_class_is_created() { // Arrange var subject = new CSharpAssemblyGenerator(); var assemblyDefinition = AssemblyDefinitionBuilder .Create("slang") .AsLibrary() .AddModule(m => m .WithName("CSharpAssemblyGeneratorTestModule") .WithNamespace("slang.Clr.Tests")) .Build(); // Act var result = subject.GenerateDynamicAssembly(assemblyDefinition); // Assert var typeInfo = result.GetType("slang.Clr.Tests.CSharpAssemblyGeneratorTestModule", true).GetTypeInfo(); typeInfo.IsPublic.Should().BeTrue(); } } }
using slang.Compiler.Clr.Compilation.Core.Builders; using slang.Compiler.Clr.Compilation.CSharp; using Xunit; namespace Clr.Tests.Compilation.CSharp { public class CSharpAssemblyGeneratorTests { [Fact] public void Given_a_defined_module_When_compiled_Then_a_CLR_class_is_created() { // Arrange var subject = new CSharpAssemblyGenerator(); var assemblyDefinition = AssemblyDefinitionBuilder .Create("slang") .AsLibrary() .AddModule(m => m .WithName("CSharpAssemblyGeneratorTestModule") .WithNamespace("slang.Clr.Tests")) .Build(); // Act var result = subject.GenerateDynamicAssembly(assemblyDefinition); // Assert result.GetType("slang.Clr.Tests.CSharpAssemblyGeneratorTestModule", true); } } }
mit
C#
19db35501e156ceaaf45f65bb4360dc4d859a68f
Fix incorrect end date usage in timeshift ready button
NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu
osu.Game/Screens/Multi/Timeshift/TimeshiftReadyButton.cs
osu.Game/Screens/Multi/Timeshift/TimeshiftReadyButton.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi.Components; namespace osu.Game.Screens.Multi.Timeshift { public class TimeshiftReadyButton : ReadyButton { [Resolved(typeof(Room), nameof(Room.EndDate))] private Bindable<DateTimeOffset> endDate { get; set; } public TimeshiftReadyButton() { Text = "Start"; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Green; Triangles.ColourDark = colours.Green; Triangles.ColourLight = colours.GreenLight; } protected override void Update() { base.Update(); Enabled.Value = DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(GameBeatmap.Value.Track.Length) < endDate.Value; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi.Components; namespace osu.Game.Screens.Multi.Timeshift { public class TimeshiftReadyButton : ReadyButton { [Resolved(typeof(Room), nameof(Room.EndDate))] private Bindable<DateTimeOffset?> endDate { get; set; } public TimeshiftReadyButton() { Text = "Start"; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Green; Triangles.ColourDark = colours.Green; Triangles.ColourLight = colours.GreenLight; } protected override void Update() { base.Update(); Enabled.Value = endDate.Value == null || DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(GameBeatmap.Value.Track.Length) < endDate.Value; } } }
mit
C#
8cd2db6cd4acdb7d3b8f4ad1186ca51fb4b03d47
improve assertion for event senders
mastersign/Mastersign.Tasks
src/LibraryTests/Monitoring/EventHistory.cs
src/LibraryTests/Monitoring/EventHistory.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mastersign.Tasks.Test.Monitors { public class EventHistory : ICollection<EventRecord>, ICollection { public EventRecord[] EventRecords { get; } public EventHistory(EventRecord[] records) { EventRecords = records; } public T[] PropertyValues<T>() { return EventRecords.Select(er => { var v = er.ValueUpdate?.GetNewValue(); return v == null ? default(T) : (T)v; }).ToArray(); } public EventRecord First => EventRecords.Length > 0 ? EventRecords[0] : null; public EventRecord Last => EventRecords.Length > 0 ? EventRecords[EventRecords.Length - 1] : null; public void AssertEventNames(params string[] eventNames) { CollectionAssert.AreEqual(EventRecords.Select(re => re.EventName).ToArray(), eventNames); } public void AssertPropertyValues<T>(params T[] values) { CollectionAssert.AreEqual(PropertyValues<T>(), values); } public void AssertSender(object sender) { foreach (var re in EventRecords) { Assert.AreEqual(sender, re.Sender, "The sender of the event is unexpected."); } } #region ICollection Implementation public int Count => EventRecords.Length; public object SyncRoot => EventRecords; public bool IsSynchronized => true; public void CopyTo(Array array, int index) => EventRecords.CopyTo(array, index); #endregion #region ICollection<EventRecord> Implementation public bool Contains(EventRecord item) => EventRecords.Contains(item); public void CopyTo(EventRecord[] array, int arrayIndex) => EventRecords.CopyTo(array, arrayIndex); public IEnumerator<EventRecord> GetEnumerator() => EventRecords.Where(er => true).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => EventRecords.GetEnumerator(); public bool IsReadOnly => true; public void Add(EventRecord item) => throw new NotSupportedException(); public bool Remove(EventRecord item) => throw new NotSupportedException(); public void Clear() => throw new NotSupportedException(); #endregion } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mastersign.Tasks.Test.Monitors { public class EventHistory : ICollection<EventRecord>, ICollection { public EventRecord[] EventRecords { get; } public EventHistory(EventRecord[] records) { EventRecords = records; } public T[] PropertyValues<T>() { return EventRecords.Select(er => { var v = er.ValueUpdate?.GetNewValue(); return v == null ? default(T) : (T)v; }).ToArray(); } public EventRecord First => EventRecords.Length > 0 ? EventRecords[0] : null; public EventRecord Last => EventRecords.Length > 0 ? EventRecords[EventRecords.Length - 1] : null; public void AssertEventNames(params string[] eventNames) { CollectionAssert.AreEqual(EventRecords.Select(re => re.EventName).ToArray(), eventNames); } public void AssertPropertyValues<T>(params T[] values) { CollectionAssert.AreEqual(PropertyValues<T>(), values); } public void AssertSender(object sender) { Assert.IsTrue(EventRecords.All(re => re.Sender == sender), "Not all recored events had the asserted sender."); } #region ICollection Implementation public int Count => EventRecords.Length; public object SyncRoot => EventRecords; public bool IsSynchronized => true; public void CopyTo(Array array, int index) => EventRecords.CopyTo(array, index); #endregion #region ICollection<EventRecord> Implementation public bool Contains(EventRecord item) => EventRecords.Contains(item); public void CopyTo(EventRecord[] array, int arrayIndex) => EventRecords.CopyTo(array, arrayIndex); public IEnumerator<EventRecord> GetEnumerator() => EventRecords.Where(er => true).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => EventRecords.GetEnumerator(); public bool IsReadOnly => true; public void Add(EventRecord item) => throw new NotSupportedException(); public bool Remove(EventRecord item) => throw new NotSupportedException(); public void Clear() => throw new NotSupportedException(); #endregion } }
mit
C#
951e68207046a9d83a91fdb9ca35f1b597c4abf8
remove constant
piotrpMSFT/cli-old,nguerrera/cli,livarcocc/cli-1,livarcocc/cli-1,mylibero/cli,AbhitejJohn/cli,EdwardBlair/cli,krwq/cli,borgdylan/dotnet-cli,anurse/Cli,mylibero/cli,Faizan2304/cli,danquirk/cli,johnbeisner/cli,piotrpMSFT/cli-old,jaredpar/cli,piotrpMSFT/cli-old,jonsequitur/cli,MichaelSimons/cli,MichaelSimons/cli,nguerrera/cli,FubarDevelopment/cli,jonsequitur/cli,FubarDevelopment/cli,gkhanna79/cli,ravimeda/cli,MichaelSimons/cli,AbhitejJohn/cli,Faizan2304/cli,FubarDevelopment/cli,jkotas/cli,blackdwarf/cli,jkotas/cli,borgdylan/dotnet-cli,mlorbetske/cli,schellap/cli,stuartleeks/dotnet-cli,gkhanna79/cli,schellap/cli,gkhanna79/cli,piotrpMSFT/cli-old,JohnChen0/cli,krwq/cli,dasMulli/cli,Faizan2304/cli,jaredpar/cli,stuartleeks/dotnet-cli,krwq/cli,harshjain2/cli,EdwardBlair/cli,JohnChen0/cli,piotrpMSFT/cli-old,piotrpMSFT/cli-old,harshjain2/cli,dasMulli/cli,schellap/cli,gkhanna79/cli,MichaelSimons/cli,mylibero/cli,svick/cli,marono/cli,borgdylan/dotnet-cli,nguerrera/cli,marono/cli,mlorbetske/cli,schellap/cli,jonsequitur/cli,jaredpar/cli,dasMulli/cli,marono/cli,naamunds/cli,danquirk/cli,svick/cli,stuartleeks/dotnet-cli,nguerrera/cli,krwq/cli,mylibero/cli,borgdylan/dotnet-cli,svick/cli,mylibero/cli,JohnChen0/cli,ravimeda/cli,marono/cli,jonsequitur/cli,blackdwarf/cli,jkotas/cli,jaredpar/cli,harshjain2/cli,MichaelSimons/cli,mlorbetske/cli,blackdwarf/cli,weshaggard/cli,stuartleeks/dotnet-cli,EdwardBlair/cli,weshaggard/cli,naamunds/cli,danquirk/cli,blackdwarf/cli,naamunds/cli,mlorbetske/cli,marono/cli,danquirk/cli,danquirk/cli,livarcocc/cli-1,krwq/cli,FubarDevelopment/cli,schellap/cli,johnbeisner/cli,weshaggard/cli,weshaggard/cli,jkotas/cli,jaredpar/cli,naamunds/cli,stuartleeks/dotnet-cli,borgdylan/dotnet-cli,JohnChen0/cli,weshaggard/cli,schellap/cli,AbhitejJohn/cli,ravimeda/cli,naamunds/cli,jaredpar/cli,gkhanna79/cli,johnbeisner/cli,AbhitejJohn/cli,jkotas/cli
src/Microsoft.DotNet.Cli.Utils/Constants.cs
src/Microsoft.DotNet.Cli.Utils/Constants.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace Microsoft.DotNet.Cli.Utils { internal static class Constants { public static readonly string ExeSuffix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : string.Empty; public static readonly string HostExecutableName = "corehost" + ExeSuffix; public static readonly string DefaultConfiguration = "Debug"; public static readonly string BinDirectoryName = "bin"; public static readonly string ObjDirectoryName = "obj"; public static readonly string DynamicLibSuffix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".dll" : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? ".dylib" : ".so"; public static readonly string StaticLibSuffix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".lib" : ".a" ; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace Microsoft.DotNet.Cli.Utils { internal static class Constants { public static readonly string ExeSuffix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : string.Empty; public static readonly string HostExecutableName = "corehost" + ExeSuffix; public static readonly string DefaultConfiguration = "Debug"; public static readonly string BinDirectoryName = "bin"; public static readonly string ObjDirectoryName = "obj"; public static readonly string DynamicLibSuffix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".dll" : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? ".dylib" : ".so"; public static readonly string StaticLibSuffix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".lib" : ".a" ; public static readonly string ClrPathEnvironmentVariable = "DOTNET_CLR_PATH"; } }
mit
C#
ce4304667d1bf19ba265cbbd7a9e7c87f6dbfaf2
Fix wrong logic of channel join
gyrosworkshop/Wukong,gyrosworkshop/Wukong
src/Wukong/Controllers/ChannelController.cs
src/Wukong/Controllers/ChannelController.cs
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Options; using System.Security.Claims; using Wukong.Services; using Wukong.Models; using Wukong.Options; using Microsoft.Extensions.Logging; namespace Wukong.Controllers { [Authorize] [Route("api/[controller]")] public class ChannelController : Controller { private readonly ILogger Logger; private readonly IChannelServiceFactory ChannelServiceFactory; private readonly IChannelManager ChannelManager; public ChannelController(IOptions<ProviderOption> providerOption, ILoggerFactory loggerFactory, IChannelServiceFactory channelServiceFactory, IChannelManager channelManager) { ChannelServiceFactory = channelServiceFactory; Logger = loggerFactory.CreateLogger("ChannelController"); ChannelManager = channelManager; } string UserId => HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; // POST api/channel/join [HttpPost("join/{channelId}")] public void Join(string channelId, [FromBody] Join join) { ChannelManager.Leave(join.PreviousChannelId, UserId); ChannelManager.Join(channelId, UserId); } [HttpPost("finished/{channelId}")] public ActionResult Finished(string channelId, [FromBody] ClientSong song) { // FIXME: test whether user joined this channel. var success = Storage.Instance.GetChannel(channelId).ReportFinish(UserId, song); if (success) return NoContent(); else return BadRequest(); } // POST api/channel/updateNextSong [HttpPost("updateNextSong/{channelId}")] public void UpdateNextSong(string channelId, [FromBody] ClientSong song) { // FIXME: test whether user joined this channel. var channel = Storage.Instance.GetChannel(channelId); channel?.UpdateSong(UserId, song); } [HttpPost("downVote/{channelId}")] public ActionResult DownVote(string channelId, [FromBody] ClientSong song) { // FIXME: test whether user joined this channel. var channel = Storage.Instance.GetChannel(channelId); var success = channel.ReportFinish(UserId, song, true); if (success) return NoContent(); else return BadRequest(); } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Options; using System.Security.Claims; using Wukong.Services; using Wukong.Models; using Wukong.Options; using Microsoft.Extensions.Logging; namespace Wukong.Controllers { [Authorize] [Route("api/[controller]")] public class ChannelController : Controller { private readonly ILogger Logger; private readonly IChannelServiceFactory ChannelServiceFactory; private readonly IChannelManager ChannelManager; public ChannelController(IOptions<ProviderOption> providerOption, ILoggerFactory loggerFactory, IChannelServiceFactory channelServiceFactory, IChannelManager channelManager) { ChannelServiceFactory = channelServiceFactory; Logger = loggerFactory.CreateLogger("ChannelController"); ChannelManager = channelManager; } string UserId => HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; // POST api/channel/join [HttpPost("join/{channelId}")] public void Join(string channelId, [FromBody] Join join) { ChannelManager.Leave(channelId, UserId); ChannelManager.Join(channelId, UserId); } [HttpPost("finished/{channelId}")] public ActionResult Finished(string channelId, [FromBody] ClientSong song) { // FIXME: test whether user joined this channel. var success = Storage.Instance.GetChannel(channelId).ReportFinish(UserId, song); if (success) return NoContent(); else return BadRequest(); } // POST api/channel/updateNextSong [HttpPost("updateNextSong/{channelId}")] public void UpdateNextSong(string channelId, [FromBody] ClientSong song) { // FIXME: test whether user joined this channel. var channel = Storage.Instance.GetChannel(channelId); channel?.UpdateSong(UserId, song); } [HttpPost("downVote/{channelId}")] public ActionResult DownVote(string channelId, [FromBody] ClientSong song) { // FIXME: test whether user joined this channel. var channel = Storage.Instance.GetChannel(channelId); var success = channel.ReportFinish(UserId, song, true); if (success) return NoContent(); else return BadRequest(); } } }
mit
C#
dd7441434d6bb20b277f71627175a9136b8cb889
Fix lifestyles of job to dispose after each execution
prinzo/Attack-Of-The-Fines-TA15,prinzo/Attack-Of-The-Fines-TA15,prinzo/Attack-Of-The-Fines-TA15
FineBot/FineBot.Workers/DI/WorkerInstaller.cs
FineBot/FineBot.Workers/DI/WorkerInstaller.cs
using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; namespace FineBot.Workers.DI { public class WorkerInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Classes.FromThisAssembly().Pick().WithService.DefaultInterfaces().LifestyleTransient()); } } }
using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; namespace FineBot.Workers.DI { public class WorkerInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Classes.FromThisAssembly().Pick().WithService.DefaultInterfaces()); } } }
mit
C#
72e2797aa10e571ef1b70cefb123829a8378b658
Disable unit test parallelization
hudl/Mjolnir
Hudl.Mjolnir.Tests/Properties/AssemblyInfo.cs
Hudl.Mjolnir.Tests/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; // 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("Hudl.Mjolnir.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Hudl.Mjolnir.Tests")] [assembly: AssemblyCopyright("Copyright © 2013")] [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)] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // Disabled for now. A number of tests set static configuration state that, // when leaked between parallel tests, makes them quite sad. If we can find // a way to encapsulate that state, or perhaps just group those tests into // a non-parallelized group, we should revisit this. [assembly: CollectionBehavior(DisableTestParallelization = true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("070914b7-5f05-4d47-a275-98bb15754727")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Hudl.Mjolnir.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Hudl.Mjolnir.Tests")] [assembly: AssemblyCopyright("Copyright © 2013")] [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)] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("070914b7-5f05-4d47-a275-98bb15754727")] // 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#
e83d32c1c063118ef6fe9bf0131e231b22636a56
Delete duplicate CoreFX tests (dotnet/coreclr#20532)
shimingsg/corefx,mmitche/corefx,ptoonen/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,wtgodbe/corefx,wtgodbe/corefx,BrennanConroy/corefx,shimingsg/corefx,ericstj/corefx,mmitche/corefx,ptoonen/corefx,ptoonen/corefx,wtgodbe/corefx,mmitche/corefx,ericstj/corefx,mmitche/corefx,mmitche/corefx,BrennanConroy/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ptoonen/corefx,shimingsg/corefx,BrennanConroy/corefx,ViktorHofer/corefx,wtgodbe/corefx,shimingsg/corefx,mmitche/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,ptoonen/corefx,wtgodbe/corefx,ptoonen/corefx,ViktorHofer/corefx,ptoonen/corefx,wtgodbe/corefx,shimingsg/corefx,shimingsg/corefx,mmitche/corefx,ViktorHofer/corefx,shimingsg/corefx,ericstj/corefx
src/Common/src/CoreLib/System/AttributeUsageAttribute.cs
src/Common/src/CoreLib/System/AttributeUsageAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: The class denotes how to specify the usage of an attribute ** ** ===========================================================*/ using System.Reflection; namespace System { /* By default, attributes are inherited and multiple attributes are not allowed */ [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class AttributeUsageAttribute : Attribute { private AttributeTargets _attributeTarget = AttributeTargets.All; // Defaults to all private bool _allowMultiple = false; // Defaults to false private bool _inherited = true; // Defaults to true internal static readonly AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All); //Constructors public AttributeUsageAttribute(AttributeTargets validOn) { _attributeTarget = validOn; } internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited) { _attributeTarget = validOn; _allowMultiple = allowMultiple; _inherited = inherited; } public AttributeTargets ValidOn { get { return _attributeTarget; } } public bool AllowMultiple { get { return _allowMultiple; } set { _allowMultiple = value; } } public bool Inherited { get { return _inherited; } set { _inherited = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: The class denotes how to specify the usage of an attribute ** ** ===========================================================*/ using System.Reflection; namespace System { /* By default, attributes are inherited and multiple attributes are not allowed */ [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class AttributeUsageAttribute : Attribute { private AttributeTargets _attributeTarget = AttributeTargets.All; // Defaults to all private bool _allowMultiple = false; // Defaults to false private bool _inherited = true; // Defaults to true internal static AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All); //Constructors public AttributeUsageAttribute(AttributeTargets validOn) { _attributeTarget = validOn; } internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited) { _attributeTarget = validOn; _allowMultiple = allowMultiple; _inherited = inherited; } public AttributeTargets ValidOn { get { return _attributeTarget; } } public bool AllowMultiple { get { return _allowMultiple; } set { _allowMultiple = value; } } public bool Inherited { get { return _inherited; } set { _inherited = value; } } } }
mit
C#
85f4b700f3c4939b55ba37560d57532ced0d5e54
Add missing throw from DatabaseContextFactory.UseContext()
Cyberboss/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Host/Core/DatabaseContextFactory.cs
src/Tgstation.Server.Host/Core/DatabaseContextFactory.cs
using Microsoft.Extensions.DependencyInjection; using System; using System.Threading.Tasks; using Tgstation.Server.Host.Models; namespace Tgstation.Server.Host.Core { /// <inheritdoc /> sealed class DatabaseContextFactory : IDatabaseContextFactory { /// <summary> /// The <see cref="IServiceScopeFactory"/> for the <see cref="DatabaseContextFactory"/> /// </summary> readonly IServiceScopeFactory scopeFactory; /// <summary> /// Construct a <see cref="DatabaseContextFactory"/> /// </summary> /// <param name="scopeFactory">The value of <see cref="scopeFactory"/>. Created scopes must be able to provide instances of <see cref="IDatabaseContext"/></param> public DatabaseContextFactory(IServiceScopeFactory scopeFactory) { this.scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); using (var scope = scopeFactory.CreateScope()) scope.ServiceProvider.GetRequiredService<IDatabaseContext>(); } /// <inheritdoc /> public async Task UseContext(Func<IDatabaseContext, Task> operation) { if (operation == null) throw new ArgumentNullException(nameof(operation)); using (var scope = scopeFactory.CreateScope()) await operation(scope.ServiceProvider.GetRequiredService<IDatabaseContext>()).ConfigureAwait(false); } } }
using Microsoft.Extensions.DependencyInjection; using System; using System.Threading.Tasks; using Tgstation.Server.Host.Models; namespace Tgstation.Server.Host.Core { /// <inheritdoc /> sealed class DatabaseContextFactory : IDatabaseContextFactory { /// <summary> /// The <see cref="IServiceScopeFactory"/> for the <see cref="DatabaseContextFactory"/> /// </summary> readonly IServiceScopeFactory scopeFactory; /// <summary> /// Construct a <see cref="DatabaseContextFactory"/> /// </summary> /// <param name="scopeFactory">The value of <see cref="scopeFactory"/>. Created scopes must be able to provide instances of <see cref="IDatabaseContext"/></param> public DatabaseContextFactory(IServiceScopeFactory scopeFactory) { this.scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); using (var scope = scopeFactory.CreateScope()) scope.ServiceProvider.GetRequiredService<IDatabaseContext>(); } /// <inheritdoc /> public async Task UseContext(Func<IDatabaseContext, Task> operation) { using (var scope = scopeFactory.CreateScope()) await operation(scope.ServiceProvider.GetRequiredService<IDatabaseContext>()).ConfigureAwait(false); } } }
agpl-3.0
C#
2419c591c4e2a35a7891f84afc9cafbc17731bf4
Simplify code.
jamesqo/roslyn,aelij/roslyn,paulvanbrenk/roslyn,sharwell/roslyn,sharwell/roslyn,agocke/roslyn,reaction1989/roslyn,jcouv/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,reaction1989/roslyn,KevinRansom/roslyn,dpoeschl/roslyn,OmarTawfik/roslyn,tannergooding/roslyn,jmarolf/roslyn,KevinRansom/roslyn,dotnet/roslyn,mavasani/roslyn,swaroop-sridhar/roslyn,diryboy/roslyn,paulvanbrenk/roslyn,MichalStrehovsky/roslyn,OmarTawfik/roslyn,KirillOsenkov/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,jcouv/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,davkean/roslyn,sharwell/roslyn,brettfo/roslyn,genlu/roslyn,DustinCampbell/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,weltkante/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jmarolf/roslyn,davkean/roslyn,cston/roslyn,VSadov/roslyn,AmadeusW/roslyn,aelij/roslyn,jamesqo/roslyn,weltkante/roslyn,tmat/roslyn,AmadeusW/roslyn,wvdd007/roslyn,diryboy/roslyn,davkean/roslyn,tmeschter/roslyn,xasx/roslyn,mgoertz-msft/roslyn,physhi/roslyn,cston/roslyn,stephentoub/roslyn,heejaechang/roslyn,gafter/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,tannergooding/roslyn,tmat/roslyn,panopticoncentral/roslyn,agocke/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,OmarTawfik/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,AlekseyTs/roslyn,eriawan/roslyn,tannergooding/roslyn,mavasani/roslyn,heejaechang/roslyn,bkoelman/roslyn,abock/roslyn,xasx/roslyn,physhi/roslyn,DustinCampbell/roslyn,panopticoncentral/roslyn,diryboy/roslyn,reaction1989/roslyn,weltkante/roslyn,dpoeschl/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,nguerrera/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,nguerrera/roslyn,abock/roslyn,bartdesmet/roslyn,brettfo/roslyn,agocke/roslyn,tmeschter/roslyn,panopticoncentral/roslyn,MichalStrehovsky/roslyn,cston/roslyn,dotnet/roslyn,gafter/roslyn,MichalStrehovsky/roslyn,genlu/roslyn,mavasani/roslyn,paulvanbrenk/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,VSadov/roslyn,xasx/roslyn,bkoelman/roslyn,bartdesmet/roslyn,physhi/roslyn,jcouv/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ErikSchierboom/roslyn,brettfo/roslyn,tmeschter/roslyn,KevinRansom/roslyn,gafter/roslyn,aelij/roslyn,abock/roslyn,bkoelman/roslyn,dpoeschl/roslyn,genlu/roslyn,jasonmalinowski/roslyn,swaroop-sridhar/roslyn,AlekseyTs/roslyn,jamesqo/roslyn,jmarolf/roslyn
src/Workspaces/Core/Portable/VirtualChars/VirtualChar.cs
src/Workspaces/Core/Portable/VirtualChars/VirtualChar.cs
// Copyright (c) Microsoft. 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.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.VirtualChars { /// <summary> /// The Regex parser wants to work over an array of characters, however this array of characters /// is not the same as the array of characters a user types into a string in C# or VB. For example /// In C# someone may write: @"\z". This should appear to the user the same as if they wrote "\\z" /// and the same as "\\\u007a". However, as these all have wildly different presentations for the /// user, there needs to be a way to map back the characters it sees ( '\' and 'z' ) back to the /// ranges of characters the user wrote. /// /// VirtualChar serves this purpose. It contains the interpretted value of any language character/ /// character-escape-sequence, as well as the original SourceText span where that interpretted /// character was created from. This allows the regex engine to both process regexes from any /// language uniformly, but then also produce trees and diagnostics that map back properly to /// the original source text locations that make sense to the user. /// </summary> internal struct VirtualChar : IEquatable<VirtualChar> { public readonly char Char; public readonly TextSpan Span; public VirtualChar(char @char, TextSpan span) { if (span.IsEmpty) { throw new ArgumentException(); } Char = @char; Span = span; } public override bool Equals(object obj) => obj is VirtualChar vc && Equals(vc); public bool Equals(VirtualChar other) => Char == other.Char && Span == other.Span; public override int GetHashCode() { var hashCode = 244102310; hashCode = hashCode * -1521134295 + Char.GetHashCode(); hashCode = hashCode * -1521134295 + Span.GetHashCode(); return hashCode; } public static bool operator ==(VirtualChar char1, VirtualChar char2) => char1.Equals(char2); public static bool operator !=(VirtualChar char1, VirtualChar char2) => !(char1 == char2); public static implicit operator char(VirtualChar vc) => vc.Char; } }
// Copyright (c) Microsoft. 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.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.VirtualChars { /// <summary> /// The Regex parser wants to work over an array of characters, however this array of characters /// is not the same as the array of characters a user types into a string in C# or VB. For example /// In C# someone may write: @"\z". This should appear to the user the same as if they wrote "\\z" /// and the same as "\\\u007a". However, as these all have wildly different presentations for the /// user, there needs to be a way to map back the characters it sees ( '\' and 'z' ) back to the /// ranges of characters the user wrote. /// /// VirtualChar serves this purpose. It contains the interpretted value of any language character/ /// character-escape-sequence, as well as the original SourceText span where that interpretted /// character was created from. This allows the regex engine to both process regexes from any /// language uniformly, but then also produce trees and diagnostics that map back properly to /// the original source text locations that make sense to the user. /// </summary> internal struct VirtualChar : IEquatable<VirtualChar> { public readonly char Char; public readonly TextSpan Span; public VirtualChar(char @char, TextSpan span) { if (span.IsEmpty) { throw new ArgumentException(); } Char = @char; Span = span; } public override bool Equals(object obj) => obj is VirtualChar vc && Equals(vc); public bool Equals(VirtualChar other) => Char == other.Char && Span.Equals(other.Span); public override int GetHashCode() { var hashCode = 244102310; hashCode = hashCode * -1521134295 + base.GetHashCode(); hashCode = hashCode * -1521134295 + Char.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<TextSpan>.Default.GetHashCode(Span); return hashCode; } public static bool operator ==(VirtualChar char1, VirtualChar char2) => char1.Equals(char2); public static bool operator !=(VirtualChar char1, VirtualChar char2) => !(char1 == char2); public static implicit operator char(VirtualChar vc) => vc.Char; } }
mit
C#
3c01e6122301b3ef6e39773d23c5e28c1224c617
Make the testcase a bit more interested and avoid fix warnings.
lnu/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core
src/NHibernate.Test/NHSpecificTest/NH3641/TestFixture.cs
src/NHibernate.Test/NHSpecificTest/NH3641/TestFixture.cs
using System.Linq; using NHibernate.Linq; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3641 { public class TestFixture : BugTestCase { protected override void OnSetUp() { using (var session = OpenSession()) using (var tx = session.BeginTransaction()) { var child = new Entity { Id = 1, Flag = true }; var parent = new Entity { Id = 2, ChildInterface = child, ChildConcrete = child }; session.Save(child); session.Save(parent); tx.Commit(); } } protected override void OnTearDown() { using (var session = OpenSession()) using (var tx = session.BeginTransaction()) { DeleteAll<Entity>(session); tx.Commit(); } } private static void DeleteAll<T>(ISession session) { session.CreateQuery("delete from " + typeof(T).Name).ExecuteUpdate(); } [Test] public void TrueOrChildPropertyConcrete() { using (var session = OpenSession()) { var result = session.Query<IEntity>() .Where(x => x.ChildConcrete == null || x.ChildConcrete.Flag) .ToList(); Assert.That(result, Has.Count.EqualTo(2)); } } [Test] public void TrueOrChildPropertyInterface() { using (var session = OpenSession()) { var result = session.Query<IEntity>() .Where(x => x.ChildInterface == null || ((Entity) x.ChildInterface).Flag) .ToList(); Assert.That(result, Has.Count.EqualTo(2)); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using NHibernate.Linq; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3641 { public class TestFixture : BugTestCase { protected override void OnSetUp() { using (var session = OpenSession()) using (var tx = session.BeginTransaction()) { var child = new Entity { Id = 1, Flag = false }; var parent = new Entity { Id = 2, ChildInterface = child, ChildConcrete = child }; session.Save(child); session.Save(parent); tx.Commit(); } } protected override void OnTearDown() { using (var session = OpenSession()) using (var tx = session.BeginTransaction()) { DeleteAll<Entity>(session); tx.Commit(); } } private static void DeleteAll<T>(ISession session) { session.CreateQuery("delete from " + typeof(T).Name).ExecuteUpdate(); } [Test] public void TrueOrChildPropertyConcrete() { using (var session = OpenSession()) { var result = session.Query<IEntity>().Where(x => true || x.ChildConcrete.Flag).ToList(); Assert.That(result, Has.Count.EqualTo(2)); } } [Test] public void TrueOrChildPropertyInterface() { using (var session = OpenSession()) { var result = session.Query<IEntity>().Where(x => true || ((Entity)x.ChildInterface).Flag).ToList(); Assert.That(result, Has.Count.EqualTo(2)); } } } }
lgpl-2.1
C#
88f00fcdffc2f7f41c1377ce51e23469eff23d33
Update TextAlignmentVertical.cs
asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Formatting/ConfiguringAlignmentSettings/TextAlignmentVertical.cs
Examples/CSharp/Formatting/ConfiguringAlignmentSettings/TextAlignmentVertical.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Formatting.ConfiguringAlignmentSettings { public class TextAlignmentVertical { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Clearing all the worksheets workbook.Worksheets.Clear(); //Adding a new worksheet to the Excel object int i = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[i]; //Accessing the "A1" cell from the worksheet Aspose.Cells.Cell cell = worksheet.Cells["A1"]; //Adding some value to the "A1" cell cell.PutValue("Visit Aspose!"); //Setting the horizontal alignment of the text in the "A1" cell Style style = cell.GetStyle(); //Setting the vertical alignment of the text in a cell style.VerticalAlignment = TextAlignmentType.Center; cell.SetStyle(style); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Formatting.ConfiguringAlignmentSettings { public class TextAlignmentVertical { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Clearing all the worksheets workbook.Worksheets.Clear(); //Adding a new worksheet to the Excel object int i = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[i]; //Accessing the "A1" cell from the worksheet Aspose.Cells.Cell cell = worksheet.Cells["A1"]; //Adding some value to the "A1" cell cell.PutValue("Visit Aspose!"); //Setting the horizontal alignment of the text in the "A1" cell Style style = cell.GetStyle(); //Setting the vertical alignment of the text in a cell style.VerticalAlignment = TextAlignmentType.Center; cell.SetStyle(style); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); } } }
mit
C#
c8650ccc7f8016a861272fd2577e8ddb084e0235
use direct returns
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
src/SqlPersistence/SynchronizedStorage/StorageAdapter.cs
src/SqlPersistence/SynchronizedStorage/StorageAdapter.cs
using System; using System.Data.Common; using System.Data.SqlClient; using System.Threading.Tasks; using System.Transactions; using NServiceBus; using NServiceBus.Extensibility; using NServiceBus.Outbox; using NServiceBus.Persistence; using NServiceBus.Transport; class StorageAdapter : ISynchronizedStorageAdapter { static Task<CompletableSynchronizedStorageSession> EmptyResultTask = Task.FromResult(default(CompletableSynchronizedStorageSession)); SagaInfoCache infoCache; Func<DbConnection> connectionBuilder; public StorageAdapter(Func<DbConnection> connectionBuilder, SagaInfoCache infoCache) { this.connectionBuilder = connectionBuilder; this.infoCache = infoCache; } public Task<CompletableSynchronizedStorageSession> TryAdapt(OutboxTransaction transaction, ContextBag context) { var outboxTransaction = transaction as SqlOutboxTransaction; if (outboxTransaction == null) { return EmptyResultTask; } CompletableSynchronizedStorageSession session = new StorageSession(outboxTransaction.Connection, outboxTransaction.Transaction, false, infoCache); return Task.FromResult(session); } public async Task<CompletableSynchronizedStorageSession> TryAdapt(TransportTransaction transportTransaction, ContextBag context) { SqlConnection existingSqlConnection; SqlTransaction existingSqlTransaction; //SQL server transport in native TX mode if (transportTransaction.TryGet(out existingSqlConnection) && transportTransaction.TryGet(out existingSqlTransaction)) { return new StorageSession(existingSqlConnection, existingSqlTransaction, false, infoCache); } // Transport supports DTC and uses TxScope owned by the transport Transaction transportTx; var scopeTx = Transaction.Current; if (transportTransaction.TryGet(out transportTx) && scopeTx != null && !transportTx.Equals(scopeTx)) { throw new Exception("A TransactionScope has been opened in the current context overriding the one created by the transport. " + "This setup can result in inconsistent data because operations done via connections enlisted in the context scope won't be committed " + "atomically with the receive transaction. To manually control the TransactionScope in the pipeline switch the transport transaction mode " + $"to values lower than '{nameof(TransportTransactionMode.TransactionScope)}'."); } var ambientTransaction = transportTx ?? scopeTx; if (ambientTransaction != null) { var connection = await connectionBuilder.OpenConnection(); connection.EnlistTransaction(ambientTransaction); return new StorageSession(connection, null, true, infoCache); } //Other modes handled by creating a new session. return null; } }
using System; using System.Data.Common; using System.Data.SqlClient; using System.Threading.Tasks; using System.Transactions; using NServiceBus; using NServiceBus.Extensibility; using NServiceBus.Outbox; using NServiceBus.Persistence; using NServiceBus.Transport; class StorageAdapter : ISynchronizedStorageAdapter { static Task<CompletableSynchronizedStorageSession> EmptyResultTask = Task.FromResult(default(CompletableSynchronizedStorageSession)); SagaInfoCache infoCache; Func<DbConnection> connectionBuilder; public StorageAdapter(Func<DbConnection> connectionBuilder, SagaInfoCache infoCache) { this.connectionBuilder = connectionBuilder; this.infoCache = infoCache; } public Task<CompletableSynchronizedStorageSession> TryAdapt(OutboxTransaction transaction, ContextBag context) { var outboxTransaction = transaction as SqlOutboxTransaction; if (outboxTransaction == null) { return EmptyResultTask; } CompletableSynchronizedStorageSession session = new StorageSession(outboxTransaction.Connection, outboxTransaction.Transaction, false, infoCache); return Task.FromResult(session); } public async Task<CompletableSynchronizedStorageSession> TryAdapt(TransportTransaction transportTransaction, ContextBag context) { SqlConnection existingSqlConnection; SqlTransaction existingSqlTransaction; //SQL server transport in native TX mode if (transportTransaction.TryGet(out existingSqlConnection) && transportTransaction.TryGet(out existingSqlTransaction)) { CompletableSynchronizedStorageSession session = new StorageSession(existingSqlConnection, existingSqlTransaction, false, infoCache); return session; } // Transport supports DTC and uses TxScope owned by the transport Transaction transportTx; var scopeTx = Transaction.Current; if (transportTransaction.TryGet(out transportTx) && scopeTx != null && !transportTx.Equals(scopeTx)) { throw new Exception("A TransactionScope has been opened in the current context overriding the one created by the transport. " + "This setup can result in inconsistent data because operations done via connections enlisted in the context scope won't be committed " + "atomically with the receive transaction. To manually control the TransactionScope in the pipeline switch the transport transaction mode " + $"to values lower than '{nameof(TransportTransactionMode.TransactionScope)}'."); } var ambientTransaction = transportTx ?? scopeTx; if (ambientTransaction != null) { var connection = await connectionBuilder.OpenConnection(); connection.EnlistTransaction(ambientTransaction); CompletableSynchronizedStorageSession session = new StorageSession(connection, null, true, infoCache); return session; } //Other modes handled by creating a new session. return null; } }
mit
C#
a33d8ed413600b23ea06b0ca8dd269bc3f7237a8
update ChangeCultureTest to pass in any culture :trollface:
thorgeirk11/code-cracker,modulexcite/code-cracker,code-cracker/code-cracker,kindermannhubert/code-cracker,thomaslevesque/code-cracker,dlsteuer/code-cracker,ElemarJR/code-cracker,baks/code-cracker,jwooley/code-cracker,jhancock93/code-cracker,robsonalves/code-cracker,GuilhermeSa/code-cracker,carloscds/code-cracker,dmgandini/code-cracker,giggio/code-cracker,andrecarlucci/code-cracker,caioadz/code-cracker,carloscds/code-cracker,eriawan/code-cracker,eirielson/code-cracker,code-cracker/code-cracker,akamud/code-cracker,AlbertoMonteiro/code-cracker,gerryaobrien/code-cracker,adraut/code-cracker
test/CSharp/CodeCracker.Test/ChangeCultureTests.cs
test/CSharp/CodeCracker.Test/ChangeCultureTests.cs
#pragma warning disable CC0022 //todo: remove this pragma as soon as CC0022 is fixed (issue #319) using FluentAssertions; using Xunit; namespace CodeCracker.Test.CSharp { public class ChangeCultureTests { [Fact] public void ChangesCulture() { using (new ChangeCulture("en-US")) 2.5.ToString().Should().Be("2.5"); using (new ChangeCulture("pt-BR")) 2.5.ToString().Should().Be("2,5"); using (new ChangeCulture("")) 2.5.ToString().Should().Be("2.5"); } } } #pragma warning restore CC0022
#pragma warning disable CC0022 //todo: remove this pragma as soon as CC0022 is fixed (issue #319) using FluentAssertions; using Xunit; namespace CodeCracker.Test.CSharp { public class ChangeCultureTests { [Fact] public void ChangesCulture() { 2.5.ToString().Should().Be("2.5"); using (new ChangeCulture("pt-BR")) 2.5.ToString().Should().Be("2,5"); 2.5.ToString().Should().Be("2.5"); } } } #pragma warning restore CC0022
apache-2.0
C#
74f1f31b4a6089634119f425e3a83e4c85926cef
Delete PayRent in District.cs
iwelina-popova/Blackcurrant-team
MonopolyGame/MonopolyGame/Model/Classes/District.cs
MonopolyGame/MonopolyGame/Model/Classes/District.cs
namespace MonopolyGame.Model.Classes { using System; using System.Linq; using System.Collections.Generic; public class District { public List<StreetTile> Section { get; set; } public District() { this.Section = new List<StreetTile>(); } public List<StreetTile> LoadDistrict(List<StreetTile> streets, StreetTile currentStreet) { foreach (var street in streets) { if (street.Color == currentStreet.Color) { this.Section.Add(street); } } return this.Section; } public bool CheckDistrictOwner() { var owner = this.Section.First().Owner; foreach (var street in this.Section) { if (street.Owner != owner) { return false; } } return true; } } }
namespace MonopolyGame.Model.Classes { using System; using System.Linq; using System.Collections.Generic; public class District { public List<StreetTile> Section { get; set; } public District() { this.Section = new List<StreetTile>(); } public List<StreetTile> LoadDistrict(List<StreetTile> streets, StreetTile currentStreet) { foreach (var street in streets) { if (street.Color == currentStreet.Color) { this.Section.Add(street); } } return this.Section; } public bool CheckDistrictOwner() { var owner = this.Section.First().Owner; foreach (var street in this.Section) { if (street.Owner != owner) { return false; } } return true; } public int PayRent() { int districtRent = 0; foreach (var street in this.Section) { districtRent += street.BaseRent; } return districtRent; } } }
mit
C#
076a045ca94c8d74abef0f2aa7593e21144d6368
Change delay.
vebin/Foundatio,Bartmax/Foundatio,FoundatioFx/Foundatio,wgraham17/Foundatio,exceptionless/Foundatio
src/Core/Tests/Jobs/WithLockingJob.cs
src/Core/Tests/Jobs/WithLockingJob.cs
using System; using System.Threading; using System.Threading.Tasks; using Foundatio.Caching; using Foundatio.Extensions; using Foundatio.Jobs; using Foundatio.Lock; using Xunit; namespace Foundatio.Tests.Jobs { public class WithLockingJob : JobBase { private readonly ILockProvider _locker = new CacheLockProvider(new InMemoryCacheClient()); public int RunCount { get; set; } protected override IDisposable GetJobLock() { return _locker.TryAcquireLock("WithLockingJob", TimeSpan.FromSeconds(1), TimeSpan.Zero); } protected override Task<JobResult> RunInternalAsync(CancellationToken token) { RunCount++; Thread.Sleep(150); Assert.True(_locker.IsLocked("WithLockingJob")); return Task.FromResult(JobResult.Success); } } }
using System; using System.Threading; using System.Threading.Tasks; using Foundatio.Caching; using Foundatio.Extensions; using Foundatio.Jobs; using Foundatio.Lock; using Xunit; namespace Foundatio.Tests.Jobs { public class WithLockingJob : JobBase { private readonly ILockProvider _locker = new CacheLockProvider(new InMemoryCacheClient()); public int RunCount { get; set; } protected override IDisposable GetJobLock() { return _locker.TryAcquireLock("WithLockingJob", TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(50)); } protected override Task<JobResult> RunInternalAsync(CancellationToken token) { RunCount++; Thread.Sleep(150); Assert.True(_locker.IsLocked("WithLockingJob")); return Task.FromResult(JobResult.Success); } } }
apache-2.0
C#
ade9623f8ec04a764ba9e7816e39f38e9096bbfb
Fix - Cancellazione squadra quando torna in sede
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
src/backend/SO115App.Persistence.MongoDB/GestioneStatoSquadra/SetStatoSquadra.cs
src/backend/SO115App.Persistence.MongoDB/GestioneStatoSquadra/SetStatoSquadra.cs
//----------------------------------------------------------------------- // <copyright file="SetStatoSquadra.cs" company="CNVVF"> // Copyright (C) 2017 - CNVVF // // This file is part of SOVVF. // SOVVF is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // SOVVF 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> //----------------------------------------------------------------------- using MongoDB.Driver; using Persistence.MongoDB; using SO115App.Models.Classi.Condivise; using SO115App.Models.Servizi.Infrastruttura.GestioneStatoOperativoSquadra; namespace SO115App.Persistence.MongoDB.GestioneStatoSquadra { /// <summary> /// classe che implementa il servizio ISetStatoSquadra e va a scrivere lo stesso su MongoDB /// </summary> public class SetStatoSquadra : ISetStatoSquadra { private readonly DbContext _dbContext; public SetStatoSquadra(DbContext dbContext) { _dbContext = dbContext; } /// <summary> /// metodo che va a scrivere su MongoDB /// </summary> /// <param name="idSquadra">l'identificativo della squadra</param> /// <param name="idRichiesta">l'id della richiesta</param> /// <param name="statoSquadra">lo stato della squadra</param> public void SetStato(string idSquadra, string idRichiesta, string statoSquadra, string codiceSede) { var statoOperativoSquadra = new StatoOperativoSquadra { IdRichiesta = idRichiesta, IdSquadra = idSquadra, StatoSquadra = statoSquadra, CodiceSede = codiceSede }; if (statoOperativoSquadra.StatoSquadra.Equals("In Sede")) { _dbContext.StatoSquadraCollection.DeleteOne(Builders<StatoOperativoSquadra>.Filter.Eq(x => x.IdSquadra, idSquadra)); } else { var findAndReplaceOptions = new FindOneAndReplaceOptions<StatoOperativoSquadra> { IsUpsert = true }; _dbContext.StatoSquadraCollection.FindOneAndReplace(Builders<StatoOperativoSquadra>.Filter.Eq(x => x.IdSquadra, idSquadra), statoOperativoSquadra, findAndReplaceOptions); } } } }
//----------------------------------------------------------------------- // <copyright file="SetStatoSquadra.cs" company="CNVVF"> // Copyright (C) 2017 - CNVVF // // This file is part of SOVVF. // SOVVF is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // SOVVF 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> //----------------------------------------------------------------------- using MongoDB.Driver; using Persistence.MongoDB; using SO115App.Models.Classi.Condivise; using SO115App.Models.Servizi.Infrastruttura.GestioneStatoOperativoSquadra; namespace SO115App.Persistence.MongoDB.GestioneStatoSquadra { /// <summary> /// classe che implementa il servizio ISetStatoSquadra e va a scrivere lo stesso su MongoDB /// </summary> public class SetStatoSquadra : ISetStatoSquadra { private readonly DbContext _dbContext; public SetStatoSquadra(DbContext dbContext) { _dbContext = dbContext; } /// <summary> /// metodo che va a scrivere su MongoDB /// </summary> /// <param name="idSquadra">l'identificativo della squadra</param> /// <param name="idRichiesta">l'id della richiesta</param> /// <param name="statoSquadra">lo stato della squadra</param> public void SetStato(string idSquadra, string idRichiesta, string statoSquadra, string codiceSede) { var statoOperativoSquadra = new StatoOperativoSquadra { IdRichiesta = idRichiesta, IdSquadra = idSquadra, StatoSquadra = statoSquadra, CodiceSede = codiceSede }; var findAndReplaceOptions = new FindOneAndReplaceOptions<StatoOperativoSquadra> { IsUpsert = true }; _dbContext.StatoSquadraCollection.FindOneAndReplace(Builders<StatoOperativoSquadra>.Filter.Eq(x => x.IdSquadra, idSquadra), statoOperativoSquadra, findAndReplaceOptions); } } }
agpl-3.0
C#
4f8e912f063b08ed8be5afb2a513d8c804092685
Fix `APINotification` parsing failing
peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu
osu.Game/Online/API/Requests/Responses/APINotification.cs
osu.Game/Online/API/Requests/Responses/APINotification.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 Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace osu.Game.Online.API.Requests.Responses { [JsonObject(MemberSerialization.OptIn)] public class APINotification { [JsonProperty(@"id")] public long Id { get; set; } [JsonProperty(@"name")] public string Name { get; set; } = null!; [JsonProperty(@"created_at")] public DateTimeOffset? CreatedAt { get; set; } [JsonProperty(@"object_type")] public string ObjectType { get; set; } = null!; [JsonProperty(@"object_id")] public string ObjectId { get; set; } = null!; [JsonProperty(@"source_user_id")] public long? SourceUserId { get; set; } [JsonProperty(@"is_read")] public bool IsRead { get; set; } [JsonProperty(@"details")] public JObject? Details { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using Newtonsoft.Json; namespace osu.Game.Online.API.Requests.Responses { [JsonObject(MemberSerialization.OptIn)] public class APINotification { [JsonProperty(@"id")] public long Id { get; set; } [JsonProperty(@"name")] public string Name { get; set; } = null!; [JsonProperty(@"created_at")] public DateTimeOffset? CreatedAt { get; set; } [JsonProperty(@"object_type")] public string ObjectType { get; set; } = null!; [JsonProperty(@"object_id")] public string ObjectId { get; set; } = null!; [JsonProperty(@"source_user_id")] public long? SourceUserId { get; set; } [JsonProperty(@"is_read")] public bool IsRead { get; set; } [JsonProperty(@"details")] public Dictionary<string, string>? Details { get; set; } } }
mit
C#
3b599f94776e3b937bddc866c0ce13e826168d7a
add HasInterestInMma to ListAgencies
CodeForCharlotte/Mentor,CodeForCharlotte/Mentor
src/Mentor/Views/Agency/ListAgencies.cshtml
src/Mentor/Views/Agency/ListAgencies.cshtml
@model List<Agency> @{ ViewBag._Title = "List Agencies"; } <h1 class="page-header">@ViewBag._Title</h1> <div class="form-group"> <form method="POST" enctype="multipart/form-data" action="@Url.Action("ImportAgencies")"> @Html.ActionLink("Add Agency", "EditAgency", null, new { @class = "btn btn-primary" }) | <input type="file" name="InputFile" style="display:inline-block;" /> @Html.SubmitButton("Import Agencies (xlsx)", new { @class = "btn btn-default" }) | @Html.ActionLink("Export Agencies (xlsx)", "ExportAgencies", null, new { @class = "btn btn-default" }) </form> </div> <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Address</th> <th>Phone</th> <th>Website</th> <th>MMA</th> </tr> </thead> <tbody> @foreach (var agency in Model) { <tr> <td>@Html.ActionLink("Edit " + agency.Id, "EditAgency", new { agency.Id })</td> <td>@agency.Name</td> <td>@agency.Address</td> <td>@agency.Phone</td> <td><a href="@agency.Website" target="_blank">@agency.Website.Left(40, "...")</a></td> <td>@agency.HasInterestInMma</td> </tr> } </tbody> </table>
@model List<Agency> @{ ViewBag._Title = "List Agencies"; } <h1 class="page-header">@ViewBag._Title</h1> <div class="form-group"> <form method="POST" enctype="multipart/form-data" action="@Url.Action("ImportAgencies")"> @Html.ActionLink("Add Agency", "EditAgency", null, new { @class = "btn btn-primary" }) | <input type="file" name="InputFile" style="display:inline-block;" /> @Html.SubmitButton("Import Agencies (xlsx)", new { @class = "btn btn-default" }) | @Html.ActionLink("Export Agencies (xlsx)", "ExportAgencies", null, new { @class = "btn btn-default" }) </form> </div> <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Address</th> <th>Phone</th> <th>Website</th> </tr> </thead> <tbody> @foreach (var agency in Model) { <tr> <td>@Html.ActionLink("Edit " + agency.Id, "EditAgency", new { agency.Id })</td> <td>@agency.Name</td> <td>@agency.Address</td> <td>@agency.Phone</td> <td><a href="@agency.Website" target="_blank">@agency.Website.Left(40, "...")</a></td> </tr> } </tbody> </table>
mit
C#
4a0b7acae6daa5a2d049dc0aa268e49b40441791
Change the title
chuckeles/Udpit
MainForm.Designer.cs
MainForm.Designer.cs
namespace Udpit { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Name = "MainForm"; this.Text = "Udpit"; this.ResumeLayout(false); } #endregion } }
namespace Udpit { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Text = "MainForm"; } #endregion } }
mit
C#
a1a9877e772b029626544f184e60aef541b00a6d
Update version.
LogosBible/Leeroy
src/Leeroy/Properties/AssemblyInfo.cs
src/Leeroy/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Leeroy Build Service")] [assembly: AssemblyDescription("Updates a build git repo when submodules change.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Leeroy")] [assembly: AssemblyCopyright("Copyright 2012-2017 Faithlife")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.7.2.0")] [assembly: AssemblyFileVersion("1.7.2.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Leeroy Build Service")] [assembly: AssemblyDescription("Updates a build git repo when submodules change.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Leeroy")] [assembly: AssemblyCopyright("Copyright 2012-2014 Logos Bible Software")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.7.0.0")] [assembly: AssemblyFileVersion("1.7.0.0")]
mit
C#
e2404c13987e4c70f57016cdbd8ad8b1aacc8514
Update Security Manager to include Parameters
JoeBurns27/FactoryByReflection
src/Security/Interfaces/ISecurityManager.cs
src/Security/Interfaces/ISecurityManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Jebur27.Security.Interfaces { public interface ISecurityManager { string UserName { get; set; } int UserSecurityLevel { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Jebur27.Security.Interfaces { public interface ISecurityManager { } }
mit
C#
d116a3263d71d2a1783165eaa017c9e63fe8fc47
Use BigInteger.Zero instead of implicit conversion
martincostello/project-euler
src/ProjectEuler/Puzzles/Puzzle048.cs
src/ProjectEuler/Puzzles/Puzzle048.cs
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Globalization; using System.Linq; using System.Numerics; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=48</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle048 : Puzzle { /// <inheritdoc /> public override string Question => "Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + N^N."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int n; if (!TryParseInt32(args[0], out n) || n < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } BigInteger value = BigInteger.Zero; foreach (int exponent in Enumerable.Range(1, n)) { value += BigInteger.Pow(exponent, exponent); } string result = value.ToString(CultureInfo.InvariantCulture); result = result.Substring(Math.Max(0, result.Length - 10), 10); Answer = result; return 0; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Globalization; using System.Linq; using System.Numerics; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=48</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle048 : Puzzle { /// <inheritdoc /> public override string Question => "Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + N^N."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int n; if (!TryParseInt32(args[0], out n) || n < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } BigInteger value = 0; foreach (int exponent in Enumerable.Range(1, n)) { value += BigInteger.Pow(exponent, exponent); } string result = value.ToString(CultureInfo.InvariantCulture); result = result.Substring(Math.Max(0, result.Length - 10), 10); Answer = result; return 0; } } }
apache-2.0
C#
2354163900f89a8df4f2fbff4387ddbab1a6bbd5
Change icon for audio settings
2yangk23/osu,johnneijzen/osu,DrabWeb/osu,2yangk23/osu,EVAST9919/osu,naoey/osu,smoogipoo/osu,peppy/osu,ppy/osu,peppy/osu,ZLima12/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,DrabWeb/osu,Nabile-Rahmani/osu,peppy/osu,ppy/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,DrabWeb/osu,naoey/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,naoey/osu,NeoAdonis/osu,Frontear/osuKyzer,ZLima12/osu,UselessToucan/osu,peppy/osu-new
osu.Game/Overlays/Settings/Sections/AudioSection.cs
osu.Game/Overlays/Settings/Sections/AudioSection.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Overlays.Settings.Sections.Audio; namespace osu.Game.Overlays.Settings.Sections { public class AudioSection : SettingsSection { public override string Header => "Audio"; public override FontAwesome Icon => FontAwesome.fa_volume_up; public AudioSection() { Children = new Drawable[] { new AudioDevicesSettings(), new VolumeSettings(), new OffsetSettings(), new MainMenuSettings(), }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Overlays.Settings.Sections.Audio; namespace osu.Game.Overlays.Settings.Sections { public class AudioSection : SettingsSection { public override string Header => "Audio"; public override FontAwesome Icon => FontAwesome.fa_headphones; public AudioSection() { Children = new Drawable[] { new AudioDevicesSettings(), new VolumeSettings(), new OffsetSettings(), new MainMenuSettings(), }; } } }
mit
C#
f3ff814d277836077a535c2cc67981737718b9f2
bump version to 4.0
romansp/MiniProfiler.Elasticsearch
src/MiniProfiler.Elasticsearch/Properties/AssemblyInfo.cs
src/MiniProfiler.Elasticsearch/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("MiniProfiler.Elasticsearch")] [assembly: AssemblyDescription("Elasticsearch extensions for StackExchange.Profiling - http://miniprofiler.com")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("romansp")] [assembly: AssemblyProduct("StackExchange.Profiling.Elasticsearch")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("ed1db334-f263-4470-9be0-1c1e04c57fd5")] [assembly: AssemblyVersion("4.0")] [assembly: AssemblyFileVersion("4.0")]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("MiniProfiler.Elasticsearch")] [assembly: AssemblyDescription("Elasticsearch extensions for StackExchange.Profiling - http://miniprofiler.com")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("romansp")] [assembly: AssemblyProduct("StackExchange.Profiling.Elasticsearch")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("ed1db334-f263-4470-9be0-1c1e04c57fd5")] [assembly: AssemblyVersion("3.2")] [assembly: AssemblyFileVersion("3.2")]
mit
C#
5de063c12cb2cba735571a4014cb0c7762d18337
Simplify deprecated test.
rob-somerville/riak-dotnet-client,basho/riak-dotnet-client,basho/riak-dotnet-client,rob-somerville/riak-dotnet-client
src/RiakClientTests.Live/DataTypes/BasicMapFlagDtTests.cs
src/RiakClientTests.Live/DataTypes/BasicMapFlagDtTests.cs
// <copyright file="BasicMapFlagDtTests.cs" company="Basho Technologies, Inc."> // Copyright 2015 - Basho Technologies // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using RiakClient; using RiakClient.Messages; using RiakClient.Models; #pragma warning disable 618 namespace RiakClientTests.Live.DataTypes { [TestFixture, IntegrationTest] public class BasicMapFlagDtTests : DataTypeTestsBase { [Test] public void TestFlagOperations() { string key = GetRandomKey(); var id = new RiakObjectId(BucketTypeNames.Maps, Bucket, key); const string flagName = "Name"; byte[] flagNameBytes = Serializer(flagName); var options = new RiakDtUpdateOptions(); options.SetIncludeContext(true); options.SetTimeout(new Timeout(TimeSpan.FromSeconds(60))); var flagMapUpdate = new MapUpdate { flag_op = MapUpdate.FlagOp.ENABLE, field = new MapField { name = flagNameBytes, type = MapField.MapFieldType.FLAG } }; var update = new List<MapUpdate> { flagMapUpdate }; var updatedMap1 = Client.DtUpdateMap(id, Serializer, null, null, update, options); Assert.True(updatedMap1.Result.IsSuccess, updatedMap1.Result.ErrorMessage); var mapEntry = updatedMap1.Values.Single(s => s.Field.Name == flagName); Assert.NotNull(mapEntry.FlagValue); Assert.IsTrue(mapEntry.FlagValue.Value); flagMapUpdate.flag_op = MapUpdate.FlagOp.DISABLE; var updatedMap2 = Client.DtUpdateMap(id, Serializer, updatedMap1.Context, null, update, options); Assert.True(updatedMap2.Result.IsSuccess, updatedMap2.Result.ErrorMessage); mapEntry = updatedMap2.Values.Single(s => s.Field.Name == flagName); Assert.NotNull(mapEntry.FlagValue); Assert.IsFalse(mapEntry.FlagValue.Value); } } } #pragma warning restore 618
// <copyright file="BasicMapFlagDtTests.cs" company="Basho Technologies, Inc."> // Copyright 2015 - Basho Technologies // // This file is provided to you 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.Collections.Generic; using System.Linq; using NUnit.Framework; using RiakClient.Messages; using RiakClient.Models; #pragma warning disable 618 namespace RiakClientTests.Live.DataTypes { [TestFixture, IntegrationTest] public class BasicMapFlagDtTests : DataTypeTestsBase { [Test] public void TestFlagOperations() { string key = GetRandomKey(); var id = new RiakObjectId(BucketTypeNames.Maps, Bucket, key); const string flagName = "Name"; var flagMapUpdate = new MapUpdate { flag_op = MapUpdate.FlagOp.DISABLE, field = new MapField { name = Serializer.Invoke(flagName), type = MapField.MapFieldType.FLAG } }; var updatedMap1 = Client.DtUpdateMap(id, Serializer, null, null, new List<MapUpdate> { flagMapUpdate }); Assert.True(updatedMap1.Result.IsSuccess, updatedMap1.Result.ErrorMessage); var mapEntry = updatedMap1.Values.Single(s => s.Field.Name == flagName); Assert.NotNull(mapEntry.FlagValue); Assert.IsFalse(mapEntry.FlagValue.Value); var flagMapUpdate2 = new MapUpdate { flag_op = MapUpdate.FlagOp.ENABLE, field = new MapField { name = Serializer.Invoke(flagName), type = MapField.MapFieldType.FLAG } }; var updatedMap2 = Client.DtUpdateMap(id, Serializer, updatedMap1.Context, null, new List<MapUpdate> { flagMapUpdate2 }); Assert.True(updatedMap2.Result.IsSuccess, updatedMap2.Result.ErrorMessage); mapEntry = updatedMap2.Values.Single(s => s.Field.Name == flagName); Assert.NotNull(mapEntry.FlagValue); Assert.IsTrue(mapEntry.FlagValue.Value); } } } #pragma warning restore 618
apache-2.0
C#
bd3bb063251a19a9da38bf7b1f2752c7be321d73
Fix mismatched use of MEF 1 and 2
brettfo/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,genlu/roslyn,sharwell/roslyn,nguerrera/roslyn,stephentoub/roslyn,bartdesmet/roslyn,agocke/roslyn,stephentoub/roslyn,tannergooding/roslyn,wvdd007/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,davkean/roslyn,weltkante/roslyn,eriawan/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,genlu/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,physhi/roslyn,panopticoncentral/roslyn,agocke/roslyn,heejaechang/roslyn,AmadeusW/roslyn,eriawan/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,reaction1989/roslyn,KirillOsenkov/roslyn,physhi/roslyn,dotnet/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,aelij/roslyn,panopticoncentral/roslyn,abock/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,mavasani/roslyn,abock/roslyn,CyrusNajmabadi/roslyn,reaction1989/roslyn,tmat/roslyn,jasonmalinowski/roslyn,gafter/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,eriawan/roslyn,brettfo/roslyn,diryboy/roslyn,genlu/roslyn,agocke/roslyn,AlekseyTs/roslyn,dotnet/roslyn,abock/roslyn,aelij/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,mavasani/roslyn,tannergooding/roslyn,jmarolf/roslyn,diryboy/roslyn,aelij/roslyn,KirillOsenkov/roslyn,sharwell/roslyn,wvdd007/roslyn,nguerrera/roslyn,reaction1989/roslyn,KevinRansom/roslyn,mavasani/roslyn,diryboy/roslyn,gafter/roslyn,weltkante/roslyn,heejaechang/roslyn,davkean/roslyn,sharwell/roslyn,gafter/roslyn,tmat/roslyn,stephentoub/roslyn,wvdd007/roslyn,physhi/roslyn,davkean/roslyn,tmat/roslyn
src/EditorFeatures/Core.Wpf/Tags/DefaultImageMonikerService.cs
src/EditorFeatures/Core.Wpf/Tags/DefaultImageMonikerService.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.CodeAnalysis.Editor.Tags { [ExportImageMonikerService(Name = Name)] internal class DefaultImageMonikerService : IImageMonikerService { public const string Name = nameof(DefaultImageMonikerService); public bool TryGetImageMoniker(ImmutableArray<string> tags, out ImageMoniker imageMoniker) { var glyph = tags.GetFirstGlyph(); // We can't do the compositing of these glyphs at the editor layer. So just map them // to the non-add versions. switch (glyph) { case Glyph.AddReference: glyph = Glyph.Reference; break; } imageMoniker = glyph.GetImageMoniker(); return !imageMoniker.IsNullImage(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.CodeAnalysis.Editor.Tags { [ExportImageMonikerService(Name = Name), Shared] internal class DefaultImageMonikerService : IImageMonikerService { public const string Name = nameof(DefaultImageMonikerService); public bool TryGetImageMoniker(ImmutableArray<string> tags, out ImageMoniker imageMoniker) { var glyph = tags.GetFirstGlyph(); // We can't do the compositing of these glyphs at the editor layer. So just map them // to the non-add versions. switch (glyph) { case Glyph.AddReference: glyph = Glyph.Reference; break; } imageMoniker = glyph.GetImageMoniker(); return !imageMoniker.IsNullImage(); } } }
mit
C#
45d51e4c6759aff14c23346d0b4e894aceb8d544
Add closing message to sample console runner
nspec/NSpec.VsAdapter,BrainCrumbz/NSpec.VsAdapter
src/NSpec.VsAdapter/Test/Samples/AdHocConsoleRunner/Program.cs
src/NSpec.VsAdapter/Test/Samples/AdHocConsoleRunner/Program.cs
using NSpec; using NSpec.Domain; using NSpec.Domain.Formatters; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace AdHocConsoleRunner { class Program { static void Main(string[] args) { var assemblies = new Assembly[] { typeof(SampleSpecs.DummyPublicClass).Assembly, typeof(ConfigSampleSpecs.DummyPublicClass).Assembly, }; //types that should be considered for testing var types = assemblies.SelectMany(asm => asm.GetTypes()).ToArray(); //now that we have our types, set up a finder so that NSpec //can determine the inheritance hierarchy var finder = new SpecFinder(types); //we've got our inheritance hierarchy, //now we can build our test tree using default conventions var builder = new ContextBuilder(finder, new DefaultConventions()); //create the nspec runner with a //live formatter so we get console output var runner = new ContextRunner( builder, new ConsoleFormatter(), false); //create our final collection of concrete tests var testCollection = builder.Contexts().Build(); //run the tests and get results (to do whatever you want with) var results = runner.Run(testCollection); //console write line to pause the exe Console.WriteLine(Environment.NewLine + "Press <enter> to quit..."); Console.ReadLine(); } } }
using NSpec; using NSpec.Domain; using NSpec.Domain.Formatters; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace AdHocConsoleRunner { class Program { static void Main(string[] args) { var assemblies = new Assembly[] { typeof(SampleSpecs.DummyPublicClass).Assembly, typeof(ConfigSampleSpecs.DummyPublicClass).Assembly, }; //types that should be considered for testing var types = assemblies.SelectMany(asm => asm.GetTypes()).ToArray(); //now that we have our types, set up a finder so that NSpec //can determine the inheritance hierarchy var finder = new SpecFinder(types); //we've got our inheritance hierarchy, //now we can build our test tree using default conventions var builder = new ContextBuilder(finder, new DefaultConventions()); //create the nspec runner with a //live formatter so we get console output var runner = new ContextRunner( builder, new ConsoleFormatter(), false); //create our final collection of concrete tests var testCollection = builder.Contexts().Build(); //run the tests and get results (to do whatever you want with) var results = runner.Run(testCollection); //console write line to pause the exe System.Console.ReadLine(); } } }
mit
C#
b3d1a8400b7a4f716d3c397253dcabe258774730
Fix TestConnectionSettings
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Tests/Tests.Core/Client/Settings/TestConnectionSettings.cs
src/Tests/Tests.Core/Client/Settings/TestConnectionSettings.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Elasticsearch.Net; using Nest; using Tests.Configuration; using Tests.Core.Client.Serializers; using Tests.Core.Extensions; using Tests.Core.Xunit; namespace Tests.Core.Client.Settings { public class TestConnectionSettings : ConnectionSettings { public static readonly bool RunningFiddler = Process.GetProcessesByName("fiddler").Any(); public TestConnectionSettings( Func<ICollection<Uri>, IConnectionPool> createPool = null, SourceSerializerFactory sourceSerializerFactory = null, IPropertyMappingProvider propertyMappingProvider = null, bool forceInMemory = false, int port = 9200 ) : base( CreatePool(createPool, port), TestConfiguration.Instance.CreateConnection(forceInMemory), CreateSerializerFactory(sourceSerializerFactory), propertyMappingProvider ) => ApplyTestSettings(); public static string LocalOrProxyHost => RunningFiddler ? "ipv4.fiddler" : LocalHost; private static int ConnectionLimitDefault => int.TryParse(Environment.GetEnvironmentVariable("NEST_NUMBER_OF_CONNECTIONS"), out var x) ? x : ConnectionConfiguration.DefaultConnectionLimit; private static string LocalHost => "localhost"; internal ConnectionSettings ApplyTestSettings() => EnableDebugMode() //TODO make this random //.EnableHttpCompression() #if DEBUG .EnableDebugMode() #endif .ConnectionLimit(ConnectionLimitDefault) .OnRequestCompleted(r => { if (!r.DeprecationWarnings.Any()) return; var q = r.Uri.Query; //hack to prevent the deprecation warnings from the deprecation response test to be reported if (!string.IsNullOrWhiteSpace(q) && q.Contains("routing=ignoredefaultcompletedhandler")) return; foreach (var d in r.DeprecationWarnings) XunitRunState.SeenDeprecations.Add(d); }); private static SourceSerializerFactory CreateSerializerFactory(SourceSerializerFactory provided) { if (provided != null) return provided; if (!TestConfiguration.Instance.Random.SourceSerializer) return null; return (builtin, values) => new TestSourceSerializerBase(builtin, values); } private static IConnectionPool CreatePool(Func<ICollection<Uri>, IConnectionPool> createPool = null, int port = 9200) { createPool = createPool ?? (uris => new StaticConnectionPool(uris)); var connectionPool = createPool(new[] { CreateUri(port) }); return connectionPool; } public static Uri CreateUri(int port = 9200) => new UriBuilder("http://", LocalOrProxyHost, port).Uri; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Elasticsearch.Net; using Nest; using Tests.Configuration; using Tests.Core.Client.Serializers; using Tests.Core.Extensions; using Tests.Core.Xunit; namespace Tests.Core.Client.Settings { public class TestConnectionSettings : ConnectionSettings { public static readonly bool RunningFiddler = Process.GetProcessesByName("fiddler").Any(); public TestConnectionSettings( Func<ICollection<Uri>, IConnectionPool> createPool = null, SourceSerializerFactory sourceSerializerFactory = null, IPropertyMappingProvider propertyMappingProvider = null, bool forceInMemory = false, int port = 9200 ) : base( CreatePool(createPool, port), TestConfiguration.Instance.CreateConnection(forceInMemory), CreateSerializerFactory(sourceSerializerFactory), propertyMappingProvider ) => ApplyTestSettings(); public static string LocalOrProxyHost => RunningFiddler ? "ipv4.fiddler" : LocalHost; private static int ConnectionLimitDefault => int.TryParse(Environment.GetEnvironmentVariable("NEST_NUMBER_OF_CONNECTIONS"), out var x) ? x : ConnectionConfiguration.DefaultConnectionLimit; private static string LocalHost => "localhost"; internal ConnectionSettings ApplyTestSettings() => EnableDebugMode() #endif .ConnectionLimit(ConnectionLimitDefault) .OnRequestCompleted(r => { if (!r.DeprecationWarnings.Any()) return; var q = r.Uri.Query; //hack to prevent the deprecation warnings from the deprecation response test to be reported if (!string.IsNullOrWhiteSpace(q) && q.Contains("routing=ignoredefaultcompletedhandler")) return; foreach (var d in r.DeprecationWarnings) XunitRunState.SeenDeprecations.Add(d); }); private static SourceSerializerFactory CreateSerializerFactory(SourceSerializerFactory provided) { if (provided != null) return provided; if (!TestConfiguration.Instance.Random.SourceSerializer) return null; return (builtin, values) => new TestSourceSerializerBase(builtin, values); } private static IConnectionPool CreatePool(Func<ICollection<Uri>, IConnectionPool> createPool = null, int port = 9200) { createPool = createPool ?? (uris => new StaticConnectionPool(uris)); var connectionPool = createPool(new[] { CreateUri(port) }); return connectionPool; } public static Uri CreateUri(int port = 9200) => new UriBuilder("http://", LocalOrProxyHost, port).Uri; } }
apache-2.0
C#
25bbfe765f920f92d07865927cae2ea92b7b9bfb
Add comment to class
cPetru/nunit-params,Therzok/nunit,elbaloo/nunit,ArsenShnurkov/nunit,mikkelbu/nunit,dicko2/nunit,modulexcite/nunit,jhamm/nunit,jnm2/nunit,michal-franc/nunit,JustinRChou/nunit,pflugs30/nunit,mikkelbu/nunit,nunit/nunit,akoeplinger/nunit,dicko2/nunit,pcalin/nunit,pflugs30/nunit,nivanov1984/nunit,agray/nunit,michal-franc/nunit,ggeurts/nunit,elbaloo/nunit,Green-Bug/nunit,acco32/nunit,jadarnel27/nunit,agray/nunit,cPetru/nunit-params,passaro/nunit,zmaruo/nunit,jhamm/nunit,Suremaker/nunit,danielmarbach/nunit,JohanO/nunit,agray/nunit,NikolayPianikov/nunit,appel1/nunit,ArsenShnurkov/nunit,ArsenShnurkov/nunit,pcalin/nunit,Green-Bug/nunit,nunit/nunit,jadarnel27/nunit,NarohLoyahl/nunit,appel1/nunit,Green-Bug/nunit,nivanov1984/nunit,JustinRChou/nunit,NikolayPianikov/nunit,akoeplinger/nunit,pcalin/nunit,NarohLoyahl/nunit,modulexcite/nunit,zmaruo/nunit,ChrisMaddock/nunit,JohanO/nunit,acco32/nunit,ChrisMaddock/nunit,modulexcite/nunit,akoeplinger/nunit,passaro/nunit,Therzok/nunit,acco32/nunit,dicko2/nunit,Therzok/nunit,danielmarbach/nunit,passaro/nunit,mjedrzejek/nunit,michal-franc/nunit,OmicronPersei/nunit,NarohLoyahl/nunit,ggeurts/nunit,jeremymeng/nunit,zmaruo/nunit,danielmarbach/nunit,mjedrzejek/nunit,OmicronPersei/nunit,jhamm/nunit,jeremymeng/nunit,jeremymeng/nunit,Suremaker/nunit,elbaloo/nunit,jnm2/nunit,JohanO/nunit
src/framework/NUnit/Framework/Api/DefaultTestAssemblyRunner.cs
src/framework/NUnit/Framework/Api/DefaultTestAssemblyRunner.cs
using System; using System.Collections; using System.Threading; namespace NUnit.Framework.Api { /// <summary> /// Default implementation of ITestAssemblyRunner /// </summary> public class DefaultTestAssemblyRunner : ITestAssemblyRunner { private ITestAssemblyBuilder builder; private NUnit.Core.TestSuite suite; private int runnerID; private Thread runThread; #region Constructors public DefaultTestAssemblyRunner(ITestAssemblyBuilder builder) : this(builder, 0) { } public DefaultTestAssemblyRunner(ITestAssemblyBuilder builder, int runnerID) { this.builder = builder; this.runnerID = runnerID; } #endregion #region Methods /// <summary> /// Loads the tests found in an Assembly /// </summary> /// <param name="assemblyName">File name of the assembly to load</param> /// <returns>True if the load was successful</returns> public bool Load(string assemblyName) { this.suite = this.builder.Build(assemblyName, null); if (suite == null) return false; suite.SetRunnerID(this.runnerID, true); return true; } /// <summary> /// Count Test Cases using a filter /// </summary> /// <param name="filter">The filter to apply</param> /// <returns>The number of test cases found</returns> public int CountTestCases(NUnit.Core.TestFilter filter) { return this.suite.CountTestCases(filter); } /// <summary> /// Run selected tests and return a test result. The test is run synchronously, /// and the listener interface is notified as it progresses. /// </summary> /// <param name="listener">Interface to receive EventListener notifications.</param> /// <param name="filter">The filter to apply when running the tests</param> /// <returns></returns> public NUnit.Core.TestResult Run(NUnit.Core.ITestListener listener, NUnit.Core.TestFilter filter) { try { this.runThread = Thread.CurrentThread; return this.suite.Run(listener, filter); } finally { this.runThread = null; } } #endregion } }
using System; using System.Collections; using System.Threading; namespace NUnit.Framework.Api { public class DefaultTestAssemblyRunner : ITestAssemblyRunner { private ITestAssemblyBuilder builder; private NUnit.Core.TestSuite suite; private int runnerID; private Thread runThread; #region Constructors public DefaultTestAssemblyRunner(ITestAssemblyBuilder builder) : this(builder, 0) { } public DefaultTestAssemblyRunner(ITestAssemblyBuilder builder, int runnerID) { this.builder = builder; this.runnerID = runnerID; } #endregion #region Methods /// <summary> /// Loads the tests found in an Assembly /// </summary> /// <param name="assemblyName">File name of the assembly to load</param> /// <returns>True if the load was successful</returns> public bool Load(string assemblyName) { this.suite = this.builder.Build(assemblyName, null); if (suite == null) return false; suite.SetRunnerID(this.runnerID, true); return true; } /// <summary> /// Count Test Cases using a filter /// </summary> /// <param name="filter">The filter to apply</param> /// <returns>The number of test cases found</returns> public int CountTestCases(NUnit.Core.TestFilter filter) { return this.suite.CountTestCases(filter); } /// <summary> /// Run selected tests and return a test result. The test is run synchronously, /// and the listener interface is notified as it progresses. /// </summary> /// <param name="listener">Interface to receive EventListener notifications.</param> /// <param name="filter">The filter to apply when running the tests</param> /// <returns></returns> public NUnit.Core.TestResult Run(NUnit.Core.ITestListener listener, NUnit.Core.TestFilter filter) { try { this.runThread = Thread.CurrentThread; return this.suite.Run(listener, filter); } finally { this.runThread = null; } } #endregion } }
mit
C#
3859e4a5833e2c9a61e80a08b0669a4523648356
make wait duration configurable
fschwiet/SizSelCsZzz,fschwiet/SizSelCsZzz
SizSelCsZzz/BrowserExtensions.cs
SizSelCsZzz/BrowserExtensions.cs
using System; using System.Linq; using System.Text.RegularExpressions; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace SizSelCsZzz { public static class BrowserExtensions { public static int MaxWaitMS = 5000; public static IWebElement WaitForElement(this IWebDriver browser, By condition, int? maxWaitMS) { maxWaitMS = maxWaitMS ?? MaxWaitMS; return new WebDriverWait(browser, TimeSpan.FromMilliseconds(MaxWaitMS)).Until(driver => driver.FindElement(condition)); } public static string GetBodyText(this IWebDriver browser) { if (browser.FindElements(By.TagName("body")).Count() == 0) { return ""; } return browser.FindElement(By.TagName("body")).Text; } public static bool ContainsText(this IWebDriver browser, string text) { return browser.GetBodyText().Contains(text); } public static int CountElementsMatching(this IWebDriver browser, string cssSelector) { int sum = 0; foreach(var selector in cssSelector.Split(',')) { sum += browser.FindElements(By.CssSelector(selector)).Count(); } return sum; } } }
using System; using System.Linq; using System.Text.RegularExpressions; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace SizSelCsZzz { public static class BrowserExtensions { public static IWebElement WaitForElement(this IWebDriver browser, By condition) { return new WebDriverWait(browser, TimeSpan.FromMilliseconds(5000)).Until(driver => driver.FindElement(condition)); } public static string GetBodyText(this IWebDriver browser) { if (browser.FindElements(By.TagName("body")).Count() == 0) { return ""; } return browser.FindElement(By.TagName("body")).Text; } public static bool ContainsText(this IWebDriver browser, string text) { return browser.GetBodyText().Contains(text); } public static int CountElementsMatching(this IWebDriver browser, string cssSelector) { int sum = 0; foreach(var selector in cssSelector.Split(',')) { sum += browser.FindElements(By.CssSelector(selector)).Count(); } return sum; } } }
mit
C#
f31ba1bc677db0eb4a7b61c5d1cf011b5cc661c3
Add null check to Customer.getTokenCustomerID Fixes #8
eWAYPayment/eway-rapid-net
eWAY.Rapid/Internals/Models/Customer.cs
eWAY.Rapid/Internals/Models/Customer.cs
namespace eWAY.Rapid.Internals.Models { internal class Customer { public long? TokenCustomerID { get;set; } public string Reference { get;set; } public string Title { get;set; } public string FirstName { get;set; } public string LastName { get;set; } public string CompanyName { get;set; } public string JobDescription { get;set; } public string Street1 { get;set; } public string Street2 { get;set; } public string City { get;set; } public string State { get;set; } public string PostalCode { get;set; } public string Country { get;set; } public string Email { get;set; } public string Phone { get;set; } public string Mobile { get;set; } public string Comments { get;set; } public string Fax { get;set; } public string Url { get; set; } public string getTokenCustomerID() { return (TokenCustomerID == null) ? null : TokenCustomerID.ToString(); } } }
namespace eWAY.Rapid.Internals.Models { internal class Customer { public long? TokenCustomerID { get;set; } public string Reference { get;set; } public string Title { get;set; } public string FirstName { get;set; } public string LastName { get;set; } public string CompanyName { get;set; } public string JobDescription { get;set; } public string Street1 { get;set; } public string Street2 { get;set; } public string City { get;set; } public string State { get;set; } public string PostalCode { get;set; } public string Country { get;set; } public string Email { get;set; } public string Phone { get;set; } public string Mobile { get;set; } public string Comments { get;set; } public string Fax { get;set; } public string Url { get; set; } public string getTokenCustomerID() { return TokenCustomerID.ToString(); } } }
mit
C#
1842f2c756b035f4661d5c5331ac0ebe325ccebc
Add wrapper for environment variables.
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Core/EnvironmentInfo.Others.cs
source/Nuke.Core/EnvironmentInfo.Others.cs
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections; using System.Collections.Generic; using System.Linq; #if NETCORE using System.IO; #endif namespace Nuke.Core { public static partial class EnvironmentInfo { public static string NewLine => Environment.NewLine; public static string MachineName => Environment.MachineName; public static string WorkingDirectory #if NETCORE => Directory.GetCurrentDirectory(); #else => Environment.CurrentDirectory; #endif public static IReadOnlyDictionary<string, string> Variables { get { var environmentVariables = Environment.GetEnvironmentVariables(); return Environment.GetEnvironmentVariables().Keys.Cast<string>() .ToDictionary(x => x, x => (string) environmentVariables[x], StringComparer.OrdinalIgnoreCase); } } } }
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; #if NETCORE using System.IO; #endif namespace Nuke.Core { public static partial class EnvironmentInfo { public static string NewLine => Environment.NewLine; public static string MachineName => Environment.MachineName; public static string WorkingDirectory #if NETCORE => Directory.GetCurrentDirectory(); #else => Environment.CurrentDirectory; #endif } }
mit
C#
e0edccc111238b5326453080bffb006785158852
Set custom notes properly
DMagic1/KSP_Contract_Window
Source/ContractsWindow/PanelInterfaces/parameterUIObject.cs
Source/ContractsWindow/PanelInterfaces/parameterUIObject.cs
using System; using System.Collections.Generic; using UnityEngine; using ContractParser; using ContractsWindow.Unity.Interfaces; using ContractsWindow.Unity.Unity; using ContractsWindow.Unity; namespace ContractsWindow.PanelInterfaces { public class parameterUIObject : IParameterSection { private parameterContainer container; private List<parameterUIObject> subParams = new List<parameterUIObject>(); internal parameterUIObject(parameterContainer p) { container = p; for (int i = 0; i < p.ParameterCount; i++) { parameterContainer c = p.ParamList[i]; if (c == null) continue; subParams.Add(new parameterUIObject(c)); } } public ContractState ParameterState { get { if (container == null || container.CParam == null) return ContractState.Fail; switch(container.CParam.State) { case Contracts.ParameterState.Complete: return ContractState.Complete; case Contracts.ParameterState.Failed: return ContractState.Fail; case Contracts.ParameterState.Incomplete: return ContractState.Active; default: return ContractState.Fail; } } } public int ParamLayer { get { if (container == null) return 0; return container.Level; } } public string TitleText { get { if (container == null) return ""; return container.Title; } } public string RewardText { get { if (container == null) return ""; return string.Format("<color=#69D84FFF>£ {0}</color> <color=#02D8E9FF>© {1}</color> <color=#C9B003FF>¡ {2}</color>", container.FundsRewString, container.SciRewString, container.RepRewString); } } public string PenaltyText { get { if (container == null) return ""; return string.Format("<color=#FA4224FF>£ {0}</color> <color=#FA4224FF>¡ {1}</color>", container.FundsPenString, container.RepPenString); } } public string GetNote { get { if (container == null) return ""; return container.Notes(HighLogic.LoadedScene == GameScenes.SPACECENTER || HighLogic.LoadedSceneIsEditor); } } public IList<IParameterSection> GetSubParams { get { return new List<IParameterSection>(subParams.ToArray()); } } } }
using System; using System.Collections.Generic; using UnityEngine; using ContractParser; using ContractsWindow.Unity.Interfaces; using ContractsWindow.Unity.Unity; using ContractsWindow.Unity; namespace ContractsWindow.PanelInterfaces { public class parameterUIObject : IParameterSection { private parameterContainer container; private List<parameterUIObject> subParams = new List<parameterUIObject>(); internal parameterUIObject(parameterContainer p) { container = p; for (int i = 0; i < p.ParameterCount; i++) { parameterContainer c = p.ParamList[i]; if (c == null) continue; subParams.Add(new parameterUIObject(c)); } } public ContractState ParameterState { get { if (container == null || container.CParam == null) return ContractState.Fail; switch(container.CParam.State) { case Contracts.ParameterState.Complete: return ContractState.Complete; case Contracts.ParameterState.Failed: return ContractState.Fail; case Contracts.ParameterState.Incomplete: return ContractState.Active; default: return ContractState.Fail; } } } public int ParamLayer { get { if (container == null) return 0; return container.Level; } } public string TitleText { get { if (container == null) return ""; return container.Title; } } public string RewardText { get { if (container == null) return ""; return string.Format("<color=#69D84FFF>£ {0}</color> <color=#02D8E9FF>© {1}</color> <color=#C9B003FF>¡ {2}</color>", container.FundsRewString, container.SciRewString, container.RepRewString); } } public string PenaltyText { get { if (container == null) return ""; return string.Format("<color=#FA4224FF>£ {0}</color> <color=#FA4224FF>¡ {1}</color>", container.FundsPenString, container.RepPenString); } } public string GetNote { get { if (container == null) return ""; return container.Notes(HighLogic.LoadedScene == GameScenes.SPACECENTER); } } public IList<IParameterSection> GetSubParams { get { return new List<IParameterSection>(subParams.ToArray()); } } } }
mit
C#
3a88bf20303235b1f88af58acb98df82fbea5671
remove trace
pleroy/Principia,Norgg/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,Norgg/Principia,pleroy/Principia,pleroy/Principia,mockingbirdnest/Principia,Norgg/Principia,eggrobin/Principia,eggrobin/Principia,pleroy/Principia,eggrobin/Principia,Norgg/Principia
ksp_plugin_adapter/optional_marshaler.cs
ksp_plugin_adapter/optional_marshaler.cs
using System; using System.Globalization; using System.Runtime.InteropServices; namespace principia { namespace ksp_plugin_adapter { public class OptionalMarshaler<T> : ICustomMarshaler where T : struct { // In addition to implementing the |ICustomMarshaler| interface, custom // marshalers must implement a static method called |GetInstance| that accepts // a |String| as a parameter and has a return type of |ICustomMarshaler|, // see https://goo.gl/wwmBTa. public static ICustomMarshaler GetInstance(String s) { return instance_; } public void CleanUpManagedData(object ManagedObj) {} public void CleanUpNativeData(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) { return; } Marshal.FreeHGlobal(pNativeData); } public int GetNativeDataSize() { // I think this is supposed to return -1, and I also think it doesn't // matter, but honestly I'm not sure... return -1; } public IntPtr MarshalManagedToNative(object ManagedObj) { // While we expect that the marshaling attribute will be used on a |T?|, // we get it boxed, and boxing has special behaviour on |Nullable|; // specifically, |T?| is boxed to either |T| or |null|, depending on whether // it has a value. In the latter case, we lose the type information, so we // cannot test whether |object is T?|. Instead we check whether // |object == null|, if it it's not, we check that it's a |T|. if (ManagedObj == null) { return IntPtr.Zero; } var value_if_correct_type = ManagedObj as T?; if (value_if_correct_type == null) { throw Log.Fatal( String.Format( CultureInfo.InvariantCulture, "|{0}| must be used on a |{1}| or a (possibly boxed) |{2}|.", GetType().Name, typeof(T?).Name, typeof(T).Name)); } T value = value_if_correct_type.Value; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(value)); Marshal.StructureToPtr(value, ptr, fDeleteOld: false); return ptr; } public object MarshalNativeToManaged(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) { return null; } else { return Marshal.PtrToStructure(pNativeData, typeof(T)); } } private readonly static OptionalMarshaler<T> instance_ = new OptionalMarshaler<T>(); } } // namespace ksp_plugin_adapter } // namespace principia
using System; using System.Globalization; using System.Runtime.InteropServices; namespace principia { namespace ksp_plugin_adapter { public class OptionalMarshaler<T> : ICustomMarshaler where T : struct { // In addition to implementing the |ICustomMarshaler| interface, custom // marshalers must implement a static method called |GetInstance| that accepts // a |String| as a parameter and has a return type of |ICustomMarshaler|, // see https://goo.gl/wwmBTa. public static ICustomMarshaler GetInstance(String s) { return instance_; } public void CleanUpManagedData(object ManagedObj) {} public void CleanUpNativeData(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) { return; } Marshal.FreeHGlobal(pNativeData); } public int GetNativeDataSize() { // I think this is supposed to return -1, and I also think it doesn't // matter, but honestly I'm not sure... return -1; } public IntPtr MarshalManagedToNative(object ManagedObj) { // While we expect that the marshaling attribute will be used on a |T?|, // we get it boxed, and boxing has special behaviour on |Nullable|; // specifically, |T?| is boxed to either |T| or |null|, depending on whether // it has a value. In the latter case, we lose the type information, so we // cannot test whether |object is T?|. Instead we check whether // |object == null|, if it it's not, we check that it's a |T|. if (ManagedObj == null) { return IntPtr.Zero; } var value_if_correct_type = ManagedObj as T?; if (value_if_correct_type == null) { throw Log.Fatal( String.Format( CultureInfo.InvariantCulture, "|{0}| must be used on a |{1}| or a (possibly boxed) |{2}|.", GetType().Name, typeof(T?).Name, typeof(T).Name)); } T value = value_if_correct_type.Value; Log.Error(value.ToString()); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(value)); Marshal.StructureToPtr(value, ptr, fDeleteOld: false); return ptr; } public object MarshalNativeToManaged(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) { return null; } else { return Marshal.PtrToStructure(pNativeData, typeof(T)); } } private readonly static OptionalMarshaler<T> instance_ = new OptionalMarshaler<T>(); } } // namespace ksp_plugin_adapter } // namespace principia
mit
C#
af8bfb7c475de12db3d43cb46fce71595954ce5a
update my blog post filter (code has some none PowerShell entries), and my lat/log)
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/KieranJacobsen.cs
src/Firehose.Web/Authors/KieranJacobsen.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class KieranJacobsen : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Kieran"; public string LastName => "Jacobsen"; public string ShortBioOrTagLine => "Readifarian, works with PowerShell"; public string StateOrRegion => "Melbourne, Australia"; public string EmailAddress => "code@poshsecurity.com"; public string TwitterHandle => "kjacobsen"; public string GravatarHash => ""; public Uri WebSite => new Uri("https://poshsecurity.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://poshsecurity.com/blog/?format=rss"); } } public string GitHubHandle => "kjacobsen"; public bool Filter(SyndicationItem item) { return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } public GeoPosition Position => new GeoPosition(-37.816667, 144.966667); } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class KieranJacobsen : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Kieran"; public string LastName => "Jacobsen"; public string ShortBioOrTagLine => "Readifarian, works with PowerShell"; public string StateOrRegion => "Melbourne, Australia"; public string EmailAddress => "code@poshsecurity.com"; public string TwitterHandle => "kjacobsen"; public string GravatarHash => ""; public Uri WebSite => new Uri("https://poshsecurity.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://poshsecurity.com/blog/?format=rss"); } } public string GitHubHandle => "kjacobsen"; public bool Filter(SyndicationItem item) { return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("code")); } public GeoPosition Position => new GeoPosition(43.8938256, 18.3129519); } }
mit
C#
f0c8702f7ed6685f0fa8311f86eb68427b74ce13
Remove use of LazyRef
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Identity/EntityFrameworkCore/test/EF.Test/Utilities/ScratchDatabaseFixture.cs
src/Identity/EntityFrameworkCore/test/EF.Test/Utilities/ScratchDatabaseFixture.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 Microsoft.AspNetCore.Identity.EntityFrameworkCore.Test.Utilities; using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.AspNetCore.Identity.EntityFrameworkCore.Test { public class ScratchDatabaseFixture : IDisposable { private readonly Lazy<SqlServerTestStore> _testStore; public ScratchDatabaseFixture() { _testStore = new Lazy<SqlServerTestStore>(() => SqlServerTestStore.CreateScratch()); } public string ConnectionString => _testStore.Value.Connection.ConnectionString; public void Dispose() { if (_testStore.HasValue) { _testStore.Value.Dispose(); } } } }
// 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 Microsoft.AspNetCore.Identity.EntityFrameworkCore.Test.Utilities; using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.AspNetCore.Identity.EntityFrameworkCore.Test { public class ScratchDatabaseFixture : IDisposable { #pragma warning disable EF1001 // Internal EF Core API usage. private readonly LazyRef<SqlServerTestStore> _testStore; public ScratchDatabaseFixture() { _testStore = new LazyRef<SqlServerTestStore>(() => SqlServerTestStore.CreateScratch()); } public string ConnectionString => _testStore.Value.Connection.ConnectionString; public void Dispose() { if (_testStore.HasValue) { _testStore.Value?.Dispose(); } } #pragma warning restore EF1001 // Internal EF Core API usage. } }
apache-2.0
C#
7f4269b995e44acd73adbda44ce239cf2d3c2344
Simplify expressino
KirillOsenkov/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,tmat/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,weltkante/roslyn,tmat/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,dotnet/roslyn,davkean/roslyn,aelij/roslyn,weltkante/roslyn,stephentoub/roslyn,genlu/roslyn,diryboy/roslyn,reaction1989/roslyn,brettfo/roslyn,wvdd007/roslyn,sharwell/roslyn,bartdesmet/roslyn,heejaechang/roslyn,gafter/roslyn,stephentoub/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,genlu/roslyn,eriawan/roslyn,tannergooding/roslyn,brettfo/roslyn,wvdd007/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,dotnet/roslyn,physhi/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,tmat/roslyn,AmadeusW/roslyn,physhi/roslyn,eriawan/roslyn,sharwell/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,brettfo/roslyn,reaction1989/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,jmarolf/roslyn,mgoertz-msft/roslyn,davkean/roslyn,aelij/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,wvdd007/roslyn,diryboy/roslyn,weltkante/roslyn,davkean/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,gafter/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,mavasani/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,sharwell/roslyn,gafter/roslyn,eriawan/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,physhi/roslyn,genlu/roslyn
src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationPropertyInfo.cs
src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationPropertyInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationPropertyInfo { private static readonly ConditionalWeakTable<IPropertySymbol, CodeGenerationPropertyInfo> s_propertyToInfoMap = new ConditionalWeakTable<IPropertySymbol, CodeGenerationPropertyInfo>(); private readonly bool _isNew; private readonly bool _isUnsafe; private readonly SyntaxNode _initializer; private CodeGenerationPropertyInfo( bool isNew, bool isUnsafe, SyntaxNode initializer) { _isNew = isNew; _isUnsafe = isUnsafe; _initializer = initializer; } public static void Attach( IPropertySymbol property, bool isNew, bool isUnsafe, SyntaxNode initializer) { var info = new CodeGenerationPropertyInfo(isNew, isUnsafe, initializer); s_propertyToInfoMap.Add(property, info); } private static CodeGenerationPropertyInfo GetInfo(IPropertySymbol property) { s_propertyToInfoMap.TryGetValue(property, out var info); return info; } public static SyntaxNode GetInitializer(CodeGenerationPropertyInfo info) => info?._initializer; public static SyntaxNode GetInitializer(IPropertySymbol property) { return GetInitializer(GetInfo(property)); } public static bool GetIsNew(IPropertySymbol property) { return GetIsNew(GetInfo(property)); } public static bool GetIsUnsafe(IPropertySymbol property) { return GetIsUnsafe(GetInfo(property)); } private static bool GetIsNew(CodeGenerationPropertyInfo info) { return info != null && info._isNew; } private static bool GetIsUnsafe(CodeGenerationPropertyInfo info) { return info != null && info._isUnsafe; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationPropertyInfo { private static readonly ConditionalWeakTable<IPropertySymbol, CodeGenerationPropertyInfo> s_propertyToInfoMap = new ConditionalWeakTable<IPropertySymbol, CodeGenerationPropertyInfo>(); private readonly bool _isNew; private readonly bool _isUnsafe; private readonly SyntaxNode _initializer; private CodeGenerationPropertyInfo( bool isNew, bool isUnsafe, SyntaxNode initializer) { _isNew = isNew; _isUnsafe = isUnsafe; _initializer = initializer; } public static void Attach( IPropertySymbol property, bool isNew, bool isUnsafe, SyntaxNode initializer) { var info = new CodeGenerationPropertyInfo(isNew, isUnsafe, initializer); s_propertyToInfoMap.Add(property, info); } private static CodeGenerationPropertyInfo GetInfo(IPropertySymbol property) { s_propertyToInfoMap.TryGetValue(property, out var info); return info; } public static SyntaxNode GetInitializer(CodeGenerationPropertyInfo info) { return info == null ? null : info._initializer; } public static SyntaxNode GetInitializer(IPropertySymbol property) { return GetInitializer(GetInfo(property)); } public static bool GetIsNew(IPropertySymbol property) { return GetIsNew(GetInfo(property)); } public static bool GetIsUnsafe(IPropertySymbol property) { return GetIsUnsafe(GetInfo(property)); } private static bool GetIsNew(CodeGenerationPropertyInfo info) { return info != null && info._isNew; } private static bool GetIsUnsafe(CodeGenerationPropertyInfo info) { return info != null && info._isUnsafe; } } }
mit
C#
4be5ef181efe515edc2b2a78e9712d8794534c87
Add missing property "self"
Aux/NTwitch,Aux/NTwitch
src/NTwitch.Core/API/Common/TwitchLinks.cs
src/NTwitch.Core/API/Common/TwitchLinks.cs
using Newtonsoft.Json; namespace NTwitch { public class TwitchLinks { public string Channel { get; } public string Users { get; } public string User { get; } public string Channels { get; } public string Chat { get; } public string Streams { get; } public string Ingests { get; } public string Teams { get; } public string Search { get; } [JsonProperty("self")] public string Self { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NTwitch { public class TwitchLinks { public string Channel { get; } public string Users { get; } public string User { get; } public string Channels { get; } public string Chat { get; } public string Streams { get; } public string Ingests { get; } public string Teams { get; } public string Search { get; } } }
mit
C#
ee3162ad71b9609e47a28e4dc1da3c511c01c7be
Fix return
adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress
src/SharpCompress/IO/NonDisposingStream.cs
src/SharpCompress/IO/NonDisposingStream.cs
using System; using System.IO; namespace SharpCompress.IO { public class NonDisposingStream : Stream { public NonDisposingStream(Stream stream, bool throwOnDispose = false) { Stream = stream; ThrowOnDispose = throwOnDispose; } public bool ThrowOnDispose { get; set; } protected override void Dispose(bool disposing) { if (ThrowOnDispose) { throw new InvalidOperationException($"Attempt to dispose of a {nameof(NonDisposingStream)} when {nameof(ThrowOnDispose)} is {ThrowOnDispose}"); } } protected Stream Stream { get; } public override bool CanRead => Stream.CanRead; public override bool CanSeek => Stream.CanSeek; public override bool CanWrite => Stream.CanWrite; public override void Flush() { Stream.Flush(); } public override long Length => Stream.Length; public override long Position { get => Stream.Position; set => Stream.Position = value; } public override int Read(byte[] buffer, int offset, int count) { return Stream.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return Stream.Seek(offset, origin); } public override void SetLength(long value) { Stream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { Stream.Write(buffer, offset, count); } #if NETSTANDARD2_1 public override int Read(Span<byte> buffer) { return Stream.Read(buffer); } public override void Write(ReadOnlySpan<byte> buffer) { Stream.Write(buffer); } #endif } }
using System; using System.IO; namespace SharpCompress.IO { public class NonDisposingStream : Stream { public NonDisposingStream(Stream stream, bool throwOnDispose = false) { Stream = stream; ThrowOnDispose = throwOnDispose; } public bool ThrowOnDispose { get; set; } protected override void Dispose(bool disposing) { if (ThrowOnDispose) { throw new InvalidOperationException($"Attempt to dispose of a {nameof(NonDisposingStream)} when {nameof(ThrowOnDispose)} is {ThrowOnDispose}"); } } protected Stream Stream { get; } public override bool CanRead => Stream.CanRead; public override bool CanSeek => Stream.CanSeek; public override bool CanWrite => Stream.CanWrite; public override void Flush() { Stream.Flush(); } public override long Length => Stream.Length; public override long Position { get => Stream.Position; set => Stream.Position = value; } public override int Read(byte[] buffer, int offset, int count) { return Stream.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return Stream.Seek(offset, origin); } public override void SetLength(long value) { Stream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { Stream.Write(buffer, offset, count); } #if NETSTANDARD2_1 public override int Read(Span<byte> buffer) { Stream.Read(buffer); } public override void Write(ReadOnlySpan<byte> buffer) { Stream.Write(buffer); } #endif } }
mit
C#
534047da60f0accc203447118608bef757f4bf8d
Update sideCamera.cs
lukaspj/sspt,lukaspj/sspt,lukaspj/sspt
modules/cameras/sideCamera.cs
modules/cameras/sideCamera.cs
new ScriptObject(SideCamera); function SideCamera::init(%this, %client, %group) { // Create a camera for the client. %c = new Camera() { datablock = Observer; }; // Add to SimGroup if one is given. if(isObject(%group)) { %group.add(%c); } // Cameras are not ghosted (sent across the network) by default; we need to // do it manually for the client that owns the camera or things will go south // quickly. %c.scopeToClient(%client); // Set the camera of the client to be this camera in such a manner that it // doesn't remove control from the player. %client.setCameraObject(%c); // If there's no input, capture some! if(!isObject(%this.map)) { %this.map = new ActionMap(); %this.map.bind( keyboard, w, moveforward ); %this.map.bind( keyboard, s, movebackward ); //%this.map.bind(mouse, xaxis, yaw); //%this.map.bind(mouse, yaxis, pitch); } %this.camera = %c; return %c; } function SideCamera::controls(%this, %controls) { %this.map.call(%controls? "push" : "pop"); } function SideCamera::mountToPlayer(%this, %player) { return %this.camera.setOrbitObject(%player, "0 0"SPC mDegToRad(270), 1, 8, 5, true); }
new ScriptObject(SideCamera); function SideCamera::init(%this, %client, %group) { // Create a camera for the client. %c = new Camera() { datablock = Observer; }; // Add to SimGroup if one is given. if(isObject(%group)) { %group.add(%c); } // Cameras are not ghosted (sent across the network) by default; we need to // do it manually for the client that owns the camera or things will go south // quickly. %c.scopeToClient(%client); // And let the client control the camera. %client.setCameraObject(%c); // If there's no input, capture some! if(!isObject(%this.map)) { %this.map = new ActionMap(); %this.map.bind( keyboard, w, moveforward ); %this.map.bind( keyboard, s, movebackward ); //%this.map.bind(mouse, xaxis, yaw); //%this.map.bind(mouse, yaxis, pitch); } %this.camera = %c; return %c; } function SideCamera::controls(%this, %controls) { %this.map.call(%controls? "push" : "pop"); } function SideCamera::mountToPlayer(%this, %player) { return %this.camera.setOrbitObject(%player, "0 0"SPC mDegToRad(270), 1, 8, 5, true); }
mit
C#
eab3a788a121b2c593de555461bd5123626776a6
fix acceptance test for BauTask rename
aarondandy/bau,bau-build/bau,bau-build/bau,huoxudong125/bau,aarondandy/bau,huoxudong125/bau,modulexcite/bau,adamralph/bau,bau-build/bau,huoxudong125/bau,eatdrinksleepcode/bau,modulexcite/bau,eatdrinksleepcode/bau,adamralph/bau,modulexcite/bau,eatdrinksleepcode/bau,adamralph/bau,aarondandy/bau,aarondandy/bau,huoxudong125/bau,adamralph/bau,bau-build/bau,eatdrinksleepcode/bau,modulexcite/bau
src/test/Bau.Test.Acceptance/InlineTasks.cs
src/test/Bau.Test.Acceptance/InlineTasks.cs
// <copyright file="InlineTasks.cs" company="Bau contributors"> // Copyright (c) Bau contributors. (baubuildch@gmail.com) // </copyright> namespace Bau.Test.Acceptance { using System; using System.Globalization; using System.IO; using System.Reflection; using Bau.Test.Acceptance.Support; using FluentAssertions; using Xbehave; public static class InlineTasks { [Scenario] public static void ExecutingAnInlineTask(Baufile baufile, string tempFile, string output) { var scenario = MethodBase.GetCurrentMethod().GetFullName(); "Given a baufile with a default task with an inline task" .f(() => { tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture)); baufile = Baufile.Create(scenario).WriteLine( @"Require<Bau>() .Do(() => { var task = new BauTask(); task.Actions.Add(() => File.Create(@""" + tempFile + @""").Dispose()); task.Execute(); }) .Run();"); }) .Teardown(() => File.Delete(tempFile)); "When I execute the baufile" .f(() => output = baufile.Run()); "Then the task is executed" .f(() => File.Exists(tempFile).Should().BeTrue()); "And I should not be informed that a task with no name was executed" .f(() => output.Should().NotContainEquivalentOf("starting ''")); } } }
// <copyright file="InlineTasks.cs" company="Bau contributors"> // Copyright (c) Bau contributors. (baubuildch@gmail.com) // </copyright> namespace Bau.Test.Acceptance { using System; using System.Globalization; using System.IO; using System.Reflection; using Bau.Test.Acceptance.Support; using FluentAssertions; using Xbehave; public static class InlineTasks { [Scenario] public static void ExecutingAnInlineTask(Baufile baufile, string tempFile, string output) { var scenario = MethodBase.GetCurrentMethod().GetFullName(); "Given a baufile with a default task with an inline task" .f(() => { tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture)); baufile = Baufile.Create(scenario).WriteLine( @"Require<Bau>() .Do(() => { var task = new BauCore.Task(); task.Actions.Add(() => File.Create(@""" + tempFile + @""").Dispose()); task.Execute(); }) .Run();"); }) .Teardown(() => File.Delete(tempFile)); "When I execute the baufile" .f(() => output = baufile.Run()); "Then the task is executed" .f(() => File.Exists(tempFile).Should().BeTrue()); "And I should not be informed that a task with no name was executed" .f(() => output.Should().NotContainEquivalentOf("starting ''")); } } }
mit
C#
d10f6e043aa05d0cbf8b11c268cee38d47f24e41
Replace npmcdn.com with unpkg.com
Isdas/buldringno,Isdas/buldringno,Isdas/buldringno,Isdas/buldringno
src/buldringno/Views/Shared/_Layout.cshtml
src/buldringno/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>@ViewBag.Title</title> @*<base href="/">*@ <link href="~/lib/css/bootstrap.css" rel="stylesheet" /> <link href="~/lib/css/font-awesome.css" rel="stylesheet" /> @RenderSection("styles", required: false) @*Solve IE 11 issues *@ @*<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script> <script src="https://unpkg.com/angular2/es6/dev/src/testing/shims_for_IE.js"></script>*@ <!-- 1. Load libraries --> <!-- Polyfill(s) for older browsers --> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <!-- 2. Configure SystemJS --> <script src="~/lib/js/systemjs.config.js"></script> <script src="~/lib/js/jquery.js"></script> <script src="~/lib/js/bootstrap.js"></script> </head> <body> <div> @RenderBody() </div> @RenderSection("scripts", required: false) <script type="text/javascript"> @RenderSection("customScript", required: false) </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>@ViewBag.Title</title> @*<base href="/">*@ <link href="~/lib/css/bootstrap.css" rel="stylesheet" /> <link href="~/lib/css/font-awesome.css" rel="stylesheet" /> @RenderSection("styles", required: false) @*Solve IE 11 issues *@ @*<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script> <script src="https://npmcdn.com/angular2/es6/dev/src/testing/shims_for_IE.js"></script>*@ <!-- 1. Load libraries --> <!-- Polyfill(s) for older browsers --> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <!-- 2. Configure SystemJS --> <script src="~/lib/js/systemjs.config.js"></script> <script src="~/lib/js/jquery.js"></script> <script src="~/lib/js/bootstrap.js"></script> </head> <body> <div> @RenderBody() </div> @RenderSection("scripts", required: false) <script type="text/javascript"> @RenderSection("customScript", required: false) </script> </body> </html>
mit
C#
e78382d649176de977e966444847e3f71ffcb2e1
Add ConsoleWhriteLine on Area and Perimeter Methods
ivayloivanof/OOP.CSharp,ivayloivanof/OOP.CSharp
04.EncapsulationAndPolymorphism/EncapsulationAndPolimophism/Shapes/Program.cs
04.EncapsulationAndPolymorphism/EncapsulationAndPolimophism/Shapes/Program.cs
using System; using Shapes.Class; namespace Shapes { using Interfaces; class Program { static void Main() { IShape circle = new Circle(4); Console.WriteLine("circle area: " + circle.CalculateArea()); Console.WriteLine("circle perimeter: " + circle.CalculatePerimeter()); IShape triangle = new Triangle(5, 8.4, 6.4, 8.5); Console.WriteLine("triangle area: " + triangle.CalculateArea()); Console.WriteLine("triangle perimeter: " + triangle.CalculatePerimeter()); IShape rectangle = new Rectangle(8, 5); Console.WriteLine("rectangle area: " + rectangle.CalculateArea()); Console.WriteLine("rectangle perimeter: " + rectangle.CalculatePerimeter()); Console.WriteLine(); } } }
using System; using Shapes.Class; namespace Shapes { using Interfaces; class Program { static void Main() { IShape circle = new Circle(4); Console.WriteLine(circle.CalculateArea()); circle.CalculatePerimeter(); IShape triangle = new Triangle(5, 8.4, 6.4, 8.5); triangle.CalculateArea(); triangle.CalculatePerimeter(); IShape rectangle = new Rectangle(8, 5); rectangle.CalculateArea(); rectangle.CalculatePerimeter(); Console.WriteLine(); } } }
cc0-1.0
C#
c2b8b79a6ee7892a768e93e60042682169f3a466
Fix ObjectRepresentation.IsType
daveh551/Highway.Data,daveh551/Highway.Data,daveh551/Highway.Data,daveh551/Highway.Data
Highway/src/Highway.Data/Contexts/TypeRepresentations/ObjectRepresentation.cs
Highway/src/Highway.Data/Contexts/TypeRepresentations/ObjectRepresentation.cs
 using System; using System.Collections.Generic; using System.Linq; namespace Highway.Data.Contexts.TypeRepresentations { internal class ObjectRepresentation { public ObjectRepresentation() { Parents = new Dictionary<object, Accessor>(); } internal object Entity { get; set; } internal IEnumerable<ObjectRepresentation> RelatedEntities { get; set; } internal Dictionary<object, Accessor> Parents { get; set; } public bool IsType<T1>() { return Entity is T1; } internal IEnumerable<ObjectRepresentation> AllRelated() { List<ObjectRepresentation> evaluatedObjects = new List<ObjectRepresentation>(); return AllRelated(evaluatedObjects); } internal IEnumerable<ObjectRepresentation> AllRelated(List<ObjectRepresentation> evaluatedObjects) { var items = RelatedEntities.ToList(); foreach (var objectRepresentationBase in RelatedEntities) { if (evaluatedObjects.Contains(objectRepresentationBase)) { continue; } evaluatedObjects.Add(objectRepresentationBase); items.AddRange(objectRepresentationBase.AllRelated(evaluatedObjects)); } return items; } public List<ObjectRepresentation> GetObjectRepresentationsToPrune() { return AllRelated().Where(x => x.Orphaned()).ToList(); } public bool Orphaned() { if (!Parents.Any()) return true; return Parents.All( accessor => accessor.Value == null || accessor.Value.GetterFunc == null || accessor.Value.GetterFunc(accessor.Key, Entity) == null); } } }
 using System; using System.Collections.Generic; using System.Linq; namespace Highway.Data.Contexts.TypeRepresentations { internal class ObjectRepresentation { public ObjectRepresentation() { Parents = new Dictionary<object, Accessor>(); } internal object Entity { get; set; } internal IEnumerable<ObjectRepresentation> RelatedEntities { get; set; } internal Dictionary<object, Accessor> Parents { get; set; } public bool IsType<T1>() { return Entity.GetType() is T1; } internal IEnumerable<ObjectRepresentation> AllRelated() { List<ObjectRepresentation> evaluatedObjects = new List<ObjectRepresentation>(); return AllRelated(evaluatedObjects); } internal IEnumerable<ObjectRepresentation> AllRelated(List<ObjectRepresentation> evaluatedObjects) { var items = RelatedEntities.ToList(); foreach (var objectRepresentationBase in RelatedEntities) { if (evaluatedObjects.Contains(objectRepresentationBase)) { continue; } evaluatedObjects.Add(objectRepresentationBase); items.AddRange(objectRepresentationBase.AllRelated(evaluatedObjects)); } return items; } public List<ObjectRepresentation> GetObjectRepresentationsToPrune() { return AllRelated().Where(x => x.Orphaned()).ToList(); } public bool Orphaned() { if (!Parents.Any()) return true; return Parents.All( accessor => accessor.Value == null || accessor.Value.GetterFunc == null || accessor.Value.GetterFunc(accessor.Key, Entity) == null); } } }
mit
C#
875fcb67ffe3bf3df14b1afc32bbfe36926fe16b
Test coverage for mapping from nested object-value dictionaries to nested simple type enumerables
agileobjects/AgileMapper
AgileMapper.UnitTests/WhenMappingFromDictionaryMembers.cs
AgileMapper.UnitTests/WhenMappingFromDictionaryMembers.cs
namespace AgileObjects.AgileMapper.UnitTests { using System; using System.Collections.Generic; using Shouldly; using TestClasses; using Xunit; public class WhenMappingFromDictionaryMembers { [Fact] public void ShouldPopulateANestedStringFromANestedObjectEntry() { var source = new PublicField<Dictionary<string, object>> { Value = new Dictionary<string, object> { ["Line1"] = "6478 Nested Drive" } }; var result = Mapper.Map(source).ToANew<PublicField<Address>>(); result.Value.ShouldNotBeNull(); result.Value.Line1.ShouldBe("6478 Nested Drive"); } [Fact] public void ShouldPopulateANestedIntArrayFromNestedConvertibleTypedEntries() { var source = new PublicField<Dictionary<string, short>> { Value = new Dictionary<string, short> { ["[0]"] = 6478, ["[1]"] = 9832, ["[2]"] = 1028 } }; var result = Mapper.Map(source).ToANew<PublicField<int[]>>(); result.Value.ShouldNotBeNull(); result.Value.Length.ShouldBe(3); result.Value.ShouldBe(6478, 9832, 1028); } [Fact] public void ShouldPopulateANestedGuidEnumerableFromNestedConvertibleUntypedEntries() { var guidOne = Guid.NewGuid(); var guidTwo = Guid.NewGuid(); var source = new PublicField<Dictionary<string, object>> { Value = new Dictionary<string, object> { ["[0]"] = guidOne, ["[1]"] = guidTwo } }; var result = Mapper.Map(source).ToANew<PublicField<IEnumerable<Guid>>>(); result.Value.ShouldNotBeNull(); result.Value.ShouldBe(guidOne, guidTwo); } } }
namespace AgileObjects.AgileMapper.UnitTests { using System.Collections.Generic; using Shouldly; using TestClasses; using Xunit; public class WhenMappingFromDictionaryMembers { [Fact] public void ShouldPopulateANestedStringFromANestedObjectEntry() { var source = new PublicField<Dictionary<string, object>> { Value = new Dictionary<string, object> { ["Line1"] = "6478 Nested Drive" } }; var result = Mapper.Map(source).ToANew<PublicField<Address>>(); result.Value.ShouldNotBeNull(); result.Value.Line1.ShouldBe("6478 Nested Drive"); } [Fact] public void ShouldPopulateANestedIntArrayFromNestedConvertibleTypedEntries() { var source = new PublicField<Dictionary<string, short>> { Value = new Dictionary<string, short> { ["[0]"] = 6478, ["[1]"] = 9832, ["[2]"] = 1028 } }; var result = Mapper.Map(source).ToANew<PublicField<int[]>>(); result.Value.ShouldNotBeNull(); result.Value.Length.ShouldBe(3); result.Value.ShouldBe(6478, 9832, 1028); } } }
mit
C#
274967e8759fa1cc7d9f65165201c99eb09911e1
Handle null correctly and syntax cleanup
jherby2k/AudioWorks
AudioWorks/src/AudioWorks.Extensibility/RuntimeChecker.cs
AudioWorks/src/AudioWorks.Extensibility/RuntimeChecker.cs
/* Copyright © 2020 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ #if NETSTANDARD2_0 using Microsoft.Win32; #endif using System; using System.Runtime.InteropServices; namespace AudioWorks.Extensibility { /// <summary> /// A utility class for dealing with NuGet dependencies at runtime. /// </summary> public static class RuntimeChecker { /// <summary> /// Returns the NuGet framework short folder name for the current runtime. /// </summary> /// <returns>The NuGet short folder name.</returns> #if NETSTANDARD2_0 public static string GetShortFolderName() => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.Ordinal) ? $"net{GetFrameworkVersion()}" : $"netcoreapp{Version.Parse(RuntimeInformation.FrameworkDescription.Substring(RuntimeInformation.FrameworkDescription.LastIndexOf(' '))).ToString(2)}"; static string GetFrameworkVersion() { using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); using (var ndpKey = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\")) return (int?) ndpKey?.GetValue("Release", 0) switch { >= 528040 => "48", >= 461808 => "472", >= 461308 => "471", >= 460798 => "47", _ => "462" }; } #else public static string GetShortFolderName() { var version = Version.Parse( RuntimeInformation.FrameworkDescription[RuntimeInformation.FrameworkDescription.LastIndexOf(' ')..] .Split('-')[0]); return version.Major >= 5 ? $"net{version.ToString(2)}" : $"netcoreapp{version.ToString(2)}"; } #endif } }
/* Copyright © 2020 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ #if NETSTANDARD2_0 using Microsoft.Win32; #endif using System; using System.Runtime.InteropServices; namespace AudioWorks.Extensibility { /// <summary> /// A utility class for dealing with NuGet dependencies at runtime. /// </summary> public static class RuntimeChecker { /// <summary> /// Returns the NuGet framework short folder name for the current runtime. /// </summary> /// <returns>The NuGet short folder name.</returns> #if NETSTANDARD2_0 public static string GetShortFolderName() => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.Ordinal) ? $"net{GetFrameworkVersion()}" : $"netcoreapp{Version.Parse(RuntimeInformation.FrameworkDescription.Substring(RuntimeInformation.FrameworkDescription.LastIndexOf(' '))).ToString(2)}"; static string GetFrameworkVersion() { using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); using (var ndpKey = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\")) { var release = (int) ndpKey.GetValue("Release", 0); return release switch { >= 528040 => "48", >= 461808 => "472", >= 461308 => "471", _ => release >= 460798 ? "47" : "462" }; } } #else public static string GetShortFolderName() { var version = Version.Parse( RuntimeInformation.FrameworkDescription[RuntimeInformation.FrameworkDescription.LastIndexOf(' ')..] .Split('-')[0]); return version.Major >= 5 ? $"net{version.ToString(2)}" : $"netcoreapp{version.ToString(2)}"; } #endif } }
agpl-3.0
C#
5caaa50e2cd3698efde1313070a2ba8724ed1f66
Enable to override the default setting
DotNetKit/DotNetKit.Wpf.AutoCompleteComboBox
DotNetKit.Wpf.AutoCompleteComboBox/Windows/Controls/AutoCompleteComboBoxSetting.cs
DotNetKit.Wpf.AutoCompleteComboBox/Windows/Controls/AutoCompleteComboBoxSetting.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotNetKit.Windows.Controls { /// <summary> /// Represents an object to configure <see cref="AutoCompleteComboBox"/>. /// </summary> public class AutoCompleteComboBoxSetting { /// <summary> /// Gets a filter function which determines whether items should be suggested or not /// for the specified query. /// Default: Gets the filter which maps an item to <c>true</c> /// if its text contains the query (case insensitive). /// </summary> /// <param name="query"> /// The string input by user. /// </param> /// <param name="stringFromItem"> /// The function to get a string which identifies the specified item. /// </param> /// <returns></returns> public virtual Func<object, bool> GetFilter(string query, Func<object, string> stringFromItem) { return item => stringFromItem(item).ToLowerInvariant() .Contains(query.ToLowerInvariant()); } /// <summary> /// Gets an integer. /// The combobox opens the drop down /// if the number of suggested items is less than the value. /// Note that the value is larger, it's heavier to open the drop down. /// Default: 100. /// </summary> public virtual int MaxSuggestionCount { get { return 100; } } /// <summary> /// Gets the duration to delay updating the suggestion list. /// Returns <c>Zero</c> if no delay. /// Default: 300ms. /// </summary> public virtual TimeSpan Delay { get { return TimeSpan.FromMilliseconds(300.0); } } static AutoCompleteComboBoxSetting @default = new AutoCompleteComboBoxSetting(); /// <summary> /// Gets the default setting. /// </summary> public static AutoCompleteComboBoxSetting Default { get { return @default; } set { if (value == null) throw new ArgumentNullException("value"); @default = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotNetKit.Windows.Controls { /// <summary> /// Represents an object to configure <see cref="AutoCompleteComboBox"/>. /// </summary> public class AutoCompleteComboBoxSetting { /// <summary> /// Gets a filter function which determines whether items should be suggested or not /// for the specified query. /// Default: Gets the filter which maps an item to <c>true</c> /// if its text contains the query (case insensitive). /// </summary> /// <param name="query"> /// The string input by user. /// </param> /// <param name="stringFromItem"> /// The function to get a string which identifies the specified item. /// </param> /// <returns></returns> public virtual Func<object, bool> GetFilter(string query, Func<object, string> stringFromItem) { return item => stringFromItem(item).ToLowerInvariant() .Contains(query.ToLowerInvariant()); } /// <summary> /// Gets an integer. /// The combobox opens the drop down /// if the number of suggested items is less than the value. /// Note that the value is larger, it's heavier to open the drop down. /// Default: 100. /// </summary> public virtual int MaxSuggestionCount { get { return 100; } } /// <summary> /// Gets the duration to delay updating the suggestion list. /// Returns <c>Zero</c> if no delay. /// Default: 300ms. /// </summary> public virtual TimeSpan Delay { get { return TimeSpan.FromMilliseconds(300.0); } } static readonly AutoCompleteComboBoxSetting @default = new AutoCompleteComboBoxSetting(); /// <summary> /// Gets the default setting. /// </summary> public static AutoCompleteComboBoxSetting Default { get { return @default; } } } }
mit
C#
05a597e045f5267726315fb78e8a10661356245a
Tweak so it'll send for any non-ignored units
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Jobs/PERSTATReportJob.cs
Battery-Commander.Web/Jobs/PERSTATReportJob.cs
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentEmail.Core.Models; using FluentScheduler; using System.Collections.Generic; using System.IO; namespace BatteryCommander.Web.Jobs { public class PERSTATReportJob : IJob { private static IList<Address> Recipients => new List<Address>(new Address[] { Matt // new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" } }); internal static Address Matt => new Address { Name = "1LT Wagner", EmailAddress = "MattGWagner@gmail.com" }; private readonly Database db; private readonly IFluentEmail emailSvc; public PERSTATReportJob(Database db, IFluentEmail emailSvc) { this.db = db; this.emailSvc = emailSvc; } public virtual void Execute() { foreach (var unit in UnitService.List(db).GetAwaiter().GetResult()) { // HACK - Configure the recipients and units that this is going to be wired up for emailSvc .To(Recipients) .SetFrom(Matt.EmailAddress, Matt.Name) .Subject($"{unit.Name} | RED 1 PERSTAT") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit) .Send(); } } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentEmail.Core.Models; using FluentScheduler; using System.Collections.Generic; using System.IO; namespace BatteryCommander.Web.Jobs { public class PERSTATReportJob : IJob { private static IList<Address> Recipients => new List<Address>(new Address[] { Matt // new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" } }); internal static Address Matt => new Address { Name = "1LT Wagner", EmailAddress = "MattGWagner@gmail.com" }; private readonly Database db; private readonly IFluentEmail emailSvc; public PERSTATReportJob(Database db, IFluentEmail emailSvc) { this.db = db; this.emailSvc = emailSvc; } public virtual void Execute() { // HACK - Configure the recipients and units that this is going to be wired up for var unit = UnitService.Get(db, unitId: 3).Result; // C Batt emailSvc .To(Recipients) .SetFrom(Matt.EmailAddress, Matt.Name) .Subject($"{unit.Name} | RED 1 PERSTAT") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit) .Send(); } } }
mit
C#
0c3ae5d1b54577021a1656cba2dfaa8ee8fb1056
Fix image previews not available - #610
braegelno5/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,crowar/Bonobo-Git-Server,lkho/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,lkho/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,gencer/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,gencer/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,lkho/Bonobo-Git-Server,larshg/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,gencer/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,crowar/Bonobo-Git-Server,larshg/Bonobo-Git-Server,larshg/Bonobo-Git-Server,gencer/Bonobo-Git-Server,larshg/Bonobo-Git-Server,crowar/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,crowar/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,lkho/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,crowar/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,crowar/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server
Bonobo.Git.Server/Views/Repository/Blob.cshtml
Bonobo.Git.Server/Views/Repository/Blob.cshtml
@using Bonobo.Git.Server.Extensions @model RepositoryTreeDetailModel @{ Layout = "~/Views/Repository/_RepositoryLayout.cshtml"; ViewBag.Title = Resources.Repository_Tree_Title; } @if (Model != null) { @Html.Partial("_BranchSwitcher") @Html.Partial("_AddressBar") <div class="blob"> @{ <div class="controls"> <span>@(Model.IsText ? Model.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).Length + " lines |" : "") @FileDisplayHandler.GetFileSizeString(Model.Data.LongLength)</span> <a href="@Url.Action("Blame", new { id=ViewBag.ID, encodedName = PathEncoder.Encode(Model.TreeName), encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true)})"><i class="fa fa-comments"></i> @Resources.Repository_Tree_Blame</a> <a href="@Url.Action("History", new { id=ViewBag.ID, encodedName = PathEncoder.Encode(Model.TreeName), encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true)})"><i class="fa fa-history"></i> @Resources.Repository_Tree_History</a> <a href="@Url.Action("Raw", new { id=ViewBag.ID, encodedName = PathEncoder.Encode(Model.TreeName), encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true), display = true })"><i class="fa fa-file-text"></i> @Resources.Repository_Tree_RawDisplay</a> <a href="@Url.Action("Raw", new { id=ViewBag.ID, encodedName = PathEncoder.Encode(Model.TreeName), encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true) })"><i class="fa fa-download"></i> @Resources.Repository_Tree_Download</a> </div> } @if (Model.IsImage) { <img class="fileImage" alt="@Model.Name" src="@Url.Action("Raw", new { id=ViewBag.ID, encodedName = PathEncoder.Encode(Model.TreeName), encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true) })" /> } else if (Model.IsText && Model.IsMarkdown) { <div class="markdown">@Html.MarkdownToHtml(Model.Text)</div> } else if (Model.IsText) { <pre><code class="@Model.TextBrush">@Model.Text</code></pre> } else { <pre><code>@Resources.Repository_Tree_PreviewNotSupported</code></pre> } </div> } @section scripts { <script>hljs.configure({tabReplace:' '});hljs.initHighlightingOnLoad();</script> }
@using Bonobo.Git.Server.Extensions @model RepositoryTreeDetailModel @{ Layout = "~/Views/Repository/_RepositoryLayout.cshtml"; ViewBag.Title = Resources.Repository_Tree_Title; } @if (Model != null) { @Html.Partial("_BranchSwitcher") @Html.Partial("_AddressBar") <div class="blob"> @{ <div class="controls"> <span>@(Model.IsText ? Model.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).Length + " lines |" : "") @FileDisplayHandler.GetFileSizeString(Model.Data.LongLength)</span> <a href="@Url.Action("Blame", new { id=ViewBag.ID, encodedName = PathEncoder.Encode(Model.TreeName), encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true)})"><i class="fa fa-comments"></i> @Resources.Repository_Tree_Blame</a> <a href="@Url.Action("History", new { id=ViewBag.ID, encodedName = PathEncoder.Encode(Model.TreeName), encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true)})"><i class="fa fa-history"></i> @Resources.Repository_Tree_History</a> <a href="@Url.Action("Raw", new { id=ViewBag.ID, encodedName = PathEncoder.Encode(Model.TreeName), encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true), display = true })"><i class="fa fa-file-text"></i> @Resources.Repository_Tree_RawDisplay</a> <a href="@Url.Action("Raw", new { id=ViewBag.ID, encodedName = PathEncoder.Encode(Model.TreeName), encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true) })"><i class="fa fa-download"></i> @Resources.Repository_Tree_Download</a> </div> } @if (Model.IsImage) { <img class="fileImage" alt="@Model.Name" src="@Url.Action("Raw", new { encodedPath = PathEncoder.Encode(Model.Path, allowSlash: true) })" /> } else if (Model.IsText && Model.IsMarkdown) { <div class="markdown">@Html.MarkdownToHtml(Model.Text)</div> } else if (Model.IsText) { <pre><code class="@Model.TextBrush">@Model.Text</code></pre> } else { <pre><code>@Resources.Repository_Tree_PreviewNotSupported</code></pre> } </div> } @section scripts { <script>hljs.configure({tabReplace:' '});hljs.initHighlightingOnLoad();</script> }
mit
C#
fefc3f20c27c7419c1a560c91784d4b631ec7022
allow UseJsonApiWithAutofac to take ILifetimeScope
SphtKr/JSONAPI.NET,JSONAPIdotNET/JSONAPI.NET,danshapir/JSONAPI.NET,SathishN/JSONAPI.NET
JSONAPI.Autofac/HttpConfigurationExtensions.cs
JSONAPI.Autofac/HttpConfigurationExtensions.cs
using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; using JSONAPI.Core; namespace JSONAPI.Autofac { public static class HttpConfigurationExtensions { public static void UseJsonApiWithAutofac(this HttpConfiguration httpConfig, ILifetimeScope applicationLifetimeScope) { var jsonApiConfiguration = applicationLifetimeScope.Resolve<JsonApiHttpConfiguration>(); jsonApiConfiguration.Apply(httpConfig); httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(applicationLifetimeScope); } } }
using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; using JSONAPI.Core; namespace JSONAPI.Autofac { public static class HttpConfigurationExtensions { public static void UseJsonApiWithAutofac(this HttpConfiguration httpConfig, IContainer applicationContainer) { var jsonApiConfiguration = applicationContainer.Resolve<JsonApiHttpConfiguration>(); jsonApiConfiguration.Apply(httpConfig); httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(applicationContainer); } } }
mit
C#
6a9ca74c72a5ec47e906ee876e20272e9c8530d6
improve fix for asp.net core 502 error
zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,303248153/ZKWeb,zkweb-framework/ZKWeb
ZKWeb/ZKWeb.Hosting.AspNetCore/CoreHttpResponseWrapper.cs
ZKWeb/ZKWeb.Hosting.AspNetCore/CoreHttpResponseWrapper.cs
using System.IO; using Microsoft.AspNetCore.Http; using ZKWebStandard.Web; using System; namespace ZKWeb.Hosting.AspNetCore { /// <summary> /// Http response wrapper for Asp.Net Core /// </summary> internal class CoreHttpResponseWrapper : IHttpResponse { /// <summary> /// Parent http context /// </summary> protected CoreHttpContextWrapper ParentContext { get; set; } /// <summary> /// Original http response /// </summary> protected HttpResponse CoreResponse { get; set; } public Stream Body { get { return CoreResponse.Body; } } public string ContentType { get { return CoreResponse.ContentType; } set { CoreResponse.ContentType = value; } } public IHttpContext HttpContext { get { return ParentContext; } } public int StatusCode { get { return CoreResponse.StatusCode; } set { CoreResponse.StatusCode = value; } } public void SetCookie(string key, string value, HttpCookieOptions options) { options = options ?? new HttpCookieOptions(); var coreOptions = new CookieOptions(); if (options.Domain != null) { coreOptions.Domain = options.Domain; } if (options.Expires != null) { coreOptions.Expires = options.Expires; } if (options.HttpOnly != null) { coreOptions.HttpOnly = options.HttpOnly.Value; } if (options.Path != null) { coreOptions.Path = options.Path; } if (options.Secure != null) { coreOptions.Secure = options.Secure.Value; } CoreResponse.Cookies.Append(key, value, coreOptions); } public void AddHeader(string key, string value) { CoreResponse.Headers.Add(key, value); } public void Redirect(string url, bool permanent) { CoreResponse.Redirect(url, permanent); End(); } public void End() { // Fix kesterl 1.0.0 304 => 502 error // See https://github.com/aspnet/KestrelHttpServer/issues/952 try { if (Body.Position > 0) { Body.Flush(); } else { try { CoreResponse.ContentLength = 0; } catch (InvalidOperationException) { } } } catch (NotSupportedException) { // This exception will throw when access Position property if no contents writed before. try { CoreResponse.ContentLength = 0; } catch (InvalidOperationException) { } } throw new CoreHttpResponseEndException(); } /// <summary> /// Initialize /// </summary> /// <param name="parentContext">Parent http context</param> /// <param name="coreResponse">Original http response</param> public CoreHttpResponseWrapper( CoreHttpContextWrapper parentContext, HttpResponse coreResponse) { ParentContext = parentContext; CoreResponse = coreResponse; } } }
using System.IO; using Microsoft.AspNetCore.Http; using ZKWebStandard.Web; using System; namespace ZKWeb.Hosting.AspNetCore { /// <summary> /// Http response wrapper for Asp.Net Core /// </summary> internal class CoreHttpResponseWrapper : IHttpResponse { /// <summary> /// Parent http context /// </summary> protected CoreHttpContextWrapper ParentContext { get; set; } /// <summary> /// Original http response /// </summary> protected HttpResponse CoreResponse { get; set; } public Stream Body { get { return CoreResponse.Body; } } public string ContentType { get { return CoreResponse.ContentType; } set { CoreResponse.ContentType = value; } } public IHttpContext HttpContext { get { return ParentContext; } } public int StatusCode { get { return CoreResponse.StatusCode; } set { CoreResponse.StatusCode = value; } } public void SetCookie(string key, string value, HttpCookieOptions options) { options = options ?? new HttpCookieOptions(); var coreOptions = new CookieOptions(); if (options.Domain != null) { coreOptions.Domain = options.Domain; } if (options.Expires != null) { coreOptions.Expires = options.Expires; } if (options.HttpOnly != null) { coreOptions.HttpOnly = options.HttpOnly.Value; } if (options.Path != null) { coreOptions.Path = options.Path; } if (options.Secure != null) { coreOptions.Secure = options.Secure.Value; } CoreResponse.Cookies.Append(key, value, coreOptions); } public void AddHeader(string key, string value) { CoreResponse.Headers.Add(key, value); } public void Redirect(string url, bool permanent) { CoreResponse.Redirect(url, permanent); End(); } public void End() { // Fix kesterl 1.0.0 304 => 502 error // See https://github.com/aspnet/KestrelHttpServer/issues/952 try { if (Body.Position > 0) { Body.Flush(); } else { CoreResponse.ContentLength = 0; } } catch (NotSupportedException) { // This exception will throw when access Position property if no contents writed before. CoreResponse.ContentLength = 0; } throw new CoreHttpResponseEndException(); } /// <summary> /// Initialize /// </summary> /// <param name="parentContext">Parent http context</param> /// <param name="coreResponse">Original http response</param> public CoreHttpResponseWrapper( CoreHttpContextWrapper parentContext, HttpResponse coreResponse) { ParentContext = parentContext; CoreResponse = coreResponse; } } }
mit
C#
5f6d83963062513ec4bd9027a580d40d72aa0f8a
Make as an obsolete class.
andyshao/CMS,lingxyd/CMS,techwareone/Kooboo-CMS,jtm789/CMS,Kooboo/CMS,Kooboo/CMS,jtm789/CMS,lingxyd/CMS,lingxyd/CMS,techwareone/Kooboo-CMS,jtm789/CMS,andyshao/CMS,techwareone/Kooboo-CMS,Kooboo/CMS,andyshao/CMS
Kooboo.CMS/Kooboo/ApplicationInitialization.cs
Kooboo.CMS/Kooboo/ApplicationInitialization.cs
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using System; using System.Collections.Generic; using System.Linq; namespace Kooboo { /// <summary> /// /// </summary> [Obsolete] public static class ApplicationInitialization { #region Fields private class InitializationItem { public Action InitializeMethod { get; set; } public int Priority { get; set; } } private static List<InitializationItem> items = new List<InitializationItem>(); #endregion #region Methods /// <summary> /// Registers the initializer method. /// </summary> /// <param name="method">The method.</param> /// <param name="priority">The priority.</param> public static void RegisterInitializerMethod(Action method, int priority) { items.Add(new InitializationItem() { InitializeMethod = method, Priority = priority }); } /// <summary> /// Executes this instance. /// </summary> public static void Execute() { lock (items) { foreach (var item in items.OrderBy(it => it.Priority)) { item.InitializeMethod(); } items.Clear(); } } #endregion } }
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using System; using System.Collections.Generic; using System.Linq; namespace Kooboo { /// <summary> /// /// </summary> public static class ApplicationInitialization { #region Fields private class InitializationItem { public Action InitializeMethod { get; set; } public int Priority { get; set; } } private static List<InitializationItem> items = new List<InitializationItem>(); #endregion #region Methods /// <summary> /// Registers the initializer method. /// </summary> /// <param name="method">The method.</param> /// <param name="priority">The priority.</param> public static void RegisterInitializerMethod(Action method, int priority) { items.Add(new InitializationItem() { InitializeMethod = method, Priority = priority }); } /// <summary> /// Executes this instance. /// </summary> public static void Execute() { lock (items) { foreach (var item in items.OrderBy(it => it.Priority)) { item.InitializeMethod(); } items.Clear(); } } #endregion } }
bsd-3-clause
C#
1e2fd356650b517eed581dd675f7b146bf964d4a
add new site header
csyntax/BlogSystem
Source/BlogSystem.Web/Views/Shared/_Header.cshtml
Source/BlogSystem.Web/Views/Shared/_Header.cshtml
<header id="site-header"> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <i class="fa fa-bars" aria-hidden="true"></i> </button> <a href="@Url.Action("Index", "Home")" class="navbar-brand" title="Home"> @ViewBag.Settings["Title"] </a> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li> @Html.ActionLink("Home", "Index", "Home") </li> @{ Html.RenderAction("Menu", "Nav"); } </ul> <ul class="nav navbar-nav navbar-right"> @{ Html.RenderAction("AdminMenu", "Nav"); } </ul> </div> </div> </nav> </header>
<header> <div class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="@Url.Action("Index", "Home", new { area = string.Empty })" class="navbar-brand"> @ViewBag.Settings["Title"] </a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> @{ Html.RenderAction("Menu", "Nav"); } <li class="dropdown"> @{ Html.RenderAction("AdminMenu", "Nav"); } </li> </ul> </div> </div> </div> </header>
mit
C#
805b2851ba654226bcabf2cc9ecf7fed9b2ee3ba
Add Attributes for DataGridView
techphernalia/MyPersonalAccounts
MyPersonalAccountsModel/Inventory/StockUnit.cs
MyPersonalAccountsModel/Inventory/StockUnit.cs
using System.ComponentModel; namespace com.techphernalia.MyPersonalAccounts.Model.Inventory { /// <summary> /// Unit for Inventory Items /// </summary> public class StockUnit { /// <summary> /// Unique Identifier of Unit /// </summary> [Browsable(false)] public int StockUnitId { get; set; } /// <summary> /// Name of Unit /// </summary> [DisplayName("Unit")] public string StockUnitName { get; set; } /// <summary> /// Symbol for Unit /// </summary> [DisplayName("Symbol")] public string StockUnitSymbol { get; set; } /// <summary> /// Number of Decimal Places in Unit /// </summary> [DisplayName("Decimal Places")] public int StockUnitDecimalPlaces { get; set; } /// <summary> /// Human Readable System Id /// </summary> [DisplayName("Identifier")] public string SystemId { get; set; } /// <summary> /// Display Unit information /// </summary> /// <returns></returns> public override string ToString() { return string.Format("[{0}] with symbol [{1}] having {2} Decimal Places with Id : {3}", StockUnitName, StockUnitSymbol, StockUnitDecimalPlaces, StockUnitId); } } }
namespace com.techphernalia.MyPersonalAccounts.Model.Inventory { /// <summary> /// Unit for Inventory Items /// </summary> public class StockUnit { /// <summary> /// Unique Identifier of Unit /// </summary> public int StockUnitId { get; set; } /// <summary> /// Name of Unit /// </summary> public string StockUnitName { get; set; } /// <summary> /// Symbol for Unit /// </summary> public string StockUnitSymbol { get; set; } /// <summary> /// Number of Decimal Places in Unit /// </summary> public int StockUnitDecimalPlaces { get; set; } /// <summary> /// Human Readable System Id /// </summary> public string SystemId { get; set; } /// <summary> /// Display Unit information /// </summary> /// <returns></returns> public override string ToString() { return string.Format("[{0}] with symbol [{1}] having {2} Decimal Places with Id : {3}", StockUnitName, StockUnitSymbol, StockUnitDecimalPlaces, StockUnitId); } } }
mit
C#
4a95b70bae0c961054c2cfbb521cd8003f3e0516
make QueueSettings constructor public
poxet/Influx-Capacitor,poxet/influxdb-collector
Tharga.Influx-Capacitor/Entities/QueueSettings.cs
Tharga.Influx-Capacitor/Entities/QueueSettings.cs
using Tharga.InfluxCapacitor.Interface; namespace Tharga.InfluxCapacitor.Entities { public class QueueSettings : IQueueSettings { public QueueSettings(int flushSecondsInterval = 30, bool dropOnFail = false, int maxQueueSize = 20000) { FlushSecondsInterval = flushSecondsInterval; DropOnFail = dropOnFail; MaxQueueSize = maxQueueSize; } public int FlushSecondsInterval { get; } public bool DropOnFail { get; } public int MaxQueueSize { get; } } }
using Tharga.InfluxCapacitor.Interface; namespace Tharga.InfluxCapacitor.Entities { public class QueueSettings : IQueueSettings { internal QueueSettings(int flushSecondsInterval, bool dropOnFail, int maxQueueSize) { FlushSecondsInterval = flushSecondsInterval; DropOnFail = dropOnFail; MaxQueueSize = maxQueueSize; } public int FlushSecondsInterval { get; } public bool DropOnFail { get; } public int MaxQueueSize { get; } } }
mit
C#
1cf14a99d4c902001bfdfedd984c35c19d0886c0
Add missing banner.
drewnoakes/dasher
Dasher.Tests/TestUtils.cs
Dasher.Tests/TestUtils.cs
#region License // // Dasher // // Copyright 2015 Drew Noakes // // 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. // // More information about this project is available at: // // https://github.com/drewnoakes/dasher // #endregion using System; namespace Dasher.Tests { internal static class TestUtils { internal static void CleanUpForPerfTest() { GC.Collect(2, GCCollectionMode.Forced); GC.WaitForFullGCComplete(1000); GC.WaitForPendingFinalizers(); } } }
using System; namespace Dasher.Tests { internal static class TestUtils { internal static void CleanUpForPerfTest() { GC.Collect(2, GCCollectionMode.Forced); GC.WaitForFullGCComplete(1000); GC.WaitForPendingFinalizers(); } } }
apache-2.0
C#
6cd65661d06faa9bca1d80be02356445441d514d
Implement `ArrayLiteralAst.ToString()`
WimObiwan/Pash,sillvan/Pash,mrward/Pash,WimObiwan/Pash,Jaykul/Pash,JayBazuzi/Pash,ForNeVeR/Pash,ForNeVeR/Pash,Jaykul/Pash,mrward/Pash,sburnicki/Pash,Jaykul/Pash,JayBazuzi/Pash,ForNeVeR/Pash,ForNeVeR/Pash,sburnicki/Pash,JayBazuzi/Pash,JayBazuzi/Pash,Jaykul/Pash,sburnicki/Pash,WimObiwan/Pash,mrward/Pash,sillvan/Pash,WimObiwan/Pash,sburnicki/Pash,sillvan/Pash,sillvan/Pash,mrward/Pash
Source/System.Management/Automation/Language/ArrayLiteralAst.cs
Source/System.Management/Automation/Language/ArrayLiteralAst.cs
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; namespace System.Management.Automation.Language { public class ArrayLiteralAst : ExpressionAst { public ArrayLiteralAst(IScriptExtent extent, IList<ExpressionAst> elements) : base(extent) { this.Elements = elements.ToReadOnlyCollection(); } public ReadOnlyCollection<ExpressionAst> Elements { get; private set; } public override Type StaticType { get { throw new NotImplementedException(this.ToString()); } } internal override IEnumerable<Ast> Children { get { foreach (var item in this.Elements) yield return item; foreach (var item in privateGetChildren()) yield return item; } } // Method call works around a Mono C# compiler crash [System.Diagnostics.DebuggerStepThrough] private IEnumerable<Ast> privateGetChildren() { return base.Children; } public override string ToString() { return string.Format("{0}, ...", this.Elements.First()); } } }
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; namespace System.Management.Automation.Language { public class ArrayLiteralAst : ExpressionAst { public ArrayLiteralAst(IScriptExtent extent, IList<ExpressionAst> elements) : base(extent) { this.Elements = elements.ToReadOnlyCollection(); } public ReadOnlyCollection<ExpressionAst> Elements { get; private set; } public override Type StaticType { get { throw new NotImplementedException(this.ToString()); } } internal override IEnumerable<Ast> Children { get { foreach (var item in this.Elements) yield return item; foreach (var item in privateGetChildren()) yield return item; } } // Method call works around a Mono C# compiler crash [System.Diagnostics.DebuggerStepThrough] private IEnumerable<Ast> privateGetChildren() { return base.Children; } } }
bsd-3-clause
C#
eabb1556b3ff626874eb2893310d414e9f8afdf9
Fix Watch ExternalAccess
diryboy/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,dotnet/roslyn,KevinRansom/roslyn,physhi/roslyn,sharwell/roslyn,wvdd007/roslyn,wvdd007/roslyn,diryboy/roslyn,mavasani/roslyn,diryboy/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,bartdesmet/roslyn,weltkante/roslyn,weltkante/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,eriawan/roslyn,eriawan/roslyn,weltkante/roslyn,physhi/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,eriawan/roslyn,dotnet/roslyn
src/Tools/ExternalAccess/DotNetWatch/DotNetWatchEditAndContinueWorkspaceService.cs
src/Tools/ExternalAccess/DotNetWatch/DotNetWatchEditAndContinueWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.DotNetWatch { internal sealed class DotNetWatchEditAndContinueWorkspaceService : IWorkspaceService { [ExportWorkspaceServiceFactory(typeof(DotNetWatchEditAndContinueWorkspaceService)), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) { return new DotNetWatchEditAndContinueWorkspaceService(workspaceServices.GetRequiredService<IEditAndContinueWorkspaceService>()); } } private readonly SolutionActiveStatementSpanProvider _nullSolutionActiveStatementSpanProvider = (_, _) => new(ImmutableArray<TextSpan>.Empty); private readonly IEditAndContinueWorkspaceService _workspaceService; public DotNetWatchEditAndContinueWorkspaceService(IEditAndContinueWorkspaceService workspaceService) { _workspaceService = workspaceService; } public ValueTask OnSourceFileUpdatedAsync(Document document, CancellationToken cancellationToken) => _workspaceService.OnSourceFileUpdatedAsync(document, cancellationToken); public void CommitSolutionUpdate() => _workspaceService.CommitSolutionUpdate(); public void DiscardSolutionUpdate() => _workspaceService.DiscardSolutionUpdate(); public void EndDebuggingSession() => _workspaceService.EndDebuggingSession(out _); public void StartDebuggingSession(Solution solution) => _workspaceService.StartDebuggingSessionAsync(solution, captureMatchingDocuments: false, CancellationToken.None).GetAwaiter().GetResult(); public void StartEditSession() => _workspaceService.StartEditSession(StubManagedEditAndContinueDebuggerService.Instance, out _); public void EndEditSession() => _workspaceService.EndEditSession(out _); public async ValueTask<DotNetWatchManagedModuleUpdatesWrapper> EmitSolutionUpdateAsync(Solution solution, CancellationToken cancellationToken) { var results = await _workspaceService.EmitSolutionUpdateAsync(solution, _nullSolutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); return new DotNetWatchManagedModuleUpdatesWrapper(in results.ModuleUpdates); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.DotNetWatch { internal sealed class DotNetWatchEditAndContinueWorkspaceService : IWorkspaceService { [ExportWorkspaceServiceFactory(typeof(DotNetWatchEditAndContinueWorkspaceService)), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) { return new DotNetWatchEditAndContinueWorkspaceService(workspaceServices.GetRequiredService<IEditAndContinueWorkspaceService>()); } } private readonly SolutionActiveStatementSpanProvider _nullSolutionActiveStatementSpanProvider = (_, _) => new(ImmutableArray<TextSpan>.Empty); private readonly IEditAndContinueWorkspaceService _workspaceService; public DotNetWatchEditAndContinueWorkspaceService(IEditAndContinueWorkspaceService workspaceService) { _workspaceService = workspaceService; } public ValueTask OnSourceFileUpdatedAsync(Document document, CancellationToken cancellationToken) => _workspaceService.OnSourceFileUpdatedAsync(document, cancellationToken); public void CommitSolutionUpdate() => _workspaceService.CommitSolutionUpdate(); public void DiscardSolutionUpdate() => _workspaceService.DiscardSolutionUpdate(); public void EndDebuggingSession() => _workspaceService.EndDebuggingSession(out _); public void StartDebuggingSession(Solution solution) => _workspaceService.StartDebuggingSession(solution); public void StartEditSession() => _workspaceService.StartEditSession(StubManagedEditAndContinueDebuggerService.Instance, out _); public void EndEditSession() => _workspaceService.EndEditSession(out _); public async ValueTask<DotNetWatchManagedModuleUpdatesWrapper> EmitSolutionUpdateAsync(Solution solution, CancellationToken cancellationToken) { var (updates, _) = await _workspaceService.EmitSolutionUpdateAsync(solution, _nullSolutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); return new DotNetWatchManagedModuleUpdatesWrapper(in updates); } } }
mit
C#
83147922f407922f180a0edde8562e6a572003b8
Remove gun debug logging.
space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Client/GameObjects/Components/Weapons/Ranged/ClientRangedWeaponComponent.cs
Content.Client/GameObjects/Components/Weapons/Ranged/ClientRangedWeaponComponent.cs
using System; using Content.Shared.GameObjects.Components.Weapons.Ranged; using SS14.Shared.Interfaces.Timing; using SS14.Shared.IoC; using SS14.Shared.Log; using SS14.Shared.Map; namespace Content.Client.GameObjects.Components.Weapons.Ranged { public sealed class ClientRangedWeaponComponent : SharedRangedWeaponComponent { private TimeSpan _lastFireTime; private int _tick; public void TryFire(GridCoordinates worldPos) { var curTime = IoCManager.Resolve<IGameTiming>().CurTime; var span = curTime - _lastFireTime; if (span.TotalSeconds < 1 / FireRate) { return; } _lastFireTime = curTime; SendNetworkMessage(new FireMessage(worldPos, _tick++)); } } }
using System; using Content.Shared.GameObjects.Components.Weapons.Ranged; using SS14.Shared.Interfaces.Timing; using SS14.Shared.IoC; using SS14.Shared.Log; using SS14.Shared.Map; namespace Content.Client.GameObjects.Components.Weapons.Ranged { public sealed class ClientRangedWeaponComponent : SharedRangedWeaponComponent { private TimeSpan _lastFireTime; private int _tick; public void TryFire(GridCoordinates worldPos) { var curTime = IoCManager.Resolve<IGameTiming>().CurTime; var span = curTime - _lastFireTime; if (span.TotalSeconds < 1 / FireRate) { return; } Logger.Debug("Delay: {0}", span.TotalSeconds); _lastFireTime = curTime; SendNetworkMessage(new FireMessage(worldPos, _tick++)); } } }
mit
C#
d27021d688b0c99b5707a0df0626e4df476d0a78
Correct Display name
NJWolf/SportsStore
SportsStore.Domain/Entities/ShippingDetails.cs
SportsStore.Domain/Entities/ShippingDetails.cs
using System.ComponentModel.DataAnnotations; namespace SportsStore.Domain.Entities { public class ShippingDetails { [Required(ErrorMessage ="Please enter name")] public string Name { get; set; } [Required(ErrorMessage ="Please enter address")] [Display(Name="Line 1")] public string Line1 { get; set; } [Display(Name="Line 2")] public string Line2 { get; set; } [Display(Name="Line 3")] public string Line3 { get; set; } [Required(ErrorMessage ="Please enter a city")] public string City { get; set; } [Required(ErrorMessage ="Please enter a State")] public string State { get; set; } public string Zip { get; set; } [Required(ErrorMessage ="Please enter a country")] public string Country { get; set; } public bool GiftWrap { get; set; } } }
using System.ComponentModel.DataAnnotations; namespace SportsStore.Domain.Entities { public class ShippingDetails { [Required(ErrorMessage ="Please enter name")] public string Name { get; set; } [Required(ErrorMessage ="Please enter address")] public string Line1 { get; set; } public string Line2 { get; set; } public string Line3 { get; set; } [Required(ErrorMessage ="Please enter a city")] public string City { get; set; } [Required(ErrorMessage ="Please enter a State")] public string State { get; set; } public string Zip { get; set; } [Required(ErrorMessage ="Please enter a country")] public string Country { get; set; } public bool GiftWrap { get; set; } } }
apache-2.0
C#
1d82c43f3446fbab07ee997d7bc2d7a1b4e3d850
Address feedback.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Extensions/SystemNetExtensions.cs
WalletWasabi/Extensions/SystemNetExtensions.cs
using System.Diagnostics.CodeAnalysis; namespace System.Net { public static class SystemNetExtensions { /// <summary> /// Tries to get port from <paramref name="endPoint"/> which must be either <see cref="DnsEndPoint"/> or <see cref="IPEndPoint"/>. /// </summary> /// <returns><c>true</c> when port can be returned for <paramref name="endPoint"/>, <c>false</c> otherwise.</returns> public static bool TryGetPort(this EndPoint endPoint, [NotNullWhen(true)] out int? port) { return TryGetHostAndPort(endPoint, out var _, out port); } /// <summary> /// Tries to get host from <paramref name="endPoint"/> which must be either <see cref="DnsEndPoint"/> or <see cref="IPEndPoint"/>. /// </summary> /// <returns><c>true</c> when host can be returned for <paramref name="endPoint"/>, <c>false</c> otherwise.</returns> public static bool TryGetHost(this EndPoint endPoint, [NotNullWhen(true)] out string? host) { return TryGetHostAndPort(endPoint, out host, out var _); } /// <summary> /// Tries to get host and port from <paramref name="endPoint"/> which must be either <see cref="DnsEndPoint"/> or <see cref="IPEndPoint"/>. /// </summary> /// <returns><c>true</c> when host and port can be returned for <paramref name="endPoint"/>, <c>false</c> otherwise.</returns> public static bool TryGetHostAndPort(this EndPoint endPoint, [NotNullWhen(true)] out string? host, [NotNullWhen(true)] out int? port) { if (endPoint is DnsEndPoint dnsEndPoint) { host = dnsEndPoint.Host; port = dnsEndPoint.Port; return true; } else if (endPoint is IPEndPoint ipEndPoint) { host = ipEndPoint.Address.ToString(); port = ipEndPoint.Port; return true; } else { host = null; port = null; return false; } } } }
using System.Diagnostics.CodeAnalysis; namespace System.Net { public static class SystemNetExtensions { /// <summary> /// Tries to get port from <paramref name="endPoint"/> which must be either <see cref="DnsEndPoint"/> or <see cref="IPEndPoint"/>. /// </summary> /// <returns><c>true</c> when port can be returned for <paramref name="endPoint"/>, <c>false</c> otherwise.</returns> public static bool TryGetPort(this EndPoint endPoint, [NotNullWhen(true)] out int? port) { if (endPoint is DnsEndPoint dnsEndPoint) { port = dnsEndPoint.Port; return true; } else if (endPoint is IPEndPoint ipEndPoint) { port = ipEndPoint.Port; return true; } else { port = null; return false; } } /// <summary> /// Tries to get host from <paramref name="endPoint"/> which must be either <see cref="DnsEndPoint"/> or <see cref="IPEndPoint"/>. /// </summary> /// <returns><c>true</c> when host can be returned for <paramref name="endPoint"/>, <c>false</c> otherwise.</returns> public static bool TryGetHost(this EndPoint endPoint, [NotNullWhen(true)] out string? host) { if (endPoint is DnsEndPoint dnsEndPoint) { host = dnsEndPoint.Host; return true; } else if (endPoint is IPEndPoint ipEndPoint) { host = ipEndPoint.Address.ToString(); return true; } else { host = null; return false; } } /// <summary> /// Tries to get host and port from <paramref name="endPoint"/> which must be either <see cref="DnsEndPoint"/> or <see cref="IPEndPoint"/>. /// </summary> /// <returns><c>true</c> when host and port can be returned for <paramref name="endPoint"/>, <c>false</c> otherwise.</returns> public static bool TryGetHostAndPort(this EndPoint endPoint, [NotNullWhen(true)] out string? host, [NotNullWhen(true)] out int? port) { if (endPoint is DnsEndPoint dnsEndPoint) { host = dnsEndPoint.Host; port = dnsEndPoint.Port; return true; } else if (endPoint is IPEndPoint ipEndPoint) { host = ipEndPoint.Address.ToString(); port = ipEndPoint.Port; return true; } else { host = null; port = null; return false; } } } }
mit
C#
34c7f6e764aa8880acfe228edbfde44a7ef3f861
Update to return null if XR isn't initialized
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/Providers/XRSDK/LoaderHelpers.cs
Assets/MRTK/Providers/XRSDK/LoaderHelpers.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if XR_MANAGEMENT_ENABLED using UnityEngine.XR.Management; #endif namespace Microsoft.MixedReality.Toolkit.XRSDK { public static class LoaderHelpers { /// <summary> /// Checks if the active loader has a specific name. Used in cases where the loader class is internal, like WindowsMRLoader. /// </summary> /// <param name="loaderName">The string name to compare against the active loader.</param> /// <returns>True if the active loader has the same name as the parameter. Null if there isn't an active loader.</returns> public static bool? IsLoaderActive(string loaderName) { #if XR_MANAGEMENT_ENABLED if (XRGeneralSettings.Instance != null && XRGeneralSettings.Instance.Manager != null && XRGeneralSettings.Instance.Manager.activeLoader != null) { return XRGeneralSettings.Instance.Manager.activeLoader.name == loaderName; } return null; #else return false; #endif } #if XR_MANAGEMENT_ENABLED /// <summary> /// Checks if the active loader is of a specific type. Used in cases where the loader class is accessible, like OculusLoader. /// </summary> /// <typeparam name="T">The loader class type to check against the active loader.</typeparam> /// <returns>True if the active loader is of the specified type. Null if there isn't an active loader.</returns> public static bool? IsLoaderActive<T>() where T : XRLoader { if (XRGeneralSettings.Instance != null && XRGeneralSettings.Instance.Manager != null && XRGeneralSettings.Instance.Manager.activeLoader != null) { return XRGeneralSettings.Instance.Manager.activeLoader is T; } return null; } #endif } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if XR_MANAGEMENT_ENABLED using UnityEngine.XR.Management; #endif namespace Microsoft.MixedReality.Toolkit.XRSDK { public static class LoaderHelpers { /// <summary> /// Checks if the active loader has a specific name. Used in cases where the loader class is internal, like WindowsMRLoader. /// </summary> /// <param name="loaderName">The string name to compare against the active loader.</param> /// <returns>True if the active loader has the same name as the parameter.</returns> public static bool IsLoaderActive(string loaderName) => #if XR_MANAGEMENT_ENABLED XRGeneralSettings.Instance != null && XRGeneralSettings.Instance.Manager != null && XRGeneralSettings.Instance.Manager.activeLoader != null && XRGeneralSettings.Instance.Manager.activeLoader.name == loaderName; #else false; #endif #if XR_MANAGEMENT_ENABLED /// <summary> /// Checks if the active loader is of a specific type. Used in cases where the loader class is accessible, like OculusLoader. /// </summary> /// <typeparam name="T">The loader class type to check against the active loader.</typeparam> /// <returns>True if the active loader is of the specified type.</returns> public static bool IsLoaderActive<T>() where T : XRLoader => XRGeneralSettings.Instance != null && XRGeneralSettings.Instance.Manager != null && XRGeneralSettings.Instance.Manager.activeLoader is T; #endif } }
mit
C#
b3f537b82fe92f3008ca07944763b1a04e66fe52
Refactor PlayerMovement
setchi/kagaribi,setchi/kagaribi
Assets/Scripts/Main/Player/PlayerMovement.cs
Assets/Scripts/Main/Player/PlayerMovement.cs
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using UniRx; using UniRx.Triggers; public class PlayerMovement : MonoBehaviour { [SerializeField] GameObject operationTarget; [SerializeField] float moveSpeed = 1; void Awake() { var touchDownStream = this.UpdateAsObservable() .Where(_ => Input.GetMouseButtonDown(0)) .Select(_ => Input.mousePosition); this.UpdateAsObservable() .SkipUntil(touchDownStream) .TakeWhile(_ => !Input.GetMouseButtonUp(0)) .RepeatSafe() .CombineLatest(touchDownStream, (_, startPos) => startPos) .Subscribe(startPos => Move(Input.mousePosition - startPos)); } void Move(Vector3 velocity) { velocity /= Screen.width * 1.5f; float x = Mathf.Clamp(velocity.x, -1f, 1f); float y = Mathf.Clamp(velocity.y, -1f, 1f); operationTarget.transform.Translate( x * moveSpeed, y * moveSpeed, 0 ); } }
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using UniRx; using UniRx.Triggers; public class PlayerMovement : MonoBehaviour { [SerializeField] GameObject operationTarget; [SerializeField] float moveSpeed = 1; void Awake() { var touchDownStream = this.UpdateAsObservable() .Where(_ => Input.GetMouseButtonDown(0)) .Select(_ => Input.mousePosition); var swipeStream = this.UpdateAsObservable() .SkipUntil(touchDownStream) .TakeWhile(_ => !Input.GetMouseButtonUp(0)) .RepeatSafe(); swipeStream.CombineLatest(touchDownStream, (_, startPos) => startPos) .Select(startPos => Input.mousePosition - startPos) .Subscribe(Move); } void Move(Vector3 velocity) { velocity /= Screen.width * 1.5f; float x = Mathf.Clamp(velocity.x, -1f, 1f); float y = Mathf.Clamp(velocity.y, -1f, 1f); operationTarget.transform.Translate( x * moveSpeed, y * moveSpeed, 0 ); } }
mit
C#
97430790869d926c787eafb93f08763fb5c94a68
Make the text areas bigger on suta edit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Views/SUTA/Edit.cshtml
Battery-Commander.Web/Views/SUTA/Edit.cshtml
@model BatteryCommander.Web.Commands.UpdateSUTARequest @using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Supervisor) @Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.StartDate) @Html.EditorFor(model => model.Body.StartDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.EndDate) @Html.EditorFor(model => model.Body.EndDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Reasoning) @Html.TextAreaFor(model => model.Body.Reasoning, new { cols="40", rows="5" }) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.MitigationPlan) @Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols="40", rows="5" }) </div> <button type="submit">Save</button> }
@model BatteryCommander.Web.Commands.UpdateSUTARequest @using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Supervisor) @Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.StartDate) @Html.EditorFor(model => model.Body.StartDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.EndDate) @Html.EditorFor(model => model.Body.EndDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Reasoning) @Html.TextAreaFor(model => model.Body.Reasoning) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.MitigationPlan) @Html.TextAreaFor(model => model.Body.MitigationPlan) </div> <button type="submit">Save</button> }
mit
C#
ee2b341660e33e9cee439199b0cb027f6fba057a
Fix a different error on unit create
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/Reports/Stat.cs
Battery-Commander.Web/Models/Reports/Stat.cs
using System; using System.ComponentModel.DataAnnotations; using static BatteryCommander.Web.Models.Soldier; namespace BatteryCommander.Web.Models.Reports { public class Stat { public int Assigned { get; set; } public int Passed { get; set; } public int Failed { get; set; } [Display(Name = "Not Tested")] public int NotTested { get; set; } [Display(Name = "Pass %"), DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)] public Decimal PercentPass => (Assigned > 0 ? (Decimal)Passed / Assigned : Decimal.Zero; } public class Row { public Rank Rank { get; set; } public int Assigned { get; set; } public int Incomplete => Assigned - Completed; public int Completed { get; set; } [DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)] public Decimal Percentage => Assigned > 0 ? (Decimal)Completed / Assigned : Decimal.Zero; } }
using System; using System.ComponentModel.DataAnnotations; using static BatteryCommander.Web.Models.Soldier; namespace BatteryCommander.Web.Models.Reports { public class Stat { public int Assigned { get; set; } public int Passed { get; set; } public int Failed { get; set; } [Display(Name = "Not Tested")] public int NotTested { get; set; } [Display(Name = "Pass %"), DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)] public Decimal PercentPass => (Decimal)Passed / Assigned; } public class Row { public Rank Rank { get; set; } public int Assigned { get; set; } public int Incomplete => Assigned - Completed; public int Completed { get; set; } [DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)] public Decimal Percentage => Assigned > 0 ? (Decimal)Completed / Assigned : Decimal.Zero; } }
mit
C#
1bfe44523e7de11475e7be53abe7d0bf9fbf51ca
Add test
sakapon/KLibrary-Labs
CoreLab/UnitTest/Linq/RecursiveHelperTest.cs
CoreLab/UnitTest/Linq/RecursiveHelperTest.cs
using System; using System.IO; using System.Linq; using KLibrary.Labs; using KLibrary.Labs.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest.Linq { [TestClass] public class RecursiveHelperTest { [TestMethod] public void EnumerateRecursively_Seq() { var actual = 1 .EnumerateRecursively(i => i + 2) .TakeWhile(i => i < 10) .ToArray(); var expected = new[] { 1, 3, 5, 7, 9 }; CollectionAssert.AreEqual(expected, actual); } [TestMethod] public void EnumerateRecursively_Parents() { var query = Environment.CurrentDirectory .EnumerateRecursively(p => { var di = Directory.GetParent(p); return di != null ? di.FullName : null; }) .TakeWhile(p => p != null); foreach (var path in query) { Console.WriteLine(path); } } [TestMethod] public void EnumerateRecursively_Children() { var query = Path.GetFullPath(@"..\..\") .EnumerateRecursively(p => Directory.EnumerateDirectories(p)); foreach (var path in query) { Console.WriteLine(path); } } [TestMethod] public void EnumerateRecursively_Children2() { var query = new { Index = 0, Path = Path.GetFullPath(@"..\..\") } .EnumerateRecursively(_ => Directory.EnumerateDirectories(_.Path) .Select(p => new { Index = _.Index + 1, Path = p })); foreach (var item in query) { Console.WriteLine("{0}: {1}", item.Index, item.Path); } } } }
using System; using System.IO; using System.Linq; using KLibrary.Labs; using KLibrary.Labs.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest.Linq { [TestClass] public class RecursiveHelperTest { [TestMethod] public void EnumerateRecursively_Seq() { var actual = 1 .EnumerateRecursively(i => i + 2) .TakeWhile(i => i < 10) .ToArray(); var expected = new[] { 1, 3, 5, 7, 9 }; CollectionAssert.AreEqual(expected, actual); } [TestMethod] public void EnumerateRecursively_Parents() { var query = Environment.CurrentDirectory .EnumerateRecursively(p => { var di = Directory.GetParent(p); return di != null ? di.FullName : null; }) .TakeWhile(p => p != null); foreach (var path in query) { Console.WriteLine(path); } } [TestMethod] public void EnumerateRecursively_Children() { var query = Path.GetFullPath(@"..\..\") .EnumerateRecursively(p => Directory.EnumerateDirectories(p)); foreach (var path in query) { Console.WriteLine(path); } } } }
mit
C#
7e83be56b8d4dd5f7f758aae3e92a4146a9203fb
Add ClosingBehavior.
cube-soft/Cube.Core,cube-soft/Cube.Core
Libraries/Sources/Behaviors/CloseBehavior.cs
Libraries/Sources/Behaviors/CloseBehavior.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.ComponentModel; using System.Windows; namespace Cube.Xui.Behaviors { #region CloseBehavior /* --------------------------------------------------------------------- */ /// /// CloseBehavior /// /// <summary> /// Window を閉じる Behavior です。 /// </summary> /// /* --------------------------------------------------------------------- */ public class CloseBehavior : MessengerBehavior<CloseMessage> { #region Implementations /* ----------------------------------------------------------------- */ /// /// Invoke /// /// <summary> /// 処理を実行します。 /// </summary> /// /* ----------------------------------------------------------------- */ protected override void Invoke(CloseMessage e) { if (AssociatedObject is Window w) w.Close(); } #endregion } #endregion #region ClosingBehavior /* --------------------------------------------------------------------- */ /// /// ClosingBehavior /// /// <summary> /// Represents the behavior when the Closing event is fired. /// </summary> /// /* --------------------------------------------------------------------- */ public class ClosingBehavior : CommandBehavior<Window> { #region Implementations /* ----------------------------------------------------------------- */ /// /// OnAttached /// /// <summary> /// Occurs when the instance is attached to the Window. /// </summary> /// /* ----------------------------------------------------------------- */ protected override void OnAttached() { base.OnAttached(); AssociatedObject.Closing -= WhenClosing; AssociatedObject.Closing += WhenClosing; } /* ----------------------------------------------------------------- */ /// /// OnDetaching /// /// <summary> /// Occurs when the instance is detaching from the Window. /// </summary> /// /* ----------------------------------------------------------------- */ protected override void OnDetaching() { AssociatedObject.Closing -= WhenClosing; base.OnDetaching(); } /* ----------------------------------------------------------------- */ /// /// WhenClosing /// /// <summary> /// Occurs when the Closing event is fired. /// </summary> /// /* ----------------------------------------------------------------- */ private void WhenClosing(object sender, CancelEventArgs e) { if (Command?.CanExecute(e) ?? false) Command.Execute(e); } #endregion } #endregion }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Windows; namespace Cube.Xui.Behaviors { /* --------------------------------------------------------------------- */ /// /// CloseBehavior /// /// <summary> /// Window を閉じる Behavior です。 /// </summary> /// /* --------------------------------------------------------------------- */ public class CloseBehavior : MessengerBehavior<CloseMessage> { #region Implementations /* ----------------------------------------------------------------- */ /// /// Invoke /// /// <summary> /// 処理を実行します。 /// </summary> /// /* ----------------------------------------------------------------- */ protected override void Invoke(CloseMessage e) { if (AssociatedObject is Window w) w.Close(); } #endregion } }
apache-2.0
C#
0e25b14858db3a9d347bef440712fedfce9004cb
Make repositoryContent readonly
fffej/octokit.net,rlugojr/octokit.net,gdziadkiewicz/octokit.net,cH40z-Lord/octokit.net,ChrisMissal/octokit.net,gdziadkiewicz/octokit.net,shiftkey/octokit.net,octokit-net-test-org/octokit.net,dampir/octokit.net,naveensrinivasan/octokit.net,forki/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,hahmed/octokit.net,thedillonb/octokit.net,nsrnnnnn/octokit.net,daukantas/octokit.net,hahmed/octokit.net,ivandrofly/octokit.net,michaKFromParis/octokit.net,editor-tools/octokit.net,kdolan/octokit.net,gabrielweyer/octokit.net,TattsGroup/octokit.net,M-Zuber/octokit.net,mminns/octokit.net,TattsGroup/octokit.net,Sarmad93/octokit.net,octokit/octokit.net,chunkychode/octokit.net,magoswiat/octokit.net,gabrielweyer/octokit.net,devkhan/octokit.net,shana/octokit.net,ivandrofly/octokit.net,alfhenrik/octokit.net,bslliw/octokit.net,SmithAndr/octokit.net,takumikub/octokit.net,nsnnnnrn/octokit.net,khellang/octokit.net,eriawan/octokit.net,khellang/octokit.net,alfhenrik/octokit.net,SmithAndr/octokit.net,Sarmad93/octokit.net,shiftkey/octokit.net,SamTheDev/octokit.net,devkhan/octokit.net,kolbasov/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,chunkychode/octokit.net,octokit-net-test/octokit.net,eriawan/octokit.net,Red-Folder/octokit.net,adamralph/octokit.net,editor-tools/octokit.net,shiftkey-tester/octokit.net,SLdragon1989/octokit.net,brramos/octokit.net,fake-organization/octokit.net,mminns/octokit.net,SamTheDev/octokit.net,hitesh97/octokit.net,octokit-net-test-org/octokit.net,geek0r/octokit.net,shana/octokit.net,thedillonb/octokit.net,rlugojr/octokit.net,darrelmiller/octokit.net,dlsteuer/octokit.net,octokit/octokit.net,M-Zuber/octokit.net,dampir/octokit.net,shiftkey-tester/octokit.net
Octokit/Models/Response/RepositoryContent.cs
Octokit/Models/Response/RepositoryContent.cs
using System; using System.Diagnostics; using Octokit.Internal; namespace Octokit { /// <summary> /// Represents a piece of content in the repository. This could be a submodule, a symlink, a directory, or a file. /// Look at the Type property to figure out which one it is. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RepositoryContent : RepositoryContentInfo { /// <summary> /// The encoding of the content if this is a file. Typically "base64". Otherwise it's null. /// </summary> public string Encoding { get; protected set; } /// <summary> /// The Base64 encoded content if this is a file. Otherwise it's null. /// </summary> [Parameter(Key = "content")] protected string EncodedContent { get; set; } /// <summary> /// The unencoded content. Only access this if the content is expected to be text and not binary content. /// </summary> public string Content { get { return EncodedContent != null ? EncodedContent.FromBase64String() : null; } } /// <summary> /// Path to the target file in the repository if this is a symlink. Otherwise it's null. /// </summary> public string Target { get; protected set; } /// <summary> /// The location of the submodule repository if this is a submodule. Otherwise it's null. /// </summary> public Uri SubmoduleGitUrl { get; protected set; } } }
using System; using System.Diagnostics; using Octokit.Internal; namespace Octokit { /// <summary> /// Represents a piece of content in the repository. This could be a submodule, a symlink, a directory, or a file. /// Look at the Type property to figure out which one it is. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RepositoryContent : RepositoryContentInfo { /// <summary> /// The encoding of the content if this is a file. Typically "base64". Otherwise it's null. /// </summary> public string Encoding { get; set; } /// <summary> /// The Base64 encoded content if this is a file. Otherwise it's null. /// </summary> [Parameter(Key = "content")] protected string EncodedContent { get; set; } /// <summary> /// The unencoded content. Only access this if the content is expected to be text and not binary content. /// </summary> public string Content { get { return EncodedContent != null ? EncodedContent.FromBase64String() : null; } } /// <summary> /// Path to the target file in the repository if this is a symlink. Otherwise it's null. /// </summary> public string Target { get; set; } /// <summary> /// The location of the submodule repository if this is a submodule. Otherwise it's null. /// </summary> public Uri SubmoduleGitUrl { get; set; } } }
mit
C#
1029efae792508c8722ba65354eabf68f9c16c3c
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.TrustedDocuments/ValuesOut.cs
RegistryPlugin.TrustedDocuments/ValuesOut.cs
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.TrustedDocuments { public class ValuesOut:IValueOut { public ValuesOut(string valueName, DateTimeOffset tstamp, string fileName,string username) { EventType = valueName; Timestamp = tstamp; FileName = fileName; Username = username; } public string EventType { get; } public DateTimeOffset Timestamp { get; } public string FileName { get; } public string Username { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"File Name: {FileName}"; public string BatchValueData2 => $"File Opened: {Timestamp}"; public string BatchValueData3 => $"Event Type: {EventType}"; } }
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.TrustedDocuments { public class ValuesOut:IValueOut { public ValuesOut(string valueName, DateTimeOffset tstamp, string fileName,string username) { EventType = valueName; Timestamp = tstamp; FileName = fileName; Username = username; } public string EventType { get; } public DateTimeOffset Timestamp { get; } public string FileName { get; } public string Username { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"File Name: {FileName}"; public string BatchValueData2 => $"File Opened: {Timestamp})"; public string BatchValueData3 => $"Event Type: {EventType})"; } }
mit
C#
b0896c45a661e05f224dfab580839564827eea3a
Add missing NotNull annotation
ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework
osu.Framework/Graphics/Containers/GridContainerContent.cs
osu.Framework/Graphics/Containers/GridContainerContent.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 JetBrains.Annotations; using osu.Framework.Lists; namespace osu.Framework.Graphics.Containers { /// <summary> /// A wrapper that provides access to the <see cref="GridContainer.Content"/> with element change notifications. /// </summary> public class GridContainerContent : ObservableArray<ObservableArray<Drawable>> { private readonly Drawable[][] source; public static implicit operator GridContainerContent(Drawable[][] drawables) { if (drawables == null) return null; return new GridContainerContent(drawables); } private GridContainerContent([NotNull] Drawable[][] drawables) : base(new ObservableArray<Drawable>[drawables.Length]) { source = drawables; for (int i = 0; i < drawables.Length; i++) { if (drawables[i] != null) { var observableArray = new ObservableArray<Drawable>(drawables[i]); this[i] = observableArray; observableArray.ArrayElementChanged += OnArrayElementChanged; } } } } }
// 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.Lists; namespace osu.Framework.Graphics.Containers { /// <summary> /// A wrapper that provides access to the <see cref="GridContainer.Content"/> with element change notifications. /// </summary> public class GridContainerContent : ObservableArray<ObservableArray<Drawable>> { private readonly Drawable[][] source; public static implicit operator GridContainerContent(Drawable[][] drawables) { if (drawables == null) return null; return new GridContainerContent(drawables); } private GridContainerContent(Drawable[][] drawables) : base(new ObservableArray<Drawable>[drawables.Length]) { source = drawables; for (int i = 0; i < drawables.Length; i++) { if (drawables[i] != null) { var observableArray = new ObservableArray<Drawable>(drawables[i]); this[i] = observableArray; observableArray.ArrayElementChanged += OnArrayElementChanged; } } } } }
mit
C#
460edc4cd9718d7796fd4addf9060be04c764363
maintain selected items between each showing of dialog
mgj/MvvmCross-Plugins,mgj/MvvmCross-Plugins
Playground.Core/ViewModels/FirstViewModel.cs
Playground.Core/ViewModels/FirstViewModel.cs
using artm.MvxPlugins.Dialog.Services; using MvvmCross.Core.ViewModels; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Playground.Core.ViewModels { public class FirstViewModel : MvxViewModel { private readonly string[] _allItems = new string[] { "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "c" }; private List<bool> _checkedItems = new List<bool>(); public FirstViewModel(IDialogService dialog) { _dialog = dialog; InitializeCheckedItems(); } private void InitializeCheckedItems() { var random = new Random(); foreach (var item in _allItems) { var rand = random.Next(0, 2); if (rand == 1) { _checkedItems.Add(true); } else { _checkedItems.Add(false); } } } private MvxAsyncCommand _showListCommand; public MvxAsyncCommand ShowListCommand { get { _showListCommand = _showListCommand ?? new MvxAsyncCommand(DoShowListCommandAsync); return _showListCommand; } } private async Task DoShowListCommandAsync() { var result = await _dialog.ShowMultipleChoice(_allItems, _checkedItems.ToArray()); for (int i = 0; i < _checkedItems.Count; i++) { _checkedItems[i] = false; } foreach (var index in result) { _checkedItems[index] = true; } } private string _hello = "Hello MvvmCross"; private readonly IDialogService _dialog; public string Hello { get { return _hello; } set { SetProperty (ref _hello, value); } } } }
using artm.MvxPlugins.Dialog.Services; using MvvmCross.Core.ViewModels; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Playground.Core.ViewModels { public class FirstViewModel : MvxViewModel { public FirstViewModel(IDialogService dialog) { _dialog = dialog; } private MvxAsyncCommand _showListCommand; public MvxAsyncCommand ShowListCommand { get { _showListCommand = _showListCommand ?? new MvxAsyncCommand(DoShowListCommandAsync); return _showListCommand; } } private async Task DoShowListCommandAsync() { var items = new string[]{ "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "c" }; var checkedItems = new List<bool>(); var random = new Random(); foreach (var item in items) { var rand = random.Next(0, 2); if (rand == 1) { checkedItems.Add(true); } else { checkedItems.Add(false); } } var result = await _dialog.ShowMultipleChoice(items, checkedItems.ToArray()); } private string _hello = "Hello MvvmCross"; private readonly IDialogService _dialog; public string Hello { get { return _hello; } set { SetProperty (ref _hello, value); } } } }
apache-2.0
C#
77a1a260a16bca38d8e1c066b7b3978a9f3af234
Fix the server list update
DragonEyes7/ConcoursUBI17,DragonEyes7/ConcoursUBI17
Proto/Assets/Scripts/UI/OnActivateRefresh.cs
Proto/Assets/Scripts/UI/OnActivateRefresh.cs
using UnityEngine; public class OnActivateRefresh : MonoBehaviour { private ServerUI _serverUi; private void Start() { _serverUi = FindObjectOfType<ServerUI>(); _serverUi.GetServerList(); } private void OnEnable() { if(_serverUi)_serverUi.GetServerList(); } }
using UnityEngine; public class OnActivateRefresh : MonoBehaviour { private ServerUI _serverUi; private void Start() { _serverUi = FindObjectOfType<ServerUI>(); } private void OnEnable() { _serverUi.GetServerList(); } }
mit
C#
6a9b4035055323c92e6c8dde0327fb96208184e3
make BackupFolder class public
Willster419/RelhaxModpack,Willster419/RelhaxModpack,Willster419/RelicModManager
RelicModManager/UIComponents/BackupFolder.cs
RelicModManager/UIComponents/BackupFolder.cs
using System; using System.Collections.Generic; namespace RelhaxModpack { public class BackupFolder { public string TopfolderName { get; set; } = ""; public List<string> FullnameList { get; set; } public UInt64 FilesSize { get; set; } = 0; public UInt64 FilesSizeOnDisk { get; set; } = 0; public uint FileCount { get; set; } = 0; public uint FolderCount { get; set; } = 0; } }
using System; using System.Collections.Generic; namespace RelhaxModpack { class BackupFolder { public string TopfolderName { get; set; } = ""; public List<string> FullnameList { get; set; } public UInt64 FilesSize { get; set; } = 0; public UInt64 FilesSizeOnDisk { get; set; } = 0; public uint FileCount { get; set; } = 0; public uint FolderCount { get; set; } = 0; } }
apache-2.0
C#
c5f6606818a6ea2bfe7f4afa211cdfe7a228f77e
Update EmailService.cs
Branimir123/FMI-IoT-Teamwork,Branimir123/FMI-IoT-Teamwork
SmartHive/SmartHive.Services/EmailService.cs
SmartHive/SmartHive.Services/EmailService.cs
using System.Net.Mail; using System.Text; using System.Net; using System.Threading.Tasks; using SmartHive.Services.Contracts; namespace SmartHive.Services { public class EmailService : IEmailService { private readonly string companyEmail = "smarthivebg@gmail.com"; private readonly string password = "123456smart"; public async Task SendAsync(string sendTo, string subject, string body) { string smtpAddress = "smtp.gmail.com"; int portNumber = 587; MailMessage mail = new MailMessage(); mail.From = new MailAddress(companyEmail); mail.To.Add(sendTo); mail.Subject = subject; mail.Body = body; mail.BodyEncoding = UTF8Encoding.UTF8; using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber)) { smtp.Credentials = new NetworkCredential(companyEmail, password); smtp.EnableSsl = true; await smtp.SendMailAsync(mail); } } } }
using System.Net.Mail; using System.Text; using System.Net; using System.Threading.Tasks; namespace SmartHive.Services { public class EmailService : IEmailService { private readonly string companyEmail = "smarthivebg@gmail.com"; private readonly string password = "123456smart"; public async Task SendAsync(string sendTo, string subject, string body) { string smtpAddress = "smtp.gmail.com"; int portNumber = 587; MailMessage mail = new MailMessage(); mail.From = new MailAddress(companyEmail); mail.To.Add(sendTo); mail.Subject = subject; mail.Body = body; mail.BodyEncoding = UTF8Encoding.UTF8; using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber)) { smtp.Credentials = new NetworkCredential(companyEmail, password); smtp.EnableSsl = true; await smtp.SendMailAsync(mail); } } } }
mit
C#
ffddacdf838c86b61f5b1c91f942fdcfd403ab88
update connection strings for deprecation
agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov
WebAPI.Search.Soe/Properties/AssemblyInfo.cs
WebAPI.Search.Soe/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using ESRI.ArcGIS.SOESupport; // 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("WebAPI.Search.Soe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebAPI.Search.Soe")] [assembly: AssemblyCopyright("Copyright ©2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("D837482C-8E72-45A0-9CD3-D49F517533D3")] [assembly: AssemblyVersion("1.6.3.0")] [assembly: AssemblyFileVersion("1.6.3.0")] [assembly: AddInPackage("WebAPI.Search.Soe", "021ED22C-4D23-4A84-9CC3-A16D24BA1D5E", Author = "@steveoh", Company = "agrc", Date = "12/10/2012 5:56:42 PM", Description = "assembly info description", TargetProduct = "Server", TargetVersion = "10.8", Version = "1.0")]
using System.Reflection; using System.Runtime.InteropServices; using ESRI.ArcGIS.SOESupport; // 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("WebAPI.Search.Soe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebAPI.Search.Soe")] [assembly: AssemblyCopyright("Copyright ©2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("D837482C-8E72-45A0-9CD3-D49F517533D3")] [assembly: AssemblyVersion("1.6.2.0")] [assembly: AssemblyFileVersion("1.6.2.0")] [assembly: AddInPackage("WebAPI.Search.Soe", "021ED22C-4D23-4A84-9CC3-A16D24BA1D5E", Author = "@steveoh", Company = "agrc", Date = "12/10/2012 5:56:42 PM", Description = "assembly info description", TargetProduct = "Server", TargetVersion = "10.8", Version = "1.0")]
mit
C#
8313949904d684663aa728ae0a9c47d05f87f7e4
stop walking animation on dialoque start
Hyunkell/LD32
Assets/StartDialog.cs
Assets/StartDialog.cs
using UnityEngine; using System.Collections; public class StartDialog : MonoBehaviour { void OnTriggerEnter2D(Collider2D other){ var gameObject = other.gameObject; gameObject.GetComponent<Movement> ().enabled = false; gameObject.GetComponentInChildren<Animator>().Play("MainCharacterIdle"); var dialogue = GetComponent<Dialogue>(); if (dialogue != null) { dialogue.BeginDialogue(); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using UnityEngine; using System.Collections; public class StartDialog : MonoBehaviour { void OnTriggerEnter2D(Collider2D other){ var gameObject = other.gameObject; gameObject.GetComponent<Movement> ().enabled = false; var dialogue = GetComponent<Dialogue>(); dialogue.BeginDialogue(); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
mit
C#
2227b054732e410b179450f407d1d6e14d81ecd8
swap public ip address with internal public ip
ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell
src/ResourceManager/Network/Commands.Network/AzureFirewall/SetAzureFirewallCommand.cs
src/ResourceManager/Network/Commands.Network/AzureFirewall/SetAzureFirewallCommand.cs
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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.Management.Automation; using Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Network; using MNM = Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.Set, "AzureRmFirewall", SupportsShouldProcess = true), OutputType(typeof(PSAzureFirewall))] public class SetAzureFirewallCommand : AzureFirewallBaseCmdlet { [Parameter( Mandatory = true, ValueFromPipeline = true, HelpMessage = "The AzureFirewall")] public PSAzureFirewall AzureFirewall { get; set; } public override void Execute() { base.Execute(); if (!this.IsAzureFirewallPresent(this.AzureFirewall.ResourceGroupName, this.AzureFirewall.Name)) { throw new ArgumentException(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound); } if (this.AzureFirewall.IpConfigurations.Count != 1) { throw new ArgumentException(string.Format("There must be exactly one IP configuration associated with the Azure Firewall, found {0}.", this.AzureFirewall.IpConfigurations.Count)); } if (this.AzureFirewall.IpConfigurations[0].PublicIpAddress == null) { throw new ArgumentException("The Azure Firewall IP configuration Public IP Address must be populated."); } this.AzureFirewall.IpConfigurations[0].InternalPublicIpAddress = this.AzureFirewall.IpConfigurations[0].PublicIpAddress; this.AzureFirewall.IpConfigurations[0].PublicIpAddress = null; // Map to the sdk object var secureGwModel = NetworkResourceManagerProfile.Mapper.Map<MNM.AzureFirewall>(this.AzureFirewall); secureGwModel.Tags = TagsConversionHelper.CreateTagDictionary(this.AzureFirewall.Tag, validate: true); // Execute the PUT AzureFirewall call this.AzureFirewallClient.CreateOrUpdate(this.AzureFirewall.ResourceGroupName, this.AzureFirewall.Name, secureGwModel); var getAzureFirewall = this.GetAzureFirewall(this.AzureFirewall.ResourceGroupName, this.AzureFirewall.Name); WriteObject(getAzureFirewall); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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.Management.Automation; using Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Network; using MNM = Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.Set, "AzureRmFirewall", SupportsShouldProcess = true), OutputType(typeof(PSAzureFirewall))] public class SetAzureFirewallCommand : AzureFirewallBaseCmdlet { [Parameter( Mandatory = true, ValueFromPipeline = true, HelpMessage = "The AzureFirewall")] public PSAzureFirewall AzureFirewall { get; set; } public override void Execute() { base.Execute(); if (!this.IsAzureFirewallPresent(this.AzureFirewall.ResourceGroupName, this.AzureFirewall.Name)) { throw new ArgumentException(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound); } // Map to the sdk object var secureGwModel = NetworkResourceManagerProfile.Mapper.Map<MNM.AzureFirewall>(this.AzureFirewall); secureGwModel.Tags = TagsConversionHelper.CreateTagDictionary(this.AzureFirewall.Tag, validate: true); // Execute the PUT AzureFirewall call this.AzureFirewallClient.CreateOrUpdate(this.AzureFirewall.ResourceGroupName, this.AzureFirewall.Name, secureGwModel); var getAzureFirewall = this.GetAzureFirewall(this.AzureFirewall.ResourceGroupName, this.AzureFirewall.Name); WriteObject(getAzureFirewall); } } }
apache-2.0
C#
f1a1757fd2b5665a153f4c847f9a5d5b5dc07f21
Fix test break
ErikEJ/EntityFramework7.SqlServerCompact,ErikEJ/EntityFramework.SqlServerCompact
test/EntityFramework.SqlServerCompact.FunctionalTests/FunkyDataQuerySqlCeFixture.cs
test/EntityFramework.SqlServerCompact.FunctionalTests/FunkyDataQuerySqlCeFixture.cs
using Microsoft.EntityFrameworkCore.Specification.Tests; using Microsoft.EntityFrameworkCore.Specification.Tests.TestModels.FunkyDataModel; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore.Specification.Tests.Utilities; namespace Microsoft.EntityFrameworkCore.SqlCe.FunctionalTests { public class FunkyDataQuerySqlCeFixture : FunkyDataQueryFixtureBase<SqlCeTestStore> { public const string DatabaseName = "FunkyDataQueryTest"; private readonly DbContextOptions _options; private readonly string _connectionString = SqlCeTestStore.CreateConnectionString(DatabaseName); public FunkyDataQuerySqlCeFixture() { var serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlCe() .AddSingleton(TestModelSource.GetFactory(OnModelCreating)) .AddSingleton<ILoggerFactory>(new TestSqlLoggerFactory()) .BuildServiceProvider(); _options = new DbContextOptionsBuilder() .EnableSensitiveDataLogging() .UseInternalServiceProvider(serviceProvider) .Options; } public override SqlCeTestStore CreateTestStore() { return SqlCeTestStore.GetOrCreateShared(DatabaseName, () => { var optionsBuilder = new DbContextOptionsBuilder() .UseSqlCe(_connectionString, b => b.ApplyConfiguration()); using (var context = new FunkyDataContext(optionsBuilder.Options)) { context.Database.EnsureClean(); FunkyDataModelInitializer.Seed(context); TestSqlLoggerFactory.Reset(); } }); } public override FunkyDataContext CreateContext(SqlCeTestStore testStore) { var options = new DbContextOptionsBuilder(_options) .UseSqlCe(testStore.Connection, b => b.ApplyConfiguration()) .Options; var context = new FunkyDataContext(options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; context.Database.UseTransaction(testStore.Transaction); return context; } } }
using System; using Microsoft.EntityFrameworkCore.Specification.Tests; using Microsoft.EntityFrameworkCore.Specification.Tests.TestModels.FunkyDataModel; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Microsoft.EntityFrameworkCore.SqlCe.FunctionalTests { public class FunkyDataQuerySqlCeFixture : FunkyDataQueryFixtureBase<SqlCeTestStore> { public const string DatabaseName = "FunkyDataQueryTest"; private readonly IServiceProvider _serviceProvider; private readonly string _connectionString = SqlCeTestStore.CreateConnectionString(DatabaseName); public FunkyDataQuerySqlCeFixture() { _serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlCe() .AddSingleton(TestModelSource.GetFactory(OnModelCreating)) .AddSingleton<ILoggerFactory>(new TestSqlLoggerFactory()) .BuildServiceProvider(); } public override SqlCeTestStore CreateTestStore() { return SqlCeTestStore.GetOrCreateShared(DatabaseName, () => { var optionsBuilder = new DbContextOptionsBuilder() .UseSqlCe(_connectionString) .UseInternalServiceProvider(_serviceProvider); using (var context = new FunkyDataContext(optionsBuilder.Options)) { context.Database.EnsureClean(); FunkyDataModelInitializer.Seed(context); TestSqlLoggerFactory.Reset(); } }); } public override FunkyDataContext CreateContext(SqlCeTestStore testStore) { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder .EnableSensitiveDataLogging() .UseInternalServiceProvider(_serviceProvider) .UseSqlCe(testStore.Connection); var context = new FunkyDataContext(optionsBuilder.Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; context.Database.UseTransaction(testStore.Transaction); return context; } } }
apache-2.0
C#
706a73911294613836b52ce0dd3a07309d060cda
Add context menu to select the script of a scriptable object
bitcake/bitstrap
Assets/BitStrap/Plugins/Inspector/Editor/ContextMenus/ScriptableObjectContextMenu.cs
Assets/BitStrap/Plugins/Inspector/Editor/ContextMenus/ScriptableObjectContextMenu.cs
using UnityEditor; using UnityEngine; namespace BitStrap { public class ScriptableObjectContextMenu { [MenuItem("CONTEXT/ScriptableObject/Select Script", false, 10)] public static void SelectScriptabelObjectScript(MenuCommand menuCommand) { var serializedObject = new SerializedObject(menuCommand.context); var scriptProperty = serializedObject.FindProperty("m_Script"); var scriptObject = scriptProperty.objectReferenceValue; Selection.activeObject = scriptObject; } [MenuItem("CONTEXT/ScriptableObject/Show in Project View")] public static void SelectScriptabelObject(MenuCommand menuCommand) { EditorGUIUtility.PingObject(menuCommand.context); } } }
using UnityEditor; namespace BitStrap { public class ScriptableObjectContextMenu { [MenuItem("CONTEXT/ScriptableObject/Select in Project View")] public static void SelectScriptabelObject(MenuCommand menuCommand) { EditorGUIUtility.PingObject(menuCommand.context); } } }
mit
C#
b8f63e5b1a27ee63d60d9698b0b544c060d2eefb
Add None enum member to flags
json-api-dotnet/JsonApiDotNetCore
test/JsonApiDotNetCoreTests/IntegrationTests/ResourceDefinitionExtensibilityPoints.cs
test/JsonApiDotNetCoreTests/IntegrationTests/ResourceDefinitionExtensibilityPoints.cs
using System; using JsonApiDotNetCore.Resources; namespace JsonApiDotNetCoreTests.IntegrationTests { /// <summary> /// Lists the various extensibility points on <see cref="IResourceDefinition{TResource,TId}" />. /// </summary> [Flags] public enum ResourceDefinitionExtensibilityPoints { None = 0, OnApplyIncludes = 1, OnApplyFilter = 1 << 1, OnApplySort = 1 << 2, OnApplyPagination = 1 << 3, OnApplySparseFieldSet = 1 << 4, OnRegisterQueryableHandlersForQueryStringParameters = 1 << 5, GetMeta = 1 << 6, OnPrepareWriteAsync = 1 << 7, OnSetToOneRelationshipAsync = 1 << 8, OnSetToManyRelationshipAsync = 1 << 9, OnAddToRelationshipAsync = 1 << 10, OnRemoveFromRelationshipAsync = 1 << 11, OnWritingAsync = 1 << 12, OnWriteSucceededAsync = 1 << 13, OnDeserialize = 1 << 14, OnSerialize = 1 << 15, Reading = OnApplyIncludes | OnApplyFilter | OnApplySort | OnApplyPagination | OnApplySparseFieldSet | OnRegisterQueryableHandlersForQueryStringParameters | GetMeta, Writing = OnPrepareWriteAsync | OnSetToOneRelationshipAsync | OnSetToManyRelationshipAsync | OnAddToRelationshipAsync | OnRemoveFromRelationshipAsync | OnWritingAsync | OnWriteSucceededAsync, Serialization = OnDeserialize | OnSerialize, All = Reading | Writing | Serialization } }
using System; using JsonApiDotNetCore.Resources; namespace JsonApiDotNetCoreTests.IntegrationTests { /// <summary> /// Lists the various extensibility points on <see cref="IResourceDefinition{TResource,TId}" />. /// </summary> [Flags] public enum ResourceDefinitionExtensibilityPoints { OnApplyIncludes = 1, OnApplyFilter = 1 << 1, OnApplySort = 1 << 2, OnApplyPagination = 1 << 3, OnApplySparseFieldSet = 1 << 4, OnRegisterQueryableHandlersForQueryStringParameters = 1 << 5, GetMeta = 1 << 6, OnPrepareWriteAsync = 1 << 7, OnSetToOneRelationshipAsync = 1 << 8, OnSetToManyRelationshipAsync = 1 << 9, OnAddToRelationshipAsync = 1 << 10, OnRemoveFromRelationshipAsync = 1 << 11, OnWritingAsync = 1 << 12, OnWriteSucceededAsync = 1 << 13, OnDeserialize = 1 << 14, OnSerialize = 1 << 15, Reading = OnApplyIncludes | OnApplyFilter | OnApplySort | OnApplyPagination | OnApplySparseFieldSet | OnRegisterQueryableHandlersForQueryStringParameters | GetMeta, Writing = OnPrepareWriteAsync | OnSetToOneRelationshipAsync | OnSetToManyRelationshipAsync | OnAddToRelationshipAsync | OnRemoveFromRelationshipAsync | OnWritingAsync | OnWriteSucceededAsync, Serialization = OnDeserialize | OnSerialize, All = Reading | Writing | Serialization } }
mit
C#
26da01e8b3e9fda5dcf29ab5cd4cd1d49699ff91
Allow 'data-folder' and 'data-directory' config options
bizcad/LeanJJN,StefanoRaggi/Lean,bizcad/Lean,mabeale/Lean,dpavlenkov/Lean,QuantConnect/Lean,dpavlenkov/Lean,AnshulYADAV007/Lean,JKarathiya/Lean,AlexCatarino/Lean,QuantConnect/Lean,devalkeralia/Lean,dpavlenkov/Lean,tomhunter-gh/Lean,bizcad/Lean,Obawoba/Lean,kaffeebrauer/Lean,JKarathiya/Lean,squideyes/Lean,Obawoba/Lean,young-zhang/Lean,andrewhart098/Lean,AnObfuscator/Lean,Phoenix1271/Lean,FrancisGauthier/Lean,AnObfuscator/Lean,bizcad/LeanJJN,Phoenix1271/Lean,jameschch/Lean,bdilber/Lean,AlexCatarino/Lean,Phoenix1271/Lean,AnObfuscator/Lean,tomhunter-gh/Lean,StefanoRaggi/Lean,devalkeralia/Lean,andrewhart098/Lean,bizcad/LeanJJN,AlexCatarino/Lean,Obawoba/Lean,Mendelone/forex_trading,andrewhart098/Lean,Mendelone/forex_trading,bizcad/LeanJJN,kaffeebrauer/Lean,bdilber/Lean,Phoenix1271/Lean,young-zhang/Lean,jameschch/Lean,mabeale/Lean,FrancisGauthier/Lean,JKarathiya/Lean,redmeros/Lean,tomhunter-gh/Lean,bizcad/Lean,AnshulYADAV007/Lean,squideyes/Lean,AnshulYADAV007/Lean,redmeros/Lean,QuantConnect/Lean,bdilber/Lean,Jay-Jay-D/LeanSTP,andrewhart098/Lean,StefanoRaggi/Lean,StefanoRaggi/Lean,jameschch/Lean,FrancisGauthier/Lean,young-zhang/Lean,mabeale/Lean,Jay-Jay-D/LeanSTP,FrancisGauthier/Lean,kaffeebrauer/Lean,jameschch/Lean,kaffeebrauer/Lean,QuantConnect/Lean,Jay-Jay-D/LeanSTP,AnshulYADAV007/Lean,jameschch/Lean,kaffeebrauer/Lean,StefanoRaggi/Lean,bdilber/Lean,young-zhang/Lean,squideyes/Lean,Mendelone/forex_trading,squideyes/Lean,tomhunter-gh/Lean,redmeros/Lean,dpavlenkov/Lean,AlexCatarino/Lean,bizcad/Lean,devalkeralia/Lean,AnshulYADAV007/Lean,Jay-Jay-D/LeanSTP,mabeale/Lean,Mendelone/forex_trading,Jay-Jay-D/LeanSTP,Obawoba/Lean,JKarathiya/Lean,devalkeralia/Lean,AnObfuscator/Lean,redmeros/Lean
Common/Constants.cs
Common/Constants.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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 QuantConnect.Configuration; namespace QuantConnect { /// <summary> /// Provides application level constant values /// </summary> public static class Constants { private static readonly string DataFolderPath = Config.Get("data-folder", Config.Get("data-directory", @"../../../Data/")); /// <summary> /// The root directory of the data folder for this application /// </summary> public static string DataFolder { get { return DataFolderPath; } } /// <summary> /// The directory used for storing downloaded remote files /// </summary> public const string Cache = "./cache/data"; /// <summary> /// The version of lean /// </summary> public static readonly string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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 QuantConnect.Configuration; namespace QuantConnect { /// <summary> /// Provides application level constant values /// </summary> public static class Constants { private static readonly string DataFolderPath = Config.Get("data-folder", @"../../../Data/"); /// <summary> /// The root directory of the data folder for this application /// </summary> public static string DataFolder { get { return DataFolderPath; } } /// <summary> /// The directory used for storing downloaded remote files /// </summary> public const string Cache = "./cache/data"; /// <summary> /// The version of lean /// </summary> public static readonly string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); } }
apache-2.0
C#
28805c89c1383c0953d0b27f7143f519dbb8c72e
support line mapping in find usages
OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
src/OmniSharp.Roslyn.CSharp/Helpers/LocationExtensions.cs
src/OmniSharp.Roslyn.CSharp/Helpers/LocationExtensions.cs
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using OmniSharp.Models; namespace OmniSharp.Helpers { public static class LocationExtensions { public static QuickFix GetQuickFix(this Location location, OmniSharpWorkspace workspace) { if (!location.IsInSource) throw new Exception("Location is not in the source tree"); var lineSpan = location.GetMappedLineSpan(); var path = lineSpan.Path; var documents = workspace.GetDocuments(path); var line = lineSpan.StartLinePosition.Line; var text = location.SourceTree.GetText().Lines[line].ToString(); return new QuickFix { Text = text.Trim(), FileName = path, Line = line, Column = lineSpan.StartLinePosition.Character, EndLine = lineSpan.EndLinePosition.Line, EndColumn = lineSpan.EndLinePosition.Character, Projects = documents.Select(document => document.Project.Name).ToArray() }; } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using OmniSharp.Models; namespace OmniSharp.Helpers { public static class LocationExtensions { public static QuickFix GetQuickFix(this Location location, OmniSharpWorkspace workspace) { if (!location.IsInSource) throw new Exception("Location is not in the source tree"); var lineSpan = location.GetLineSpan(); var path = lineSpan.Path; var documents = workspace.GetDocuments(path); var line = lineSpan.StartLinePosition.Line; var text = location.SourceTree.GetText().Lines[line].ToString(); return new QuickFix { Text = text.Trim(), FileName = path, Line = line, Column = lineSpan.StartLinePosition.Character, EndLine = lineSpan.EndLinePosition.Line, EndColumn = lineSpan.EndLinePosition.Character, Projects = documents.Select(document => document.Project.Name).ToArray() }; } } }
mit
C#
84dbd0882a0428e8bac5cd9b2f607c027617d07c
Add a null check.
KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog
src/StructuredLogViewer/SourceFiles/SourceFileResolver.cs
src/StructuredLogViewer/SourceFiles/SourceFileResolver.cs
using System.Collections.Generic; namespace StructuredLogViewer { public class SourceFileResolver : ISourceFileResolver { private readonly IEnumerable<ISourceFileResolver> resolvers = new[] { new LocalSourceFileResolver() }; public string GetSourceFileText(string filePath) { if (filePath == null) { return null; } foreach (var resolver in resolvers) { var candidate = resolver.GetSourceFileText(filePath); if (candidate != null) { return candidate; } } return null; } } }
using System.Collections.Generic; namespace StructuredLogViewer { public class SourceFileResolver : ISourceFileResolver { private readonly IEnumerable<ISourceFileResolver> resolvers = new[] { new LocalSourceFileResolver() }; public string GetSourceFileText(string filePath) { foreach (var resolver in resolvers) { var candidate = resolver.GetSourceFileText(filePath); if (candidate != null) { return candidate; } } return null; } } }
mit
C#
df9de7a8ddee1986df712deb138c7d4238f41bed
Remove null check that is not required anymore
UselessToucan/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,smoogipooo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu
osu.Game.Rulesets.Catch/Skinning/Default/CatchHitObjectPiece.cs
osu.Game.Rulesets.Catch/Skinning/Default/CatchHitObjectPiece.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; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Catch.Objects.Drawables; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.Skinning.Default { public abstract class CatchHitObjectPiece : CompositeDrawable { public readonly Bindable<Color4> AccentColour = new Bindable<Color4>(); public readonly Bindable<bool> HyperDash = new Bindable<bool>(); [Resolved] protected IHasCatchObjectState ObjectState { get; private set; } /// <summary> /// A part of this piece that will be faded out while falling in the playfield. /// </summary> [CanBeNull] protected virtual BorderPiece BorderPiece => null; /// <summary> /// A part of this piece that will be only visible when <see cref="HyperDash"/> is true. /// </summary> [CanBeNull] protected virtual HyperBorderPiece HyperBorderPiece => null; protected override void LoadComplete() { base.LoadComplete(); AccentColour.BindTo(ObjectState.AccentColour); HyperDash.BindTo(ObjectState.HyperDash); HyperDash.BindValueChanged(hyper => { if (HyperBorderPiece != null) HyperBorderPiece.Alpha = hyper.NewValue ? 1 : 0; }, true); } protected override void Update() { if (BorderPiece != null) BorderPiece.Alpha = (float)Math.Clamp((ObjectState.HitObject.StartTime - Time.Current) / 500, 0, 1); } } }
// 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; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Catch.Objects.Drawables; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.Skinning.Default { public abstract class CatchHitObjectPiece : CompositeDrawable { public readonly Bindable<Color4> AccentColour = new Bindable<Color4>(); public readonly Bindable<bool> HyperDash = new Bindable<bool>(); [Resolved] protected IHasCatchObjectState ObjectState { get; private set; } /// <summary> /// A part of this piece that will be faded out while falling in the playfield. /// </summary> [CanBeNull] protected virtual BorderPiece BorderPiece => null; /// <summary> /// A part of this piece that will be only visible when <see cref="HyperDash"/> is true. /// </summary> [CanBeNull] protected virtual HyperBorderPiece HyperBorderPiece => null; protected override void LoadComplete() { base.LoadComplete(); AccentColour.BindTo(ObjectState.AccentColour); HyperDash.BindTo(ObjectState.HyperDash); HyperDash.BindValueChanged(hyper => { if (HyperBorderPiece != null) HyperBorderPiece.Alpha = hyper.NewValue ? 1 : 0; }, true); } protected override void Update() { if (BorderPiece != null && ObjectState?.HitObject != null) BorderPiece.Alpha = (float)Math.Clamp((ObjectState.HitObject.StartTime - Time.Current) / 500, 0, 1); } } }
mit
C#
4bd9692dad155fc9da56b95f9707544199fc04a9
Make querying successors and predeccors fail explicitly
beardgame/utilities
src/Graphs/AdjacencyListDirectedGraph.cs
src/Graphs/AdjacencyListDirectedGraph.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; namespace Bearded.Utilities.Graphs { class AdjacencyListDirectedGraph<T> : IDirectedGraph<T> where T : IEquatable<T> { private readonly ImmutableList<T> elements; private readonly ImmutableDictionary<T, ImmutableList<T>> directSuccessors; private readonly ImmutableDictionary<T, ImmutableList<T>> directPredecessors; public IEnumerable<T> Elements => elements; public int Count => elements.Count; public AdjacencyListDirectedGraph( ImmutableList<T> elements, ImmutableDictionary<T, ImmutableList<T>> directSuccessors, ImmutableDictionary<T, ImmutableList<T>> directPredecessors) { this.elements = elements; this.directSuccessors = directSuccessors; this.directPredecessors = directPredecessors; } public IEnumerable<T> GetDirectSuccessorsOf(T element) => directSuccessors.ContainsKey(element) ? directSuccessors[element] : throw new ArgumentOutOfRangeException(nameof(element), "Element not found in graph."); public IEnumerable<T> GetDirectPredecessorsOf(T element) => directPredecessors.ContainsKey(element) ? directPredecessors[element] : throw new ArgumentOutOfRangeException(nameof(element), "Element not found in graph."); } }
using System; using System.Collections.Generic; using System.Collections.Immutable; namespace Bearded.Utilities.Graphs { class AdjacencyListDirectedGraph<T> : IDirectedGraph<T> where T : IEquatable<T> { private readonly ImmutableList<T> elements; private readonly ImmutableDictionary<T, ImmutableList<T>> directSuccessors; private readonly ImmutableDictionary<T, ImmutableList<T>> directPredecessors; public IEnumerable<T> Elements => elements; public int Count => elements.Count; public AdjacencyListDirectedGraph( ImmutableList<T> elements, ImmutableDictionary<T, ImmutableList<T>> directSuccessors, ImmutableDictionary<T, ImmutableList<T>> directPredecessors) { this.elements = elements; this.directSuccessors = directSuccessors; this.directPredecessors = directPredecessors; } public IEnumerable<T> GetDirectSuccessorsOf(T element) => directSuccessors[element]; public IEnumerable<T> GetDirectPredecessorsOf(T element) => directPredecessors[element]; } }
mit
C#
f90eae109a8a7706915f59e3ac2f46913ce625b3
fix condition
serenabenny/Caliburn.Micro,Caliburn-Micro/Caliburn.Micro
src/Caliburn.Micro.Core/DefaultCloseStrategy.cs
src/Caliburn.Micro.Core/DefaultCloseStrategy.cs
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Caliburn.Micro { /// <summary> /// Used to gather the results from multiple child elements which may or may not prevent closing. /// </summary> /// <typeparam name="T">The type of child element.</typeparam> public class DefaultCloseStrategy<T> : ICloseStrategy<T> { readonly bool closeConductedItemsWhenConductorCannotClose; /// <summary> /// Creates an instance of the class. /// </summary> /// <param name="closeConductedItemsWhenConductorCannotClose">Indicates that even if all conducted items are not closable, those that are should be closed. The default is FALSE.</param> public DefaultCloseStrategy(bool closeConductedItemsWhenConductorCannotClose = false) { this.closeConductedItemsWhenConductorCannotClose = closeConductedItemsWhenConductorCannotClose; } /// <inheritdoc /> public async Task<ICloseResult<T>> ExecuteAsync(IEnumerable<T> toClose, CancellationToken cancellationToken = default) { var closeable = new List<T>(); var closeCanOccur = true; foreach(var child in toClose) { if (child is IGuardClose guard) { var canClose = await guard.CanCloseAsync(cancellationToken); if (canClose) { closeable.Add(child); } closeCanOccur = closeCanOccur && canClose; } else { closeable.Add(child); } } if (!this.closeConductedItemsWhenConductorCannotClose && !closeCanOccur) { closeable.Clear(); } return new CloseResult<T>(closeCanOccur, closeable); } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Caliburn.Micro { /// <summary> /// Used to gather the results from multiple child elements which may or may not prevent closing. /// </summary> /// <typeparam name="T">The type of child element.</typeparam> public class DefaultCloseStrategy<T> : ICloseStrategy<T> { readonly bool closeConductedItemsWhenConductorCannotClose; /// <summary> /// Creates an instance of the class. /// </summary> /// <param name="closeConductedItemsWhenConductorCannotClose">Indicates that even if all conducted items are not closable, those that are should be closed. The default is FALSE.</param> public DefaultCloseStrategy(bool closeConductedItemsWhenConductorCannotClose = false) { this.closeConductedItemsWhenConductorCannotClose = closeConductedItemsWhenConductorCannotClose; } /// <inheritdoc /> public async Task<ICloseResult<T>> ExecuteAsync(IEnumerable<T> toClose, CancellationToken cancellationToken = default) { var closeable = new List<T>(); var closeCanOccur = true; foreach(var child in toClose) { if (child is IGuardClose guard) { var canClose = await guard.CanCloseAsync(cancellationToken); if (canClose) { closeable.Add(child); } closeCanOccur = closeCanOccur && canClose; } else { closeable.Add(child); } } if (!this.closeConductedItemsWhenConductorCannotClose) { closeable.Clear(); } return new CloseResult<T>(closeCanOccur, closeable); } } }
mit
C#
951a52a578611cd603917ebb695df293a5377810
Update SettingSuperScriptEffect.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET
Examples/CSharp/Formatting/DealingWithFontSettings/SettingSuperScriptEffect.cs
Examples/CSharp/Formatting/DealingWithFontSettings/SettingSuperScriptEffect.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Formatting.DealingWithFontSettings { public class SettingSuperScriptEffect { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a new worksheet to the Excel object int i = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[i]; //Accessing the "A1" cell from the worksheet Aspose.Cells.Cell cell = worksheet.Cells["A1"]; //Adding some value to the "A1" cell cell.PutValue("Hello Aspose!"); //Obtaining the style of the cell Style style = cell.GetStyle(); //Setting superscript effect style.Font.IsSuperscript = true; //Applying the style to the cell cell.SetStyle(style); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Formatting.DealingWithFontSettings { public class SettingSuperScriptEffect { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a new worksheet to the Excel object int i = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[i]; //Accessing the "A1" cell from the worksheet Aspose.Cells.Cell cell = worksheet.Cells["A1"]; //Adding some value to the "A1" cell cell.PutValue("Hello Aspose!"); //Obtaining the style of the cell Style style = cell.GetStyle(); //Setting superscript effect style.Font.IsSuperscript = true; //Applying the style to the cell cell.SetStyle(style); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); } } }
mit
C#
9e0d47f8ee03df36010714487afb0b555fd7a7b7
Update StaticDirectoryContent.cs
cgourlay/Nancy,khellang/Nancy,vladlopes/Nancy,xt0rted/Nancy,Crisfole/Nancy,murador/Nancy,VQComms/Nancy,sroylance/Nancy,thecodejunkie/Nancy,jeff-pang/Nancy,jongleur1983/Nancy,Worthaboutapig/Nancy,jonathanfoster/Nancy,albertjan/Nancy,NancyFx/Nancy,thecodejunkie/Nancy,albertjan/Nancy,wtilton/Nancy,tparnell8/Nancy,anton-gogolev/Nancy,duszekmestre/Nancy,ccellar/Nancy,danbarua/Nancy,Worthaboutapig/Nancy,anton-gogolev/Nancy,Novakov/Nancy,EIrwin/Nancy,Crisfole/Nancy,tparnell8/Nancy,jmptrader/Nancy,cgourlay/Nancy,rudygt/Nancy,Crisfole/Nancy,guodf/Nancy,rudygt/Nancy,daniellor/Nancy,wtilton/Nancy,jmptrader/Nancy,sloncho/Nancy,dbolkensteyn/Nancy,phillip-haydon/Nancy,horsdal/Nancy,JoeStead/Nancy,cgourlay/Nancy,duszekmestre/Nancy,khellang/Nancy,jchannon/Nancy,guodf/Nancy,EIrwin/Nancy,wtilton/Nancy,tsdl2013/Nancy,ccellar/Nancy,felipeleusin/Nancy,asbjornu/Nancy,malikdiarra/Nancy,horsdal/Nancy,lijunle/Nancy,AcklenAvenue/Nancy,malikdiarra/Nancy,tsdl2013/Nancy,ayoung/Nancy,rudygt/Nancy,damianh/Nancy,grumpydev/Nancy,lijunle/Nancy,VQComms/Nancy,tareq-s/Nancy,khellang/Nancy,thecodejunkie/Nancy,hitesh97/Nancy,grumpydev/Nancy,sloncho/Nancy,murador/Nancy,tsdl2013/Nancy,dbabox/Nancy,EIrwin/Nancy,murador/Nancy,hitesh97/Nancy,sloncho/Nancy,nicklv/Nancy,SaveTrees/Nancy,jmptrader/Nancy,danbarua/Nancy,MetSystem/Nancy,sadiqhirani/Nancy,vladlopes/Nancy,joebuschmann/Nancy,MetSystem/Nancy,SaveTrees/Nancy,VQComms/Nancy,albertjan/Nancy,SaveTrees/Nancy,albertjan/Nancy,kekekeks/Nancy,damianh/Nancy,khellang/Nancy,charleypeng/Nancy,cgourlay/Nancy,NancyFx/Nancy,duszekmestre/Nancy,tareq-s/Nancy,phillip-haydon/Nancy,jchannon/Nancy,VQComms/Nancy,horsdal/Nancy,asbjornu/Nancy,sadiqhirani/Nancy,hitesh97/Nancy,guodf/Nancy,asbjornu/Nancy,joebuschmann/Nancy,davidallyoung/Nancy,davidallyoung/Nancy,Worthaboutapig/Nancy,JoeStead/Nancy,adamhathcock/Nancy,kekekeks/Nancy,murador/Nancy,jchannon/Nancy,charleypeng/Nancy,danbarua/Nancy,felipeleusin/Nancy,tsdl2013/Nancy,jongleur1983/Nancy,grumpydev/Nancy,malikdiarra/Nancy,ccellar/Nancy,davidallyoung/Nancy,sadiqhirani/Nancy,jonathanfoster/Nancy,jchannon/Nancy,MetSystem/Nancy,anton-gogolev/Nancy,jeff-pang/Nancy,damianh/Nancy,Worthaboutapig/Nancy,sroylance/Nancy,blairconrad/Nancy,tareq-s/Nancy,NancyFx/Nancy,kekekeks/Nancy,blairconrad/Nancy,malikdiarra/Nancy,danbarua/Nancy,adamhathcock/Nancy,dbolkensteyn/Nancy,sloncho/Nancy,EliotJones/NancyTest,jchannon/Nancy,sroylance/Nancy,ccellar/Nancy,ayoung/Nancy,JoeStead/Nancy,horsdal/Nancy,MetSystem/Nancy,felipeleusin/Nancy,fly19890211/Nancy,AIexandr/Nancy,davidallyoung/Nancy,dbabox/Nancy,fly19890211/Nancy,nicklv/Nancy,Novakov/Nancy,asbjornu/Nancy,AIexandr/Nancy,Novakov/Nancy,EliotJones/NancyTest,AlexPuiu/Nancy,sroylance/Nancy,grumpydev/Nancy,fly19890211/Nancy,AIexandr/Nancy,AcklenAvenue/Nancy,dbolkensteyn/Nancy,AcklenAvenue/Nancy,rudygt/Nancy,AlexPuiu/Nancy,daniellor/Nancy,adamhathcock/Nancy,AlexPuiu/Nancy,duszekmestre/Nancy,AIexandr/Nancy,vladlopes/Nancy,asbjornu/Nancy,fly19890211/Nancy,lijunle/Nancy,charleypeng/Nancy,AlexPuiu/Nancy,anton-gogolev/Nancy,tareq-s/Nancy,EliotJones/NancyTest,thecodejunkie/Nancy,blairconrad/Nancy,daniellor/Nancy,charleypeng/Nancy,VQComms/Nancy,jongleur1983/Nancy,daniellor/Nancy,davidallyoung/Nancy,guodf/Nancy,phillip-haydon/Nancy,sadiqhirani/Nancy,hitesh97/Nancy,EliotJones/NancyTest,dbabox/Nancy,jeff-pang/Nancy,tparnell8/Nancy,blairconrad/Nancy,xt0rted/Nancy,felipeleusin/Nancy,phillip-haydon/Nancy,vladlopes/Nancy,AIexandr/Nancy,xt0rted/Nancy,NancyFx/Nancy,adamhathcock/Nancy,jmptrader/Nancy,joebuschmann/Nancy,dbabox/Nancy,jonathanfoster/Nancy,nicklv/Nancy,charleypeng/Nancy,Novakov/Nancy,jeff-pang/Nancy,ayoung/Nancy,EIrwin/Nancy,SaveTrees/Nancy,dbolkensteyn/Nancy,lijunle/Nancy,ayoung/Nancy,tparnell8/Nancy,wtilton/Nancy,jonathanfoster/Nancy,xt0rted/Nancy,joebuschmann/Nancy,jongleur1983/Nancy,JoeStead/Nancy,AcklenAvenue/Nancy,nicklv/Nancy
src/Nancy/Conventions/StaticDirectoryContent.cs
src/Nancy/Conventions/StaticDirectoryContent.cs
namespace Nancy.Conventions { /// <summary> /// Nancy static directory convention helper /// </summary> public class StaticDirectoryContent { private readonly NancyConventions conventions; /// <summary> /// Creates a new instance of StaticDirectoryContent /// </summary> /// <param name="conventions">NancyConventions, to wich static directories get added</param> public StaticDirectoryContent(NancyConventions conventions) { this.conventions = conventions; } /// <summary> /// Adds a new static directory to the nancy conventions /// </summary> /// <param name="requestDirectory">The route of the file</param> public string this[string requestDirectory] { set { this.conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(requestDirectory, value)); } } } }
namespace Nancy.Conventions { /// <summary> /// Nancy static directory convention helper /// </summary> public class StaticDirectoryContent { NancyConventions conventions; /// <summary> /// Creates a new instance of StaticDirectoryContent /// </summary> /// <param name="conventions">NancyConventions, to wich static directories get added</param> public StaticDirectoryContent(NancyConventions conventions) { this.conventions = conventions; } /// <summary> /// Adds a new static directory to the nancy conventions /// </summary> /// <param name="requestFile">The route of the file</param> public string this[string requestDirectory] { set { conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(requestDirectory, value)); } } } }
mit
C#
120fa0def062ddf5980071971c21589a9a64fa3d
fix console log time format
xakep139/nuclear-river,xakep139/nuclear-river,2gis/nuclear-river,2gis/nuclear-river-validation-rules,2gis/nuclear-river
StateInitialization/StateInitialization.Core/Actors/SequentialPipelineActor.cs
StateInitialization/StateInitialization.Core/Actors/SequentialPipelineActor.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NuClear.Replication.Core; using NuClear.Replication.Core.Actors; namespace NuClear.StateInitialization.Core.Actors { internal sealed class SequentialPipelineActor : IActor { private readonly IReadOnlyCollection<IActor> _actors; public SequentialPipelineActor(IReadOnlyCollection<IActor> actors) { _actors = actors; } public IReadOnlyCollection<IEvent> ExecuteCommands(IReadOnlyCollection<ICommand> commands) { if (!commands.Any()) { return Array.Empty<IEvent>(); } return _actors.Aggregate( new List<IEvent>(), (events, actor) => { var sw = Stopwatch.StartNew(); events.AddRange(actor.ExecuteCommands(commands)); sw.Stop(); Console.WriteLine($"[{DateTime.Now}] [{Environment.CurrentManagedThreadId}] {actor.GetType().GetFriendlyName()}: {sw.Elapsed.TotalSeconds:F3} seconds"); return events; }); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NuClear.Replication.Core; using NuClear.Replication.Core.Actors; namespace NuClear.StateInitialization.Core.Actors { internal sealed class SequentialPipelineActor : IActor { private readonly IReadOnlyCollection<IActor> _actors; public SequentialPipelineActor(IReadOnlyCollection<IActor> actors) { _actors = actors; } public IReadOnlyCollection<IEvent> ExecuteCommands(IReadOnlyCollection<ICommand> commands) { if (!commands.Any()) { return Array.Empty<IEvent>(); } return _actors.Aggregate( new List<IEvent>(), (events, actor) => { var sw = Stopwatch.StartNew(); events.AddRange(actor.ExecuteCommands(commands)); sw.Stop(); Console.WriteLine($"[{DateTime.Now}] [{Environment.CurrentManagedThreadId}] {actor.GetType().GetFriendlyName()}: {sw.Elapsed.TotalSeconds} seconds"); return events; }); } } }
mpl-2.0
C#
4916d91e057297ea04bef7b0f289dafa2a91ed0b
Fix for #108 - Entity properties are tracked and don't need to call DbSet<>.Update(entity)
JasonGT/NorthwindTraders,JasonGT/NorthwindTraders,JasonGT/NorthwindTraders,JasonGT/NorthwindTraders
Northwind.Application/Customers/Commands/UpdateCustomer/UpdateCustomerCommandHandler.cs
Northwind.Application/Customers/Commands/UpdateCustomer/UpdateCustomerCommandHandler.cs
using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.EntityFrameworkCore; using Northwind.Application.Exceptions; using Northwind.Application.Interfaces; using Northwind.Domain.Entities; namespace Northwind.Application.Customers.Commands.UpdateCustomer { public class UpdateCustomerCommandHandler : IRequestHandler<UpdateCustomerCommand, Unit> { private readonly INorthwindDbContext _context; public UpdateCustomerCommandHandler(INorthwindDbContext context) { _context = context; } public async Task<Unit> Handle(UpdateCustomerCommand request, CancellationToken cancellationToken) { var entity = await _context.Customers .SingleOrDefaultAsync(c => c.CustomerId == request.Id, cancellationToken); if (entity == null) { throw new NotFoundException(nameof(Customer), request.Id); } entity.Address = request.Address; entity.City = request.City; entity.CompanyName = request.CompanyName; entity.ContactName = request.ContactName; entity.ContactTitle = request.ContactTitle; entity.Country = request.Country; entity.Fax = request.Fax; entity.Phone = request.Phone; entity.PostalCode = request.PostalCode; await _context.SaveChangesAsync(cancellationToken); return Unit.Value; } } }
using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.EntityFrameworkCore; using Northwind.Application.Exceptions; using Northwind.Application.Interfaces; using Northwind.Domain.Entities; namespace Northwind.Application.Customers.Commands.UpdateCustomer { public class UpdateCustomerCommandHandler : IRequestHandler<UpdateCustomerCommand, Unit> { private readonly INorthwindDbContext _context; public UpdateCustomerCommandHandler(INorthwindDbContext context) { _context = context; } public async Task<Unit> Handle(UpdateCustomerCommand request, CancellationToken cancellationToken) { var entity = await _context.Customers .SingleOrDefaultAsync(c => c.CustomerId == request.Id, cancellationToken); if (entity == null) { throw new NotFoundException(nameof(Customer), request.Id); } entity.Address = request.Address; entity.City = request.City; entity.CompanyName = request.CompanyName; entity.ContactName = request.ContactName; entity.ContactTitle = request.ContactTitle; entity.Country = request.Country; entity.Fax = request.Fax; entity.Phone = request.Phone; entity.PostalCode = request.PostalCode; _context.Customers.Update(entity); await _context.SaveChangesAsync(cancellationToken); return Unit.Value; } } }
mit
C#
af617d559f27fab1687e356260d65e312ef8a4b7
Fix type name in exception message for HasUniqueDomainSignature
alphacloud/Sharp-Architecture,ysdiong/Sharp-Architecture,chenkaibin/Sharp-Architecture
Solutions/SharpArch.NHibernate/NHibernateValidator/HasUniqueDomainSignatureAttribute.cs
Solutions/SharpArch.NHibernate/NHibernateValidator/HasUniqueDomainSignatureAttribute.cs
namespace SharpArch.NHibernate.NHibernateValidator { using System.ComponentModel.DataAnnotations; using SharpArch.Domain; using SharpArch.Domain.DomainModel; using SharpArch.Domain.PersistenceSupport; /// <summary> /// Provides a class level validator for determining if the entity has a unique domain signature /// when compared with other entries in the database. /// /// Due to the fact that .NET does not support generic attributes, this only works for entity /// types having an Id of type int. /// </summary> public class HasUniqueDomainSignatureAttribute : ValidationAttribute { public override bool IsValid(object value) { var entityToValidate = value as IEntityWithTypedId<int>; Check.Require( entityToValidate != null, "This validator must be used at the class level of an IEntityWithTypedId<int>. The type you provided was " + value.GetType()); var duplicateChecker = SafeServiceLocator<IEntityDuplicateChecker>.GetService(); return ! duplicateChecker.DoesDuplicateExistWithTypedIdOf(entityToValidate); } public override string FormatErrorMessage(string name) { return "Provided values matched an existing, duplicate entity"; } } }
namespace SharpArch.NHibernate.NHibernateValidator { using System.ComponentModel.DataAnnotations; using SharpArch.Domain; using SharpArch.Domain.DomainModel; using SharpArch.Domain.PersistenceSupport; /// <summary> /// Provides a class level validator for determining if the entity has a unique domain signature /// when compared with other entries in the database. /// /// Due to the fact that .NET does not support generic attributes, this only works for entity /// types having an Id of type int. /// </summary> public class HasUniqueDomainSignatureAttribute : ValidationAttribute { public override bool IsValid(object value) { var entityToValidate = value as IEntityWithTypedId<int>; Check.Require( entityToValidate != null, "This validator must be used at the class level of an IDomainWithTypedId<int>. The type you provided was " + value.GetType()); var duplicateChecker = SafeServiceLocator<IEntityDuplicateChecker>.GetService(); return ! duplicateChecker.DoesDuplicateExistWithTypedIdOf(entityToValidate); } public override string FormatErrorMessage(string name) { return "Provided values matched an existing, duplicate entity"; } } }
bsd-3-clause
C#
5f0a8a361dfbb41d052a3f964b4407a470e58099
fix array type conversion
Pondidum/Stronk,Pondidum/Stronk
src/Stronk/ValueConversion/CsvValueConverter.cs
src/Stronk/ValueConversion/CsvValueConverter.cs
using System; using System.Collections.Generic; using System.Linq; namespace Stronk.ValueConversion { public class CsvValueConverter : IValueConverter { public bool CanMap(Type target) { if (target == typeof(string)) return false; if (IsIEnumerable(target)) return true; return GetGenericInterfaces(target) .Contains(typeof(IEnumerable<>)); } public object Map(ValueConverterArgs e) { var values = e.Input.Split(','); var converters = e.OtherConverters.ToArray(); var targetType = e.Target.IsGenericType ? e.Target.GetGenericArguments()[0] : e.Target.GetElementType(); var converter = converters .First(c => c.CanMap(targetType)); var convertedValues = values .Select(val => converter.Map(new ValueConverterArgs(converters, targetType, val))); if (IsIEnumerable(e.Target)) return convertedValues.ToArray(); if (IsIList(e.Target)) return convertedValues.ToList(); if (e.Target.IsArray) return CastArray(targetType, convertedValues.ToArray()); throw new NotSupportedException("Only arrays, IEnumerable<T> an IList<T> are supported at the moment"); } private static bool IsIEnumerable(Type target) { return target.IsGenericType && target.GetGenericTypeDefinition() == typeof(IEnumerable<>); } private static bool IsIList(Type target) { return target.IsGenericType && target.GetGenericTypeDefinition() == typeof(IList<>); } private static IEnumerable<Type> GetGenericInterfaces(Type target) { return target .GetInterfaces() .Where(i => i.IsGenericType) .Select(i => i.GetGenericTypeDefinition()); } private static Array CastArray(Type target, object[] input) { Array dest = Array.CreateInstance(target, input.Length); Array.Copy(input, dest, input.Length); return dest; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Stronk.ValueConversion { public class CsvValueConverter : IValueConverter { public bool CanMap(Type target) { if (target == typeof(string)) return false; if (IsIEnumerable(target)) return true; return GetGenericInterfaces(target) .Contains(typeof(IEnumerable<>)); } public object Map(ValueConverterArgs e) { var values = e.Input.Split(','); var converters = e.OtherConverters.ToArray(); var targetType = e.Target.IsGenericType ? e.Target.GetGenericArguments()[0] : e.Target.GetElementType(); var converter = converters .First(c => c.CanMap(targetType)); var convertedValues = values .Select(val => converter.Map(new ValueConverterArgs(converters, targetType, val))); if (IsIEnumerable(e.Target)) return convertedValues.ToArray(); if (IsIList(e.Target)) return convertedValues.ToList(); if (e.Target.IsArray) return convertedValues.ToArray(); throw new NotSupportedException("Only arrays, IEnumerable<T> an IList<T> are supported at the moment"); } private static bool IsIEnumerable(Type target) { return target.IsGenericType && target.GetGenericTypeDefinition() == typeof(IEnumerable<>); } private static bool IsIList(Type target) { return target.IsGenericType && target.GetGenericTypeDefinition() == typeof(IList<>); } private static IEnumerable<Type> GetGenericInterfaces(Type target) { return target .GetInterfaces() .Where(i => i.IsGenericType) .Select(i => i.GetGenericTypeDefinition()); } } }
lgpl-2.1
C#
6ce813ea1de55714fe790c32a3c9e4291f7058f7
Fix "broken" User tests
awseward/Bugsnag.NET,awseward/Bugsnag.NET
Bugsnag.NET.Tests/Request/UserTests.cs
Bugsnag.NET.Tests/Request/UserTests.cs
using Bugsnag.NET.Request; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Bugsnag.Common; namespace Bugsnag.NET.Tests.Request { class UserTests { static Guid _guidId = Guid.Parse("72eae7d5-b3c9-43fd-8fa6-5dae60d509a7"); static string _stringId = "q5OKLQpuYNmtiZ5wx/Aa+JkozBKaSBKI9ImYRG+1=="; static int _intId = 8675309; static object[] _commonIds = new object[] { _guidId, _stringId, _intId }; static string _name = "Robert Paulson"; static string _email = "rpaulson@fight.club"; public static object[] CommonIds { get { return _commonIds; } } [TestCaseSource("CommonIds")] public void IdIsCorrect(object id) { var user = _BuildUser(id, _name, _email); Assert.AreEqual(id, user.Id); } [Test] public void GuidIdIsCorrect() { _AssertId(_guidId); } [Test] public void StringIdIsCorrect() { _AssertId(_stringId); } [Test] public void IntIdIsCorrect() { _AssertId(_intId); } [Test] public void NameIsCorrect() { var user = _BuildUser(_guidId, _name, _email); Assert.AreEqual(_name, user.Name); } [Test] public void EmailIsCorrect() { var user = _BuildUser(_guidId, _name, _email); Assert.AreEqual(_email, user.Email); } IUser _BuildUser(object id, string name, string email) { return new User(id) { Name = name, Email = email }; } void _AssertId(object id) { var user = _BuildUser(id, _name, _email); Assert.AreEqual(id, user.Id); } } }
using Bugsnag.NET.Request; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Bugsnag.Common; namespace Bugsnag.NET.Tests.Request { class UserTests { static Guid _guidId = Guid.NewGuid(); static string _stringId = System.IO.Path.GetRandomFileName().Replace(".", ""); static int _intId = 8675309; static object[] _commonIds = new object[] { _guidId, _stringId, _intId }; static string _name = "Robert Paulson"; static string _email = "rpaulson@fight.club"; public static object[] CommonIds { get { return _commonIds; } } [TestCaseSource("CommonIds")] [Ignore("Possible bug in NUnit (`Test adapter sent back a result for an unknown test case.`)")] public void IdIsCorrect(object id) { var user = _BuildUser(id, _name, _email); Assert.AreEqual(id, user.Id); } [Test] public void GuidIdIsCorrect() { _AssertId(_guidId); } [Test] public void StringIdIsCorrect() { _AssertId(_stringId); } [Test] public void IntIdIsCorrect() { _AssertId(_intId); } [Test] public void NameIsCorrect() { var user = _BuildUser(_guidId, _name, _email); Assert.AreEqual(_name, user.Name); } [Test] public void EmailIsCorrect() { var user = _BuildUser(_guidId, _name, _email); Assert.AreEqual(_email, user.Email); } IUser _BuildUser(object id, string name, string email) { return new User(id) { Name = name, Email = email }; } void _AssertId(object id) { var user = _BuildUser(id, _name, _email); Assert.AreEqual(id, user.Id); } } }
mit
C#
b6a0b278c8f7e237b548319e4b7f9c05fd546d7f
Fix dependency context bugs
karajas/core-setup,rakeshsinghranchi/core-setup,joperezr/core-setup,gkhanna79/core-setup,janvorli/core-setup,MichaelSimons/core-setup,weshaggard/core-setup,cakine/core-setup,ericstj/core-setup,ramarag/core-setup,steveharter/core-setup,ericstj/core-setup,gkhanna79/core-setup,schellap/core-setup,steveharter/core-setup,MichaelSimons/core-setup,weshaggard/core-setup,cakine/core-setup,wtgodbe/core-setup,rakeshsinghranchi/core-setup,steveharter/core-setup,ellismg/core-setup,MichaelSimons/core-setup,joperezr/core-setup,janvorli/core-setup,schellap/core-setup,schellap/core-setup,ravimeda/core-setup,MichaelSimons/core-setup,schellap/core-setup,zamont/core-setup,weshaggard/core-setup,joperezr/core-setup,ramarag/core-setup,zamont/core-setup,chcosta/core-setup,rakeshsinghranchi/core-setup,zamont/core-setup,wtgodbe/core-setup,crummel/dotnet_core-setup,karajas/core-setup,crummel/dotnet_core-setup,MichaelSimons/core-setup,ramarag/core-setup,crummel/dotnet_core-setup,ramarag/core-setup,chcosta/core-setup,vivmishra/core-setup,janvorli/core-setup,weshaggard/core-setup,ericstj/core-setup,ravimeda/core-setup,vivmishra/core-setup,ramarag/core-setup,chcosta/core-setup,ellismg/core-setup,karajas/core-setup,joperezr/core-setup,wtgodbe/core-setup,wtgodbe/core-setup,ericstj/core-setup,karajas/core-setup,steveharter/core-setup,ravimeda/core-setup,MichaelSimons/core-setup,zamont/core-setup,ericstj/core-setup,gkhanna79/core-setup,rakeshsinghranchi/core-setup,ravimeda/core-setup,steveharter/core-setup,wtgodbe/core-setup,ravimeda/core-setup,ellismg/core-setup,rakeshsinghranchi/core-setup,ellismg/core-setup,cakine/core-setup,ellismg/core-setup,zamont/core-setup,ericstj/core-setup,chcosta/core-setup,gkhanna79/core-setup,vivmishra/core-setup,karajas/core-setup,rakeshsinghranchi/core-setup,steveharter/core-setup,ramarag/core-setup,karajas/core-setup,schellap/core-setup,crummel/dotnet_core-setup,cakine/core-setup,ravimeda/core-setup,janvorli/core-setup,ellismg/core-setup,chcosta/core-setup,janvorli/core-setup,crummel/dotnet_core-setup,cakine/core-setup,gkhanna79/core-setup,vivmishra/core-setup,crummel/dotnet_core-setup,vivmishra/core-setup,weshaggard/core-setup,cakine/core-setup,wtgodbe/core-setup,zamont/core-setup,joperezr/core-setup,gkhanna79/core-setup,vivmishra/core-setup,joperezr/core-setup,schellap/core-setup,chcosta/core-setup,janvorli/core-setup,weshaggard/core-setup
CompilationLibrary.cs
CompilationLibrary.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace Microsoft.Extensions.DependencyModel { public class CompilationLibrary : Library { private static Lazy<Assembly> _entryAssembly = new Lazy<Assembly>(GetEntryAssembly); public CompilationLibrary(string libraryType, string packageName, string version, string hash, string[] assemblies, Dependency[] dependencies, bool serviceable) : base(libraryType, packageName, version, hash, dependencies, serviceable) { Assemblies = assemblies; } public IReadOnlyList<string> Assemblies { get; } public IEnumerable<string> ResolveReferencePaths() { var entryAssembly = _entryAssembly.Value; var entryAssemblyName = entryAssembly.GetName().Name; var basePath = GetRefsLocation(); foreach (var assembly in Assemblies) { if (Path.GetFileNameWithoutExtension(assembly) == entryAssemblyName) { yield return entryAssembly.Location; continue; } var fullName = Path.Combine(basePath, Path.GetFileName(assembly)); if (!File.Exists(fullName)) { throw new InvalidOperationException($"Can not resolve assembly {assembly} location"); } yield return fullName; } } private static Assembly GetEntryAssembly() { var entryAssembly = (Assembly)typeof(Assembly).GetTypeInfo().GetDeclaredMethod("GetEntryAssembly").Invoke(null, null); if (entryAssembly == null) { throw new InvalidOperationException("Could not determine entry assembly"); } return entryAssembly; } private static string GetRefsLocation() { return Path.Combine(Path.GetDirectoryName(_entryAssembly.Value.Location), "refs"); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace Microsoft.Extensions.DependencyModel { public class CompilationLibrary : Library { private static Lazy<string> _refsLocation = new Lazy<string>(GetRefsLocation); public CompilationLibrary(string libraryType, string packageName, string version, string hash, string[] assemblies, Dependency[] dependencies, bool serviceable) : base(libraryType, packageName, version, hash, dependencies, serviceable) { Assemblies = assemblies; } public IReadOnlyList<string> Assemblies { get; } public IEnumerable<string> ResolveReferencePaths() { var basePath = _refsLocation.Value; foreach (var assembly in Assemblies) { var fullName = Path.Combine(basePath, Path.GetFileName(assembly)); if (!File.Exists(fullName)) { throw new InvalidOperationException($"Can not resolve assembly {assembly} location"); } yield return fullName; } } private static string GetRefsLocation() { var entryAssembly = (Assembly)typeof(Assembly).GetTypeInfo().GetDeclaredMethod("GetEntryAssembly").Invoke(null, null); if (entryAssembly == null) { throw new InvalidOperationException("Could not determine entry assembly"); } return Path.Combine(Path.GetDirectoryName(entryAssembly.Location), "refs"); } } }
mit
C#
0195d654cacb2e496ce7cc2b3c3b3991111eabb3
Increase the precision of speed multiplier to match osu-stable
peppy/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu
osu.Game/Beatmaps/ControlPoints/DifficultyControlPoint.cs
osu.Game/Beatmaps/ControlPoints/DifficultyControlPoint.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.Bindables; using osu.Game.Graphics; using osuTK.Graphics; namespace osu.Game.Beatmaps.ControlPoints { public class DifficultyControlPoint : ControlPoint { public static readonly DifficultyControlPoint DEFAULT = new DifficultyControlPoint { SpeedMultiplierBindable = { Disabled = true }, }; /// <summary> /// The speed multiplier at this control point. /// </summary> public readonly BindableDouble SpeedMultiplierBindable = new BindableDouble(1) { Precision = 0.01, Default = 1, MinValue = 0.1, MaxValue = 10 }; public override Color4 GetRepresentingColour(OsuColour colours) => colours.GreenDark; /// <summary> /// The speed multiplier at this control point. /// </summary> public double SpeedMultiplier { get => SpeedMultiplierBindable.Value; set => SpeedMultiplierBindable.Value = value; } public override bool IsRedundant(ControlPoint existing) => existing is DifficultyControlPoint existingDifficulty && SpeedMultiplier == existingDifficulty.SpeedMultiplier; public override void CopyFrom(ControlPoint other) { SpeedMultiplier = ((DifficultyControlPoint)other).SpeedMultiplier; base.CopyFrom(other); } } }
// 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.Bindables; using osu.Game.Graphics; using osuTK.Graphics; namespace osu.Game.Beatmaps.ControlPoints { public class DifficultyControlPoint : ControlPoint { public static readonly DifficultyControlPoint DEFAULT = new DifficultyControlPoint { SpeedMultiplierBindable = { Disabled = true }, }; /// <summary> /// The speed multiplier at this control point. /// </summary> public readonly BindableDouble SpeedMultiplierBindable = new BindableDouble(1) { Precision = 0.1, Default = 1, MinValue = 0.1, MaxValue = 10 }; public override Color4 GetRepresentingColour(OsuColour colours) => colours.GreenDark; /// <summary> /// The speed multiplier at this control point. /// </summary> public double SpeedMultiplier { get => SpeedMultiplierBindable.Value; set => SpeedMultiplierBindable.Value = value; } public override bool IsRedundant(ControlPoint existing) => existing is DifficultyControlPoint existingDifficulty && SpeedMultiplier == existingDifficulty.SpeedMultiplier; public override void CopyFrom(ControlPoint other) { SpeedMultiplier = ((DifficultyControlPoint)other).SpeedMultiplier; base.CopyFrom(other); } } }
mit
C#
0ff9ed3342be95d43ff737a979114e532b95e000
Update InputListener.cs
ghandhikus/Xna-Basic-Input-Detection
Code/InputControlling/InputListener.cs
Code/InputControlling/InputListener.cs
#region Using Statements using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; #endregion namespace MapEditor { class InputListener { virtual public void Down(GameTime gameTime) { } virtual public void Up(GameTime gameTime) { } virtual public void Click(GameTime gameTime) { } virtual public void Hold(GameTime gameTime) { } virtual public void Tick(GameTime gameTime) { } } }
#region Using Statements using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; #endregion namespace Game { class InputListener { virtual public void Down() { } virtual public void Up() { } virtual public void Click() { } virtual public void Hold() { } virtual public void Tick(GameTime gameTime) { } } }
apache-2.0
C#
94dd2d4e228fc821b6f44c0cc0465834abe76bd4
Fix typos in the tests
cloudfoundry/IronFrame,cloudfoundry-incubator/IronFrame,cloudfoundry/IronFrame,cloudfoundry-incubator/IronFrame,stefanschneider/IronFrame,stefanschneider/IronFrame
IronFrame.Test/FirewallRuleSpecTest.cs
IronFrame.Test/FirewallRuleSpecTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace IronFrame { public class FirewallRuleSpecTest { [Fact] public void TestRemoteAddresses() { var firewallRuleSpec = new FirewallRuleSpec() { Networks = new List<IPRange> { new IPRange {Start = "10.1.1.1", End = "10.1.1.10"}, new IPRange {Start = "10.3.1.1", End = "10.3.1.10"} } }; Assert.Equal("10.1.1.1-10.1.1.10,10.3.1.1-10.3.1.10", firewallRuleSpec.RemoteAddresses); } [Fact] public void TestRemotePorts() { var firewallRuleSpec = new FirewallRuleSpec() { Ports = new List<PortRange> { new PortRange() {Start = 8080, End = 8090}, new PortRange() {Start = 9090, End = 9099}, } }; Assert.Equal("8080-8090,9090-9099", firewallRuleSpec.RemotePorts); } [Fact] public void ReturnStarIfAddressesIsEmpty() { var firewallRuleSpec = new FirewallRuleSpec(); Assert.Equal("*", firewallRuleSpec.RemoteAddresses); } [Fact] public void ReturnStarIfPortIsEmpty() { var firewallRuleSpec = new FirewallRuleSpec(); Assert.Equal("*", firewallRuleSpec.RemotePorts); } [Fact] public void InitializeProtocolToAll() { var firewallRuleSpec = new FirewallRuleSpec(); Assert.Equal(Protocol.All, firewallRuleSpec.Protocol); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace IronFrame { public class FirewallRuleSpecTest { [Fact] public void TestRemoteAddresses() { var firewallRuleSpec = new FirewallRuleSpec() { Networks = new List<IPRange> { new IPRange {Start = "10.1.1.1", End = "10.1.1.10"}, new IPRange {Start = "10.3.1.1", End = "10.3.1.10"} } }; Assert.Equal("10.1.1.1-10.1.1.10,10.3.1.1-10.3.1.10", firewallRuleSpec.RemoteAddresses); } [Fact] public void TestRemotePorts() { var firewallRuleSpec = new FirewallRuleSpec() { Ports = new List<PortRange> { new PortRange() {Start = 8080, End = 8090}, new PortRange() {Start = 9090, End = 9099}, } }; Assert.Equal("8080-8090,9090-9099", firewallRuleSpec.RemotePorts); } [Fact] public void ReturnStartIfAddressesIsEmpty() { var firewallRuleSpec = new FirewallRuleSpec(); Assert.Equal("*", firewallRuleSpec.RemoteAddresses); } [Fact] public void ReturnStartIfPortIsEmpty() { var firewallRuleSpec = new FirewallRuleSpec(); Assert.Equal("*", firewallRuleSpec.RemotePorts); } [Fact] public void InitializeProtocolToTcp() { var firewallRuleSpec = new FirewallRuleSpec(); Assert.Equal(Protocol.All, firewallRuleSpec.Protocol); } } }
apache-2.0
C#