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
e466d5641e2f9afd4011a0d5a6d505bde9148d55
Update Program.cs
Mattgyver317/GitTest1,Mattgyver317/GitTest1
ConsoleApp1/ConsoleApp1/Program.cs
ConsoleApp1/ConsoleApp1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { /* This code has been edited */ } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { } } }
mit
C#
bc39da0bf72bdc056b2530b8028c3a0ec2698ab0
Use proper HTTP client.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/WebClients/Wasabi/WasabiClientFactory.cs
WalletWasabi/WebClients/Wasabi/WasabiClientFactory.cs
using System; using System.Net; using WalletWasabi.Tor.Http; namespace WalletWasabi.WebClients.Wasabi { /// <summary> /// Factory class to create <see cref="WasabiClient"/> instances. /// </summary> public class WasabiClientFactory { /// <summary> /// To detect redundant calls. /// </summary> private bool _disposed = false; /// <summary> /// Creates a new instance of the object. /// </summary> /// <param name="torEndPoint">If <c>null</c> then clearnet (not over Tor) is used, otherwise HTTP requests are routed through provided Tor endpoint.</param> public WasabiClientFactory(EndPoint? torEndPoint, Func<Uri> backendUriGetter) { TorEndpoint = torEndPoint; BackendUriGetter = backendUriGetter; if (torEndPoint is { }) { BackendHttpClient = new TorHttpClient(BackendUriGetter, TorEndpoint, isolateStream: false); } else { BackendHttpClient = new ClearnetHttpClient(BackendUriGetter); } SharedWasabiClient = new WasabiClient(BackendHttpClient); } /// <summary>Tor SOCKS5 endpoint.</summary> /// <remarks>The property should be <c>>private</c> when Tor refactoring is done.</remarks> public EndPoint? TorEndpoint { get; } /// <remarks>The property should be <c>>private</c> when Tor refactoring is done.</remarks> public Func<Uri> BackendUriGetter { get; } /// <summary>Whether Tor is enabled or disabled.</summary> public bool IsTorEnabled => TorEndpoint is { }; /// <summary>Backend HTTP client, shared instance.</summary> private IRelativeHttpClient BackendHttpClient { get; } /// <summary>Shared instance of <see cref="WasabiClient"/>.</summary> public WasabiClient SharedWasabiClient { get; } /// <summary> /// Creates new <see cref="TorHttpClient"/> instance with correctly set backend URL. /// </summary> public TorHttpClient NewTorHttpClient(bool isolateStream = true) { return new TorHttpClient(BackendUriGetter.Invoke(), TorEndpoint, isolateStream: isolateStream); } /// <summary> /// Creates new <see cref="TorHttpClient"/>. /// </summary> public TorHttpClient NewBackendTorHttpClient(bool isolateStream) { return new TorHttpClient(BackendUriGetter, TorEndpoint, isolateStream); } // Protected implementation of Dispose pattern. protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { // Dispose managed state (managed objects). if (BackendHttpClient is IDisposable httpClient) { httpClient.Dispose(); } } _disposed = true; } public void Dispose() { // Dispose of unmanaged resources. Dispose(true); // Suppress finalization. GC.SuppressFinalize(this); } } }
using System; using System.Net; using WalletWasabi.Tor.Http; namespace WalletWasabi.WebClients.Wasabi { /// <summary> /// Factory class to create <see cref="WasabiClient"/> instances. /// </summary> public class WasabiClientFactory { /// <summary> /// To detect redundant calls. /// </summary> private bool _disposed = false; /// <summary> /// Creates a new instance of the object. /// </summary> /// <param name="torEndPoint">If <c>null</c> then clearnet (not over Tor) is used, otherwise HTTP requests are routed through provided Tor endpoint.</param> public WasabiClientFactory(EndPoint? torEndPoint, Func<Uri> backendUriGetter) { TorEndpoint = torEndPoint; BackendUriGetter = backendUriGetter; SharedTorHttpClient = new TorHttpClient(BackendUriGetter.Invoke(), TorEndpoint, isolateStream: false); SharedWasabiClient = new WasabiClient(SharedTorHttpClient); } /// <summary>Tor SOCKS5 endpoint.</summary> /// <remarks>The property should be <c>>private</c> when Tor refactoring is done.</remarks> public EndPoint? TorEndpoint { get; } /// <remarks>The property should be <c>>private</c> when Tor refactoring is done.</remarks> public Func<Uri> BackendUriGetter { get; } /// <summary>Whether Tor is enabled or disabled.</summary> public bool IsTorEnabled => TorEndpoint is { }; /// <summary>Shared instance of <see cref="TorHttpClient"/>.</summary> public TorHttpClient SharedTorHttpClient { get; } /// <summary>Shared instance of <see cref="WasabiClient"/>.</summary> public WasabiClient SharedWasabiClient { get; } /// <summary> /// Creates new <see cref="TorHttpClient"/> instance with correctly set backend URL. /// </summary> public TorHttpClient NewTorHttpClient(bool isolateStream = true) { return new TorHttpClient(BackendUriGetter.Invoke(), TorEndpoint, isolateStream: isolateStream); } // Protected implementation of Dispose pattern. protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { // Dispose managed state (managed objects). SharedTorHttpClient.Dispose(); } _disposed = true; } public void Dispose() { // Dispose of unmanaged resources. Dispose(true); // Suppress finalization. GC.SuppressFinalize(this); } /// <summary> /// Creates new <see cref="TorHttpClient"/>. /// </summary> public TorHttpClient NewBackendTorHttpClient(bool isolateStream) { return new TorHttpClient(BackendUriGetter, TorEndpoint, isolateStream); } } }
mit
C#
4accd17bfbfad3fdca4833aee176f9b61ae1de75
Support multi field in select shell command
89sos98/LiteDB,falahati/LiteDB,falahati/LiteDB,89sos98/LiteDB,mbdavid/LiteDB
LiteDB/Shell/Collections/Select.cs
LiteDB/Shell/Collections/Select.cs
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; namespace LiteDB.Shell { internal class Select : BaseCollection, ICommand { public bool IsCommand(StringScanner s) { return this.IsCollectionCommand(s, "select"); } public IEnumerable<BsonValue> Execute(StringScanner s, LiteEngine engine) { var col = this.ReadCollection(engine, s); var fields = new Dictionary<string, BsonExpression>(); var index = 0; // read all fields definitions (support AS as keyword no name field) while(!s.HasTerminated) { var expression = BsonExpression.ReadExpression(s, false); var key = s.Scan(@"\s*as\s+(\w+)", 1).TrimToNull() ?? ("expr" + (++index)); fields.Add(key, new BsonExpression(expression)); if (s.Scan(@"\s*,\s*").Length > 0) continue; break; } // select command required output value, path or expression if (fields.Count == 0) throw LiteException.SyntaxError(s, "Missing select path"); var query = Query.All(); if (s.Scan(@"\s*where\s*").Length > 0) { query = this.ReadQuery(s, true); } var skipLimit = this.ReadSkipLimit(s); var includes = this.ReadIncludes(s); s.ThrowIfNotFinish(); var docs = engine.Find(col, query, includes, skipLimit.Key, skipLimit.Value); foreach(var doc in docs) { // if is a single value, return as just field if (fields.Count == 1) { foreach (var value in fields.Values.First().Execute(doc, false)) { yield return value; } } else { var output = new BsonDocument(); foreach (var field in fields) { output[field.Key] = field.Value.Execute(doc, true).First(); } yield return output; } } } } }
using System; using System.Collections.Generic; namespace LiteDB.Shell { internal class Select : BaseCollection, ICommand { public bool IsCommand(StringScanner s) { return this.IsCollectionCommand(s, "select"); } public IEnumerable<BsonValue> Execute(StringScanner s, LiteEngine engine) { var col = this.ReadCollection(engine, s); var expression = BsonExpression.ReadExpression(s, false); var output = expression == null ? this.ReadBsonValue(s) : null; // select command required output value, path or expression if (expression == null && output == null) throw LiteException.SyntaxError(s, "Missing select path"); var query = Query.All(); if (s.Scan(@"\s*where\s*").Length > 0) { query = this.ReadQuery(s, true); } var skipLimit = this.ReadSkipLimit(s); var includes = this.ReadIncludes(s); s.ThrowIfNotFinish(); var docs = engine.Find(col, query, includes, skipLimit.Key, skipLimit.Value); var expr = expression == null ? null : new BsonExpression(expression); foreach(var doc in docs) { if (expr != null) { foreach(var value in expr.Execute(doc, false)) { yield return value; } } else { yield return output; } } } } }
mit
C#
a62f4df0b1044f4cd8ed69a5627541d91faa61e7
Implement entry.ToString(), let it return entry.Key (#351)
adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress
src/SharpCompress/Common/Entry.cs
src/SharpCompress/Common/Entry.cs
using System; using System.Collections.Generic; namespace SharpCompress.Common { public abstract class Entry : IEntry { /// <summary> /// The File's 32 bit CRC Hash /// </summary> public abstract long Crc { get; } /// <summary> /// The string key of the file internal to the Archive. /// </summary> public abstract string Key { get; } /// <summary> /// The compressed file size /// </summary> public abstract long CompressedSize { get; } /// <summary> /// The compression type /// </summary> public abstract CompressionType CompressionType { get; } /// <summary> /// The uncompressed file size /// </summary> public abstract long Size { get; } /// <summary> /// The entry last modified time in the archive, if recorded /// </summary> public abstract DateTime? LastModifiedTime { get; } /// <summary> /// The entry create time in the archive, if recorded /// </summary> public abstract DateTime? CreatedTime { get; } /// <summary> /// The entry last accessed time in the archive, if recorded /// </summary> public abstract DateTime? LastAccessedTime { get; } /// <summary> /// The entry time when archived, if recorded /// </summary> public abstract DateTime? ArchivedTime { get; } /// <summary> /// Entry is password protected and encrypted and cannot be extracted. /// </summary> public abstract bool IsEncrypted { get; } /// <summary> /// Entry is password protected and encrypted and cannot be extracted. /// </summary> public abstract bool IsDirectory { get; } /// <summary> /// Entry is split among multiple volumes /// </summary> public abstract bool IsSplit { get; } /// <inheritdoc/> public override string ToString() { return this.Key; } internal abstract IEnumerable<FilePart> Parts { get; } internal bool IsSolid { get; set; } internal virtual void Close() { } /// <summary> /// Entry file attribute. /// </summary> public virtual int? Attrib => throw new NotImplementedException(); } }
using System; using System.Collections.Generic; namespace SharpCompress.Common { public abstract class Entry : IEntry { /// <summary> /// The File's 32 bit CRC Hash /// </summary> public abstract long Crc { get; } /// <summary> /// The string key of the file internal to the Archive. /// </summary> public abstract string Key { get; } /// <summary> /// The compressed file size /// </summary> public abstract long CompressedSize { get; } /// <summary> /// The compression type /// </summary> public abstract CompressionType CompressionType { get; } /// <summary> /// The uncompressed file size /// </summary> public abstract long Size { get; } /// <summary> /// The entry last modified time in the archive, if recorded /// </summary> public abstract DateTime? LastModifiedTime { get; } /// <summary> /// The entry create time in the archive, if recorded /// </summary> public abstract DateTime? CreatedTime { get; } /// <summary> /// The entry last accessed time in the archive, if recorded /// </summary> public abstract DateTime? LastAccessedTime { get; } /// <summary> /// The entry time when archived, if recorded /// </summary> public abstract DateTime? ArchivedTime { get; } /// <summary> /// Entry is password protected and encrypted and cannot be extracted. /// </summary> public abstract bool IsEncrypted { get; } /// <summary> /// Entry is password protected and encrypted and cannot be extracted. /// </summary> public abstract bool IsDirectory { get; } /// <summary> /// Entry is split among multiple volumes /// </summary> public abstract bool IsSplit { get; } internal abstract IEnumerable<FilePart> Parts { get; } internal bool IsSolid { get; set; } internal virtual void Close() { } /// <summary> /// Entry file attribute. /// </summary> public virtual int? Attrib => throw new NotImplementedException(); } }
mit
C#
98c43bcc170b7de722d8331b4022c6d765a1822c
更新版本号。 :relaxed:
Zongsoft/Zongsoft.Externals.Redis
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Zongsoft.Externals.Redis")] [assembly: AssemblyDescription("This is a library about Redis SDK.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Zongsoft Corporation")] [assembly: AssemblyProduct("Zongsoft.Externals.Redis Library")] [assembly: AssemblyCopyright("Copyright(C) Zongsoft Corporation 2014-2016. All rights reserved.")] [assembly: AssemblyTrademark("Zongsoft is registered trademarks of Zongsoft Corporation in the P.R.C. and/or other countries.")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.1.0.1611")] [assembly: AssemblyFileVersion("1.1.0.1611")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Zongsoft.Externals.Redis")] [assembly: AssemblyDescription("This is a library about Redis SDK.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Zongsoft Corporation")] [assembly: AssemblyProduct("Zongsoft.Externals.Redis Library")] [assembly: AssemblyCopyright("Copyright(C) Zongsoft Corporation 2014-2015. All rights reserved.")] [assembly: AssemblyTrademark("Zongsoft is registered trademarks of Zongsoft Corporation in the P.R.C. and/or other countries.")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.1407.0")] [assembly: AssemblyFileVersion("1.0.1407.0")]
lgpl-2.1
C#
a5be9a77ba8eef4f0e22fb43fa74fa6bd1d6cd0b
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
autofac/Autofac.Extras.AggregateService
Properties/VersionAssemblyInfo.cs
Properties/VersionAssemblyInfo.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
mit
C#
f55f32fdb83ff51a89488f35707223ebd9fb5c14
Make LocalizedString a class
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.Extensions.Localization.Abstractions/LocalizedString.cs
src/Microsoft.Extensions.Localization.Abstractions/LocalizedString.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.Extensions.Localization { /// <summary> /// A locale specific string. /// </summary> public class LocalizedString { /// <summary> /// Creates a new <see cref="LocalizedString"/>. /// </summary> /// <param name="name">The name of the string in the resource it was loaded from.</param> /// <param name="value">The actual string.</param> public LocalizedString(string name, string value) : this(name, value, resourceNotFound: false) { } /// <summary> /// Creates a new <see cref="LocalizedString"/>. /// </summary> /// <param name="name">The name of the string in the resource it was loaded from.</param> /// <param name="value">The actual string.</param> /// <param name="resourceNotFound">Whether the string was found in a resource. Set this to <c>false</c> to indicate an alternate string value was used.</param> public LocalizedString(string name, string value, bool resourceNotFound) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Name = name; Value = value; ResourceNotFound = resourceNotFound; } public static implicit operator string(LocalizedString localizedString) { return localizedString.Value; } /// <summary> /// The name of the string in the resource it was loaded from. /// </summary> public string Name { get; } /// <summary> /// The actual string. /// </summary> public string Value { get; } /// <summary> /// Whether the string was found in a resource. If <c>false</c>, an alternate string value was used. /// </summary> public bool ResourceNotFound { get; } /// <summary> /// Returns the actual string. /// </summary> /// <returns>The actual string.</returns> public override string ToString() => Value; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.Extensions.Localization { /// <summary> /// A locale specific string. /// </summary> public struct LocalizedString { /// <summary> /// Creates a new <see cref="LocalizedString"/>. /// </summary> /// <param name="name">The name of the string in the resource it was loaded from.</param> /// <param name="value">The actual string.</param> public LocalizedString(string name, string value) : this(name, value, resourceNotFound: false) { } /// <summary> /// Creates a new <see cref="LocalizedString"/>. /// </summary> /// <param name="name">The name of the string in the resource it was loaded from.</param> /// <param name="value">The actual string.</param> /// <param name="resourceNotFound">Whether the string was found in a resource. Set this to <c>false</c> to indicate an alternate string value was used.</param> public LocalizedString(string name, string value, bool resourceNotFound) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Name = name; Value = value; ResourceNotFound = resourceNotFound; } public static implicit operator string(LocalizedString localizedString) { return localizedString.Value; } /// <summary> /// The name of the string in the resource it was loaded from. /// </summary> public string Name { get; } /// <summary> /// The actual string. /// </summary> public string Value { get; } /// <summary> /// Whether the string was found in a resource. If <c>false</c>, an alternate string value was used. /// </summary> public bool ResourceNotFound { get; } /// <summary> /// Returns the actual string. /// </summary> /// <returns>The actual string.</returns> public override string ToString() => Value; } }
apache-2.0
C#
213b28e66da469a1d91a1e0b0242250c99620fec
Use Utc time in DailyMoneyRepository.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/MitternachtBot/Database/Repositories/Impl/DailyMoneyRepository.cs
src/MitternachtBot/Database/Repositories/Impl/DailyMoneyRepository.cs
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using Mitternacht.Database.Models; namespace Mitternacht.Database.Repositories.Impl { public class DailyMoneyRepository : Repository<DailyMoney>, IDailyMoneyRepository { public DailyMoneyRepository(DbContext context) : base(context) { } public DailyMoney GetOrCreate(ulong guildId, ulong userId) { var dm = _set.FirstOrDefault(c => c.GuildId == guildId && c.UserId == userId); if(dm == null) { _set.Add(dm = new DailyMoney { GuildId = guildId, UserId = userId, LastTimeGotten = DateTime.MinValue }); } return dm; } public DateTime GetLastReceived(ulong guildId, ulong userId) => _set.FirstOrDefault(c => c.GuildId == guildId && c.UserId == userId)?.LastTimeGotten ?? DateTime.MinValue; public bool CanReceive(ulong guildId, ulong userId, TimeZoneInfo timeZoneInfo) => GetLastReceived(guildId, userId).Date < TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZoneInfo ?? TimeZoneInfo.Utc).Date; public DateTime UpdateState(ulong guildId, ulong userId) { var dm = GetOrCreate(guildId, userId); dm.LastTimeGotten = DateTime.UtcNow; return dm.LastTimeGotten; } public void ResetLastTimeReceived(ulong guildId, ulong userId, TimeZoneInfo timeZoneInfo) { if(!CanReceive(guildId, userId, timeZoneInfo)) { var dm = GetOrCreate(guildId, userId); if(dm.LastTimeGotten.Date >= DateTime.Today.Date) { dm.LastTimeGotten = DateTime.Today.AddDays(-1); } } } } }
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using Mitternacht.Database.Models; namespace Mitternacht.Database.Repositories.Impl { public class DailyMoneyRepository : Repository<DailyMoney>, IDailyMoneyRepository { public DailyMoneyRepository(DbContext context) : base(context) { } public DailyMoney GetOrCreate(ulong guildId, ulong userId) { var dm = _set.FirstOrDefault(c => c.GuildId == guildId && c.UserId == userId); if(dm == null) { _set.Add(dm = new DailyMoney { GuildId = guildId, UserId = userId, LastTimeGotten = DateTime.MinValue }); } return dm; } public DateTime GetLastReceived(ulong guildId, ulong userId) => _set.FirstOrDefault(c => c.GuildId == guildId && c.UserId == userId)?.LastTimeGotten ?? DateTime.MinValue; public bool CanReceive(ulong guildId, ulong userId, TimeZoneInfo timeZoneInfo) => GetLastReceived(guildId, userId).Date < TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZoneInfo ?? TimeZoneInfo.Utc).Date; public DateTime UpdateState(ulong guildId, ulong userId) { var dm = GetOrCreate(guildId, userId); dm.LastTimeGotten = DateTime.Now; return dm.LastTimeGotten; } public void ResetLastTimeReceived(ulong guildId, ulong userId, TimeZoneInfo timeZoneInfo) { if(!CanReceive(guildId, userId, timeZoneInfo)) { var dm = GetOrCreate(guildId, userId); if(dm.LastTimeGotten.Date >= DateTime.Today.Date) { dm.LastTimeGotten = DateTime.Today.AddDays(-1); } } } } }
mit
C#
5718d40d5e3865e4de04f0eacb95ff31616b1d20
fix StartSuccessfully test
takenet/messaginghub-client-csharp
src/Takenet.MessagingHub.Client.Test/MessagingHubClientTests_Start.cs
src/Takenet.MessagingHub.Client.Test/MessagingHubClientTests_Start.cs
using System; using NUnit.Framework; using System.Threading.Tasks; using Shouldly; using Takenet.MessagingHub.Client.Connection; namespace Takenet.MessagingHub.Client.Test { [TestFixture] internal class MessagingHubClientTests_Start : MessagingHubClientTestBase { [SetUp] public void TestSetUp() { base.Setup(); if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday || DateTime.Today.DayOfWeek == DayOfWeek.Sunday || DateTime.Now.Hour < 6 || DateTime.Now.Hour > 19) { Assert.Ignore("As this test uses hmg server, it cannot be run out of worktime!"); } } [TearDown] protected override void TearDown() { base.TearDown(); } [Test] public async Task StartSuccessfully() { var connection = new MessagingHubConnectionBuilder() .WithMaxConnectionRetries(1) .UsingHostName("hmg.msging.net") .UsingGuest() .Build(); await connection.ConnectAsync().ConfigureAwait(false); } [Test] public void TryToStartConnectionWithInvalidServer() { var connection = new MessagingHubConnectionBuilder() .WithMaxConnectionRetries(1) .UsingHostName("invalid.iris.io") .UsingGuest() .WithSendTimeout(TimeSpan.FromSeconds(2)) .Build(); Should.ThrowAsync<TimeoutException>(async () => await connection.ConnectAsync().ConfigureAwait(false)).Wait(); } } }
using System; using NUnit.Framework; using System.Threading.Tasks; using Shouldly; using Takenet.MessagingHub.Client.Connection; namespace Takenet.MessagingHub.Client.Test { [TestFixture] internal class MessagingHubClientTests_Start : MessagingHubClientTestBase { [SetUp] public void TestSetUp() { base.Setup(); if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday || DateTime.Today.DayOfWeek == DayOfWeek.Sunday || DateTime.Now.Hour < 6 || DateTime.Now.Hour > 19) { Assert.Ignore("As this test uses hmg server, it cannot be run out of worktime!"); } } [TearDown] protected override void TearDown() { base.TearDown(); } [Test] public async Task StartSuccessfully() { var connection = new MessagingHubConnectionBuilder() .UsingHostName("hmg.msging.net") .UsingGuest() .Build(); await connection.ConnectAsync().ConfigureAwait(false); } [Test] public void TryToStartConnectionWithInvalidServer() { var connection = new MessagingHubConnectionBuilder() .WithMaxConnectionRetries(1) .UsingHostName("invalid.iris.io") .UsingGuest() .WithSendTimeout(TimeSpan.FromSeconds(2)) .Build(); Should.ThrowAsync<TimeoutException>(async () => await connection.ConnectAsync().ConfigureAwait(false)).Wait(); } } }
apache-2.0
C#
28ef1eeaa068d6e550821ecfc84cf0060d301d05
Fix failing test
kswoll/npeg
PEG.Samples/Lengths/LengthTests.cs
PEG.Samples/Lengths/LengthTests.cs
using NUnit.Framework; namespace PEG.Samples.Lengths { [TestFixture] public class LengthTests { [Test] public void IntegerDecimal() { var s = "5.5'"; var length = Length.Parse(s); Assert.AreEqual(5.5, length.Feet); } [Test] public void InchesInteger() { var s = "5\""; var length = Length.Parse(s); Assert.AreEqual(5, length.Inches); } [Test] public void FeetAndInchesInteger() { var s = "5' 4\""; var length = Length.Parse(s); Assert.AreEqual(64, length.Inches); } } }
using NUnit.Framework; namespace PEG.Samples.Lengths { [TestFixture] public class LengthTests { [Test] public void IntegerDecimal() { var s = "5.5'"; var length = Length.Parse(s); Assert.AreEqual(5.5, length.Feet); } [Test] public void InchesInteger() { var s = "5\""; var length = Length.Parse(s); Assert.AreEqual(5, length.Inches); } [Test] public void FeetAndInchesInteger() { var s = "5' 4\""; var length = Length.Parse(s); Assert.AreEqual(5, length.Feet); Assert.AreEqual(4, length.Inches); } } }
mit
C#
e36dd9afa533b153fc42e7ec7cc05aec6fcc462e
undo using ...
ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins
StankinsTests/TestTransformRow.cs
StankinsTests/TestTransformRow.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using StankinsInterfaces; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Transformers; namespace StankinsTests { [TestClass] public class TestTransformRow { [TestMethod] public async Task TestTransform2RowToOne() { #region arange var rows = new List<IRow>(); int nrRows = 10; for (int i = 0; i < nrRows; i++) { var rowAndrei = new Mock<IRow>(); rowAndrei.SetupProperty(it => it.Values, new Dictionary<string, object>() { ["ID"] = i, ["FirstName"] = "Andrei" + i, ["LastName"] = "Ignat" + i } ); rows.Add(rowAndrei.Object); } #endregion #region act var addField= "var s=new StanskinsImplementation.RowRead();" + "s.Values.Add(\"FullName\",Values[\"LastName\"]?.ToString() +Values[\"FirstName\"]?.ToString());" + "s"; var transform = new TransformRow(addField); transform.valuesRead = rows.ToArray(); await transform.Run(); transform.valuesRead = rows.ToArray(); await transform.Run(); #endregion #region assert for (int i = 0; i < transform.valuesTransformed.Length; i++) { Assert.AreEqual(transform.valuesTransformed[i].Values["FullName"].ToString(), transform.valuesRead[i].Values["LastName"].ToString() + transform.valuesRead[i].Values["FirstName"].ToString()); } #endregion } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using StankinsInterfaces; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Transformers; using Transformers.BasicTransformersType; namespace StankinsTests { [TestClass] public class TestTransformRow { [TestMethod] public async Task TestTransform2RowToOne() { #region arange var rows = new List<IRow>(); int nrRows = 10; for (int i = 0; i < nrRows; i++) { var rowAndrei = new Mock<IRow>(); rowAndrei.SetupProperty(it => it.Values, new Dictionary<string, object>() { ["ID"] = i, ["FirstName"] = "Andrei" + i, ["LastName"] = "Ignat" + i } ); rows.Add(rowAndrei.Object); } #endregion #region act var addField= "var s=new StanskinsImplementation.RowRead();" + "s.Values.Add(\"FullName\",Values[\"LastName\"]?.ToString() +Values[\"FirstName\"]?.ToString());" + "s"; var transform = new TransformRow(addField); transform.valuesRead = rows.ToArray(); await transform.Run(); transform.valuesRead = rows.ToArray(); await transform.Run(); #endregion #region assert for (int i = 0; i < transform.valuesTransformed.Length; i++) { Assert.AreEqual(transform.valuesTransformed[i].Values["FullName"].ToString(), transform.valuesRead[i].Values["LastName"].ToString() + transform.valuesRead[i].Values["FirstName"].ToString()); } #endregion } } }
mit
C#
90ebabd2db4c94edddc20eb134f75a1426dee9b3
Fix nullref
DrabWeb/osu,ppy/osu,naoey/osu,naoey/osu,ZLima12/osu,DrabWeb/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ZLima12/osu,DrabWeb/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,2yangk23/osu,peppy/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,naoey/osu,johnneijzen/osu,johnneijzen/osu,UselessToucan/osu,NeoAdonis/osu
osu.Game/Skinning/SkinReloadableDrawable.cs
osu.Game/Skinning/SkinReloadableDrawable.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; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; namespace osu.Game.Skinning { /// <summary> /// A drawable which has a callback when the skin changes. /// </summary> public abstract class SkinReloadableDrawable : CompositeDrawable { private readonly Func<ISkinSource, bool> allowFallback; private ISkinSource skin; /// <summary> /// Whether fallback to default skin should be allowed if the custom skin is missing this resource. /// </summary> private bool allowDefaultFallback => allowFallback == null || allowFallback.Invoke(skin); /// <summary> /// Create a new <see cref="SkinReloadableDrawable"/> /// </summary> /// <param name="allowFallback">A conditional to decide whether to allow fallback to the default implementation if a skinned element is not present.</param> protected SkinReloadableDrawable(Func<ISkinSource, bool> allowFallback = null) { this.allowFallback = allowFallback; } [BackgroundDependencyLoader] private void load(ISkinSource source) { skin = source; skin.SourceChanged += onChange; } private void onChange() => SkinChanged(skin, allowDefaultFallback); protected override void LoadAsyncComplete() { base.LoadAsyncComplete(); onChange(); } /// <summary> /// Called when a change is made to the skin. /// </summary> /// <param name="skin">The new skin.</param> /// <param name="allowFallback">Whether fallback to default skin should be allowed if the custom skin is missing this resource.</param> protected virtual void SkinChanged(ISkinSource skin, bool allowFallback) { } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (skin != null) skin.SourceChanged -= onChange; } } }
// 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; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; namespace osu.Game.Skinning { /// <summary> /// A drawable which has a callback when the skin changes. /// </summary> public abstract class SkinReloadableDrawable : CompositeDrawable { private readonly Func<ISkinSource, bool> allowFallback; private ISkinSource skin; /// <summary> /// Whether fallback to default skin should be allowed if the custom skin is missing this resource. /// </summary> private bool allowDefaultFallback => allowFallback == null || allowFallback.Invoke(skin); /// <summary> /// Create a new <see cref="SkinReloadableDrawable"/> /// </summary> /// <param name="allowFallback">A conditional to decide whether to allow fallback to the default implementation if a skinned element is not present.</param> protected SkinReloadableDrawable(Func<ISkinSource, bool> allowFallback = null) { this.allowFallback = allowFallback; } [BackgroundDependencyLoader] private void load(ISkinSource source) { skin = source; skin.SourceChanged += onChange; } private void onChange() => SkinChanged(skin, allowDefaultFallback); protected override void LoadAsyncComplete() { base.LoadAsyncComplete(); onChange(); } /// <summary> /// Called when a change is made to the skin. /// </summary> /// <param name="skin">The new skin.</param> /// <param name="allowFallback">Whether fallback to default skin should be allowed if the custom skin is missing this resource.</param> protected virtual void SkinChanged(ISkinSource skin, bool allowFallback) { } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); skin.SourceChanged -= onChange; } } }
mit
C#
fed19228f5791003d523bfd983a36f4abfec5a99
store Json/Start/Length.
PenguinF/sandra-three
Sandra.UI.WF/Storage/JsonSyntax.cs
Sandra.UI.WF/Storage/JsonSyntax.cs
#region License /********************************************************************************* * JsonSyntax.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ #endregion using System; namespace Sandra.UI.WF.Storage { public class JsonTerminalSymbol { public string Json { get; } public int Start { get; } public int Length { get; } public JsonTerminalSymbol(string json, int start, int length) { if (json == null) throw new ArgumentNullException(nameof(json)); if (start < 0) throw new ArgumentOutOfRangeException(nameof(start)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); if (json.Length < start) throw new ArgumentOutOfRangeException(nameof(start)); if (json.Length < start + length) throw new ArgumentOutOfRangeException(nameof(length)); Json = json; Start = start; Length = length; } } }
#region License /********************************************************************************* * JsonSyntax.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ #endregion using System; namespace Sandra.UI.WF.Storage { public class JsonTerminalSymbol { public string Json { get; } public int Start { get; } public int Length { get; } public JsonTerminalSymbol(string json, int start, int length) { if (json == null) throw new ArgumentNullException(nameof(json)); if (start < 0) throw new ArgumentOutOfRangeException(nameof(start)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); if (json.Length < start) throw new ArgumentOutOfRangeException(nameof(start)); if (json.Length < start + length) throw new ArgumentOutOfRangeException(nameof(length)); } } }
apache-2.0
C#
488393861325fcb2bb55183abcfd3cdca6662255
Put some explanation into Relative.cshtml.
LorandBiro/OctoPack.Precompile,LorandBiro/OctoPack.Precompile
TestWebApplication/Relative.cshtml
TestWebApplication/Relative.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>OctoPack.Precompile</title> </head> <body> <p>This page is for testing linked files. Intentionally placed outside of the project.</p> </body> </html>
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>OctoPack.Precompile</title> </head> <body> <p>This is a test website with a Razor view page to test the precompilation.</p> <ul> @for (int i = 1; i <= 10; i++) { <li>@i</li> } </ul> </body> </html>
mit
C#
18d930d24d4ba22f7d3be44bafd803d02d9b8065
Fix AssemblyInfo
MarkKhromov/The-Log
TheLog/Properties/AssemblyInfo.cs
TheLog/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("The Log")] [assembly: AssemblyProduct("The Log")] [assembly: AssemblyCopyright("Copyright © Mark Khromov 2017")] [assembly: AssemblyDescription("Library for logging.")] [assembly: ComVisible(false)] [assembly: Guid("968ef723-0186-4600-9c3b-674f480f7333")] [assembly: AssemblyVersion("1.1.*")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("The Log")] [assembly: AssemblyProduct("Th eLog")] [assembly: AssemblyCopyright("Copyright © Mark Khromov 2017")] [assembly: ComVisible(false)] [assembly: Guid("968ef723-0186-4600-9c3b-674f480f7333")] [assembly: AssemblyVersion("1.1.*")]
mit
C#
98e6f40fbf690eb14e95be6306561ca7454806e7
add constructor to Game.cs
svmnotn/friendly-guacamole
Assets/src/data/Game.cs
Assets/src/data/Game.cs
using System.Collections.Generic; public class Game { List<Player> players; Player curr; Dictionary<Vector, Grid> map; public Game(List<Player> players) { this.players = players; curr = players.ToArray () [0]; map = new Dictionary<Vector, Grid> (); map.Add (new Vector (0, 0), new Grid ()); } }
using System.Collections.Generic; public class Game { List<Player> players; Player curr; Dictionary<Vector, Grid> map; }
mit
C#
f3572d9f72acb4f16e8c66f1757c37b7aecbf1d8
Update standard submission status types
openchargemap/ocm-system,openchargemap/ocm-system,openchargemap/ocm-system,openchargemap/ocm-system
API/OCM.Net/OCM.API.Model/Base/CoreReferenceData.cs
API/OCM.Net/OCM.API.Model/Base/CoreReferenceData.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace OCM.API.Common.Model { public enum StandardDataProviders { OpenChargeMapContrib = 1 } public enum StandardOperators { UnknownOperator = 0 } public enum StandardUsageTypes { Public = 1, PrivateRestricted = 2, PrivatelyOwned_NoticeRequired = 3 } public enum StandardSubmissionStatusTypes { Submitted_UnderReview = 1, Imported_UnderReview = 50, Imported_Published = 100, Submitted_Published = 200, Submission_Rejected_Incomplete = 250, Delisted = 1000, Delisted_Duplicate = 1001, Delisted_NoLongerActive = 1002, Delisted_NotPublicInformation = 1010 } public enum StandardCommentTypes { GeneralComment = 10, ImportantNotice = 50, SuggestedChange = 100, SuggestedChangeActioned = 110, FaultReport = 1000 } public enum StandardUsers { System = 1008 } public enum StandardEntityTypes { POI=1 } public class CoreReferenceData { public List<ChargerType> ChargerTypes { get; set; } public List<ConnectionType> ConnectionTypes { get; set; } public List<CurrentType> CurrentTypes { get; set; } public List<Country> Countries { get; set; } public List<DataProvider> DataProviders { get; set; } public List<OperatorInfo> Operators { get; set; } public List<StatusType> StatusTypes { get; set; } public List<SubmissionStatusType> SubmissionStatusTypes { get; set; } public List<UsageType> UsageTypes { get; set; } public List<UserCommentType> UserCommentTypes { get; set; } public List<CheckinStatusType> CheckinStatusTypes { get; set; } public List<MetadataGroup> MetadataGroups { get; set; } /// <summary> /// Blank item used as template to populate/construct JSON object /// </summary> public ChargePoint ChargePoint { get; set; } public UserComment UserComment { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace OCM.API.Common.Model { public enum StandardDataProviders { OpenChargeMapContrib = 1 } public enum StandardOperators { UnknownOperator = 0 } public enum StandardUsageTypes { Public = 1, PrivateRestricted = 2, PrivatelyOwned_NoticeRequired = 3 } public enum StandardSubmissionStatusTypes { Submitted_UnderReview = 1, Imported_UnderReview = 50, Imported_Published = 100, Submitted_Published = 200, Delisted = 1000 } public enum StandardCommentTypes { GeneralComment = 10, ImportantNotice = 50, SuggestedChange = 100, SuggestedChangeActioned = 110, FaultReport = 1000 } public enum StandardUsers { System = 1008 } public enum StandardEntityTypes { POI=1 } public class CoreReferenceData { public List<ChargerType> ChargerTypes { get; set; } public List<ConnectionType> ConnectionTypes { get; set; } public List<CurrentType> CurrentTypes { get; set; } public List<Country> Countries { get; set; } public List<DataProvider> DataProviders { get; set; } public List<OperatorInfo> Operators { get; set; } public List<StatusType> StatusTypes { get; set; } public List<SubmissionStatusType> SubmissionStatusTypes { get; set; } public List<UsageType> UsageTypes { get; set; } public List<UserCommentType> UserCommentTypes { get; set; } public List<CheckinStatusType> CheckinStatusTypes { get; set; } public List<MetadataGroup> MetadataGroups { get; set; } /// <summary> /// Blank item used as template to populate/construct JSON object /// </summary> public ChargePoint ChargePoint { get; set; } public UserComment UserComment { get; set; } } }
mit
C#
836a068e3c7ba0243dfb292df8976d7926999344
Fix dangling reference to forthcoming DatumToStringVisitor
Sunlighter/CanonicalTypes
CanonicalTypes/Datum.cs
CanonicalTypes/Datum.cs
using System; using CanonicalTypes.Parsing; namespace CanonicalTypes { public abstract class Datum { public abstract DatumType DatumType { get; } public abstract T Visit<T>(IDatumVisitor<T> visitor); public abstract T Visit<T>(IDatumVisitorWithState<T> visitor, T state); public static bool TryParse(string str, out Datum d) { ICharParser<Datum> parser = Parser.ParseConvert ( Parser.ParseSequence ( Parser.ParseDatumWithBoxes.ResultToObject(), Parser.ParseEOF.ResultToObject() ), list => (Datum)(list[0]), "failure message" ); CharParserContext context = new CharParserContext(str); ParseResult<Datum> result = context.TryParseAt(parser, 0, str.Length); if (result is ParseSuccess<Datum>) { ParseSuccess<Datum> success = (ParseSuccess<Datum>)result; d = success.Value; return true; } d = null; return false; } } }
using System; using CanonicalTypes.Parsing; namespace CanonicalTypes { public abstract class Datum { public abstract DatumType DatumType { get; } public abstract T Visit<T>(IDatumVisitor<T> visitor); public abstract T Visit<T>(IDatumVisitorWithState<T> visitor, T state); public static bool TryParse(string str, out Datum d) { ICharParser<Datum> parser = Parser.ParseConvert ( Parser.ParseSequence ( Parser.ParseDatumWithBoxes.ResultToObject(), Parser.ParseEOF.ResultToObject() ), list => (Datum)(list[0]), "failure message" ); CharParserContext context = new CharParserContext(str); ParseResult<Datum> result = context.TryParseAt(parser, 0, str.Length); if (result is ParseSuccess<Datum>) { ParseSuccess<Datum> success = (ParseSuccess<Datum>)result; d = success.Value; return true; } d = null; return false; } public override string ToString() { DatumToStringVisitor dsv = new DatumToStringVisitor(); return Visit(dsv); } } }
apache-2.0
C#
032a1a754891b795bc320e4dc35a0bb8314f499b
Fix Alphabet component solver
samfun123/KtaneTwitchPlays,CaitSith2/KtaneTwitchPlays
Assets/Scripts/ComponentSolvers/Modded/Misc/AlphabetComponentSolver.cs
Assets/Scripts/ComponentSolvers/Modded/Misc/AlphabetComponentSolver.cs
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine; public class AlphabetComponentSolver : ComponentSolver { public AlphabetComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) : base(bombCommander, bombComponent, ircConnection, canceller) { _buttons = bombComponent.GetComponent<KMSelectable>().Children; modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType()); } protected override IEnumerator RespondToCommandInternal(string inputCommand) { var commands = inputCommand.ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (commands.Length >= 2 && (commands[0] == "submit" || commands[0] == "press")) { List<string> buttonLabels = _buttons.Select(button => button.GetComponentInChildren<TextMesh>().text.ToLowerInvariant()).ToList(); if (!buttonLabels.Any(label => label == " ")) { IEnumerable<string> submittedText = commands.Where((_, i) => i > 0); List<string> fixedLabels = new List<string>(); foreach (string text in submittedText) { if (buttonLabels.Any(label => label.Equals(text))) { fixedLabels.Add(text); } } if (fixedLabels.Count == submittedText.Count()) { yield return null; foreach (string fixedLabel in fixedLabels) { yield return DoInteractionClick(_buttons[buttonLabels.IndexOf(fixedLabel)]); } } } } } private KMSelectable[] _buttons = null; }
using System; using System.Linq; using System.Reflection; using System.Collections; using System.Collections.Generic; using UnityEngine; public class AlphabetComponentSolver : ComponentSolver { public AlphabetComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) : base(bombCommander, bombComponent, ircConnection, canceller) { _buttons = bombComponent.GetComponent<KMSelectable>().Children; modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType()); } protected override IEnumerator RespondToCommandInternal(string inputCommand) { var commands = inputCommand.ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); yield return null; if (commands.Length >= 2 && commands[0].Equals("submit")) { List<string> buttonLabels = _buttons.Select(button => button.GetComponentInChildren<TextMesh>().text.ToLowerInvariant()).ToList(); if (!buttonLabels.Any(label => label == " ")) { IEnumerable<string> submittedText = commands.Where((_, i) => i > 0); List<string> fixedLabels = new List<string>(); foreach (string text in submittedText) { if (buttonLabels.Any(label => label.Equals(text))) { fixedLabels.Add(text); } } if (fixedLabels.Count == submittedText.Count()) { foreach (string fixedLabel in fixedLabels) { KMSelectable button = _buttons[buttonLabels.IndexOf(fixedLabel)]; DoInteractionStart(button); DoInteractionEnd(button); yield return new WaitForSeconds(0.1f); } } } } } private KMSelectable[] _buttons = null; }
mit
C#
869814580a8bea2e3ad2f8696929cd15f9a69b0a
Use List because IList isn't supported by FX.Configuration
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
IntegrationEngine.Core/Configuration/IntegrationPointConfigurations.cs
IntegrationEngine.Core/Configuration/IntegrationPointConfigurations.cs
using System; using System.Collections.Generic; namespace IntegrationEngine.Core.Configuration { public class IntegrationPointConfigurations { public List<MailConfiguration> Mail { get; set; } public List<RabbitMQConfiguration> RabbitMQ { get; set; } public List<ElasticsearchConfiguration> Elasticsearch { get; set; } } }
using System; using System.Collections.Generic; namespace IntegrationEngine.Core.Configuration { public class IntegrationPointConfigurations { public IList<MailConfiguration> Mail { get; set; } public IList<RabbitMQConfiguration> RabbitMQ { get; set; } public IList<ElasticsearchConfiguration> Elasticsearch { get; set; } } }
mit
C#
cc23065579a63426bd0a40488e68b4b99ff41034
Reformat exception throwing statements
dirkrombauts/SpecLogLogoReplacer
UI/ViewModel/SpecLogTransformer.cs
UI/ViewModel/SpecLogTransformer.cs
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO.Abstractions; namespace SpecLogLogoReplacer.UI.ViewModel { public class SpecLogTransformer : ISpecLogTransformer { private readonly IFileSystem fileSystem; public SpecLogTransformer() : this (new FileSystem()) { } public SpecLogTransformer(IFileSystem fileSystem) { this.fileSystem = fileSystem; } public void Transform(string pathToSpecLogFile, string pathToLogo) { if (pathToSpecLogFile == null) throw new ArgumentNullException("pathToSpecLogFile"); if (pathToLogo == null) throw new ArgumentNullException("pathToLogo"); pathToSpecLogFile = SanitizePath(pathToSpecLogFile); pathToLogo = SanitizePath(pathToLogo); var specLogFile = LoadSpecLogHtmlFile(pathToSpecLogFile); var newLogo = LoadLogo(pathToLogo); var patchedSpecLogFile = PatchSpecLogFile(specLogFile, newLogo); ReplaceSpecLogHtmlFile(pathToSpecLogFile, patchedSpecLogFile); } private void ReplaceSpecLogHtmlFile(string pathToSpecLogFile, string patchedSpecLogFile) { this.fileSystem.File.WriteAllText(pathToSpecLogFile, patchedSpecLogFile); } private static string PatchSpecLogFile(string specLogFile, Image newLogo) { var patchedSpecLogFile = new LogoReplacer().Replace(specLogFile, newLogo, ImageFormat.Png); return patchedSpecLogFile; } private string LoadSpecLogHtmlFile(string pathToSpecLogFile) { var specLogFile = this.fileSystem.File.ReadAllText(pathToSpecLogFile); return specLogFile; } private Image LoadLogo(string pathToLogo) { Image newLogo; using (var stream = this.fileSystem.File.OpenRead(pathToLogo)) { newLogo = Image.FromStream(stream); } return newLogo; } private static string SanitizePath(string pathToSpecLogFile) { if (pathToSpecLogFile.StartsWith("\"")) { pathToSpecLogFile = pathToSpecLogFile.Substring(1); } if (pathToSpecLogFile.EndsWith("\"")) { pathToSpecLogFile = pathToSpecLogFile.Substring(0, pathToSpecLogFile.Length - 1); } return pathToSpecLogFile; } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO.Abstractions; namespace SpecLogLogoReplacer.UI.ViewModel { public class SpecLogTransformer : ISpecLogTransformer { private readonly IFileSystem fileSystem; public SpecLogTransformer() : this (new FileSystem()) { } public SpecLogTransformer(IFileSystem fileSystem) { this.fileSystem = fileSystem; } public void Transform(string pathToSpecLogFile, string pathToLogo) { if (pathToSpecLogFile == null) { throw new ArgumentNullException("pathToSpecLogFile"); } if (pathToLogo == null) { throw new ArgumentNullException("pathToLogo"); } pathToSpecLogFile = SanitizePath(pathToSpecLogFile); pathToLogo = SanitizePath(pathToLogo); var specLogFile = LoadSpecLogHtmlFile(pathToSpecLogFile); var newLogo = LoadLogo(pathToLogo); var patchedSpecLogFile = PatchSpecLogFile(specLogFile, newLogo); ReplaceSpecLogHtmlFile(pathToSpecLogFile, patchedSpecLogFile); } private void ReplaceSpecLogHtmlFile(string pathToSpecLogFile, string patchedSpecLogFile) { this.fileSystem.File.WriteAllText(pathToSpecLogFile, patchedSpecLogFile); } private static string PatchSpecLogFile(string specLogFile, Image newLogo) { var patchedSpecLogFile = new LogoReplacer().Replace(specLogFile, newLogo, ImageFormat.Png); return patchedSpecLogFile; } private string LoadSpecLogHtmlFile(string pathToSpecLogFile) { var specLogFile = this.fileSystem.File.ReadAllText(pathToSpecLogFile); return specLogFile; } private Image LoadLogo(string pathToLogo) { Image newLogo; using (var stream = this.fileSystem.File.OpenRead(pathToLogo)) { newLogo = Image.FromStream(stream); } return newLogo; } private static string SanitizePath(string pathToSpecLogFile) { if (pathToSpecLogFile.StartsWith("\"")) { pathToSpecLogFile = pathToSpecLogFile.Substring(1); } if (pathToSpecLogFile.EndsWith("\"")) { pathToSpecLogFile = pathToSpecLogFile.Substring(0, pathToSpecLogFile.Length - 1); } return pathToSpecLogFile; } } }
isc
C#
f63f3992ab4da74d21317970ae3b87b3483920e6
Update AlphaStreamsSlippageModel.cs
QuantConnect/Lean,StefanoRaggi/Lean,StefanoRaggi/Lean,JKarathiya/Lean,AlexCatarino/Lean,QuantConnect/Lean,jameschch/Lean,jameschch/Lean,jameschch/Lean,QuantConnect/Lean,StefanoRaggi/Lean,JKarathiya/Lean,AlexCatarino/Lean,AlexCatarino/Lean,QuantConnect/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,jameschch/Lean,StefanoRaggi/Lean,JKarathiya/Lean,jameschch/Lean,JKarathiya/Lean
Common/Orders/Slippage/AlphaStreamsSlippageModel.cs
Common/Orders/Slippage/AlphaStreamsSlippageModel.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using QuantConnect.Securities; using System.Collections.Generic; namespace QuantConnect.Orders.Slippage { /// <summary> /// Represents a slippage model that uses a constant percentage of slip /// </summary> public class AlphaStreamsSlippageModel : ISlippageModel { private const decimal _slippagePercent = 0.0001m; /// <summary> /// Unfortunate dictionary of ETFs and their spread on 10/10 so that we can better approximate /// slippage for the competition /// </summary> private readonly IDictionary<string, decimal> _spreads = new Dictionary<string, decimal> { {"PPLT", 0.13m}, {"DGAZ", 0.135m}, {"EDV", 0.085m}, {"SOXL", 0.1m} }; /// <summary> /// Initializes a new instance of the <see cref="AlphaStreamsSlippageModel"/> class /// </summary> public AlphaStreamsSlippageModel() { } /// <summary> /// Return a decimal cash slippage approximation on the order. /// </summary> public decimal GetSlippageApproximation(Security asset, Order order) { if (asset.Type != SecurityType.Equity) { return 0; } decimal slippagePercent; if (!_spreads.TryGetValue(asset.Symbol.Value, out slippagePercent)) { return _slippagePercent * asset.GetLastData()?.Value ?? 0; } return slippagePercent * asset.GetLastData()?.Value ?? 0; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using QuantConnect.Securities; using System.Collections.Generic; namespace QuantConnect.Orders.Slippage { /// <summary> /// Represents a slippage model that uses a constant percentage of slip /// </summary> public class AlphaStreamsSlippageModel : ISlippageModel { private const decimal _slippagePercent = 0.0005m; /// <summary> /// Unfortunate dictionary of ETFs and their spread on 10/10 so that we can better approximate /// slippage for the competition /// </summary> private readonly IDictionary<string, decimal> _spreads = new Dictionary<string, decimal> { {"PPLT", 0.13m}, {"DGAZ", 0.135m}, {"EDV", 0.085m}, {"SOXL", 0.1m} }; /// <summary> /// Initializes a new instance of the <see cref="AlphaStreamsSlippageModel"/> class /// </summary> public AlphaStreamsSlippageModel() { } /// <summary> /// Return a decimal cash slippage approximation on the order. /// </summary> public decimal GetSlippageApproximation(Security asset, Order order) { if (asset.Type != SecurityType.Equity) { return 0; } decimal slippagePercent; if (!_spreads.TryGetValue(asset.Symbol.Value, out slippagePercent)) { return _slippagePercent * asset.GetLastData()?.Value ?? 0; } return slippagePercent * asset.GetLastData()?.Value ?? 0; } } }
apache-2.0
C#
32daea67f5c95addef13024060eb0999c745c234
Update CalculatingFormulasOnce.cs
aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET
Examples/CSharp/Formulas/CalculatingFormulasOnce.cs
Examples/CSharp/Formulas/CalculatingFormulasOnce.cs
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.Formulas { public class CalculatingFormulasOnce { 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); //Load the template workbook Workbook workbook = new Workbook(dataDir + "book1.xls"); //Print the time before formula calculation Console.WriteLine(DateTime.Now); //Set the CreateCalcChain as false workbook.Settings.CreateCalcChain = false; //Calculate the workbook formulas workbook.CalculateFormula(); //Print the time after formula calculation Console.WriteLine(DateTime.Now); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.Formulas { public class CalculatingFormulasOnce { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Load the template workbook Workbook workbook = new Workbook(dataDir + "book1.xls"); //Print the time before formula calculation Console.WriteLine(DateTime.Now); //Set the CreateCalcChain as false workbook.Settings.CreateCalcChain = false; //Calculate the workbook formulas workbook.CalculateFormula(); //Print the time after formula calculation Console.WriteLine(DateTime.Now); } } }
mit
C#
c47953872eecc1c6ef5fa7208415351f0ed5eafe
fix argument null ex on mono
ntent-ad/Metrics.NET,huoxudong125/Metrics.NET,Liwoj/Metrics.NET,ntent-ad/Metrics.NET,alhardy/Metrics.NET,alhardy/Metrics.NET,etishor/Metrics.NET,huoxudong125/Metrics.NET,DeonHeyns/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,Recognos/Metrics.NET,mnadel/Metrics.NET
Src/Metrics/PerfCounters/PerformanceCounterGauge.cs
Src/Metrics/PerfCounters/PerformanceCounterGauge.cs
using System; using System.Diagnostics; namespace Metrics.PerfCounters { public class PerformanceCounterGauge : Gauge { private static readonly Func<float, string> DefaultFormat = f => f.ToString("F"); private readonly Func<float, string> format; private readonly PerformanceCounter performanceCounter; public PerformanceCounterGauge(string category, string counter) : this(category, counter, instance: null) { } public PerformanceCounterGauge(string category, string counter, Func<float, string> format) : this(category, counter, instance: null, format: format) { } public PerformanceCounterGauge(string category, string counter, string instance) : this(category, counter, instance, DefaultFormat) { } public PerformanceCounterGauge(string category, string counter, string instance, Func<float, string> format) { this.format = format; this.performanceCounter = instance == null? new PerformanceCounter(category, counter, true): new PerformanceCounter(category, counter, instance, true); } public GaugeValue Value { get { return new GaugeValue(format(this.performanceCounter.NextValue())); } } } }
using System; using System.Diagnostics; namespace Metrics.PerfCounters { public class PerformanceCounterGauge : Gauge { private static readonly Func<float, string> DefaultFormat = f => f.ToString("F"); private readonly Func<float, string> format; private readonly PerformanceCounter performanceCounter; public PerformanceCounterGauge(string category, string counter) : this(category, counter, instance: null) { } public PerformanceCounterGauge(string category, string counter, Func<float, string> format) : this(category, counter, instance: null, format: format) { } public PerformanceCounterGauge(string category, string counter, string instance) : this(category, counter, instance, DefaultFormat) { } public PerformanceCounterGauge(string category, string counter, string instance, Func<float, string> format) { this.format = format; this.performanceCounter = new PerformanceCounter(category, counter, instance, true); } public GaugeValue Value { get { return new GaugeValue(format(this.performanceCounter.NextValue())); } } } }
apache-2.0
C#
b94580f76725affbf30e3547ae942e4ed61be778
fix spawner
CallumCode/KaosGiraffe-,CallumCode/KaosGiraffe-
JamTestBed/Assets/Scripts/Spawner.cs
JamTestBed/Assets/Scripts/Spawner.cs
using UnityEngine; using System.Collections; public class Spawner : MonoBehaviour { public GameObject EnemyPrefab; public GameObject TreeManPrefab; public GameObject SwarmHeadPrefab; public GameObject TowerObject; public float spawnRate = 10; public float radius = 10; private float spawnTimer = 0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Time.time > (spawnTimer + 1 / spawnRate)) { spawnTimer = Time.time; SpawnEnemy(); } } void SpawnEnemy() { if (EnemyPrefab != null && TowerObject != null) { GameObject type = null; float rand = Random.value; SpawnSwarmHead(); /* if (rand > 0.5) { SpawnEnenmy(); } else if (rand > 0.2) { SpawnSwarm(); } else { SpawnTreeMan(); } */ } } void SpawnEnenmy() { Vector3 pos = PointOnCircle(radius, Random.Range(0, 360), TowerObject.transform.position); pos = new Vector3(pos.x,EnemyPrefab.transform.localScale.y, pos.z); GameObject enemy = Instantiate(EnemyPrefab, pos, Quaternion.identity) as GameObject; enemy.GetComponent<Enemy>().SetUp(TowerObject); enemy.transform.parent = transform; } void SpawnTreeMan() { Vector3 pos = PointOnCircle(radius, Random.Range(0, 360), TowerObject.transform.position); pos = new Vector3(pos.x, TreeManPrefab.transform.localScale.y, pos.z); GameObject enemy = Instantiate(TreeManPrefab, pos, Quaternion.identity) as GameObject; enemy.GetComponent<Enemy>().SetUp(TowerObject); enemy.transform.parent = transform; } void SpawnSwarmHead() { Vector3 pos = PointOnCircle(radius, Random.Range(0,360), TowerObject.transform.position); pos = new Vector3(pos.x, SwarmHeadPrefab.transform.localScale.y , pos.z); GameObject head = Instantiate(SwarmHeadPrefab, pos , Quaternion.identity) as GameObject; head.GetComponent<SwarmHead>().SetUp(TowerObject); head.transform.parent = transform; } Vector3 PointOnCircle(float radius, float angleInDegrees, Vector3 origin) { float x = (float)(radius * Mathf.Cos(angleInDegrees * Mathf.PI / 180F)) + origin.x; float z = (float)(radius * Mathf.Sin(angleInDegrees * Mathf.PI / 180F)) + origin.z; return new Vector3(x,0,z); } }
using UnityEngine; using System.Collections; public class Spawner : MonoBehaviour { public GameObject EnemyPrefab; public GameObject TreeManPrefab; public GameObject SwarmPrefab; public GameObject TowerObject; public float spawnRate = 10; public float radius = 10; private float spawnTimer = 0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Time.time > (spawnTimer + 1 / spawnRate)) { spawnTimer = Time.time; SpawnEnemy(); } } void SpawnEnemy() { if (EnemyPrefab != null && TowerObject != null) { GameObject type = null; float rand = Random.value; if (rand > 0.5) { SpawnEnenmy(); } else if (rand > 0.2) { SpawnSwarm(); } else { SpawnTreeMan(); } } } void SpawnEnenmy() { Vector3 pos = PointOnCircle(radius, Random.Range(0, 360), TowerObject.transform.position); pos = new Vector3(pos.x,EnemyPrefab.transform.localScale.y, pos.z); GameObject enemy = Instantiate(EnemyPrefab, pos, Quaternion.identity) as GameObject; enemy.GetComponent<Enemy>().SetUp(TowerObject); enemy.transform.parent = transform; } void SpawnTreeMan() { Vector3 pos = PointOnCircle(radius, Random.Range(0, 360), TowerObject.transform.position); pos = new Vector3(pos.x, TreeManPrefab.transform.localScale.y, pos.z); GameObject enemy = Instantiate(TreeManPrefab, pos, Quaternion.identity) as GameObject; enemy.GetComponent<Enemy>().SetUp(TowerObject); enemy.transform.parent = transform; } void SpawnSwarm() { Vector3 pos = PointOnCircle(radius, Random.Range(0,360), TowerObject.transform.position); pos = new Vector3(pos.x, SwarmPrefab.transform.localScale.y , pos.z); const int num = 5; for (int i = 0; i < num; i ++ ) { GameObject enemy = Instantiate(SwarmPrefab, pos + transform.right*i , Quaternion.identity) as GameObject; enemy.GetComponent<Enemy>().SetUp(TowerObject); enemy.transform.parent = transform; } } Vector3 PointOnCircle(float radius, float angleInDegrees, Vector3 origin) { float x = (float)(radius * Mathf.Cos(angleInDegrees * Mathf.PI / 180F)) + origin.x; float z = (float)(radius * Mathf.Sin(angleInDegrees * Mathf.PI / 180F)) + origin.z; return new Vector3(x,0,z); } }
mit
C#
d49608ddd9aad7f2ef3c88ad3f6fa77c2aa00e6a
disable warnings in tests
dadhi/ImTools
test/ImTools.UnitTests/SomeTests.cs
test/ImTools.UnitTests/SomeTests.cs
using NUnit.Framework; using System.Runtime.InteropServices; #pragma warning disable CS0649 namespace ImTools.UnitTests { [TestFixture] public class SomeTests { [Test] public void I_can_cast_specialized_instance_to_the_generic_type() { var eInt = CreateEntry(42); Assert.IsInstanceOf<IntEntry>(eInt); var eKey = CreateEntry("a"); Assert.IsInstanceOf<KEntry<string>>(eKey); } static Entry<K> CreateEntry<K>(K key) => key switch { int k => new IntEntry(k) as Entry<K>, _ => new KEntry<K>(key, key.GetHashCode()) }; abstract record Entry<K>(K Key); record KEntry<K>(K Key, int Hash) : Entry<K>(Key); record IntEntry(int Key) : Entry<int>(Key) { } [Test] public void The_empty_struct_takes_8_bytes() { int GetSize(object obj) => Marshal.ReadInt32(obj.GetType().TypeHandle.Value, 4); var e = new KEntry<string>("a", "a".GetHashCode()); var ee = new EEntry<string>("a", "a".GetHashCode()); var eSize = GetSize(e); var eeSize = GetSize(ee); Assert.Greater(eeSize, eSize); } readonly struct Empty {} record EEntry<K>(K Key, int Hash) : Entry<K>(Key) { public readonly Empty E; } } } // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { using System.ComponentModel; /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class IsExternalInit { } }
using NUnit.Framework; using System.Runtime.InteropServices; namespace ImTools.UnitTests { [TestFixture] public class SomeTests { [Test] public void I_can_cast_specialized_instance_to_the_generic_type() { var eInt = CreateEntry(42); Assert.IsInstanceOf<IntEntry>(eInt); var eKey = CreateEntry("a"); Assert.IsInstanceOf<KEntry<string>>(eKey); } static Entry<K> CreateEntry<K>(K key) => key switch { int k => new IntEntry(k) as Entry<K>, _ => new KEntry<K>(key, key.GetHashCode()) }; abstract record Entry<K>(K Key); record KEntry<K>(K Key, int Hash) : Entry<K>(Key); record IntEntry(int Key) : Entry<int>(Key) { } [Test] public void The_empty_struct_takes_8_bytes() { int GetSize(object obj) => Marshal.ReadInt32(obj.GetType().TypeHandle.Value, 4); var e = new KEntry<string>("a", "a".GetHashCode()); var ee = new EEntry<string>("a", "a".GetHashCode()); var eSize = GetSize(e); var eeSize = GetSize(ee); Assert.Greater(eeSize, eSize); } readonly struct Empty {} record EEntry<K>(K Key, int Hash) : Entry<K>(Key) { public readonly Empty E; } } } // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { using System.ComponentModel; /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class IsExternalInit { } }
mit
C#
c394c7d8a6a4b5fb9ec7b118af1e67babfe88344
Remove setter
smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
osu.Framework/Input/StateChanges/ISourcedFromTouch.cs
osu.Framework/Input/StateChanges/ISourcedFromTouch.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.Input.StateChanges.Events; namespace osu.Framework.Input.StateChanges { /// <summary> /// Denotes an input which was sourced from a touch event. /// Generally used to mark when an alternate input was triggered from a touch source (ie. touch being emulated as a mouse). /// </summary> public interface ISourcedFromTouch : IInput { /// <summary> /// The source touch event. /// </summary> TouchStateChangeEvent TouchEvent { get; } } }
// 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.Input.StateChanges.Events; namespace osu.Framework.Input.StateChanges { /// <summary> /// Denotes an input which was sourced from a touch event. /// Generally used to mark when an alternate input was triggered from a touch source (ie. touch being emulated as a mouse). /// </summary> public interface ISourcedFromTouch : IInput { /// <summary> /// The source touch event. /// </summary> TouchStateChangeEvent TouchEvent { get; set; } } }
mit
C#
c68309ac4f977a7fc104038bdc1ec6c78b0f8e0b
Update TestSceneCatcherArea to use SkinnableTestScene
smoogipoo/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,ppy/osu,ppy/osu,smoogipooo/osu,EVAST9919/osu,peppy/osu-new,peppy/osu
osu.Game.Rulesets.Catch.Tests/TestSceneCatcherArea.cs
osu.Game.Rulesets.Catch.Tests/TestSceneCatcherArea.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.UI; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatcherArea : SkinnableTestScene { private RulesetInfo catchRuleset; public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(CatcherArea), }; public TestSceneCatcherArea() { AddSliderStep<float>("CircleSize", 0, 8, 5, createCatcher); AddToggleStep("Hyperdash", t => CreatedDrawables.OfType<CatchInputManager>().Select(i => i.Child) .OfType<TestCatcherArea>().ForEach(c => c.ToggleHyperDash(t))); } private void createCatcher(float size) { SetContents(() => new CatchInputManager(catchRuleset) { RelativeSizeAxes = Axes.Both, Child = new TestCatcherArea(new BeatmapDifficulty { CircleSize = size }) { Anchor = Anchor.CentreLeft, Origin = Anchor.TopLeft }, }); } [BackgroundDependencyLoader] private void load(RulesetStore rulesets) { catchRuleset = rulesets.GetRuleset(2); } private class TestCatcherArea : CatcherArea { public TestCatcherArea(BeatmapDifficulty beatmapDifficulty) : base(beatmapDifficulty) { } public void ToggleHyperDash(bool status) => MovableCatcher.SetHyperDashState(status ? 2 : 1); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.UI; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatcherArea : OsuTestScene { private RulesetInfo catchRuleset; private TestCatcherArea catcherArea; public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(CatcherArea), }; public TestSceneCatcherArea() { AddSliderStep<float>("CircleSize", 0, 8, 5, createCatcher); AddToggleStep("Hyperdash", t => catcherArea.ToggleHyperDash(t)); } private void createCatcher(float size) { Child = new CatchInputManager(catchRuleset) { RelativeSizeAxes = Axes.Both, Child = catcherArea = new TestCatcherArea(new BeatmapDifficulty { CircleSize = size }) { Anchor = Anchor.CentreLeft, Origin = Anchor.TopLeft }, }; } [BackgroundDependencyLoader] private void load(RulesetStore rulesets) { catchRuleset = rulesets.GetRuleset(2); } private class TestCatcherArea : CatcherArea { public TestCatcherArea(BeatmapDifficulty beatmapDifficulty) : base(beatmapDifficulty) { } public void ToggleHyperDash(bool status) => MovableCatcher.SetHyperDashState(status ? 2 : 1); } } }
mit
C#
e558fd69d22fcf17dffce8e4b2d90b5c7042a513
Remove unnecessary null check and associated comment
NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu
osu.Game/Tests/Visual/RateAdjustedBeatmapTestScene.cs
osu.Game/Tests/Visual/RateAdjustedBeatmapTestScene.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Tests.Visual { /// <summary> /// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests. /// </summary> public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene { protected override void Update() { base.Update(); if (Beatmap.Value.TrackLoaded) { // note that this will override any mod rate application Beatmap.Value.Track.Tempo.Value = Clock.Rate; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Tests.Visual { /// <summary> /// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests. /// </summary> public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene { protected override void Update() { base.Update(); if (Beatmap.Value.TrackLoaded && Beatmap.Value.Track != null) // null check... wasn't required until now? { // note that this will override any mod rate application Beatmap.Value.Track.Tempo.Value = Clock.Rate; } } } }
mit
C#
17e2aa4e50452a4fda021146c687264de355e963
document QuickFixes property better
corngood/omnisharp-server,svermeulen/omnisharp-server,OmniSharp/omnisharp-server,mispencer/OmniSharpServer,x335/omnisharp-server,syl20bnr/omnisharp-server,x335/omnisharp-server,syl20bnr/omnisharp-server,corngood/omnisharp-server
OmniSharp/Common/QuickFixResponse.cs
OmniSharp/Common/QuickFixResponse.cs
using System.Collections.Generic; using OmniSharp.Common; namespace OmniSharp.Common { /// <summary> /// Base class for QuickFix-centered responses. /// </summary> public abstract class QuickFixResponse { public QuickFixResponse() {} public QuickFixResponse(IEnumerable<QuickFix> quickFixes) { this.QuickFixes = quickFixes; } /// <remarks> /// This will not be sent over the network. It must be /// accessed in a public property in a derived class. Then /// the public property will be sent. /// </remarks> protected IEnumerable<QuickFix> QuickFixes { get; set; } } }
using System.Collections.Generic; using OmniSharp.Common; namespace OmniSharp.Common { /// <summary> /// Base class for QuickFix-centered responses. /// </summary> public abstract class QuickFixResponse { public QuickFixResponse() {} public QuickFixResponse(IEnumerable<QuickFix> quickFixes) { this.QuickFixes = quickFixes; } protected IEnumerable<QuickFix> QuickFixes { get; set; } } }
mit
C#
aaeaa39a407a101002c71e7b543281061a810afc
Update 0Basics.cs
iitjee/SteppinsMachineLearning,iitjee/SteppinsMachineLearning,iitjee/SteppinsMachineLearning
ENCOG/0Basics.cs
ENCOG/0Basics.cs
/* - ENCOG is an advanced machine learning framework - Machine learning algorithms such as Support Vector Machines, Artificial Neural Networks, Bayesian Networks, Hidden Markov Models, Genetic Programming and Genetic Algorithms are supported. - Most Encog training algoritms are multi-threaded and scale well to multicore hardware. - C, C++, Java, and .NET are supported Outline: - Data - Network - Training - Evaluation - XOR Problem ENCOG uses IMLData inteface for ENCOG /*Setup: Just open .csproj file in Visual Studio and run. Tut says to downlaod some ENCOG dll file but worked fine without it. Just try one :) */ For simple case use BasicMLData class eg: double[] p = new double[10]; //Use double or Array of double values for NNs IMLData data = new BasicMLData(p); If you've smaller training data: Use Jagged array to provide smaller training input or output data instances double[][] XOR_Input = { new[] {0.0. 0.0}, new[] {0.0. 0.0}, new[] {0.0. 0.0}, new[] {0.0. 0.0} }; To create Training Data set: Use BasicMLDataSet class var trainingSet = new BasicMLDataSet(XOR_Input, XOR_Ideal); /* Creating Neural Network */ private static BasicNetwork CreateNetwork() { //Create an object of 'BasicNetwork' Class var network = new BasicNetwork(); //Use BasicLayer class to create input, hidden and output layers network.AddLayer(new BasicLayer(null, true, 2)); //This is input layer and we haven't used any activation function(=> null). Two neurons are used network.AddLayer(new BasicLayer(new ActivationSigmoid(), true, 2)); //First hidden layer with sigmoid activation function with bias network.AddLayer(new BasicLayer(new ActivationSigmoid(), false, 1)); //Output layer with sigmoid activation with no bias //1stparam = Activation function should always implement IActivationFunction Interface //Here, we've used sigmoid activation function //2ndparam = should use bias parameter for the layer or not //3rdparam = Number of neurons in that layer network.Structure.FinalizeStructure(); //Tells fw that all the layers have been added now network.Reset();//Randomly initialize the weights return network; } /* Training Process */ In ENCOG, Training algos are classes implementing the IMLTrain Interface var train = new ResilientPropagation(network, trainingSet); //created a training object int epoch = 1; do { train.Iteration(); epoch++; Console.WriteLine("Iteration No :{0}, Error: {1}", epoch, train.Error); } while (train.Error > 0.001); //loop until the error is less than a particular epoch /* Evaluation */ foreach (var item in trainingSet) //we pass each data set { var output = network.Compute(item.Input); //You can use compute method of trained network to calculate the output //Note that the input should be a double array or implement IMLDataInterface Console.WriteLine("Input : {0}, {1} Ideal : {2} Actual : {3}", item.Input[0], item.Input[1], item.Ideal[0], output[0]); } //Complte problem solution @ https://github.com/iitjee/SteppinsMachineLearning/blob/master/ENCOG/1XORproblem.cs
/* - ENCOG is an advanced machine learning framework - Machine learning algorithms such as Support Vector Machines, Artificial Neural Networks, Bayesian Networks, Hidden Markov Models, Genetic Programming and Genetic Algorithms are supported. - Most Encog training algoritms are multi-threaded and scale well to multicore hardware. - C, C++, Java, and .NET are supported Outline: - Data - Network - Training - Evaluation - XOR Problem ENCOG uses IMLData inteface for ENCOG */ For simple case use BasicMLData class eg: double[] p = new double[10]; //Use double or Array of double values for NNs IMLData data = new BasicMLData(p); If you've smaller training data: Use Jagged array to provide smaller training input or output data instances double[][] XOR_Input = { new[] {0.0. 0.0}, new[] {0.0. 0.0}, new[] {0.0. 0.0}, new[] {0.0. 0.0} }; To create Training Data set: Use BasicMLDataSet class var trainingSet = new BasicMLDataSet(XOR_Input, XOR_Ideal);
apache-2.0
C#
7c2d7f5939f3e6aec0b374969b11624d5890ff55
Update Test project
yishn/GTPWrapper
GTPWrapperTest/Program.cs
GTPWrapperTest/Program.cs
using GTPWrapper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GTPWrapperTest { public class Program { static void Main(string[] args) { TestEngine engine = new TestEngine(); engine.NewCommand += engine_NewCommand; engine.ResponsePushed += engine_ResponsePushed; engine.ConnectionClosed += engine_ConnectionClosed; while (true) { string input = Console.ReadLine(); engine.ParseString(input); } } static void engine_ConnectionClosed(object sender, EventArgs e) { Environment.Exit(0); } static void engine_NewCommand(object sender, CommandEventArgs e) { TestEngine engine = (TestEngine)sender; engine.ExecuteCommands(); } static void engine_ResponsePushed(object sender, ResponseEventArgs e) { Console.WriteLine(e.Response.ToString() + "\n"); } } }
using GTPWrapper; using GTPWrapper.DataTypes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GTPWrapperTest { public class Program { static void Main(string[] args) { Engine engine = new Engine("GTP\nWrapper\nTest", "1"); engine.NewCommand += engine_NewCommand; engine.ResponsePushed += engine_ResponsePushed; engine.ConnectionClosed += engine_ConnectionClosed; engine.SupportedCommands.AddRange(new string[] { "showboard", "error" }); while (true) { string input = Console.ReadLine(); engine.ParseString(input); } } static void engine_ConnectionClosed(object sender, EventArgs e) { Environment.Exit(0); } static void engine_NewCommand(object sender, CommandEventArgs e) { Engine engine = (Engine)sender; string response = e.Command.Name; if (e.Command.Name == "showboard") { response = new Board(13).ToString(); } engine.PushResponse(new Response(e.Command, response, e.Command.Name == "error")); } static void engine_ResponsePushed(object sender, ResponseEventArgs e) { Console.Write(e.Response.ToString() + "\n\n"); } } }
mit
C#
4f36e5d6233f3582444caffe330cb9128f851fb5
Fix message cleaning
glconti/awesome-bot,glconti/awesome-bot
awesome-bot/Dialogs/RootDialog.cs
awesome-bot/Dialogs/RootDialog.cs
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; namespace awesome_bot.Dialogs { [Serializable] public class RootDialog : IDialog<object> { public Task StartAsync(IDialogContext context) { context.Wait(MessageReceivedAsync); return Task.CompletedTask; } private static async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result) { var activity = await result as Activity; if (activity == null) { await context.PostAsync("Do you want to ask me something?"); context.Wait(MessageReceivedAsync); return; } var message = RemoveMentions(activity); var command = message.Split(' ').FirstOrDefault(); var commandHandler = CommandHandlerFactory.Handle(command); if (commandHandler == null) { await context.PostAsync($"Sorry, I don't understand {message}"); await context.PostAsync(CommandHandlerFactory.GetGuide()); context.Wait(MessageReceivedAsync); return; } await commandHandler.Answer(context, message.Substring(command.Length)); context.Wait(MessageReceivedAsync); } private static string RemoveMentions(IMessageActivity activity) => activity.GetMentions() .Where(mention => mention.Mentioned.Id == activity.Recipient.Id && mention.Text != null) .Aggregate(activity.Text, (current, mention) => current.Replace(mention.Text, string.Empty)) .Trim(); } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; namespace awesome_bot.Dialogs { [Serializable] public class RootDialog : IDialog<object> { public Task StartAsync(IDialogContext context) { context.Wait(MessageReceivedAsync); return Task.CompletedTask; } private static async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result) { var activity = await result as Activity; if (activity == null) { await context.PostAsync("Do you want to ask me something?"); context.Wait(MessageReceivedAsync); return; } var message = RemoveMentions(activity); var command = message.Split(' ').FirstOrDefault(); var commandHandler = CommandHandlerFactory.Handle(command); if (commandHandler == null) { await context.PostAsync($"Sorry, I don't understand {activity.Text}"); await context.PostAsync(CommandHandlerFactory.GetGuide()); context.Wait(MessageReceivedAsync); return; } await commandHandler.Answer(context, activity.Text.Substring(command.Length)); context.Wait(MessageReceivedAsync); } private static string RemoveMentions(IMessageActivity activity) => activity.GetMentions() .Where(mention => mention.Mentioned.Id == activity.Recipient.Id && mention.Text != null) .Aggregate(activity.Text, (current, mention) => current.Replace(mention.Text, string.Empty)); } }
mit
C#
2e3d70650dfd718ccb20a4df4568c4ac305f4123
Remove not common engine from base
wangkanai/Detection
src/Models/Engine.cs
src/Models/Engine.cs
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System; namespace Wangkanai.Detection.Models { [Flags] public enum Engine { Unknown = 0, // Unknown engine WebKit = 1, // iOs (Safari, WebViews, Chrome <28) Blink = 1 << 1, // Google Chrome, Opera v15+ Gecko = 1 << 2, // Firefox, Netscape Trident = 1 << 3, // IE, Outlook EdgeHTML = 1 << 4, // Microsoft Edge Servo = 1 << 12, // Mozilla & Samsung Others = 1 << 15 // Others } }
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System; namespace Wangkanai.Detection.Models { [Flags] public enum Engine { Unknown = 0, // Unknown engine WebKit = 1, // iOs (Safari, WebViews, Chrome <28) Blink = 1 << 1, // Google Chrome, Opera v15+ Gecko = 1 << 2, // Firefox, Netscape Trident = 1 << 3, // IE, Outlook EdgeHTML = 1 << 4, // Microsoft Edge KHTML = 1 << 5, // Konqueror Presto = 1 << 6, // Goanna = 1 << 7, // Pale Moon NetSurf = 1 << 8, // NetSurf NetFront = 1 << 9, // Access NetFront Prince = 1 << 10, // Robin = 1 << 11, // The Bat! Servo = 1 << 12, // Mozilla & Samsung Tkhtml = 1 << 13, // hv3 Links2 = 1 << 14, // launched with -g Others = 1 << 15 // Others } }
apache-2.0
C#
d353cac77a7276b065cd230ccc5d69f0b57e9a02
Fix misleading config in Webpack sample
reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET
src/React.Sample.Webpack.CoreMvc/Startup.cs
src/React.Sample.Webpack.CoreMvc/Startup.cs
using System; using JavaScriptEngineSwitcher.ChakraCore; using JavaScriptEngineSwitcher.Extensions.MsDependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using React.AspNet; namespace React.Sample.Webpack.CoreMvc { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddJsEngineSwitcher(options => options.DefaultEngineName = ChakraCoreJsEngine.EngineName) .AddChakraCore(); services.AddReact(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // Build the intermediate service provider then return it services.BuildServiceProvider(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { // Initialise ReactJS.NET. Must be before static files. app.UseReact(config => { config .SetReuseJavaScriptEngines(true) .SetLoadBabel(false) .SetLoadReact(false) .AddScriptWithoutTransform("~/dist/runtime.js") .AddScriptWithoutTransform("~/dist/vendor.js") .AddScriptWithoutTransform("~/dist/components.js"); }); app.UseStaticFiles(); #if NETCOREAPP3_0 app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{path?}", new { controller = "Home", action = "Index" }); endpoints.MapControllerRoute("comments-root", "comments", new { controller = "Home", action = "Index" }); endpoints.MapControllerRoute("comments", "comments/page-{page}", new { controller = "Home", action = "Comments" }); }); #else app.UseMvc(routes => { routes.MapRoute("default", "{path?}", new { controller = "Home", action = "Index" }); routes.MapRoute("comments-root", "comments", new { controller = "Home", action = "Index" }); routes.MapRoute("comments", "comments/page-{page}", new { controller = "Home", action = "Comments" }); }); #endif } } }
using System; using JavaScriptEngineSwitcher.ChakraCore; using JavaScriptEngineSwitcher.Extensions.MsDependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using React.AspNet; namespace React.Sample.Webpack.CoreMvc { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddJsEngineSwitcher(options => options.DefaultEngineName = ChakraCoreJsEngine.EngineName) .AddChakraCore(); services.AddReact(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // Build the intermediate service provider then return it services.BuildServiceProvider(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { // Initialise ReactJS.NET. Must be before static files. app.UseReact(config => { config .SetReuseJavaScriptEngines(true) .SetLoadBabel(true) .SetLoadReact(false) .SetBabelVersion(BabelVersions.Babel7) .AddScriptWithoutTransform("~/dist/runtime.js") .AddScriptWithoutTransform("~/dist/vendor.js") .AddScriptWithoutTransform("~/dist/components.js"); }); app.UseStaticFiles(); #if NETCOREAPP3_0 app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{path?}", new { controller = "Home", action = "Index" }); endpoints.MapControllerRoute("comments-root", "comments", new { controller = "Home", action = "Index" }); endpoints.MapControllerRoute("comments", "comments/page-{page}", new { controller = "Home", action = "Comments" }); }); #else app.UseMvc(routes => { routes.MapRoute("default", "{path?}", new { controller = "Home", action = "Index" }); routes.MapRoute("comments-root", "comments", new { controller = "Home", action = "Index" }); routes.MapRoute("comments", "comments/page-{page}", new { controller = "Home", action = "Comments" }); }); #endif } } }
mit
C#
191d6e9bfd831cbf11a11580c1b99f56674650e9
Refactor RemoveDuplicates: use HashSet and List
cdmihai/msbuild,mono/msbuild,chipitsine/msbuild,Microsoft/msbuild,sean-gilliam/msbuild,sean-gilliam/msbuild,jeffkl/msbuild,mono/msbuild,mono/msbuild,chipitsine/msbuild,rainersigwald/msbuild,rainersigwald/msbuild,sean-gilliam/msbuild,rainersigwald/msbuild,jeffkl/msbuild,AndyGerlicher/msbuild,rainersigwald/msbuild,Microsoft/msbuild,AndyGerlicher/msbuild,Microsoft/msbuild,chipitsine/msbuild,AndyGerlicher/msbuild,AndyGerlicher/msbuild,cdmihai/msbuild,Microsoft/msbuild,mono/msbuild,cdmihai/msbuild,sean-gilliam/msbuild,jeffkl/msbuild,chipitsine/msbuild,jeffkl/msbuild,cdmihai/msbuild
src/Tasks/ListOperators/RemoveDuplicates.cs
src/Tasks/ListOperators/RemoveDuplicates.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Microsoft.Build.Tasks { /// <summary> /// Given a list of items, remove duplicate items. Attributes are not considered. Case insensitive. /// </summary> public class RemoveDuplicates : TaskExtension { /// <summary> /// The left-hand set of items to be RemoveDuplicatesed from. /// </summary> public ITaskItem[] Inputs { get; set; } = Array.Empty<TaskItem>(); /// <summary> /// List of unique items. /// </summary> [Output] public ITaskItem[] Filtered { get; set; } = null; /// <summary> /// True if any duplicate items were found. False otherwise. /// </summary> [Output] public bool HadAnyDuplicates { get; set; } = false; /// <summary> /// Execute the task. /// </summary> /// <returns></returns> public override bool Execute() { if (Inputs == null || Inputs.Length == 0) { Filtered = Array.Empty<ITaskItem>(); HadAnyDuplicates = false; return true; } var alreadySeen = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var filteredList = new List<ITaskItem>(Inputs.Length); foreach (ITaskItem item in Inputs) { if (alreadySeen.Add(item.ItemSpec)) { filteredList.Add(item); } } Filtered = filteredList.ToArray(); HadAnyDuplicates = Inputs.Length != Filtered.Length; return true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Microsoft.Build.Tasks { /// <summary> /// Given a list of items, remove duplicate items. Attributes are not considered. Case insensitive. /// </summary> public class RemoveDuplicates : TaskExtension { /// <summary> /// The left-hand set of items to be RemoveDuplicatesed from. /// </summary> public ITaskItem[] Inputs { get; set; } = Array.Empty<TaskItem>(); /// <summary> /// List of unique items. /// </summary> [Output] public ITaskItem[] Filtered { get; set; } = null; /// <summary> /// True if any duplicate items were found. False otherwise. /// </summary> [Output] public bool HadAnyDuplicates { get; set; } = false; /// <summary> /// Execute the task. /// </summary> /// <returns></returns> public override bool Execute() { var alreadySeen = new Hashtable(Inputs.Length, StringComparer.OrdinalIgnoreCase); var filteredList = new ArrayList(); foreach (ITaskItem item in Inputs) { if (!alreadySeen.ContainsKey(item.ItemSpec)) { alreadySeen[item.ItemSpec] = String.Empty; filteredList.Add(item); } } Filtered = (ITaskItem[])filteredList.ToArray(typeof(ITaskItem)); HadAnyDuplicates = Inputs.Length != Filtered.Length; return true; } } }
mit
C#
f4c7eb14ec2436ff5aa551d951d3a9ce99c1c0fd
Add ScriptLoader.LoadResources with unlimited parameters
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
Resources/ScriptLoader.cs
Resources/ScriptLoader.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Windows.Forms; using System.Linq; namespace TweetDck.Resources{ static class ScriptLoader{ public static string LoadResource(string name){ try{ return File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,name),Encoding.UTF8); }catch(Exception ex){ MessageBox.Show("Unfortunately, "+Program.BrandName+" could not load the "+name+" file. The program will continue running with limited functionality.\r\n\r\n"+ex.Message,Program.BrandName+" Has Failed :(",MessageBoxButtons.OK,MessageBoxIcon.Error); return null; } } public static IList<string> LoadResources(params string[] names){ return names.Select(LoadResource).ToList(); } } }
using System; using System.IO; using System.Text; using System.Windows.Forms; namespace TweetDck.Resources{ static class ScriptLoader{ public static string LoadResource(string name){ try{ return File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,name),Encoding.UTF8); }catch(Exception ex){ MessageBox.Show("Unfortunately, "+Program.BrandName+" could not load the "+name+" file. The program will continue running with limited functionality.\r\n\r\n"+ex.Message,Program.BrandName+" Has Failed :(",MessageBoxButtons.OK,MessageBoxIcon.Error); return null; } } } }
mit
C#
0359296d9dd5b4fd05bacee84d65159c39fd1f44
add link name (accessibility) (#620)
reactiveui/website,reactiveui/website,reactiveui/website,reactiveui/website
input/_Scripts.cshtml
input/_Scripts.cshtml
<script type="text/javascript" src="/assets/js/anchor.min.js"></script> <script type="text/javascript" src="/assets/js/clipboard.min.js"></script> <script type="text/javascript"> anchors.options.placement = 'left'; anchors.add('.content h1:not(.no-anchor), .content h2:not(.no-anchor), .content h3:not(.no-anchor), .content h4:not(.no-anchor), .content-header h1:not(.no-anchor)'); var snippets = document.querySelectorAll("pre > code"); [].forEach.call(snippets, function(snippet) { snippet.insertAdjacentHTML("beforebegin", "<button class='btn-copy' data-clipboard-snippet><i class='fa fa-clipboard clippy' aria-hidden='true'></i></button>"); }); var clipboardSnippets = new Clipboard('[data-clipboard-snippet]', { target: function(trigger) { return trigger.nextElementSibling; } }); clipboardSnippets.on('success', function(e) { e.clearSelection(); showTooltip(e.trigger, "Copied!"); }); clipboardSnippets.on('error', function(e) { showTooltip(e.trigger, fallbackMessage(e.action)); }); var iframeItem = $('iframe'); iframeItem.attr('title', 'video'); var apiSearchButton = $('.sidebar-form .btn'); apiSearchButton.attr('title', 'Search button'); var sideBarTreeView = $('.treeview a'); sideBarTreeView.attr('aria-label', 'link'); </script>
<script type="text/javascript" src="/assets/js/anchor.min.js"></script> <script type="text/javascript" src="/assets/js/clipboard.min.js"></script> <script type="text/javascript"> anchors.options.placement = 'left'; anchors.add('.content h1:not(.no-anchor), .content h2:not(.no-anchor), .content h3:not(.no-anchor), .content h4:not(.no-anchor), .content-header h1:not(.no-anchor)'); var snippets = document.querySelectorAll("pre > code"); [].forEach.call(snippets, function(snippet) { snippet.insertAdjacentHTML("beforebegin", "<button class='btn-copy' data-clipboard-snippet><i class='fa fa-clipboard clippy' aria-hidden='true'></i></button>"); }); var clipboardSnippets = new Clipboard('[data-clipboard-snippet]', { target: function(trigger) { return trigger.nextElementSibling; } }); clipboardSnippets.on('success', function(e) { e.clearSelection(); showTooltip(e.trigger, "Copied!"); }); clipboardSnippets.on('error', function(e) { showTooltip(e.trigger, fallbackMessage(e.action)); }); var iframeItem = $('iframe'); iframeItem.attr('title', 'video'); var apiSearchButton = $('.sidebar-form .btn'); apiSearchButton.attr('title', 'Search button'); </script>
mit
C#
dbbe27e5613ae4e1134b85efc8cfb0039860f706
Fix parsing in RenPyReturn. Fixes #47
dpek/unity-raconteur,exodrifter/unity-raconteur
Assets/Raconteur/RenPy/Script/RenPyReturn.cs
Assets/Raconteur/RenPy/Script/RenPyReturn.cs
using UnityEngine; using DPek.Raconteur.RenPy.State; using DPek.Raconteur.Util.Parser; namespace DPek.Raconteur.RenPy.Script { /// <summary> /// Ren'Py return statement. /// </summary> public class RenPyReturn : RenPyStatement { [SerializeField] private Expression m_expression; private string m_expressionString; private bool m_optionalExpressionUsed; public Expression Expression { get { return m_expression; } } public RenPyReturn() : base(RenPyStatementType.RETURN) { // Nothing to do } public override void Parse(ref Scanner tokens) { tokens.Seek("return"); tokens.Next(); // Check to see what's after the return before looking parsing m_expressionString = tokens.Seek("\0").Trim(); if(tokens.HasNext()) { // Parse the expression var parser = ExpressionParserFactory.GetRenPyParser (); m_expression = parser.ParseExpression (m_expressionString); m_optionalExpressionUsed = true; } } //TODO Dynamically scope the _return variable for Milestone 3 public override void Execute(RenPyState state) { //Evaluate the optional expression and store in _return if(m_optionalExpressionUsed) state.SetVariable ("_return", m_expression.Evaluate (state).ToString()); state.Execution.PopStackFrame(); } public override string ToDebugString() { string str = "return " + m_expressionString; return str; } } }
using UnityEngine; using DPek.Raconteur.RenPy.State; using DPek.Raconteur.Util.Parser; namespace DPek.Raconteur.RenPy.Script { /// <summary> /// Ren'Py return statement. /// </summary> public class RenPyReturn : RenPyStatement { [SerializeField] private Expression m_expression; private string m_expressionString; private bool m_optionalExpressionUsed; public Expression Expression { get { return m_expression; } } public RenPyReturn() : base(RenPyStatementType.RETURN) { // Nothing to do } public override void Parse(ref Scanner tokens) { tokens.Seek("return"); tokens.Next(); // Check if there is anything after the return if(tokens.HasNext()) { // Get the expression m_expressionString = tokens.Seek ("\0").Trim(); tokens.Next(); // Parse the expression var parser = ExpressionParserFactory.GetRenPyParser (); m_expression = parser.ParseExpression (m_expressionString); m_optionalExpressionUsed = true; } } //TODO Dynamically scope the _return variable for Milestone 3 public override void Execute(RenPyState state) { //Evaluate the optional expression and store in _return if(m_optionalExpressionUsed) state.SetVariable ("_return", m_expression.Evaluate (state).ToString()); state.Execution.PopStackFrame(); } public override string ToDebugString() { string str = "return " + m_expressionString; return str; } } }
bsd-3-clause
C#
18c97036945398421a9a94905e80eab607add7d9
Fix APFT list sort by score
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Views/APFT/List.cshtml
Battery-Commander.Web/Views/APFT/List.cshtml
@model IEnumerable<APFT> <div class="page-header"> <h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1> </div> <table class="table table-striped" id="dt"> <thead> <tr> <th>Soldier</th> <th>Date</th> <th>Score</th> <th>Result</th> <th>Details</th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td> <a href="@Url.Action("Index", new { date = model.Date })"> @Html.DisplayFor(_ => model.Date) </a> </td> <td data-sort="@model.TotalScore"> @Html.DisplayFor(_ => model.TotalScore) @if(model.IsAlternateAerobicEvent) { <span class="label">Alt. Aerobic</span> } </td> <td> @if (model.IsPassing) { <span class="label label-success">Passing</span> } else { <span class="label label-danger">Failure</span> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>
@model IEnumerable<APFT> <div class="page-header"> <h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1> </div> <table class="table table-striped" id="dt"> <thead> <tr> <th>Soldier</th> <th>Date</th> <th>Score</th> <th>Result</th> <th>Details</th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td> <a href="@Url.Action("Index", new { date = model.Date })"> @Html.DisplayFor(_ => model.Date) </a> </td> <td> @Html.DisplayFor(_ => model.TotalScore) @if(model.IsAlternateAerobicEvent) { <span class="label">Alt. Aerobic</span> } </td> <td> @if (model.IsPassing) { <span class="label label-success">Passing</span> } else { <span class="label label-danger">Failure</span> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>
mit
C#
751449731972b2cc928ba11d3dccd51f2698411f
Update Program.cs
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
samples/BehaviorsTestApplication.Desktop/Program.cs
samples/BehaviorsTestApplication.Desktop/Program.cs
using System; using Avalonia; using Avalonia.ReactiveUI; using Avalonia.Xaml.Interactions.Core; using Avalonia.Xaml.Interactivity; namespace BehaviorsTestApplication; class Program { [STAThread] private static void Main(string[] args) { BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); } public static AppBuilder BuildAvaloniaApp() { GC.KeepAlive(typeof(Interaction).Assembly); GC.KeepAlive(typeof(ComparisonConditionType).Assembly); return AppBuilder.Configure<App>() .UsePlatformDetect() .With(new Win32PlatformOptions { UseCompositor = true }) .With(new X11PlatformOptions { UseCompositor = true }) .With(new AvaloniaNativePlatformOptions { UseCompositor = true }) .UseReactiveUI() .LogToTrace(); } }
using System; using Avalonia; using Avalonia.ReactiveUI; using Avalonia.Xaml.Interactions.Core; using Avalonia.Xaml.Interactivity; namespace BehaviorsTestApplication; class Program { [STAThread] private static void Main(string[] args) { BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); } public static AppBuilder BuildAvaloniaApp() { GC.KeepAlive(typeof(Interaction).Assembly); GC.KeepAlive(typeof(ComparisonConditionType).Assembly); return AppBuilder.Configure<App>() .UsePlatformDetect() .UseReactiveUI() .LogToTrace(); } }
mit
C#
f71eb66e583e978fe9f68bf68f3399b07ff8718a
Create TermsJosnViewModel
lucasdavid/Gamedalf,lucasdavid/Gamedalf
Gamedalf/ViewModels/TermsViewModels.cs
Gamedalf/ViewModels/TermsViewModels.cs
using Gamedalf.Core.Attributes; using System; using System.ComponentModel.DataAnnotations; namespace Gamedalf.ViewModels { public class TermsCreateViewModel { [Required] [StringLength(100, MinimumLength = 1)] public string Title { get; set; } [Required] public string Content { get; set; } } public class TermsEditViewModel { public int Id { get; set; } public string Title { get; set; } [Required] public string Content { get; set; } } public class AcceptTermsViewModel { [EnforceTrue] [Display(Name = "I hereby accept the presented terms")] public bool AcceptTerms { get; set; } } public class TermsJsonViewModel { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public DateTime DateCreated { get; set; } } }
using Gamedalf.Core.Attributes; using System.ComponentModel.DataAnnotations; namespace Gamedalf.ViewModels { public class TermsCreateViewModel { [Required] [StringLength(100, MinimumLength = 1)] public string Title { get; set; } [Required] public string Content { get; set; } } public class TermsEditViewModel { public int Id { get; set; } public string Title { get; set; } [Required] public string Content { get; set; } } public class AcceptTermsViewModel { [EnforceTrue] [Display(Name = "I hereby accept the presented terms")] public bool AcceptTerms { get; set; } } }
mit
C#
20e9bcdc9669a18c9285a41ec6b9c5d96f19e44e
Implement General AnimationEvent
umm-projects/animationevent_dispatcher
Assets/Scripts/UnityModule/AnimationEventDispatcher/GeneralDispatcher.cs
Assets/Scripts/UnityModule/AnimationEventDispatcher/GeneralDispatcher.cs
using UniRx; using UnityEngine; namespace UnityModule.AnimationEventDispatcher { /// <summary> /// 汎用ディスパッチャ /// </summary> public class GeneralDispatcher : Base { /// <summary> /// 汎用イベント名: アニメーション開始 /// </summary> private const string ANIMATION_EVENT_NAME_BEGIN_ANIMATION = "BeginAnimation"; /// <summary> /// 汎用イベント名: アニメーション終了 /// </summary> private const string ANIMATION_EVENT_NAME_END_ANIMATION = "EndAnimation"; /// <summary> /// AnimationEvent を Dispatch する /// </summary> /// <param name="animationEvent">Inspector で設定する情報を含んだ AnimationEvent</param> public void Dispatch(AnimationEvent animationEvent) { this.StreamAnimationEvent.OnNext(animationEvent); } /// <summary> /// アニメーション開始を表す AnimationEvent を Dispatch する /// </summary> public void DispatchBeginAnimation() { this.StreamAnimationEvent.OnNext(new AnimationEvent() { stringParameter = ANIMATION_EVENT_NAME_BEGIN_ANIMATION}); } /// <summary> /// アニメーション終了を表す AnimationEvent を Dispatch する /// </summary> public void DispatchEndAnimation() { this.StreamAnimationEvent.OnNext(new AnimationEvent() { stringParameter = ANIMATION_EVENT_NAME_END_ANIMATION}); } /// <summary> /// Dispatch されたアニメーション開始を表す AnimationEvent を UniRx ストリームとして返す /// </summary> /// <returns>AnimationEvent のストリーム</returns> public IObservable<AnimationEvent> OnDispatchBeginAnimation() { return this.OnDispatchAsObservable(ANIMATION_EVENT_NAME_BEGIN_ANIMATION); } /// <summary> /// Dispatch されたアニメーション終了を表す AnimationEvent を UniRx ストリームとして返す /// </summary> /// <returns>AnimationEvent のストリーム</returns> public IObservable<AnimationEvent> OnDispatchEndAnimation() { return this.OnDispatchAsObservable(ANIMATION_EVENT_NAME_BEGIN_ANIMATION); } } }
using UnityEngine; namespace UnityModule.AnimationEventDispatcher { /// <summary> /// 汎用ディスパッチャ /// </summary> public class GeneralDispatcher : Base { /// <summary> /// AnimationEvent を Dispatch する /// </summary> /// <param name="animationEvent">Inspector で設定する情報を含んだ AnimationEvent</param> public void Dispatch(AnimationEvent animationEvent) { this.StreamAnimationEvent.OnNext(animationEvent); } } }
mit
C#
32f5639265d45346b36f8a9c58b66c4bc8ef6305
remove failing, invalid tests
j2ghz/IntranetGJAK,j2ghz/IntranetGJAK
UnitTests/Class1.cs
UnitTests/Class1.cs
using IntranetGJAK.Controllers; using Xunit; namespace UnitTests { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". public class Home { [Fact] public void ControllerNotNull() { } } public class UploadController { [Fact] public void ControllerNotNull() { } } }
using IntranetGJAK.Controllers; using Xunit; namespace UnitTests { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". public class Home { [Fact] public void ControllerNotNull() { Assert.NotNull((new HomeController()).Index()); } } public class UploadController { [Fact] public void ControllerNotNull() { Assert.NotNull((new Files(null)).List()); //moq } } }
agpl-3.0
C#
056de509b6f796a1c4cb6639416ee119b4fa883f
fix main activity title
SabotageAndi/ELMAR
net.the-engineers.elmar/elmar.droid/MainActivity.cs
net.the-engineers.elmar/elmar.droid/MainActivity.cs
using System; using Android.App; using Android.Content; using Android.Widget; using Android.OS; using elmar.droid.Common; using elmar.droid.Voice; using TinyIoC; namespace elmar.droid { [Activity(Label = "E.L.M.A.R.", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { private ImageButton _startVoiceButton; private ImageButton _preferenceButton; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); ActionBar.Hide(); var serviceIntent = new Intent(this, typeof(MediaButtonService)); StartService(serviceIntent); var ttsChecker = Container.Resolve<TTSChecker>(); ttsChecker.SetActivity(this); ttsChecker.checkTTS(); _startVoiceButton = FindViewById<ImageButton>(Resource.Id.startVoice); _preferenceButton = FindViewById<ImageButton>(Resource.Id.preferences); _startVoiceButton.Click += StartVoiceButtonOnClick; _preferenceButton.Click += StartPreferenceActivity; } private void StartPreferenceActivity(object sender, EventArgs e) { var intent = new Intent(this, typeof(SettingsActivity)); StartActivity(intent); } private void StartVoiceButtonOnClick(object sender, EventArgs eventArgs) { var voiceRecognizer = new VoiceRecognizer(this); voiceRecognizer.StartVoiceRecognition(); } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { var ttsChecker = Container.Resolve<TTSChecker>(); ttsChecker.onResult(requestCode, resultCode, data); } } }
using System; using Android.App; using Android.Content; using Android.Widget; using Android.OS; using elmar.droid.Common; using elmar.droid.Voice; using TinyIoC; namespace elmar.droid { [Activity(Label = "elmar.droid", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { private ImageButton _startVoiceButton; private ImageButton _preferenceButton; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); ActionBar.Hide(); var serviceIntent = new Intent(this, typeof(MediaButtonService)); StartService(serviceIntent); var ttsChecker = Container.Resolve<TTSChecker>(); ttsChecker.SetActivity(this); ttsChecker.checkTTS(); _startVoiceButton = FindViewById<ImageButton>(Resource.Id.startVoice); _preferenceButton = FindViewById<ImageButton>(Resource.Id.preferences); _startVoiceButton.Click += StartVoiceButtonOnClick; _preferenceButton.Click += StartPreferenceActivity; } private void StartPreferenceActivity(object sender, EventArgs e) { var intent = new Intent(this, typeof(SettingsActivity)); StartActivity(intent); } private void StartVoiceButtonOnClick(object sender, EventArgs eventArgs) { var voiceRecognizer = new VoiceRecognizer(this); voiceRecognizer.StartVoiceRecognition(); } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { var ttsChecker = Container.Resolve<TTSChecker>(); ttsChecker.onResult(requestCode, resultCode, data); } } }
agpl-3.0
C#
42ac0c72eac12ea39415f9bc9926adcc5a1a6ff6
Fix grammer issue and more rewording
NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipooo/osu,peppy/osu-new,ppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu
osu.Game.Rulesets.Catch/Skinning/CatchSkinColour.cs
osu.Game.Rulesets.Catch/Skinning/CatchSkinColour.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Catch.Skinning { public enum CatchSkinColour { /// <summary> /// The colour to be used for the catcher while in hyper-dashing state. /// </summary> HyperDash, /// <summary> /// The colour to be used for fruits that grant the catcher the ability to hyper-dash. /// </summary> HyperDashFruit, /// <summary> /// The colour to be used for the "exploding" catcher sprite on beginning of hyper-dashing. /// </summary> HyperDashAfterImage, } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Catch.Skinning { public enum CatchSkinColour { /// <summary> /// The colour to be used for the catcher while on hyper-dashing state. /// </summary> HyperDash, /// <summary> /// The colour to be used for hyper-dash fruits. /// </summary> HyperDashFruit, /// <summary> /// The colour to be used for the "exploding" catcher sprite on beginning of hyper-dashing. /// </summary> HyperDashAfterImage, } }
mit
C#
da996ffe748d2d30821284f1ccf48ad0fa0d193d
Update header breadcrumb tab control
EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,peppy/osu,peppy/osu
osu.Game/Overlays/BreadcrumbControlOverlayHeader.cs
osu.Game/Overlays/BreadcrumbControlOverlayHeader.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays { public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string> { protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl(); public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; Height = 47; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { AccentColour = colourProvider.Light2; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { RelativeSizeAxes = Axes.Y; Text.Font = Text.Font.With(size: 14); Text.Anchor = Anchor.CentreLeft; Text.Origin = Anchor.CentreLeft; Chevron.Y = 1; Bar.Height = 0; } // base OsuTabItem makes font bold on activation, we don't want that here protected override void OnActivated() => FadeHovered(); protected override void OnDeactivated() => FadeUnhovered(); } } } }
// 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.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays { public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string> { protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl(); public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { Text.Font = Text.Font.With(size: 14); Chevron.Y = 3; Bar.Height = 0; } } } } }
mit
C#
242069ef77eb1a669da75038e521706b015dd409
fix branch create and delete by name test
maikebing/NGitLab,Xarlot/NGitLab
NGitLab/NGitLab/Models/BranchCreate.cs
NGitLab/NGitLab/Models/BranchCreate.cs
using System.Runtime.Serialization; namespace NGitLab.Models { [DataContract] public class BranchCreate { [DataMember(Name = "branch")] public string Name { get; set; } [DataMember(Name = "ref")] public string Ref { get; set; } } }
using System.Runtime.Serialization; namespace NGitLab.Models { [DataContract] public class BranchCreate { [DataMember(Name = "branch_name")] public string Name { get; set; } [DataMember(Name = "ref")] public string Ref { get; set; } } }
mit
C#
df1befdc0a8441580312f4a67c875c1e1330265a
Fix UpdatedAt typo in MergeRequest model (#32)
maikebing/NGitLab,Xarlot/NGitLab
NGitLab/NGitLab/Models/MergeRequest.cs
NGitLab/NGitLab/Models/MergeRequest.cs
using System; using System.Runtime.Serialization; namespace NGitLab.Models { [DataContract] public class MergeRequest { public const string Url = "/merge_requests"; [DataMember(Name = "id")] public int Id; [DataMember(Name = "iid")] public int Iid; [DataMember(Name = "state")] public string State; [DataMember(Name = "title")] public string Title; [DataMember(Name = "assignee")] public User Assignee; [DataMember(Name = "author")] public User Author; [DataMember(Name = "created_at")] public DateTime CreatedAt; [DataMember(Name = "description")] public string Description; [DataMember(Name = "downvotes")] public int Downvotes; [DataMember(Name = "upvotes")] public int Upvotes; [DataMember(Name = "updated_at")] public DateTime UpdatedAt; [DataMember(Name="target_branch")] public string TargetBranch; [DataMember(Name="source_branch")] public string SourceBranch; [DataMember(Name="project_id")] public int ProjectId; [DataMember(Name="source_project_id")] public int SourceProjectId; [DataMember(Name = "target_project_id")] public int TargetProjectId; } }
using System; using System.Runtime.Serialization; namespace NGitLab.Models { [DataContract] public class MergeRequest { public const string Url = "/merge_requests"; [DataMember(Name = "id")] public int Id; [DataMember(Name = "iid")] public int Iid; [DataMember(Name = "state")] public string State; [DataMember(Name = "title")] public string Title; [DataMember(Name = "assignee")] public User Assignee; [DataMember(Name = "author")] public User Author; [DataMember(Name = "created_at")] public DateTime CreatedAt; [DataMember(Name = "description")] public string Description; [DataMember(Name = "downvotes")] public int Downvotes; [DataMember(Name = "upvotes")] public int Upvotes; [DataMember(Name = "updated_at")] public DateTime UpvotedAt; [DataMember(Name="target_branch")] public string TargetBranch; [DataMember(Name="source_branch")] public string SourceBranch; [DataMember(Name="project_id")] public int ProjectId; [DataMember(Name="source_project_id")] public int SourceProjectId; [DataMember(Name = "target_project_id")] public int TargetProjectId; } }
mit
C#
ebb58caa0fe96d21761585091c765bb97ff0b847
add locker to .net40 thing
cartermp/dnx-apps
libs/lib/src/Lib/Lib.cs
libs/lib/src/Lib/Lib.cs
using System; #if NET40 using System.Net; #else using System.Net.Http; using System.Threading.Tasks; #endif using System.Text.RegularExpressions; namespace Lib { public class Library { #if NET40 private readonly WebClient _client = new WebClient(); private readonly object _locker = new object(); #else private readonly HttpClient _client = new HttpClient(); #endif #if NET40 public string GetDotNetCount() { string url = "http://www.dotnetfoundation.org/"; var uri = new Uri(url); lock(_locker) { var result = _client.DownloadString(uri); } int dotNetCount = Regex.Matches(result, ".NET").Count; return $"Dotnet Foundation mentions .NET {dotNetCount} times!"; } #else public async Task<string> GetDotNetCountAsync() { string url = "http://www.dotnetfoundation.org/"; var result = await _client.GetStringAsync(url); int dotNetCount = Regex.Matches(result, ".NET").Count; return $"dotnetfoundation.orgmentions .NET {dotNetCount} times in its HTML!"; } #endif } }
using System; #if NET40 using System.Net; #else using System.Net.Http; using System.Threading.Tasks; #endif using System.Text.RegularExpressions; namespace Lib { public class Library { #if NET40 private readonly WebClient _client = new WebClient(); #else private readonly HttpClient _client = new HttpClient(); #endif #if NET40 public string GetDotNetCount() { string url = "http://www.dotnetfoundation.org/"; var uri = new Uri(url); var result = _client.DownloadString(uri); int dotNetCount = Regex.Matches(result, ".NET").Count; return $"Dotnet Foundation mentions .NET {dotNetCount} times!"; } #else public async Task<string> GetDotNetCountAsync() { string url = "http://www.dotnetfoundation.org/"; var result = await _client.GetStringAsync(url); int dotNetCount = Regex.Matches(result, ".NET").Count; return $"dotnetfoundation.orgmentions .NET {dotNetCount} times in its HTML!"; } #endif } }
mit
C#
e9c93b2ed5ba2cf03778baa4ced05389df8adf25
Add null check to RemoteCollection
gep13/GitVersion,gep13/GitVersion,GitTools/GitVersion,asbjornu/GitVersion,asbjornu/GitVersion,GitTools/GitVersion
src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs
src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs
using GitVersion.Extensions; namespace GitVersion; internal sealed class RemoteCollection : IRemoteCollection { private readonly LibGit2Sharp.RemoteCollection innerCollection; internal RemoteCollection(LibGit2Sharp.RemoteCollection collection) => this.innerCollection = collection.NotNull(); public IEnumerator<IRemote> GetEnumerator() => this.innerCollection.Select(reference => new Remote(reference)).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IRemote? this[string name] { get { var remote = this.innerCollection[name]; return remote is null ? null : new Remote(remote); } } public void Remove(string remoteName) => this.innerCollection.Remove(remoteName); public void Update(string remoteName, string refSpec) => this.innerCollection.Update(remoteName, r => r.FetchRefSpecs.Add(refSpec)); }
namespace GitVersion; internal sealed class RemoteCollection : IRemoteCollection { private readonly LibGit2Sharp.RemoteCollection innerCollection; internal RemoteCollection(LibGit2Sharp.RemoteCollection collection) => this.innerCollection = collection; public IEnumerator<IRemote> GetEnumerator() => this.innerCollection.Select(reference => new Remote(reference)).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IRemote? this[string name] { get { var remote = this.innerCollection[name]; return remote is null ? null : new Remote(remote); } } public void Remove(string remoteName) => this.innerCollection.Remove(remoteName); public void Update(string remoteName, string refSpec) => this.innerCollection.Update(remoteName, r => r.FetchRefSpecs.Add(refSpec)); }
mit
C#
5a33775c5edc685b615cda2fd6e466605262e113
Fix NuGet name typo
ctaggart/nuget,antiufo/NuGet2,akrisiun/NuGet,oliver-feng/nuget,GearedToWar/NuGet2,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey,anurse/NuGet,alluran/node.net,alluran/node.net,mrward/nuget,themotleyfool/NuGet,pratikkagda/nuget,mrward/NuGet.V2,GearedToWar/NuGet2,chester89/nugetApi,pratikkagda/nuget,kumavis/NuGet,indsoft/NuGet2,anurse/NuGet,mrward/nuget,mrward/NuGet.V2,indsoft/NuGet2,pratikkagda/nuget,oliver-feng/nuget,jholovacs/NuGet,chocolatey/nuget-chocolatey,dolkensp/node.net,dolkensp/node.net,oliver-feng/nuget,OneGet/nuget,RichiCoder1/nuget-chocolatey,akrisiun/NuGet,atheken/nuget,mono/nuget,GearedToWar/NuGet2,chocolatey/nuget-chocolatey,antiufo/NuGet2,xoofx/NuGet,RichiCoder1/nuget-chocolatey,mono/nuget,jmezach/NuGet2,OneGet/nuget,jholovacs/NuGet,chocolatey/nuget-chocolatey,mrward/nuget,chocolatey/nuget-chocolatey,zskullz/nuget,atheken/nuget,jmezach/NuGet2,xoofx/NuGet,chocolatey/nuget-chocolatey,antiufo/NuGet2,rikoe/nuget,mrward/NuGet.V2,mrward/NuGet.V2,xero-github/Nuget,kumavis/NuGet,jholovacs/NuGet,jmezach/NuGet2,mrward/NuGet.V2,jmezach/NuGet2,jholovacs/NuGet,zskullz/nuget,rikoe/nuget,xoofx/NuGet,jmezach/NuGet2,GearedToWar/NuGet2,ctaggart/nuget,oliver-feng/nuget,jholovacs/NuGet,mono/nuget,oliver-feng/nuget,themotleyfool/NuGet,pratikkagda/nuget,pratikkagda/nuget,zskullz/nuget,mono/nuget,mrward/nuget,indsoft/NuGet2,mrward/NuGet.V2,zskullz/nuget,mrward/nuget,oliver-feng/nuget,ctaggart/nuget,pratikkagda/nuget,chocolatey/nuget-chocolatey,RichiCoder1/nuget-chocolatey,alluran/node.net,ctaggart/nuget,xoofx/NuGet,GearedToWar/NuGet2,jmezach/NuGet2,GearedToWar/NuGet2,jholovacs/NuGet,antiufo/NuGet2,indsoft/NuGet2,themotleyfool/NuGet,antiufo/NuGet2,xoofx/NuGet,antiufo/NuGet2,xoofx/NuGet,OneGet/nuget,rikoe/nuget,OneGet/nuget,RichiCoder1/nuget-chocolatey,dolkensp/node.net,mrward/nuget,rikoe/nuget,indsoft/NuGet2,indsoft/NuGet2,alluran/node.net,chester89/nugetApi,dolkensp/node.net
src/VisualStudio.Interop/Properties/AssemblyInfo.cs
src/VisualStudio.Interop/Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("NuGet.VisualStudio.Interop")] [assembly: AssemblyDescription("NuGet/Visual Studio interop assembly")] // The version of this assembly should never be changed. [assembly: AssemblyVersion("1.0.0.0")]
using System.Reflection; [assembly: AssemblyTitle("NuGet.VisualStudio.Interop")] [assembly: AssemblyDescription("Nuget/Visual Studio interop assembly")] // The version of this assembly should never be changed. [assembly: AssemblyVersion("1.0.0.0")]
apache-2.0
C#
5256e307dac183e913d511a5d208db45be39bdc6
Update HeightCalculatorFromBones.cs
cwesnow/Net_Fiddle
2017oct/HeightCalculatorFromBones.cs
2017oct/HeightCalculatorFromBones.cs
// Original Source Information // Author: GitGub on Reddit // Link: https://www.reddit.com/r/learnprogramming/comments/77a49n/c_help_refactoring_an_ugly_method_with_lots_of_if/ // Refactored using .NET Fiddle - https://dotnetfiddle.net/YiG9XQ using System; public class Program { static Random random = new Random(); enum Bones { Femur, Tibia, Humerus, Radius } enum Gender { Male, Female } public static void Main() { for(int x = 0; x < 5; x++) { // Get Randome Values float length = randomLength(); Bones bone = randomBone(); Gender gender = randomGender(); int age = randomAge(); // Result Console.WriteLine("\nGender: {0}\nAge: {1}\nBone: {2}\nLength: {3}\nHeight: {4}", gender, age, bone, length, calculateHeight(bone, length, gender, age)); } } private static float calculateHeight(Bones bone, float boneLength, Gender gender, int age) { float height = 0; float A = age * 0.06f; switch(bone) { case Bones.Femur: height = (gender == Gender.Male) ? 69.089f + (2.238f * boneLength) - A : // Male 61.412f + (2.317f * boneLength) - A; // Female break; case Bones.Tibia: height = (gender == Gender.Male) ? 81.688f + (2.392f * boneLength) - A : // Male 72.572f + (2.533f * boneLength) - A; // Female break; case Bones.Humerus: height = (gender == Gender.Male) ? 73.570f + (2.970f * boneLength) - A : // Male 64.977f + (3.144f * boneLength) - A; // Female break; case Bones.Radius: height = (gender == Gender.Male) ? 80.405f + (3.650f * boneLength) - A : // Male 73.502f + (3.876f * boneLength) - A; // Female break; default: break; } return height; } private static float randomLength() { return (float)random.NextDouble()*3; } private static Bones randomBone() { return (Bones)random.Next(0,3); } private static Gender randomGender() { return (Gender)random.Next(0,2); } // 0,2 works better than 1,2 or 0,1. Unknown reasons private static int randomAge() { return random.Next(16, 99); } }
// Original Source Information // Author: GitGub on Reddit // Link: https://www.reddit.com/r/learnprogramming/comments/77a49n/c_help_refactoring_an_ugly_method_with_lots_of_if/ // Refactored using .NET Fiddle - https://dotnetfiddle.net/F8UcJW using System; public class Program { static Random random = new Random(); enum Bones { Femur, Tibia, Humerus, Radius } enum Gender { Male, Female} public static void Main() { for(int x = 0; x < 5; x++) { // Get Randome Values float length = randomLength(); Bones bone = randomBone(); Gender gender = randomGender(); int age = randomAge(); // Result Console.WriteLine("\nGender: {0}\nAge: {1}\nBone: {2}\nLength: {3}\nHeight: {4}", gender, age, bone, length, calculateHeight(bone, length, gender, age)); } } private static float calculateHeight(Bones bone, float boneLength, Gender gender, int age) { float height = 0; switch(bone) { case Bones.Femur: height = (gender == Gender.Male) ? 69.089f + (2.238f * boneLength) - age * 0.06f : 61.412f + (2.317f * boneLength) - age * 0.06f; break; case Bones.Tibia: height = (gender == Gender.Male) ? 81.688f + (2.392f * boneLength) - age * 0.06f : 72.572f + (2.533f * boneLength) - age * 0.06f; break; case Bones.Humerus: height = (gender == Gender.Male) ? 73.570f + (2.970f * boneLength) - age * 0.06f : 64.977f + (3.144f * boneLength) - age * 0.06f; break; case Bones.Radius: height = (gender == Gender.Male) ? 80.405f + (3.650f * boneLength) - age * 0.06f : 73.502f + (3.876f * boneLength) - age * 0.06f; break; default: break; } return height; } private static float randomLength() { return (float)random.NextDouble()*3; } private static Bones randomBone() { return (Bones)random.Next(1,4); } private static Gender randomGender() { return (Gender)random.Next(0,2); } // 1,2 & 0,1 always gave the same gender private static int randomAge() { return random.Next(16, 99); } }
mit
C#
ed93c410e9e325c0c022f97c7b9f6f2b1cfcff96
Simplify Text.Advance's ability to protect against advancing beyond the end of the span.
plioi/parsley
src/Parsley/Text.cs
src/Parsley/Text.cs
namespace Parsley; public ref struct Text { ReadOnlySpan<char> input; public Text(ReadOnlySpan<char> input) => this.input = input; public readonly ReadOnlySpan<char> Peek(int characters) => characters >= input.Length ? input.Slice(0) : input.Slice(0, characters); public (int lineDelta, int columnDelta) Advance(Position start, int characters) { if (characters == 0) return (0, 0); int lineDelta = 0; int columnDelta = 0; var peek = Peek(characters); foreach (var ch in peek) { if (ch == '\n') { lineDelta++; columnDelta = 0 - start.Column; } columnDelta++; } input = input.Slice(peek.Length); return (lineDelta, columnDelta); } public readonly bool EndOfInput => input.Length == 0; public readonly ReadOnlySpan<char> TakeWhile(Predicate<char> test) { int i = 0; while (i < input.Length && test(input[i])) i++; return Peek(i); } public readonly override string ToString() => input.ToString(); }
namespace Parsley; public ref struct Text { ReadOnlySpan<char> input; public Text(ReadOnlySpan<char> input) => this.input = input; public readonly ReadOnlySpan<char> Peek(int characters) => characters >= input.Length ? input.Slice(0) : input.Slice(0, characters); public (int lineDelta, int columnDelta) Advance(Position start, int characters) { if (characters == 0) return (0, 0); int lineDelta = 0; int columnDelta = 0; foreach (var ch in Peek(characters)) { if (ch == '\n') { lineDelta++; columnDelta = 0 - start.Column; } columnDelta++; } input = characters < input.Length ? input.Slice(characters) : ReadOnlySpan<char>.Empty; return (lineDelta, columnDelta); } public readonly bool EndOfInput => input.Length == 0; public readonly ReadOnlySpan<char> TakeWhile(Predicate<char> test) { int i = 0; while (i < input.Length && test(input[i])) i++; return Peek(i); } public readonly override string ToString() => input.ToString(); }
mit
C#
b0dcaeae528065cb3c93d1b646ffb11779e7c4a1
Update Helpers.cs
scottolsonjr/scriptlink-core
Helpers.cs
Helpers.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NTST.ScriptLinkService.Objects; namespace ScriptLinkCore { public partial class ScriptLink { /// <summary> /// Used set required fields /// </summary> /// <param name="optionObject"></param> /// <param name="fieldNumber"></param> /// <returns></returns> public static OptionObject SetRequiredField(OptionObject optionObject, string fieldNumber) { OptionObject returnOptionObject = optionObject; Boolean updated = false; foreach (var form in returnOptionObject.Forms) { foreach (var currentField in form.CurrentRow.Fields) { if (currentField.FieldNumber == fieldNumber) { currentField.Required = "1"; updated = true; } } } if (updated == true) { foreach (var form in returnOptionObject.Forms) { form.CurrentRow.RowAction = "EDIT"; } return returnOptionObject; } else { return optionObject; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NTST.ScriptLinkService.Objects; namespace ScriptLinkCore { public partial class ScriptLink { /// <summary> /// Used set required fields /// </summary> /// <param name="optionObject"></param> /// <param name="field1"></param> /// <returns></returns> public static OptionObject SetRequiredFields(OptionObject optionObject, string field1) { OptionObject returnOptionObject = optionObject; Boolean updated = false; foreach (var form in returnOptionObject.Forms) { foreach (var currentField in form.CurrentRow.Fields) { if (currentField.FieldNumber == field1) { currentField.Required = "1"; updated = true; } } } if (updated == true) { foreach (var form in returnOptionObject.Forms) { form.CurrentRow.RowAction = "EDIT"; } return returnOptionObject; } else { return optionObject; } } } }
mit
C#
a48cf542e0cf0a8917cf99122b62f6ed043dceea
Fix exception
Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife
PhotoLife/PhotoLife.Services/UserService.cs
PhotoLife/PhotoLife.Services/UserService.cs
using System; using System.Linq; using PhotoLife.Data.Contracts; using PhotoLife.Models; using PhotoLife.Services.Contracts; namespace PhotoLife.Services { public class UserService : IUserService { private readonly IRepository<User> userRepository; private readonly IUnitOfWork unitOfWork; public UserService( IRepository<User> userRepository, IUnitOfWork unitOfWork) { if (userRepository == null) { throw new ArgumentNullException(nameof(userRepository)); } if (unitOfWork == null) { throw new ArgumentNullException(nameof(unitOfWork)); } this.userRepository = userRepository; this.unitOfWork = unitOfWork; } public User GetUserById(string id) { return this.userRepository.GetById(id); } public User GetUserByUsername(string username) { return this.userRepository .GetAll(u => u.UserName.Equals(username)) .FirstOrDefault(); } public void EditUser(string id, string username, string name, string description, string profilePicUrl) { var user = this.userRepository.GetById(id); if (user != null) { user.UserName = username; user.Name = name; user.Description = description; user.ProfilePicUrl = profilePicUrl; this.userRepository.Update(user); this.unitOfWork.Commit(); } } } }
using System; using System.Linq; using PhotoLife.Data.Contracts; using PhotoLife.Models; using PhotoLife.Services.Contracts; namespace PhotoLife.Services { public class UserService : IUserService { private readonly IRepository<User> userRepository; private readonly IUnitOfWork unitOfWork; public UserService( IRepository<User> userRepository, IUnitOfWork unitOfWork) { if (userRepository == null) { throw new ArgumentNullException(nameof(userRepository)); } if (unitOfWork == null) { throw new ArgumentNullException(nameof(userRepository)); } this.userRepository = userRepository; this.unitOfWork = unitOfWork; } public User GetUserById(string id) { return this.userRepository.GetById(id); } public User GetUserByUsername(string username) { return this.userRepository .GetAll(u => u.UserName.Equals(username)) .FirstOrDefault(); } public void EditUser(string id, string username, string name, string description, string profilePicUrl) { var user = this.userRepository.GetById(id); if (user != null) { user.UserName = username; user.Name = name; user.Description = description; user.ProfilePicUrl = profilePicUrl; this.userRepository.Update(user); this.unitOfWork.Commit(); } } } }
mit
C#
75a0e8213b7e679732ff3188cb2dc0f1b4e4f540
Add PublishRequestAsync method with ContextConfigurator overload
lahma/MassTransit,abombss/MassTransit,jsmale/MassTransit,lahma/MassTransit,petedavis/MassTransit,vebin/MassTransit,vebin/MassTransit,abombss/MassTransit,ccellar/MassTransit,ccellar/MassTransit,lahma/MassTransit,D3-LucaPiombino/MassTransit,lahma/MassTransit,petedavis/MassTransit,ccellar/MassTransit,lahma/MassTransit,abombss/MassTransit,ccellar/MassTransit
src/MassTransit/TaskExtensions.cs
src/MassTransit/TaskExtensions.cs
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit { using System; using RequestResponse.Configurators; #if NET40 public static class TaskExtensions { public static ITaskRequest<TRequest> PublishRequestAsync<TRequest>(this IServiceBus bus, TRequest message, Action<TaskRequestConfigurator<TRequest>> configureCallback) where TRequest : class { var configurator = new TaskRequestConfiguratorImpl<TRequest>(message); configureCallback(configurator); ITaskRequest<TRequest> request = configurator.Create(bus); bus.Publish(message, context => configurator.ApplyContext(context, bus.Endpoint.Address.Uri)); return request; } public static ITaskRequest<TRequest> PublishRequestAsync<TRequest>(this IServiceBus bus, TRequest message, Action<TaskRequestConfigurator<TRequest>> configureCallback, Action<IPublishContext<TRequest>> contextConfigurator) where TRequest : class { var configurator = new TaskRequestConfiguratorImpl<TRequest>(message); configureCallback(configurator); ITaskRequest<TRequest> request = configurator.Create(bus); bus.Publish(message, context => { configurator.ApplyContext(context, bus.Endpoint.Address.Uri); contextConfigurator(context); }); return request; } public static ITaskRequest<TRequest> SendRequestAsync<TRequest>(this IEndpoint endpoint, IServiceBus bus, TRequest message, Action<TaskRequestConfigurator<TRequest>> configureCallback) where TRequest : class { var configurator = new TaskRequestConfiguratorImpl<TRequest>(message); configureCallback(configurator); ITaskRequest<TRequest> request = configurator.Create(bus); endpoint.Send(message, context => configurator.ApplyContext(context, bus.Endpoint.Address.Uri)); return request; } } #endif }
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit { using System; using RequestResponse.Configurators; #if NET40 public static class TaskExtensions { public static ITaskRequest<TRequest> PublishRequestAsync<TRequest>(this IServiceBus bus, TRequest message, Action<TaskRequestConfigurator<TRequest>> configureCallback) where TRequest : class { var configurator = new TaskRequestConfiguratorImpl<TRequest>(message); configureCallback(configurator); ITaskRequest<TRequest> request = configurator.Create(bus); bus.Publish(message, context => configurator.ApplyContext(context, bus.Endpoint.Address.Uri)); return request; } public static ITaskRequest<TRequest> SendRequestAsync<TRequest>(this IEndpoint endpoint, IServiceBus bus, TRequest message, Action<TaskRequestConfigurator<TRequest>> configureCallback) where TRequest : class { var configurator = new TaskRequestConfiguratorImpl<TRequest>(message); configureCallback(configurator); ITaskRequest<TRequest> request = configurator.Create(bus); endpoint.Send(message, context => configurator.ApplyContext(context, bus.Endpoint.Address.Uri)); return request; } } #endif }
apache-2.0
C#
7e6b0dec2301259441732acb26a17c6d0d9cb6ce
remove test for absent ctor
icarus-consulting/Yaapii.Atoms
tests/Yaapii.Atoms.Tests/Enumerable/StringsTests.cs
tests/Yaapii.Atoms.Tests/Enumerable/StringsTests.cs
// MIT License // // Copyright(c) 2019 ICARUS Consulting GmbH // // 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.Collections.Generic; using Xunit; namespace Yaapii.Atoms.Enumerable { public sealed class StringsTests { [Fact] public void Enumerates() { Assert.Equal( new List<string>() { "one", "two", "eight" }, new Strings("one", "two", "eight") ); } } }
// MIT License // // Copyright(c) 2019 ICARUS Consulting GmbH // // 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.Collections.Generic; using Xunit; namespace Yaapii.Atoms.Enumerable { public sealed class StringsTests { [Fact] public void Enumerates() { Assert.Equal( new List<string>() { "one", "two", "eight" }, new Strings("one", "two", "eight") ); } [Fact] public void Converts() { var number = 2.3f; var enumerator = new Strings(number).GetEnumerator(); enumerator.MoveNext(); Assert.Equal( number.ToString(), enumerator.Current ); } } }
mit
C#
b651915ecc45ce395f46a39cfdd43472e4243e54
correct doc remark
dgg/nmoneys,dgg/nmoneys
src/NMoneys/RemainderAllocator.cs
src/NMoneys/RemainderAllocator.cs
using NMoneys.Allocations; namespace NMoneys { /// <summary> /// Factory class for provided implementations of <see cref="IRemainderAllocator"/> /// </summary> public static class RemainderAllocator { /// <summary> /// Allocate the remainder to the first known recipient and keep going in order towards /// the last recipient until the remainder has been fully allocated. /// </summary> /// <remarks> /// In the case of a dollar split three ways the extra penny to the first receipient /// and the allocation is done. /// </remarks> public static readonly IRemainderAllocator FirstToLast = new FirstToLastAllocator(); /// <summary> /// Allocate the remainder to the last known recipient and keep going in order towards /// the first recipient until the remainder has been fully allocated. /// </summary> /// <remarks> /// In the case of a dollar split three ways the extra penny to the last receipient /// and the allocation is done. /// </remarks> public static readonly IRemainderAllocator LastToFirst = new LastToFirstAllocator(); /// <summary> /// Allocate the remainder to a randomly selected recipient and keep going using another randomly /// selected recipient until the remainder has been fully allocated. /// </summary> /// <remarks> /// In the case of the dollar split three ways randomly, the recipient that gets the extra penny is indeterminate. /// <para> /// This <see cref="IRemainderAllocator"/> is much slower than either <see cref="FirstToLastAllocator"/> /// or <see cref="LastToFirstAllocator"/>. In addition, this particular implementation *could* arguably /// be made even more random. See the referenced links for some other implementation ideas that might /// enhance perf and/or randomness. /// </para> /// <seealso href="http://stackoverflow.com/questions/48087/select-a-random-n-elements-from-listt-in-c-sharp"/> /// <seealso href="http://www.fsmpi.uni-bayreuth.de/~dun3/archives/return-random-subset-of-n-elements-of-a-given-array/98.html"/> /// </remarks> public static readonly IRemainderAllocator Random = new RandomAllocator(); } }
using NMoneys.Allocations; namespace NMoneys { /// <summary> /// Factory class for provided implementations of <see cref="IRemainderAllocator"/> /// </summary> public static class RemainderAllocator { /// <summary> /// Allocate the remainder to the first known recipient and keep going in order towards /// the last recipient until the remainder has been fully allocated. /// </summary> /// <remarks> /// In the case of a dollar split three ways the extra penny to the first receipient /// and the allocation is done. /// </remarks> public static readonly IRemainderAllocator FirstToLast = new FirstToLastAllocator(); /// <summary> /// Allocate the remainder to the last known recipient and keep going in order towards /// the first recipient until the remainder has been fully allocated. /// </summary> /// <remarks> /// In the case of a dollar split three ways the extra penny to the first receipient /// and the allocation is done. /// </remarks> public static readonly IRemainderAllocator LastToFirst = new LastToFirstAllocator(); /// <summary> /// Allocate the remainder to a randomly selected recipient and keep going using another randomly /// selected recipient until the remainder has been fully allocated. /// </summary> /// <remarks> /// In the case of the dollar split three ways randomly, the recipient that gets the extra penny is indeterminate. /// <para> /// This <see cref="IRemainderAllocator"/> is much slower than either <see cref="FirstToLastAllocator"/> /// or <see cref="LastToFirstAllocator"/>. In addition, this particular implementation *could* arguably /// be made even more random. See the referenced links for some other implementation ideas that might /// enhance perf and/or randomness. /// </para> /// <seealso href="http://stackoverflow.com/questions/48087/select-a-random-n-elements-from-listt-in-c-sharp"/> /// <seealso href="http://www.fsmpi.uni-bayreuth.de/~dun3/archives/return-random-subset-of-n-elements-of-a-given-array/98.html"/> /// </remarks> public static readonly IRemainderAllocator Random = new RandomAllocator(); } }
bsd-3-clause
C#
7da8cc3c3e3e488cec93ea79f114766711f18ccb
Revise dropdowns for building unitypackages.
PlayFab/UnityEditorExtensions
Source/Assets/Editor/PlayFabEdExPackager.cs
Source/Assets/Editor/PlayFabEdExPackager.cs
using UnityEditor; using UnityEngine; namespace PlayFab.Internal { public static class PlayFabEdExPackager { private static readonly string[] SdkAssets = { "Assets/PlayFabEditorExtensions" }; [MenuItem("PlayFab/Testing/Build PlayFab EdEx UnityPackage")] public static void BuildUnityPackage() { var packagePath = "C:/depot/sdks/UnityEditorExtensions/Packages/PlayFabEditorExtensions.unitypackage"; AssetDatabase.ExportPackage(SdkAssets, packagePath, ExportPackageOptions.Recurse); Debug.Log("Package built: " + packagePath); } } }
using UnityEditor; using UnityEngine; namespace PlayFab.Internal { public static class PlayFabEdExPackager { private static readonly string[] SdkAssets = { "Assets/PlayFabEditorExtensions" }; [MenuItem("PlayFab/Build PlayFab EdEx UnityPackage")] public static void BuildUnityPackage() { var packagePath = "C:/depot/sdks/UnityEditorExtensions/Packages/PlayFabEditorExtensions.unitypackage"; AssetDatabase.ExportPackage(SdkAssets, packagePath, ExportPackageOptions.Recurse); Debug.Log("Package built: " + packagePath); } } }
apache-2.0
C#
1fa8089a14669d89d398c5130cab8e0fa19ae1a1
add assimp library
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 System.IO; using System; using UnrealBuildTool; public class MeshGenerator : ModuleRules { private string ModulePath { get { return ModuleDirectory; } } private string ThirdPartyPath { get { return Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/")); } } public MeshGenerator(TargetInfo Target) { PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore"}); PublicDependencyModuleNames.AddRange(new string[] { "ShaderCore", "RenderCore", "RHI", "RuntimeMeshComponent" }); PrivateDependencyModuleNames.AddRange(new string[] { }); PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "assimp", "Libraries", "assimp.lib")); PublicIncludePaths.Add(Path.Combine(ThirdPartyPath, "assimp", "Includes")); } }
// Fill out your copyright notice in the Description page of Project Settings. using System.IO; using System; using UnrealBuildTool; public class MeshGenerator : ModuleRules { private string ModulePath { get { return ModuleDirectory; } } private string ThirdPartyPath { get { return Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/")); } } public MeshGenerator(TargetInfo Target) { PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore"}); PublicDependencyModuleNames.AddRange(new string[] { "ShaderCore", "RenderCore", "RHI", "RuntimeMeshComponent" }); PrivateDependencyModuleNames.AddRange(new string[] { }); PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "tinyply", "Libraries", "tinyply.lib")); PublicIncludePaths.Add(Path.Combine(ThirdPartyPath, "tinyply", "Includes")); } }
mit
C#
0d1f38844a4e6abdc801f88a097352c89e6c48c0
Add helper
KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog
src/BinlogTool/Program.cs
src/BinlogTool/Program.cs
using System; using System.IO; using System.Linq; namespace BinlogTool { class Program { static void Main(string[] args) { if (args.Length == 3 && string.Equals(args[0], "savefiles", StringComparison.OrdinalIgnoreCase)) { var binlog = args[1]; var outputRoot = args[2]; new SaveFiles(args).Run(binlog, outputRoot); return; } if (args.Length == 3 && string.Equals(args[0], "savestrings", StringComparison.OrdinalIgnoreCase)) { var binlog = args[1]; var outputFile = args[2]; new SaveStrings().Run(binlog, outputFile); return; } Console.WriteLine("Usage: binlogtool savefiles input.binlog"); } private static void CompareStrings() { var left = SaveStrings.ReadStrings(@"C:\temp\1.txt"); var right = SaveStrings.ReadStrings(@"C:\temp\2.txt"); var onlyLeft = left.Except(right).ToArray(); var onlyRight = right.Except(left).ToArray(); File.WriteAllLines(@"C:\temp\onlyLeft.txt", onlyLeft); File.WriteAllLines(@"C:\temp\onlyRight.txt", onlyRight); } } }
using System; using System.Linq; namespace BinlogTool { class Program { static void Main(string[] args) { if (args.Length == 3 && string.Equals(args[0], "savefiles", StringComparison.OrdinalIgnoreCase)) { var binlog = args[1]; var outputRoot = args[2]; new SaveFiles(args).Run(binlog, outputRoot); return; } if (args.Length == 3 && string.Equals(args[0], "savestrings", StringComparison.OrdinalIgnoreCase)) { var binlog = args[1]; var outputFile = args[2]; new SaveStrings().Run(binlog, outputFile); return; } Console.WriteLine("Usage: binlogtool savefiles input.binlog"); } } }
mit
C#
90ef72e50defd269fdf4373f6eaf95c6b451b30a
Increase project version number to 0.11.0
atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.11.0.0")] [assembly: AssemblyFileVersion("0.11.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.10.0.0")] [assembly: AssemblyFileVersion("0.10.0.0")]
apache-2.0
C#
704ed67970e9eab48ed1d4a81270c82255b4da81
clean up code
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/IFramework.Test/EntityFramework/User.cs
Src/IFramework.Test/EntityFramework/User.cs
using System; using System.Collections.Generic; using System.Text; using IFramework.Domain; using IFramework.Infrastructure; using MongoDB.Bson.Serialization.Attributes; namespace IFramework.Test.EntityFramework { public class User: TimestampedAggregateRoot { public string Id { get; protected set; } public string Name { get; protected set; } public string Gender { get; protected set; } public virtual ICollection<Card> Cards { get; set; } = new HashSet<Card>(); protected User() { } public User(string name, string gender) { Id = ObjectId.GenerateNewId() .ToString(); Name = name; Gender = gender; } public void ModifyName(string name) { Name = name; } public void AddCard(string cardName) { Cards.Add(new Card(Id, cardName)); } } }
using System; using System.Collections.Generic; using System.Text; using IFramework.Domain; using IFramework.Infrastructure; using MongoDB.Bson.Serialization.Attributes; namespace IFramework.Test.EntityFramework { public class User: TimestampedAggregateRoot { public string Id { get; protected set; } public string Name { get; protected set; } public string Gender { get; protected set; } [BsonElement] public virtual ICollection<Card> Cards { get; set; } = new HashSet<Card>(); protected User() { } public User(string name, string gender) { Id = ObjectId.GenerateNewId() .ToString(); Name = name; Gender = gender; } public void ModifyName(string name) { Name = name; } public void AddCard(string cardName) { Cards.Add(new Card(Id, cardName)); } } }
mit
C#
4246763ffa54cd9947cac3f84055b2007879e347
Add version numbers
whampson/cascara,whampson/bft-spec
Src/WHampson.BFT/Properties/AssemblyInfo.cs
Src/WHampson.BFT/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.BFT")] [assembly: AssemblyDescription("Binary File Template parser.")] [assembly: AssemblyProduct("WHampson.BFT")] [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.0.1")] [assembly: AssemblyVersion("0.0.1")] [assembly: AssemblyInformationalVersion("0.0.1")]
#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.BFT")] [assembly: AssemblyDescription("Binary File Template (BFT) implementation.")] [assembly: AssemblyProduct("WHampson.BFT")] [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")]
mit
C#
817c84b8f356dc668e96649df8ccdaf39ec8cb46
change print stats
amiralles/contest,amiralles/contest
src/Contest.Core/Printer.cs
src/Contest.Core/Printer.cs
//#define DARK_TEXT namespace Contest.Core { using System; using System.Collections.Generic; using System.Diagnostics; class Printer{ #if DARK_TEXT static ConsoleColor Default = ConsoleColor.Black; #else static ConsoleColor Default = ConsoleColor.White; #endif static ConsoleColor Red = ConsoleColor.Red; static ConsoleColor Green = ConsoleColor.Green; static ConsoleColor Yellow = ConsoleColor.Yellow; // void PrintResults(int casesCount, long elapsedMilliseconds) public readonly static Action<int, long, int, int, int, int, string> PrintResults = (casesCount, elapsedms, assertsCount, passCount, failCount, ignoreCount, cherry) => { Print("".PadRight(40, '-'), Default); Print("ASSERTS - STATS", Default); if(!string.IsNullOrEmpty(cherry)){ Print("".PadRight(40, '-'), Default); Print($"Cherry Picking => {cherry}", Default); } Print("".PadRight(40, '-'), Default); // Print("Test : {0}".Interpol(casesCount), Default); // Print("Asserts : {0}".Interpol(assertsCount), Default); Print($"Elapsed : {elapsedms} ms", Default); Print($"Passing : {passCount}", Green); Print($"Failing : {failCount}", Red); Print($"Ignored : {ignoreCount}", Yellow); Print("".PadRight(40, '-'), Default); }; public readonly static Action<string> PrintFixName = name => { Print("".PadRight(40, '='), ConsoleColor.Cyan); Print(name, ConsoleColor.Cyan); Print("".PadRight(40, '='), ConsoleColor.Cyan); }; public readonly static Action<string, ConsoleColor> Print = (msg, color) => { var fcolor = Console.ForegroundColor; try { Console.ForegroundColor = color; Console.WriteLine(msg); } finally { Console.ForegroundColor = fcolor; } }; } }
//#define DARK_TEXT namespace Contest.Core { using System; using System.Collections.Generic; using System.Diagnostics; class Printer{ #if DARK_TEXT static ConsoleColor Default = ConsoleColor.Black; #else static ConsoleColor Default = ConsoleColor.White; #endif static ConsoleColor Red = ConsoleColor.Red; static ConsoleColor Green = ConsoleColor.Green; static ConsoleColor Yellow = ConsoleColor.Yellow; // void PrintResults(int casesCount, long elapsedMilliseconds) public readonly static Action<int, long, int, int, int, int, string> PrintResults = (casesCount, elapsedms, assertsCount, passCount, failCount, ignoreCount, cherry) => { Print("".PadRight(40, '='), Default); Print("STATS", Default); if(!string.IsNullOrEmpty(cherry)){ Print("".PadRight(40, '='), Default); Print("Cherry Picking => {0}".Interpol(cherry), Default); } Print("".PadRight(40, '='), Default); Print("Test : {0}".Interpol(casesCount), Default); Print("Asserts : {0}".Interpol(assertsCount), Default); Print("Elapsed : {0} ms".Interpol(elapsedms), Default); Print("Passing : {0}".Interpol(passCount), Green); Print("Failing : {0}".Interpol(failCount), Red); Print("Ignored : {0}".Interpol(ignoreCount), Yellow); Print("".PadRight(40, '='), Default); }; public readonly static Action<string> PrintFixName = name => { Print("".PadRight(40, '='), ConsoleColor.Cyan); Print(name, ConsoleColor.Cyan); Print("".PadRight(40, '='), ConsoleColor.Cyan); }; public readonly static Action<string, ConsoleColor> Print = (msg, color) => { var fcolor = Console.ForegroundColor; try { Console.ForegroundColor = color; Console.WriteLine(msg); } finally { Console.ForegroundColor = fcolor; } }; } }
mit
C#
d04c7998e7952a49bc8fdb2e5679d647bad0df3c
Use user displayfor on game page
joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net
Joinrpg/Views/Game/Details.cshtml
Joinrpg/Views/Game/Details.cshtml
@*TODO: Have nice view model here, with Current user acls*@ @model JoinRpg.DataModel.Project @{ ViewBag.Title = "Игра «"+ Model.ProjectName +"»"; } <h2>@ViewBag.Title</h2> <div> <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.CreatedDate) </dt> <dd> @Html.DisplayFor(model => model.CreatedDate) </dd> <dt> @Html.DisplayNameFor(model => model.Active) </dt> <dd> @Html.DisplayFor(model => model.Active) </dd> </dl> <h4>Мастера</h4> <ul> @foreach (var master in Model.ProjectAcls) { <li>@Html.DisplayFor(model => master.User) @if (master.IsOwner) { <span>(создатель проекта)</span> } </li> } </ul> <h4>Управление проектом</h4> <ul> @*TODO: Show if avail*@ <li>@Html.ActionLink("Настройка полей", "Index", "GameField", new {Model.ProjectId}, null)</li> <li>@Html.ActionLink("Ролевка (группы персонажей и персонажи)", "Index", "GameGroups", new {Model.ProjectId}, null)</li> @* TODO: Show count*@ @*TODO: Show if avail*@ <li>@Html.ActionLink("Заявки на обсуждении", "Discussing", "Claim", new {Model.ProjectId}, null)</li> @*TODO: Show if avail*@ <li>@Html.ActionLink("Изменить свойства проекта", "Edit", new { Model.ProjectId })</li> </ul> </div>
@*TODO: Have nice view model here, with Current user acls*@ @model JoinRpg.DataModel.Project @{ ViewBag.Title = "Игра «"+ Model.ProjectName +"»"; } <h2>@ViewBag.Title</h2> <div> <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.CreatedDate) </dt> <dd> @Html.DisplayFor(model => model.CreatedDate) </dd> <dt> @Html.DisplayNameFor(model => model.Active) </dt> <dd> @Html.DisplayFor(model => model.Active) </dd> </dl> <h4>Мастера</h4> <ul> @foreach (var master in Model.ProjectAcls) { <li>@master.User.DisplayName @if (master.IsOwner) { <span>(создатель проекта)</span> } </li> } </ul> <h4>Управление проектом</h4> <ul> @*TODO: Show if avail*@ <li>@Html.ActionLink("Настройка полей", "Index", "GameField", new {Model.ProjectId}, null)</li> <li>@Html.ActionLink("Ролевка (группы персонажей и персонажи)", "Index", "GameGroups", new {Model.ProjectId}, null)</li> @* TODO: Show count*@ @*TODO: Show if avail*@ <li>@Html.ActionLink("Заявки на обсуждении", "Discussing", "Claim", new {Model.ProjectId}, null)</li> @*TODO: Show if avail*@ <li>@Html.ActionLink("Изменить свойства проекта", "Edit", new { Model.ProjectId })</li> </ul> </div>
mit
C#
7f33cebce16fe34bb466c076b764059b35b9daea
Set version 1.0.17
vdemydiuk/mtapi,vdemydiuk/mtapi,vdemydiuk/mtapi
MtApi5/Properties/AssemblyInfo.cs
MtApi5/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("MtApi5")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MtApi5")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f3256daf-a5c0-422d-9d79-f7156cccb910")] // 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.17")] [assembly: AssemblyFileVersion("1.0.17")]
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("MtApi5")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MtApi5")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f3256daf-a5c0-422d-9d79-f7156cccb910")] // 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.16")] [assembly: AssemblyFileVersion("1.0.16")]
mit
C#
06d0e58351339e06601cd5b3c7e73173aefc8041
Fix for NdapiMetaObject.ChildObjectProperties
felipebz/ndapi
Ndapi/Metadata/NdapiMetaObject.cs
Ndapi/Metadata/NdapiMetaObject.cs
using System; using System.Collections.Generic; using System.Linq; namespace Ndapi.Metadata { public class NdapiMetaObject { private readonly Type _type; private readonly Lazy<IEnumerable<NdapiMetaProperty>> _properties; public string ClassName => _type.Name; public IEnumerable<NdapiMetaProperty> AllProperties => _properties.Value; public IEnumerable<NdapiMetaProperty> StringProperties => AllProperties.Where(p => p.PropertyType == typeof(string)); public IEnumerable<NdapiMetaProperty> BooleanProperties => AllProperties.Where(p => p.PropertyType == typeof(bool)); public IEnumerable<NdapiMetaProperty> IntegerProperties => AllProperties.Where(p => p.PropertyType == typeof(int) || p.PropertyType.IsEnum); public IEnumerable<NdapiMetaProperty> ObjectProperties => AllProperties.Where(p => p.PropertyType.BaseType == typeof(NdapiObject)); public IEnumerable<NdapiMetaProperty> ChildObjectProperties => AllProperties.Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>)); public NdapiMetaObject(Type type) { _type = type; _properties = new Lazy<IEnumerable<NdapiMetaProperty>>(LoadProperties); } private IEnumerable<NdapiMetaProperty> LoadProperties() { return from property in _type.GetProperties() from info in property.GetCustomAttributes(typeof(PropertyAttribute), false).Cast<PropertyAttribute>() select new NdapiMetaProperty(info.PropertyId, property.CanRead, property.CanWrite, property.PropertyType); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Ndapi.Metadata { public class NdapiMetaObject { private readonly Type _type; private readonly Lazy<IEnumerable<NdapiMetaProperty>> _properties; public string ClassName => _type.Name; public IEnumerable<NdapiMetaProperty> AllProperties => _properties.Value; public IEnumerable<NdapiMetaProperty> StringProperties => AllProperties.Where(p => p.PropertyType == typeof(string)); public IEnumerable<NdapiMetaProperty> BooleanProperties => AllProperties.Where(p => p.PropertyType == typeof(bool)); public IEnumerable<NdapiMetaProperty> IntegerProperties => AllProperties.Where(p => p.PropertyType == typeof(int) || p.PropertyType.IsEnum); public IEnumerable<NdapiMetaProperty> ObjectProperties => AllProperties.Where(p => p.PropertyType.BaseType == typeof(NdapiObject)); public IEnumerable<NdapiMetaProperty> ChildObjectProperties => AllProperties.Where(p => p.PropertyType.BaseType == typeof(IEnumerable<>)); public NdapiMetaObject(Type type) { _type = type; _properties = new Lazy<IEnumerable<NdapiMetaProperty>>(LoadProperties); } private IEnumerable<NdapiMetaProperty> LoadProperties() { return from property in _type.GetProperties() from info in property.GetCustomAttributes(typeof(PropertyAttribute), false).Cast<PropertyAttribute>() select new NdapiMetaProperty(info.PropertyId, property.CanRead, property.CanWrite, property.PropertyType); } } }
mit
C#
36aa3a0e9d7efbe4282f07a813a1bfdd8e770221
make createIndex and modifyIndex nullable
Pondidum/OctopusStore,Pondidum/OctopusStore
OctopusStore/Consul/ValueModel.cs
OctopusStore/Consul/ValueModel.cs
namespace OctopusStore.Consul { public class ValueModel { public int? CreateIndex { get; set; } public int? ModifyIndex { get; set; } public int LockIndex { get; set; } public string Session { get; set; } public string Key { get; set; } public int Flags { get; set; } public string Value { get; set; } } }
namespace OctopusStore.Consul { public class ValueModel { public int CreateIndex { get; set; } public int ModifyIndex { get; set; } public int LockIndex { get; set; } public string Key { get; set; } public int Flags { get; set; } public string Value { get; set; } public string Session { get; set; } } }
lgpl-2.1
C#
28ebec8332b1dfae1d8258fe8c4f14f75262e3b3
Check debugger is attached before writing something to it
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/CSharpClient/Bit.CSharpClient.Prism/ViewModel/BitExceptionHandler.cs
src/CSharpClient/Bit.CSharpClient.Prism/ViewModel/BitExceptionHandler.cs
#define Debug using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel { public class BitExceptionHandler { public static BitExceptionHandler Current { get; set; } = new BitExceptionHandler(); public virtual void OnExceptionReceived(Exception exp, IDictionary<string, string> properties = null) { properties = properties ?? new Dictionary<string, string>(); if (exp != null && Debugger.IsAttached) { Debug.WriteLine($"DateTime: {DateTime.Now.ToLongTimeString()} Message: {exp}", category: "ApplicationException"); } } } }
#define Debug using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel { public class BitExceptionHandler { public static BitExceptionHandler Current { get; set; } = new BitExceptionHandler(); public virtual void OnExceptionReceived(Exception exp, IDictionary<string, string> properties = null) { properties = properties ?? new Dictionary<string, string>(); if (exp != null) { Debug.WriteLine($"DateTime: {DateTime.Now.ToLongTimeString()} Message: {exp}", category: "ApplicationException"); } } } }
mit
C#
1326905a3b85fc7a5ef81cc92ee9bbb7591001e1
Use Any instead of Count > 0
NicatorBa/Porthor
src/Porthor/ResourceRequestValidators/ContentValidators/JsonValidator.cs
src/Porthor/ResourceRequestValidators/ContentValidators/JsonValidator.cs
using Microsoft.AspNetCore.Http; using NJsonSchema; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators.ContentValidators { /// <summary> /// Request validator for json content. /// </summary> public class JsonValidator : ContentValidatorBase { private readonly JsonSchema4 _schema; /// <summary> /// Constructs a new instance of <see cref="JsonValidator"/>. /// </summary> /// <param name="template">Template for json schema.</param> public JsonValidator(string template) : base(template) { _schema = JsonSchema4.FromJsonAsync(template).GetAwaiter().GetResult(); } /// <summary> /// Validates the content of the current <see cref="HttpContext"/> agains the json schema. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous query string validation process. /// Returns null if the content is valid agains the json schema. /// </returns> public override async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { var errors = _schema.Validate(await StreamToString(context.Request.Body)); if (errors.Any()) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } return null; } private Task<string> StreamToString(Stream stream) { var streamContent = new StreamContent(stream); stream.Position = 0; return streamContent.ReadAsStringAsync(); } } }
using Microsoft.AspNetCore.Http; using NJsonSchema; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators.ContentValidators { /// <summary> /// Request validator for json content. /// </summary> public class JsonValidator : ContentValidatorBase { private readonly JsonSchema4 _schema; /// <summary> /// Constructs a new instance of <see cref="JsonValidator"/>. /// </summary> /// <param name="template">Template for json schema.</param> public JsonValidator(string template) : base(template) { _schema = JsonSchema4.FromJsonAsync(template).GetAwaiter().GetResult(); } /// <summary> /// Validates the content of the current <see cref="HttpContext"/> agains the json schema. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous query string validation process. /// Returns null if the content is valid agains the json schema. /// </returns> public override async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { var errors = _schema.Validate(await StreamToString(context.Request.Body)); if (errors.Count > 0) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } return null; } private Task<string> StreamToString(Stream stream) { var streamContent = new StreamContent(stream); stream.Position = 0; return streamContent.ReadAsStringAsync(); } } }
apache-2.0
C#
754776cccae4a3bafb7b13c6b9fd74b11441e0ae
Edit deploy_local.csx
mrahhal/Migrator.EF6
deploy_local.csx
deploy_local.csx
using System; using System.IO; using System.Text.RegularExpressions; using System.Diagnostics; using System.Linq; var cd = Environment.CurrentDirectory; var projectName = "Migrator.EF6.Tools"; var userName = Environment.UserName; var userProfileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var deploymentFolder = Environment.GetEnvironmentVariable("MIGRATOR_EF6_LOCAL_PACKAGES_FEED_PATH") ?? $@"C:\dev\LocalPackages"; Directory.CreateDirectory(deploymentFolder); var nugetDirectory = Path.Combine(userProfileDirectory, ".nuget/packages"); var nugetToolsDirectory = Path.Combine(nugetDirectory, ".tools"); var nugetProjectDirectory = Path.Combine(nugetDirectory, projectName); var nugetToolsProjectDirectory = Path.Combine(nugetToolsDirectory, projectName); var regexFolder = new Regex(@"(.\..\..)-(.+)"); var regexFile = new Regex($@"{projectName}\.(.\..\..)-(.+).nupkg"); if (!Pack()) { Console.WriteLine("A problem occurred while packing."); return; } RemoveDevPackageFilesIn(deploymentFolder); RemoveDevPackagesIn(nugetProjectDirectory); RemoveDevPackagesIn(nugetToolsProjectDirectory); var package = GetPackagePath(); if (package == null) { Console.WriteLine("Package file not found. A problem might have occurred with the build script."); return; } var packageFileName = Path.GetFileName(package); var deployedPackagePath = Path.Combine(deploymentFolder, packageFileName); File.Copy(package, deployedPackagePath); Console.WriteLine($"{packageFileName} -> {deployedPackagePath}"); //------------------------------------------------------------------------------ void RemoveDevPackagesIn(string directory) { var folders = Directory.EnumerateDirectories(directory); foreach (var folder in folders) { var name = Path.GetFileName(folder); if (regexFolder.IsMatch(name)) { Directory.Delete(folder, true); } } } void RemoveDevPackageFilesIn(string directory) { var files = Directory.EnumerateFiles(directory); foreach (var file in files) { var name = Path.GetFileName(file); if (regexFile.IsMatch(name)) { File.Delete(file); } } } bool Pack() { var process = Process.Start("powershell", "./build.ps1"); process.WaitForExit(); var exitCode = process.ExitCode; return exitCode == 0; } string GetPackagePath() { var packagesDirectory = Path.Combine(cd, "artifacts/packages"); if (!Directory.Exists(packagesDirectory)) { return null; } var files = Directory.EnumerateFiles(packagesDirectory); return files.OrderBy(f => f.Length).FirstOrDefault(); }
using System; using System.IO; using System.Text.RegularExpressions; using System.Diagnostics; using System.Linq; var cd = Environment.CurrentDirectory; var projectName = "Migrator.EF6.Tools"; var userName = Environment.UserName; var userProfileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var deploymentFolder = Environment.GetEnvironmentVariable("MIGRATOR_EF6_LOCAL_PACKAGES_FEED_PATH") ?? $@"C:\D\dev\src\Local Packages"; Directory.CreateDirectory(deploymentFolder); var nugetDirectory = Path.Combine(userProfileDirectory, ".nuget/packages"); var nugetToolsDirectory = Path.Combine(nugetDirectory, ".tools"); var nugetProjectDirectory = Path.Combine(nugetDirectory, projectName); var nugetToolsProjectDirectory = Path.Combine(nugetToolsDirectory, projectName); var regexFolder = new Regex(@"(.\..\..)-(.+)"); var regexFile = new Regex($@"{projectName}\.(.\..\..)-(.+).nupkg"); if (!Pack()) { Console.WriteLine("A problem occurred while packing."); return; } RemoveDevPackageFilesIn(deploymentFolder); RemoveDevPackagesIn(nugetProjectDirectory); RemoveDevPackagesIn(nugetToolsProjectDirectory); var package = GetPackagePath(); if (package == null) { Console.WriteLine("Package file not found. A problem might have occurred with the build script."); return; } var packageFileName = Path.GetFileName(package); var deployedPackagePath = Path.Combine(deploymentFolder, packageFileName); File.Copy(package, deployedPackagePath); Console.WriteLine($"{packageFileName} -> {deployedPackagePath}"); //------------------------------------------------------------------------------ void RemoveDevPackagesIn(string directory) { var folders = Directory.EnumerateDirectories(directory); foreach (var folder in folders) { var name = Path.GetFileName(folder); if (regexFolder.IsMatch(name)) { Directory.Delete(folder, true); } } } void RemoveDevPackageFilesIn(string directory) { var files = Directory.EnumerateFiles(directory); foreach (var file in files) { var name = Path.GetFileName(file); if (regexFile.IsMatch(name)) { File.Delete(file); } } } bool Pack() { var process = Process.Start("powershell", "build.ps1"); process.WaitForExit(); var exitCode = process.ExitCode; return exitCode == 0; } string GetPackagePath() { var packagesDirectory = Path.Combine(cd, "artifacts/packages"); if (!Directory.Exists(packagesDirectory)) { return null; } var files = Directory.EnumerateFiles(packagesDirectory); return files.OrderBy(f => f.Length).FirstOrDefault(); }
mit
C#
9984debf927338698464f7e12a8d8e43109b2d7d
Revert "Fixed a bug where closing the quicknotes window then clicking show/hide quicknotes on the settings window would crash the program."
Saveyour-Team/Saveyour
Saveyour/Saveyour/Settings.xaml.cs
Saveyour/Saveyour/Settings.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.Shapes; namespace Saveyour { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : Window, Module { Window qnotes; public Settings() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (qnotes.IsVisible) qnotes.Hide(); else qnotes.Show(); } public void addQNotes(Window module) { qnotes = module; } public String moduleID() { return "Settings"; } public Boolean update() { return false; } public String save() { return ""; } public Boolean load(String data) { return false; } public Boolean Equals(Module other) { return false; } } }
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.Shapes; namespace Saveyour { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : Window, Module { Window qnotes; public Settings() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (qnotes.IsVisible) qnotes.Hide(); else if (qnotes.IsActive) qnotes.Show(); } public void addQNotes(Window module) { qnotes = module; } public String moduleID() { return "Settings"; } public Boolean update() { return false; } public String save() { return ""; } public Boolean load(String data) { return false; } public Boolean Equals(Module other) { return false; } } }
apache-2.0
C#
dce1e2c99b593e8b783365e81f178c4db4ef0c70
update version?
TempoIQ/tempoiq-net,jcc333/tempoiq-net,selecsosi/tempoiq-net,TempoIQ/tempoiq-net,mrgaaron/tempoiq-net
TempoIQ/Properties/AssemblyInfo.cs
TempoIQ/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("TempoIQ")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TempoIQ")] [assembly: AssemblyProduct("TempoIQ")] [assembly: AssemblyCopyright("Copyright © 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("a622a7c0-9342-47d3-a09c-6b94f94d683f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
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("TempoIQ")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TempoIQ")] [assembly: AssemblyProduct("TempoIQ")] [assembly: AssemblyCopyright("Copyright © 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("a622a7c0-9342-47d3-a09c-6b94f94d683f")] // 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#
032c78cccce46886424f97eeecf4474b0428169c
Update AssemblyInfo.cs
rosolko/WebDriverManager.Net
WebDriverManager/Properties/AssemblyInfo.cs
WebDriverManager/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebDriverManager.Net")] [assembly: AssemblyDescription("Automatic Selenium WebDriver binaries management for .Net")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("Alexander Rosolko")] [assembly: AssemblyProduct("WebDriverManager.Net")] [assembly: AssemblyCopyright("Copyright © Alexander Rosolko 2016")] // 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("0066742e-391b-407c-9dc1-ff71a60bec53")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: //[assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebDriverManager.Net")] [assembly: AssemblyDescription("Automatic Selenium WebDriver binaries management for .Net")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("Alexander Rosolko")] [assembly: AssemblyProduct("WebDriverManager.Net")] [assembly: AssemblyCopyright("Copyright © Alexander Rosolko 2016")] // 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("0066742e-391b-407c-9dc1-ff71a60bec53")] // 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.1.*")] //[assembly: AssemblyVersion("1.0.0.0")] //[assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
dd5677a8d5cbcf1ca2f1735e78f2f5784b1e766a
use utf-8 file encoding for javascript files served by Kestrel
dotnet-toolbox/dotnet-toolbox,dotnet-toolbox/dotnet-toolbox,LukeWinikates/dotnet-toolbox,dotnet-toolbox/dotnet-toolbox,dotnet-toolbox/dotnet-toolbox,LukeWinikates/dotnet-toolbox,LukeWinikates/dotnet-toolbox,LukeWinikates/dotnet-toolbox
src/dotnet-toolbox.api/Startup.cs
src/dotnet-toolbox.api/Startup.cs
using Autofac; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Autofac.Extensions.DependencyInjection; using System; using Microsoft.AspNet.StaticFiles; namespace dotnet_toolbox.api { public class Startup { private const string JavaScriptExtension = ".js"; public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); var builder = new ContainerBuilder(); builder.RegisterType<Nuget.NugetApi>().As<Nuget.INugetApi>().InstancePerLifetimeScope(); builder.Populate(services); var container = builder.Build(); return container.Resolve<IServiceProvider>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseIISPlatformHandler(); app.UseDefaultFiles(); var provider = new FileExtensionContentTypeProvider(); ForceUtf8EncodingForJavaScript(provider); // Serve static files. app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider }); app.UseMvc(); } private static void ForceUtf8EncodingForJavaScript(FileExtensionContentTypeProvider provider) { if (provider.Mappings.ContainsKey(JavaScriptExtension)) { provider.Mappings.Remove(JavaScriptExtension); } provider.Mappings.Add(JavaScriptExtension, "application/javascript; charset=utf-8"); } // Entry point for the application. public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args); } }
using Autofac; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Autofac.Extensions.DependencyInjection; using System; namespace dotnet_toolbox.api { public class Startup { public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); var builder = new ContainerBuilder(); builder.RegisterType<Nuget.NugetApi>().As<Nuget.INugetApi>().InstancePerLifetimeScope(); builder.Populate(services); var container = builder.Build(); return container.Resolve<IServiceProvider>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseIISPlatformHandler(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(); } // Entry point for the application. public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args); } }
mit
C#
7afd3070790c362b2ed17fcc3179116e7639bbaa
Update parameters
sakapon/Samples-2015
WpfSample/ProgressWpf/AppModel.cs
WpfSample/ProgressWpf/AppModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using KLibrary.Labs.ObservableModel; namespace ProgressWpf { public class AppModel { public IGetOnlyProperty<double> ProgressValue { get; private set; } public AppModel() { ProgressValue = Observable.Interval(TimeSpan.FromSeconds(0.03)) .Select(n => n % 120) .Select(n => n / 100.0) .Select(v => v < 1.0 ? v : 1.0) .ToGetOnly(0.0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using KLibrary.Labs.ObservableModel; namespace ProgressWpf { public class AppModel { public IGetOnlyProperty<double> ProgressValue { get; private set; } public AppModel() { ProgressValue = Observable.Interval(TimeSpan.FromSeconds(0.05)) .Select(l => l % 101) .Select(l => l / 100.0) .ToGetOnly(0.0); } } }
mit
C#
2bee195a0ecf1463db96da13b32784ff655341b4
Fix IconClass for WebConfigTransformRunnerTasks.
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/IconClasses.cs
source/Nuke.Common/IconClasses.cs
// Copyright Matthias Koch 2018. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common; using Nuke.Common.ChangeLog; using Nuke.Common.Git; using Nuke.Common.Gitter; using Nuke.Common.Tools.CoverallsNet; using Nuke.Common.Tools.DocFx; using Nuke.Common.Tools.DotCover; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.DupFinder; using Nuke.Common.Tools.Git; using Nuke.Common.Tools.GitLink; using Nuke.Common.Tools.GitReleaseManager; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.InspectCode; using Nuke.Common.Tools.MSBuild; using Nuke.Common.Tools.Npm; using Nuke.Common.Tools.NuGet; using Nuke.Common.Tools.Nunit; using Nuke.Common.Tools.Octopus; using Nuke.Common.Tools.OpenCover; using Nuke.Common.Tools.Paket; using Nuke.Common.Tools.ReportGenerator; using Nuke.Common.Tools.SignTool; using Nuke.Common.Tools.TestCloud; using Nuke.Common.Tools.VsTest; using Nuke.Common.Tools.WebConfigTransformRunner; using Nuke.Common.Tools.Xunit; using Nuke.Core.Execution; [assembly: IconClass(typeof(ChangelogTasks), "books")] [assembly: IconClass(typeof(CoverallsNetTasks), "pie-chart4")] [assembly: IconClass(typeof(DefaultSettings), "equalizer")] [assembly: IconClass(typeof(DocFxTasks), "books")] [assembly: IconClass(typeof(DotCoverTasks), "shield2")] [assembly: IconClass(typeof(DotNetTasks), "fire")] [assembly: IconClass(typeof(DupFinderTasks), "code")] [assembly: IconClass(typeof(GitTasks), "git")] [assembly: IconClass(typeof(GitLinkTasks), "link")] [assembly: IconClass(typeof(GitReleaseManagerTasks), "books")] [assembly: IconClass(typeof(GitRepository), "git")] [assembly: IconClass(typeof(GitterTasks), "bubbles")] [assembly: IconClass(typeof(GitVersionTasks), "podium")] [assembly: IconClass(typeof(InspectCodeTasks), "code")] [assembly: IconClass(typeof(MSBuildTasks), "sword")] [assembly: IconClass(typeof(NpmTasks), "box")] [assembly: IconClass(typeof(NuGetTasks), "box")] [assembly: IconClass(typeof(NunitTasks), "bug2")] [assembly: IconClass(typeof(OctopusTasks), "cloud-upload")] [assembly: IconClass(typeof(OpenCoverTasks), "shield2")] [assembly: IconClass(typeof(PaketTasks), "box")] [assembly: IconClass(typeof(ReportGeneratorTasks), "pie-chart4")] [assembly: IconClass(typeof(SignToolTasks), "key")] [assembly: IconClass(typeof(TestCloudTasks), "bug2")] [assembly: IconClass(typeof(VsTestTasks), "bug2")] [assembly: IconClass(typeof(WebConfigTransformRunnerTasks), "file-empty2")] [assembly: IconClass(typeof(XunitTasks), "bug2")]
// Copyright Matthias Koch 2018. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common; using Nuke.Common.ChangeLog; using Nuke.Common.Git; using Nuke.Common.Gitter; using Nuke.Common.Tools.CoverallsNet; using Nuke.Common.Tools.DocFx; using Nuke.Common.Tools.DotCover; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.DupFinder; using Nuke.Common.Tools.Git; using Nuke.Common.Tools.GitLink; using Nuke.Common.Tools.GitReleaseManager; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.InspectCode; using Nuke.Common.Tools.MSBuild; using Nuke.Common.Tools.Npm; using Nuke.Common.Tools.NuGet; using Nuke.Common.Tools.Nunit; using Nuke.Common.Tools.Octopus; using Nuke.Common.Tools.OpenCover; using Nuke.Common.Tools.Paket; using Nuke.Common.Tools.ReportGenerator; using Nuke.Common.Tools.SignTool; using Nuke.Common.Tools.TestCloud; using Nuke.Common.Tools.VsTest; using Nuke.Common.Tools.WebConfigTransformRunner; using Nuke.Common.Tools.Xunit; using Nuke.Core.Execution; [assembly: IconClass(typeof(ChangelogTasks), "books")] [assembly: IconClass(typeof(CoverallsNetTasks), "pie-chart4")] [assembly: IconClass(typeof(DefaultSettings), "equalizer")] [assembly: IconClass(typeof(DocFxTasks), "books")] [assembly: IconClass(typeof(DotCoverTasks), "shield2")] [assembly: IconClass(typeof(DotNetTasks), "fire")] [assembly: IconClass(typeof(DupFinderTasks), "code")] [assembly: IconClass(typeof(GitTasks), "git")] [assembly: IconClass(typeof(GitLinkTasks), "link")] [assembly: IconClass(typeof(GitReleaseManagerTasks), "books")] [assembly: IconClass(typeof(GitRepository), "git")] [assembly: IconClass(typeof(GitterTasks), "bubbles")] [assembly: IconClass(typeof(GitVersionTasks), "podium")] [assembly: IconClass(typeof(InspectCodeTasks), "code")] [assembly: IconClass(typeof(MSBuildTasks), "sword")] [assembly: IconClass(typeof(NpmTasks), "box")] [assembly: IconClass(typeof(NuGetTasks), "box")] [assembly: IconClass(typeof(NunitTasks), "bug2")] [assembly: IconClass(typeof(OctopusTasks), "cloud-upload")] [assembly: IconClass(typeof(OpenCoverTasks), "shield2")] [assembly: IconClass(typeof(PaketTasks), "box")] [assembly: IconClass(typeof(ReportGeneratorTasks), "pie-chart4")] [assembly: IconClass(typeof(SignToolTasks), "key")] [assembly: IconClass(typeof(TestCloudTasks), "bug2")] [assembly: IconClass(typeof(VsTestTasks), "bug2")] [assembly: IconClass(typeof(WebConfigTransformRunnerTasks), "bug2")] [assembly: IconClass(typeof(XunitTasks), "bug2")]
mit
C#
2a09adf2f526b52a2aa3fd8bfb8cc500a5bdde14
Add X.Is
vain0/EnumerableTest
EnumerableTest.Core/TestExtension.cs
EnumerableTest.Core/TestExtension.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using EnumerableTest.Sdk; namespace EnumerableTest { /// <summary> /// Provides extension methods related to <see cref="Test"/>. /// </summary> public static class TestExtension { /// <summary> /// Groups tests. /// <para lang="ja"> /// テストをグループ化する。 /// </para> /// </summary> /// <param name="tests"></param> /// <param name="testName"></param> /// <returns></returns> public static GroupTest ToTestGroup(this IEnumerable<Test> tests, string testName) { var testList = new List<Test>(); var exceptionOrNull = default(Exception); try { foreach (var test in tests) { testList.Add(test); } } catch (Exception exception) { exceptionOrNull = exception; } return new GroupTest(testName, testList.ToArray(), exceptionOrNull); } /// <summary> /// Equivalent to <see cref="Test.Equal{X}(X, X)"/>. /// </summary> /// <typeparam name="X"></typeparam> /// <param name="actual"></param> /// <param name="expected"></param> /// <returns></returns> public static Test Is<X>(this X actual, X expected) { return Test.Equal(expected, actual); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EnumerableTest.Sdk; namespace EnumerableTest { /// <summary> /// Provides extension methods related to <see cref="Test"/>. /// </summary> public static class TestExtension { /// <summary> /// Groups tests. /// <para lang="ja"> /// テストをグループ化する。 /// </para> /// </summary> /// <param name="tests"></param> /// <param name="testName"></param> /// <returns></returns> public static GroupTest ToTestGroup(this IEnumerable<Test> tests, string testName) { var testList = new List<Test>(); var exceptionOrNull = default(Exception); try { foreach (var test in tests) { testList.Add(test); } } catch (Exception exception) { exceptionOrNull = exception; } return new GroupTest(testName, testList.ToArray(), exceptionOrNull); } } }
mit
C#
5d4e3b1cd9b84821422a5095e7b3605b585ef4f1
Fix test
cbcrc/LinkIt
LinkIt.Tests/LookupIdContextTests.cs
LinkIt.Tests/LookupIdContextTests.cs
using LinkIt.Core; using LinkIt.PublicApi; using LinkIt.Tests.Shared; using NUnit.Framework; namespace LinkIt.Tests { [TestFixture] public class LookupIdContextTests { private LookupIdContext _sut; [SetUp] public void SetUp() { _sut = new LookupIdContext(); } [Test] public void Add_Distinct_ShouldAdd() { _sut.AddSingle<Image,string>("a"); _sut.AddSingle<Image, string>("b"); Assert.That(_sut.GetReferenceIds<Image, string>(), Is.EquivalentTo(new []{"a","b"})); } [Test] public void Add_WithDuplicates_DuplicatesShouldNotBeAdded() { _sut.AddSingle<Image, string>("a"); _sut.AddSingle<Image, string>("a"); _sut.AddSingle<Image, string>("b"); Assert.That(_sut.GetReferenceIds<Image, string>(), Is.EquivalentTo(new[] { "a", "b" })); } [Test] public void Add_NullId_ShouldIgnoreNullId() { _sut.AddSingle<Image, string>(null); var actual = _sut.GetReferenceTypes(); Assert.That(actual, Is.Empty); } } }
using LinkIt.Core; using LinkIt.PublicApi; using LinkIt.Tests.Shared; using NUnit.Framework; namespace LinkIt.Tests { [TestFixture] public class LookupIdContextTests { private ILookupIdContext _sut; [SetUp] public void SetUp() { _sut = new LookupIdContext(); } [Test] public void Add_Distinct_ShouldAdd() { _sut.AddSingle<Image,string>("a"); _sut.AddSingle<Image, string>("b"); Assert.That(_sut.GetReferenceIds<Image, string>(), Is.EquivalentTo(new []{"a","b"})); } [Test] public void Add_WithDuplicates_DuplicatesShouldNotBeAdded() { _sut.AddSingle<Image, string>("a"); _sut.AddSingle<Image, string>("a"); _sut.AddSingle<Image, string>("b"); Assert.That(_sut.GetReferenceIds<Image, string>(), Is.EquivalentTo(new[] { "a", "b" })); } [Test] public void Add_NullId_ShouldIgnoreNullId() { _sut.AddSingle<Image, string>(null); var actual = _sut.GetReferenceTypes(); Assert.That(actual, Is.Empty); } } }
mit
C#
ec9ad7107d1262883aeac154bfe2ae4eeb861280
Update AssemblyCopyright year (At somepoint it would be nice to update the source files, though that may have to wait until much later)
rover886/CefSharp,haozhouxu/CefSharp,zhangjingpu/CefSharp,illfang/CefSharp,AJDev77/CefSharp,rlmcneary2/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,gregmartinhtc/CefSharp,ITGlobal/CefSharp,Haraguroicha/CefSharp,zhangjingpu/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,AJDev77/CefSharp,joshvera/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,twxstar/CefSharp,AJDev77/CefSharp,dga711/CefSharp,Livit/CefSharp,yoder/CefSharp,battewr/CefSharp,rlmcneary2/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,jamespearce2006/CefSharp,yoder/CefSharp,joshvera/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,haozhouxu/CefSharp,Haraguroicha/CefSharp,gregmartinhtc/CefSharp,windygu/CefSharp,NumbersInternational/CefSharp,jamespearce2006/CefSharp,NumbersInternational/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,NumbersInternational/CefSharp,gregmartinhtc/CefSharp,ruisebastiao/CefSharp,ruisebastiao/CefSharp,battewr/CefSharp,wangzheng888520/CefSharp,rover886/CefSharp,rover886/CefSharp,zhangjingpu/CefSharp,Livit/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,windygu/CefSharp,rover886/CefSharp,rlmcneary2/CefSharp,twxstar/CefSharp,battewr/CefSharp,dga711/CefSharp,Livit/CefSharp,wangzheng888520/CefSharp,AJDev77/CefSharp,joshvera/CefSharp,jamespearce2006/CefSharp,gregmartinhtc/CefSharp,illfang/CefSharp,illfang/CefSharp,VioletLife/CefSharp,haozhouxu/CefSharp,NumbersInternational/CefSharp,ruisebastiao/CefSharp,joshvera/CefSharp,dga711/CefSharp,rover886/CefSharp,ITGlobal/CefSharp,VioletLife/CefSharp,VioletLife/CefSharp,Livit/CefSharp,wangzheng888520/CefSharp,ITGlobal/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,windygu/CefSharp,illfang/CefSharp,Haraguroicha/CefSharp
CefSharp/Properties/AssemblyInfo.cs
CefSharp/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using CefSharp; using System; [assembly: AssemblyTitle("CefSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyCompany(AssemblyInfo.AssemblyCompany)] [assembly: AssemblyProduct(AssemblyInfo.AssemblyProduct)] [assembly: AssemblyCopyright(AssemblyInfo.AssemblyCopyright)] [assembly: ComVisible(AssemblyInfo.ComVisible)] [assembly: AssemblyVersion(AssemblyInfo.AssemblyVersion)] [assembly: AssemblyFileVersion(AssemblyInfo.AssemblyFileVersion)] [assembly: CLSCompliant(AssemblyInfo.ClsCompliant)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpCoreProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpBrowserSubprocessProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpBrowserSubprocessCoreProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpWpfProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpWinFormsProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpTestProject)] namespace CefSharp { public static class AssemblyInfo { public const bool ClsCompliant = false; public const bool ComVisible = false; public const string AssemblyCompany = "The CefSharp Authors"; public const string AssemblyProduct = "CefSharp"; public const string AssemblyVersion = "39.0.0"; public const string AssemblyFileVersion = "39.0.0.0"; public const string AssemblyCopyright = "Copyright © The CefSharp Authors 2010-2015"; public const string CefSharpCoreProject = "CefSharp.Core, PublicKey=" + PublicKey; public const string CefSharpBrowserSubprocessProject = "CefSharp.BrowserSubprocess, PublicKey=" + PublicKey; public const string CefSharpBrowserSubprocessCoreProject = "CefSharp.BrowserSubprocess.Core, PublicKey=" + PublicKey; public const string CefSharpWpfProject = "CefSharp.Wpf, PublicKey=" + PublicKey; public const string CefSharpWinFormsProject = "CefSharp.WinForms, PublicKey=" + PublicKey; public const string CefSharpTestProject = "CefSharp.Test, PublicKey=" + PublicKey; // Use "%ProgramFiles%\Microsoft SDKs\Windows\v7.0A\bin\sn.exe" -Tp <assemblyname> to get PublicKey public const string PublicKey = "0024000004800000940000000602000000240000525341310004000001000100c5ddf5d063ca8e695d4b8b5ad76634f148db9a41badaed8850868b75f916e313f15abb62601d658ce2bed877d73314d5ed202019156c21033983fed80ce994a325b5d4d93b0f63a86a1d7db49800aa5638bb3fd98f4a33cceaf8b8ba1800b7d7bff67b72b90837271491b61c91ef6d667be0521ce171f77e114fc2bbcfd185d3"; } }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using CefSharp; using System; [assembly: AssemblyTitle("CefSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyCompany(AssemblyInfo.AssemblyCompany)] [assembly: AssemblyProduct(AssemblyInfo.AssemblyProduct)] [assembly: AssemblyCopyright(AssemblyInfo.AssemblyCopyright)] [assembly: ComVisible(AssemblyInfo.ComVisible)] [assembly: AssemblyVersion(AssemblyInfo.AssemblyVersion)] [assembly: AssemblyFileVersion(AssemblyInfo.AssemblyFileVersion)] [assembly: CLSCompliant(AssemblyInfo.ClsCompliant)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpCoreProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpBrowserSubprocessProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpBrowserSubprocessCoreProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpWpfProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpWinFormsProject)] [assembly: InternalsVisibleTo(AssemblyInfo.CefSharpTestProject)] namespace CefSharp { public static class AssemblyInfo { public const bool ClsCompliant = false; public const bool ComVisible = false; public const string AssemblyCompany = "The CefSharp Authors"; public const string AssemblyProduct = "CefSharp"; public const string AssemblyVersion = "39.0.0"; public const string AssemblyFileVersion = "39.0.0.0"; public const string AssemblyCopyright = "Copyright © The CefSharp Authors 2010-2014"; public const string CefSharpCoreProject = "CefSharp.Core, PublicKey=" + PublicKey; public const string CefSharpBrowserSubprocessProject = "CefSharp.BrowserSubprocess, PublicKey=" + PublicKey; public const string CefSharpBrowserSubprocessCoreProject = "CefSharp.BrowserSubprocess.Core, PublicKey=" + PublicKey; public const string CefSharpWpfProject = "CefSharp.Wpf, PublicKey=" + PublicKey; public const string CefSharpWinFormsProject = "CefSharp.WinForms, PublicKey=" + PublicKey; public const string CefSharpTestProject = "CefSharp.Test, PublicKey=" + PublicKey; // Use "%ProgramFiles%\Microsoft SDKs\Windows\v7.0A\bin\sn.exe" -Tp <assemblyname> to get PublicKey public const string PublicKey = "0024000004800000940000000602000000240000525341310004000001000100c5ddf5d063ca8e695d4b8b5ad76634f148db9a41badaed8850868b75f916e313f15abb62601d658ce2bed877d73314d5ed202019156c21033983fed80ce994a325b5d4d93b0f63a86a1d7db49800aa5638bb3fd98f4a33cceaf8b8ba1800b7d7bff67b72b90837271491b61c91ef6d667be0521ce171f77e114fc2bbcfd185d3"; } }
bsd-3-clause
C#
791ea9053123f9242aaacf3d34d7116618ff559e
Check it
ToBeerOrNotToBeer/Favor,ToBeerOrNotToBeer/Favor
Favor/Favor/Models/FavorModels/ListAllFavorsModel.cs
Favor/Favor/Models/FavorModels/ListAllFavorsModel.cs
using Favor.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Favor.Models.FavorModels { public class ListAllFavorsModel { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public Category Category { get; set; } } }
using Favor.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Favor.Models.FavorModels { public class ListAllFavorsModel { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public Category Category { get; set; } } }
mit
C#
ec0a12eb0a74df3ba1a0f75a287e55319cdfa292
Update EditAndContinueCapabilities.cs (#52935)
eriawan/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,sharwell/roslyn,eriawan/roslyn,mavasani/roslyn,physhi/roslyn,sharwell/roslyn,mavasani/roslyn,diryboy/roslyn,weltkante/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,bartdesmet/roslyn,eriawan/roslyn,physhi/roslyn,diryboy/roslyn,physhi/roslyn,weltkante/roslyn,dotnet/roslyn,wvdd007/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,diryboy/roslyn,wvdd007/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,weltkante/roslyn,dotnet/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn
src/Features/Core/Portable/EditAndContinue/EditAndContinueCapabilities.cs
src/Features/Core/Portable/EditAndContinue/EditAndContinueCapabilities.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; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// The capabilities that the runtime has with respect to edit and continue /// </summary> [Flags] internal enum EditAndContinueCapabilities { None = 0, /// <summary> /// Edit and continue is generally available with the set of capabilities that Mono 6, .NET Framework and .NET 5 have in common. /// </summary> Baseline = 1 << 0, /// <summary> /// Adding a static or instance method to an existing type. /// </summary> AddMethodToExistingType = 1 << 1, /// <summary> /// Adding a static field to an existing type. /// </summary> AddStaticFieldToExistingType = 1 << 2, /// <summary> /// Adding an instance field to an existing type. /// </summary> AddInstanceFieldToExistingType = 1 << 3, /// <summary> /// Creating a new type definition. /// </summary> NewTypeDefinition = 1 << 4 } }
// 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; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// The capabilities that the runtime has with respect to edit and continue /// </summary> [Flags] internal enum EditAndContinueCapabilities { None = 0, /// <summary> /// Edit and continue is generally available with the set of capabilities that Mono 6, .NET Framework and .NET 5 have in common. /// </summary> Baseline = 1 << 0, /// <summary> /// Adding a static or instance method to an existing type. /// </summary> AddMethodToExistingType = 1 << 1, /// <summary> /// Adding a static field to an existing type. /// </summary> AddStaticFieldToExistingType = 1 << 2, /// <summary> /// Adding an instance field to an existing type. /// </summary> AddInstanceFieldToExistingType = 1 << 3, /// <summary> /// Creating a new type definition. /// </summary> NewTypeDefinition = 1 << 2 } }
mit
C#
85dcea5b8fc8707728c92e280a8ff5644f012e2d
Set env vars when updating VSTS variables
AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning
src/NerdBank.GitVersioning/CloudBuildServices/VisualStudioTeamServices.cs
src/NerdBank.GitVersioning/CloudBuildServices/VisualStudioTeamServices.cs
namespace Nerdbank.GitVersioning.CloudBuildServices { using System; using System.IO; /// <summary> /// /// </summary> /// <remarks> /// The VSTS-specific properties referenced here are documented here: /// https://msdn.microsoft.com/en-us/Library/vs/alm/Build/scripts/variables /// </remarks> internal class VisualStudioTeamServices : ICloudBuild { public bool IsPullRequest => false; // VSTS doesn't define this. public string BuildingTag => null; // VSTS doesn't define this. public string BuildingBranch => Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); public string BuildingRef => this.BuildingBranch; public string GitCommitId => null; public bool IsApplicable => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECTID")); public void SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[build.updatebuildnumber]{buildNumber}"); SetEnvVariableForBuildVariable("Build.BuildNumber", buildNumber); } public void SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[task.setvariable variable={name};]{value}"); SetEnvVariableForBuildVariable(name, value); } private static void SetEnvVariableForBuildVariable(string name, string value) { string envVarName = name.ToUpperInvariant().Replace('.', '_'); Environment.SetEnvironmentVariable(envVarName, value); } } }
namespace Nerdbank.GitVersioning.CloudBuildServices { using System; using System.IO; /// <summary> /// /// </summary> /// <remarks> /// The VSTS-specific properties referenced here are documented here: /// https://msdn.microsoft.com/en-us/Library/vs/alm/Build/scripts/variables /// </remarks> internal class VisualStudioTeamServices : ICloudBuild { public bool IsPullRequest => false; // VSTS doesn't define this. public string BuildingTag => null; // VSTS doesn't define this. public string BuildingBranch => Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); public string BuildingRef => this.BuildingBranch; public string GitCommitId => null; public bool IsApplicable => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECTID")); public void SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[build.updatebuildnumber]{buildNumber}"); } public void SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[task.setvariable variable={name};]{value}"); } } }
mit
C#
a62118ff46b6ee57f8ce241637625232e3c69291
Set default size for window
Aqovia/OctopusPuppet
OctopusPuppet.Gui/AppBootstrapper.cs
OctopusPuppet.Gui/AppBootstrapper.cs
using System.Collections.Generic; using System.Windows; using Caliburn.Micro; using OctopusPuppet.Gui.ViewModels; namespace OctopusPuppet.Gui { public class AppBootstrapper : BootstrapperBase { public AppBootstrapper() { Initialize(); } protected override void OnStartup(object sender, StartupEventArgs e) { var settings = new Dictionary<string, object> { { "SizeToContent", SizeToContent.Manual }, { "Height" , 768 }, { "Width" , 768 }, }; DisplayRootViewFor<DeploymentPlannerViewModel>(settings); } } }
using System.Windows; using Caliburn.Micro; using OctopusPuppet.Gui.ViewModels; namespace OctopusPuppet.Gui { public class AppBootstrapper : BootstrapperBase { public AppBootstrapper() { Initialize(); } protected override void OnStartup(object sender, StartupEventArgs e) { DisplayRootViewFor<DeploymentPlannerViewModel>(); } } }
apache-2.0
C#
d2bd0a13d041616c9cd85dc7a7b6b4a9ced9e776
Fix unit test for SDK Name is required validate
dhawalharsora/connectedcare-sdk,SnapMD/connectedcare-sdk
SnapMD.VirtualCare.Sdk.Tests/ModelTests/NewPatientRequestValidationTest.cs
SnapMD.VirtualCare.Sdk.Tests/ModelTests/NewPatientRequestValidationTest.cs
using System; using NUnit.Framework; using SnapMD.VirtualCare.ApiModels; namespace SnapMD.VirtualCare.Sdk.Tests.ModelTests { [TestFixture] public class NewPatientRequestValidationTest { [Test] public void TestModelValidationFail() { var target = new NewPatientRequest(); var thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("Name is required.", thrown.Message); target.Name = new FirstLast(); thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("First name required.", thrown.Message); target.Name.First = "First Name"; thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("Email address required.", thrown.Message); target.Email = "test@mail.com"; thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("Address required.", thrown.Message); target.Address = "I.R. Address"; thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("Date of birth required.", thrown.Message); target.Dob = new DateTime(2015, 1, 1); thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("ProviderId required.", thrown.Message); target.ProviderId = 1; bool actual = target.ValidateModel(m => new Exception(m)); Assert.IsTrue(actual); } } }
using System; using NUnit.Framework; using SnapMD.VirtualCare.ApiModels; namespace SnapMD.VirtualCare.Sdk.Tests.ModelTests { [TestFixture] public class NewPatientRequestValidationTest { [Test] public void TestModelValidationFail() { var target = new NewPatientRequest(); var thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("Name is required", thrown.Message); target.Name = new FirstLast(); thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("First name required.", thrown.Message); target.Name.First = "First Name"; thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("Email address required.", thrown.Message); target.Email = "test@mail.com"; thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("Address required.", thrown.Message); target.Address = "I.R. Address"; thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("Date of birth required.", thrown.Message); target.Dob = new DateTime(2015, 1, 1); thrown = Assert.Throws<Exception>(() => target.ValidateModel(m => new Exception(m))); Assert.AreEqual("ProviderId required.", thrown.Message); target.ProviderId = 1; bool actual = target.ValidateModel(m => new Exception(m)); Assert.IsTrue(actual); } } }
apache-2.0
C#
f78c4fd577473ff73418bbe1220a8ba7a18bea88
Remove #if directive which is no longer necessary: .NET 4.7.1 supports all types used by the Dotnet helper class.
fixie/fixie
src/Fixie/Cli/Dotnet.cs
src/Fixie/Cli/Dotnet.cs
namespace Fixie.Cli { using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; class Dotnet { public static readonly string Path = FindDotnet(); static string FindDotnet() { var fileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet"; //If `dotnet` is the currently running process, return the full path to that executable. var mainModule = GetCurrentProcessMainModule(); var currentProcessIsDotNet = !string.IsNullOrEmpty(mainModule?.FileName) && System.IO.Path.GetFileName(mainModule.FileName) .Equals(fileName, StringComparison.OrdinalIgnoreCase); if (currentProcessIsDotNet) return mainModule.FileName; // Find "dotnet" by using the location of the shared framework. var fxDepsFile = AppContext.GetData("FX_DEPS_FILE") as string; if (string.IsNullOrEmpty(fxDepsFile)) throw new CommandLineException("While attempting to locate `dotnet`, FX_DEPS_FILE could not be found in the AppContext."); var dotnetDirectory = new FileInfo(fxDepsFile) // Microsoft.NETCore.App.deps.json .Directory? // (version) .Parent? // Microsoft.NETCore.App .Parent? // shared .Parent; // DOTNET_HOME if (dotnetDirectory == null) throw new CommandLineException("While attempting to locate `dotnet`. Could not traverse directories from FX_DEPS_FILE to DOTNET_HOME."); var dotnetPath = System.IO.Path.Combine(dotnetDirectory.FullName, fileName); if (!File.Exists(dotnetPath)) throw new CommandLineException($"Failed to locate `dotnet`. The path does not exist: {dotnetPath}"); return dotnetPath; } static ProcessModule GetCurrentProcessMainModule() { using (var currentProcess = Process.GetCurrentProcess()) return currentProcess.MainModule; } } }
#if !NET471 namespace Fixie.Cli { using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; class Dotnet { public static readonly string Path = FindDotnet(); static string FindDotnet() { var fileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet"; //If `dotnet` is the currently running process, return the full path to that executable. var mainModule = GetCurrentProcessMainModule(); var currentProcessIsDotNet = !string.IsNullOrEmpty(mainModule?.FileName) && System.IO.Path.GetFileName(mainModule.FileName) .Equals(fileName, StringComparison.OrdinalIgnoreCase); if (currentProcessIsDotNet) return mainModule.FileName; // Find "dotnet" by using the location of the shared framework. var fxDepsFile = AppContext.GetData("FX_DEPS_FILE") as string; if (string.IsNullOrEmpty(fxDepsFile)) throw new CommandLineException("While attempting to locate `dotnet`, FX_DEPS_FILE could not be found in the AppContext."); var dotnetDirectory = new FileInfo(fxDepsFile) // Microsoft.NETCore.App.deps.json .Directory? // (version) .Parent? // Microsoft.NETCore.App .Parent? // shared .Parent; // DOTNET_HOME if (dotnetDirectory == null) throw new CommandLineException("While attempting to locate `dotnet`. Could not traverse directories from FX_DEPS_FILE to DOTNET_HOME."); var dotnetPath = System.IO.Path.Combine(dotnetDirectory.FullName, fileName); if (!File.Exists(dotnetPath)) throw new CommandLineException($"Failed to locate `dotnet`. The path does not exist: {dotnetPath}"); return dotnetPath; } static ProcessModule GetCurrentProcessMainModule() { using (var currentProcess = Process.GetCurrentProcess()) return currentProcess.MainModule; } } } #endif
mit
C#
0b3360358a19d220086d4a567b016098840264f6
Fix formatting
timtmok/ktanemod-twofactor,timtmok/ktanemod-twofactor
Assets/Scripts/TwoFactorWidget.cs
Assets/Scripts/TwoFactorWidget.cs
using System.Collections.Generic; using Newtonsoft.Json; using UnityEngine; using Random = UnityEngine.Random; public class TwoFactorWidget : MonoBehaviour { public TextMesh KeyText; public TextMesh TimeRemainingText; public AudioClip Notify; private bool _activated; private int _key; private float _timeElapsed; private float TimerLength = 60.0f; private ModSettings _modSettings; public static string WidgetQueryTwofactor = "twofactor"; public static string WidgetTwofactorKey = "twofactor_key"; void Awake() { Debug.Log("[TwoFactorWidget] Two Factor present"); GetComponent<KMWidget>().OnQueryRequest += GetQueryResponse; GetComponent<KMWidget>().OnWidgetActivate += Activate; GenerateKey(); KeyText.text = ""; TimeRemainingText.text = ""; _modSettings = new ModSettings("TwoFactor"); _modSettings.ReadSettings(); TimerLength = _modSettings.Settings.TwoFactorTimerLength; if (TimerLength < 30) TimerLength = 30; if (TimerLength > 999) TimerLength = 999; } void Update() { if (!_activated) return; _timeElapsed += Time.deltaTime; // ReSharper disable once InvertIf if (_timeElapsed >= TimerLength) { _timeElapsed = 0f; UpdateKey(); } TimeRemainingText.text = string.Format("{0,3}", (int)(TimerLength - _timeElapsed)) + "."; } private void Activate() { _timeElapsed = 0f; DisplayKey(); _activated = true; } void UpdateKey() { GetComponent<KMAudio>().HandlePlaySoundAtTransform(Notify.name, transform); GenerateKey(); DisplayKey(); } private void GenerateKey() { _key = Random.Range(0, 1000000); } private void DisplayKey() { KeyText.text = string.Format("{0,6}", _key) + "."; } private string GetQueryResponse(string querykey, string queryinfo) { if (querykey != WidgetQueryTwofactor) return string.Empty; var response = new Dictionary<string, int> { { WidgetTwofactorKey, _key } }; var serializedResponse = JsonConvert.SerializeObject(response); return serializedResponse; } }
using System.Collections.Generic; using Newtonsoft.Json; using UnityEngine; using Random = UnityEngine.Random; public class TwoFactorWidget : MonoBehaviour { public TextMesh KeyText; public TextMesh TimeRemainingText; public AudioClip Notify; private bool _activated; private int _key; private float _timeElapsed; private float TimerLength = 60.0f; private ModSettings _modSettings; public static string WidgetQueryTwofactor = "twofactor"; public static string WidgetTwofactorKey = "twofactor_key"; void Awake () { Debug.Log("[TwoFactorWidget] Two Factor present"); GetComponent<KMWidget>().OnQueryRequest += GetQueryResponse; GetComponent<KMWidget>().OnWidgetActivate += Activate; GenerateKey(); KeyText.text = ""; TimeRemainingText.text = ""; _modSettings = new ModSettings("TwoFactor"); _modSettings.ReadSettings(); TimerLength = _modSettings.Settings.TwoFactorTimerLength; if (TimerLength < 30) TimerLength = 30; if (TimerLength > 999) TimerLength = 999; } void Update() { if (!_activated) return; _timeElapsed += Time.deltaTime; // ReSharper disable once InvertIf if (_timeElapsed >= TimerLength) { _timeElapsed = 0f; UpdateKey(); } TimeRemainingText.text = string.Format("{0,3}", (int)(TimerLength - _timeElapsed)) + "."; } private void Activate() { _timeElapsed = 0f; DisplayKey(); _activated = true; } void UpdateKey() { GetComponent<KMAudio>().HandlePlaySoundAtTransform(Notify.name, transform); GenerateKey(); DisplayKey(); } private void GenerateKey() { _key = Random.Range(0, 1000000); } private void DisplayKey() { KeyText.text = string.Format("{0,6}", _key) + "."; } private string GetQueryResponse(string querykey, string queryinfo) { if (querykey != WidgetQueryTwofactor) return string.Empty; var response = new Dictionary<string, int> {{WidgetTwofactorKey, _key}}; var serializedResponse = JsonConvert.SerializeObject(response); return serializedResponse; } }
mit
C#
09332218fe416dc421d2a441810e26753f069b19
Fix InvalidOperationException
k-t/SharpHaven
MonoHaven.Client/Game/GameScreen.cs
MonoHaven.Client/Game/GameScreen.cs
using System; using System.Drawing; using System.Linq; using C5; using MonoHaven.Login; using MonoHaven.UI; using MonoHaven.UI.Remote; using MonoHaven.Utils; using NLog; namespace MonoHaven.Game { public class GameScreen : BaseScreen { private static readonly NLog.Logger log = LogManager.GetCurrentClassLogger(); private readonly GameSession session; private readonly TreeDictionary<ushort, Controller> controllers; private readonly WidgetAdapterRegistry adapterRegistry; public GameScreen(GameSession session) { this.session = session; this.controllers = new TreeDictionary<ushort, Controller>(); this.controllers[0] = new Controller(0, session); this.controllers[0].Bind(RootWidget, new RootAdapter()); this.adapterRegistry = new WidgetAdapterRegistry(session); } public EventHandler Closed; public void Close() { App.Instance.QueueOnMainThread(() => Host.SetScreen(new LoginScreen())); } public void CreateWidget(ushort id, string type, Point location, ushort parentId, object[] args) { var parent = FindController(parentId); if (parent == null) throw new Exception( string.Format("Non-existent parent widget {0} for {1}", parentId, id)); var adapter = adapterRegistry.Get(type); var widget = adapter.Create(parent.Widget, args); widget.SetLocation(location); var ctl = new Controller(id, parent); ctl.Bind(widget, adapter); controllers[id] = ctl; } public void MessageWidget(ushort id, string message, object[] args) { var ctl = FindController(id); if (ctl == null) { log.Warn("UI message {1} to non-existent widget {0}", id, message); return; } ctl.HandleRemoteMessage(message, args); } public void DestroyWidget(ushort id) { Controller ctl; if (controllers.Remove(id, out ctl)) { ctl.Dispose(); foreach (var child in ctl.Children.ToList()) DestroyWidget(child.Id); return; } log.Warn("Try to remove non-existent widget {0}", id); } protected override void OnClose() { Closed.Raise(this, EventArgs.Empty); } private Controller FindController(ushort id) { Controller ctl; return controllers.Find(ref id, out ctl) ? ctl : null; } } }
using System; using System.Drawing; using C5; using MonoHaven.Login; using MonoHaven.UI; using MonoHaven.UI.Remote; using MonoHaven.Utils; using NLog; namespace MonoHaven.Game { public class GameScreen : BaseScreen { private static readonly NLog.Logger log = LogManager.GetCurrentClassLogger(); private readonly GameSession session; private readonly TreeDictionary<ushort, Controller> controllers; private readonly WidgetAdapterRegistry adapterRegistry; public GameScreen(GameSession session) { this.session = session; this.controllers = new TreeDictionary<ushort, Controller>(); this.controllers[0] = new Controller(0, session); this.controllers[0].Bind(RootWidget, new RootAdapter()); this.adapterRegistry = new WidgetAdapterRegistry(session); } public EventHandler Closed; public void Close() { App.Instance.QueueOnMainThread(() => Host.SetScreen(new LoginScreen())); } public void CreateWidget(ushort id, string type, Point location, ushort parentId, object[] args) { var parent = FindController(parentId); if (parent == null) throw new Exception( string.Format("Non-existent parent widget {0} for {1}", parentId, id)); var adapter = adapterRegistry.Get(type); var widget = adapter.Create(parent.Widget, args); widget.SetLocation(location); var ctl = new Controller(id, parent); ctl.Bind(widget, adapter); controllers[id] = ctl; } public void MessageWidget(ushort id, string message, object[] args) { var ctl = FindController(id); if (ctl == null) { log.Warn("UI message {1} to non-existent widget {0}", id, message); return; } ctl.HandleRemoteMessage(message, args); } public void DestroyWidget(ushort id) { Controller ctl; if (controllers.Remove(id, out ctl)) { ctl.Dispose(); foreach (var child in ctl.Children) DestroyWidget(child.Id); return; } log.Warn("Try to remove non-existent widget {0}", id); } protected override void OnClose() { Closed.Raise(this, EventArgs.Empty); } private Controller FindController(ushort id) { Controller ctl; return controllers.Find(ref id, out ctl) ? ctl : null; } } }
mit
C#
f1fd28181dbc1db2c93efeddb982085c2f0bbcca
Remove redundant code
k-t/SharpHaven
MonoHaven.Client/Graphics/Avatar.cs
MonoHaven.Client/Graphics/Avatar.cs
using System.Collections.Generic; using System.Linq; using MonoHaven.Resources; using MonoHaven.Utils; namespace MonoHaven.Graphics { public class Avatar : Drawable { private readonly Texture tex; public Avatar(IEnumerable<FutureResource> layers) { var images = layers.SelectMany(x => x.Value.GetLayers<ImageData>()); using (var bitmap = ImageUtils.Combine(images)) tex = new Texture(bitmap); Width = tex.Width; Height = tex.Height; } public override void Draw(SpriteBatch batch, int x, int y, int w, int h) { tex.Draw(batch, x, y, w, h); } public override void Dispose() { if (tex != null) tex.Dispose(); } } }
using System.Collections.Generic; using System.Linq; using MonoHaven.Resources; using MonoHaven.Utils; namespace MonoHaven.Graphics { public class Avatar : Drawable { private readonly Texture tex; public Avatar(IEnumerable<FutureResource> layers) { var images = layers .SelectMany(x => x.Value.GetLayers<ImageData>()) .OrderBy(x => x.Z); using (var bitmap = ImageUtils.Combine(images)) tex = new Texture(bitmap); Width = tex.Width; Height = tex.Height; } public override void Draw(SpriteBatch batch, int x, int y, int w, int h) { tex.Draw(batch, x, y, w, h); } public override void Dispose() { if (tex != null) tex.Dispose(); } } }
mit
C#
de498f264121c5fefd2107a9888933890dedfef3
Update to test harness
ArasExtensions/Aras.Model
Aras.Model.Design.Debug/Program.cs
Aras.Model.Design.Debug/Program.cs
/* Aras.Model provides a .NET cient library for Aras Innovator Copyright (C) 2015 Processwall Limited. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://opensource.org/licenses/AGPL-3.0. Company: Processwall Limited Address: The Winnowing House, Mill Lane, Askham Richard, York, YO23 3NW, United Kingdom Tel: +44 113 815 3440 Email: support@processwall.com */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Aras.Model; using System.IO; namespace Aras.Model.Design.Debug { class Program { static void Main(string[] args) { // Connect to Server Model.Server server = new Model.Server("http://localhost/11SP9"); // Load Solution server.LoadAssembly("Aras.Model.Design"); // Get Database Model.Database database = server.Database("Development"); // Start Session Model.Session session = database.Login("admin", IO.Server.PasswordHash("innovator")); // Find Document Model.Design.Document document = (Model.Design.Document)session.Store("Document").Get("17E4C652AF9D49AAA7EFFBF489D47CF7"); // Check if Update is possible if (document.CanUpdate) { // Start Transaction using (Transaction trans = session.BeginTransaction()) { // Lock Document for Update document.Update(trans); // Update Properties document.Property("description").Value = "New Description"; // Commit all Changes trans.Commit(true); } } // Build Three Level Assembly using (Transaction trans = session.BeginTransaction()) { Model.Item part1 = session.Store("Part").Create(trans); part1.Property("item_number").Value = "1234"; Model.Item part2 = session.Store("Part").Create(trans); part2.Property("item_number").Value = "1235"; part2.Store("Part BOM").Create(part1, trans); Model.Item part3 = session.Store("Part").Create(trans); part3.Property("item_number").Value = "1236"; part3.Store("Part BOM").Create(part2, trans); // Commit all Changes trans.Commit(true); } } } }
/* Aras.Model provides a .NET cient library for Aras Innovator Copyright (C) 2015 Processwall Limited. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://opensource.org/licenses/AGPL-3.0. Company: Processwall Limited Address: The Winnowing House, Mill Lane, Askham Richard, York, YO23 3NW, United Kingdom Tel: +44 113 815 3440 Email: support@processwall.com */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Aras.Model; using System.IO; namespace Aras.Model.Design.Debug { class Program { static void Main(string[] args) { // Connect to Server Model.Server server = new Model.Server("http://localhost/11SP9"); server.LoadAssembly("Aras.Model.Design"); Model.Database database = server.Database("Development"); Model.Session session = database.Login("admin", IO.Server.PasswordHash("innovator")); Model.Design.Document document = (Model.Design.Document)session.Store("Document").Get("17E4C652AF9D49AAA7EFFBF489D47CF7"); using (Transaction trans = session.BeginTransaction()) { document.Update(trans); trans.Commit(true); } } } }
apache-2.0
C#
8f76dc4e3f99a8f540466ead4a0d3fe5160e4f27
Update BestHTTP example
Mazyod/PhoenixSharp
Vendor/BestHTTP/BestHTTPWebsocket.cs
Vendor/BestHTTP/BestHTTPWebsocket.cs
using System; using Phoenix; using BestHTTP.WebSocket; namespace Networking { public sealed class BestHTTPWebsocketFactory: IWebsocketFactory { public IWebsocket Build(WebsocketConfiguration config) { var websocket = new WebSocket(config.uri); websocket.InternalRequest.ConnectTimeout = TimeSpan.FromSeconds(8); var adapter = new BestHTTPWebsocketAdapter(websocket); websocket.OnOpen += (_) => config.onOpenCallback(adapter); websocket.OnClosed += (_, code, message) => config.onCloseCallback(adapter, code, message); websocket.OnError += (_, message) => config.onErrorCallback(adapter, message); websocket.OnMessage += (_, msg) => config.onMessageCallback(adapter, msg); return adapter; } } sealed class BestHTTPWebsocketAdapter: IWebsocket { public WebSocket ws { get; private set; } public WebsocketState state { get { return ws.State switch { WebSocketStates.Connecting => WebsocketState.Connecting, WebSocketStates.Open => WebsocketState.Open, WebSocketStates.Closing => WebsocketState.Closing, _ => WebsocketState.Closed, }; } } public BestHTTPWebsocketAdapter(WebSocket ws) { this.ws = ws; } public void Connect() => ws.Open(); public void Send(string message) => ws.Send(message); public void Close(ushort? code = null, string message = null) { if (code.HasValue) { ws.Close(code.Value, message); } else { ws.Close(); } } } }
using System; using Phoenix; using BestHTTP.WebSocket; public sealed class BestHTTPWebsocketFactory: IWebsocketFactory { public IWebsocket Build(WebsocketConfiguration config) { var websocket = new WebSocket(config.uri); websocket.InternalRequest.ConnectTimeout = TimeSpan.FromSeconds(8); var adapter = new BestHTTPWebsocketAdapter(websocket); websocket.OnOpen += (_) => config.onOpenCallback(adapter); websocket.OnClosed += (_, code, message) => config.onCloseCallback(adapter, code, message); websocket.OnErrorDesc += (_, message) => config.onErrorCallback(adapter, message); websocket.OnMessage += (_, msg) => config.onMessageCallback(adapter, msg); return adapter; } } sealed class BestHTTPWebsocketAdapter: IWebsocket { public WebSocket ws { get; private set; } public BestHTTPWebsocketAdapter(WebSocket ws) { this.ws = ws; } public void Connect() { ws.Open(); } public void Send(string message) { ws.Send(message); } public void Close(ushort? code = null, string message = null) { if (code.HasValue) { ws.Close(code.Value, message); } else { ws.Close(); } } }
mit
C#
e49f61e1251b4ba471c6489d6ccfa7da30b7f1b9
Make the DataAccessProviders class public
andrewjk/Watsonia.Data
Watsonia.Data/DataAccessProviders.cs
Watsonia.Data/DataAccessProviders.cs
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace Watsonia.Data { /// <summary> /// Provides access to the data access providers for different database systems. /// </summary> public static class DataAccessProviders { private static string _providerPath; private static List<IDataAccessProvider> _providers = null; /// <summary> /// Gets or sets the path in which to look for provider assemblies. /// </summary> /// <value> /// The provider path. /// </value> public static string ProviderPath { get { return _providerPath; } set { _providerPath = value; } } /// <summary> /// Gets the data access providers that have been placed in the provider path. /// </summary> /// <value> /// The providers. /// </value> [ImportMany(typeof(IDataAccessProvider))] public static List<IDataAccessProvider> Providers { get { if (_providers == null) { LoadProviders(); } return _providers; } } /// <summary> /// Initializes the <see cref="DataAccessProviders" /> class. /// </summary> static DataAccessProviders() { // Default to the directory containing the executing assembly _providerPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } private static void LoadProviders() { // Scan through the supplied directory and get the assemblies var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new DirectoryCatalog(_providerPath)); CompositionContainer container = new CompositionContainer(catalog); _providers = container.GetExportedValues<IDataAccessProvider>().ToList(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace Watsonia.Data { /// <summary> /// Provides access to the data access providers for different database systems. /// </summary> internal static class DataAccessProviders { private static string _providerPath; private static List<IDataAccessProvider> _providers = null; /// <summary> /// Gets or sets the path in which to look for provider assemblies. /// </summary> /// <value> /// The provider path. /// </value> public static string ProviderPath { get { return _providerPath; } set { _providerPath = value; } } /// <summary> /// Gets the data access providers that have been placed in the provider path. /// </summary> /// <value> /// The providers. /// </value> [ImportMany(typeof(IDataAccessProvider))] public static List<IDataAccessProvider> Providers { get { if (_providers == null) { LoadProviders(); } return _providers; } } /// <summary> /// Initializes the <see cref="DataAccessProviders" /> class. /// </summary> static DataAccessProviders() { // Default to the directory containing the executing assembly _providerPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } private static void LoadProviders() { // Scan through the supplied directory and get the assemblies var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new DirectoryCatalog(_providerPath)); CompositionContainer container = new CompositionContainer(catalog); _providers = container.GetExportedValues<IDataAccessProvider>().ToList(); } } }
mit
C#
b37fb781193a12a00a1110c82324cc00bf97be03
Fix typo in identity service
TheTree/branch,TheTree/branch,TheTree/branch
dotnet/Apps/ServiceIdentity/Startup.cs
dotnet/Apps/ServiceIdentity/Startup.cs
using Apollo; using Branch.Apps.ServiceIdentity.App; using Branch.Apps.ServiceIdentity.Models; using Branch.Apps.ServiceIdentity.Server; using Branch.Apps.ServiceIdentity.Services; using Branch.Clients.Token; using Branch.Packages.Contracts.ServiceIdentity; using Branch.Packages.Enums.ServiceIdentity; using Branch.Packages.Models.Common.Config; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Branch.Apps.ServiceIdentity { public class Startup : ApolloStartup<Config> { public Startup(IHostingEnvironment environment) : base(environment, "service-identity") { var tokenConfig = Configuration.Services["Token"]; var tokenClient = new TokenClient(tokenConfig.Url, tokenConfig.Key); var xblClient = new XboxLiveClient(tokenClient); var identityMapper = new IdentityMapper(xblClient); var app = new Application(tokenClient, identityMapper); var rpc = new RPC(app); RpcRegistration<RPC>(rpc); RegisterMethod<ReqGetXboxLiveIdentity, ResGetXboxLiveIdentity>("get_xboxlive_identity", "2018-08-19", rpc.GetXboxLiveIdentity, rpc.GetXboxLiveIdentitySchema); } public static async Task Main(string[] args) => await new WebHostBuilder() .UseKestrel() .UseStartup<Startup>() .Build() .RunAsync(); } }
using Apollo; using Branch.Apps.ServiceIdentity.App; using Branch.Apps.ServiceIdentity.Models; using Branch.Apps.ServiceIdentity.Server; using Branch.Apps.ServiceIdentity.Services; using Branch.Clients.Token; using Branch.Packages.Contracts.ServiceIdentity; using Branch.Packages.Enums.ServiceIdentity; using Branch.Packages.Models.Common.Config; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Branch.Apps.ServiceIdentity { public class Startup : ApolloStartup<Config> { public Startup(IHostingEnvironment environment) : base(environment, "service-identity") { var tokenConfig = Configuration.Services["Tokem"]; var tokenClient = new TokenClient(tokenConfig.Url, tokenConfig.Key); var xblClient = new XboxLiveClient(tokenClient); var identityMapper = new IdentityMapper(xblClient); var app = new Application(tokenClient, identityMapper); var rpc = new RPC(app); RpcRegistration<RPC>(rpc); RegisterMethod<ReqGetXboxLiveIdentity, ResGetXboxLiveIdentity>("get_xboxlive_identity", "2018-08-19", rpc.GetXboxLiveIdentity, rpc.GetXboxLiveIdentitySchema); } public static async Task Main(string[] args) => await new WebHostBuilder() .UseKestrel() .UseStartup<Startup>() .Build() .RunAsync(); } }
mit
C#
7560c8e449232d929cf65cb4297b05f7ee342678
Package Update #CHANGE: Pushed AdamsLair.WinForms 1.1.14
AdamsLair/winforms
WinForms/Properties/AssemblyInfo.cs
WinForms/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AdamsLair.WinForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdamsLair.WinForms")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.14")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AdamsLair.WinForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdamsLair.WinForms")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.13")]
mit
C#
3648108648825f40dedefff6c48b4d2f327544d1
Build 22 preparation
DeathCradle/Terraria-s-Dedicated-Server-Mod,DeathCradle/Terraria-s-Dedicated-Server-Mod,DeathCradle/Terraria-s-Dedicated-Server-Mod,DeathCradle/Terraria-s-Dedicated-Server-Mod
Terraria_Server/Server/Statics.cs
Terraria_Server/Server/Statics.cs
using System; using System.IO; namespace Terraria_Server { public static class Statics { public const int BUILD = 22; public const int CURRENT_TERRARIA_RELEASE = 12; private const String WORLDS = "Worlds"; private const String PLAYERS = "Players"; private const String PLUGINS = "Plugins"; private const String DATA = "Data"; public static bool cmdMessages = true; public static bool debugMode = false; public static bool keepRunning = false; public static bool IsActive = false; public static bool serverStarted = false; public static String SavePath = Environment.CurrentDirectory; public static String WorldPath { get { return SavePath + Path.DirectorySeparatorChar + WORLDS; } } public static String PlayerPath { get { return SavePath + Path.DirectorySeparatorChar + PLAYERS; } } public static String PluginPath { get { return SavePath + Path.DirectorySeparatorChar + PLUGINS; } } public static String DataPath { get { return SavePath + Path.DirectorySeparatorChar + DATA; } } } }
using System; using System.IO; namespace Terraria_Server { public static class Statics { public const int BUILD = 21; public const int CURRENT_TERRARIA_RELEASE = 12; private const String WORLDS = "Worlds"; private const String PLAYERS = "Players"; private const String PLUGINS = "Plugins"; private const String DATA = "Data"; public static bool cmdMessages = true; public static bool debugMode = false; public static bool keepRunning = false; public static bool IsActive = false; public static bool serverStarted = false; public static String SavePath = Environment.CurrentDirectory; public static String WorldPath { get { return SavePath + Path.DirectorySeparatorChar + WORLDS; } } public static String PlayerPath { get { return SavePath + Path.DirectorySeparatorChar + PLAYERS; } } public static String PluginPath { get { return SavePath + Path.DirectorySeparatorChar + PLUGINS; } } public static String DataPath { get { return SavePath + Path.DirectorySeparatorChar + DATA; } } } }
mit
C#
c37f2361beb433f3547d6b8037bb57a965b61676
remove debugging code
p-org/PSharp
Tools/Testing/Replayer/Program.cs
Tools/Testing/Replayer/Program.cs
//----------------------------------------------------------------------- // <copyright file="Program.cs"> // Copyright (c) Microsoft Corporation. All rights reserved. // // 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. // </copyright> //----------------------------------------------------------------------- using System; using Microsoft.PSharp.Utilities; namespace Microsoft.PSharp { /// <summary> /// The P# trace replayer. /// </summary> class Program { static void Main(string[] args) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); // Parses the command line options to get the configuration. var configuration = new ReplayerCommandLineOptions(args).Parse(); // Creates and starts a replaying process. ReplayingProcess.Create(configuration).Start(); IO.PrintLine(". Done"); } /// <summary> /// Handler for unhandled exceptions. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) { var ex = (Exception)args.ExceptionObject; IO.Debug(ex.Message); IO.Debug(ex.StackTrace); IO.Error.ReportAndExit("internal failure: {0}: {1}", ex.GetType().ToString(), ex.Message); } } }
//----------------------------------------------------------------------- // <copyright file="Program.cs"> // Copyright (c) Microsoft Corporation. All rights reserved. // // 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. // </copyright> //----------------------------------------------------------------------- using System; using Microsoft.PSharp.Utilities; namespace Microsoft.PSharp { /// <summary> /// The P# trace replayer. /// </summary> class Program { static void Main(string[] args) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); System.Diagnostics.Debugger.Launch(); // Parses the command line options to get the configuration. var configuration = new ReplayerCommandLineOptions(args).Parse(); // Creates and starts a replaying process. ReplayingProcess.Create(configuration).Start(); IO.PrintLine(". Done"); } /// <summary> /// Handler for unhandled exceptions. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) { var ex = (Exception)args.ExceptionObject; IO.Debug(ex.Message); IO.Debug(ex.StackTrace); IO.Error.ReportAndExit("internal failure: {0}: {1}", ex.GetType().ToString(), ex.Message); } } }
mit
C#
fea9207c82e233adf214c9e99254236a114a82fe
Add comments to ApplicationOptions
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
bindings/src/ApplicationOptions.cs
bindings/src/ApplicationOptions.cs
using System.Text; namespace Urho { /// <summary> /// Application options, see full description at: /// http://urho3d.github.io/documentation/1.4/_running.html /// </summary> public class ApplicationOptions { /// <summary> /// Desktop only /// </summary> public int Width { get; set; } = 0; /// <summary> /// Desktop only /// </summary> public int Height { get; set; } = 0; /// <summary> /// Desktop only /// </summary> public bool WindowedMode { get; set; } = true; /// <summary> /// Desktop only /// </summary> public bool ResizableWindow { get; set; } = false; /// <summary> /// With limit enabled: 200 fps for Desktop (and always 60 fps for mobile despite of the flag) /// </summary> public bool LimitFps { get; set; } = true; /// <summary> /// iOS only /// </summary> public OrientationType Orientation { get; set; } = OrientationType.Landscape; public enum OrientationType { Landscape, Portrait } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("args");//it will be skipped by Urho; if (WindowedMode) builder.Append(" -w"); if (!LimitFps) builder.Append(" -nolimit"); if (Width > 0) builder.AppendFormat(" -x {0}", Width); if (Height > 0) builder.AppendFormat(" -y {0}", Height); if (ResizableWindow) builder.Append(" -s"); builder.AppendFormat(" -{0}", Orientation.ToString().ToLower()); return builder.ToString(); } // Some predefined: public static ApplicationOptions Default { get; } = new ApplicationOptions(); public static ApplicationOptions PortraitDefault { get; } = new ApplicationOptions { Height = 800, Width = 500, Orientation = OrientationType.Portrait }; } }
using System.Text; namespace Urho { public class ApplicationOptions { // see http://urho3d.github.io/documentation/1.4/_running.html (Command line options) public int Width { get; set; } = 0; public int Height { get; set; } = 0; public bool WindowedMode { get; set; } = true; public bool ResizableWindow { get; set; } = true; public bool LimitFps { get; set; } = true; public OrientationType Orientation { get; set; } = OrientationType.Landscape; public enum OrientationType { Landscape, Portrait } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("args");//it will be skipped by Urho; if (WindowedMode) builder.Append(" -w"); if (!LimitFps) builder.Append(" -nolimit"); if (Width > 0) builder.AppendFormat(" -x {0}", Width); if (Height > 0) builder.AppendFormat(" -y {0}", Height); if (ResizableWindow) builder.Append(" -s"); builder.AppendFormat(" -{0}", Orientation.ToString().ToLower()); return builder.ToString(); } // Some predefined: public static ApplicationOptions Default { get; } = new ApplicationOptions(); public static ApplicationOptions PortraitDefault { get; } = new ApplicationOptions { Height = 800, Width = 500, Orientation = OrientationType.Portrait }; } }
mit
C#
9aa3917755b4832d3d853738e6cb4cd179fe2460
fix extension method call
handcraftsman/Afluistic
src/Afluistic/Commands/ArgumentChecks/IsTheIndexOfAnExistingAccountType.cs
src/Afluistic/Commands/ArgumentChecks/IsTheIndexOfAnExistingAccountType.cs
// * ************************************************************************** // * Copyright (c) Clinton Sheppard <sheppard@cs.unm.edu> // * // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * // * source repository: https://github.com/handcraftsman/Afluistic // * ************************************************************************** using System.Linq; using Afluistic.Domain; using Afluistic.Extensions; using Afluistic.MvbaCore; namespace Afluistic.Commands.ArgumentChecks { public class IsTheIndexOfAnExistingAccountType : IArgumentValidator { public const string IndexDoesNotExistMessageText = "An {0} with that index does not exist."; public Notification Check(ExecutionArguments executionArguments, int argumentIndex) { var argument = executionArguments.Args[argumentIndex]; Statement statement = executionArguments.Statement; if (!statement.AccountTypes.GetIndexedValues().Select(x => x.Index.ToString()).Any(x => x == argument)) { return Notification.ErrorFor(IndexDoesNotExistMessageText, typeof(AccountType).GetSingularUIDescription()); } return Notification.Empty; } } }
// * ************************************************************************** // * Copyright (c) Clinton Sheppard <sheppard@cs.unm.edu> // * // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * // * source repository: https://github.com/handcraftsman/Afluistic // * ************************************************************************** using System.Linq; using Afluistic.Domain; using Afluistic.Extensions; using Afluistic.MvbaCore; namespace Afluistic.Commands.ArgumentChecks { public class IsTheIndexOfAnExistingAccountType : IArgumentValidator { public const string IndexDoesNotExistMessageText = "An {0} with that index does not exist."; public Notification Check(ExecutionArguments executionArguments, int argumentIndex) { var argument = executionArguments.Args[argumentIndex]; Statement statement = executionArguments.Statement; if (!Enumerable.Any<string>(statement.AccountTypes.GetIndexedValues().Select(x => x.Index.ToString()), x => x == argument)) { return Notification.ErrorFor(IndexDoesNotExistMessageText, typeof(AccountType).GetSingularUIDescription()); } return Notification.Empty; } } }
mit
C#