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 |
|---|---|---|---|---|---|---|---|---|
e3478fd4fbdf7fe1ddb94659b99826c55faf794a | Update AssemblyInfo.cs | Ex-Presidents/Loadout | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Loadout")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ex-Presidents")]
[assembly: AssemblyProduct("Loadout")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ba8a3d8d-5a9b-4d0d-90d8-6284ff0a5393")]
// 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("Loadout")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kr4ken & Symix")]
[assembly: AssemblyProduct("Loadout")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ba8a3d8d-5a9b-4d0d-90d8-6284ff0a5393")]
// 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")]
| agpl-3.0 | C# |
00b0d8de273309d7da87282320605aa201be3217 | fix channel members | Inumedia/SlackAPI | SlackAPI/Channel.cs | SlackAPI/Channel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
public class Channel : Conversation
{
public string name;
public string creator;
public string user;
public bool is_archived;
public bool is_member;
public bool is_general;
public bool is_channel;
public bool is_group;
public bool is_im;
//Is this deprecated by is_open?
public bool IsPrivateGroup { get { return id != null && id[0] == 'G'; } }
public int num_members;
public OwnedStampedMessage topic;
public OwnedStampedMessage purpose;
public string[] members;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
public class Channel : Conversation
{
public string name;
public string creator;
public string user;
public bool is_archived;
public bool is_member;
public bool is_general;
public bool is_channel;
public bool is_group;
public bool is_im;
//Is this deprecated by is_open?
public bool IsPrivateGroup { get { return id != null && id[0] == 'G'; } }
public int num_members;
public OwnedStampedMessage topic;
public OwnedStampedMessage purpose;
public string[] members;
//im related properties
public bool is_im;
public string user;
}
}
| mit | C# |
c162413d983570acb54b269d47b2a721c60b63c1 | Make class static | mmanela/diffplex,mmanela/diffplex,mmanela/diffplex,mmanela/diffplex | Perf.DiffPlex/Program.cs | Perf.DiffPlex/Program.cs | using System;
namespace Perf.DiffPlex
{
internal static class Program
{
private static void Main()
{
Console.WriteLine(@"DiffPlex Perf Tester");
new DiffPerfTester().Run();
Console.WriteLine();
}
}
}
| using System;
namespace Perf.DiffPlex
{
internal class Program
{
private static void Main()
{
Console.WriteLine(@"DiffPlex Perf Tester");
new DiffPerfTester().Run();
Console.WriteLine();
}
}
}
| apache-2.0 | C# |
a7e6efd34fc83ceb33cf7c8a31200d3d709e1dad | Rename keys -> actions | smoogipoo/osu,DrabWeb/osu,Drezi126/osu,naoey/osu,naoey/osu,naoey/osu,DrabWeb/osu,ppy/osu,Nabile-Rahmani/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,Damnae/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu-new,ZLima12/osu,Frontear/osuKyzer,ppy/osu,ppy/osu,NeoAdonis/osu,DrabWeb/osu,EVAST9919/osu,peppy/osu,peppy/osu,smoogipoo/osu,johnneijzen/osu,2yangk23/osu,2yangk23/osu | osu.Game.Rulesets.Taiko/Replays/TaikoFramedReplayInputHandler.cs | osu.Game.Rulesets.Taiko/Replays/TaikoFramedReplayInputHandler.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.Game.Rulesets.Replays;
using System.Collections.Generic;
using osu.Framework.Input;
namespace osu.Game.Rulesets.Taiko.Replays
{
internal class TaikoFramedReplayInputHandler : FramedReplayInputHandler
{
public TaikoFramedReplayInputHandler(Replay replay)
: base(replay)
{
}
public override List<InputState> GetPendingStates()
{
var actions = new List<TaikoAction>();
if (CurrentFrame?.MouseRight1 == true)
actions.Add(TaikoAction.LeftCentre);
if (CurrentFrame?.MouseRight2 == true)
actions.Add(TaikoAction.RightCentre);
if (CurrentFrame?.MouseLeft1 == true)
actions.Add(TaikoAction.LeftRim);
if (CurrentFrame?.MouseLeft2 == true)
actions.Add(TaikoAction.RightRim);
return new List<InputState> { new ReplayState<TaikoAction> { PressedActions = actions } };
}
}
}
| // 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.Game.Rulesets.Replays;
using System.Collections.Generic;
using osu.Framework.Input;
namespace osu.Game.Rulesets.Taiko.Replays
{
internal class TaikoFramedReplayInputHandler : FramedReplayInputHandler
{
public TaikoFramedReplayInputHandler(Replay replay)
: base(replay)
{
}
public override List<InputState> GetPendingStates()
{
var keys = new List<TaikoAction>();
if (CurrentFrame?.MouseRight1 == true)
keys.Add(TaikoAction.LeftCentre);
if (CurrentFrame?.MouseRight2 == true)
keys.Add(TaikoAction.RightCentre);
if (CurrentFrame?.MouseLeft1 == true)
keys.Add(TaikoAction.LeftRim);
if (CurrentFrame?.MouseLeft2 == true)
keys.Add(TaikoAction.RightRim);
return new List<InputState> { new ReplayState<TaikoAction> { PressedActions = keys } };
}
}
}
| mit | C# |
27cb07455f270142053d6426da0deda26f0d537a | Set version number of unit tests to be different | mirhagk/PowerCommandParser | UnitTests/Properties/AssemblyInfo.cs | UnitTests/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc38a28-87ec-4b55-8130-ce705cdb49e8")]
// 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.2.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc38a28-87ec-4b55-8130-ce705cdb49e8")]
// 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")]
| mit | C# |
10d9261e81f37bc64e40f6a7e7a2f34d07f3128b | Update WalletWasabi/Models/CoinsRegistry.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Models/CoinsRegistry.cs | WalletWasabi/Models/CoinsRegistry.cs | using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using NBitcoin;
using WalletWasabi.Models;
namespace WalletWasabi.Models
{
public class CoinsRegistry
{
private HashSet<SmartCoin> _coins;
private object _lock;
public event NotifyCollectionChangedEventHandler CollectionChanged;
public CoinsRegistry()
{
_coins = new HashSet<SmartCoin>();
_lock = new object();
}
public CoinsView AsCoinsView()
{
return new CoinsView(_coins);
}
public bool IsEmpty => !_coins.Any();
public SmartCoin GetByOutPoint(OutPoint outpoint)
{
return _coins.FirstOrDefault(x => x.GetOutPoint() == outpoint);
}
public bool TryAdd(SmartCoin coin)
{
var added = false;
lock (_lock)
{
added = _coins.Add(coin);
}
if (added)
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, coin));
}
return added;
}
public void Remove(SmartCoin coin)
{
var coinsToRemove = AsCoinsView().DescendantOf(coin).ToList();
coinsToRemove.Add(coin);
lock (_lock)
{
foreach (var toRemove in coinsToRemove)
{
_coins.Remove(coin);
}
}
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, coinsToRemove));
}
public void Clear()
{
lock (_lock)
{
_coins.Clear();
}
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
}
| using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using NBitcoin;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Models
{
public class CoinsRegistry
{
private HashSet<SmartCoin> _coins;
private object _lock;
public event NotifyCollectionChangedEventHandler CollectionChanged;
public CoinsRegistry()
{
_coins = new HashSet<SmartCoin>();
_lock = new object();
}
public CoinsView AsCoinsView()
{
return new CoinsView(_coins);
}
public bool IsEmpty => !_coins.Any();
public SmartCoin GetByOutPoint(OutPoint outpoint)
{
return _coins.FirstOrDefault(x => x.GetOutPoint() == outpoint);
}
public bool TryAdd(SmartCoin coin)
{
var added = false;
lock (_lock)
{
added = _coins.Add(coin);
}
if (added)
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, coin));
}
return added;
}
public void Remove(SmartCoin coin)
{
var coinsToRemove = AsCoinsView().DescendantOf(coin).ToList();
coinsToRemove.Add(coin);
lock (_lock)
{
foreach (var toRemove in coinsToRemove)
{
_coins.Remove(coin);
}
}
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, coinsToRemove));
}
public void Clear()
{
lock (_lock)
{
_coins.Clear();
}
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
}
| mit | C# |
545cc6df2cc8c9b28ce152b2c578a25929dae261 | Improve existing unit tests | vadimzozulya/FakeHttpContext | src/FakeHttpContext.Tests/FakeContextTests.cs | src/FakeHttpContext.Tests/FakeContextTests.cs | namespace FakeHttpContext.Tests
{
using System;
using System.IO;
using System.Web;
using FluentAssertions;
using Ploeh.AutoFixture.Xunit2;
using Xunit;
/// <summary>The fake context tests.</summary>
public class FakeContextTests
{
[Fact]
public void Should_initialize_httpContext_current()
{
// Act
using (new FakeHttpContext())
{
// Assert
HttpContext.Current.Should().NotBeNull();
}
}
/// <summary>The should_ fact method name.</summary>
[Fact]
public void Should_restore_previous_context()
{
// Arrange
var httpContext = new HttpContext(
new HttpRequest(string.Empty, "http://server", string.Empty),
new HttpResponse(new StringWriter()));
HttpContext.Current = httpContext;
// Act
using (new FakeHttpContext())
{
// Assert
HttpContext.Current.Should().NotBeSameAs(httpContext);
}
HttpContext.Current.Should().BeSameAs(httpContext);
}
[Theory, AutoData]
public void Should_allow_to_use_map_path(string path)
{
// Arrange
var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
// Act
using (new FakeHttpContext())
{
// Assert
HttpContext.Current.Server.MapPath(path).Should().Be(expectedPath);
}
}
[Theory, AutoData]
public void Should_fake_user_agent(string userAgentString)
{
// Arrange && Act
using (new FakeHttpContext().WithUserAgent(userAgentString))
{
// Assert
HttpContext.Current.Request.UserAgent.Should().Be(userAgentString);
}
}
}
}
| namespace FakeHttpContext.Tests
{
using System;
using System.IO;
using System.Web;
using FluentAssertions;
using Ploeh.AutoFixture.Xunit2;
using Xunit;
/// <summary>The fake context tests.</summary>
public class FakeContextTests
{
[Fact]
public void Should_initialize_httpContext_current()
{
// Arrange
using (new FakeHttpContext())
{
// Assert
HttpContext.Current.Should().NotBeNull();
}
}
/// <summary>The should_ fact method name.</summary>
[Fact]
public void Should_restore_previous_context()
{
// Arrange
var httpContext = new HttpContext(
new HttpRequest(string.Empty, "http://server", string.Empty),
new HttpResponse(new StringWriter()));
HttpContext.Current = httpContext;
using (new FakeHttpContext())
{
HttpContext.Current = null;
}
HttpContext.Current.Should().BeSameAs(httpContext);
}
[Theory, AutoData]
public void Should_allow_to_use_map_path(string path)
{
// Arrange
var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
using (new FakeHttpContext())
{
// Act && Assert
HttpContext.Current.Server.MapPath(path).Should().Be(expectedPath);
}
}
[Theory, AutoData]
public void Should_fake_user_agent(string userAgentString)
{
// Arrange
using (new FakeHttpContext().WithUserAgent(userAgentString))
{
// Act
// Assert
HttpContext.Current.Request.UserAgent.Should().Be(userAgentString);
}
}
public void Should_fake_user_agent1()
{
// Arrange
const string ExpectedUserAgentString = "user agent string";
using (new FakeHttpContext().WithUserAgent(ExpectedUserAgentString))
{
// Assert
HttpContext.Current.Request.UserAgent.Should().Be(ExpectedUserAgentString);
}
}
}
}
| mit | C# |
a9b726acf4a175b037c26dbe402504733dcb0f5e | allow assmblies besides Nancy.dll to use the EmbeddedFileResponse | Novakov/Nancy,horsdal/Nancy,EliotJones/NancyTest,joebuschmann/Nancy,tareq-s/Nancy,AlexPuiu/Nancy,blairconrad/Nancy,jmptrader/Nancy,jchannon/Nancy,asbjornu/Nancy,anton-gogolev/Nancy,tareq-s/Nancy,fly19890211/Nancy,Worthaboutapig/Nancy,vladlopes/Nancy,ayoung/Nancy,vladlopes/Nancy,daniellor/Nancy,felipeleusin/Nancy,jeff-pang/Nancy,duszekmestre/Nancy,daniellor/Nancy,charleypeng/Nancy,jongleur1983/Nancy,lijunle/Nancy,horsdal/Nancy,jongleur1983/Nancy,AlexPuiu/Nancy,blairconrad/Nancy,SaveTrees/Nancy,duszekmestre/Nancy,Crisfole/Nancy,sloncho/Nancy,malikdiarra/Nancy,nicklv/Nancy,asbjornu/Nancy,NancyFx/Nancy,EIrwin/Nancy,xt0rted/Nancy,sroylance/Nancy,xt0rted/Nancy,MetSystem/Nancy,guodf/Nancy,malikdiarra/Nancy,jonathanfoster/Nancy,asbjornu/Nancy,lijunle/Nancy,adamhathcock/Nancy,damianh/Nancy,horsdal/Nancy,kekekeks/Nancy,tsdl2013/Nancy,dbolkensteyn/Nancy,lijunle/Nancy,davidallyoung/Nancy,ccellar/Nancy,AcklenAvenue/Nancy,damianh/Nancy,dbabox/Nancy,Novakov/Nancy,albertjan/Nancy,anton-gogolev/Nancy,cgourlay/Nancy,SaveTrees/Nancy,kekekeks/Nancy,tsdl2013/Nancy,ayoung/Nancy,tsdl2013/Nancy,jonathanfoster/Nancy,jonathanfoster/Nancy,charleypeng/Nancy,lijunle/Nancy,tparnell8/Nancy,anton-gogolev/Nancy,joebuschmann/Nancy,EIrwin/Nancy,NancyFx/Nancy,fly19890211/Nancy,NancyFx/Nancy,nicklv/Nancy,albertjan/Nancy,malikdiarra/Nancy,AcklenAvenue/Nancy,MetSystem/Nancy,joebuschmann/Nancy,dbolkensteyn/Nancy,SaveTrees/Nancy,jongleur1983/Nancy,Crisfole/Nancy,Worthaboutapig/Nancy,EliotJones/NancyTest,thecodejunkie/Nancy,AIexandr/Nancy,jmptrader/Nancy,davidallyoung/Nancy,charleypeng/Nancy,damianh/Nancy,murador/Nancy,fly19890211/Nancy,grumpydev/Nancy,ayoung/Nancy,duszekmestre/Nancy,EliotJones/NancyTest,jchannon/Nancy,VQComms/Nancy,thecodejunkie/Nancy,EIrwin/Nancy,rudygt/Nancy,jchannon/Nancy,phillip-haydon/Nancy,grumpydev/Nancy,danbarua/Nancy,malikdiarra/Nancy,joebuschmann/Nancy,SaveTrees/Nancy,dbolkensteyn/Nancy,guodf/Nancy,JoeStead/Nancy,khellang/Nancy,phillip-haydon/Nancy,asbjornu/Nancy,Worthaboutapig/Nancy,vladlopes/Nancy,davidallyoung/Nancy,davidallyoung/Nancy,vladlopes/Nancy,xt0rted/Nancy,thecodejunkie/Nancy,VQComms/Nancy,AcklenAvenue/Nancy,jonathanfoster/Nancy,VQComms/Nancy,jmptrader/Nancy,hitesh97/Nancy,tareq-s/Nancy,cgourlay/Nancy,hitesh97/Nancy,grumpydev/Nancy,JoeStead/Nancy,cgourlay/Nancy,sadiqhirani/Nancy,albertjan/Nancy,sloncho/Nancy,danbarua/Nancy,wtilton/Nancy,AIexandr/Nancy,sadiqhirani/Nancy,sroylance/Nancy,guodf/Nancy,cgourlay/Nancy,khellang/Nancy,dbolkensteyn/Nancy,adamhathcock/Nancy,albertjan/Nancy,AIexandr/Nancy,murador/Nancy,blairconrad/Nancy,rudygt/Nancy,tparnell8/Nancy,felipeleusin/Nancy,murador/Nancy,sloncho/Nancy,fly19890211/Nancy,davidallyoung/Nancy,wtilton/Nancy,Novakov/Nancy,wtilton/Nancy,jchannon/Nancy,jeff-pang/Nancy,adamhathcock/Nancy,charleypeng/Nancy,horsdal/Nancy,khellang/Nancy,dbabox/Nancy,phillip-haydon/Nancy,AIexandr/Nancy,Crisfole/Nancy,duszekmestre/Nancy,charleypeng/Nancy,JoeStead/Nancy,ccellar/Nancy,daniellor/Nancy,anton-gogolev/Nancy,EliotJones/NancyTest,sroylance/Nancy,AlexPuiu/Nancy,tareq-s/Nancy,tparnell8/Nancy,felipeleusin/Nancy,sloncho/Nancy,dbabox/Nancy,AcklenAvenue/Nancy,sadiqhirani/Nancy,AlexPuiu/Nancy,adamhathcock/Nancy,tparnell8/Nancy,xt0rted/Nancy,asbjornu/Nancy,tsdl2013/Nancy,wtilton/Nancy,VQComms/Nancy,JoeStead/Nancy,sadiqhirani/Nancy,guodf/Nancy,Novakov/Nancy,danbarua/Nancy,EIrwin/Nancy,grumpydev/Nancy,jeff-pang/Nancy,ayoung/Nancy,felipeleusin/Nancy,jmptrader/Nancy,jongleur1983/Nancy,phillip-haydon/Nancy,ccellar/Nancy,khellang/Nancy,VQComms/Nancy,blairconrad/Nancy,rudygt/Nancy,nicklv/Nancy,MetSystem/Nancy,jchannon/Nancy,sroylance/Nancy,jeff-pang/Nancy,rudygt/Nancy,Worthaboutapig/Nancy,NancyFx/Nancy,thecodejunkie/Nancy,kekekeks/Nancy,ccellar/Nancy,daniellor/Nancy,murador/Nancy,danbarua/Nancy,hitesh97/Nancy,AIexandr/Nancy,hitesh97/Nancy,dbabox/Nancy,MetSystem/Nancy,nicklv/Nancy | src/Nancy/Diagnostics/EmbeddedFileResponse.cs | src/Nancy/Diagnostics/EmbeddedFileResponse.cs | namespace Nancy.Diagnostics
{
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
public class EmbeddedFileResponse : Response
{
private static readonly byte[] ErrorText;
static EmbeddedFileResponse()
{
ErrorText = Encoding.UTF8.GetBytes("NOT FOUND");
}
public EmbeddedFileResponse(Assembly assembly, string resourcePath, string name)
{
this.ContentType = MimeTypes.GetMimeType(name);
this.StatusCode = HttpStatusCode.OK;
this.Contents = stream =>
{
var content =
GetResourceContent(assembly, resourcePath, name);
if (content != null)
{
content.CopyTo(stream);
}
else
{
stream.Write(ErrorText, 0, ErrorText.Length);
}
};
}
private Stream GetResourceContent(Assembly assembly, string resourcePath, string name)
{
var resourceName = assembly
.GetManifestResourceNames()
.Where(x => GetFileNameFromResourceName(resourcePath, x).Equals(name, StringComparison.OrdinalIgnoreCase))
.Select(x => GetFileNameFromResourceName(resourcePath, x))
.FirstOrDefault();
resourceName =
string.Concat(resourcePath, ".", resourceName);
return assembly.GetManifestResourceStream(resourceName);
}
private static string GetFileNameFromResourceName(string resourcePath, string resourceName)
{
return resourceName.Replace(resourcePath, string.Empty).Substring(1);
}
}
} | namespace Nancy.Diagnostics
{
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
public class EmbeddedFileResponse : Response
{
private static readonly byte[] ErrorText;
static EmbeddedFileResponse()
{
ErrorText = Encoding.UTF8.GetBytes("NOT FOUND");
}
public EmbeddedFileResponse(Assembly assembly, string resourcePath, string name)
{
this.ContentType = MimeTypes.GetMimeType(name);
this.StatusCode = HttpStatusCode.OK;
this.Contents = stream =>
{
var content =
GetResourceContent(assembly, resourcePath, name);
if (content != null)
{
content.CopyTo(stream);
}
else
{
stream.Write(ErrorText, 0, ErrorText.Length);
}
};
}
private Stream GetResourceContent(Assembly assembly, string resourcePath, string name)
{
var resourceName = assembly
.GetManifestResourceNames()
.Where(x => GetFileNameFromResourceName(resourcePath, x).Equals(name, StringComparison.OrdinalIgnoreCase))
.Select(x => GetFileNameFromResourceName(resourcePath, x))
.FirstOrDefault();
resourceName =
string.Concat(resourcePath, ".", resourceName);
return this.GetType().Assembly.GetManifestResourceStream(resourceName);
}
private static string GetFileNameFromResourceName(string resourcePath, string resourceName)
{
return resourceName.Replace(resourcePath, string.Empty).Substring(1);
}
}
} | mit | C# |
e69adaa1081b02b8850e2fcf9846b66fad488c05 | fix class name | TravisTX/TfsSlackFactory | src/TfsSlackFactory/Services/FormatService.cs | src/TfsSlackFactory/Services/FormatService.cs | using TfsSlackFactory.Models;
namespace TfsSlackFactory.Services
{
public class FormatService
{
public string Format(SlackWorkItemModel model, string formatString)
{
string message = formatString;
message = message.Replace("{teamProjectCollection}", model.TeamProjectCollection);
message = message.Replace("{dDisplayName}", model.DisplayName);
message = message.Replace("{projectName}", model.ProjectName);
message = message.Replace("{wiUrl}", model.WiUrl);
message = message.Replace("{wiType}", model.WiType);
message = message.Replace("{wiId}", model.WiId);
message = message.Replace("{wiTitle}", model.WiTitle);
message = message.Replace("{isStateChanged}", model.IsStateChanged);
message = message.Replace("{isAssigmentChanged}", model.IsAssigmentChanged);
message = message.Replace("{assignedTo}", model.AssignedTo);
message = message.Replace("{state}", model.State);
message = message.Replace("{userName}", model.UserName);
message = message.Replace("{action}", model.Action);
message = message.Replace("{assignedToUserName}", model.AssignedToUserName);
message = message.Replace("{mappedAssignedToUser}", model.MappedAssignedToUser);
message = message.Replace("{mappedUser}", model.MappedUser);
message = message.Replace("{parentWiUrl}", model.ParentWiUrl);
message = message.Replace("{parentWiType}", model.ParentWiType);
message = message.Replace("{parentWiId}", model.ParentWiId);
message = message.Replace("{parentWiTitle}", model.ParentWiTitle);
return message;
}
}
} | using TfsSlackFactory.Models;
namespace TfsSlackFactory.Services
{
public class Formatter
{
public string Format(SlackWorkItemModel model, string formatString)
{
string message = formatString;
message = message.Replace("{teamProjectCollection}", model.TeamProjectCollection);
message = message.Replace("{dDisplayName}", model.DisplayName);
message = message.Replace("{projectName}", model.ProjectName);
message = message.Replace("{wiUrl}", model.WiUrl);
message = message.Replace("{wiType}", model.WiType);
message = message.Replace("{wiId}", model.WiId);
message = message.Replace("{wiTitle}", model.WiTitle);
message = message.Replace("{isStateChanged}", model.IsStateChanged);
message = message.Replace("{isAssigmentChanged}", model.IsAssigmentChanged);
message = message.Replace("{assignedTo}", model.AssignedTo);
message = message.Replace("{state}", model.State);
message = message.Replace("{userName}", model.UserName);
message = message.Replace("{action}", model.Action);
message = message.Replace("{assignedToUserName}", model.AssignedToUserName);
message = message.Replace("{mappedAssignedToUser}", model.MappedAssignedToUser);
message = message.Replace("{mappedUser}", model.MappedUser);
message = message.Replace("{parentWiUrl}", model.ParentWiUrl);
message = message.Replace("{parentWiType}", model.ParentWiType);
message = message.Replace("{parentWiId}", model.ParentWiId);
message = message.Replace("{parentWiTitle}", model.ParentWiTitle);
return message;
}
}
} | mit | C# |
c056c9d910c0f20b919c4fa725569b7f3ba764c7 | Revert AssemblyVersion to 2.0.0 because there are no breaking changes in this version | begoldsm/azure-sdk-for-net,mihymel/azure-sdk-for-net,mihymel/azure-sdk-for-net,begoldsm/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,mihymel/azure-sdk-for-net,begoldsm/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net | src/ResourceManagement/TrafficManager/Microsoft.Azure.Management.TrafficManager/Properties/AssemblyInfo.cs | src/ResourceManagement/TrafficManager/Microsoft.Azure.Management.TrafficManager/Properties/AssemblyInfo.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Traffic Manager Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Traffic Manager management functions for managing the Microsoft Azure Traffic Manager service.")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Traffic Manager Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Traffic Manager management functions for managing the Microsoft Azure Traffic Manager service.")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| mit | C# |
8b88033c559ec06c5f90c9c84d46caaba348acba | Disable unused functionality | mavasani/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,mavasani/roslyn | src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingIncrementalAnalyzerBase.cs | src/Features/Core/Portable/ExternalAccess/UnitTesting/SolutionCrawler/UnitTestingIncrementalAnalyzerBase.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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.SolutionCrawler
{
internal class UnitTestingIncrementalAnalyzerBase : IUnitTestingIncrementalAnalyzer
{
protected UnitTestingIncrementalAnalyzerBase()
{
}
#if false // Not used in unit testing crawling
public virtual Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task ActiveDocumentSwitchedAsync(TextDocument document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task AnalyzeSyntaxAsync(Document document, UnitTestingInvocationReasons reasons, CancellationToken cancellationToken)
=> Task.CompletedTask;
#endif
public virtual Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, UnitTestingInvocationReasons reasons, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task AnalyzeProjectAsync(Project project, bool semanticsChanged, UnitTestingInvocationReasons reasons, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
=> Task.CompletedTask;
#if false // Not used in unit testing crawling
public virtual Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellation)
=> Task.CompletedTask;
public virtual Task NonSourceDocumentOpenAsync(TextDocument textDocument, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task NonSourceDocumentCloseAsync(TextDocument textDocument, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task NonSourceDocumentResetAsync(TextDocument textDocument, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task AnalyzeNonSourceDocumentAsync(TextDocument textDocument, UnitTestingInvocationReasons reasons, CancellationToken cancellationToken)
=> Task.CompletedTask;
public void LogAnalyzerCountSummary()
{
}
/// <summary>
/// Order all incremental analyzers below DiagnosticIncrementalAnalyzer
/// </summary>
public virtual int Priority => 1;
public virtual void Shutdown()
{
}
#endif
}
}
| // 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.SolutionCrawler
{
internal class UnitTestingIncrementalAnalyzerBase : IUnitTestingIncrementalAnalyzer
{
protected UnitTestingIncrementalAnalyzerBase()
{
}
public virtual Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task ActiveDocumentSwitchedAsync(TextDocument document, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task AnalyzeSyntaxAsync(Document document, UnitTestingInvocationReasons reasons, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, UnitTestingInvocationReasons reasons, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task AnalyzeProjectAsync(Project project, bool semanticsChanged, UnitTestingInvocationReasons reasons, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellation)
=> Task.CompletedTask;
public virtual Task NonSourceDocumentOpenAsync(TextDocument textDocument, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task NonSourceDocumentCloseAsync(TextDocument textDocument, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task NonSourceDocumentResetAsync(TextDocument textDocument, CancellationToken cancellationToken)
=> Task.CompletedTask;
public virtual Task AnalyzeNonSourceDocumentAsync(TextDocument textDocument, UnitTestingInvocationReasons reasons, CancellationToken cancellationToken)
=> Task.CompletedTask;
public void LogAnalyzerCountSummary()
{
}
/// <summary>
/// Order all incremental analyzers below DiagnosticIncrementalAnalyzer
/// </summary>
public virtual int Priority => 1;
public virtual void Shutdown()
{
}
}
}
| mit | C# |
2ae3b815d0d9dca060eb20af297d9ed67d6e883a | build 7.1.21.0 | agileharbor/channelAdvisorAccess | src/Global/GlobalAssemblyInfo.cs | src/Global/GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.21.0" ) ] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.20.0" ) ] | bsd-3-clause | C# |
3754aa35818607980d2e545f506efd421d89ed2b | Update SharedAssemblyInfo.cs | wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter | src/Shared/SharedAssemblyInfo.cs | src/Shared/SharedAssemblyInfo.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
[assembly: AssemblyCompany("Wiesław Šoltés")]
[assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2010-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.3.4")]
[assembly: AssemblyFileVersion("0.3.4")]
[assembly: AssemblyInformationalVersion("0.3.4")]
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
[assembly: AssemblyCompany("Wiesław Šoltés")]
[assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2010-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.3.4")]
[assembly: AssemblyFileVersion("0.3.4")]
[assembly: AssemblyInformationalVersion("0.3.4")]
| mit | C# |
140d21e4aa453cc1467f7269912fd4d1543b0e3b | Update ResolveApprenticeshipOverlappingTrainingDateRequest.cs | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Requests/ResolveApprenticeshipOverlappingTrainingDateRequest.cs | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Requests/ResolveApprenticeshipOverlappingTrainingDateRequest.cs | using SFA.DAS.CommitmentsV2.Types;
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class ResolveApprenticeshipOverlappingTrainingDateRequest
{
public long? ApprenticeshipId { get; set; }
public OverlappingTrainingDateRequestResolutionType? ResolutionType { get; set; }
}
} | using SFA.DAS.CommitmentsV2.Types;
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class ResolveApprenticeshipOverlappingTrainingDateRequest
{
public long? ApprenticeshipId { get; set; }
public long? DraftApprenticeshipId { get; set; }
public OverlappingTrainingDateRequestResolutionType? ResolutionType { get; set; }
}
} | mit | C# |
a64511e2f8fd3ffb57c07cc6c0cb8ca7c88a3605 | Update App.xaml.cs | nunit/nunit.runners,nunit/nunit.xamarin,nunit/nunit.runners | src/nunit.xamarin/App.xaml.cs | src/nunit.xamarin/App.xaml.cs | // Copyright (c) 2015 CNUnit Project
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System.Reflection;
using System.Collections.Generic;
using NUnit.Runner.Services;
using NUnit.Runner.View;
using NUnit.Runner.ViewModel;
using Xamarin.Forms;
namespace NUnit.Runner
{
/// <summary>
/// The NUnit Xamarin test runner
/// </summary>
public partial class App : Application
{
private readonly SummaryViewModel _model;
/// <summary>
/// Constructs a new app adding the current assembly to be tested
/// </summary>
public App ()
{
InitializeComponent ();
if(Device.RuntimePlatform == Device.UWP)
{
Resources["defaultBackground"] = Resources["windowsBackground"];
}
_model = new SummaryViewModel();
MainPage = new NavigationPage(new SummaryView(_model));
#if !NETFX_CORE
AddTestAssembly(Assembly.GetCallingAssembly());
#endif
}
/// <summary>
/// Adds an assembly to be tested.
/// </summary>
/// <param name="testAssembly">The test assembly.</param>
/// <param name="options">An optional dictionary of options for loading the assembly.</param>
public void AddTestAssembly(Assembly testAssembly, Dictionary<string, object> options = null)
{
_model.AddTest(testAssembly, options);
}
/// <summary>
/// User options for the test suite.
/// </summary>
public TestOptions Options
{
get { return _model.Options; }
set { _model.Options = value; }
}
}
}
| // Copyright (c) 2015 CNUnit Project
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System.Reflection;
using System.Collections.Generic;
using NUnit.Runner.Services;
using NUnit.Runner.View;
using NUnit.Runner.ViewModel;
using Xamarin.Forms;
namespace NUnit.Runner
{
/// <summary>
/// The NUnit Xamarin test runner
/// </summary>
public partial class App : Application
{
private readonly SummaryViewModel _model;
/// <summary>
/// Constructs a new app adding the current assembly to be tested
/// </summary>
public App ()
{
InitializeComponent ();
if(Device.RuntimePlatform == Device.UWP)
{
Resources["defaultBackground"] = Resources["windowsBackground"];
}
_model = new SummaryViewModel();
MainPage = new NavigationPage(new SummaryView(_model));
#if !NETFX_CORE
AddTestAssembly(Assembly.GetCallingAssembly());
#endif
}
/// <summary>
/// Adds an assembly to be tested.
/// </summary>
/// <param name="testAssembly">The test assembly.</param>
/// <param name="options">An optional dictionary of options for loading the assembly.</param>
public void AddTestAssembly(Assembly testAssembly, Dictionary<string, object> options = null)
{
_model.AddTest(testAssembly, options);
}
/// <summary>
/// User options for the test suite.
/// </summary>
public TestOptions Options
{
get { return _model.Options; }
set { _model.Options = value; }
}
}
}
| mit | C# |
9bee820d79cea15c12d7be247fb9fe161f3066f1 | Fix missing check if Builder was correctly setup before executing Build operation | Seddryck/NBi,Seddryck/NBi | NBi.NUnit/Builder/Helper/InstanceArgsBuilder.cs | NBi.NUnit/Builder/Helper/InstanceArgsBuilder.cs | using NBi.Core.Injection;
using NBi.Core.Sequence.Resolver;
using NBi.Core.Variable;
using NBi.Xml;
using NBi.Xml.Settings;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.NUnit.Builder.Helper
{
public class InstanceArgsBuilder
{
private readonly ServiceLocator serviceLocator;
private readonly IDictionary<string, ITestVariable> globalVariables;
private bool isSetup = false;
private object obj = null;
private SettingsXml settings = SettingsXml.Empty;
private IInstanceArgs args = null;
public InstanceArgsBuilder(ServiceLocator serviceLocator, IDictionary<string, ITestVariable> globalVariables)
{
this.serviceLocator = serviceLocator;
this.globalVariables = globalVariables;
}
public void Setup(SettingsXml settings)
{
this.settings = settings;
}
public void Setup(InstanceXml definition)
{
obj = definition;
isSetup = true;
}
public void Build()
{
if (!isSetup)
throw new InvalidOperationException();
if ((obj as InstanceXml).Variable != null)
{
var variable = (obj as InstanceXml).Variable;
var argsBuilder = new SequenceResolverArgsBuilder(serviceLocator);
argsBuilder.Setup(settings);
argsBuilder.Setup(globalVariables);
argsBuilder.Setup(variable.SentinelLoop);
argsBuilder.Setup(variable.Type);
argsBuilder.Build();
var factory = new SequenceResolverFactory(serviceLocator);
args = new SingleVariableInstanceArgs()
{
Name = variable.Name,
Resolver = factory.Instantiate<object>(argsBuilder.GetArgs())
};
}
}
public IInstanceArgs GetArgs() => args ?? throw new InvalidOperationException();
}
}
| using NBi.Core.Injection;
using NBi.Core.Sequence.Resolver;
using NBi.Core.Variable;
using NBi.Xml;
using NBi.Xml.Settings;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.NUnit.Builder.Helper
{
public class InstanceArgsBuilder
{
private readonly ServiceLocator serviceLocator;
private readonly IDictionary<string, ITestVariable> globalVariables;
private bool isSetup = false;
private object obj = null;
private SettingsXml settings = SettingsXml.Empty;
private IInstanceArgs args = null;
public InstanceArgsBuilder(ServiceLocator serviceLocator, IDictionary<string, ITestVariable> globalVariables)
{
this.serviceLocator = serviceLocator;
this.globalVariables = globalVariables;
}
public void Setup(SettingsXml settings)
{
this.settings = settings;
}
public void Setup(InstanceXml definition)
{
obj = definition;
}
public void Build()
{
if ((obj as InstanceXml).Variable != null)
{
var variable = (obj as InstanceXml).Variable;
var argsBuilder = new SequenceResolverArgsBuilder(serviceLocator);
argsBuilder.Setup(settings);
argsBuilder.Setup(globalVariables);
argsBuilder.Setup(variable.SentinelLoop);
argsBuilder.Setup(variable.Type);
argsBuilder.Build();
var factory = new SequenceResolverFactory(serviceLocator);
args = new SingleVariableInstanceArgs()
{
Name = variable.Name,
Resolver = factory.Instantiate<object>(argsBuilder.GetArgs())
};
}
}
public IInstanceArgs GetArgs() => args ?? throw new InvalidOperationException();
}
}
| apache-2.0 | C# |
6d0eef267d1c94c184220ee318fe20cdfdf79333 | Delete unnecessary debugging code. | mysql-net/MySqlConnector,mysql-net/MySqlConnector | tests/SideBySide/AppConfig.cs | tests/SideBySide/AppConfig.cs | using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
namespace SideBySide
{
public static class AppConfig
{
private static IReadOnlyDictionary<string, string> DefaultConfig { get; } =
new Dictionary<string, string>
{
["Data:NoPasswordUser"] = "",
["Data:SupportsCachedProcedures"] = "false",
["Data:SupportsJson"] = "false",
};
public static string CertsPath => Path.GetFullPath(Config.GetValue<string>("Data:CertificatesPath"));
private static IConfiguration ConfigBuilder { get; } = new ConfigurationBuilder()
.AddInMemoryCollection(DefaultConfig)
.AddJsonFile("config.json")
.Build();
public static IConfiguration Config => ConfigBuilder;
public static string ConnectionString => Config.GetValue<string>("Data:ConnectionString");
public static string PasswordlessUser => Config.GetValue<string>("Data:PasswordlessUser");
public static string SecondaryDatabase => Config.GetValue<string>("Data:SecondaryDatabase");
public static ServerFeatures SupportedFeatures => (ServerFeatures) Enum.Parse(typeof(ServerFeatures), Config.GetValue<string>("Data:SupportedFeatures"));
public static bool SupportsJson => SupportedFeatures.HasFlag(ServerFeatures.Json);
public static string MySqlBulkLoaderCsvFile => Config.GetValue<string>("Data:MySqlBulkLoaderCsvFile");
public static string MySqlBulkLoaderLocalCsvFile => Config.GetValue<string>("Data:MySqlBulkLoaderLocalCsvFile");
public static string MySqlBulkLoaderTsvFile => Config.GetValue<string>("Data:MySqlBulkLoaderTsvFile");
public static string MySqlBulkLoaderLocalTsvFile => Config.GetValue<string>("Data:MySqlBulkLoaderLocalTsvFile");
public static MySqlConnectionStringBuilder CreateConnectionStringBuilder() => new MySqlConnectionStringBuilder(ConnectionString);
public static MySqlConnectionStringBuilder CreateSha256ConnectionStringBuilder()
{
var csb = CreateConnectionStringBuilder();
csb.UserID = "sha256user";
csb.Password = "Sh@256Pa55";
csb.Database = null;
return csb;
}
// tests can run much slower in CI environments
public static int TimeoutDelayFactor { get; } = Environment.GetEnvironmentVariable("APPVEYOR") == "True" || Environment.GetEnvironmentVariable("TRAVIS") == "true" ? 6 : 1;
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
namespace SideBySide
{
public static class AppConfig
{
private static IReadOnlyDictionary<string, string> DefaultConfig { get; } =
new Dictionary<string, string>
{
["Data:NoPasswordUser"] = "",
["Data:SupportsCachedProcedures"] = "false",
["Data:SupportsJson"] = "false",
};
public static string CertsPath => Path.GetFullPath(Config.GetValue<string>("Data:CertificatesPath"));
private static int _configFirst;
private static IConfiguration ConfigBuilder { get; } = new ConfigurationBuilder()
.AddInMemoryCollection(DefaultConfig)
.AddJsonFile("config.json")
.Build();
public static IConfiguration Config
{
get
{
if (Interlocked.Exchange(ref _configFirst, 1) == 0)
Console.WriteLine("Config Read");
return ConfigBuilder;
}
}
public static string ConnectionString => Config.GetValue<string>("Data:ConnectionString");
public static string PasswordlessUser => Config.GetValue<string>("Data:PasswordlessUser");
public static string SecondaryDatabase => Config.GetValue<string>("Data:SecondaryDatabase");
public static ServerFeatures SupportedFeatures => (ServerFeatures) Enum.Parse(typeof(ServerFeatures), Config.GetValue<string>("Data:SupportedFeatures"));
public static bool SupportsJson => SupportedFeatures.HasFlag(ServerFeatures.Json);
public static string MySqlBulkLoaderCsvFile => Config.GetValue<string>("Data:MySqlBulkLoaderCsvFile");
public static string MySqlBulkLoaderLocalCsvFile => Config.GetValue<string>("Data:MySqlBulkLoaderLocalCsvFile");
public static string MySqlBulkLoaderTsvFile => Config.GetValue<string>("Data:MySqlBulkLoaderTsvFile");
public static string MySqlBulkLoaderLocalTsvFile => Config.GetValue<string>("Data:MySqlBulkLoaderLocalTsvFile");
public static MySqlConnectionStringBuilder CreateConnectionStringBuilder() => new MySqlConnectionStringBuilder(ConnectionString);
public static MySqlConnectionStringBuilder CreateSha256ConnectionStringBuilder()
{
var csb = CreateConnectionStringBuilder();
csb.UserID = "sha256user";
csb.Password = "Sh@256Pa55";
csb.Database = null;
return csb;
}
// tests can run much slower in CI environments
public static int TimeoutDelayFactor { get; } = (Environment.GetEnvironmentVariable("APPVEYOR") == "True" || Environment.GetEnvironmentVariable("TRAVIS") == "true") ? 6 : 1;
}
}
| mit | C# |
07fee61989e3f230d1a8ef9dbfc2c272eba4a741 | Use reflection to load Rulesets. | Nabile-Rahmani/osu,EVAST9919/osu,Frontear/osuKyzer,ZLima12/osu,johnneijzen/osu,osu-RP/osu-RP,smoogipoo/osu,ppy/osu,Damnae/osu,default0/osu,Drezi126/osu,2yangk23/osu,ZLima12/osu,naoey/osu,smoogipoo/osu,2yangk23/osu,peppy/osu-new,ppy/osu,DrabWeb/osu,theguii/osu,RedNesto/osu,ppy/osu,nyaamara/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,tacchinotacchi/osu,peppy/osu,smoogipooo/osu,naoey/osu,johnneijzen/osu,NeoAdonis/osu,UselessToucan/osu,NotKyon/lolisu,naoey/osu,UselessToucan/osu,peppy/osu,DrabWeb/osu,UselessToucan/osu,DrabWeb/osu | osu.Game/Modes/Ruleset.cs | osu.Game/Modes/Ruleset.cs | //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using osu.Game.Modes.Objects;
using osu.Game.Modes.UI;
using System.Reflection;
using osu.Framework.Extensions;
using System;
using System.Linq;
namespace osu.Game.Modes
{
public abstract class Ruleset
{
public abstract ScoreOverlay CreateScoreOverlay();
public abstract HitRenderer CreateHitRendererWith(List<HitObject> objects);
public static Ruleset GetRuleset(PlayMode mode)
{
Type type = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName.Contains($@"osu.Game.Modes.{mode}"))
.SelectMany(a => a.GetTypes())
.Where(t => t.Name == $@"{mode}Ruleset")
.FirstOrDefault();
if (type == null)
return null;
return Activator.CreateInstance(type) as Ruleset;
}
}
}
| //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using osu.Game.Modes.Objects;
using osu.Game.Modes.UI;
namespace osu.Game.Modes
{
public abstract class Ruleset
{
public abstract ScoreOverlay CreateScoreOverlay();
public abstract HitRenderer CreateHitRendererWith(List<HitObject> objects);
public static Ruleset GetRuleset(PlayMode mode)
{
switch (mode)
{
default:
return null;
// return new OsuRuleset();
//case PlayMode.Catch:
// return new CatchRuleset();
//case PlayMode.Mania:
// return new ManiaRuleset();
//case PlayMode.Taiko:
// return new TaikoRuleset();
}
}
}
}
| mit | C# |
f65a9e36aded46a3b927c5c5b631d34883cd6b5e | Add devToolsCommand variable | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Shell/Commands/ToolCommands.cs | WalletWasabi.Gui/Shell/Commands/ToolCommands.cs | using Avalonia;
using Avalonia.Controls;
using Avalonia.Diagnostics;
using AvalonStudio.Commands;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using ReactiveUI;
using System;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Gui.Tabs;
using WalletWasabi.Gui.Tabs.WalletManager;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class ToolCommands
{
public Global Global { get; }
[ImportingConstructor]
public ToolCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = global.Global;
var walletManagerCommand = ReactiveCommand.Create(OnWalletManager);
var settingsCommand = ReactiveCommand.Create(() =>
{
IoC.Get<IShell>().AddOrSelectDocument(() => new SettingsViewModel(Global));
});
#if DEBUG
var devToolsCommand = ReactiveCommand.Create(() =>
{
var devTools = new DevTools(Application.Current.Windows.FirstOrDefault());
var devToolsWindow = new Window
{
Width = 1024,
Height = 512,
Content = devTools,
DataTemplates =
{
new ViewLocator<Avalonia.Diagnostics.ViewModels.ViewModelBase>()
}
};
devToolsWindow.Show();
});
#endif
Observable
.Merge(walletManagerCommand.ThrownExceptions)
.Merge(settingsCommand.ThrownExceptions)
#if DEBUG
.Merge(devToolsCommand.ThrownExceptions)
#endif
.Subscribe(OnException);
WalletManagerCommand = new CommandDefinition(
"Wallet Manager",
commandIconService.GetCompletionKindImage("WalletManager"),
walletManagerCommand);
SettingsCommand = new CommandDefinition(
"Settings",
commandIconService.GetCompletionKindImage("Settings"),
settingsCommand);
#if DEBUG
DevToolsCommand = new CommandDefinition(
"Dev Tools",
commandIconService.GetCompletionKindImage("DevTools"),
devToolsCommand);
#endif
}
private void OnWalletManager()
{
var walletManagerViewModel = IoC.Get<IShell>().GetOrCreate<WalletManagerViewModel>();
if (Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any())
{
walletManagerViewModel.SelectLoadWallet();
}
else
{
walletManagerViewModel.SelectGenerateWallet();
}
}
private void OnException(Exception ex)
{
Logging.Logger.LogError<ToolCommands>(ex);
}
[ExportCommandDefinition("Tools.WalletManager")]
public CommandDefinition WalletManagerCommand { get; }
[ExportCommandDefinition("Tools.Settings")]
public CommandDefinition SettingsCommand { get; }
#if DEBUG
[ExportCommandDefinition("Tools.DevTools")]
public CommandDefinition DevToolsCommand { get; }
#endif
}
}
| using Avalonia;
using Avalonia.Controls;
using Avalonia.Diagnostics;
using AvalonStudio.Commands;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using ReactiveUI;
using System;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Gui.Tabs;
using WalletWasabi.Gui.Tabs.WalletManager;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class ToolCommands
{
public Global Global { get; }
[ImportingConstructor]
public ToolCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = global.Global;
var walletManagerCommand = ReactiveCommand.Create(OnWalletManager);
var settingsCommand = ReactiveCommand.Create(() =>
{
IoC.Get<IShell>().AddOrSelectDocument(() => new SettingsViewModel(Global));
});
Observable
.Merge(walletManagerCommand.ThrownExceptions)
.Merge(settingsCommand.ThrownExceptions)
.Subscribe(OnException);
WalletManagerCommand = new CommandDefinition(
"Wallet Manager",
commandIconService.GetCompletionKindImage("WalletManager"),
walletManagerCommand);
SettingsCommand = new CommandDefinition(
"Settings",
commandIconService.GetCompletionKindImage("Settings"),
settingsCommand);
#if DEBUG
DevToolsCommand = new CommandDefinition(
"Dev Tools",
commandIconService.GetCompletionKindImage("DevTools"),
ReactiveCommand.Create(() =>
{
var devTools = new DevTools(Application.Current.Windows.FirstOrDefault());
var devToolsWindow = new Window
{
Width = 1024,
Height = 512,
Content = devTools,
DataTemplates =
{
new ViewLocator<Avalonia.Diagnostics.ViewModels.ViewModelBase>()
}
};
devToolsWindow.Show();
}));
#endif
}
private void OnWalletManager()
{
var walletManagerViewModel = IoC.Get<IShell>().GetOrCreate<WalletManagerViewModel>();
if (Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any())
{
walletManagerViewModel.SelectLoadWallet();
}
else
{
walletManagerViewModel.SelectGenerateWallet();
}
}
private void OnException(Exception ex)
{
Logging.Logger.LogError<ToolCommands>(ex);
}
[ExportCommandDefinition("Tools.WalletManager")]
public CommandDefinition WalletManagerCommand { get; }
[ExportCommandDefinition("Tools.Settings")]
public CommandDefinition SettingsCommand { get; }
#if DEBUG
[ExportCommandDefinition("Tools.DevTools")]
public CommandDefinition DevToolsCommand { get; }
#endif
}
}
| mit | C# |
b7fba6667c22ff63a6bc882899c9e4a6cd0cded6 | Fix creating a font with a specific style | PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,PowerOfCode/Eto | Source/Eto.Platform.iOS/Drawing/FontFamilyHandler.cs | Source/Eto.Platform.iOS/Drawing/FontFamilyHandler.cs | using System;
using Eto.Drawing;
using System.Collections.Generic;
using MonoTouch.UIKit;
using System.Linq;
namespace Eto.Platform.iOS.Drawing
{
public class FontFamilyHandler : WidgetHandler<object, FontFamily>, IFontFamily
{
public FontFamilyHandler ()
{
}
public FontFamilyHandler (string familyName)
{
Create (familyName);
}
public void Create (string familyName)
{
this.Name = familyName;
}
public string Name { get; private set; }
public IEnumerable<FontTypeface> Typefaces {
get { return UIFont.FontNamesForFamilyName(this.Name).Select(r => new FontTypeface(Widget, new FontTypefaceHandler(r))); }
}
public UIFont CreateFont (float size, FontStyle style)
{
var matched = Typefaces.FirstOrDefault (r => r.FontStyle == style);
if (matched == null) matched = Typefaces.First ();
var handler = matched.Handler as FontTypefaceHandler;
return handler.CreateFont(size);
}
public FontTypeface GetFace(UIFont font)
{
return Typefaces.FirstOrDefault (r => string.Equals (((FontTypefaceHandler)r.Handler).FontName, font.Name, StringComparison.InvariantCultureIgnoreCase));
}
}
}
| using System;
using Eto.Drawing;
using System.Collections.Generic;
using MonoTouch.UIKit;
using System.Linq;
namespace Eto.Platform.iOS.Drawing
{
public class FontFamilyHandler : WidgetHandler<object, FontFamily>, IFontFamily
{
public FontFamilyHandler ()
{
}
public FontFamilyHandler (string familyName)
{
Create (familyName);
}
public void Create (string familyName)
{
this.Name = familyName;
}
public string Name { get; private set; }
public IEnumerable<FontTypeface> Typefaces {
get { return UIFont.FontNamesForFamilyName(this.Name).Select(r => new FontTypeface(Widget, new FontTypefaceHandler(r))); }
}
public UIFont CreateFont (float size, FontStyle style)
{
// scan!
var handler = Typefaces.First().Handler as FontTypefaceHandler;
return handler.CreateFont(size);
}
public FontTypeface GetFace(UIFont font)
{
return Typefaces.FirstOrDefault (r => string.Equals (((FontTypefaceHandler)r.Handler).FontName, font.Name, StringComparison.InvariantCultureIgnoreCase));
}
}
}
| bsd-3-clause | C# |
2573046e603a00bcf0e240cc79d51ac1e9ec3514 | Implement Equals(object obj) for SortingPreference to fix VS complain | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Models/Sorting/SortingPreference.cs | WalletWasabi.Gui/Models/Sorting/SortingPreference.cs | using System;
using System.Diagnostics.CodeAnalysis;
namespace WalletWasabi.Gui.Models.Sorting
{
public struct SortingPreference : IEquatable<SortingPreference>
{
public SortingPreference(SortOrder sortOrder, string colTarget)
{
SortOrder = sortOrder;
ColumnTarget = colTarget;
}
public SortOrder SortOrder { get; set; }
public string ColumnTarget { get; set; }
public SortOrder Match(SortOrder targetOrd, string match)
{
return ColumnTarget == match ? targetOrd : SortOrder.None;
}
#region EqualityAndComparison
public override bool Equals(object obj)
{
if (obj is SortingPreference sp)
{
return Equals(sp);
}
else
{
return false;
}
}
public bool Equals(SortingPreference other) => this == other;
public override int GetHashCode() => (SortOrder, ColumnTarget).GetHashCode();
public static bool operator ==(SortingPreference x, SortingPreference y)
=> (x.SortOrder, x.ColumnTarget) == (y.SortOrder, y.ColumnTarget);
public static bool operator !=(SortingPreference x, SortingPreference y) => !(x == y);
#endregion EqualityAndComparison
}
}
| using System;
using System.Diagnostics.CodeAnalysis;
namespace WalletWasabi.Gui.Models.Sorting
{
public struct SortingPreference : IEquatable<SortingPreference>
{
public SortingPreference(SortOrder sortOrder, string colTarget)
{
SortOrder = sortOrder;
ColumnTarget = colTarget;
}
public SortOrder SortOrder { get; set; }
public string ColumnTarget { get; set; }
public SortOrder Match(SortOrder targetOrd, string match)
{
return ColumnTarget == match ? targetOrd : SortOrder.None;
}
#region EqualityAndComparison
public bool Equals(SortingPreference other) => this == other;
public override int GetHashCode() => (SortOrder, ColumnTarget).GetHashCode();
public static bool operator ==(SortingPreference x, SortingPreference y)
=> (x.SortOrder, x.ColumnTarget) == (y.SortOrder, y.ColumnTarget);
public static bool operator !=(SortingPreference x, SortingPreference y) => !(x == y);
#endregion EqualityAndComparison
}
}
| mit | C# |
8f7e23cb329f2a98fc6db4cc2abc7d1a00346f3a | fix for release build | fealty/Frost | Frost.DirectX.Composition/CompositionDevice.cs | Frost.DirectX.Composition/CompositionDevice.cs | // Copyright (c) 2012, Joshua Burke
// All rights reserved.
//
// See LICENSE for more information.
using System;
using System.Diagnostics.Contracts;
using SharpDX.DXGI;
using SharpDX.Direct3D10;
using Device = SharpDX.Direct3D10.Device;
using Device1 = SharpDX.Direct3D10.Device1;
namespace Frost.DirectX.Composition
{
public sealed class CompositionDevice : IDisposable
{
private readonly Device _Device3D;
private readonly Lazy<Factory1> _DxgiFactory;
private readonly Compositor _ImmediateContext;
public CompositionDevice(Adapter1 adapter, Device2D device2D)
{
Contract.Requires(device2D != null);
_DxgiFactory = new Lazy<Factory1>();
Adapter1 newAdapter = adapter;
if(adapter == null)
{
newAdapter = _DxgiFactory.Value.GetAdapter1(0);
}
#if DEBUG
_Device3D = new Device1(
newAdapter, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, FeatureLevel.Level_10_0);
#else
_Device3D = new Device1(
newAdapter,
DeviceCreationFlags.BgraSupport,
FeatureLevel.Level_10_0);
#endif
if(adapter == null)
{
newAdapter.Dispose();
}
_ImmediateContext = new Compositor(_Device3D, device2D);
device2D.Effects.Register<ColorOutputEffect>();
device2D.Effects.Register<GaussianBlurEffect>();
device2D.Effects.Register<DropShadowEffect>();
device2D.Effects.Register<BoxBlurEffect>();
}
public Device Device3D
{
get { return _Device3D; }
}
public Frost.Composition.Compositor ImmediateContext
{
get { return _ImmediateContext; }
}
public void Dispose()
{
Dispose(true);
}
public void SignalUpdate()
{
_ImmediateContext.FrameBatchCount.Reset();
_ImmediateContext.FrameDuration.Reset();
}
private void Dispose(bool disposing)
{
if(disposing)
{
_ImmediateContext.Dispose();
if(_DxgiFactory.IsValueCreated)
{
_DxgiFactory.Value.Dispose();
}
}
}
}
} | // Copyright (c) 2012, Joshua Burke
// All rights reserved.
//
// See LICENSE for more information.
using System;
using System.Diagnostics.Contracts;
using SharpDX.DXGI;
using SharpDX.Direct3D10;
using Device = SharpDX.Direct3D10.Device;
using Device1 = SharpDX.Direct3D10.Device1;
namespace Frost.DirectX.Composition
{
public sealed class CompositionDevice : IDisposable
{
private readonly Device _Device3D;
private readonly Lazy<Factory1> _DxgiFactory;
private readonly Compositor _ImmediateContext;
public CompositionDevice(Adapter1 adapter, Device2D device2D)
{
Contract.Requires(device2D != null);
_DxgiFactory = new Lazy<Factory1>();
Adapter1 newAdapter = adapter;
if(adapter == null)
{
newAdapter = _DxgiFactory.Value.GetAdapter1(0);
}
#if DEBUG
_Device3D = new Device1(
newAdapter, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, FeatureLevel.Level_10_0);
#else
mDevice3D = new Device1(
newAdapter,
DeviceCreationFlags.BgraSupport,
FeatureLevel.Level_10_0);
#endif
if(adapter == null)
{
newAdapter.Dispose();
}
_ImmediateContext = new Compositor(_Device3D, device2D);
device2D.Effects.Register<ColorOutputEffect>();
device2D.Effects.Register<GaussianBlurEffect>();
device2D.Effects.Register<DropShadowEffect>();
device2D.Effects.Register<BoxBlurEffect>();
}
public Device Device3D
{
get { return _Device3D; }
}
public Frost.Composition.Compositor ImmediateContext
{
get { return _ImmediateContext; }
}
public void Dispose()
{
Dispose(true);
}
public void SignalUpdate()
{
_ImmediateContext.FrameBatchCount.Reset();
_ImmediateContext.FrameDuration.Reset();
}
private void Dispose(bool disposing)
{
if(disposing)
{
_ImmediateContext.Dispose();
if(_DxgiFactory.IsValueCreated)
{
_DxgiFactory.Value.Dispose();
}
}
}
}
} | bsd-2-clause | C# |
a7d4d84b3608627d25a4aca5c49ba3a35202708f | Support Daily commendations | glitch100/Halo-API | HaloEzAPI/Abstraction/Enum/CommendationType.cs | HaloEzAPI/Abstraction/Enum/CommendationType.cs | namespace HaloEzAPI.Abstraction.Enum
{
public enum CommendationType
{
Progressive,
Meta,
Daily
}
} | namespace HaloEzAPI.Abstraction.Enum
{
public enum CommendationType
{
Progressive,
Meta
}
} | mit | C# |
90fd7ac037876e202748b38b36ec91a3826f6a9e | Change to using TypeCatalog instead of AssemblyCatalog | danielpalme/IocPerformance,seesharper/IocPerformance,lamLeX/IocPerformance,z4kn4fein/IocPerformance,dadhi/IocPerformance,kool79/IocPerformance | IocPerformance/Adapters/MefContainerAdapter.cs | IocPerformance/Adapters/MefContainerAdapter.cs | using System.ComponentModel.Composition.Hosting;
namespace IocPerformance.Adapters
{
public sealed class MefContainerAdapter : IContainerAdapter
{
private CompositionContainer container;
public void Prepare()
{
var catalog = new TypeCatalog(typeof(Implementation1), typeof(Implementation2), typeof(Combined));
this.container = new CompositionContainer(catalog);
}
public T Resolve<T>() where T : class
{
return this.container.GetExportedValue<T>();
}
public void Dispose()
{
// Allow the container and everything it references to be disposed.
this.container = null;
}
}
}
| using System.ComponentModel.Composition.Hosting;
namespace IocPerformance.Adapters
{
public sealed class MefContainerAdapter : IContainerAdapter
{
private CompositionContainer container;
public void Prepare()
{
var catalog = new AssemblyCatalog(typeof(Program).Assembly);
this.container = new CompositionContainer(catalog);
}
public T Resolve<T>() where T : class
{
return this.container.GetExportedValue<T>();
}
public void Dispose()
{
this.container = null;
}
}
}
| apache-2.0 | C# |
0e4133bd0ac2c7b15e1ab12a6448eb559b6433fb | Make LinkCommand implement ICommand | appharbor/appharbor-cli | src/AppHarbor/Commands/LinkCommand.cs | src/AppHarbor/Commands/LinkCommand.cs | using System;
namespace AppHarbor.Commands
{
public class LinkCommand : ICommand
{
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
| namespace AppHarbor.Commands
{
public class LinkCommand
{
}
}
| mit | C# |
c68734e9b7cb3a62d9794f17c81dcb52a33bd067 | fix the ProcessWork reference | jacksonh/manos,jmptrader/manos,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,jmptrader/manos | src/Manos/Manos.Threading/Boundary.cs | src/Manos/Manos.Threading/Boundary.cs | //
// Copyright (C) 2011 Robin Duerden (rduerden@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
//
using System;
using Manos.IO;
using Libev;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
namespace Manos.Threading
{
public class Boundary : IBoundary
{
public static readonly Boundary Instance = new Boundary (IOLoop.Instance);
private readonly AsyncWatcher asyncWatcher;
private readonly ConcurrentQueue<Action> workQueue;
private int maxWorkPerLoop;
public Boundary( IOLoop loop ) : this( loop, 18 ) {}
public Boundary( IOLoop loop, int maxWorkPerLoop )
{
asyncWatcher = new AsyncWatcher ((LibEvLoop)loop.EventLoop, ( l, w, et ) => ProcessWork());
asyncWatcher.Start ();
workQueue = new ConcurrentQueue<Action> ();
this.maxWorkPerLoop = maxWorkPerLoop;
}
public void ExecuteOnTargetLoop (Action action)
{
workQueue.Enqueue (action);
asyncWatcher.Send ();
}
private void ProcessWork ()
{
int remaining = maxWorkPerLoop + 1;
while( --remaining > 0 ) {
Action action;
if( workQueue.TryDequeue (out action)) {
try {
action();
}
catch (Exception ex) {
Console.WriteLine ("Error in processing synchronized action");
Console.WriteLine (ex);
}
}
else break;
}
if (remaining < 0) asyncWatcher.Send ();
}
}
}
| //
// Copyright (C) 2011 Robin Duerden (rduerden@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
//
using System;
using Manos.IO;
using Libev;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
namespace Manos.Threading
{
public class Boundary : IBoundary
{
public static readonly Boundary Instance = new Boundary (IOLoop.Instance);
private readonly AsyncWatcher asyncWatcher;
private readonly ConcurrentQueue<Action> workQueue;
private int maxWorkPerLoop;
public Boundary( IOLoop loop ) : this( loop, 18 ) {}
public Boundary( IOLoop loop, int maxWorkPerLoop )
{
asyncWatcher = new AsyncWatcher ((LibEvLoop)loop.EventLoop, ( l, w, et ) => processWork());
asyncWatcher.Start ();
workQueue = new ConcurrentQueue<Action> ();
this.maxWorkPerLoop = maxWorkPerLoop;
}
public void ExecuteOnTargetLoop (Action action)
{
workQueue.Enqueue (action);
asyncWatcher.Send ();
}
private void ProcessWork ()
{
int remaining = maxWorkPerLoop + 1;
while( --remaining > 0 ) {
Action action;
if( workQueue.TryDequeue (out action)) {
try {
action();
}
catch (Exception ex) {
Console.WriteLine ("Error in processing synchronized action");
Console.WriteLine (ex);
}
}
else break;
}
if (remaining < 0) asyncWatcher.Send ();
}
}
}
| mit | C# |
d6ed4b6fdd86cfcc9e37274d27b05310763cd642 | fix member access | wikibus/Argolis | src/Lernaean.Hydra/Discovery/SupportedOperations/SupportedOperationsOfT.cs | src/Lernaean.Hydra/Discovery/SupportedOperations/SupportedOperationsOfT.cs | using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace Hydra.Discovery.SupportedOperations
{
/// <summary>
/// Base class for setting up operations supported by class <typeparamref name="T" />
/// </summary>
/// <typeparam name="T">the supported class type</typeparam>
public abstract class SupportedOperations<T> : SupportedOperations
{
/// <summary>
/// Initializes a new instance of the <see cref="SupportedOperations{T}"/> class.
/// </summary>
protected SupportedOperations() : base(typeof(T))
{
}
/// <summary>
/// Allows the setup of an operation supported by a property
/// </summary>
/// <typeparam name="TReturn">Property return type.</typeparam>
protected SupportedOperationBuilder Property<TReturn>(Expression<Func<T, TReturn>> propertyExpression)
{
PropertyInfo propertyInfo = (PropertyInfo)((MemberExpression)propertyExpression.Body).Member;
if (PropertyOperations.ContainsKey(propertyInfo) == false)
{
PropertyOperations[propertyInfo] = new List<OperationMeta>();
}
return new SupportedOperationBuilder(PropertyOperations[propertyInfo]);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace Hydra.Discovery.SupportedOperations
{
/// <summary>
/// Base class for setting up operations supported by class <typeparamref name="T" />
/// </summary>
/// <typeparam name="T">the supported class type</typeparam>
public abstract class SupportedOperations<T> : SupportedOperations
{
/// <summary>
/// Initializes a new instance of the <see cref="SupportedOperations{T}"/> class.
/// </summary>
protected SupportedOperations() : base(typeof(T))
{
}
/// <summary>
/// Allows the setup of an operation supported by a property
/// </summary>
protected SupportedOperationBuilder Property(Expression<Func<T, object>> propertyExpression)
{
PropertyInfo propertyInfo = (PropertyInfo)((MemberExpression)propertyExpression.Body).Member;
if (PropertyOperations.ContainsKey(propertyInfo) == false)
{
PropertyOperations[propertyInfo] = new List<OperationMeta>();
}
return new SupportedOperationBuilder(PropertyOperations[propertyInfo]);
}
}
}
| mit | C# |
a5dac7ff72bab3ca2db9ad9b839b6c43131d104c | 更新.NET 4.5项目版本号 | JeffreySu/WxOpen,JeffreySu/WxOpen | src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Properties/AssemblyInfo.cs | src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Senparc.Weixin.WxOpen")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Senparc.Weixin.WxOpen")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("379d8c97-4f96-45af-9f91-6bd160514495")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.6.1.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Senparc.Weixin.WxOpen")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Senparc.Weixin.WxOpen")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("379d8c97-4f96-45af-9f91-6bd160514495")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.5.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
3585dce0579b5ba36cf4c3fab325dbe77f86ee03 | Fix Unit Test | MartinChavez/CSharp | SchoolOfCSharp/Parameters/DefaultParameters.cs | SchoolOfCSharp/Parameters/DefaultParameters.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Parameters
{
[TestClass]
public class DefaultParameters
{
[TestMethod]
public void DefaultParametersWithoutParameter()
{
//GetString will execute using the default parameter of 'OptionalString'
Assert.AreEqual(GetString(), "OptionalString");
}
[TestMethod]
public void DefaultParametersWithParameter()
{
//GetString will execute using the para,eter defined at the method's execution
Assert.AreEqual(GetString("NewString"), "NewString");
}
[TestMethod]
public void NamedParameters()
{
//By stating the name of the optional parameter, the code becomes more readable
Assert.AreEqual(GetNull(nullParam: "NewString"), "NewString");
}
private static string GetString(string optionalString = "OptionalString") //You can specify the method signature with default values
{
return optionalString;
}
private static string GetNull(string nullParam = null) //You can define reference Types with default param as null
{
return nullParam;
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Parameters
{
[TestClass]
public class DefaultParameters
{
[TestMethod]
public void DefaultParametersWithoutParameter()
{
//GetString will execute using the default parameter of 'OptionalString'
Assert.AreEqual(GetString(), "OptionalString");
}
[TestMethod]
public void DefaultParametersWithParameter()
{
//GetString will execute using the para,eter defined at the method's execution
Assert.AreEqual(GetString("NewString"), "NewString");
}
[TestMethod]
public void NamedParameters()
{
//By stating the name of the optional parameter, the code becomes more readable
Assert.AreEqual(GetString(optionalString : "NewString"), "NewString");
}
private static string GetString(string optionalString = "OptionalString") //You can specify the method signature with default values
{
return optionalString;
}
}
}
| mit | C# |
b06f12d887e16ff5f68a7eb9d941ccc88f6b6404 | Implement window toggle | DMagic1/KSP_Better_Maneuvering | Source/BetterManeuvering.Unity/ManeuverSnap.cs | Source/BetterManeuvering.Unity/ManeuverSnap.cs | using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace BetterManeuvering.Unity
{
public class ManeuverSnap : MonoBehaviour, IBeginDragHandler, IDragHandler, IPointerEnterHandler, IPointerExitHandler
{
public Toggle WindowToggle = null;
public GameObject NextOrbit = null;
public GameObject PreviousOrbit = null;
public GameObject Apo = null;
public GameObject Peri = null;
public GameObject NextPatch = null;
public GameObject PreviousPatch = null;
public GameObject EqAsc = null;
public GameObject EqDesc = null;
public GameObject RelAsc = null;
public GameObject RelDesc = null;
public GameObject ClApp = null;
public GameObject Reset = null;
public Button NextOrbitButton = null;
public Button PreviousOrbitButton = null;
public Button ApoButton = null;
public Button PeriButton = null;
public Button NextPatchButton = null;
public Button PreviousPatchButton = null;
public Button EqAscButton = null;
public Button EqDescButton = null;
public Button RelAscButton = null;
public Button RelDescButton = null;
public Button ClAppButton = null;
public Button ResetButton = null;
public Transform TitleTransform = null;
public TextHandler CurrentTime = null;
public TextHandler ApoTime = null;
public TextHandler PeriTime = null;
public TextHandler NOTime = null;
public TextHandler POTime = null;
public TextHandler NPTime = null;
public TextHandler PPTime = null;
public TextHandler EqAscTime = null;
public TextHandler EqDescTime = null;
public TextHandler RelAscTime = null;
public TextHandler RelDescTime = null;
public TextHandler ApproachTime = null;
public TextHandler ResetTime = null;
private RectTransform rect;
private Vector2 mouseStart;
private Vector3 windowStart;
public class OnDragEvent : UnityEvent<RectTransform> { }
public class OnMouseEvent : UnityEvent<bool> { }
public OnDragEvent DragEvent = new OnDragEvent();
public OnMouseEvent MouseOverEvent = new OnMouseEvent();
private void Awake()
{
rect = GetComponent<RectTransform>();
}
private void OnDestroy()
{
gameObject.SetActive(false);
Destroy(gameObject);
}
public void OnBeginDrag(PointerEventData eventData)
{
if (rect == null)
return;
mouseStart = eventData.position;
windowStart = rect.position;
}
public void OnDrag(PointerEventData eventData)
{
if (rect == null)
return;
rect.position = windowStart + (Vector3)(eventData.position - mouseStart);
DragEvent.Invoke(rect);
}
public void OnPointerEnter(PointerEventData eventData)
{
MouseOverEvent.Invoke(true);
}
public void OnPointerExit(PointerEventData eventData)
{
MouseOverEvent.Invoke(false);
}
}
}
| using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace BetterManeuvering.Unity
{
public class ManeuverSnap : MonoBehaviour, IBeginDragHandler, IDragHandler, IPointerEnterHandler, IPointerExitHandler
{
public GameObject NextOrbit = null;
public GameObject PreviousOrbit = null;
public GameObject Apo = null;
public GameObject Peri = null;
public GameObject NextPatch = null;
public GameObject PreviousPatch = null;
public GameObject EqAsc = null;
public GameObject EqDesc = null;
public GameObject RelAsc = null;
public GameObject RelDesc = null;
public GameObject ClApp = null;
public GameObject Reset = null;
public Button NextOrbitButton = null;
public Button PreviousOrbitButton = null;
public Button ApoButton = null;
public Button PeriButton = null;
public Button NextPatchButton = null;
public Button PreviousPatchButton = null;
public Button EqAscButton = null;
public Button EqDescButton = null;
public Button RelAscButton = null;
public Button RelDescButton = null;
public Button ClAppButton = null;
public Button ResetButton = null;
public Transform TitleTransform = null;
public TextHandler CurrentTime = null;
public TextHandler ApoTime = null;
public TextHandler PeriTime = null;
public TextHandler NOTime = null;
public TextHandler POTime = null;
public TextHandler NPTime = null;
public TextHandler PPTime = null;
public TextHandler EqAscTime = null;
public TextHandler EqDescTime = null;
public TextHandler RelAscTime = null;
public TextHandler RelDescTime = null;
public TextHandler ApproachTime = null;
public TextHandler ResetTime = null;
private RectTransform rect;
private Vector2 mouseStart;
private Vector3 windowStart;
public class OnDragEvent : UnityEvent<RectTransform> { }
public class OnMouseEvent : UnityEvent<bool> { }
public OnDragEvent DragEvent = new OnDragEvent();
public OnMouseEvent MouseOverEvent = new OnMouseEvent();
private void Awake()
{
rect = GetComponent<RectTransform>();
}
private void OnDestroy()
{
gameObject.SetActive(false);
Destroy(gameObject);
}
public void OnBeginDrag(PointerEventData eventData)
{
if (rect == null)
return;
mouseStart = eventData.position;
windowStart = rect.position;
}
public void OnDrag(PointerEventData eventData)
{
if (rect == null)
return;
rect.position = windowStart + (Vector3)(eventData.position - mouseStart);
DragEvent.Invoke(rect);
}
public void OnPointerEnter(PointerEventData eventData)
{
MouseOverEvent.Invoke(true);
}
public void OnPointerExit(PointerEventData eventData)
{
MouseOverEvent.Invoke(false);
}
}
}
| mit | C# |
128e71a1c7d614ad6b9d2db312abdc1a7e0370f7 | Increment version to 0.11; remove description | whampson/bft-spec,whampson/cascara | Src/WHampson.Cascara/Properties/AssemblyInfo.cs | Src/WHampson.Cascara/Properties/AssemblyInfo.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.Cascara")]
[assembly: AssemblyProduct("WHampson.Cascara")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.11.0")]
[assembly: AssemblyVersion("0.11.0.0")]
[assembly: AssemblyInformationalVersion("0.11")]
| #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.Cascara")]
[assembly: AssemblyDescription("Binary File Template parser.")]
[assembly: AssemblyProduct("WHampson.Cascara")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.10.1")]
[assembly: AssemblyVersion("0.10.1")]
[assembly: AssemblyInformationalVersion("0.10.1")]
| mit | C# |
95a3df67a182107ecfc18dda400f5f8d060dbcee | Add Entity Framework configuration extension to support Sql Server Date column type | TheOtherTimDuncan/TOTD | TOTD.EntityFramework/ConfigurationExtensions.cs | TOTD.EntityFramework/ConfigurationExtensions.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
namespace TOTD.EntityFramework
{
public static class ConfigurationExtensions
{
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name, int order)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name, order)));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name, int order)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name, order)
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration IsIdentity(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
public static PrimitivePropertyConfiguration IsDateOnly(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnType("Date");
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
namespace TOTD.EntityFramework
{
public static class ConfigurationExtensions
{
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name, int order)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name, order)));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name, int order)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name, order)
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration IsIdentity(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
| mit | C# |
3c17619648886b427a5696936bdac00d4dbf51e9 | support for Korean identifier | inkle/ink,inkle/ink,ghostpattern/ink,ghostpattern/ink | compiler/InkParser/InkParser_CharacterRanges.cs | compiler/InkParser/InkParser_CharacterRanges.cs | using Ink.Parsed;
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Ink
{
internal partial class InkParser
{
internal static readonly CharacterRange LatinBasic =
CharacterRange.Define ('\u0041', '\u007A', excludes: new CharacterSet().AddRange('\u005B', '\u0060'));
internal static readonly CharacterRange LatinExtendedA = CharacterRange.Define('\u0100', '\u017F'); // no excludes here
internal static readonly CharacterRange LatinExtendedB = CharacterRange.Define('\u0180', '\u024F'); // no excludes here
internal static readonly CharacterRange Greek =
CharacterRange.Define('\u0370', '\u03FF', excludes: new CharacterSet().AddRange('\u0378','\u0385').AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));
internal static readonly CharacterRange Cyrillic =
CharacterRange.Define('\u0400', '\u04FF', excludes: new CharacterSet().AddRange('\u0482', '\u0489'));
internal static readonly CharacterRange Armenian =
CharacterRange.Define('\u0530', '\u058F', excludes: new CharacterSet().AddCharacters("\u0530").AddRange('\u0557', '\u0560').AddRange('\u0588', '\u058E'));
internal static readonly CharacterRange Hebrew =
CharacterRange.Define('\u0590', '\u05FF', excludes: new CharacterSet());
internal static readonly CharacterRange Arabic =
CharacterRange.Define('\u0600', '\u06FF', excludes: new CharacterSet());
internal static readonly CharacterRange Korean =
CharacterRange.Define('\uAC00', '\uD7AF', excludes: new CharacterSet());
private void ExtendIdentifierCharacterRanges(CharacterSet identifierCharSet)
{
var characterRanges = ListAllCharacterRanges();
foreach (var charRange in characterRanges)
{
identifierCharSet.AddCharacters(charRange.ToCharacterSet());
}
}
/// <summary>
/// Gets an array of <see cref="CharacterRange" /> representing all of the currently supported
/// non-ASCII character ranges that can be used in identifier names.
/// </summary>
/// <returns>
/// An array of <see cref="CharacterRange" /> representing all of the currently supported
/// non-ASCII character ranges that can be used in identifier names.
/// </returns>
internal static CharacterRange[] ListAllCharacterRanges() {
return new CharacterRange[] {
LatinBasic,
LatinExtendedA,
LatinExtendedB,
Arabic,
Armenian,
Cyrillic,
Greek,
Hebrew,
Korean,
};
}
}
}
| using Ink.Parsed;
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Ink
{
internal partial class InkParser
{
internal static readonly CharacterRange LatinBasic =
CharacterRange.Define ('\u0041', '\u007A', excludes: new CharacterSet().AddRange('\u005B', '\u0060'));
internal static readonly CharacterRange LatinExtendedA = CharacterRange.Define('\u0100', '\u017F'); // no excludes here
internal static readonly CharacterRange LatinExtendedB = CharacterRange.Define('\u0180', '\u024F'); // no excludes here
internal static readonly CharacterRange Greek =
CharacterRange.Define('\u0370', '\u03FF', excludes: new CharacterSet().AddRange('\u0378','\u0385').AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));
internal static readonly CharacterRange Cyrillic =
CharacterRange.Define('\u0400', '\u04FF', excludes: new CharacterSet().AddRange('\u0482', '\u0489'));
internal static readonly CharacterRange Armenian =
CharacterRange.Define('\u0530', '\u058F', excludes: new CharacterSet().AddCharacters("\u0530").AddRange('\u0557', '\u0560').AddRange('\u0588', '\u058E'));
internal static readonly CharacterRange Hebrew =
CharacterRange.Define('\u0590', '\u05FF', excludes: new CharacterSet());
internal static readonly CharacterRange Arabic =
CharacterRange.Define('\u0600', '\u06FF', excludes: new CharacterSet());
private void ExtendIdentifierCharacterRanges(CharacterSet identifierCharSet)
{
var characterRanges = ListAllCharacterRanges();
foreach (var charRange in characterRanges)
{
identifierCharSet.AddCharacters(charRange.ToCharacterSet());
}
}
/// <summary>
/// Gets an array of <see cref="CharacterRange" /> representing all of the currently supported
/// non-ASCII character ranges that can be used in identifier names.
/// </summary>
/// <returns>
/// An array of <see cref="CharacterRange" /> representing all of the currently supported
/// non-ASCII character ranges that can be used in identifier names.
/// </returns>
internal static CharacterRange[] ListAllCharacterRanges() {
return new CharacterRange[] {
LatinBasic,
LatinExtendedA,
LatinExtendedB,
Arabic,
Armenian,
Cyrillic,
Greek,
Hebrew,
};
}
}
}
| mit | C# |
93f4c6b340f05b50592c3aa50b869bc4ab64effa | Update TokenChannel.cs | b3b00/csly | sly/lexer/TokenChannel.cs | sly/lexer/TokenChannel.cs | using System.Collections.Generic;
using System.Text;
using System.Diagnostics.CodeAnalysis;
namespace sly.lexer
{
public class TokenChannel<IN>
{
public readonly List<Token<IN>> Tokens;
public int ChannelId;
public int Count => Tokens.Count;
public TokenChannel(List<Token<IN>> tokens, int channelId)
{
Tokens = tokens;
ChannelId = channelId;
}
public TokenChannel(int channelId) : this(new List<Token<IN>>(),channelId)
{
}
private Token<IN> GetToken(int i)
{
return Tokens[i];
}
private void SetToken(int i, Token<IN> token)
{
if (i >= Tokens.Count)
{
for (int j = Tokens.Count; j <= i; j++)
{
Tokens.Add(null);
}
}
Tokens[i] = token;
}
public Token<IN> this[int key]
{
get => GetToken(key);
set => SetToken(key,value);
}
public void Add(Token<IN> token)
{
Tokens.Add(token);
if (token != null)
token.PositionInTokenFlow = Tokens.Count;
}
[ExcludeFromCodeCoverage]
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("#").Append(ChannelId).Append(" ");
foreach (var token in Tokens)
{
if (token != null)
{
builder.Append(token.ToString()).Append(" > ");
}
}
return builder.ToString();
}
}
}
| using System.Collections.Generic;
using System.Text;
namespace sly.lexer
{
public class TokenChannel<IN>
{
public readonly List<Token<IN>> Tokens;
public int ChannelId;
public int Count => Tokens.Count;
public TokenChannel(List<Token<IN>> tokens, int channelId)
{
Tokens = tokens;
ChannelId = channelId;
}
public TokenChannel(int channelId) : this(new List<Token<IN>>(),channelId)
{
}
private Token<IN> GetToken(int i)
{
return Tokens[i];
}
private void SetToken(int i, Token<IN> token)
{
if (i >= Tokens.Count)
{
for (int j = Tokens.Count; j <= i; j++)
{
Tokens.Add(null);
}
}
Tokens[i] = token;
}
public Token<IN> this[int key]
{
get => GetToken(key);
set => SetToken(key,value);
}
public void Add(Token<IN> token)
{
Tokens.Add(token);
if (token != null)
token.PositionInTokenFlow = Tokens.Count;
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("#").Append(ChannelId).Append(" ");
foreach (var token in Tokens)
{
if (token != null)
{
builder.Append(token.ToString()).Append(" > ");
}
}
return builder.ToString();
}
}
} | mit | C# |
07da4fcb2b78434272593d52283f91bb23dcc4e2 | Update Pettable.cs | fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation | UnityProject/Assets/Scripts/Player/Pettable.cs | UnityProject/Assets/Scripts/Player/Pettable.cs | using UnityEngine;
/// <summary>
/// Allows an object to be pet by a player.
/// </summary>
public class Pettable : MonoBehaviour, IClientInteractable<PositionalHandApply>
{
public bool Interact(PositionalHandApply interaction)
{
var targetNPCHealth = interaction.TargetObject.GetComponent<LivingHealthBehaviour>();
var performerPlayerHealth = interaction.Performer.GetComponent<PlayerHealth>();
var performerRegisterPlayer = interaction.Performer.GetComponent<RegisterPlayer>();
// Is the target in range for a pet? Is the target conscious for the pet? Is the performer's intent set to help?
// Is the performer's hand empty? Is the performer not stunned/downed? Is the performer conscious to perform the interaction?
// Is the performer interacting with itself?
if (!PlayerManager.LocalPlayerScript.IsInReach(interaction.WorldPositionTarget, false) ||
targetNPCHealth.ConsciousState != ConsciousState.CONSCIOUS ||
UIManager.CurrentIntent != Intent.Help ||
interaction.HandObject != null ||
performerPlayerHealth.ConsciousState != ConsciousState.CONSCIOUS ||
performerRegisterPlayer.IsLayingDown ||
interaction.Performer == interaction.TargetObject)
{
return false;
}
Chat.AddActionMsgToChat(interaction.Performer,
$"You pet {interaction.TargetObject.name}.", $"{interaction.Performer.ExpensiveName()} pets {interaction.TargetObject.name}.");
return true;
}
} | using UnityEngine;
/// <summary>
/// Allows an object to be hugged by a player.
/// </summary>
public class Pettable : MonoBehaviour, IClientInteractable<PositionalHandApply>
{
public bool Interact(PositionalHandApply interaction)
{
var targetNPCHealth = interaction.TargetObject.GetComponent<LivingHealthBehaviour>();
var performerPlayerHealth = interaction.Performer.GetComponent<PlayerHealth>();
var performerRegisterPlayer = interaction.Performer.GetComponent<RegisterPlayer>();
// Is the target in range for a hug? Is the target conscious for the hug? Is the performer's intent set to help?
// Is the performer's hand empty? Is the performer not stunned/downed? Is the performer conscious to perform the interaction?
// Is the performer interacting with itself?
if (!PlayerManager.LocalPlayerScript.IsInReach(interaction.WorldPositionTarget, false) ||
targetNPCHealth.ConsciousState != ConsciousState.CONSCIOUS ||
UIManager.CurrentIntent != Intent.Help ||
interaction.HandObject != null ||
performerPlayerHealth.ConsciousState != ConsciousState.CONSCIOUS ||
performerRegisterPlayer.IsLayingDown ||
interaction.Performer == interaction.TargetObject)
{
return false;
}
Chat.AddActionMsgToChat(interaction.Performer,
$"You pet {interaction.TargetObject.name}.", $"{interaction.Performer.ExpensiveName()} pets {interaction.TargetObject.name}.");
return true;
}
} | agpl-3.0 | C# |
935239625a74ba9107e7fe924ccee94ea824aa76 | Add a couple Enumerable utility methods for KeyValuePairs | AaronLieberman/Addle | Addle.Core/Linq/EnumerableExtensions.cs | Addle.Core/Linq/EnumerableExtensions.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Addle.Core.Linq;
using JetBrains.Annotations;
namespace Addle.Core.Linq
{
public static class EnumerableExtensions
{
static readonly object _lock = new object();
static readonly Random _random = new Random();
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list, Random random = null)
{
var array = list.ToArray();
for (var i = 0; i < array.Length - 1; i++)
{
int index;
lock (_lock)
{
index = (random ?? _random).Next(i, array.Length);
}
var swap = array[index];
array[index] = array[i];
array[i] = swap;
}
return array;
}
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
foreach (var item in list)
{
action(item);
}
}
public static IEnumerable<T> Concat<T>(this IEnumerable<T> @this, T other)
{
return @this.Concat(EnumerableEx.Return(other));
}
// ReSharper disable once InconsistentNaming
public static bool IContains(this IEnumerable<string> @this, string other)
{
return @this.Any(a => a.IEquals(other));
}
public static IOrderedEnumerable<KeyValuePair<K, V>> OrderByKey<K, V>(this IEnumerable<KeyValuePair<K, V>> list)
{
return list.OrderBy(a => a.Key);
}
public static IEnumerable<V> SelectValues<K, V>(this IEnumerable<KeyValuePair<K, V>> list)
{
foreach (var item in list)
{
yield return item.Value;
}
}
}
public static class EnumerableEx
{
public static IEnumerable<T> Return<T>(T @this)
{
yield return @this;
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Addle.Core.Linq;
using JetBrains.Annotations;
namespace Addle.Core.Linq
{
public static class EnumerableExtensions
{
static readonly object _lock = new object();
static readonly Random _random = new Random();
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list, Random random = null)
{
var array = list.ToArray();
for (var i = 0; i < array.Length - 1; i++)
{
int index;
lock (_lock)
{
index = (random ?? _random).Next(i, array.Length);
}
var swap = array[index];
array[index] = array[i];
array[i] = swap;
}
return array;
}
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
foreach (var item in list)
{
action(item);
}
}
public static IEnumerable<T> Concat<T>(this IEnumerable<T> @this, T other)
{
return @this.Concat(EnumerableEx.Return(other));
}
// ReSharper disable once InconsistentNaming
public static bool IContains(this IEnumerable<string> @this, string other)
{
return @this.Any(a => a.IEquals(other));
}
}
public static class EnumerableEx
{
public static IEnumerable<T> Return<T>(T @this)
{
yield return @this;
}
}
}
| mit | C# |
3ea90cb82eaa65a6f460b4f37121727e3caf416f | Use Equals instead operator==. | jesterret/ReClass.NET,KN4CK3R/ReClass.NET,jesterret/ReClass.NET,KN4CK3R/ReClass.NET,KN4CK3R/ReClass.NET,jesterret/ReClass.NET | ReClass.NET/Extensions/EncodingExtensions.cs | ReClass.NET/Extensions/EncodingExtensions.cs | using System;
using System.Text;
namespace ReClassNET.Extensions
{
public static class EncodingExtension
{
/// <summary>Gets the (perhaps wrong) byte count per character. Special characters may need more bytes.</summary>
/// <param name="encoding">The encoding.</param>
/// <returns>The byte count per character.</returns>
public static int GetSimpleByteCountPerChar(this Encoding encoding)
{
if (encoding.Equals(Encoding.UTF8) || encoding.Equals(Encoding.ASCII)) return 1;
if (encoding.Equals(Encoding.Unicode)) return 2;
if (encoding.Equals(Encoding.UTF32)) return 4;
throw new NotImplementedException();
}
}
}
| using System;
using System.Text;
namespace ReClassNET.Extensions
{
public static class EncodingExtension
{
/// <summary>Gets the (wrong) byte count per character. Special chars may need more bytes per character.</summary>
/// <param name="encoding">The encoding.</param>
/// <returns>The byte count per character.</returns>
public static int GetSimpleByteCountPerChar(this Encoding encoding)
{
if (encoding == Encoding.UTF8 || encoding == Encoding.ASCII) return 1;
if (encoding == Encoding.Unicode) return 2;
if (encoding == Encoding.UTF32) return 4;
throw new NotImplementedException();
}
}
}
| mit | C# |
b6493a7fe6e2535217104cf42d98af66562228d3 | Update version | gahcep/App.Refoveo | App.Refoveo/Properties/GlobalAssemblyInfo.cs | App.Refoveo/Properties/GlobalAssemblyInfo.cs | using System.Reflection;
/* General Product Information */
[assembly: AssemblyProduct("App.Refoveo")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
/* Configuration Type */
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
/* Assembly Versioning: mixture of MSDN and SemVer approaches
* MSDN Versioning: http://msdn.microsoft.com/en-us/library/51ket42z%28v=vs.110%29.aspx
* SemVer: http://semver.org/spec/v2.0.0.html
*
* Format: Major.Minor.Patch-ReleaseType.BuildNum
* - Major - for incompatible API changes (big changes)
* - Minor - for adding functionality in a backwards-compatible manner (small changes)
* - Patch - for bugfixes (increments only for "bugfix/" branch)
* - ReleaseType - additional information: either
* -- "pre-alpha" - active phase on docs creation and specifications ("dev" branch)
* -- "alpha" - active development and adding new features ("dev" branch)
* -- "beta" - feature-freeze (feature-complete), active bugfixes ("staging-qa" branch)
* -- "rc" - stabilizing code: only very critical issues are to be resolved ("staging-qa" branch)
* -- "release" - release in production ("release" branch)
* -- "release.hotfix" - rapid bugfix for release ("hotfix" branch)
*
* AssemblyVersion - defines a version for the product itself
* -- format: Major.Minor.0
* AssemblyFileVersion - defines a version for particular assembly
* -- format: Major.Minor.Patch
* AssemblyInformationalVersion - defines detailed version for the product and assemblies
* -- format: Major.Minor.Patch-ReleaseType.BuildNumber
*
* {develop} branch contains ONLY alpha version
*/
[assembly: AssemblyVersion("0.7.0")]
[assembly: AssemblyFileVersion("0.7.0")]
[assembly: AssemblyInformationalVersion("0.7.0-alpha.8")]
| using System.Reflection;
/* General Product Information */
[assembly: AssemblyProduct("App.Refoveo")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
/* Configuration Type */
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
/* Assembly Versioning: mixture of MSDN and SemVer approaches
* MSDN Versioning: http://msdn.microsoft.com/en-us/library/51ket42z%28v=vs.110%29.aspx
* SemVer: http://semver.org/spec/v2.0.0.html
*
* Format: Major.Minor.Patch-ReleaseType.BuildNum
* - Major - for incompatible API changes (big changes)
* - Minor - for adding functionality in a backwards-compatible manner (small changes)
* - Patch - for bugfixes (increments only for "bugfix/" branch)
* - ReleaseType - additional information: either
* -- "pre-alpha" - active phase on docs creation and specifications ("dev" branch)
* -- "alpha" - active development and adding new features ("dev" branch)
* -- "beta" - feature-freeze (feature-complete), active bugfixes ("staging-qa" branch)
* -- "rc" - stabilizing code: only very critical issues are to be resolved ("staging-qa" branch)
* -- "release" - release in production ("release" branch)
* -- "release.hotfix" - rapid bugfix for release ("hotfix" branch)
*
* AssemblyVersion - defines a version for the product itself
* -- format: Major.Minor.0
* AssemblyFileVersion - defines a version for particular assembly
* -- format: Major.Minor.Patch
* AssemblyInformationalVersion - defines detailed version for the product and assemblies
* -- format: Major.Minor.Patch-ReleaseType.BuildNumber
*
* {develop} branch contains ONLY alpha version
*/
[assembly: AssemblyVersion("0.6.0")]
[assembly: AssemblyFileVersion("0.6.0")]
[assembly: AssemblyInformationalVersion("0.6.0-alpha.7")]
| mit | C# |
2fe268b0d14aadcd9dfaba817224fe6e3c353ee2 | Update CoreModule.cs | tiksn/TIKSN-Framework | TIKSN.Core/DependencyInjection/CoreModule.cs | TIKSN.Core/DependencyInjection/CoreModule.cs | using Autofac;
using TIKSN.Data.Mongo;
using TIKSN.Serialization;
using TIKSN.Web.Rest;
namespace TIKSN.DependencyInjection
{
public class CoreModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<DotNetXmlDeserializer>().AsSelf().SingleInstance();
builder.RegisterType<DotNetXmlSerializer>().AsSelf().SingleInstance();
builder.RegisterType<JsonDeserializer>().AsSelf().SingleInstance();
builder.RegisterType<JsonSerializer>().AsSelf().SingleInstance();
builder.RegisterType<RestRequester>().As<IRestRequester>();
builder.RegisterType<SerializationRestFactory>().As<ISerializerRestFactory>().As<IDeserializerRestFactory>()
.SingleInstance();
builder.RegisterType<MongoClientSessionContext>()
.As<IMongoClientSessionStore>()
.As<IMongoClientSessionProvider>()
.InstancePerLifetimeScope();
}
}
}
| using Autofac;
using TIKSN.Data.Mongo;
using TIKSN.Serialization;
using TIKSN.Web.Rest;
namespace TIKSN.DependencyInjection
{
public class CoreModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<DotNetXmlDeserializer>().AsSelf().SingleInstance();
builder.RegisterType<DotNetXmlSerializer>().AsSelf().SingleInstance();
builder.RegisterType<JsonDeserializer>().AsSelf().SingleInstance();
builder.RegisterType<JsonSerializer>().AsSelf().SingleInstance();
builder.RegisterType<RestRequester>().As<IRestRequester>();
builder.RegisterType<SerializationRestFactory>().As<ISerializerRestFactory>().As<IDeserializerRestFactory>().SingleInstance();
builder.RegisterType<MongoClientSessionContext>()
.As<IMongoClientSessionStore>()
.As<IMongoClientSessionProvider>()
.InstancePerLifetimeScope();
}
}
} | mit | C# |
ffa2034d10af746240cc112be42039c15e137c4a | update to latest canonical data (#1323) | robkeim/xcsharp,exercism/xcsharp,robkeim/xcsharp,exercism/xcsharp | exercises/leap/LeapTest.cs | exercises/leap/LeapTest.cs | // This file was auto-generated based on version 1.6.0 of the canonical data.
using Xunit;
public class LeapTest
{
[Fact]
public void Year_not_divisible_by_4_in_common_year()
{
Assert.False(Leap.IsLeapYear(2015));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_2_not_divisible_by_4_in_common_year()
{
Assert.False(Leap.IsLeapYear(1970));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_4_not_divisible_by_100_in_leap_year()
{
Assert.True(Leap.IsLeapYear(1996));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_4_and_5_is_still_a_leap_year()
{
Assert.True(Leap.IsLeapYear(1960));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_100_not_divisible_by_400_in_common_year()
{
Assert.False(Leap.IsLeapYear(2100));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_100_but_not_by_3_is_still_not_a_leap_year()
{
Assert.False(Leap.IsLeapYear(1900));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_400_in_leap_year()
{
Assert.True(Leap.IsLeapYear(2000));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_400_but_not_by_125_is_still_a_leap_year()
{
Assert.True(Leap.IsLeapYear(2400));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_200_not_divisible_by_400_in_common_year()
{
Assert.False(Leap.IsLeapYear(1800));
}
} | // This file was auto-generated based on version 1.5.1 of the canonical data.
using Xunit;
public class LeapTest
{
[Fact]
public void Year_not_divisible_by_4_in_common_year()
{
Assert.False(Leap.IsLeapYear(2015));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_2_not_divisible_by_4_in_common_year()
{
Assert.False(Leap.IsLeapYear(1970));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_4_not_divisible_by_100_in_leap_year()
{
Assert.True(Leap.IsLeapYear(1996));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_100_not_divisible_by_400_in_common_year()
{
Assert.False(Leap.IsLeapYear(2100));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_400_in_leap_year()
{
Assert.True(Leap.IsLeapYear(2000));
}
[Fact(Skip = "Remove to run test")]
public void Year_divisible_by_200_not_divisible_by_400_in_common_year()
{
Assert.False(Leap.IsLeapYear(1800));
}
} | mit | C# |
d7ed0eab544585d113b1f3bc845735ae1683c55a | add try.catch | sebastus/AzureFunctionForSplunk | shared/sendToSplunk.csx | shared/sendToSplunk.csx | #r "Newtonsoft.Json"
using System;
using System.Dynamic;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class SingleHttpClientInstance
{
private static readonly HttpClient HttpClient;
static SingleHttpClientInstance()
{
HttpClient = new HttpClient();
}
public static async Task<HttpResponseMessage> SendToSplunk(HttpRequestMessage req)
{
HttpResponseMessage response = await HttpClient.SendAsync(req);
return response;
}
}
static async Task SendMessagesToSplunk(string[] messages, TraceWriter log)
{
var converter = new ExpandoObjectConverter();
ServicePointManager.ServerCertificateValidationCallback =
new System.Net.Security.RemoteCertificateValidationCallback(
delegate { return true; });
var client = new SingleHttpClientInstance();
string newClientContent = "";
foreach (var message in messages)
{
bool parsedOk = true;
try {
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(message, converter);
} catch (Exception e) {
parsedOk = false;
log.Info($"Error {e} caught while parsing message: {message}");
}
if (parsedOk) {
foreach (var record in obj.records)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(record);
newClientContent += "{\"event\": " + json + "}";
}
}
}
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "https://asplunktest.westus.cloudapp.azure.com:8088/services/collector/event");
req.Headers.Accept.Clear();
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
req.Headers.Add("Authorization", "Splunk 73A24AB7-60DD-4235-BF71-D892AE47F49D");
req.Content = new StringContent(newClientContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await SingleHttpClientInstance.SendToSplunk(req);
}
| #r "Newtonsoft.Json"
using System;
using System.Dynamic;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class SingleHttpClientInstance
{
private static readonly HttpClient HttpClient;
static SingleHttpClientInstance()
{
HttpClient = new HttpClient();
}
public static async Task<HttpResponseMessage> SendToSplunk(HttpRequestMessage req)
{
HttpResponseMessage response = await HttpClient.SendAsync(req);
return response;
}
}
static async Task SendMessagesToSplunk(string[] messages, TraceWriter log)
{
var converter = new ExpandoObjectConverter();
ServicePointManager.ServerCertificateValidationCallback =
new System.Net.Security.RemoteCertificateValidationCallback(
delegate { return true; });
var client = new SingleHttpClientInstance();
string newClientContent = "";
foreach (var message in messages)
{
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(message, converter);
foreach (var record in obj.records)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(record);
newClientContent += "{\"event\": " + json + "}";
}
}
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "https://asplunktest.westus.cloudapp.azure.com:8088/services/collector/event");
req.Headers.Accept.Clear();
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
req.Headers.Add("Authorization", "Splunk 73A24AB7-60DD-4235-BF71-D892AE47F49D");
req.Content = new StringContent(newClientContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await SingleHttpClientInstance.SendToSplunk(req);
}
| mit | C# |
b6b626216670392124537bfc88c27a114530a062 | Make sure debugger is attached for DebugBreak, otherwise user is prompted to attach a debugger | chrisblock/Bumblebee,kool79/Bumblebee,Bumblebee/Bumblebee,Bumblebee/Bumblebee,qchicoq/Bumblebee,qchicoq/Bumblebee,chrisblock/Bumblebee,toddmeinershagen/Bumblebee,toddmeinershagen/Bumblebee,kool79/Bumblebee | Bumblebee/Extensions/Debugging.cs | Bumblebee/Extensions/Debugging.cs | using System;
using System.Collections.Generic;
using System.Threading;
namespace Bumblebee.Extensions
{
public static class Debugging
{
public static T DebugPrint<T>(this T obj)
{
Console.WriteLine(obj.ToString());
return obj;
}
public static T DebugPrint<T>(this T obj, string message)
{
Console.WriteLine(message);
return obj;
}
public static T DebugPrint<T>(this T obj, Func<T, object> getObject)
{
Console.WriteLine(getObject(obj));
return obj;
}
public static T DebugPrint<T>(this T obj, Func<T, IEnumerable<object>> getEnumerable)
{
getEnumerable(obj).Each(Console.WriteLine);
return obj;
}
public static T DebugBreak<T>(this T obj)
{
if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
return obj;
}
public static T PlaySound<T>(this T obj, int pause = 0)
{
System.Media.SystemSounds.Exclamation.Play();
return obj.Pause(pause);
}
public static T Pause<T>(this T block, int miliseconds)
{
if (miliseconds > 0) Thread.Sleep(miliseconds);
return block;
}
}
} | using System;
using System.Collections.Generic;
using System.Threading;
namespace Bumblebee.Extensions
{
public static class Debugging
{
public static T DebugPrint<T>(this T obj)
{
Console.WriteLine(obj.ToString());
return obj;
}
public static T DebugPrint<T>(this T obj, string message)
{
Console.WriteLine(message);
return obj;
}
public static T DebugPrint<T>(this T obj, Func<T, object> getObject)
{
Console.WriteLine(getObject(obj));
return obj;
}
public static T DebugPrint<T>(this T obj, Func<T, IEnumerable<object>> getEnumerable)
{
getEnumerable(obj).Each(Console.WriteLine);
return obj;
}
public static T DebugBreak<T>(this T obj)
{
System.Diagnostics.Debugger.Break();
return obj;
}
public static T PlaySound<T>(this T obj, int pause = 0)
{
System.Media.SystemSounds.Exclamation.Play();
return obj.Pause(pause);
}
public static T Pause<T>(this T block, int miliseconds)
{
if (miliseconds > 0) Thread.Sleep(miliseconds);
return block;
}
}
} | mit | C# |
bdc430bf72a84faecd451941b241cb1e1d94a23c | fix for earlier renaming. | jyarbro/forum,jyarbro/forum,jyarbro/forum | Forum3/Views/Smileys/Index.cshtml | Forum3/Views/Smileys/Index.cshtml | @model ViewModels.Smileys.IndexPage
<div class="content-box pad">
<div asp-validation-summary="All"></div>
<form method="post" asp-action="@nameof(Smileys.Edit)">
<ol>
@if(Model.Items.Any()) {
@for (int i = 0; i < Model.Items.Count; i++) {
<li>
<input hidden="hidden" asp-for="@Model.Items[i].Id" />
<a asp-action="@nameof(Smileys.Delete)" asp-route-id="@Model.Items[i].Id" class="borderless spaced"><img alt="Delete" src="~/images/deleteSmall.png" /></a>
<img src="@Model.Items[i].Path" />
<span asp-validation-for="@Model.Items[i].Code" class="error"></span>
<input asp-for="@Model.Items[i].Code" />
<input asp-for="@Model.Items[i].Thought" />
</li>
}
}
</ol>
<ul>
<li><button>Save Changes</button></li>
<li><a class="button" href="@ViewData["Referrer"]">Cancel</a></li>
</ul>
</form>
</div>
@{ViewData["Title"] = "Smileys";}
@section PageActions {
<p>
<a class="button" asp-action="Create" asp-controller="Smileys">Create a new Smiley</a>
</p>
} | @model ViewModels.Smileys.IndexPage
<div class="content-box pad">
<div asp-validation-summary="All"></div>
<form method="post" asp-action="@nameof(Smileys.Edit)">
<ol>
@if(Model.Smileys.Any()) {
@for (int i = 0; i < Model.Smileys.Count; i++) {
<li>
<input hidden="hidden" asp-for="@Model.Smileys[i].Id" />
<a asp-action="@nameof(Smileys.Delete)" asp-route-id="@Model.Smileys[i].Id" class="borderless spaced"><img alt="Delete" src="~/images/deleteSmall.png" /></a>
<img src="@Model.Smileys[i].Path" />
<span asp-validation-for="@Model.Smileys[i].Code" class="error"></span>
<input asp-for="@Model.Smileys[i].Code" />
<input asp-for="@Model.Smileys[i].Thought" />
</li>
}
}
</ol>
<ul>
<li><button>Save Changes</button></li>
<li><a class="button" href="@ViewData["Referrer"]">Cancel</a></li>
</ul>
</form>
</div>
@{ViewData["Title"] = "Smileys";}
@section PageActions {
<p>
<a class="button" asp-action="Create" asp-controller="Smileys">Create a new Smiley</a>
</p>
} | unlicense | C# |
1779ba60dd95dfbcdbde580ae4878e69822111d6 | Remove hard coded total tips from Details view | BillChirico/Tipage,BillChirico/Tipage | src/Tipage.Web/Views/Shifts/Details.cshtml | src/Tipage.Web/Views/Shifts/Details.cshtml | @model Tipage.Web.Models.ViewModels.ShiftViewModel
@{
ViewData["Title"] = "Details";
}
<h2>@Model.Shift.Start.ToString("d")</h2>
<div>
<hr />
<h1 class="total-tip">@Html.DisplayFor(model => model.Shift.TotalTips)</h1>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Shift.Start)
</dt>
<dd>
@Model.Shift.Start.ToString("t")
</dd>
<dt>
@Html.DisplayNameFor(model => model.Shift.End)
</dt>
<dd>
@Model.Shift.End.ToString("t")
</dd>
<dt>
@Html.DisplayNameFor(model => model.Shift.CashTips)
</dt>
<dd>
@Html.DisplayFor(model => model.Shift.CashTips)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Shift.CreditTips)
</dt>
<dd>
@Html.DisplayFor(model => model.Shift.CreditTips)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Shift.TotalTips)
</dt>
<dd>
@Html.DisplayFor(model => model.Shift.TotalTips)
</dd>
<dt>
@Html.DisplayNameFor(model => model.HourlyWage)
</dt>
<dd>
@Html.DisplayFor(model => model.HourlyWage)
</dd>
<dt>
@Html.DisplayNameFor(model => model.BusserTipout)
</dt>
<dd>
@Html.DisplayFor(model => model.BusserTipout)
</dd>
<dt>
@Html.DisplayNameFor(model => model.RunnerTipout)
</dt>
<dd>
@Html.DisplayFor(model => model.RunnerTipout)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.Shift.Id">Edit</a> |
<a asp-action="Index">Back to List</a>
</div>
| @model Tipage.Web.Models.ViewModels.ShiftViewModel
@{
ViewData["Title"] = "Details";
}
<h2>@Model.Shift.Start.ToString("d")</h2>
<div>
<hr />
<h1 class="total-tip">$71.00</h1>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Shift.Start)
</dt>
<dd>
@Model.Shift.Start.ToString("t")
</dd>
<dt>
@Html.DisplayNameFor(model => model.Shift.End)
</dt>
<dd>
@Model.Shift.End.ToString("t")
</dd>
<dt>
@Html.DisplayNameFor(model => model.Shift.CashTips)
</dt>
<dd>
@Html.DisplayFor(model => model.Shift.CashTips)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Shift.CreditTips)
</dt>
<dd>
@Html.DisplayFor(model => model.Shift.CreditTips)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Shift.TotalTips)
</dt>
<dd>
@Html.DisplayFor(model => model.Shift.TotalTips)
</dd>
<dt>
@Html.DisplayNameFor(model => model.HourlyWage)
</dt>
<dd>
@Html.DisplayFor(model => model.HourlyWage)
</dd>
<dt>
@Html.DisplayNameFor(model => model.BusserTipout)
</dt>
<dd>
@Html.DisplayFor(model => model.BusserTipout)
</dd>
<dt>
@Html.DisplayNameFor(model => model.RunnerTipout)
</dt>
<dd>
@Html.DisplayFor(model => model.RunnerTipout)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.Shift.Id">Edit</a> |
<a asp-action="Index">Back to List</a>
</div>
| mit | C# |
cb55ac7138f67d250cefac130751858559657add | Fix invalid target type on UnsafeKey attribute | CoraleStudios/Colore,WolfspiritM/Colore | Corale.Colore/Razer/Keyboard/UnsafeKeyAttribute.cs | Corale.Colore/Razer/Keyboard/UnsafeKeyAttribute.cs | // ---------------------------------------------------------------------------------------
// <copyright file="UnsafeKeyAttribute.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// 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.
//
// Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any
// of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott
// do not take responsibility for any harm caused, direct or indirect, to any
// Razer peripherals via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Corale.Colore.Razer.Keyboard
{
using System;
/// <summary>
/// Marks a <see cref="Key" /> value as unsafe.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class UnsafeKeyAttribute : Attribute
{
}
}
| // ---------------------------------------------------------------------------------------
// <copyright file="UnsafeKeyAttribute.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// 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.
//
// Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any
// of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott
// do not take responsibility for any harm caused, direct or indirect, to any
// Razer peripherals via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Corale.Colore.Razer.Keyboard
{
using System;
/// <summary>
/// Marks a <see cref="Key" /> value as unsafe.
/// </summary>
[AttributeUsage(AttributeTargets.Enum)]
public class UnsafeKeyAttribute : Attribute
{
}
}
| mit | C# |
ddfbcea53bf8a1a0a2a82d4147e25136746fabbd | Attach to remove | DragonSpark/Framework,DragonSpark/Framework,DragonSpark/Framework,DragonSpark/Framework | DragonSpark.Application/Entities/Editing/Editor.cs | DragonSpark.Application/Entities/Editing/Editor.cs | using DragonSpark.Compose;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
namespace DragonSpark.Application.Entities.Editing;
sealed class Editor : DragonSpark.Model.Operations.Allocated.Terminating<int>, IEditor
{
readonly DbContext _context;
readonly IDisposable _disposable;
public Editor(DbContext context) : this(context, context) {}
public Editor(DbContext context, IDisposable disposable) : base(context.Save)
{
_context = context;
_disposable = disposable;
}
public void Add(object entity)
{
_context.Add(entity);
}
public void Attach(object entity)
{
_context.Attach(entity);
}
public void Update(object entity)
{
_context.Update(entity);
}
public void Remove(object entity)
{
var record = _context.Entry(entity);
switch (record.State)
{
case EntityState.Added:
case EntityState.Modified:
case EntityState.Unchanged:
_context.Remove(entity);
break;
case EntityState.Detached:
_context.Attach(entity);
_context.Remove(entity);
break;
}
}
public void Clear()
{
_context.ChangeTracker.Clear();
}
public ValueTask Refresh(object entity) => _context.Entry(entity).ReloadAsync().ToOperation();
public void Dispose()
{
_disposable.Dispose();
}
} | using DragonSpark.Compose;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
namespace DragonSpark.Application.Entities.Editing;
sealed class Editor : DragonSpark.Model.Operations.Allocated.Terminating<int>, IEditor
{
readonly DbContext _context;
readonly IDisposable _disposable;
public Editor(DbContext context) : this(context, context) {}
public Editor(DbContext context, IDisposable disposable) : base(context.Save)
{
_context = context;
_disposable = disposable;
}
public void Add(object entity)
{
_context.Add(entity);
}
public void Attach(object entity)
{
_context.Attach(entity);
}
public void Update(object entity)
{
_context.Update(entity);
}
public void Remove(object entity)
{
var record = _context.Entry(entity);
switch (record.State)
{
case EntityState.Added:
case EntityState.Modified:
case EntityState.Unchanged:
_context.Remove(entity);
break;
}
}
public void Clear()
{
_context.ChangeTracker.Clear();
}
public ValueTask Refresh(object entity) => _context.Entry(entity).ReloadAsync().ToOperation();
public void Dispose()
{
_disposable.Dispose();
}
} | mit | C# |
c67500f9e1bb205a3cdbe09a4a19bccfb01faf9f | Update CopyingRows.cs | aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,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,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/RowsColumns/Copying/CopyingRows.cs | Examples/CSharp/RowsColumns/Copying/CopyingRows.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.Copying
{
public class CopyingRows
{
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 a new Workbook.
//Open the existing excel file.
Workbook excelWorkbook1 = new Workbook(dataDir + "book1.xls");
//Get the first worksheet in the workbook.
Worksheet wsTemplate = excelWorkbook1.Worksheets[0];
//Copy the second row with data, formattings, images and drawing objects
//to the 16th row in the worksheet.
wsTemplate.Cells.CopyRow(wsTemplate.Cells, 1, 15);
//Save the excel file.
excelWorkbook1.Save(dataDir + "output.out.xls");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.Copying
{
public class CopyingRows
{
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 a new Workbook.
//Open the existing excel file.
Workbook excelWorkbook1 = new Workbook(dataDir + "book1.xls");
//Get the first worksheet in the workbook.
Worksheet wsTemplate = excelWorkbook1.Worksheets[0];
//Copy the second row with data, formattings, images and drawing objects
//to the 16th row in the worksheet.
wsTemplate.Cells.CopyRow(wsTemplate.Cells, 1, 15);
//Save the excel file.
excelWorkbook1.Save(dataDir + "output.out.xls");
}
}
} | mit | C# |
1664a07b338f435a6c75fe47f813ab80e980df82 | fix lock in listener | lontivero/Open.HttpProxy | Open.HttpProxy/Listeners/TcpListener.cs | Open.HttpProxy/Listeners/TcpListener.cs | using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
namespace Open.HttpProxy.Listeners
{
using EventArgs;
using Utils;
public enum ListenerStatus
{
Listening,
Stopped
}
internal class TcpListener
{
public event EventHandler<ConnectionEventArgs> ConnectionRequested;
private static readonly ConcurrentQueue<SocketAsyncEventArgs> ConnectSaeaPool = new ConcurrentQueue<SocketAsyncEventArgs>();
//BlockingPool<SocketAsyncEventArgs> ConnectSaeaPool =
// new BlockingPool<SocketAsyncEventArgs>(() => new SocketAsyncEventArgs());
private readonly IPEndPoint _endPoint;
private Socket _listener;
private ListenerStatus _status;
public int Port { get; }
public TcpListener(int port)
{
Port = port;
_status = ListenerStatus.Stopped;
_endPoint = new IPEndPoint(IPAddress.Any, port);
// ConnectSaeaPool.PreAllocate(100);
}
public ListenerStatus Status => _status;
public IPEndPoint Endpoint => _endPoint;
public void Start()
{
if (Status == ListenerStatus.Listening)
{
throw new InvalidOperationException("Already listing");
}
try
{
_listener = CreateSocket();
_status = ListenerStatus.Listening;
Listen();
}
catch (SocketException)
{
Stop();
throw;
}
}
private Socket CreateSocket()
{
var socket = new Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// socket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
socket.Bind(_endPoint);
socket.Listen(int.MaxValue);
return socket;
}
private void Notify(SocketAsyncEventArgs saea)
{
Events.Raise(ConnectionRequested, this, new ConnectionEventArgs(saea.AcceptSocket));
}
private void Listen()
{
SocketAsyncEventArgs saea;
if (!ConnectSaeaPool.TryDequeue(out saea))
{
saea = new SocketAsyncEventArgs();
}
saea.AcceptSocket = null;
saea.Completed += IoCompleted;
if (_status == ListenerStatus.Stopped) return;
var async = _listener.AcceptAsync(saea);
if (!async)
{
IoCompleted(null, saea);
}
}
private void IoCompleted(object sender, SocketAsyncEventArgs saea)
{
try
{
if (saea.SocketError == SocketError.Success)
{
Notify(saea);
}
else
{
// bad connect. Close socket because it could be in a unknown state
saea.AcceptSocket.Close();
}
}
finally
{
saea.Completed -= IoCompleted;
ConnectSaeaPool.Enqueue(saea);
}
if (_listener != null) Listen();
}
public void Stop()
{
_status = ListenerStatus.Stopped;
if (_listener != null)
{
_listener.Close();
_listener = null;
}
}
}
} | using System;
using System.Net;
using System.Net.Sockets;
namespace Open.HttpProxy.Listeners
{
using EventArgs;
using Utils;
public enum ListenerStatus
{
Listening,
Stopped
}
internal class TcpListener
{
public event EventHandler<ConnectionEventArgs> ConnectionRequested;
private static readonly BlockingPool<SocketAsyncEventArgs> ConnectSaeaPool =
new BlockingPool<SocketAsyncEventArgs>(() => new SocketAsyncEventArgs());
private readonly IPEndPoint _endPoint;
private Socket _listener;
private ListenerStatus _status;
public int Port { get; }
public TcpListener(int port)
{
Port = port;
_status = ListenerStatus.Stopped;
_endPoint = new IPEndPoint(IPAddress.Any, port);
ConnectSaeaPool.PreAllocate(100);
}
public ListenerStatus Status => _status;
public IPEndPoint Endpoint => _endPoint;
public void Start()
{
if (Status == ListenerStatus.Listening)
{
throw new InvalidOperationException("Already listing");
}
try
{
_listener = CreateSocket();
_status = ListenerStatus.Listening;
Listen();
}
catch (SocketException)
{
Stop();
throw;
}
}
private Socket CreateSocket()
{
var socket = new Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// socket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
socket.Bind(_endPoint);
socket.Listen(int.MaxValue);
return socket;
}
private void Notify(SocketAsyncEventArgs saea)
{
var stream = new NetworkStream(saea.AcceptSocket);
Events.RaiseAsync(ConnectionRequested, this, new ConnectionEventArgs(stream));
}
private void Listen()
{
var saea = ConnectSaeaPool.Take();
saea.AcceptSocket = null;
saea.Completed += IoCompleted;
if(_status == ListenerStatus.Stopped) return;
var async = _listener.AcceptAsync(saea);
if (!async)
{
IoCompleted(null, saea);
}
}
private void IoCompleted(object sender, SocketAsyncEventArgs saea)
{
if (_listener != null) Listen();
try
{
if (saea.SocketError == SocketError.Success)
{
Notify(saea);
}
else
{
// bad connect. Close socket because it could be in a unknown state
saea.AcceptSocket.Close();
}
}
finally
{
saea.Completed -= IoCompleted;
ConnectSaeaPool.Add(saea);
}
}
public void Stop()
{
_status = ListenerStatus.Stopped;
if (_listener != null)
{
_listener.Close();
_listener = null;
}
}
}
} | mit | C# |
190d85302165adba14b01723a499ba48bfa527ce | Bump version | glorylee/FluentValidation,deluxetiky/FluentValidation,roend83/FluentValidation,GDoronin/FluentValidation,olcayseker/FluentValidation,cecilphillip/FluentValidation,IRlyDontKnow/FluentValidation,ruisebastiao/FluentValidation,roend83/FluentValidation,robv8r/FluentValidation,regisbsb/FluentValidation,mgmoody42/FluentValidation | src/CommonAssemblyInfo.cs | src/CommonAssemblyInfo.cs | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly : AssemblyTitle("FluentValidation")]
[assembly : AssemblyDescription("FluentValidation")]
[assembly : AssemblyProduct("FluentValidation")]
[assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2013")]
#if !PORTABLE
[assembly : ComVisible(false)]
#endif
[assembly : AssemblyVersion("5.0.0.1")]
[assembly : AssemblyFileVersion("5.0.0.1")]
[assembly: CLSCompliant(true)]
[assembly: System.Resources.NeutralResourcesLanguage("en")] | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly : AssemblyTitle("FluentValidation")]
[assembly : AssemblyDescription("FluentValidation")]
[assembly : AssemblyProduct("FluentValidation")]
[assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2013")]
#if !PORTABLE
[assembly : ComVisible(false)]
#endif
[assembly : AssemblyVersion("5.0.0.0")]
[assembly : AssemblyFileVersion("5.0.0.0")]
[assembly: CLSCompliant(true)]
[assembly: System.Resources.NeutralResourcesLanguage("en")] | apache-2.0 | C# |
37adb70bc6bec730101a8ba8e4506ce102bb07ee | Revert "Added method to perform validity check for effect parameters" | igece/SoxSharp | src/Effects/BaseEffect.cs | src/Effects/BaseEffect.cs | namespace SoxSharp.Effects
{
public abstract class BaseEffect : IBaseEffect
{
public abstract string Name { get; }
public abstract override string ToString();
}
}
| namespace SoxSharp.Effects
{
public abstract class BaseEffect : IBaseEffect
{
public abstract string Name { get; }
public virtual bool IsValid() { return true; }
public abstract override string ToString();
}
}
| apache-2.0 | C# |
ccf5768cc7afec331425ab34b315383d21f52687 | Add IsFilterActive; remove unneeded parameters for filter method (pass it on ctor) | neitsa/PrepareLanding,neitsa/PrepareLanding | src/Filters/TileFilter.cs | src/Filters/TileFilter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using PrepareLanding.Extensions;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;
namespace PrepareLanding.Filters
{
public abstract class TileFilter : ITileFilter
{
protected List<int> _filteredTiles = new List<int>();
protected PrepareLandingUserData UserData;
public abstract string SubjectThingDef { get; }
public abstract bool IsFilterActive { get; }
public virtual List<int> FilteredTiles => _filteredTiles;
public virtual string RunningDescription => $"Filtering {SubjectThingDef}";
public string AttachedProperty { get; }
public Action<List<int>> FilterAction { get; }
public FilterHeaviness Heaviness { get; }
protected TileFilter(PrepareLandingUserData userData, string attachedProperty, FilterHeaviness heaviness)
{
UserData = userData;
AttachedProperty = attachedProperty;
Heaviness = heaviness;
FilterAction = Filter;
}
public virtual void Filter(List<int> inputList)
{
_filteredTiles.Clear();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using PrepareLanding.Extensions;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;
namespace PrepareLanding.Filters
{
public abstract class TileFilter : ITileFilter
{
protected List<int> _filteredTiles = new List<int>();
public abstract string SubjectThingDef { get; }
public virtual List<int> FilteredTiles => _filteredTiles;
public virtual string RunningDescription => $"Filtering {SubjectThingDef}";
public string AttachedProperty { get; }
public Action<PrepareLandingUserData, List<int>> FilterAction { get; }
public FilterHeaviness Heaviness { get; }
protected TileFilter(string attachedProperty, FilterHeaviness heaviness)
{
AttachedProperty = attachedProperty;
Heaviness = heaviness;
FilterAction = Filter;
}
public virtual void Filter(PrepareLandingUserData userData, List<int> inputList)
{
_filteredTiles.Clear();
}
}
} | mit | C# |
de2086eb4d1b91b6a5e82b95be30f6a346882c8d | Bump version to 2.4 | mattleibow/SQLite.Net-PCL,TiendaNube/SQLite.Net-PCL,oysteinkrog/SQLite.Net-PCL,fernandovm/SQLite.Net-PCL,igrali/SQLite.Net-PCL,caseydedore/SQLite.Net-PCL,kreuzhofer/SQLite.Net-PCL,molinch/SQLite.Net-PCL,igrali/SQLite.Net-PCL | src/GlobalAssemblyInfo.cs | src/GlobalAssemblyInfo.cs | using System.Reflection;
// 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("2.4.0.0")]
[assembly: AssemblyFileVersion("2.4.0.0")] | using System.Reflection;
// 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("2.3.0.0")]
[assembly: AssemblyFileVersion("2.3.0.0")] | mit | C# |
8df51bc4526639fbd4f26c6836992fdcad2b68ad | Update Index.cshtml | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/Home/Index.cshtml | Anlab.Mvc/Views/Home/Index.cshtml | @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Update posted: December 8, 2020<br /><br />
<strong>Please Note Holiday Closure Information:</strong><br /><br />
The Lab will be closed from December 24 - January 1<br />
Please arrange sample deliveries by noon on December 23 if possible.<br />
We will reopen with normal business hours on Monday, January 4.<br /><br />
<strong>Also Note:</strong><br /><br />
The emergency arrangement for wine testing has concluded and we are no longer accepting samples for smoke taint analysis.
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
| @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Update posted: December 8, 2020<br /><br />
<strong>Please Note Holiday Closure Information:</strong><br /><br />
The Lab will be closed from December 24 - January 1<br />
Please arrange sample deliveries by noon on December 23 if possible.<br />
We will reopen with normal business hours on Monday, January 4.<br /><br />
<strong>Also Note:</strong><br /><br />
The emergency arrangement for wine testing is concluding.
Results for samples already received will be reported soon but we are no longer accepting new samples.
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
| mit | C# |
98fd720a9327c0799b370d1c109ff4eac0e4e639 | Update Univ. Holidays | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/Home/Index.cshtml | Anlab.Mvc/Views/Home/Index.cshtml | @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Update posted: September 30, 2020<br /><br />
In response to the emergency need for the analysis of wine for smoke taint,
the UC Davis Department of Viticulture and Enology is partnering with the UC Davis Analytical Lab to offer testing<br /><br />
Please click <a href="/media/pdf/anlab_smoke-taint_instructions_v2.pdf" target="_blank"><strong>here</strong> for more information on
<strong> Wine Testing for Smoke Taint</strong></a>.<br /><br />
Please Note Receiving Hours: M - F, 8 - 5, except University Holidays.<br />
Upcoming University Holidays include November 11, 26, and 27.
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
| @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Update posted: September 30, 2020<br /><br />
In response to the emergency need for the analysis of wine for smoke taint,
the UC Davis Department of Viticulture and Enology is partnering with the UC Davis Analytical Lab to offer testing<br /><br />
Please click <a href="/media/pdf/anlab_smoke-taint_instructions_v2.pdf" target="_blank"><strong>here</strong> for more information on
<strong> Wine Testing for Smoke Taint</strong></a>.<br /><br />
Please Note Receiving Hours: M - F, 8 - 5, except University Holidays.
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
| mit | C# |
8845a41c93aba6c8e5b44025b188ddf3923926b5 | Update Hive building ants | MasonSchneider/BattleAntz | BattleAntz/Assets/Scripts/Hive.cs | BattleAntz/Assets/Scripts/Hive.cs | using UnityEngine;
using System.Collections;
public class Hive : MonoBehaviour {
float nextTick = 0;
int SUGAR_RATE = 1;
int BASE_PRODUCTION = 10;
int WORKER_COST = 50;
int WORKER_PRODUCTION = 10;
int ARMY_ANT_COST = 50;
int BULL_ANT_COST = 100;
int FIRE_ANT_COST = 150;
int RETURN_VALUE = 2;
int ANT_COST = 10; // ONLY FOR DEBUGGING PURPOSES
public int sugar;
public int health;
public int workers;
public int income; // total production of the hive
private AntController antController;
// Use this for initialization
void Start () {
income = BASE_PRODUCTION;
sugar = 100;
health = 100;
antController = GameObject.Find("Ant Controller").GetComponent("AntController") as AntController;
}
// Update is called once per frame (60fps?)
void Update () {
Debug.Log (sugar);
if (Time.time > nextTick) {
nextTick = Time.time + SUGAR_RATE;
sugar += income;
}
}
// Buy a worker
public bool buyWorker(){
if(sugar >= WORKER_COST){
sugar -= WORKER_COST;
workers += 1;
income += WORKER_PRODUCTION;
return true;
}
return false;
}
// Sell a worker.
public bool sellWorker(){
if(workers > 0){
workers -= 1;
income -= WORKER_PRODUCTION;
sugar += WORKER_COST/RETURN_VALUE;
antController.spawnAnt();
return true;
}
return false;
}
// Buy an army ant
public bool buyArmyAnt(){
if (sugar >= ARMY_ANT_COST) {
sugar -= ANT_COST;
// TODO create army ant
return true;
}
return false;
}
public void takeDamage(int damage){
health -= damage;
if (health <= 0) {
// TODO: end game
}
}
public void upgrade(string upgrade){
// worker speed, armyant health, bullant strength, fireant special
//string ant = upgrade.Split[0]
//string cate = upgrade.Split[1]
}
} | using UnityEngine;
using System.Collections;
public class Hive : MonoBehaviour {
float nextTick = 0;
int SUGAR_RATE = 1;
int BASE_PRODUCTION = 10;
int WORKER_COST = 50;
int WORKER_PRODUCTION = 10;
int ARMY_ANT_COST = 50;
int BULL_ANT_COST = 100;
int FIRE_ANT_COST = 150;
int RETURN_VALUE = 2;
int ANT_COST = 10; // ONLY FOR DEBUGGING PURPOSES
public int sugar;
public int health;
public int workers;
public int income; // total production of the hive
// Use this for initialization
void Start () {
income = BASE_PRODUCTION;
sugar = 100;
health = 100;
}
// Update is called once per frame (60fps?)
void Update () {
Debug.Log (sugar);
if (Time.time > nextTick) {
nextTick = Time.time + SUGAR_RATE;
sugar += income;
}
}
// Buy a worker
public bool buyWorker(){
if(sugar > WORKER_COST){
sugar -= WORKER_COST;
workers += 1;
income += WORKER_PRODUCTION;
return true;
}
return false;
}
// Sell a worker.
public bool sellWorker(){
if(workers > 0){
workers -= 1;
income -= WORKER_PRODUCTION;
sugar += WORKER_COST/RETURN_VALUE;
return true;
}
return false;
}
public void buyAnt(int n){
if (sugar > n * ANT_COST) {
sugar -= n * ANT_COST;
// TODO: SPAWN N ants
}
}
public void takeDamage(int damage){
health -= damage;
if (health <= 0) {
// TODO: end game
}
}
public void upgrade(string upgrade){
// worker speed, armyant health, bullant strength, fireant special
//string ant = upgrade.Split[0]
//string cate = upgrade.Split[1]
}
} | mit | C# |
ed8965d18493f74ab345e33a28f64688a0eeeaf3 | Update ValuesOut.cs | EricZimmerman/RegistryPlugins | RegistryPlugin.WindowsPortableDevices/ValuesOut.cs | RegistryPlugin.WindowsPortableDevices/ValuesOut.cs | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.WindowsPortableDevices
{
public class ValuesOut : IValueOut
{
public ValuesOut(string device, string serialnumber, string guid, string friendlyname, DateTimeOffset? timestamp)
{
Device = device;
SerialNumber = serialnumber;
Guid = guid;
FriendlyName = friendlyname;
Timestamp = timestamp;
}
public DateTimeOffset? Timestamp { get; }
public string Device { get; }
public string SerialNumber { get; }
public string Guid { get; }
public string FriendlyName { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Device: {Device} SerialNumber: {SerialNumber} Guid: {Guid}";
public string BatchValueData2 => $"FriendlyName: {FriendlyName}";
public string BatchValueData3 => $"Timestamp: {Timestamp?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}";
}
}
| using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.WindowsPortableDevices
{
public class ValuesOut : IValueOut
{
public ValuesOut(string device, string serialnumber, string guid, string friendlyname, DateTimeOffset? timestamp)
{
Device = device;
SerialNumber = serialnumber;
Guid = guid;
FriendlyName = friendlyname;
Timestamp = timestamp;
}
public DateTimeOffset? Timestamp { get; }
public string Device { get; }
public string SerialNumber { get; }
public string Guid { get; }
public string FriendlyName { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Device: {Device} SerialNumber: {SerialNumber} Guid: {Guid}";
public string BatchValueData2 => $"FriendlyName: {FriendlyName}";
public string BatchValueData3 => $"Timestamp: {Timestamp?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff} ";
}
}
| mit | C# |
38d9035250d8372ff646abd56f93e9f42c76e8b5 | Modify operation recorder | emoacht/Monitorian | Source/Monitorian.Core/Models/OperationRecorder.cs | Source/Monitorian.Core/Models/OperationRecorder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monitorian.Core.Helper;
namespace Monitorian.Core.Models
{
internal class OperationRecorder
{
public OperationRecorder(string message) => LogService.RecordOperation(message);
public void Record(string content) => LogService.RecordOperation(content);
private string _actionName;
public void StartRecord(string actionName) => this._actionName = actionName;
private readonly List<(string group, StringWrapper item)> _groups = new List<(string, StringWrapper)>();
public void AddItem(string groupName, string itemString) => _groups.Add((groupName, new StringWrapper(itemString)));
public void AddItems(string groupName, IEnumerable<string> itemStrings) => _groups.AddRange(itemStrings.Select(x => (groupName, new StringWrapper(x))));
public void StopRecord()
{
var groupsStrings = _groups.GroupBy(x => x.group).Select(x => (x.Key, (object)x.Select(y => y.item))).ToArray();
LogService.RecordOperation($"{_actionName}{Environment.NewLine}{SimpleSerialization.Serialize(groupsStrings)}");
_groups.Clear();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monitorian.Core.Helper;
namespace Monitorian.Core.Models
{
internal class OperationRecorder
{
public OperationRecorder(string message) => LogService.RecordOperation(message);
public void Record(string content) => LogService.RecordOperation(content);
private string _actionName;
public void StartRecord(string actionName) => this._actionName = actionName;
private readonly List<(string group, string item)> _groups = new List<(string, string)>();
public void AddItem(string groupName, string itemString) => _groups.Add((groupName, itemString));
public void AddItems(string groupName, IEnumerable<string> itemStrings) => _groups.AddRange(itemStrings.Select(x => (groupName, x)));
public void StopRecord()
{
var groupsStrings = _groups.GroupBy(x => x.group).Select(x => (x.Key, (object)x.Select(y => new StringWrapper(y.item)))).ToArray();
LogService.RecordOperation($"{_actionName}{Environment.NewLine}{SimpleSerialization.Serialize(groupsStrings)}");
_groups.Clear();
}
}
} | mit | C# |
6e56bb04c84db9802497bf85b8e026b408235c16 | Add a method to get GameIDs | SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake | Snowflake.API/Romfile/IFileSignature.cs | Snowflake.API/Romfile/IFileSignature.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snowflake.Romfile
{
/// <summary>
/// Represents the ROM file signature
/// </summary>
public interface IFileSignature
{
/// <summary>
/// Accepted file extensions for the ROM file.
/// Cuesheets are not considered ROM data.
/// </summary>
/// <example>
/// .iso, .cso, .wbfs for Wii games
/// </example>
HashSet<string> FileExtensions { get; }
/// <summary>
/// The byte array from byte position 0 containing the header or other identifier of the ROM.
/// Usually the first 1024 bytes.
/// </summary>
byte[] HeaderSignature { get; }
/// <summary>
/// The offset from byte position 0 to the start of the header.
/// IFileSignature.HeaderSignature[IFileSignature.HeaderOffset] should return the first byte of the header
/// </summary>
long HeaderOffset { get; }
/// <summary>
/// The Stone Platform ID this file signature uses
/// </summary>
string StonePlatformId{ get; }
/// <summary>
/// Whether or not the filename's file extension is in IFileSignature.FileExtensions
/// </summary>
/// <param name="fileName">The filename of the ROM</param>
/// <returns>Whether or not this filename's file extension is valid for this type of platform</returns>
bool FileExtensionMatches(string fileName);
/// <summary>
/// Whether or not the header signature of a file matches this platform's ROM type.
/// To handle multiple types of ROMs, use a series of ifs or an switch.
/// </summary>
/// <param name="fileName">The filename of the ROM</param>
/// <returns>If this ROM is executable data for this platform, it should return true.</returns>
bool HeaderSignatureMatches(string fileName);
/// <summary>
/// Gets the game id from the file signature if possible
/// </summary>
string GetGameID(string fileName);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snowflake.Romfile
{
/// <summary>
/// Represents the ROM file signature
/// </summary>
public interface IFileSignature
{
/// <summary>
/// Accepted file extensions for the ROM file.
/// Cuesheets are not considered ROM data.
/// </summary>
/// <example>
/// .iso, .cso, .wbfs for Wii games
/// </example>
HashSet<string> FileExtensions { get; }
/// <summary>
/// The byte array from byte position 0 containing the header or other identifier of the ROM.
/// Usually the first 1024 bytes.
/// </summary>
byte[] HeaderSignature { get; }
/// <summary>
/// The offset from byte position 0 to the start of the header.
/// IFileSignature.HeaderSignature[IFileSignature.HeaderOffset] should return the first byte of the header
/// </summary>
long HeaderOffset { get; }
/// <summary>
/// The Stone Platform ID this file signature uses
/// </summary>
string StonePlatformId{ get; }
/// <summary>
/// Whether or not the filename's file extension is in IFileSignature.FileExtensions
/// </summary>
/// <param name="fileName">The filename of the ROM</param>
/// <returns>Whether or not this filename's file extension is valid for this type of platform</returns>
bool FileExtensionMatches(string fileName);
/// <summary>
/// Whether or not the header signature of a file matches this platform's ROM type.
/// To handle multiple types of ROMs, use a series of ifs or an switch.
/// </summary>
/// <param name="fileName">The filename of the ROM</param>
/// <returns>If this ROM is executable data for this platform, it should return true.</returns>
bool HeaderSignatureMatches(string fileName);
}
}
| mpl-2.0 | C# |
7ba60ed700a4026491ef5e002dfb9c65cced64cf | Change type. | mika-f/Orion,OrionDevelop/Orion | Source/Orion.Shared/ProviderRedirect.cs | Source/Orion.Shared/ProviderRedirect.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Orion.Shared
{
internal static class ProviderRedirect
{
private static readonly Dictionary<string, string> RedirectHosts = new Dictionary<string, string>
{
["mstdn.jp"] = "streaming.mstdn.jp",
["qiitadon.com"] = "streaming.qiitadon.com:4000",
};
public static string Redirect(string url)
{
var host = new Uri(url).Host;
return RedirectHosts.Any(w => w.Key == host) ? RedirectHosts.First(w => w.Key == host).Value : host;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Orion.Shared
{
// F**king mstdn.jp
internal static class ProviderRedirect
{
private static readonly List<Tuple<string, string>> RedirectHosts = new List<Tuple<string, string>>
{
new Tuple<string, string>("mstdn.jp", "streaming.mstdn.jp"),
new Tuple<string, string>("qiitadon.com", "streaming.qiitadon.com:4000")
};
public static string Redirect(string url)
{
var host = new Uri(url).Host;
return RedirectHosts.Any(w => w.Item1 == host) ? RedirectHosts.First(w => w.Item1 == host).Item2 : host;
}
}
} | mit | C# |
b9c87ef8c71effcb012ae58972e37160039fad46 | Update documentation | whampson/bft-spec,whampson/cascara | Src/WHampson.Cascara/Types/ICascaraStruct.cs | Src/WHampson.Cascara/Types/ICascaraStruct.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
namespace WHampson.Cascara.Types
{
/// <summary>
/// Dummy interface used internally for classifying
/// structs defined in a template.
/// </summary>
internal interface ICascaraStruct
{
}
}
| #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
namespace WHampson.Cascara.Types
{
/// <summary>
/// Dummy interface used internally for classifying structs.
/// </summary>
internal interface ICascaraStruct
{
}
}
| mit | C# |
09092fc772e3c2755dd5aa4a49fdb12dfdb34e7a | fix JasilyTimeout API | Cologler/jasily.cologler | Jasily/Threading/JasilyTimeout.cs | Jasily/Threading/JasilyTimeout.cs | using System;
using System.Diagnostics.Contracts;
using System.Threading;
namespace Jasily.Threading
{
/// <summary>
/// alse see: http://referencesource.microsoft.com/#mscorlib/system/threading/SpinWait.cs,b8cdeb634d79d613
/// 使用算法来构造从生成 JasilyTimeout 开始到将此超时传递给系统 API 的时间。
/// </summary>
public class JasilyTimeout
{
private readonly uint created;
private JasilyTimeout(int origin)
{
Contract.Assert(origin == Timeout.Infinite || origin > 0);
this.Value = origin;
this.created = CurrentTickCount;
}
/// <summary>
/// 大约 49.7 天重置
/// </summary>
private static uint CurrentTickCount => (uint)Environment.TickCount;
public int Value { get; }
/// <summary>
/// 返回从 JasilyTimeout 构造开始到当前的毫秒时间
/// </summary>
public uint TimeOffset => CurrentTickCount - this.created;
/// <summary>
/// 剩下的时间
/// </summary>
public int LeftTime
{
get
{
var offset = this.TimeOffset;
return offset > this.Value ? 0 : (int)(this.Value - offset);
}
}
public bool IsTimeout => this.TimeOffset >= this.Value;
public static implicit operator JasilyTimeout(int milliseconds)
{
if (milliseconds == Timeout.Infinite)
return InfiniteTimeSpan;
if (milliseconds <= 0)
throw new ArgumentOutOfRangeException(nameof(milliseconds), milliseconds, "value must > 0");
return new JasilyTimeout(milliseconds);
}
public static readonly JasilyTimeout InfiniteTimeSpan
= new JasilyTimeout(Timeout.Infinite);
}
} | using System;
using System.Diagnostics.Contracts;
using System.Threading;
namespace Jasily.Threading
{
/// <summary>
/// alse see: http://referencesource.microsoft.com/#mscorlib/system/threading/SpinWait.cs,b8cdeb634d79d613
/// 使用算法来构造从生成 JasilyTimeout 开始到将此超时传递给系统 API 的时间。
/// </summary>
public struct JasilyTimeout
{
private readonly int originalMillisecondsTimeout;
private readonly uint created;
public JasilyTimeout(int originalMillisecondsTimeout)
{
Contract.Assert(originalMillisecondsTimeout != Timeout.Infinite);
this.originalMillisecondsTimeout = originalMillisecondsTimeout;
this.created = CurrentTickCount;
}
private static uint CurrentTickCount => (uint)Environment.TickCount;
/// <summary>
/// 返回从 Timeout 减去构造 JasilyTimeout 到调用 Value.Get() 的时间
/// </summary>
public int Value
{
get
{
var elapsedMilliseconds = CurrentTickCount - this.created;
return elapsedMilliseconds > int.MaxValue
? 0
: Math.Max(this.originalMillisecondsTimeout - (int) elapsedMilliseconds, 0);
}
}
public bool IsTimeout => this.Value <= 0;
public static implicit operator JasilyTimeout(int milliseconds) => new JasilyTimeout(milliseconds);
}
} | mit | C# |
35eaadcbaa1c689a9de2ec5cf029fe0fad92e188 | Update WalletWasabi.Tests/UnitTests/ListExtensionTests.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Tests/UnitTests/ListExtensionTests.cs | WalletWasabi.Tests/UnitTests/ListExtensionTests.cs | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class ListExtensionTests
{
[Fact]
public void InsertSorted_Orders_Items_Correctly()
{
var actual = new List<int>();
actual.InsertSorted(5);
actual.InsertSorted(4);
actual.InsertSorted(3);
actual.InsertSorted(2);
actual.InsertSorted(1);
actual.InsertSorted(0);
var expected = new List<int> { 0, 1, 2, 3, 4, 5 };
Assert.Equal(expected, actual);
}
[Fact]
public void InsertSorted_Orders_Items_Correctly_Allowing_Duplicates()
{
var actual = new List<int>();
actual.InsertSorted(5);
actual.InsertSorted(4);
actual.InsertSorted(3);
actual.InsertSorted(2);
actual.InsertSorted(5, false);
actual.InsertSorted(1);
actual.InsertSorted(0);
var expected = new List<int> { 0, 1, 2, 3, 4, 5, 5 };
Assert.Equal(expected, actual);
}
[Fact]
public void BinarySearch_Uses_CompareTo()
{
var actual = new List<ReverseComparable>();
actual.InsertSorted(new ReverseComparable(0));
actual.InsertSorted(new ReverseComparable(1));
actual.InsertSorted(new ReverseComparable(2));
actual.InsertSorted(new ReverseComparable(3));
actual.InsertSorted(new ReverseComparable(4));
var expected = new List<ReverseComparable>
{
new ReverseComparable(4),
new ReverseComparable(3),
new ReverseComparable(2),
new ReverseComparable(1),
new ReverseComparable(0)
};
Assert.Equal(expected, actual);
}
private class ReverseComparable : IComparable<ReverseComparable>
{
public ReverseComparable(int value)
{
Value = value;
}
public int Value { get; }
public int CompareTo([AllowNull] ReverseComparable other)
{
return other.Value.CompareTo(Value);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class ListExtensionTests
{
[Fact]
public void InsertSorted_Orders_Items_Correctly ()
{
var actual = new List<int>();
actual.InsertSorted(5);
actual.InsertSorted(4);
actual.InsertSorted(3);
actual.InsertSorted(2);
actual.InsertSorted(1);
actual.InsertSorted(0);
var expected = new List<int> { 0, 1, 2, 3, 4, 5 };
Assert.Equal(expected, actual);
}
[Fact]
public void InsertSorted_Orders_Items_Correctly_Allowing_Duplicates()
{
var actual = new List<int>();
actual.InsertSorted(5);
actual.InsertSorted(4);
actual.InsertSorted(3);
actual.InsertSorted(2);
actual.InsertSorted(5, false);
actual.InsertSorted(1);
actual.InsertSorted(0);
var expected = new List<int> { 0, 1, 2, 3, 4, 5, 5 };
Assert.Equal(expected, actual);
}
[Fact]
public void BinarySearch_Uses_CompareTo()
{
var actual = new List<ReverseComparable>();
actual.InsertSorted(new ReverseComparable(0));
actual.InsertSorted(new ReverseComparable(1));
actual.InsertSorted(new ReverseComparable(2));
actual.InsertSorted(new ReverseComparable(3));
actual.InsertSorted(new ReverseComparable(4));
var expected = new List<ReverseComparable>
{
new ReverseComparable(4),
new ReverseComparable(3),
new ReverseComparable(2),
new ReverseComparable(1),
new ReverseComparable(0)
};
Assert.Equal(expected, actual);
}
private class ReverseComparable : IComparable<ReverseComparable>
{
public ReverseComparable(int value)
{
Value = value;
}
public int Value { get; }
public int CompareTo([AllowNull] ReverseComparable other)
{
return other.Value.CompareTo(Value);
}
}
}
}
| mit | C# |
e52c9a9a0a81ed1285d1ee02eea17388b5b1f300 | Update description, version and remove ComVisible | richardlawley/NModbus4,NModbus/NModbus,xlgwr/NModbus4,Maxwe11/NModbus4,NModbus4/NModbus4,yvschmid/NModbus4 | Modbus/Properties/AssemblyInfo.cs | Modbus/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("NModbus4")]
[assembly: AssemblyProduct("NModbus4")]
[assembly: AssemblyCompany("Maxwe11")]
[assembly: AssemblyCopyright("Licensed under MIT License.")]
[assembly: AssemblyDescription("NModbus is a C# implementation of the Modbus protocol. " +
"Provides connectivity to Modbus slave compatible devices and applications. " +
"Supports serial ASCII, serial RTU, TCP, and UDP protocols. "+
"NModbus4 it's a fork of NModbus(https://code.google.com/p/nmodbus)")]
[assembly: CLSCompliant(false)]
[assembly: Guid("95B2AE1E-E0DC-4306-8431-D81ED10A2D5D")]
[assembly: AssemblyVersion("2.0.*")]
#if !SIGNED
[assembly: InternalsVisibleTo(@"Modbus.UnitTests")]
[assembly: InternalsVisibleTo(@"DynamicProxyGenAssembly2")]
#endif | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("NModbus4")]
[assembly: AssemblyProduct("NModbus4")]
[assembly: AssemblyCompany("Maxwe11")]
[assembly: AssemblyCopyright("Licensed under MIT License.")]
[assembly: AssemblyDescription("Differs from this one (https://code.google.com/p/nmodbus) in following: " +
"removed FtdAdapter.dll, log4net, Unme.Common.dll dependencies, assembly renamed to NModbus.dll, " +
"target framework changed to .NET 4")]
// required for VBA applications
[assembly: ComVisible(true)]
[assembly: CLSCompliant(false)]
[assembly: Guid("95B2AE1E-E0DC-4306-8431-D81ED10A2D5D")]
[assembly: AssemblyVersion("1.12.0.0")]
#if !WindowsCE
[assembly: AssemblyFileVersion("1.12.0.0")]
#endif
#if !SIGNED
[assembly: InternalsVisibleTo(@"Modbus.UnitTests")]
[assembly: InternalsVisibleTo(@"DynamicProxyGenAssembly2")]
#endif | mit | C# |
fa84fe57706e72eff4dfc0f576f5f830b44bc0a2 | Remove custom schema from IdentityRegistrar. | aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,GutierrezDev/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,GutierrezDev/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,GutierrezDev/aspnetboilerplate-samples,GutierrezDev/aspnetboilerplate-samples | IdentityServerDemo/src/IdentityServerDemo.Core/Identity/IdentityRegistrar.cs | IdentityServerDemo/src/IdentityServerDemo.Core/Identity/IdentityRegistrar.cs | using IdentityServerDemo.Authorization;
using IdentityServerDemo.Authorization.Roles;
using IdentityServerDemo.Authorization.Users;
using IdentityServerDemo.Editions;
using IdentityServerDemo.MultiTenancy;
using Microsoft.Extensions.DependencyInjection;
namespace IdentityServerDemo.Identity
{
public static class IdentityRegistrar
{
public static void Register(IServiceCollection services)
{
services.AddLogging();
services.AddAbpIdentity<Tenant, User, Role>()
.AddAbpTenantManager<TenantManager>()
.AddAbpUserManager<UserManager>()
.AddAbpRoleManager<RoleManager>()
.AddAbpEditionManager<EditionManager>()
.AddAbpUserStore<UserStore>()
.AddAbpRoleStore<RoleStore>()
.AddAbpLogInManager<LogInManager>()
.AddAbpSignInManager<SignInManager>()
.AddAbpSecurityStampValidator<SecurityStampValidator>()
.AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>()
.AddDefaultTokenProviders();
}
}
}
| using IdentityServerDemo.Authorization;
using IdentityServerDemo.Authorization.Roles;
using IdentityServerDemo.Authorization.Users;
using IdentityServerDemo.Editions;
using IdentityServerDemo.MultiTenancy;
using Microsoft.Extensions.DependencyInjection;
namespace IdentityServerDemo.Identity
{
public static class IdentityRegistrar
{
public static void Register(IServiceCollection services)
{
services.AddLogging();
services.AddAbpIdentity<Tenant, User, Role>(options =>
{
options.Cookies.ApplicationCookie.AuthenticationScheme = "AbpZeroTemplateAuthSchema";
options.Cookies.ApplicationCookie.CookieName = "AbpZeroTemplateAuth";
})
.AddAbpTenantManager<TenantManager>()
.AddAbpUserManager<UserManager>()
.AddAbpRoleManager<RoleManager>()
.AddAbpEditionManager<EditionManager>()
.AddAbpUserStore<UserStore>()
.AddAbpRoleStore<RoleStore>()
.AddAbpLogInManager<LogInManager>()
.AddAbpSignInManager<SignInManager>()
.AddAbpSecurityStampValidator<SecurityStampValidator>()
.AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>()
.AddDefaultTokenProviders();
}
}
}
| mit | C# |
4ed3533f51e7bbc2427f3a37c9d934fdf55719e1 | Add Windows.UI.ApplicationSettings to the using directives of MainPage.xaml.cs and clean up the code. | wangjun/windows-app,wangjun/windows-app | wallabag/wallabag.Windows/MainPage.xaml.cs | wallabag/wallabag.Windows/MainPage.xaml.cs | using wallabag.Common;
using wallabag.Views;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml.Controls;
namespace wallabag
{
public sealed partial class MainPage : basicPage
{
public MainPage()
{
this.InitializeComponent();
SettingsPane.GetForCurrentView().CommandsRequested += MainPage_CommandsRequested;
}
void MainPage_CommandsRequested(Windows.UI.ApplicationSettings.SettingsPane sender, Windows.UI.ApplicationSettings.SettingsPaneCommandsRequestedEventArgs args)
{
SettingsCommand generalSettings = new SettingsCommand("generalSettings", "General", (handler) =>
{
generalSettingsFlyout settingsFlyout = new generalSettingsFlyout();
settingsFlyout.Show();
});
SettingsCommand readingSettings = new SettingsCommand("readingSettings", "Reading", (handler) =>
{
readingSettingsFlyout readingFlyout = new readingSettingsFlyout();
readingFlyout.Show();
});
if (args.Request.ApplicationCommands.Count == 0)
{
args.Request.ApplicationCommands.Add(generalSettings);
args.Request.ApplicationCommands.Add(readingSettings);
}
}
private void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
this.Frame.Navigate(typeof(ItemPage), e.ClickedItem);
}
}
}
| using Windows.UI.Xaml.Controls;
using wallabag.Common;
using wallabag.Views;
namespace wallabag
{
public sealed partial class MainPage : basicPage
{
public MainPage()
{
this.InitializeComponent();
Windows.UI.ApplicationSettings.SettingsPane.GetForCurrentView().CommandsRequested += MainPage_CommandsRequested;
}
void MainPage_CommandsRequested(Windows.UI.ApplicationSettings.SettingsPane sender, Windows.UI.ApplicationSettings.SettingsPaneCommandsRequestedEventArgs args)
{
Windows.UI.ApplicationSettings.SettingsCommand generalSettings =
new Windows.UI.ApplicationSettings.SettingsCommand("generalSettings", "General", (handler) =>
{
generalSettingsFlyout settingsFlyout = new generalSettingsFlyout();
settingsFlyout.Show();
});
Windows.UI.ApplicationSettings.SettingsCommand readingSettings =
new Windows.UI.ApplicationSettings.SettingsCommand("readingSettings", "Reading", (handler) =>
{
readingSettingsFlyout readingFlyout = new readingSettingsFlyout();
readingFlyout.Show();
});
if (args.Request.ApplicationCommands.Count == 0)
{
args.Request.ApplicationCommands.Add(generalSettings);
args.Request.ApplicationCommands.Add(readingSettings);
}
}
private void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
this.Frame.Navigate(typeof(ItemPage), e.ClickedItem);
}
}
}
| mit | C# |
9d68a1eab82dd3fc9af930ab97b2fb2d0c38cb07 | Make PoEItemModCategory implement IReadOnlyList<PoEItemModList> | jcmoyer/Yeena | Yeena/PathOfExile/PoEItemModCategory.cs | Yeena/PathOfExile/PoEItemModCategory.cs | // Copyright 2013 J.C. Moyer
//
// 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.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
[JsonObject]
class PoEItemModCategory : IReadOnlyList<PoEItemModList> {
[JsonProperty("name")]
private readonly string _name;
[JsonProperty("modLists")]
private readonly List<PoEItemModList> _modLists;
public string Name { get { return _name; } }
public IReadOnlyList<PoEItemModList> ModLists { get { return _modLists; } }
[JsonConstructor]
private PoEItemModCategory() {
}
public PoEItemModCategory(string name, IEnumerable<PoEItemModList> mods) {
_name = name;
_modLists = mods.ToList();
}
public IEnumerator<PoEItemModList> GetEnumerator() {
return _modLists.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public int Count {
get { return _modLists.Count; }
}
public PoEItemModList this[int index] {
get { return _modLists[index]; }
}
public override string ToString() {
return Name;
}
}
} | // Copyright 2013 J.C. Moyer
//
// 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.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
[JsonObject]
class PoEItemModCategory : IEnumerable<PoEItemModList> {
[JsonProperty("name")]
private readonly string _name;
[JsonProperty("modLists")]
private readonly List<PoEItemModList> _modLists;
public string Name { get { return _name; } }
public IReadOnlyList<PoEItemModList> ModLists { get { return _modLists; } }
[JsonConstructor]
private PoEItemModCategory() {
}
public PoEItemModCategory(string name, IEnumerable<PoEItemModList> mods) {
_name = name;
_modLists = mods.ToList();
}
public IEnumerator<PoEItemModList> GetEnumerator() {
return _modLists.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public override string ToString() {
return Name;
}
}
} | apache-2.0 | C# |
e7e40350a1d32d86e259e957096875a16863b2de | Bump to version 0.1.1. | FacilityApi/FacilityCSharp | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("0.1.1.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| using System.Reflection;
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| mit | C# |
3e31196b9e2c985dc1b5c0dddca251f365287e3f | Check all commands for validation msg with Identifier strings, close #116 | kotorihq/kotori-core | KotoriCore/Commands/Project/CreateProjectKey.cs | KotoriCore/Commands/Project/CreateProjectKey.cs | using System.Collections.Generic;
using KotoriCore.Configurations;
using KotoriCore.Helpers;
namespace KotoriCore.Commands
{
/// <summary>
/// Create project key command.
/// </summary>
public class CreateProjectKey : Command
{
/// <summary>
/// The instance.
/// </summary>
public readonly string Instance;
/// <summary>
/// The project identifier.
/// </summary>
public readonly string ProjectId;
/// <summary>
/// The project key.
/// </summary>
public readonly ProjectKey ProjectKey;
/// <summary>
/// Initializes a new instance of the <see cref="T:KotoriCore.Commands.ProjectAddKey"/> class.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="projectId">Project identifier.</param>
/// <param name="projectKey">Project key.</param>
public CreateProjectKey(string instance, string projectId, ProjectKey projectKey)
{
Instance = instance;
ProjectId = projectId;
ProjectKey = projectKey;
}
/// <summary>
/// Validates the command.
/// </summary>
/// <returns>The validate result.</returns>
public override IEnumerable<ValidationResult> Validate()
{
if (string.IsNullOrEmpty(Instance))
yield return new ValidationResult("Instance must be set.");
if (string.IsNullOrEmpty(ProjectId))
yield return new ValidationResult("Project Id must be set.");
if (ProjectKey == null)
yield return new ValidationResult("Project key must be set.");
if (string.IsNullOrEmpty(ProjectKey.Key))
yield return new ValidationResult("Project key must be set.");
}
}
}
| using System.Collections.Generic;
using KotoriCore.Configurations;
using KotoriCore.Helpers;
namespace KotoriCore.Commands
{
/// <summary>
/// Create project key command.
/// </summary>
public class CreateProjectKey : Command
{
/// <summary>
/// Gets the instance.
/// </summary>
public readonly string Instance;
/// <summary>
/// Gets the project identifier.
/// </summary>
public readonly string ProjectId;
/// <summary>
/// Gets the project key.
/// </summary>
public readonly ProjectKey ProjectKey;
/// <summary>
/// Initializes a new instance of the <see cref="T:KotoriCore.Commands.ProjectAddKey"/> class.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="projectId">Project identifier.</param>
/// <param name="projectKey">Project key.</param>
public CreateProjectKey(string instance, string projectId, ProjectKey projectKey)
{
Instance = instance;
ProjectId = projectId;
ProjectKey = projectKey;
}
/// <summary>
/// Validates the command.
/// </summary>
/// <returns>The validate result.</returns>
public override IEnumerable<ValidationResult> Validate()
{
if (string.IsNullOrEmpty(Instance))
yield return new ValidationResult("Instance must be set.");
if (string.IsNullOrEmpty(ProjectId))
yield return new ValidationResult("Project Id must be set.");
if (ProjectKey == null)
yield return new ValidationResult("Project key must be set.");
if (string.IsNullOrEmpty(ProjectKey.Key))
yield return new ValidationResult("Project key must be set.");
}
}
}
| mit | C# |
5a3903c1b8a32dad609072a61c84651344faf684 | Update assembly info for development of the next version | nanathan/ManeuverNodeSplitter | ManeuverNodeSplitter/Properties/AssemblyInfo.cs | ManeuverNodeSplitter/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ManeuverNodeSplitter")]
[assembly: AssemblyDescription("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ManeuverNodeSplitter")]
[assembly: AssemblyCopyright("Copyright © 2016 nanathan")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cd8998f3-feab-4d6f-839d-595e305e3aff")]
// 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.2")]
[assembly: AssemblyFileVersion("1.2.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("ManeuverNodeSplitter")]
[assembly: AssemblyDescription("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ManeuverNodeSplitter")]
[assembly: AssemblyCopyright("Copyright © 2016 nanathan")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cd8998f3-feab-4d6f-839d-595e305e3aff")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1")]
[assembly: AssemblyFileVersion("1.1.0")]
| mit | C# |
dc489d7ba198e9e4110dd603b713b349204097c9 | Remove unused method | wyldphyre/KaomojiTray | KaomojiTray/MainWindow.xaml.cs | KaomojiTray/MainWindow.xaml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace KaomojiTray
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Deactivated(object sender, EventArgs e)
{
Close();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace KaomojiTray
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_LostFocus(object sender, RoutedEventArgs e)
{
Close();
}
private void Window_Deactivated(object sender, EventArgs e)
{
Close();
}
}
}
| apache-2.0 | C# |
a69bb797fbfb2f65d0caeee94bb222b1ad347cf9 | Return the value of the animation | martijn00/LottieXamarin,fabionuno/LottieXamarin,fabionuno/LottieXamarin,martijn00/LottieXamarin | Lottie.iOS/LOTAnimationView.cs | Lottie.iOS/LOTAnimationView.cs | using System;
using System.Threading.Tasks;
using Foundation;
namespace Airbnb.Lottie
{
public partial class LOTAnimationView
{
/// <summary>
/// Asynchronously play the animation.
/// </summary>
public async Task<bool> PlayAsync()
{
var tcs = new TaskCompletionSource<bool>();
this.CompletionBlock = animationFinished => tcs.SetResult(true);
this.Play();
return await tcs.Task;
}
/// <summary>
/// Plays the animation from its current position to a specific progress.
/// The animation will start from its current position.
/// </summary>
public Task<bool> PlayToProgressAsync(nfloat toProgress)
{
var tcs = new TaskCompletionSource<bool>();
this.PlayToProgress(toProgress, (bool animationFinished) => tcs.SetResult(animationFinished));
return tcs.Task;
}
public Task<bool> PlayFromProgressAsync(nfloat fromStartProgress, nfloat toEndProgress)
{
var tcs = new TaskCompletionSource<bool>();
this.PlayFromProgress(fromStartProgress, toEndProgress, (bool animationFinished) => tcs.SetResult(animationFinished));
return tcs.Task;
}
public Task<bool> PlayToFrameAsync(NSNumber toFrame)
{
var tcs = new TaskCompletionSource<bool>();
this.PlayToFrame(toFrame, (bool animationFinished) => tcs.SetResult(animationFinished));
return tcs.Task;
}
public Task<bool> PlayFromFrameAsync(NSNumber fromStartFrame, NSNumber toEndFrame)
{
var tcs = new TaskCompletionSource<bool>();
this.PlayFromFrame(fromStartFrame, toEndFrame, (bool animationFinished) => tcs.SetResult(animationFinished));
return tcs.Task;
}
}
}
| using System;
using System.Threading.Tasks;
using Foundation;
namespace Airbnb.Lottie
{
public partial class LOTAnimationView
{
/// <summary>
/// Asynchronously play the animation.
/// </summary>
public async Task<bool> PlayAsync()
{
var tcs = new TaskCompletionSource<bool>();
this.CompletionBlock = animationFinished => tcs.SetResult(true);
this.Play();
await tcs.Task;
}
/// <summary>
/// Plays the animation from its current position to a specific progress.
/// The animation will start from its current position.
/// </summary>
public Task<bool> PlayToProgressAsync(nfloat toProgress)
{
var tcs = new TaskCompletionSource<bool>();
this.PlayToProgress(toProgress, (bool animationFinished) => tcs.SetResult(animationFinished));
return tcs.Task;
}
public Task<bool> PlayFromProgressAsync(nfloat fromStartProgress, nfloat toEndProgress)
{
var tcs = new TaskCompletionSource<bool>();
this.PlayFromProgress(fromStartProgress, toEndProgress, (bool animationFinished) => tcs.SetResult(animationFinished));
return tcs.Task;
}
public Task<bool> PlayToFrameAsync(NSNumber toFrame)
{
var tcs = new TaskCompletionSource<bool>();
this.PlayToFrame(toFrame, (bool animationFinished) => tcs.SetResult(animationFinished));
return tcs.Task;
}
public Task<bool> PlayFromFrameAsync(NSNumber fromStartFrame, NSNumber toEndFrame)
{
var tcs = new TaskCompletionSource<bool>();
this.PlayFromFrame(fromStartFrame, toEndFrame, (bool animationFinished) => tcs.SetResult(animationFinished));
return tcs.Task;
}
}
}
| apache-2.0 | C# |
520835b263bff83268c771815cd0974f7c823369 | Add comment to explain empty binding | kendaleiv/ui-specflow-selenium,kendaleiv/ui-specflow-selenium,kendaleiv/ui-specflow-selenium | Web.UI.Tests/GherkinTableSteps.cs | Web.UI.Tests/GherkinTableSteps.cs | using System;
using System.Collections.Generic;
using System.Linq;
using TechTalk.SpecFlow;
using TechTalk.SpecFlow.Assist;
using Xunit;
namespace Web.UI.Tests
{
[Binding]
public class GherkinTableSteps
{
private static IEnumerable<CourseInformation> Courses;
[Given(@"I have the course information")]
public void GivenIHaveTheCourseInformation(Table table)
{
Courses = table.CreateSet<CourseInformation>();
}
[When(@"I get a list of available courses")]
public void WhenIGetAListOfAvailableCourses()
{
// If this was an actual UI test
// We might be invoking the browser here.
}
[Then(@"I should see there are (.*) courses")]
public void ThenIShouldSeeThereAreCourses(int count)
{
Assert.Equal(count, Courses.Count());
}
[Then(@"I should see (.*) is instructing (.*)")]
public void ThenIShouldSeeIsInstructing(string instructor, string name)
{
var course = Courses.Single(
x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase));
Assert.Equal(instructor, course.Instructor);
}
[Then(@"I should see (.*) is scheduled for (.*)")]
public void ThenIShouldSeeIntroductionToCommandIsScheduledForAM(string name, string scheduled)
{
var scheduledDateTime = DateTime.Parse(scheduled);
var course = Courses.Single(
x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase));
Assert.Equal(scheduledDateTime, course.Scheduled);
}
public class CourseInformation
{
public string Name { get; set; }
public string Instructor { get; set; }
public string Location { get; set; }
public DateTime Scheduled { get; set; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using TechTalk.SpecFlow;
using TechTalk.SpecFlow.Assist;
using Xunit;
namespace Web.UI.Tests
{
[Binding]
public class GherkinTableSteps
{
private static IEnumerable<CourseInformation> Courses;
[Given(@"I have the course information")]
public void GivenIHaveTheCourseInformation(Table table)
{
Courses = table.CreateSet<CourseInformation>();
}
[When(@"I get a list of available courses")]
public void WhenIGetAListOfAvailableCourses()
{
}
[Then(@"I should see there are (.*) courses")]
public void ThenIShouldSeeThereAreCourses(int count)
{
Assert.Equal(count, Courses.Count());
}
[Then(@"I should see (.*) is instructing (.*)")]
public void ThenIShouldSeeIsInstructing(string instructor, string name)
{
var course = Courses.Single(
x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase));
Assert.Equal(instructor, course.Instructor);
}
[Then(@"I should see (.*) is scheduled for (.*)")]
public void ThenIShouldSeeIntroductionToCommandIsScheduledForAM(string name, string scheduled)
{
var scheduledDateTime = DateTime.Parse(scheduled);
var course = Courses.Single(
x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase));
Assert.Equal(scheduledDateTime, course.Scheduled);
}
public class CourseInformation
{
public string Name { get; set; }
public string Instructor { get; set; }
public string Location { get; set; }
public DateTime Scheduled { get; set; }
}
}
}
| mit | C# |
66956b0a60bac73c39185eb11c24759957986d0d | add scenario test | jwChung/Experimentalism,jwChung/Experimentalism | test/ExperimentalUnitTest/Scenario.cs | test/ExperimentalUnitTest/Scenario.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using Xunit;
using Xunit.Extensions;
namespace Jwc.Experimental
{
public class Scenario
{
[Theorem]
public void TheoremOnMethodIndicatesTestCase()
{
Assert.True(true, "excuted.");
}
[Theorem]
[InlineData("expected", 1234)]
[ParameterizedTestData]
public void TheoremSupportsParameterizedTest(string arg1, int arg2)
{
Assert.Equal("expected", arg1);
Assert.Equal(1234, arg2);
}
public class ParameterizedTestDataAttribute : DataAttribute
{
public override IEnumerable<object[]> GetData(MethodInfo methodUnderTest, Type[] parameterTypes)
{
yield return new object[] { "expected", 1234 };
}
}
}
} | using Xunit;
namespace Jwc.Experimental
{
public class Scenario
{
[Theorem]
public void TheoremAttributeOnMethodIndicatesTestCase()
{
Assert.True(true, "excuted.");
}
}
} | mit | C# |
08e1dcda0c531c996e95a6a02241136629da9bfd | Update state string to Header referer | davidebbo/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,fashaikh/SimpleWAWS,projectkudu/SimpleWAWS,fashaikh/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,projectkudu/TryAppService,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS | SimpleWAWS/Authentication/GoogleAuthProvider.cs | SimpleWAWS/Authentication/GoogleAuthProvider.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace SimpleWAWS.Authentication
{
public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider
{
public override string GetLoginUrl(HttpContextBase context)
{
var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant();
var builder = new StringBuilder();
builder.Append("https://accounts.google.com/o/oauth2/auth");
builder.Append("?response_type=id_token");
builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"])));
builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId);
builder.AppendFormat("&scope={0}", "email");
if (context.IsFunctionsPortalRequest())
{
builder.AppendFormat("&state={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "/{0}/{1}", context.Request.Headers["Referer"], context.Request.Url.Query) ));
}
else
builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery));
return builder.ToString();
}
protected override string GetValidAudiance()
{
return AuthSettings.GoogleAppId;
}
public override string GetIssuerName(string altSecId)
{
return "Google";
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace SimpleWAWS.Authentication
{
public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider
{
public override string GetLoginUrl(HttpContextBase context)
{
var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant();
var builder = new StringBuilder();
builder.Append("https://accounts.google.com/o/oauth2/auth");
builder.Append("?response_type=id_token");
builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"])));
builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId);
builder.AppendFormat("&scope={0}", "email");
if (context.IsFunctionsPortalRequest())
{
builder.AppendFormat("&state={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "/{0}/{1}", context.Request.Headers["Origin"], context.Request.Url.Query) ));
}
else
builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery));
return builder.ToString();
}
protected override string GetValidAudiance()
{
return AuthSettings.GoogleAppId;
}
public override string GetIssuerName(string altSecId)
{
return "Google";
}
}
} | apache-2.0 | C# |
5bdd0277b7ed936d389f9024b499996d2117212b | Increase version number to 1.2.0.0. | TorbenRahbekKoch/SoftwarePassion.Common | Source/Projects/Core/Properties/AssemblyInfo.cs | Source/Projects/Core/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Common.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Software Passion")]
[assembly: AssemblyProduct("Common.Core")]
[assembly: AssemblyCopyright("Copyright © Software Passion 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("30a96287-13a9-48e0-85db-4d0afe222eaf")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Common.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Software Passion")]
[assembly: AssemblyProduct("Common.Core")]
[assembly: AssemblyCopyright("Copyright © Software Passion 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("30a96287-13a9-48e0-85db-4d0afe222eaf")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| mit | C# |
f09a4be01798ecfe2bb2de7849a61fab4437ab33 | Update demo | sunkaixuan/SqlSugar | Src/Asp.Net/SqlServerTest/Demo/DemoD_DbFirst.cs | Src/Asp.Net/SqlServerTest/Demo/DemoD_DbFirst.cs | using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OrmTest
{
public class DemoD_DbFirst
{
public static void Init()
{
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
db.DbFirst.CreateClassFile("c:\\Demo\\1", "Models");
db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\2", "Models");
db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\3", "Models");
db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\4", "Models");
db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\5", "Models");
db.DbFirst.IsCreateDefaultValue().CreateClassFile("c:\\Demo\\6", "Demo.Models");
db.DbFirst. SettingClassTemplate(old => { return old;})
.SettingNamespaceTemplate(old =>{ return old;})
.SettingPropertyDescriptionTemplate(old =>
{
return @" /// <summary>
/// Desc_New:{PropertyDescription}
/// Default_New:{DefaultValue}
/// Nullable_New:{IsNullable}
/// </summary>";
})
.SettingPropertyTemplate(old =>{return old;})
.SettingConstructorTemplate(old =>{return old; })
.CreateClassFile("c:\\Demo\\7");
}
}
}
| using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OrmTest
{
public class DemoD_DbFirst
{
public static void Init()
{
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
}
}
});
db.DbFirst.CreateClassFile("c:\\Demo\\1", "Models");
db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\2", "Models");
db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\3");
db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\4");
}
}
}
| apache-2.0 | C# |
28b5f07273bd38469fa87b5379ccb115996ed4ca | Update tests | CareerHub/.NET-CareerHub-API-Client,CareerHub/.NET-CareerHub-API-Client | Test/API/Authorization/AuthorizationApiFacts.cs | Test/API/Authorization/AuthorizationApiFacts.cs | using CareerHub.Client.API.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace CareerHub.Client.Tests.API.Authorization {
public class AuthorizationApiFacts {
[Fact]
public void Get_TokenInfo_Url() {
string accessToken = "adsfasdfasdf";
string scope1 = "Test.Scope.1";
string scope2 = "Test.Scope.2";
string expected = String.Format("tokeninfo?access_token={0}&scopes={1}&scopes={2}", accessToken, scope1, scope2);
string actual = AuthorizationApi.GetTokenInfoUrl(accessToken, new string[] { scope1, scope2 });
Assert.Equal(expected, actual);
}
[Fact]
public void Get_TokenInfo_Url_Throws_Null_Access_Token() {
Assert.Throws<ArgumentNullException>(() => {
AuthorizationApi.GetTokenInfoUrl(null, new string[] { });
});
}
[Fact]
public void Get_TokenInfo_Url_Throws_Null_Scopes() {
Assert.Throws<ArgumentNullException>(() => {
AuthorizationApi.GetTokenInfoUrl("test", null);
});
}
}
}
| using CareerHub.Client.API.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace CareerHub.Client.Tests.API.Authorization {
public class AuthorizationApiFacts {
[Fact]
public void Get_TokenInfo_Url() {
string accessToken = "adsfasdfasdf";
string scope1 = "Test.Scope.1";
string scope2 = "Test.Scope.2";
string expected = String.Format("/tokeninfo?access_token={0}&scopes={1}&scopes={2}", accessToken, scope1, scope2);
string actual = AuthorizationApi.GetTokenInfoUrl(accessToken, new string[] { scope1, scope2 });
Assert.Equal(expected, actual);
}
[Fact]
public void Get_TokenInfo_Url_Throws_Null_Access_Token() {
Assert.Throws<ArgumentNullException>(() => {
AuthorizationApi.GetTokenInfoUrl(null, new string[] { });
});
}
[Fact]
public void Get_TokenInfo_Url_Throws_Null_Scopes() {
Assert.Throws<ArgumentNullException>(() => {
AuthorizationApi.GetTokenInfoUrl("test", null);
});
}
}
}
| mit | C# |
a457cb90ffdea12b93178cbfaf3e381987862d9c | Improve PpwAuxiliaryDatabaseObject further (in progress) + rename IHbmMapping to IPpwHbmMapping | peopleware/net-ppwcode-vernacular-nhibernate | src/PPWCode.Vernacular.NHibernate.I.Tests/IntegrationTests/BaseQueryTests.cs | src/PPWCode.Vernacular.NHibernate.I.Tests/IntegrationTests/BaseQueryTests.cs | // Copyright 2017 by PeopleWare n.v..
//
// 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.Collections.Generic;
using NHibernate.Mapping;
using PPWCode.Vernacular.NHibernate.I.Interfaces;
using PPWCode.Vernacular.NHibernate.I.Test;
using PPWCode.Vernacular.NHibernate.I.Utilities;
namespace PPWCode.Vernacular.NHibernate.I.Tests.IntegrationTests
{
public abstract class BaseQueryTests : BaseRepositoryFixture<int, TestIntAuditLog>
{
private IPpwHbmMapping m_PpwHbmMapping;
protected override string CatalogName
{
get { return "Test.PPWCode.Vernacular.NHibernate.I.Tests"; }
}
protected override string ConnectionString
{
get { return FixedConnectionString; }
}
protected override IPpwHbmMapping PpwHbmMapping
{
get { return m_PpwHbmMapping ?? (m_PpwHbmMapping = new TestsSimpleModelMapper(new TestsMappingAssemblies())); }
}
protected override string IdentityName
{
get { return "Test - IdentityName"; }
}
protected override IEnumerable<IAuxiliaryDatabaseObject> AuxiliaryDatabaseObjects
{
get
{
yield return new TestHighLowPerTableAuxiliaryDatabaseObject(PpwHbmMapping);
}
}
}
}
| // Copyright 2017 by PeopleWare n.v..
//
// 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.Collections.Generic;
using NHibernate.Mapping;
using PPWCode.Vernacular.NHibernate.I.Interfaces;
using PPWCode.Vernacular.NHibernate.I.Test;
using PPWCode.Vernacular.NHibernate.I.Utilities;
namespace PPWCode.Vernacular.NHibernate.I.Tests.IntegrationTests
{
public abstract class BaseQueryTests : BaseRepositoryFixture<int, TestIntAuditLog>
{
private IPpwHbmMapping m_PpwHbmMapping;
protected override string CatalogName
{
get { return "Test.PPWCode.Vernacular.NHibernate.I.Tests"; }
}
protected override string ConnectionString
{
get { return FixedConnectionString; }
}
protected override IPpwHbmMapping PpwHbmMapping
{
get { return m_PpwHbmMapping ?? (m_PpwHbmMapping = new TestsSimpleModelMapper(new TestsMappingAssemblies())); }
}
protected override string IdentityName
{
get { return "Test - IdentityName"; }
}
protected override IEnumerable<IAuxiliaryDatabaseObject> AuxiliaryDatabaseObjects
{
get
{
yield return new TestHighLowPerTableAuxiliaryDatabaseObject(PpwHbmMapping);
yield return new PpwSubclassCheckConstraintsAuxiliaryDatabaseObject(PpwHbmMapping);
}
}
}
}
| apache-2.0 | C# |
4f48aa3d2e72b4c8647c8576a09eeee246885511 | Use interface for bind/unbind instead of raw component | ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework | osu.Framework/Audio/AdjustableAudioComponent.cs | osu.Framework/Audio/AdjustableAudioComponent.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;
namespace osu.Framework.Audio
{
/// <summary>
/// An audio component which allows for basic bindable adjustments to be applied.
/// </summary>
public class AdjustableAudioComponent : AudioComponent, IAggregateAudioAdjustment
{
private readonly AudioAdjustments adjustments = new AudioAdjustments();
/// <summary>
/// The volume of this component.
/// </summary>
public BindableDouble Volume => adjustments.Volume;
/// <summary>
/// The playback balance of this sample (-1 .. 1 where 0 is centered)
/// </summary>
public BindableDouble Balance => adjustments.Balance;
/// <summary>
/// Rate at which the component is played back (affects pitch). 1 is 100% playback speed, or default frequency.
/// </summary>
public BindableDouble Frequency => adjustments.Frequency;
protected AdjustableAudioComponent()
{
AggregateVolume.ValueChanged += InvalidateState;
AggregateBalance.ValueChanged += InvalidateState;
AggregateFrequency.ValueChanged += InvalidateState;
}
public void AddAdjustment(AdjustableProperty type, BindableDouble adjustBindable) =>
adjustments.AddAdjustment(type, adjustBindable);
public void RemoveAdjustment(AdjustableProperty type, BindableDouble adjustBindable) =>
adjustments.RemoveAdjustment(type, adjustBindable);
internal void InvalidateState(ValueChangedEvent<double> valueChangedEvent = null) => EnqueueAction(OnStateChanged);
internal virtual void OnStateChanged()
{
}
/// <summary>
/// Bind all adjustments to another component's aggregated results.
/// </summary>
/// <param name="component">The other component (generally a direct parent).</param>
internal void BindAdjustments(IAggregateAudioAdjustment component) => adjustments.BindAdjustments(component);
/// <summary>
/// Unbind all adjustments from another component's aggregated results.
/// </summary>
/// <param name="component">The other component (generally a direct parent).</param>
internal void UnbindAdjustments(IAggregateAudioAdjustment component) => adjustments.UnbindAdjustments(component);
public IBindable<double> AggregateVolume => adjustments.AggregateVolume;
public IBindable<double> AggregateBalance => adjustments.AggregateBalance;
public IBindable<double> AggregateFrequency => adjustments.AggregateFrequency;
}
public enum AdjustableProperty
{
Volume,
Balance,
Frequency
}
}
| // 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;
namespace osu.Framework.Audio
{
/// <summary>
/// An audio component which allows for basic bindable adjustments to be applied.
/// </summary>
public class AdjustableAudioComponent : AudioComponent, IAggregateAudioAdjustment
{
private readonly AudioAdjustments adjustments = new AudioAdjustments();
/// <summary>
/// The volume of this component.
/// </summary>
public BindableDouble Volume => adjustments.Volume;
/// <summary>
/// The playback balance of this sample (-1 .. 1 where 0 is centered)
/// </summary>
public BindableDouble Balance => adjustments.Balance;
/// <summary>
/// Rate at which the component is played back (affects pitch). 1 is 100% playback speed, or default frequency.
/// </summary>
public BindableDouble Frequency => adjustments.Frequency;
protected AdjustableAudioComponent()
{
AggregateVolume.ValueChanged += InvalidateState;
AggregateBalance.ValueChanged += InvalidateState;
AggregateFrequency.ValueChanged += InvalidateState;
}
public void AddAdjustment(AdjustableProperty type, BindableDouble adjustBindable) =>
adjustments.AddAdjustment(type, adjustBindable);
public void RemoveAdjustment(AdjustableProperty type, BindableDouble adjustBindable) =>
adjustments.RemoveAdjustment(type, adjustBindable);
internal void InvalidateState(ValueChangedEvent<double> valueChangedEvent = null) => EnqueueAction(OnStateChanged);
internal virtual void OnStateChanged()
{
}
/// <summary>
/// Bind all adjustments to another component's aggregated results.
/// </summary>
/// <param name="component">The other component (generally a direct parent).</param>
internal void BindAdjustments(AdjustableAudioComponent component) => adjustments.BindAdjustments(component);
/// <summary>
/// Unbind all adjustments from another component's aggregated results.
/// </summary>
/// <param name="component">The other component (generally a direct parent).</param>
internal void UnbindAdjustments(AdjustableAudioComponent component) => adjustments.UnbindAdjustments(component);
public IBindable<double> AggregateVolume => adjustments.AggregateVolume;
public IBindable<double> AggregateBalance => adjustments.AggregateBalance;
public IBindable<double> AggregateFrequency => adjustments.AggregateFrequency;
}
public enum AdjustableProperty
{
Volume,
Balance,
Frequency
}
}
| mit | C# |
a3f29625587fd0cb52c8d4042dd1b48f82d62db2 | Disable "deselect all mods" button if none are selected | ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu | osu.Game/Overlays/Mods/DeselectAllModsButton.cs | osu.Game/Overlays/Mods/DeselectAllModsButton.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.Collections.Generic;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input.Bindings;
using osu.Game.Localisation;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Overlays.Mods
{
public class DeselectAllModsButton : ShearedButton, IKeyBindingHandler<GlobalAction>
{
private readonly Bindable<IReadOnlyList<Mod>> selectedMods = new Bindable<IReadOnlyList<Mod>>();
public DeselectAllModsButton(ModSelectOverlay modSelectOverlay)
: base(ModSelectOverlay.BUTTON_WIDTH)
{
Text = CommonStrings.DeselectAll;
Action = modSelectOverlay.DeselectAll;
selectedMods.BindTo(modSelectOverlay.SelectedMods);
}
protected override void LoadComplete()
{
base.LoadComplete();
selectedMods.BindValueChanged(_ => updateEnabledState(), true);
}
private void updateEnabledState()
{
Enabled.Value = selectedMods.Value.Any();
}
public bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
{
if (e.Repeat || e.Action != GlobalAction.DeselectAllMods)
return false;
TriggerClick();
return true;
}
public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input.Bindings;
using osu.Game.Localisation;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Overlays.Mods
{
public class DeselectAllModsButton : ShearedButton, IKeyBindingHandler<GlobalAction>
{
public DeselectAllModsButton(ModSelectOverlay modSelectOverlay)
: base(ModSelectOverlay.BUTTON_WIDTH)
{
Text = CommonStrings.DeselectAll;
Action = modSelectOverlay.DeselectAll;
}
public bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
{
if (e.Repeat || e.Action != GlobalAction.DeselectAllMods)
return false;
TriggerClick();
return true;
}
public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
{
}
}
}
| mit | C# |
d7417312fb8084969192fab54c5a708b0ffe0a9e | Fix nuget package order. | avidafinance/FinancialUtility | Avida.FinancialUtility.Tests/SwedenTests.cs | Avida.FinancialUtility.Tests/SwedenTests.cs | using Avida.FinancialUtility.NationalIdentification;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Avida.FinancialUtility.Tests
{
[TestClass]
public class SwedenTests
{
/// <summary>
/// Simple test of age.
/// </summary>
[TestMethod]
public void TestAge()
{
var nr = new CivicRegNumberSe("19790717-9191");
var age1 = CivicRegNumberSe.GetAgeInYears(nr, new DateTime(2015, 7, 16));
Assert.AreEqual(35, age1);
var age2 = CivicRegNumberSe.GetAgeInYears(nr, new DateTime(2015, 7, 17));
Assert.AreEqual(36, age2);
Assert.AreEqual(nr.DateOfBirth, new DateTime(1979, 7, 17));
}
}
}
| using Avida.FinancialUtility.NationalIdentification;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Avida.FinancialUtility.Tests
{
[TestClass]
public class SwedenTests
{
[TestMethod]
public void TestAge()
{
var nr = new CivicRegNumberSe("19790717-9191");
var age1 = CivicRegNumberSe.GetAgeInYears(nr, new DateTime(2015, 7, 16));
Assert.AreEqual(35, age1);
var age2 = CivicRegNumberSe.GetAgeInYears(nr, new DateTime(2015, 7, 17));
Assert.AreEqual(36, age2);
Assert.AreEqual(nr.DateOfBirth, new DateTime(1979, 7, 17));
}
}
}
| apache-2.0 | C# |
8500e39b1eb1dad1904a66649d959bfd4d0c7544 | test 2 | MatthewKapteyn/SubmoduleTest | SubmoduleTest/IwantTOStashThis.cs | SubmoduleTest/IwantTOStashThis.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace SubmoduleTest
{
class IwantTOStashThis
{
// This change is lovely, keep this one
// generic asdfjoa asdfk;jasd
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace SubmoduleTest
{
class IwantTOStashThis
{
// This change is lovely, keep this one
}
}
| unlicense | C# |
c5d2dc2f6a4e0751d0592f0ea028232017c5e34e | Remove unnecessary newline | smoogipooo/osu,DrabWeb/osu,johnneijzen/osu,DrabWeb/osu,peppy/osu,ZLima12/osu,ppy/osu,DrabWeb/osu,peppy/osu-new,naoey/osu,UselessToucan/osu,ZLima12/osu,EVAST9919/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,2yangk23/osu,ppy/osu,naoey/osu,ppy/osu,naoey/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,2yangk23/osu,peppy/osu,EVAST9919/osu | osu.Game/Database/IHasFiles.cs | osu.Game/Database/IHasFiles.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
namespace osu.Game.Database
{
/// <summary>
/// A model that contains a list of files it is responsible for.
/// </summary>
/// <typeparam name="TFile">The model representing a file.</typeparam>
public interface IHasFiles<TFile>
where TFile : INamedFileInfo
{
List<TFile> Files { get; set; }
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
namespace osu.Game.Database
{
/// <summary>
/// A model that contains a list of files it is responsible for.
/// </summary>
/// <typeparam name="TFile">The model representing a file.</typeparam>
public interface IHasFiles<TFile>
where TFile : INamedFileInfo
{
List<TFile> Files { get; set; }
}
}
| mit | C# |
9990d3d35048a83d765928e2c40528b0f86ec2d3 | Remove old comments | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/MainViewModel.cs | WalletWasabi.Fluent/ViewModels/MainViewModel.cs | using NBitcoin;
using ReactiveUI;
using System.Reactive;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Fluent.ViewModels.Dialogs;
using Global = WalletWasabi.Gui.Global;
namespace WalletWasabi.Fluent.ViewModels
{
public class MainViewModel : ViewModelBase, IScreen, IDialogHost
{
private Global _global;
private NavigationStateViewModel _navigationState;
private StatusBarViewModel _statusBar;
private string _title = "Wasabi Wallet";
private DialogScreenViewModel _dialogScreen;
private DialogViewModelBase _currentDialog;
private NavBarViewModel _navBar;
public MainViewModel(Global global)
{
_global = global;
_dialogScreen = new DialogScreenViewModel();
_navigationState = new NavigationStateViewModel()
{
MainScreen = () => this,
DialogScreen = () => _dialogScreen,
DialogHost = () => this
};
Network = global.Network;
StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments);
NavBar = new NavBarViewModel(_navigationState, Router, global.WalletManager, global.UiConfig);
}
public static MainViewModel Instance { get; internal set; }
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; }
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public Network Network { get; }
public DialogScreenViewModel DialogScreen
{
get => _dialogScreen;
set => this.RaiseAndSetIfChanged(ref _dialogScreen, value);
}
public DialogViewModelBase CurrentDialog
{
get => _currentDialog;
set => this.RaiseAndSetIfChanged(ref _currentDialog, value);
}
public NavBarViewModel NavBar
{
get => _navBar;
set => this.RaiseAndSetIfChanged(ref _navBar, value);
}
public StatusBarViewModel StatusBar
{
get => _statusBar;
set => this.RaiseAndSetIfChanged(ref _statusBar, value);
}
public string Title
{
get => _title;
internal set => this.RaiseAndSetIfChanged(ref _title, value);
}
public void Initialize()
{
// Temporary to keep things running without VM modifications.
MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false);
StatusBar.Initialize(_global.Nodes.ConnectedNodes);
if (Network != Network.Main)
{
Title += $" - {Network}";
}
}
}
}
| using NBitcoin;
using ReactiveUI;
using System.Reactive;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Fluent.ViewModels.Dialogs;
using Global = WalletWasabi.Gui.Global;
namespace WalletWasabi.Fluent.ViewModels
{
public class MainViewModel : ViewModelBase, IScreen, IDialogHost
{
private Global _global;
private NavigationStateViewModel _navigationState;
private StatusBarViewModel _statusBar;
private string _title = "Wasabi Wallet";
private DialogScreenViewModel _dialogScreen;
private DialogViewModelBase _currentDialog;
private NavBarViewModel _navBar;
public MainViewModel(Global global)
{
_global = global;
_dialogScreen = new DialogScreenViewModel();
// TODO: Set Dialog with IScreen implementation
// TODO: Set default NextView
// TODO: Set default CancelView
_navigationState = new NavigationStateViewModel()
{
MainScreen = () => this,
DialogScreen = () => _dialogScreen,
DialogHost = () => this
};
Network = global.Network;
StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments);
NavBar = new NavBarViewModel(_navigationState, Router, global.WalletManager, global.UiConfig);
}
public static MainViewModel Instance { get; internal set; }
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; }
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public Network Network { get; }
public DialogScreenViewModel DialogScreen
{
get => _dialogScreen;
set => this.RaiseAndSetIfChanged(ref _dialogScreen, value);
}
public DialogViewModelBase CurrentDialog
{
get => _currentDialog;
set => this.RaiseAndSetIfChanged(ref _currentDialog, value);
}
public NavBarViewModel NavBar
{
get => _navBar;
set => this.RaiseAndSetIfChanged(ref _navBar, value);
}
public StatusBarViewModel StatusBar
{
get => _statusBar;
set => this.RaiseAndSetIfChanged(ref _statusBar, value);
}
public string Title
{
get => _title;
internal set => this.RaiseAndSetIfChanged(ref _title, value);
}
public void Initialize()
{
// Temporary to keep things running without VM modifications.
MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false);
StatusBar.Initialize(_global.Nodes.ConnectedNodes);
if (Network != Network.Main)
{
Title += $" - {Network}";
}
}
}
}
| mit | C# |
507f5416eb7b8d4bab818c020a30d1b2ecceafa4 | Store extracted pages in subfolder | eggapauli/MyDocs,eggapauli/MyDocs | WindowsStore/Service/PdfPageExtractorService.cs | WindowsStore/Service/PdfPageExtractorService.cs | using MyDocs.Common.Contract.Service;
using MyDocs.Common.Model.Logic;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Data.Pdf;
using Windows.Storage;
namespace MyDocs.WindowsStore.Service
{
public class PdfPageExtractorService : IPageExtractorService
{
public bool SupportsExtension(string extension)
{
return new[] { ".pdf" }.Contains(extension, StringComparer.OrdinalIgnoreCase);
}
public async Task<IEnumerable<Photo>> ExtractPages(StorageFile file, Document document)
{
var doc = await PdfDocument.LoadFromFileAsync(file);
var baseFolder = await file.GetParentAsync();
var folder = await baseFolder.CreateFolderAsync(Path.GetFileNameWithoutExtension(file.Name));
var extractTasks = Enumerable.Range(0, (int)doc.PageCount)
.Select(i => ExtractPage(doc, file.Name, i, folder));
var images = await Task.WhenAll(extractTasks);
return images.Select(image => new Photo(image));
}
private async Task<StorageFile> ExtractPage(PdfDocument doc, string fileName, int pageNumber, IStorageFolder folder)
{
var pageFileName = Path.ChangeExtension(fileName, ".jpg");
var image = await folder.CreateFileAsync(pageFileName, CreationCollisionOption.GenerateUniqueName);
using (var page = doc.GetPage((uint)pageNumber))
using (var stream = await image.OpenAsync(FileAccessMode.ReadWrite)) {
await page.RenderToStreamAsync(stream);
}
return image;
}
}
}
| using MyDocs.Common.Contract.Service;
using MyDocs.Common.Model.Logic;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Data.Pdf;
using Windows.Storage;
namespace MyDocs.WindowsStore.Service
{
public class PdfPageExtractorService : IPageExtractorService
{
public bool SupportsExtension(string extension)
{
return new[] { ".pdf" }.Contains(extension, StringComparer.OrdinalIgnoreCase);
}
public async Task<IEnumerable<Photo>> ExtractPages(StorageFile file, Document document)
{
var doc = await PdfDocument.LoadFromFileAsync(file);
var folder = ApplicationData.Current.TemporaryFolder;
var extractTasks = Enumerable.Range(0, (int)doc.PageCount)
.Select(i => ExtractPage(doc, file.Name, i, folder));
var images = await Task.WhenAll(extractTasks);
return images.Select(image => new Photo(image));
}
private async Task<StorageFile> ExtractPage(PdfDocument doc, string fileName, int pageNumber, StorageFolder folder)
{
var pageFileName = Path.ChangeExtension(fileName, ".jpg");
var image = await folder.CreateFileAsync(pageFileName, CreationCollisionOption.GenerateUniqueName);
using (var page = doc.GetPage((uint)pageNumber))
using (var stream = await image.OpenAsync(FileAccessMode.ReadWrite)) {
await page.RenderToStreamAsync(stream);
}
return image;
}
}
}
| mit | C# |
e65cb9c5fa9c306e1907a71e5c86d1369afa689b | fix 2s instead of 3 for stun and ice | kangoo13/GameToolBJTU,kangoo13/GameToolBJTU,kangoo13/GameToolBJTU,kangoo13/GameToolBJTU | Unity_TD/Assets/MonsterInfo.cs | Unity_TD/Assets/MonsterInfo.cs | using UnityEngine;
using System.Collections;
public class MonsterInfo : MonoBehaviour {
public bool isPoisoned = false;
public bool isImmunedToPoison = false;
public bool isImmunedToIce = false;
public bool isImmunedToStunned = false;
public bool isRegenerable = false;
public void touchedByIce()
{
if (!isImmunedToIce)
StartCoroutine(iced());
}
public void touchedByStun()
{
if (!isImmunedToStunned)
StartCoroutine(stunned());
}
public void touchedByPoison(int damage)
{
if (!isImmunedToPoison)
StartCoroutine(poisonned(damage));
}
IEnumerator iced() {
float i = 0f;
while (i <= 2f) {
GetComponent<MoveEnemy> ().isIced = true;
i += 0.05f;
yield return new WaitForSeconds(0.05f);
}
GetComponent<MoveEnemy> ().isIced = false;
}
IEnumerator stunned() {
float i = 0f;
while (i <= 2f) {
GetComponent<MoveEnemy> ().isStunned = true;
i += 0.05f;
yield return new WaitForSeconds(0.05f);
}
GetComponent<MoveEnemy> ().isStunned = false;
}
IEnumerator poisonned(int damage) {
int i = 0;
while (i != 3) {
i++;
float rdamage = damage / 10f;
GetComponentInChildren<HealthBar> ().currentHealth -= Mathf.Max(rdamage, 0);
yield return new WaitForSeconds(1);
}
}
// Update is called once per frame
void Update () {
HealthBar hb = GetComponentInChildren<HealthBar> ();
if (isRegenerable && hb.currentHealth < hb.maxHealth)
hb.currentHealth += Mathf.Min(hb.maxHealth / 200f, hb.maxHealth);
}
}
| using UnityEngine;
using System.Collections;
public class MonsterInfo : MonoBehaviour {
public bool isPoisoned = false;
public bool isImmunedToPoison = false;
public bool isImmunedToIce = false;
public bool isImmunedToStunned = false;
public bool isRegenerable = false;
void Start()
{
}
public void touchedByIce()
{
if (!isImmunedToIce)
StartCoroutine(iced());
}
public void touchedByStun()
{
if (!isImmunedToStunned)
StartCoroutine(stunned());
}
public void touchedByPoison(int damage)
{
if (!isImmunedToPoison)
StartCoroutine(poisonned(damage));
}
IEnumerator iced() {
float i = 0f;
while (i <= 3f) {
GetComponent<MoveEnemy> ().isIced = true;
i += 0.05f;
yield return new WaitForSeconds(0.05f);
}
GetComponent<MoveEnemy> ().isIced = false;
}
IEnumerator stunned() {
float i = 0f;
while (i <= 3f) {
GetComponent<MoveEnemy> ().isStunned = true;
i += 0.05f;
Debug.Log (i);
yield return new WaitForSeconds(0.05f);
}
GetComponent<MoveEnemy> ().isStunned = false;
}
IEnumerator poisonned(int damage) {
int i = 0;
while (i != 3) {
i++;
float rdamage = damage / 10f;
GetComponentInChildren<HealthBar> ().currentHealth -= Mathf.Max(rdamage, 0);
yield return new WaitForSeconds(1);
}
}
// Update is called once per frame
void Update () {
HealthBar hb = GetComponentInChildren<HealthBar> ();
if (isRegenerable && hb.currentHealth < hb.maxHealth)
hb.currentHealth += Mathf.Min(hb.maxHealth / 200f, hb.maxHealth);
}
}
| mit | C# |
79b6a2d37b7de1a86f3b19135e5e9d79b19472ad | Disable GetNextInfoId_Max test, takes forever | ermau/WinRT.NET | WinRT.NET/Tests/AsyncInfoTests.cs | WinRT.NET/Tests/AsyncInfoTests.cs | //
// IAsyncInfo.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2011 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using Windows.Foundation;
namespace WinRTNET.Tests
{
[TestFixture]
public class AsyncInfoTests
{
[Test]
public void GetNextInfoId()
{
uint id = AsyncInfo.GetNextInfoId();
Assert.Greater (AsyncInfo.GetNextInfoId(), id);
}
//[Test] Takes far too long to prove
public void GetNextInfoId_Max()
{
uint lastId = AsyncInfo.GetNextInfoId();
ulong count = UInt32.MaxValue - lastId;
for (ulong i = 0; i < count; ++i)
{
uint next = AsyncInfo.GetNextInfoId();
Assert.Greater (next, lastId);
lastId = next;
}
Assert.AreEqual (1, AsyncInfo.GetNextInfoId());
}
}
} | //
// IAsyncInfo.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2011 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using Windows.Foundation;
namespace WinRTNET.Tests
{
[TestFixture]
public class AsyncInfoTests
{
[Test]
public void GetNextInfoId()
{
uint id = AsyncInfo.GetNextInfoId();
Assert.Greater (AsyncInfo.GetNextInfoId(), id);
}
[Test]
public void GetNextInfoId_Max()
{
uint lastId = AsyncInfo.GetNextInfoId();
ulong count = UInt32.MaxValue - lastId;
for (ulong i = 0; i < count; ++i)
{
uint next = AsyncInfo.GetNextInfoId();
Assert.Greater (next, lastId);
lastId = next;
}
Assert.AreEqual (1, AsyncInfo.GetNextInfoId());
}
}
} | mit | C# |
5fd7722c4b2f2bbf2277c107f179ea63d806aed5 | add Foreground, Background | TakeAsh/cs-WpfUtility | WpfUtility/DataGridExAttribute.cs | WpfUtility/DataGridExAttribute.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TakeAshUtility;
namespace WpfUtility {
[AttributeUsage(AttributeTargets.Property)]
public class DataGridExAttribute :
Attribute {
public DataGridExAttribute() { }
public DataGridExAttribute(string header) {
Header = header;
}
[ToStringMember]
public string Header { get; set; }
[ToStringMember]
public bool Ignore { get; set; }
[ToStringMember]
public string StringFormat { get; set; }
[ToStringMember]
public string Foreground { get; set; }
[ToStringMember]
public string Background { get; set; }
public override string ToString() {
return this.ToStringMembers();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TakeAshUtility;
namespace WpfUtility {
[AttributeUsage(AttributeTargets.Property)]
public class DataGridExAttribute :
Attribute {
public DataGridExAttribute() { }
public DataGridExAttribute(string header) {
Header = header;
}
[ToStringMember]
public string Header { get; set; }
[ToStringMember]
public bool Ignore { get; set; }
[ToStringMember]
public string StringFormat { get; set; }
public override string ToString() {
return this.ToStringMembers();
}
}
}
| mit | C# |
f337cace8c57127963d6b6748cc318ddefd5a18d | update log file name | zhouyongtao/my_aspnetmvc_learning,zhouyongtao/my_aspnetmvc_learning | my_aspnetmvc_learning/Controllers/ImageController.cs | my_aspnetmvc_learning/Controllers/ImageController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NLog;
namespace my_aspnetmvc_learning.Controllers
{
public class ImageController : Controller
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
// GET: Upload
public ActionResult Index()
{
return View();
}
public ActionResult Upload()
{
for (var i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null)
{
logger.Info("FileName : " + file.FileName);
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName);
}
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace my_aspnetmvc_learning.Controllers
{
public class ImageController : Controller
{
// GET: Upload
public ActionResult Index()
{
return View();
}
public ActionResult Upload()
{
for (var i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null)
{
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName);
}
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
} | mit | C# |
f4d2262cf177c755ca0509069df5f6349c9cef4b | Add Genre model implementation. | TeamYAGNI/LibrarySystem | LibrarySystem/LibrarySystem.Models/Genre.cs | LibrarySystem/LibrarySystem.Models/Genre.cs | // <copyright file="Genre.cs" company="YAGNI">
// All rights reserved.
// </copyright>
// <summary>Holds implementation of Genre model.</summary>
using System.Collections.Generic;
namespace LibrarySystem.Models
{
/// <summary>
/// Represent a <see cref="Genre"/> entity model.
/// </summary>
public class Genre
{
/// <summary>
/// Books from the <see cref="Genre"/> entity.
/// </summary>
private ICollection<Book> books;
/// <summary>
/// Initializes a new instance of the <see cref="Genre"/> class.
/// </summary>
public Genre()
{
this.books = new HashSet<Book>();
}
/// <summary>
/// Gets or sets the primary key of the <see cref="Genre"/> entity.
/// </summary>
/// <value>Primary key of the <see cref="Genre"/> entity.</value>
public int Id { get; set; }
/// <summary>
/// Gets or sets the name of the <see cref="Genre"/> entity.
/// </summary>
/// <value>Name of the <see cref="Genre"/> entity.</value>
public string Name { get; set; }
/// <summary>
/// Gets or sets foreign key of the Genre to witch the <see cref="Genre"/> entity is sub-category.
/// </summary>
/// <value>Primary key of the sup-genre of the <see cref="Book"/> entity.</value>
public int SuperGenreId { get; set; }
/// <summary>
/// Gets or sets the Genre to witch the <see cref="Genre"/> entity is sub-category.
/// </summary>
/// <value>Sup-genre of the <see cref="Book"/> entity.</value>
public Genre SuperGenre { get; set; }
/// <summary>
/// Gets or sets the initial collection of books from the <see cref="Genre"/> entity.
/// </summary>
/// <value>Collection of books from the <see cref="Genre"/> entity.</value>
public ICollection<Book> Books
{
get
{
return this.books;
}
set
{
this.books = value;
}
}
}
} | namespace LibrarySystem.Models
{
public class Genre
{
}
} | mit | C# |
dfe5734a5d8aea9ca238ae9ced813bc1175ce76d | Fix highlight deserialization | synhershko/HebrewSearch | NElasticsearch/NElasticsearch/Models/Hit.cs | NElasticsearch/NElasticsearch/Models/Hit.cs | using System.Collections.Generic;
using System.Diagnostics;
namespace NElasticsearch.Models
{
/// <summary>
/// Individual hit response from ElasticSearch.
/// </summary>
[DebuggerDisplay("{_type} in {_index} id {_id}")]
public class Hit<T>
{
public string _index { get; set; }
public string _type { get; set; }
public string _id { get; set; }
public double? _score { get; set; }
public T _source { get; set; }
public Dictionary<string, IEnumerable<object>> fields = new Dictionary<string, IEnumerable<object>>();
public Dictionary<string, List<string>> highlight { get; set; }
}
}
| using System.Collections.Generic;
using System.Diagnostics;
namespace NElasticsearch.Models
{
/// <summary>
/// Individual hit response from ElasticSearch.
/// </summary>
[DebuggerDisplay("{_type} in {_index} id {_id}")]
public class Hit<T>
{
public string _index { get; set; }
public string _type { get; set; }
public string _id { get; set; }
public double? _score { get; set; }
public T _source { get; set; }
public Dictionary<string, IEnumerable<object>> fields = new Dictionary<string, IEnumerable<object>>();
public Dictionary<string, IEnumerable<string>> highlight;
}
}
| agpl-3.0 | C# |
30f635c1bfa9a0a5b8a35ef91d80cacd91e23c28 | Fix for StringValidator InvalidCharacters (from Nels_P_Olsen) | flcdrg/XSDExtractor | Parsers/Validators/StringValidatorParser.cs | Parsers/Validators/StringValidatorParser.cs | #region License
/*
JFDI the .Net Job Framework (http://jfdi.sourceforge.net)
Copyright (C) 2006 Steven Ward (steve.ward.uk@gmail.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#endregion
using System.Configuration;
using System.Reflection;
using System.Xml.Schema;
namespace JFDI.Utils.XSDExtractor.Parsers.Validators
{
/// <summary>
/// </summary>
public class StringValidatorParser : NoValidatorParser
{
/// <summary>
/// </summary>
public StringValidatorParser(PropertyInfo property, ConfigurationValidatorAttribute attribute)
: base(property, attribute)
{
}
/// <summary>
/// Returns a simple type which extends the basic datatype and
/// restricts is using the string validator
/// </summary>
public override XmlSchemaSimpleType GetSimpleType(string attributeDataType)
{
var retVal = base.GetSimpleType(attributeDataType);
var restriction = (XmlSchemaSimpleTypeRestriction) retVal.Content;
var sva = (StringValidatorAttribute) Attribute;
if (!string.IsNullOrEmpty(sva.InvalidCharacters))
{
var pFacet = new XmlSchemaPatternFacet { Value = sva.InvalidCharacters };
// TODO: convert this to a regex that excludes the characters
pFacet.Value = string.Format(
"[^{0}]*",
pFacet.Value
.Replace(@"\", @"\\")
.Replace(@"[", @"\[")
.Replace(@"]", @"\]"));
restriction.Facets.Add(pFacet);
}
var minFacet = new XmlSchemaMinLengthFacet { Value = sva.MinLength.ToString() };
restriction.Facets.Add(minFacet);
var maxFacet = new XmlSchemaMaxLengthFacet { Value = sva.MaxLength.ToString() };
restriction.Facets.Add(maxFacet);
return retVal;
}
}
} | #region License
/*
JFDI the .Net Job Framework (http://jfdi.sourceforge.net)
Copyright (C) 2006 Steven Ward (steve.ward.uk@gmail.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#endregion
using System.Configuration;
using System.Reflection;
using System.Xml.Schema;
namespace JFDI.Utils.XSDExtractor.Parsers.Validators
{
/// <summary>
/// </summary>
public class StringValidatorParser : NoValidatorParser
{
/// <summary>
/// </summary>
public StringValidatorParser(PropertyInfo property, ConfigurationValidatorAttribute attribute)
: base(property, attribute)
{
}
/// <summary>
/// Returns a simple type which extends the basic datatype and
/// restricts is using the string validator
/// </summary>
public override XmlSchemaSimpleType GetSimpleType(string attributeDataType)
{
var retVal = base.GetSimpleType(attributeDataType);
var restriction = (XmlSchemaSimpleTypeRestriction) retVal.Content;
var sva = (StringValidatorAttribute) Attribute;
if (!string.IsNullOrEmpty(sva.InvalidCharacters))
{
var pFacet = new XmlSchemaPatternFacet { Value = sva.InvalidCharacters };
// TODO: convert this to a regex that excludes the characters
restriction.Facets.Add(pFacet);
}
var minFacet = new XmlSchemaMinLengthFacet { Value = sva.MinLength.ToString() };
restriction.Facets.Add(minFacet);
var maxFacet = new XmlSchemaMaxLengthFacet { Value = sva.MaxLength.ToString() };
restriction.Facets.Add(maxFacet);
return retVal;
}
}
} | lgpl-2.1 | C# |
8f60f00fec76b782499a8dc62e5681ebdee4a49f | add runtimemeshcomponent to build file | indyfree/MoleculeVR,indyfree/MoleculeVR,indyfree/MoleculeVR | Source/MeshGenerator/MeshGenerator.Build.cs | Source/MeshGenerator/MeshGenerator.Build.cs | // Fill out your copyright notice in the Description page of Project Settings.
using UnrealBuildTool;
public class MeshGenerator : ModuleRules
{
public MeshGenerator(TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "ProceduralMeshComponent" });
PublicDependencyModuleNames.AddRange(new string[] { "ShaderCore", "RenderCore", "RHI", "RuntimeMeshComponent" });
PrivateDependencyModuleNames.AddRange(new string[] { });
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
}
| // Fill out your copyright notice in the Description page of Project Settings.
using UnrealBuildTool;
public class MeshGenerator : ModuleRules
{
public MeshGenerator(TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "ProceduralMeshComponent" });
PrivateDependencyModuleNames.AddRange(new string[] { });
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
}
| mit | C# |
eb76aeed645c5984d978523aa0892fb2816dfacf | Revert "Introduced TryValidate<T>() extension method for HttpRequest which accompanies Validate<T>(), but is more flexible, because it allows to explicitly handle the case when model validator is missing. (#230)" (#238) | jchannon/Botwin | src/Carter/ModelBinding/ValidationExtensions.cs | src/Carter/ModelBinding/ValidationExtensions.cs | namespace Carter.ModelBinding
{
using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation.Results;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
public static class ValidationExtensions
{
/// <summary>
/// Performs validation on the specified <paramref name="model"/> instance
/// </summary>
/// <typeparam name="T">The type of the <paramref name="model"/> that is being validated</typeparam>
/// <param name="request">Current <see cref="HttpRequest"/></param>
/// <param name="model">The model instance that is being validated</param>
/// <returns><see cref="ValidationResult"/></returns>
public static ValidationResult Validate<T>(this HttpRequest request, T model)
{
var validatorLocator = request.HttpContext.RequestServices.GetService<IValidatorLocator>();
var validator = validatorLocator.GetValidator<T>();
return validator == null
? throw new NullReferenceException("")//new ValidationResult(new[] { new ValidationFailure(typeof(T).Name, "No validator found") })
: validator.Validate(model);
}
/// <summary>
/// Retrieve formatted validation errors
/// </summary>
/// <param name="result"><see cref="ValidationResult"/></param>
/// <returns><see cref="IEnumerable{dynamic}"/> of property names and associated error messages</returns>
public static IEnumerable<dynamic> GetFormattedErrors(this ValidationResult result)
{
return result.Errors.Select(x => new { x.PropertyName, x.ErrorMessage });
}
}
} | namespace Carter.ModelBinding
{
using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation.Results;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
public static class ValidationExtensions
{
/// <summary>
/// Performs validation on the specified <paramref name="model"/> instance
/// </summary>
/// <typeparam name="T">The type of the <paramref name="model"/> that is being validated</typeparam>
/// <param name="request">Current <see cref="HttpRequest"/></param>
/// <param name="model">The model instance that is being validated</param>
/// <returns><see cref="ValidationResult"/></returns>
public static ValidationResult Validate<T>(this HttpRequest request, T model)
{
var validatorLocator = request.HttpContext.RequestServices.GetService<IValidatorLocator>();
var validator = validatorLocator.GetValidator<T>();
return validator == null
? throw new NullReferenceException("")//new ValidationResult(new[] { new ValidationFailure(typeof(T).Name, "No validator found") })
: validator.Validate(model);
}
/// <summary>
/// Performs validation on the specified <paramref name="model"/> instance
/// </summary>
/// <typeparam name="T">The type of the <paramref name="model"/> that is being validated</typeparam>
/// <param name="request">Current <see cref="HttpRequest"/></param>
/// <param name="model">The model instance that is being validated</param>
/// <param name="result"><see cref="ValidationResult"/></param>
/// <returns>true if there's a validator associated with the <paramref name="model"/></returns>
public static bool TryValidate<T>(this HttpRequest request, T model, out ValidationResult result)
{
var validatorLocator = request.HttpContext.RequestServices.GetService<IValidatorLocator>();
var validator = validatorLocator?.GetValidator<T>();
if (validator == null)
{
result = null;
return false;
}
result = validator.Validate(model);
return true;
}
/// <summary>
/// Retrieve formatted validation errors
/// </summary>
/// <param name="result"><see cref="ValidationResult"/></param>
/// <returns><see cref="IEnumerable{dynamic}"/> of property names and associated error messages</returns>
public static IEnumerable<dynamic> GetFormattedErrors(this ValidationResult result)
{
return result.Errors.Select(x => new { x.PropertyName, x.ErrorMessage });
}
}
} | mit | C# |
5e08cdb62513e23faa61a22866b43615ab30ceea | update 'DataGenericCache' package version | jeduardocosta/data-generic-cache,jeduardocosta/DataGenericCache | src/DataGenericCache/Properties/AssemblyInfo.cs | src/DataGenericCache/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DataGenericCache")]
[assembly: AssemblyDescription("A simple .NET library to cache data using custom providers.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DataGenericCache")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("73eb219c-4185-4f18-a942-63fbf9613672")]
// 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.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: InternalsVisibleTo("DataGenericCache.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] | 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("DataGenericCache")]
[assembly: AssemblyDescription("A simple .NET library to cache data using custom providers.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DataGenericCache")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("73eb219c-4185-4f18-a942-63fbf9613672")]
// 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.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: InternalsVisibleTo("DataGenericCache.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] | mit | C# |
516911f820589462e2db5eea8b1c2481de00a7e0 | add NeutralResourcesLanguageAttribute | Weswit/Lightstreamer-example-StockList-client-winphone,Lightstreamer/Lightstreamer-example-StockList-client-winphone | WP7StockListDemo/Properties/AssemblyInfo.cs | WP7StockListDemo/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
[assembly: AssemblyTitle("Lightstreamer Windows Phone Demo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Lightstreamer Windows Phone Demo")]
[assembly: AssemblyCopyright("Copyright © Weswit 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("3e0afa5b-ebe3-408b-8c68-d1a45ae7eee8")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Lightstreamer Windows Phone Demo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Lightstreamer Windows Phone Demo")]
[assembly: AssemblyCopyright("Copyright © Weswit 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("3e0afa5b-ebe3-408b-8c68-d1a45ae7eee8")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
725d72d9d4e2ff70d6e4e2fd0feaa539326e36f3 | Address feedback. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Tor/Http/ClearnetHttpClient.cs | WalletWasabi/Tor/Http/ClearnetHttpClient.cs | using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace WalletWasabi.Tor.Http
{
/// <summary>
/// HTTP client implementation based on .NET's <see cref="HttpClient"/> which provides least privacy for Wasabi users,
/// as HTTP requests are being sent over clearnet.
/// </summary>
/// <remarks>Inner <see cref="HttpClient"/> instance is thread-safe.</remarks>
public class ClearnetHttpClient : IHttpClient
{
static ClearnetHttpClient()
{
var socketHandler = new SocketsHttpHandler()
{
// Only GZip is currently used by Wasabi Backend.
AutomaticDecompression = DecompressionMethods.GZip,
PooledConnectionLifetime = TimeSpan.FromMinutes(5)
};
HttpClient = new HttpClient(socketHandler);
}
public ClearnetHttpClient(Func<Uri> baseUriGetter)
{
BaseUriGetter = baseUriGetter;
}
public Func<Uri> BaseUriGetter { get; }
/// <summary>Predefined HTTP client that handles HTTP requests when Tor is disabled.</summary>
private static HttpClient HttpClient { get; }
/// <summary>The value is not used at the moment.</summary>
/// <remarks>
/// There is currently no mechanism to make HTTP(s) requests "more private" when using clearnet (i.e. .NET's <see cref="HttpClient"/>).
/// <para>If you need privacy, use Tor.</para>
/// </remarks>
public bool DefaultIsolateStream => false;
/// <inheritdoc cref="HttpClient.SendAsync(HttpRequestMessage, CancellationToken)"/>
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token = default)
{
return SendAsync(request, isolateStream: false, token);
}
/// <param name="isolateStream">Clearnet HTTP client does not support this option.</param>
/// <inheritdoc/>
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, bool isolateStream, CancellationToken token = default)
{
return HttpClient.SendAsync(request, token);
}
}
}
| using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace WalletWasabi.Tor.Http
{
/// <summary>
/// HTTP client implementation based on .NET's <see cref="HttpClient"/> which provides least privacy for Wasabi users,
/// as HTTP requests are being sent over clearnet.
/// </summary>
/// <remarks>Inner <see cref="HttpClient"/> instance is thread-safe.</remarks>
public class ClearnetHttpClient : IHttpClient
{
static ClearnetHttpClient()
{
var socketHandler = new SocketsHttpHandler()
{
// Only GZip is currently used by Wasabi Backend.
AutomaticDecompression = DecompressionMethods.GZip,
PooledConnectionLifetime = TimeSpan.FromMinutes(5)
};
HttpClient = new HttpClient(socketHandler);
}
public ClearnetHttpClient(Func<Uri> destinationUriAction)
{
BaseUriGetter = destinationUriAction;
}
public Func<Uri> BaseUriGetter { get; }
/// <summary>Predefined HTTP client that handles HTTP requests when Tor is disabled.</summary>
private static HttpClient HttpClient { get; }
/// <summary>The value is not used at the moment.</summary>
/// <remarks>
/// There is currently no mechanism to make HTTP(s) requests "more private" when using clearnet (i.e. .NET's <see cref="HttpClient"/>).
/// <para>If you need privacy, use Tor.</para>
/// </remarks>
public bool DefaultIsolateStream => false;
/// <inheritdoc cref="HttpClient.SendAsync(HttpRequestMessage, CancellationToken)"/>
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token = default)
{
return SendAsync(request, isolateStream: false, token);
}
/// <param name="isolateStream">Clearnet HTTP client does not support this option.</param>
/// <inheritdoc/>
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, bool isolateStream, CancellationToken token = default)
{
return HttpClient.SendAsync(request, token);
}
}
}
| mit | C# |
efa7167550d7c9a2fd1384b7d84dd08fa3b23324 | Update EntityFrameworkConvertToDbGeometry.cs | GeoJSON-Net/GeoJSON.Net.Contrib | src/GeoJSON.Net.Contrib.EntityFramework/EntityFrameworkConvertToDbGeometry.cs | src/GeoJSON.Net.Contrib.EntityFramework/EntityFrameworkConvertToDbGeometry.cs | using System.Data.Entity.Spatial;
using GeoJSON.Net.Geometry;
using GeoJSON.Net.Contrib.Wkb.Conversions;
namespace GeoJSON.Net.Contrib.EntityFramework
{
public static partial class EntityFrameworkConvert
{
[Obsolete("This method will be removed in future releases, consider migrating now to the newest signature.", false)]
public static DbGeometry ToDbGeometry(this IGeometryObject geometryObject)
{
return geometryObject.ToDbGeometry(4326);
}
public static DbGeometry ToDbGeometry(this IGeometryObject geometryObject, int coordinateSystemId = 4326)
{
return DbGeometry.FromBinary(WkbEncode.Encode(geometryObject), coordinateSystemId);
}
}
}
| using System.Data.Entity.Spatial;
using GeoJSON.Net.Geometry;
using GeoJSON.Net.Contrib.Wkb.Conversions;
namespace GeoJSON.Net.Contrib.EntityFramework
{
public static partial class EntityFrameworkConvert
{
public static DbGeometry ToDbGeometry(this IGeometryObject geometryObject, int coordinateSystemId = 4326)
{
return DbGeometry.FromBinary(WkbEncode.Encode(geometryObject), coordinateSystemId);
}
}
}
| mit | C# |
a95d48fa141b8f5dfec6c03d4c2e29bb33c8506e | change h4 to h2 | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | src/StockportWebapp/Views/Shared/InlineQuote.cshtml | src/StockportWebapp/Views/Shared/InlineQuote.cshtml | @model StockportWebapp.Models.InlineQuote
<div class="inline-quote-container">
<img src="@Model.Image" alt="@Model.ImageAltText" />
<h2>@Model.Author</h2>
<div class="quote-body">
<span class="green open fa fa-2x fa-quote-left" aria-hidden="true"></span>
<p class="lead-paragraph">@Model.Quote</p>
<span class="green fa fa-2x fa-quote-right" aria-hidden="true"></span>
</div>
</div> | @model StockportWebapp.Models.InlineQuote
<div class="inline-quote-container">
<img src="@Model.Image" alt="@Model.ImageAltText" />
<h4>@Model.Author</h4>
<div class="quote-body">
<span class="green open fa fa-2x fa-quote-left" aria-hidden="true"></span>
<p class="lead-paragraph">@Model.Quote</p>
<span class="green fa fa-2x fa-quote-right" aria-hidden="true"></span>
</div>
</div> | mit | C# |
b471be128ee1e420bdec690128859f862e747941 | Fix typos in cluster reroute explanation | cstlaurent/elasticsearch-net,adam-mccoy/elasticsearch-net,robrich/elasticsearch-net,adam-mccoy/elasticsearch-net,jonyadamit/elasticsearch-net,geofeedia/elasticsearch-net,joehmchan/elasticsearch-net,mac2000/elasticsearch-net,joehmchan/elasticsearch-net,SeanKilleen/elasticsearch-net,starckgates/elasticsearch-net,wawrzyn/elasticsearch-net,KodrAus/elasticsearch-net,abibell/elasticsearch-net,DavidSSL/elasticsearch-net,RossLieberman/NEST,amyzheng424/elasticsearch-net,elastic/elasticsearch-net,faisal00813/elasticsearch-net,elastic/elasticsearch-net,amyzheng424/elasticsearch-net,wawrzyn/elasticsearch-net,tkirill/elasticsearch-net,azubanov/elasticsearch-net,geofeedia/elasticsearch-net,LeoYao/elasticsearch-net,faisal00813/elasticsearch-net,UdiBen/elasticsearch-net,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,robertlyson/elasticsearch-net,azubanov/elasticsearch-net,LeoYao/elasticsearch-net,ststeiger/elasticsearch-net,junlapong/elasticsearch-net,DavidSSL/elasticsearch-net,gayancc/elasticsearch-net,jonyadamit/elasticsearch-net,SeanKilleen/elasticsearch-net,wawrzyn/elasticsearch-net,junlapong/elasticsearch-net,DavidSSL/elasticsearch-net,UdiBen/elasticsearch-net,KodrAus/elasticsearch-net,junlapong/elasticsearch-net,cstlaurent/elasticsearch-net,RossLieberman/NEST,faisal00813/elasticsearch-net,amyzheng424/elasticsearch-net,KodrAus/elasticsearch-net,robrich/elasticsearch-net,CSGOpenSource/elasticsearch-net,tkirill/elasticsearch-net,TheFireCookie/elasticsearch-net,TheFireCookie/elasticsearch-net,jonyadamit/elasticsearch-net,robertlyson/elasticsearch-net,robertlyson/elasticsearch-net,starckgates/elasticsearch-net,ststeiger/elasticsearch-net,robrich/elasticsearch-net,cstlaurent/elasticsearch-net,gayancc/elasticsearch-net,adam-mccoy/elasticsearch-net,mac2000/elasticsearch-net,abibell/elasticsearch-net,SeanKilleen/elasticsearch-net,CSGOpenSource/elasticsearch-net,abibell/elasticsearch-net,joehmchan/elasticsearch-net,mac2000/elasticsearch-net,ststeiger/elasticsearch-net,gayancc/elasticsearch-net,RossLieberman/NEST,TheFireCookie/elasticsearch-net,LeoYao/elasticsearch-net,starckgates/elasticsearch-net,azubanov/elasticsearch-net,geofeedia/elasticsearch-net,tkirill/elasticsearch-net | src/Nest/Domain/Cluster/ClusterRerouteExplanation.cs | src/Nest/Domain/Cluster/ClusterRerouteExplanation.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Nest
{
[JsonObject]
public class ClusterRerouteExplanation
{
[JsonProperty("command")]
public string Command { get; set; }
[JsonProperty("parameters")]
public ClusterRerouteParameters Parameters { get; set; }
[JsonProperty("decisions")]
public IEnumerable<ClusterRerouteDecision> Decisions { get; set; }
}
}
| using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Nest
{
[JsonObject]
public class ClusterRerouteExplanation
{
[JsonProperty("command")]
public string Comand { get; set; }
[JsonProperty("parameters")]
public ClusterRerouteParameters Parameters { get; set; }
[JsonProperty("decisions")]
public IEnumerable<ClusterRerouteDecision> Descisions { get; set; }
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.