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
7df1e911696261639e4ca19fb14770c0dd23c16f
Change forums schema
drasticactions/AwfulForumsLibrary
AwfulForumsLibrary/Entity/ForumEntity.cs
AwfulForumsLibrary/Entity/ForumEntity.cs
using PropertyChanged; using SQLite.Net.Attributes; using SQLiteNetExtensions.Attributes; namespace AwfulForumsLibrary.Entity { [ImplementPropertyChanged] public class ForumEntity { public string Name { get; set; } public string Location { get; set; } public string Description { get; set; } public int CurrentPage { get; set; } public bool IsSubforum { get; set; } public int TotalPages { get; set; } public int ForumId { get; set; } [PrimaryKey] public int Id { get; set; } [ForeignKey(typeof(ForumCategoryEntity))] public int ForumCategoryEntityId { get; set; } [ForeignKey(typeof(ForumEntity))] public int ParentForumId { get; set; } [ManyToOne] public ForumEntity ParentForum { get; set; } [ManyToOne] public ForumCategoryEntity ForumCategory { get; set; } public bool IsBookmarks { get; set; } } }
using PropertyChanged; using SQLite.Net.Attributes; using SQLiteNetExtensions.Attributes; namespace AwfulForumsLibrary.Entity { [ImplementPropertyChanged] public class ForumEntity { public string Name { get; set; } public string Location { get; set; } public string Description { get; set; } public int CurrentPage { get; set; } public bool IsSubforum { get; set; } public int TotalPages { get; set; } [PrimaryKey] public int ForumId { get; set; } [ForeignKey(typeof(ForumCategoryEntity))] public int ForumCategoryEntityId { get; set; } [ForeignKey(typeof(ForumEntity))] public int ParentForumId { get; set; } [ManyToOne] public ForumEntity ParentForum { get; set; } [ManyToOne] public ForumCategoryEntity ForumCategory { get; set; } public bool IsBookmarks { get; set; } } }
mit
C#
5d0e4f5bafa2f8a2746cc469b04a0ca57d5d1aab
Add the binary logger
xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents
Android/Kotlin/build.cake
Android/Kotlin/build.cake
var TARGET = Argument("t", Argument("target", "ci")); Task("binderate") .Does(() => { var configFile = MakeAbsolute(new FilePath("./config.json")).FullPath; var basePath = MakeAbsolute(new DirectoryPath("./")).FullPath; var exit = StartProcess("xamarin-android-binderator", $"--config=\"{configFile}\" --basepath=\"{basePath}\""); if (exit != 0) throw new Exception($"xamarin-android-binderator exited with code {exit}."); }); Task("native") .Does(() => { var fn = IsRunningOnWindows() ? "gradlew.bat" : "gradlew"; var gradlew = MakeAbsolute((FilePath)("./native/KotlinSample/" + fn)); var exit = StartProcess(gradlew, new ProcessSettings { Arguments = "assemble", WorkingDirectory = "./native/KotlinSample/" }); if (exit != 0) throw new Exception($"Gradle exited with exit code {exit}."); }); Task("externals") .IsDependentOn("binderate") .IsDependentOn("native"); Task("libs") .IsDependentOn("externals") .Does(() => { var settings = new MSBuildSettings() .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .EnableBinaryLogger("./output/libs.binlog") .WithRestore() .WithProperty("DesignTimeBuild", "false") .WithProperty("PackageOutputPath", MakeAbsolute((DirectoryPath)"./output/").FullPath) .WithTarget("Pack"); MSBuild("./generated/Xamarin.Kotlin.sln", settings); }); Task("nuget") .IsDependentOn("libs"); Task("samples") .IsDependentOn("libs") .Does(() => { var settings = new MSBuildSettings() .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .EnableBinaryLogger("./output/samples.binlog") .WithRestore() .WithProperty("DesignTimeBuild", "false"); MSBuild("./samples/KotlinSample.sln", settings); }); Task("clean") .Does(() => { CleanDirectories("./generated/*/bin"); CleanDirectories("./generated/*/obj"); CleanDirectories("./externals/"); CleanDirectories("./generated/"); CleanDirectories("./native/.gradle"); CleanDirectories("./native/**/build"); }); Task("ci") .IsDependentOn("externals") .IsDependentOn("libs") .IsDependentOn("nuget") .IsDependentOn("samples"); RunTarget(TARGET);
var TARGET = Argument("t", Argument("target", "ci")); Task("binderate") .Does(() => { var configFile = MakeAbsolute(new FilePath("./config.json")).FullPath; var basePath = MakeAbsolute(new DirectoryPath("./")).FullPath; var exit = StartProcess("xamarin-android-binderator", $"--config=\"{configFile}\" --basepath=\"{basePath}\""); if (exit != 0) throw new Exception($"xamarin-android-binderator exited with code {exit}."); }); Task("native") .Does(() => { var fn = IsRunningOnWindows() ? "gradlew.bat" : "gradlew"; var gradlew = MakeAbsolute((FilePath)("./native/KotlinSample/" + fn)); var exit = StartProcess(gradlew, new ProcessSettings { Arguments = "assemble", WorkingDirectory = "./native/KotlinSample/" }); if (exit != 0) throw new Exception($"Gradle exited with exit code {exit}."); }); Task("externals") .IsDependentOn("binderate") .IsDependentOn("native"); Task("libs") .IsDependentOn("externals") .Does(() => { var settings = new MSBuildSettings() .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .WithRestore() .WithProperty("DesignTimeBuild", "false") .WithProperty("PackageOutputPath", MakeAbsolute((DirectoryPath)"./output/").FullPath) .WithTarget("Pack"); MSBuild("./generated/Xamarin.Kotlin.sln", settings); }); Task("nuget") .IsDependentOn("libs"); Task("samples") .IsDependentOn("libs") .Does(() => { var settings = new MSBuildSettings() .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .WithRestore() .WithProperty("DesignTimeBuild", "false"); MSBuild("./samples/KotlinSample.sln", settings); }); Task("clean") .Does(() => { CleanDirectories("./generated/*/bin"); CleanDirectories("./generated/*/obj"); CleanDirectories("./externals/"); CleanDirectories("./generated/"); CleanDirectories("./native/.gradle"); CleanDirectories("./native/**/build"); }); Task("ci") .IsDependentOn("externals") .IsDependentOn("libs") .IsDependentOn("nuget") .IsDependentOn("samples"); RunTarget(TARGET);
mit
C#
a4cd04f69f53757e41d1e70d37dc83b8773bf4a5
Add EnumerableUtility.Enumerate
SaberSnail/GoldenAnvil.Utility
GoldenAnvil.Utility/EnumerableUtility.cs
GoldenAnvil.Utility/EnumerableUtility.cs
using System.Collections.Generic; using System.Linq; namespace GoldenAnvil.Utility { public static class EnumerableUtility { public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items) { return new HashSet<T>(items); } public static IEnumerable<T> Append<T>(this IEnumerable<T> items, T value) { foreach (T item in items) yield return item; yield return value; } public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> items) { return items ?? Enumerable.Empty<T>(); } public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> items) { return items.Where(x => x != null); } public static IEnumerable<T> Enumerate<T>(params T[] items) { return items; } } }
using System.Collections.Generic; using System.Linq; namespace GoldenAnvil.Utility { public static class EnumerableUtility { public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items) { return new HashSet<T>(items); } public static IEnumerable<T> Append<T>(this IEnumerable<T> items, T value) { foreach (T item in items) yield return item; yield return value; } public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> items) { return items ?? Enumerable.Empty<T>(); } public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> items) { return items.Where(x => x != null); } } }
mit
C#
a9a525c56b173971a96815f8c60847fc5c07547b
make command a bit more concise.
bennidhamma/EmergeTk,bennidhamma/EmergeTk
tools/emergecli/AddColCommand.cs
tools/emergecli/AddColCommand.cs
using System; using Mono.Options; using System.IO; namespace emergecli { [Command(Name="addcol")] public class AddColCommand : ICommand { public const string template = @" DROP PROCEDURE IF EXISTS addcol; delimiter // CREATE PROCEDURE addcol() BEGIN IF NOT EXISTS ( SELECT * FROM information_schema.COLUMNS WHERE COLUMN_NAME='{0}' AND TABLE_NAME='{1}' AND TABLE_SCHEMA=DATABASE() ) THEN ALTER TABLE {1} ADD COLUMN {0} {2} {3}; END IF; END// delimiter ; CALL addcol(); DROP PROCEDURE IF EXISTS addcol; "; public string Table {get; set;} public string ColumnName {get; set;} public string Type {get; set;} public string Suffix {get; set;} private string fileName = null; public string FileName { get { return fileName ?? string.Format ("add_{0}_to_{1}.sql", ColumnName, Table); } set { fileName = value; } } public OptionSet GetOptions (string[] args) { var o = new OptionSet () { {"t|table=", v => this.Table = v}, {"c|column=", v => this.ColumnName = v}, {"T|type=", v => this.Type = v}, {"s|suffix:", v => this.Suffix = v}, {"f|file:", v => this.FileName = v} }; return o; } public bool Validate () { return Table != null && ColumnName != null && Type != null; } public void Run () { File.WriteAllText (FileName, string.Format (template, ColumnName, Table, Type, Suffix)); } } }
using System; using Mono.Options; using System.IO; namespace emergecli { [Command(Name="addcol")] public class AddColCommand : ICommand { public const string template = @" DROP PROCEDURE IF EXISTS addcol; delimiter // CREATE PROCEDURE addcol() BEGIN IF NOT EXISTS ( SELECT * FROM information_schema.COLUMNS WHERE COLUMN_NAME='{0}' AND TABLE_NAME='{1}' AND TABLE_SCHEMA=DATABASE() ) THEN ALTER TABLE {1} ADD COLUMN {0} {2} {3}; END IF; END// delimiter ; CALL addcol(); DROP PROCEDURE IF EXISTS addcol; "; public string Table {get; set;} public string ColumnName {get; set;} public string Type {get; set;} public string Suffix {get; set;} private string fileName = null; public string FileName { get { return fileName ?? string.Format ("add_{0}_to_{1}.sql", ColumnName, Table); } set { fileName = value; } } public AddColCommand () { } public OptionSet GetOptions (string[] args) { var o = new OptionSet () { {"t|table=", v => this.Table = v}, {"c|column=", v => this.ColumnName = v}, {"T|type=", v => this.Type = v}, {"s|suffix:", v => this.Suffix = v}, {"f|file:", v => this.FileName = v} }; return o; } public bool Validate () { return Table != null && ColumnName != null && Type != null; } public void Run () { File.WriteAllText (FileName, string.Format (template, ColumnName, Table, Type, Suffix)); } } }
mit
C#
57ed91d86fcc45a0ac1aadd646d8311de5195dc3
Update metadata resource to use callback instead of console.log
dudzon/Glimpse,flcdrg/Glimpse,gabrielweyer/Glimpse,sorenhl/Glimpse,dudzon/Glimpse,SusanaL/Glimpse,sorenhl/Glimpse,codevlabs/Glimpse,elkingtonmcb/Glimpse,gabrielweyer/Glimpse,rho24/Glimpse,rho24/Glimpse,paynecrl97/Glimpse,flcdrg/Glimpse,Glimpse/Glimpse,paynecrl97/Glimpse,SusanaL/Glimpse,Glimpse/Glimpse,elkingtonmcb/Glimpse,sorenhl/Glimpse,rho24/Glimpse,codevlabs/Glimpse,dudzon/Glimpse,elkingtonmcb/Glimpse,paynecrl97/Glimpse,Glimpse/Glimpse,rho24/Glimpse,paynecrl97/Glimpse,SusanaL/Glimpse,flcdrg/Glimpse,codevlabs/Glimpse,gabrielweyer/Glimpse
source/Glimpse.Core2/Resource/MetadataResource.cs
source/Glimpse.Core2/Resource/MetadataResource.cs
using System.Collections.Generic; using System.Linq; using Glimpse.Core2.Extensibility; using Glimpse.Core2.Framework; using Glimpse.Core2.ResourceResult; namespace Glimpse.Core2.Resource { public class Metadata : IResource { internal const string InternalName = "metadata.js"; private const int CacheDuration = 12960000; //150 days public string Name { get { return InternalName; } } public IEnumerable<string> ParameterKeys { get { return new[] { ResourceParameterKey.VersionNumber, ResourceParameterKey.Callback }; } } public IResourceResult Execute(IResourceContext context) { var metadata = context.PersistanceStore.GetMetadata(); if (metadata == null) return new StatusCodeResourceResult(404); return new JsonResourceResult(metadata, context.Parameters[ResourceParameterKey.Callback], CacheDuration, CacheSetting.Public); } } }
using System.Collections.Generic; using System.Linq; using Glimpse.Core2.Extensibility; using Glimpse.Core2.Framework; using Glimpse.Core2.ResourceResult; namespace Glimpse.Core2.Resource { public class Metadata : IResource { internal const string InternalName = "metadata.js"; private const int CacheDuration = 12960000; //150 days public string Name { get { return InternalName; } } public IEnumerable<string> ParameterKeys { get { return new[] { ResourceParameterKey.VersionNumber }; } } public IResourceResult Execute(IResourceContext context) { var metadata = context.PersistanceStore.GetMetadata(); if (metadata == null) return new StatusCodeResourceResult(404); return new JsonResourceResult(metadata, "console.log", CacheDuration, CacheSetting.Public); } } }
apache-2.0
C#
379dc2c0da1c4f2edf32087e3a6c23b43fe3af65
bump version to 2.0.2
piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker
Piwik.Tracker/Properties/AssemblyInfo.cs
Piwik.Tracker/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PiwikTracker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Piwik")] [assembly: AssemblyProduct("PiwikTracker")] [assembly: AssemblyCopyright("")] [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("8121d06f-a801-42d2-a144-0036a0270bf3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.2")]
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("PiwikTracker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Piwik")] [assembly: AssemblyProduct("PiwikTracker")] [assembly: AssemblyCopyright("")] [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("8121d06f-a801-42d2-a144-0036a0270bf3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.1")]
bsd-3-clause
C#
03c988874d265f92994194a4e290c8c22cf4cf93
Allow sequence ID to wrap around.
mysql-net/MySqlConnector,gitsno/MySqlConnector,gitsno/MySqlConnector,mysql-net/MySqlConnector
src/MySql.Data/Serialization/PacketTransmitter.cs
src/MySql.Data/Serialization/PacketTransmitter.cs
using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace MySql.Data.Serialization { internal sealed class PacketTransmitter { public PacketTransmitter(Stream stream) { m_stream = stream; m_buffer = new byte[256]; } // Starts a new conversation with the server by sending the first packet. public Task SendAsync(PayloadData payload, CancellationToken cancellationToken) { m_sequenceId = 0; return DoSendAsync(payload, cancellationToken); } // Starts a new conversation with the server by receiving the first packet. public Task<PayloadData> ReceiveAsync(CancellationToken cancellationToken) { m_sequenceId = 0; return DoReceiveAsync(cancellationToken); } // Continues a conversation with the server by receiving a response to a packet sent with 'Send' or 'SendReply'. public Task<PayloadData> ReceiveReplyAsync(CancellationToken cancellationToken) => DoReceiveAsync(cancellationToken); // Continues a conversation with the server by sending a reply to a packet received with 'Receive' or 'ReceiveReply'. public Task SendReplyAsync(PayloadData payload, CancellationToken cancellationToken) => DoSendAsync(payload, cancellationToken); private async Task DoSendAsync(PayloadData payload, CancellationToken cancellationToken) { var bytesSent = 0; var data = payload.ArraySegment; const int maxBytesToSend = 16777215; int bytesToSend; do { // break payload into packets of at most (2^24)-1 bytes bytesToSend = Math.Min(data.Count - bytesSent, maxBytesToSend); // write four-byte packet header; https://dev.mysql.com/doc/internals/en/mysql-packet.html SerializationUtility.WriteUInt32((uint) bytesToSend, m_buffer, 0, 3); m_buffer[3] = (byte) m_sequenceId; m_sequenceId++; await m_stream.WriteAsync(m_buffer, 0, 4, cancellationToken); // write payload await m_stream.WriteAsync(data.Array, data.Offset + bytesSent, bytesToSend, cancellationToken); bytesSent += bytesToSend; } while (bytesToSend == maxBytesToSend); } private async Task<PayloadData> DoReceiveAsync(CancellationToken cancellationToken) { await m_stream.ReadExactlyAsync(m_buffer, 0, 4, cancellationToken); int payloadLength = (int) SerializationUtility.ReadUInt32(m_buffer, 0, 3); if (m_buffer[3] != (byte) (m_sequenceId & 0xFF)) throw new InvalidOperationException("Packet received out-of-order."); m_sequenceId++; if (payloadLength > m_buffer.Length) throw new NotSupportedException("TODO: Can't read long payloads."); await m_stream.ReadExactlyAsync(m_buffer, 0, payloadLength, cancellationToken); return new PayloadData(new ArraySegment<byte>(m_buffer, 0, payloadLength)); } readonly Stream m_stream; readonly byte[] m_buffer; int m_sequenceId; } }
using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace MySql.Data.Serialization { internal sealed class PacketTransmitter { public PacketTransmitter(Stream stream) { m_stream = stream; m_buffer = new byte[256]; } // Starts a new conversation with the server by sending the first packet. public Task SendAsync(PayloadData payload, CancellationToken cancellationToken) { m_sequenceId = 0; return DoSendAsync(payload, cancellationToken); } // Starts a new conversation with the server by receiving the first packet. public Task<PayloadData> ReceiveAsync(CancellationToken cancellationToken) { m_sequenceId = 0; return DoReceiveAsync(cancellationToken); } // Continues a conversation with the server by receiving a response to a packet sent with 'Send' or 'SendReply'. public Task<PayloadData> ReceiveReplyAsync(CancellationToken cancellationToken) => DoReceiveAsync(cancellationToken); // Continues a conversation with the server by sending a reply to a packet received with 'Receive' or 'ReceiveReply'. public Task SendReplyAsync(PayloadData payload, CancellationToken cancellationToken) => DoSendAsync(payload, cancellationToken); private async Task DoSendAsync(PayloadData payload, CancellationToken cancellationToken) { var bytesSent = 0; var data = payload.ArraySegment; const int maxBytesToSend = 16777215; int bytesToSend; do { // break payload into packets of at most (2^24)-1 bytes bytesToSend = Math.Min(data.Count - bytesSent, maxBytesToSend); // write four-byte packet header; https://dev.mysql.com/doc/internals/en/mysql-packet.html SerializationUtility.WriteUInt32((uint) bytesToSend, m_buffer, 0, 3); m_buffer[3] = (byte) m_sequenceId; m_sequenceId++; await m_stream.WriteAsync(m_buffer, 0, 4, cancellationToken); // write payload await m_stream.WriteAsync(data.Array, data.Offset + bytesSent, bytesToSend, cancellationToken); bytesSent += bytesToSend; } while (bytesToSend == maxBytesToSend); } private async Task<PayloadData> DoReceiveAsync(CancellationToken cancellationToken) { await m_stream.ReadExactlyAsync(m_buffer, 0, 4, cancellationToken); int payloadLength = (int) SerializationUtility.ReadUInt32(m_buffer, 0, 3); if (m_buffer[3] != m_sequenceId) throw new InvalidOperationException("Packet received out-of-order."); m_sequenceId++; if (payloadLength > m_buffer.Length) throw new NotSupportedException("TODO: Can't read long payloads."); await m_stream.ReadExactlyAsync(m_buffer, 0, payloadLength, cancellationToken); return new PayloadData(new ArraySegment<byte>(m_buffer, 0, payloadLength)); } readonly Stream m_stream; readonly byte[] m_buffer; int m_sequenceId; } }
mit
C#
78b663d0f2ab6f21704f64de0d641c1d6e1ba14e
Move none generic generator to top of file
inputfalken/Sharpy
GeneratorAPI/Generator.cs
GeneratorAPI/Generator.cs
using System; using System.Collections.Generic; namespace GeneratorAPI { public static class Generator { /// <summary> /// <para> /// Contains methods for creating Generators with various Providers. /// </para> /// </summary> public static GeneratorFactory Factory { get; } = new GeneratorFactory(); } /// <summary> /// </summary> /// <typeparam name="TProvider"></typeparam> public class Generator<TProvider> { private readonly TProvider _provider; public Generator(TProvider provider) => _provider = provider; private IEnumerable<TResult> InfiniteEnumerable<TResult>(Func<TProvider, TResult> fn) { while (true) yield return fn(_provider); } /// <summary> /// <para> /// Turn Generator into Generation&lt;TResult&gt; /// </para> /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="fn"></param> /// <returns></returns> public Generation<TResult> Generate<TResult>(Func<TProvider, TResult> fn) => new Generation<TResult>( InfiniteEnumerable(fn)); } /// <summary> /// <para> /// Contains methods for creating Generators with various Providers. /// </para> /// </summary> public class GeneratorFactory { /// <summary> /// <para> /// A Generator using System.Random as provider. /// </para> /// </summary> /// <param name="random"></param> /// <returns></returns> public Generator<Random> RandomGenerator(Random random) => Create(random); /// <summary> /// <para> /// Create a Generator with TProivder as provider. /// </para> /// </summary> /// <typeparam name="TProvider"></typeparam> /// <param name="provider"></param> /// <returns></returns> public Generator<TProvider> Create<TProvider>(TProvider provider) => new Generator<TProvider>(provider); } }
using System; using System.Collections.Generic; namespace GeneratorAPI { /// <summary> /// </summary> /// <typeparam name="TProvider"></typeparam> public class Generator<TProvider> { private readonly TProvider _provider; public Generator(TProvider provider) => _provider = provider; private IEnumerable<TResult> InfiniteEnumerable<TResult>(Func<TProvider, TResult> fn) { while (true) yield return fn(_provider); } /// <summary> /// <para> /// Turn Generator into Generation&lt;TResult&gt; /// </para> /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="fn"></param> /// <returns></returns> public Generation<TResult> Generate<TResult>(Func<TProvider, TResult> fn) => new Generation<TResult>( InfiniteEnumerable(fn)); } public static class Generator { /// <summary> /// <para> /// Contains methods for creating Generators with various Providers. /// </para> /// </summary> public static GeneratorFactory Factory { get; } = new GeneratorFactory(); } /// <summary> /// <para> /// Contains methods for creating Generators with various Providers. /// </para> /// </summary> public class GeneratorFactory { /// <summary> /// <para> /// A Generator using System.Random as provider. /// </para> /// </summary> /// <param name="random"></param> /// <returns></returns> public Generator<Random> RandomGenerator(Random random) => Create(random); /// <summary> /// <para> /// Create a Generator with TProivder as provider. /// </para> /// </summary> /// <typeparam name="TProvider"></typeparam> /// <param name="provider"></param> /// <returns></returns> public Generator<TProvider> Create<TProvider>(TProvider provider) => new Generator<TProvider>(provider); } }
mit
C#
159efe394f24a5935fce623a4f7be6c9a18d26bf
Fix "Countdown" widget "EndDateTime" read only
danielchalmers/DesktopWidgets
DesktopWidgets/Widgets/CountdownClock/Settings.cs
DesktopWidgets/Widgets/CountdownClock/Settings.cs
using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public DateTime EndDateTime { get; set; } = DateTime.Now; } }
using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public DateTime EndDateTime { get; } = DateTime.Now; } }
apache-2.0
C#
e96c52cc9bd4c7f4fe408c1bf5d145f337eab339
Add default database names to connectionfactory.cs
Ackara/Daterpillar
src/Tests.Daterpillar/Helper/ConnectionFactory.cs
src/Tests.Daterpillar/Helper/ConnectionFactory.cs
using System; using System.Data; using System.IO; namespace Tests.Daterpillar.Helper { public static class ConnectionFactory { public static IDbConnection CreateSQLiteConnection(string filePath = "") { if (!File.Exists(filePath)) { filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "daterpillar-test.db3"); System.Data.SQLite.SQLiteConnection.CreateFile(filePath); } var connStr = new System.Data.SQLite.SQLiteConnectionStringBuilder() { DataSource = filePath }; return new System.Data.SQLite.SQLiteConnection(connStr.ConnectionString); } public static IDbConnection CreateMySQLConnection(string database = "daterpillar") { var connStr = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder(ConnectionString.GetMySQLServerConnectionString()); if (!string.IsNullOrEmpty(database)) connStr.Database = database; return new MySql.Data.MySqlClient.MySqlConnection(connStr.ConnectionString); } public static IDbConnection CreateMSSQLConnection(string database = "daterpillar") { var connStr = new System.Data.SqlClient.SqlConnectionStringBuilder(ConnectionString.GetSQLServerConnectionString()); if (!string.IsNullOrEmpty(database)) connStr.Add("database", database); return new System.Data.SqlClient.SqlConnection(connStr.ConnectionString); } } }
using System; using System.Data; using System.IO; namespace Tests.Daterpillar.Helper { public static class ConnectionFactory { public static IDbConnection CreateMySQLConnection(string database = null) { var connStr = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder(""); if (!string.IsNullOrEmpty(database)) connStr.Database = database; return new MySql.Data.MySqlClient.MySqlConnection(connStr.ConnectionString); } public static IDbConnection CreateMSSQLConnection(string database = null) { var connStr = new System.Data.SqlClient.SqlConnectionStringBuilder(""); if (!string.IsNullOrEmpty(database)) connStr.Add("database", database); return new System.Data.SqlClient.SqlConnection(connStr.ConnectionString); } public static IDbConnection CreateSQLiteConnection(string filePath = "") { if (!File.Exists(filePath)) { filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "daterpillar-test.db3"); System.Data.SQLite.SQLiteConnection.CreateFile(filePath); } var connStr = new System.Data.SQLite.SQLiteConnectionStringBuilder() { DataSource = filePath }; return new System.Data.SQLite.SQLiteConnection(connStr.ConnectionString); } } }
mit
C#
1ec046af74d054ffd55240cfc249b8f561d7122c
Add missing flags attribute.
mono/mono-addins,mono/mono-addins
Mono.Addins/Mono.Addins.Description/AddinFlags.cs
Mono.Addins/Mono.Addins.Description/AddinFlags.cs
// AddinFlags.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // using System; namespace Mono.Addins.Description { /// <summary> /// Add-in flags /// </summary> [Flags] public enum AddinFlags { /// <summary> /// No flags /// </summary> None = 0, /// <summary> /// The add-in can't be uninstalled /// </summary> CantUninstall = 1, /// <summary> /// The add-in can't be disabled /// </summary> CantDisable = 2, /// <summary> /// The add-in is not visible to end users /// </summary> Hidden = 4 } }
// AddinFlags.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // using System; namespace Mono.Addins.Description { /// <summary> /// Add-in flags /// </summary> public enum AddinFlags { /// <summary> /// No flags /// </summary> None = 0, /// <summary> /// The add-in can't be uninstalled /// </summary> CantUninstall = 1, /// <summary> /// The add-in can't be disabled /// </summary> CantDisable = 2, /// <summary> /// The add-in is not visible to end users /// </summary> Hidden = 4 } }
mit
C#
85a4c4fb4319b96e8d730b1f15f3140f71599f5f
Remove GC debug setting (#5175)
NeoAdonis/osu,2yangk23/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,johnneijzen/osu,peppy/osu,ZLima12/osu,smoogipoo/osu,peppy/osu,johnneijzen/osu,UselessToucan/osu,ZLima12/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,2yangk23/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu
osu.Game/Overlays/Settings/Sections/Debug/GCSettings.cs
osu.Game/Overlays/Settings/Sections/Debug/GCSettings.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; namespace osu.Game.Overlays.Settings.Sections.Debug { public class GCSettings : SettingsSubsection { protected override string Header => "Garbage Collector"; [BackgroundDependencyLoader] private void load(FrameworkDebugConfigManager config) { Children = new Drawable[] { new SettingsButton { Text = "Force garbage collection", Action = GC.Collect }, }; } } }
// 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.Runtime; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Graphics; namespace osu.Game.Overlays.Settings.Sections.Debug { public class GCSettings : SettingsSubsection { protected override string Header => "Garbage Collector"; private readonly Bindable<LatencyMode> latencyMode = new Bindable<LatencyMode>(); private Bindable<GCLatencyMode> configLatencyMode; [BackgroundDependencyLoader] private void load(FrameworkDebugConfigManager config) { Children = new Drawable[] { new SettingsEnumDropdown<LatencyMode> { LabelText = "Active mode", Bindable = latencyMode }, new SettingsButton { Text = "Force garbage collection", Action = GC.Collect }, }; configLatencyMode = config.GetBindable<GCLatencyMode>(DebugSetting.ActiveGCMode); configLatencyMode.BindValueChanged(mode => latencyMode.Value = (LatencyMode)mode.NewValue, true); latencyMode.BindValueChanged(mode => configLatencyMode.Value = (GCLatencyMode)mode.NewValue); } private enum LatencyMode { Batch = GCLatencyMode.Batch, Interactive = GCLatencyMode.Interactive, LowLatency = GCLatencyMode.LowLatency, SustainedLowLatency = GCLatencyMode.SustainedLowLatency } } }
mit
C#
dc904411c1f0b602265e0d92fdad7092bf860d26
comment out remaining explicit test
dupdob/NFluent,dupdob/NFluent,dupdob/NFluent,NFluent/NFluent,tpierrain/NFluent,tpierrain/NFluent,tpierrain/NFluent,NFluent/NFluent
tests/NFluent.Tests.Internals/NotRelatedTests.cs
tests/NFluent.Tests.Internals/NotRelatedTests.cs
// // -------------------------------------------------------------------------------------------------------------------- // // <copyright file="NotRelatedTests.cs" company=""> // // Copyright 2013 Thomas PIERRAIN // // 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. // // </copyright> // // -------------------------------------------------------------------------------------------------------------------- // ReSharper disable once CheckNamespace namespace NFluent.Tests { using ForDocumentation; using Kernel; using NUnit.Framework; [TestFixture] public class NotRelatedTests { [Test] public void CheckContextWorks() { Assert.IsTrue(CheckContext.DefaulNegated); CheckContext.DefaulNegated = false; try { Assert.IsFalse(CheckContext.DefaulNegated); } finally { CheckContext.DefaulNegated = true; } } #if !NETCOREAPP1_0 [Test] [Explicit("Experimental: to check if negation works")] public void ForceNegationOnAllTest() { if (!CheckContext.DefaulNegated) { return; } CheckContext.DefaulNegated = false; try { RunnerHelper.RunAllTests(false); } finally { CheckContext.DefaulNegated = true; } } #endif } }
// // -------------------------------------------------------------------------------------------------------------------- // // <copyright file="NotRelatedTests.cs" company=""> // // Copyright 2013 Thomas PIERRAIN // // 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. // // </copyright> // // -------------------------------------------------------------------------------------------------------------------- // ReSharper disable once CheckNamespace namespace NFluent.Tests { using ForDocumentation; using Kernel; using NUnit.Framework; [TestFixture] public class NotRelatedTests { [Test] public void CheckContextWorks() { Assert.IsTrue(CheckContext.DefaulNegated); CheckContext.DefaulNegated = false; try { Assert.IsFalse(CheckContext.DefaulNegated); } finally { CheckContext.DefaulNegated = true; } } [Test] [Explicit("Experimental: to check if negation works")] public void ForceNegationOnAllTest() { if (!CheckContext.DefaulNegated) { return; } CheckContext.DefaulNegated = false; try { RunnerHelper.RunAllTests(false); } finally { CheckContext.DefaulNegated = true; } } } }
apache-2.0
C#
028040344a9c2bfcc1cd25d3efad2e8dcf651207
Fix test scene using local beatmap
smoogipoo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu
osu.Game.Tests/Skins/TestSceneBeatmapSkinResources.cs
osu.Game.Tests/Skins/TestSceneBeatmapSkinResources.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 NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.IO.Archives; using osu.Game.Tests.Resources; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Skins { [HeadlessTest] public class TestSceneBeatmapSkinResources : OsuTestScene { [Resolved] private BeatmapManager beatmaps { get; set; } [BackgroundDependencyLoader] private void load() { var imported = beatmaps.Import(new ZipArchiveReader(TestResources.OpenResource("Archives/ogg-beatmap.osz"))).Result; Beatmap.Value = beatmaps.GetWorkingBeatmap(imported.Beatmaps[0]); } [Test] public void TestRetrieveOggSample() => AddAssert("sample is non-null", () => Beatmap.Value.Skin.GetSample(new SampleInfo("sample")) != null); [Test] public void TestRetrieveOggTrack() => AddAssert("track is non-null", () => MusicController.CurrentTrack.IsDummyDevice == false); } }
// 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 NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.IO.Archives; using osu.Game.Tests.Resources; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Skins { [HeadlessTest] public class TestSceneBeatmapSkinResources : OsuTestScene { [Resolved] private BeatmapManager beatmaps { get; set; } private WorkingBeatmap beatmap; [BackgroundDependencyLoader] private void load() { var imported = beatmaps.Import(new ZipArchiveReader(TestResources.OpenResource("Archives/ogg-beatmap.osz"))).Result; beatmap = beatmaps.GetWorkingBeatmap(imported.Beatmaps[0]); } [Test] public void TestRetrieveOggSample() => AddAssert("sample is non-null", () => beatmap.Skin.GetSample(new SampleInfo("sample")) != null); [Test] public void TestRetrieveOggTrack() => AddAssert("track is non-null", () => MusicController.CurrentTrack.IsDummyDevice == false); } }
mit
C#
8115a4bb8fd9e2d53c40b8607c7ad99f0f62e9a0
Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available
NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game/Configuration/DevelopmentOsuConfigManager.cs
osu.Game/Configuration/DevelopmentOsuConfigManager.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.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { LookupKeyBindings = _ => "unknown"; LookupSkinName = _ => "unknown"; } } }
// 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.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { } } }
mit
C#
a01e9aea7be60f7eb916c396ee183f8c86546ba6
add missing dependency to bootstrapper
jorik041/ReactiveTrader,jorik041/ReactiveTrader,abbasmhd/ReactiveTrader,jorik041/ReactiveTrader,abbasmhd/ReactiveTrader,singhdev/ReactiveTrader,AdaptiveConsulting/ReactiveTrader,LeeCampbell/ReactiveTrader,rikoe/ReactiveTrader,HalidCisse/ReactiveTrader,LeeCampbell/ReactiveTrader,AdaptiveConsulting/ReactiveTrader,singhdev/ReactiveTrader,HalidCisse/ReactiveTrader,abbasmhd/ReactiveTrader,abbasmhd/ReactiveTrader,rikoe/ReactiveTrader,mrClapham/ReactiveTrader,HalidCisse/ReactiveTrader,akrisiun/ReactiveTrader,jorik041/ReactiveTrader,mrClapham/ReactiveTrader,LeeCampbell/ReactiveTrader,akrisiun/ReactiveTrader,mrClapham/ReactiveTrader,LeeCampbell/ReactiveTrader,HalidCisse/ReactiveTrader,rikoe/ReactiveTrader,akrisiun/ReactiveTrader,akrisiun/ReactiveTrader,rikoe/ReactiveTrader,singhdev/ReactiveTrader,singhdev/ReactiveTrader,mrClapham/ReactiveTrader
src/Adaptive.ReactiveTrader.Web/Bootstrapper.cs
src/Adaptive.ReactiveTrader.Web/Bootstrapper.cs
using Adaptive.ReactiveTrader.Server.Blotter; using Adaptive.ReactiveTrader.Server.Control; using Adaptive.ReactiveTrader.Server.Execution; using Adaptive.ReactiveTrader.Server.Pricing; using Adaptive.ReactiveTrader.Server.ReferenceData; using Adaptive.ReactiveTrader.Server.Transport; using Autofac; namespace Adaptive.ReactiveTrader.Web { public class Bootstrapper { public IContainer Build() { var builder = new ContainerBuilder(); // pricing builder.RegisterType<PricePublisher>().As<IPricePublisher>().SingleInstance(); builder.RegisterType<PriceFeedSimulator>().As<IPriceFeed>().SingleInstance(); builder.RegisterType<PriceLastValueCache>().As<IPriceLastValueCache>().SingleInstance(); builder.RegisterType<PricingHub>().SingleInstance(); // reference data builder.RegisterType<CurrencyPairRepository>().As<ICurrencyPairRepository>().SingleInstance(); builder.RegisterType<CurrencyPairUpdatePublisher>().As<ICurrencyPairUpdatePublisher>().SingleInstance(); builder.RegisterType<ReferenceDataHub>().SingleInstance(); // execution builder.RegisterType<ExecutionService>().As<IExecutionService>().SingleInstance(); builder.RegisterType<ExecutionHub>().SingleInstance(); // control builder.RegisterType<ControlHub>().SingleInstance(); // blotter builder.RegisterType<BlotterPublisher>().As<IBlotterPublisher>().SingleInstance(); builder.RegisterType<TradeRepository>().As<ITradeRepository>().SingleInstance(); builder.RegisterType<BlotterHub>().SingleInstance(); builder.RegisterType<ContextHolder>().As<IContextHolder>().SingleInstance(); return builder.Build(); } } }
using Adaptive.ReactiveTrader.Server.Blotter; using Adaptive.ReactiveTrader.Server.Execution; using Adaptive.ReactiveTrader.Server.Pricing; using Adaptive.ReactiveTrader.Server.ReferenceData; using Adaptive.ReactiveTrader.Server.Transport; using Autofac; namespace Adaptive.ReactiveTrader.Web { public class Bootstrapper { public IContainer Build() { var builder = new ContainerBuilder(); // pricing builder.RegisterType<PricePublisher>().As<IPricePublisher>().SingleInstance(); builder.RegisterType<PriceFeedSimulator>().As<IPriceFeed>().SingleInstance(); builder.RegisterType<PriceLastValueCache>().As<IPriceLastValueCache>().SingleInstance(); builder.RegisterType<PricingHub>().SingleInstance(); // reference data builder.RegisterType<CurrencyPairRepository>().As<ICurrencyPairRepository>().SingleInstance(); builder.RegisterType<CurrencyPairUpdatePublisher>().As<ICurrencyPairUpdatePublisher>().SingleInstance(); builder.RegisterType<ReferenceDataHub>().SingleInstance(); // execution builder.RegisterType<ExecutionService>().As<IExecutionService>().SingleInstance(); builder.RegisterType<ExecutionHub>().SingleInstance(); // blotter builder.RegisterType<BlotterPublisher>().As<IBlotterPublisher>().SingleInstance(); builder.RegisterType<TradeRepository>().As<ITradeRepository>().SingleInstance(); builder.RegisterType<BlotterHub>().SingleInstance(); builder.RegisterType<ContextHolder>().As<IContextHolder>().SingleInstance(); return builder.Build(); } } }
apache-2.0
C#
8f51fae0d93a2a345f68528462435d6b55b7d994
update comment for ResolveByName attribute.
jkoritzinsky/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,grokys/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,akrisiun/Perspex,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia
src/Avalonia.Controls/ResolveByNameAttribute.cs
src/Avalonia.Controls/ResolveByNameAttribute.cs
using System; namespace Avalonia.Controls { /// <summary> /// Indicates that the property resolves an element by Name or x:Name. /// When applying this to attached properties, ensure to put on both /// the Getter and Setter methods. /// </summary> public class ResolveByNameAttribute : Attribute { } }
using System; namespace Avalonia.Controls { public class ResolveByNameAttribute : Attribute { } }
mit
C#
8023161945bcf7d8dfb2604b6d0c72a9e8f14a73
add meta descr
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Web/Views/Shared/_Layout.cshtml
src/FilterLists.Web/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>@ViewData["Title"] - FilterLists</title> <base href="~/"/> <meta name="description" content="FilterLists is the independent and comprehensive directory of all public filter and hosts lists for advertisements, trackers, malware, and annoyances. Project by Collin M. Barrett."/> <link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true"/> <environment exclude="Development"> <link rel="stylesheet" href="~/dist/site.css" asp-append-version="true"/> </environment> </head> <body> @RenderBody() <script src="~/dist/vendor.js" asp-append-version="true"></script> @RenderSection("scripts", false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>@ViewData["Title"] - FilterLists</title> <base href="~/"/> <link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true"/> <environment exclude="Development"> <link rel="stylesheet" href="~/dist/site.css" asp-append-version="true"/> </environment> </head> <body> @RenderBody() <script src="~/dist/vendor.js" asp-append-version="true"></script> @RenderSection("scripts", false) </body> </html>
mit
C#
35d147f46bbec5ceeb0941711ff5e3457a2b6e45
Fix incorrect namespace name.
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.App/Infrastructure/ExportWrappers.cs
src/GitHub.App/Infrastructure/ExportWrappers.cs
using System.ComponentModel.Composition; using Octokit.Internal; using System; using System.Net.Http; namespace GitHub.Infrastructure { /// <summary> /// Since VS doesn't support dynamic component registration, we have to implement wrappers /// for types we don't control in order to export them. /// </summary> [Export(typeof(IHttpClient))] public class ExportedHttpClient : HttpClientAdapter { public ExportedHttpClient() : base(HttpMessageHandlerFactory.CreateDefault) {} } }
using System.ComponentModel.Composition; using Octokit.Internal; using System; using System.Net.Http; namespace GitHub.Logging { /// <summary> /// Since VS doesn't support dynamic component registration, we have to implement wrappers /// for types we don't control in order to export them. /// </summary> [Export(typeof(IHttpClient))] public class ExportedHttpClient : HttpClientAdapter { public ExportedHttpClient() : base(HttpMessageHandlerFactory.CreateDefault) {} } }
mit
C#
1e28cb9ac2707f554e3d7e961335ba9ef8ba15f0
Change StatusUpdater job to run every hour.
LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform
src/CompetitionPlatform/ScheduledJobs/JobScheduler.cs
src/CompetitionPlatform/ScheduledJobs/JobScheduler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Common.Log; using CompetitionPlatform.Data.AzureRepositories.Log; using Quartz; using Quartz.Impl; namespace CompetitionPlatform.ScheduledJobs { public static class JobScheduler { public static async void Start(string connectionString, ILog log) { var schedFact = new StdSchedulerFactory(); var sched = await schedFact.GetScheduler(); await sched.Start(); var job = JobBuilder.Create<ProjectStatusIpdaterJob>() .WithIdentity("myJob", "group1") .Build(); var trigger = TriggerBuilder.Create() .WithIdentity("myTrigger", "group1") .WithSimpleSchedule(x => x .WithIntervalInHours(1) .RepeatForever()) .Build(); job.JobDataMap["connectionString"] = connectionString; job.JobDataMap["log"] = log; await sched.ScheduleJob(job, trigger); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Common.Log; using CompetitionPlatform.Data.AzureRepositories.Log; using Quartz; using Quartz.Impl; namespace CompetitionPlatform.ScheduledJobs { public static class JobScheduler { public static async void Start(string connectionString, ILog log) { var schedFact = new StdSchedulerFactory(); var sched = await schedFact.GetScheduler(); await sched.Start(); var job = JobBuilder.Create<ProjectStatusIpdaterJob>() .WithIdentity("myJob", "group1") .Build(); var trigger = TriggerBuilder.Create() .WithIdentity("myTrigger", "group1") .WithSimpleSchedule(x => x .WithIntervalInSeconds(50) .RepeatForever()) .Build(); job.JobDataMap["connectionString"] = connectionString; job.JobDataMap["log"] = log; await sched.ScheduleJob(job, trigger); } } }
mit
C#
b18633f85ee169203e980827d2d5fd972a8220b3
Add pickable flag to the SimplePlaneAnnotation.
stevefsp/Lizitt-Unity3D-Utilities
Source/Lizitt/Utils/Core/Editor/SimplePlaneAnnotationEditor.cs
Source/Lizitt/Utils/Core/Editor/SimplePlaneAnnotationEditor.cs
/* * Copyright (c) 2015 Stephen A. Pratt * * 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 UnityEditor; using UnityEngine; namespace com.lizitt.u3d.editor { public static class SimplePlaneAnnotationEditor { private static readonly Vector3 MarkerSize = new Vector3(1, 0.01f, 1); #if UNITY_5_0_0 || UNITY_5_0_1 [DrawGizmo(GizmoType.NotSelected | GizmoType.SelectedOrChild)] #else [DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.InSelectionHierarchy | GizmoType.Pickable)] #endif static void DrawGizmo(SimplePlaneAnnotation item, GizmoType type) { #if UNITY_5_0_0 || UNITY_5_0_1 if (!(AnnotationUtil.drawAlways || (type & GizmoType.SelectedOrChild) != 0)) #else if (!(AnnotationUtil.drawAlways || (type & GizmoType.InSelectionHierarchy) != 0)) #endif return; Gizmos.color = item.Color; Gizmos.matrix = item.transform.localToWorldMatrix; Gizmos.DrawCube(item.PositionOffset, MarkerSize); } } }
/* * Copyright (c) 2015 Stephen A. Pratt * * 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 UnityEditor; using UnityEngine; namespace com.lizitt.u3d.editor { public static class SimplePlaneAnnotationEditor { private static readonly Vector3 MarkerSize = new Vector3(1, 0.01f, 1); #if UNITY_5_0_0 || UNITY_5_0_1 [DrawGizmo(GizmoType.NotSelected | GizmoType.SelectedOrChild)] #else [DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.InSelectionHierarchy)] #endif static void DrawGizmo(SimplePlaneAnnotation item, GizmoType type) { #if UNITY_5_0_0 || UNITY_5_0_1 if (!(AnnotationUtil.drawAlways || (type & GizmoType.SelectedOrChild) != 0)) #else if (!(AnnotationUtil.drawAlways || (type & GizmoType.InSelectionHierarchy) != 0)) #endif return; Gizmos.color = item.Color; Gizmos.matrix = item.transform.localToWorldMatrix; Gizmos.DrawCube(item.PositionOffset, MarkerSize); } } }
mit
C#
6a50c7bde5843d5f0ee625259b9d87c1cd902e86
Fix new office name clearing after adding
aregaz/starcounterdemo,aregaz/starcounterdemo
src/RealEstateAgencyFranchise/CorporationJson.json.cs
src/RealEstateAgencyFranchise/CorporationJson.json.cs
using RealEstateAgencyFranchise.Database; using Starcounter; namespace RealEstateAgencyFranchise { partial class CorporationJson : Json { static CorporationJson() { DefaultTemplate.Offices.ElementType.InstanceType = typeof(AgencyOfficeJson); } void Handle(Input.SaveTrigger action) { Transaction.Commit(); } void Handle(Input.NewOfficeTrigger action) { new Office() { Corporation = this.Data as Corporation, Address = new Address(), Trend = 0, Name = this.NewOfficeName }; this.NewOfficeName = ""; } } }
using RealEstateAgencyFranchise.Database; using Starcounter; namespace RealEstateAgencyFranchise { partial class CorporationJson : Json { static CorporationJson() { DefaultTemplate.Offices.ElementType.InstanceType = typeof(AgencyOfficeJson); } void Handle(Input.SaveTrigger action) { Transaction.Commit(); } void Handle(Input.NewOfficeTrigger action) { new Office() { Corporation = this.Data as Corporation, Address = new Address(), Trend = 0, Name = this.NewOfficeName }; } } }
mit
C#
5e7c91cb36e843edb2880963334e6f2ab1ddb735
Apply SerializableAttribute to custom exception
ritterim/silverpop-dotnet-api,kendaleiv/silverpop-dotnet-api,billboga/silverpop-dotnet-api,kendaleiv/silverpop-dotnet-api
src/Silverpop.Client/TransactClientException.cs
src/Silverpop.Client/TransactClientException.cs
using System; namespace Silverpop.Client { [Serializable] public class TransactClientException : Exception { public TransactClientException() { } public TransactClientException(string message) : base(message) { } public TransactClientException(string message, Exception innerException) : base(message, innerException) { } } }
using System; namespace Silverpop.Client { public class TransactClientException : Exception { public TransactClientException() { } public TransactClientException(string message) : base(message) { } public TransactClientException(string message, Exception innerException) : base(message, innerException) { } } }
mit
C#
51ded03151085f1f3a609108697c1f3b44f11451
fix echant channel resources
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/TemplateSelectors/ChannelLabelDataTemplateSelector.cs
TCC.Core/TemplateSelectors/ChannelLabelDataTemplateSelector.cs
using System.Windows; using System.Windows.Controls; using TCC.Data; namespace TCC.TemplateSelectors { public class ChannelLabelDataTemplateSelector : DataTemplateSelector { public DataTemplate NormalChannelDataTemplate { get; set; } public DataTemplate WhisperChannelDataTemplate { get; set; } public DataTemplate MegaphoneChannelDataTemplate { get; set; } public DataTemplate EnchantChannelDataTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { var m = item as ChatMessage; if (m == null) return null; switch (m.Channel) { case ChatChannel.SentWhisper: case ChatChannel.ReceivedWhisper: return WhisperChannelDataTemplate; case ChatChannel.Megaphone: return MegaphoneChannelDataTemplate; //case ChatChannel.Enchant12: // return EnchantChannelDataTemplate; //case ChatChannel.Enchant15: // return EnchantChannelDataTemplate; default: return NormalChannelDataTemplate; } } } }
using System.Windows; using System.Windows.Controls; using TCC.Data; namespace TCC.TemplateSelectors { public class ChannelLabelDataTemplateSelector : DataTemplateSelector { public DataTemplate NormalChannelDataTemplate { get; set; } public DataTemplate WhisperChannelDataTemplate { get; set; } public DataTemplate MegaphoneChannelDataTemplate { get; set; } public DataTemplate EnchantChannelDataTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { var m = item as ChatMessage; if (m == null) return null; switch (m.Channel) { case ChatChannel.SentWhisper: case ChatChannel.ReceivedWhisper: return WhisperChannelDataTemplate; case ChatChannel.Megaphone: return MegaphoneChannelDataTemplate; case ChatChannel.Enchant12: return EnchantChannelDataTemplate; case ChatChannel.Enchant15: return EnchantChannelDataTemplate; default: return NormalChannelDataTemplate; } } } }
mit
C#
13d05d3f665d6039f4ccbb2c0a9653123909d97b
add Scope.HasVariable()
maul-esel/CobaltAHK,maul-esel/CobaltAHK
CobaltAHK/ExpressionTree/Scope.cs
CobaltAHK/ExpressionTree/Scope.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace CobaltAHK.ExpressionTree { public class Scope { public Scope() : this(null) { LoadBuiltinFunctions(); } public Scope(Scope parentScope) { parent = parentScope; } private void LoadBuiltinFunctions() { var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly; var methods = typeof(IronAHK.Rusty.Core).GetMethods(flags); foreach (var method in methods) { var paramList = method.GetParameters(); if (HasFunction(method.Name) || paramList.Any(p => p.ParameterType.IsByRef)) { continue; // skips byRef and overloads // todo: support overloads! } var prms = paramList.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray(); var types = paramList.Select(p => p.ParameterType).ToList(); types.Add(method.ReturnType); var lambda = Expression.Lambda(Expression.GetFuncType(types.ToArray()), Expression.Call(method, prms), prms); AddFunction(method.Name, lambda); } } protected readonly Scope parent; public bool IsRoot { get { return parent == null; } } protected readonly IDictionary<string, LambdaExpression> functions = new Dictionary<string, LambdaExpression>(); public virtual void AddFunction(string name, LambdaExpression func) { functions[name.ToLower()] = func; } protected virtual bool HasFunction(string name) { return functions.ContainsKey(name.ToLower()); } public virtual LambdaExpression ResolveFunction(string name) { if (HasFunction(name)) { return functions[name.ToLower()]; } else if (parent != null) { return parent.ResolveFunction(name); } throw new FunctionNotFoundException(name); } protected readonly IDictionary<string, ParameterExpression> variables = new Dictionary<string, ParameterExpression>(); public virtual void AddVariable(string name, ParameterExpression variable) { variables[name.ToLower()] = variable; } protected virtual bool HasVariable(string name) { return variables.ContainsKey(name.ToLower()); } public virtual ParameterExpression ResolveVariable(string name) { if (!variables.ContainsKey(name.ToLower())) { AddVariable(name, Expression.Parameter(typeof(object), name)); } return variables[name.ToLower()]; } } public class FunctionNotFoundException : System.Exception { public FunctionNotFoundException(string func) : base("Function '" + func + "' was not found!") { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace CobaltAHK.ExpressionTree { public class Scope { public Scope() : this(null) { LoadBuiltinFunctions(); } public Scope(Scope parentScope) { parent = parentScope; } private void LoadBuiltinFunctions() { var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly; var methods = typeof(IronAHK.Rusty.Core).GetMethods(flags); foreach (var method in methods) { var paramList = method.GetParameters(); if (HasFunction(method.Name) || paramList.Any(p => p.ParameterType.IsByRef)) { continue; // skips byRef and overloads // todo: support overloads! } var prms = paramList.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray(); var types = paramList.Select(p => p.ParameterType).ToList(); types.Add(method.ReturnType); var lambda = Expression.Lambda(Expression.GetFuncType(types.ToArray()), Expression.Call(method, prms), prms); AddFunction(method.Name, lambda); } } protected readonly Scope parent; public bool IsRoot { get { return parent == null; } } protected readonly IDictionary<string, LambdaExpression> functions = new Dictionary<string, LambdaExpression>(); public virtual void AddFunction(string name, LambdaExpression func) { functions[name.ToLower()] = func; } protected virtual bool HasFunction(string name) { return functions.ContainsKey(name.ToLower()); } public virtual LambdaExpression ResolveFunction(string name) { if (HasFunction(name)) { return functions[name.ToLower()]; } else if (parent != null) { return parent.ResolveFunction(name); } throw new FunctionNotFoundException(name); } protected readonly IDictionary<string, ParameterExpression> variables = new Dictionary<string, ParameterExpression>(); public virtual void AddVariable(string name, ParameterExpression variable) { variables[name.ToLower()] = variable; } public virtual ParameterExpression ResolveVariable(string name) { if (!variables.ContainsKey(name.ToLower())) { AddVariable(name, Expression.Parameter(typeof(object), name)); } return variables[name.ToLower()]; } } public class FunctionNotFoundException : System.Exception { public FunctionNotFoundException(string func) : base("Function '" + func + "' was not found!") { } } }
mit
C#
fca5ae088e2c3864cc1e728fba8cfbc7b434bf95
Use NDes.options for binarycache test executable
lucasg/Dependencies,lucasg/Dependencies,lucasg/Dependencies
test/binarycache-test/Program.cs
test/binarycache-test/Program.cs
using System; using System.Diagnostics; using System.Collections.Generic; using Dependencies.ClrPh; using NDesk.Options; namespace Dependencies { namespace Test { class Program { static void ShowHelp(OptionSet p) { Console.WriteLine("Usage: binarycache [options] <FILES_TO_LOAD>"); Console.WriteLine(); Console.WriteLine("Options:"); p.WriteOptionDescriptions(Console.Out); } static void Main(string[] args) { bool is_verbose = false; bool show_help = false; OptionSet opts = new OptionSet() { { "v|verbose", "redirect debug traces to console", v => is_verbose = v != null }, { "h|help", "show this message and exit", v => show_help = v != null }, }; List<string> eps = opts.Parse(args); if (show_help) { ShowHelp(opts); return; } if (is_verbose) { // Redirect debug log to the console Debug.Listeners.Add(new TextWriterTraceListener(Console.Out)); Debug.AutoFlush = true; } // always the first call to make Phlib.InitializePhLib(); BinaryCache.Instance.Load(); foreach ( var peFilePath in eps) { PE Pe = BinaryCache.LoadPe(peFilePath); Console.WriteLine("Loaded PE file : {0:s}", Pe.Filepath); } BinaryCache.Instance.Unload(); } } } }
using System; using System.Diagnostics; using Dependencies.ClrPh; namespace Dependencies { namespace Test { class Program { static void Main(string[] args) { // always the first call to make Phlib.InitializePhLib(); // Redirect debug log to the console Debug.Listeners.Add(new TextWriterTraceListener(Console.Out)); Debug.AutoFlush = true; BinaryCache.Instance.Load(); foreach ( var peFilePath in args ) { PE Pe = BinaryCache.LoadPe(peFilePath); } BinaryCache.Instance.Unload(); } } } }
mit
C#
3bcef6c182601f3c6ea7f556b3d1091f62e5d0c3
Update Program.cs
Metapyziks/Ziks.WebServer
Examples/SimpleExample/Program.cs
Examples/SimpleExample/Program.cs
using System; using System.Reflection; using System.Threading.Tasks; using Ziks.WebServer; namespace SimpleExample { public class Program : IProgram { [STAThread] static void Main( string[] args ) { var server = new Server(); server.AddPrefix( "http://+:8080/" ); server.AddControllers( Assembly.GetExecutingAssembly() ); Task.Run( server.Run ); Console.ReadKey( true ); server.Stop(); } } }
using System; using System.Reflection; using System.Threading.Tasks; using Ziks.WebServer; namespace SimpleExample { public interface IProgram { void WriteLine( string message ); } public class Program : IProgram { [STAThread] static void Main( string[] args ) { var program = new Program(); program.Run(); } public void Run() { var server = new Server(); server.AddPrefix( "http://+:8080/" ); server.Components.Add<IProgram>( this ); server.AddControllers( Assembly.GetExecutingAssembly() ); Task.Run( () => server.Run() ); Console.ReadKey( true ); server.Stop(); } public void WriteLine( string message ) { Console.WriteLine( message ); } } }
mit
C#
fe1e451812fc298a0d591ed374dc03f1cd0f3341
Fix wrong dirtyness propagation
cbovar/ConvNetSharp
src/ConvNetSharp.Flow/Ops/Assign.cs
src/ConvNetSharp.Flow/Ops/Assign.cs
using System; using ConvNetSharp.Volume; namespace ConvNetSharp.Flow.Ops { /// <summary> /// Assignment: valueOp = op /// </summary> /// <typeparam name="T"></typeparam> public class Assign<T> : Op<T> where T : struct, IEquatable<T>, IFormattable { private long _lastComputeStep; public Assign(Op<T> valueOp, Op<T> op) { if (!(valueOp is Variable<T>)) { throw new ArgumentException("Assigned Op should be a Variable", nameof(valueOp)); } AddParent(valueOp); AddParent(op); } public override string Representation => "->"; public override void Differentiate() { throw new NotImplementedException(); } public override Volume<T> Evaluate(Session<T> session) { if(!this.IsDirty) { return base.Evaluate(session); } this.IsDirty = false; this.Result = this.Parents[1].Evaluate(session); ((Variable<T>)this.Parents[0]).SetValue(this.Result); return base.Evaluate(session); } public override string ToString() { return $"({this.Parents[0]} <- {this.Parents[1]})"; } } }
using System; using ConvNetSharp.Volume; namespace ConvNetSharp.Flow.Ops { /// <summary> /// Assignment: valueOp = op /// </summary> /// <typeparam name="T"></typeparam> public class Assign<T> : Op<T> where T : struct, IEquatable<T>, IFormattable { private long _lastComputeStep; public Assign(Op<T> valueOp, Op<T> op) { if (!(valueOp is Variable<T>)) { throw new ArgumentException("Assigned Op should be a Variable", nameof(valueOp)); } AddParent(valueOp); AddParent(op); } public override string Representation => "->"; public override void Differentiate() { throw new NotImplementedException(); } public override Volume<T> Evaluate(Session<T> session) { if (this._lastComputeStep == session.Step) { return this.Parents[0].Evaluate(session); } this._lastComputeStep = session.Step; this.Result = this.Parents[1].Evaluate(session); ((Variable<T>)this.Parents[0]).SetValue(this.Result); return base.Evaluate(session); } } }
mit
C#
a77306567b8ae26bafced6d2b32b9a73c2c42e6c
Swap Dictionary with ConcurrentDictionary in InMemoryBackgroundJobStore
zclmoon/aspnetboilerplate,virtualcca/aspnetboilerplate,andmattia/aspnetboilerplate,verdentk/aspnetboilerplate,verdentk/aspnetboilerplate,AlexGeller/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,ilyhacker/aspnetboilerplate,AlexGeller/aspnetboilerplate,beratcarsi/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,Nongzhsh/aspnetboilerplate,ilyhacker/aspnetboilerplate,virtualcca/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,beratcarsi/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,Nongzhsh/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,zclmoon/aspnetboilerplate,zclmoon/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,andmattia/aspnetboilerplate,beratcarsi/aspnetboilerplate,andmattia/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,Nongzhsh/aspnetboilerplate,luchaoshuai/aspnetboilerplate,virtualcca/aspnetboilerplate,ryancyq/aspnetboilerplate,AlexGeller/aspnetboilerplate
src/Abp/BackgroundJobs/InMemoryBackgroundJobStore.cs
src/Abp/BackgroundJobs/InMemoryBackgroundJobStore.cs
using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Abp.Timing; namespace Abp.BackgroundJobs { /// <summary> /// In memory implementation of <see cref="IBackgroundJobStore"/>. /// It's used if <see cref="IBackgroundJobStore"/> is not implemented by actual persistent store /// and job execution is enabled (<see cref="IBackgroundJobConfiguration.IsJobExecutionEnabled"/>) for the application. /// </summary> public class InMemoryBackgroundJobStore : IBackgroundJobStore { private readonly ConcurrentDictionary<long, BackgroundJobInfo> _jobs; private long _lastId; /// <summary> /// Initializes a new instance of the <see cref="InMemoryBackgroundJobStore"/> class. /// </summary> public InMemoryBackgroundJobStore() { _jobs = new ConcurrentDictionary<long, BackgroundJobInfo>(); } public Task<BackgroundJobInfo> GetAsync(long jobId) { return Task.FromResult(_jobs[jobId]); } public Task InsertAsync(BackgroundJobInfo jobInfo) { jobInfo.Id = Interlocked.Increment(ref _lastId); _jobs[jobInfo.Id] = jobInfo; return Task.FromResult(0); } public Task<List<BackgroundJobInfo>> GetWaitingJobsAsync(int maxResultCount) { var waitingJobs = _jobs.Values .Where(t => !t.IsAbandoned && t.NextTryTime <= Clock.Now) .OrderByDescending(t => t.Priority) .ThenBy(t => t.TryCount) .ThenBy(t => t.NextTryTime) .Take(maxResultCount) .ToList(); return Task.FromResult(waitingJobs); } public Task DeleteAsync(BackgroundJobInfo jobInfo) { _jobs.TryRemove(jobInfo.Id, out _); return Task.FromResult(0); } public Task UpdateAsync(BackgroundJobInfo jobInfo) { if (jobInfo.IsAbandoned) { return DeleteAsync(jobInfo); } return Task.FromResult(0); } } }
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Abp.Timing; namespace Abp.BackgroundJobs { /// <summary> /// In memory implementation of <see cref="IBackgroundJobStore"/>. /// It's used if <see cref="IBackgroundJobStore"/> is not implemented by actual persistent store /// and job execution is enabled (<see cref="IBackgroundJobConfiguration.IsJobExecutionEnabled"/>) for the application. /// </summary> public class InMemoryBackgroundJobStore : IBackgroundJobStore { private readonly Dictionary<long, BackgroundJobInfo> _jobs; private long _lastId; /// <summary> /// Initializes a new instance of the <see cref="InMemoryBackgroundJobStore"/> class. /// </summary> public InMemoryBackgroundJobStore() { _jobs = new Dictionary<long, BackgroundJobInfo>(); } public Task<BackgroundJobInfo> GetAsync(long jobId) { return Task.FromResult(_jobs[jobId]); } public Task InsertAsync(BackgroundJobInfo jobInfo) { jobInfo.Id = Interlocked.Increment(ref _lastId); _jobs[jobInfo.Id] = jobInfo; return Task.FromResult(0); } public Task<List<BackgroundJobInfo>> GetWaitingJobsAsync(int maxResultCount) { var waitingJobs = _jobs.Values .Where(t => !t.IsAbandoned && t.NextTryTime <= Clock.Now) .OrderByDescending(t => t.Priority) .ThenBy(t => t.TryCount) .ThenBy(t => t.NextTryTime) .Take(maxResultCount) .ToList(); return Task.FromResult(waitingJobs); } public Task DeleteAsync(BackgroundJobInfo jobInfo) { if (!_jobs.ContainsKey(jobInfo.Id)) { return Task.FromResult(0); } _jobs.Remove(jobInfo.Id); return Task.FromResult(0); } public Task UpdateAsync(BackgroundJobInfo jobInfo) { if (jobInfo.IsAbandoned) { return DeleteAsync(jobInfo); } return Task.FromResult(0); } } }
mit
C#
4883acbef61dd86afff2b3e1ab486a2943a4fcf0
Update src/Abp/Configuration/Startup/IMultiTenancyConfig.cs
beratcarsi/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,beratcarsi/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate,verdentk/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,beratcarsi/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate
src/Abp/Configuration/Startup/IMultiTenancyConfig.cs
src/Abp/Configuration/Startup/IMultiTenancyConfig.cs
using System.Collections; using Abp.Collections; using Abp.MultiTenancy; namespace Abp.Configuration.Startup { /// <summary> /// Used to configure multi-tenancy. /// </summary> public interface IMultiTenancyConfig { /// <summary> /// Is multi-tenancy enabled? /// Default value: false. /// </summary> bool IsEnabled { get; set; } /// <summary> /// Ignore feature check for host users /// Default value: false. /// </summary> bool IgnoreFeatureCheckForHostUsers { get; set; } /// <summary> /// A list of contributors for tenant resolve process. /// </summary> ITypeList<ITenantResolveContributor> Resolvers { get; } /// <summary> /// TenantId resolve key /// Default value: "Abp.TenantId" /// </summary> string TenantIdResolveKey { get; set; } } }
using System.Collections; using Abp.Collections; using Abp.MultiTenancy; namespace Abp.Configuration.Startup { /// <summary> /// Used to configure multi-tenancy. /// </summary> public interface IMultiTenancyConfig { /// <summary> /// Is multi-tenancy enabled? /// Default value: false. /// </summary> bool IsEnabled { get; set; } /// <summary> /// Ignore feature check for host users /// Default value: false. /// </summary> bool IgnoreFeatureCheckForHostUsers { get; set; } /// <summary> /// A list of contributors for tenant resolve process. /// </summary> ITypeList<ITenantResolveContributor> Resolvers { get; } /// <summary> /// TenantId resolve key, default value is Abp.TenantId /// </summary> string TenantIdResolveKey { get; set; } } }
mit
C#
2cc9326f0b657fb0383633739f98c2dfd1fcd699
Add Clock.SecondsLeftAfterLatestMove
Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training
src/ChessVariantsTraining/Models/Variant960/Clock.cs
src/ChessVariantsTraining/Models/Variant960/Clock.cs
using MongoDB.Bson.Serialization.Attributes; using System.Diagnostics; namespace ChessVariantsTraining.Models.Variant960 { public class Clock { double secondsLimit; Stopwatch stopwatch; TimeControl timeControl; [BsonElement("secondsLeftAfterLatestMove")] public double SecondsLeftAfterLatestMove { get; set; } public Clock(TimeControl tc) { timeControl = tc; secondsLimit = tc.InitialSeconds; SecondsLeftAfterLatestMove = secondsLimit; } public void Start() { stopwatch.Start(); } public void Pause() { stopwatch.Stop(); } public void AddIncrement() { secondsLimit += timeControl.Increment; } public void MoveMade() { Pause(); AddIncrement(); SecondsLeftAfterLatestMove = GetSecondsLeft(); } public double GetSecondsLeft() { return secondsLimit - stopwatch.Elapsed.TotalSeconds; } } }
using System.Diagnostics; namespace ChessVariantsTraining.Models.Variant960 { public class Clock { double secondsLimit; Stopwatch stopwatch; TimeControl timeControl; public Clock(TimeControl tc) { timeControl = tc; secondsLimit = tc.InitialSeconds; } public void Start() { stopwatch.Start(); } public void Pause() { stopwatch.Stop(); } public void AddIncrement() { secondsLimit += timeControl.Increment; } public double GetSecondsLeft() { return secondsLimit - stopwatch.Elapsed.TotalSeconds; } } }
agpl-3.0
C#
4102b5857d71cabae340c069d09cb96e2cfe59e4
Make sure multi-line output works when invoked with <<...>> output templates.
JornWildt/ZimmerBot
ZimmerBot.Core/Request.cs
ZimmerBot.Core/Request.cs
using System.Collections.Generic; using CuttingEdge.Conditions; namespace ZimmerBot.Core { public class Request { public enum EventEnum { Welcome } public string Input { get; set; } public Dictionary<string, string> State { get; set; } public string SessionId { get; set; } public string UserId { get; set; } public string RuleId { get; set; } public string RuleLabel { get; set; } public EventEnum? EventType { get; set; } public string BotId { get; set; } public Request() : this("default", "default") { } public Request(string sessionId, string userId) { Condition.Requires(sessionId, nameof(sessionId)).IsNotNullOrEmpty(); Condition.Requires(userId, nameof(userId)).IsNotNullOrEmpty(); SessionId = sessionId; UserId = userId; } public Request(Request src, string input) { Input = input; State = src.State; SessionId = src.SessionId; UserId = src.UserId; RuleId = src.RuleId; RuleLabel = src.RuleLabel; EventType = src.EventType; BotId = src.BotId; } } }
using System.Collections.Generic; using CuttingEdge.Conditions; namespace ZimmerBot.Core { public class Request { public enum EventEnum { Welcome } public string Input { get; set; } public Dictionary<string, string> State { get; set; } public string SessionId { get; set; } public string UserId { get; set; } public string RuleId { get; set; } public string RuleLabel { get; set; } public EventEnum? EventType { get; set; } public string BotId { get; set; } public Request() : this("default", "default") { } public Request(string sessionId, string userId) { Condition.Requires(sessionId, nameof(sessionId)).IsNotNullOrEmpty(); Condition.Requires(userId, nameof(userId)).IsNotNullOrEmpty(); SessionId = sessionId; UserId = userId; } public Request(Request src, string input) { Input = input; State = src.State; SessionId = src.SessionId; UserId = src.UserId; State = src.State; RuleId = src.RuleId; RuleLabel = src.RuleLabel; } } }
mit
C#
fc9aa4cd88eacd1f3f40c7029be79d0a9232c2fa
Make ConsoleHost internals visible to powershell-tests
JamesWTruher/PowerShell-1,PaulHigin/PowerShell,PaulHigin/PowerShell,bingbing8/PowerShell,PaulHigin/PowerShell,KarolKaczmarek/PowerShell,jsoref/PowerShell,kmosher/PowerShell,PaulHigin/PowerShell,bingbing8/PowerShell,kmosher/PowerShell,kmosher/PowerShell,jsoref/PowerShell,kmosher/PowerShell,TravisEz13/PowerShell,daxian-dbw/PowerShell,TravisEz13/PowerShell,TravisEz13/PowerShell,TravisEz13/PowerShell,kmosher/PowerShell,bmanikm/PowerShell,KarolKaczmarek/PowerShell,jsoref/PowerShell,JamesWTruher/PowerShell-1,bmanikm/PowerShell,KarolKaczmarek/PowerShell,JamesWTruher/PowerShell-1,jsoref/PowerShell,bingbing8/PowerShell,bmanikm/PowerShell,jsoref/PowerShell,bmanikm/PowerShell,KarolKaczmarek/PowerShell,bingbing8/PowerShell,KarolKaczmarek/PowerShell,daxian-dbw/PowerShell,daxian-dbw/PowerShell,bingbing8/PowerShell,bmanikm/PowerShell,daxian-dbw/PowerShell,JamesWTruher/PowerShell-1
src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs
src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs
using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; #if !CORECLR using System.Runtime.ConstrainedExecution; using System.Security.Permissions; #endif [assembly:InternalsVisibleTo("powershell-tests")] [assembly:AssemblyCulture("")] [assembly:NeutralResourcesLanguage("en-US")] #if !CORECLR [assembly:AssemblyConfiguration("")] [assembly:AssemblyInformationalVersionAttribute (@"10.0.10011.16384")] [assembly:ReliabilityContractAttribute(Consistency.MayCorruptAppDomain, Cer.MayFail)] [assembly:AssemblyTitle("Microsoft.PowerShell.ConsoleHost")] [assembly:AssemblyDescription("Microsoft Windows PowerShell Console Host")] [assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5")] [assembly:System.Reflection.AssemblyFileVersion("10.0.10011.16384")] [assembly:AssemblyKeyFileAttribute(@"..\signing\visualstudiopublic.snk")] [assembly:System.Reflection.AssemblyDelaySign(true)] #endif [assembly:System.Runtime.InteropServices.ComVisible(false)] [assembly:System.Reflection.AssemblyVersion("3.0.0.0")] [assembly:System.Reflection.AssemblyProduct("Microsoft (R) Windows (R) Operating System")] [assembly:System.Reflection.AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")] [assembly:System.Reflection.AssemblyCompany("Microsoft Corporation")] internal static class AssemblyStrings { internal const string AssemblyVersion = @"3.0.0.0"; internal const string AssemblyCopyright = "Copyright (C) 2006 Microsoft Corporation. All rights reserved."; }
using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; #if !CORECLR using System.Runtime.ConstrainedExecution; using System.Security.Permissions; #endif [assembly:AssemblyCulture("")] [assembly:NeutralResourcesLanguage("en-US")] #if !CORECLR [assembly:AssemblyConfiguration("")] [assembly:AssemblyInformationalVersionAttribute (@"10.0.10011.16384")] [assembly:ReliabilityContractAttribute(Consistency.MayCorruptAppDomain, Cer.MayFail)] [assembly:AssemblyTitle("Microsoft.PowerShell.ConsoleHost")] [assembly:AssemblyDescription("Microsoft Windows PowerShell Console Host")] [assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5")] [assembly:System.Reflection.AssemblyFileVersion("10.0.10011.16384")] [assembly:AssemblyKeyFileAttribute(@"..\signing\visualstudiopublic.snk")] [assembly:System.Reflection.AssemblyDelaySign(true)] #endif [assembly:System.Runtime.InteropServices.ComVisible(false)] [assembly:System.Reflection.AssemblyVersion("3.0.0.0")] [assembly:System.Reflection.AssemblyProduct("Microsoft (R) Windows (R) Operating System")] [assembly:System.Reflection.AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")] [assembly:System.Reflection.AssemblyCompany("Microsoft Corporation")] internal static class AssemblyStrings { internal const string AssemblyVersion = @"3.0.0.0"; internal const string AssemblyCopyright = "Copyright (C) 2006 Microsoft Corporation. All rights reserved."; }
mit
C#
f1192418c70c1bd8db6a8d05b23f6bf7645f5d5e
remove unused dependency on System.Threading.Tasks
biboudis/LambdaMicrobenchmarking
LambdaMicrobenchmarking/Script.cs
LambdaMicrobenchmarking/Script.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LambdaMicrobenchmarking { public static class Script { public static Script<T> Of<T>(params Tuple<String, Func<T>>[] actions) { return Script<T>.Of(actions); } public static Script<T> Of<T>(String name, Func<T> action) { return Of(Tuple.Create(name, action)); } } public class Script<T> { static public int Iterations { get { return Run<T>.iterations; } set { Run<T>.iterations = value; } } static public int WarmupIterations { get { return Run<T>.warmups; } set { Run<T>.warmups = value; } } public static double MinRunningSecs { get { return Run<T>.minimumSecs; } set { Run<T>.minimumSecs = value; } } private List<Tuple<String, Func<T>>> actions { get; set; } private Script(params Tuple<String, Func<T>>[] actions) { this.actions = actions.ToList(); } public static Script<T> Of(params Tuple<String, Func<T>>[] actions) { return new Script<T>(actions); } public Script<T> Of(String name, Func<T> action) { actions.Add(Tuple.Create(name,action)); return this; } public Script<T> WithHead() { Console.WriteLine(Run<T>.FORMAT, "Benchmark", "Mean", "Mean-Error", "Sdev", "Unit", "Count"); return this; } public Script<T> RunAll() { actions.Select(action => new Run<T>(action)).ToList().ForEach(run => run.Measure()); return this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LambdaMicrobenchmarking { public static class Script { public static Script<T> Of<T>(params Tuple<String, Func<T>>[] actions) { return Script<T>.Of(actions); } public static Script<T> Of<T>(String name, Func<T> action) { return Of(Tuple.Create(name, action)); } } public class Script<T> { static public int Iterations { get { return Run<T>.iterations; } set { Run<T>.iterations = value; } } static public int WarmupIterations { get { return Run<T>.warmups; } set { Run<T>.warmups = value; } } public static double MinRunningSecs { get { return Run<T>.minimumSecs; } set { Run<T>.minimumSecs = value; } } private List<Tuple<String, Func<T>>> actions { get; set; } private Script(params Tuple<String, Func<T>>[] actions) { this.actions = actions.ToList(); } public static Script<T> Of(params Tuple<String, Func<T>>[] actions) { return new Script<T>(actions); } public Script<T> Of(String name, Func<T> action) { actions.Add(Tuple.Create(name,action)); return this; } public Script<T> WithHead() { Console.WriteLine(Run<T>.FORMAT, "Benchmark", "Mean", "Mean-Error", "Sdev", "Unit", "Count"); return this; } public Script<T> RunAll() { actions.Select(action => new Run<T>(action)).ToList().ForEach(run => run.Measure()); return this; } } }
apache-2.0
C#
168baae3d25bf647a61056aa762e6b3c581869b6
update storage size and limit peck
ASOS/woodpecker
src/Woodpecker.Core/Sql/AzureSqlStorageSizePecker.cs
src/Woodpecker.Core/Sql/AzureSqlStorageSizePecker.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Woodpecker.Core.Sql { public class AzureSqlStorageSizePecker : AzureSqlDmvPeckerBase { private const string _query = @" select @@servername [collection_server_name] , db_name() [collection_database_name]      , getutcdate() [collection_time_utc]        , df.file_id  , df.type_desc [file_type_desc] , convert(bigint, df.size) *8 [size_kb] , convert(bigint, df.max_size) *8 [max_size_kb] from sys.database_files df;"; protected override string GetQuery() { return _query; } protected override IEnumerable<string> GetRowKeyFieldNames() { return new[] { "collection_server_name", "collection_database_name", "file_id" }; } protected override string GetUtcTimestampFieldName() { return "collection_time_utc"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Woodpecker.Core.Sql { public class AzureSqlStorageSizePecker : AzureSqlDmvPeckerBase { private const string DatabaseWaitInlineSqlNotSoBad = @"select @@servername [server_name] -- varchar(128) , db_name() [database_name] -- varchar(128) , db_id() [database_id] -- int , getutcdate() [collection_time_utc]                -- datetime , df.file_id -- int , df.type_desc [file_type_desc] -- varchar(60) , convert(bigint, df.size) *8 [size_kb] -- bigint , convert(bigint, df.max_size) *8 [max_size_kb] -- bigint from sys.database_files df; "; protected override string GetQuery() { return DatabaseWaitInlineSqlNotSoBad; } protected override IEnumerable<string> GetRowKeyFieldNames() { return new[] { "server_name", "database_name", "file_id"}; } protected override string GetUtcTimestampFieldName() { return "collection_time_utc"; } } }
mit
C#
d87c31ee01abb55c97a043c43d95a81f7d5f4368
Use PredefinedErrorTypeNames instead of literals
modulexcite/DartVS,DartVS/DartVS,DartVS/DartVS,modulexcite/DartVS,DartVS/DartVS,modulexcite/DartVS
DanTup.DartVS.Vsix/Taggers/ErrorSquiggleTagger.cs
DanTup.DartVS.Vsix/Taggers/ErrorSquiggleTagger.cs
using System; using System.ComponentModel.Composition; using System.Linq; using System.Reactive.Linq; using DanTup.DartAnalysis; using DanTup.DartAnalysis.Json; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace DanTup.DartVS { [Export(typeof(ITaggerProvider))] [ContentType(DartContentTypeDefinition.DartContentType)] [TagType(typeof(ErrorTag))] internal sealed class ErrorSquiggleTagProvider : ITaggerProvider { [Import] ITextDocumentFactoryService textDocumentFactory = null; [Import] DartAnalysisService analysisService = null; public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { return new ErrorSquiggleTagger(buffer, textDocumentFactory, analysisService) as ITagger<T>; } } class ErrorSquiggleTagger : AnalysisNotificationTagger<ErrorTag, AnalysisError, AnalysisErrorsNotification> { public ErrorSquiggleTagger(ITextBuffer buffer, ITextDocumentFactoryService textDocumentFactory, DartAnalysisService analysisService) : base(buffer, textDocumentFactory, analysisService) { this.Subscribe(); } protected override ITagSpan<ErrorTag> CreateTag(AnalysisError error) { // syntax error: red // compiler error: blue // other error: purple // warning: red var squiggleType = error.Severity == AnalysisErrorSeverity.Error ? PredefinedErrorTypeNames.SyntaxError : error.Severity == AnalysisErrorSeverity.Warning ? PredefinedErrorTypeNames.CompilerError : PredefinedErrorTypeNames.OtherError; return new TagSpan<ErrorTag>(new SnapshotSpan(buffer.CurrentSnapshot, error.Location.Offset, error.Location.Length), new ErrorTag(squiggleType, error.Message)); } protected override IDisposable Subscribe(Action<AnalysisErrorsNotification> updateSourceData) { return this.analysisService.AnalysisErrorsNotification.Where(en => en.File == textDocument.FilePath).Subscribe(updateSourceData); } protected override AnalysisError[] GetDataToTag(AnalysisErrorsNotification notification) { return notification.Errors.Where(e => e.Location.File == textDocument.FilePath).ToArray(); } protected override Tuple<int, int> GetOffsetAndLength(AnalysisError data) { return Tuple.Create(data.Location.Offset, data.Location.Length); } } }
using System; using System.ComponentModel.Composition; using System.Linq; using System.Reactive.Linq; using DanTup.DartAnalysis; using DanTup.DartAnalysis.Json; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace DanTup.DartVS { [Export(typeof(ITaggerProvider))] [ContentType(DartContentTypeDefinition.DartContentType)] [TagType(typeof(ErrorTag))] internal sealed class ErrorSquiggleTagProvider : ITaggerProvider { [Import] ITextDocumentFactoryService textDocumentFactory = null; [Import] DartAnalysisService analysisService = null; public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { return new ErrorSquiggleTagger(buffer, textDocumentFactory, analysisService) as ITagger<T>; } } class ErrorSquiggleTagger : AnalysisNotificationTagger<ErrorTag, AnalysisError, AnalysisErrorsNotification> { public ErrorSquiggleTagger(ITextBuffer buffer, ITextDocumentFactoryService textDocumentFactory, DartAnalysisService analysisService) : base(buffer, textDocumentFactory, analysisService) { this.Subscribe(); } protected override ITagSpan<ErrorTag> CreateTag(AnalysisError error) { // syntax error: red // compiler error: blue // other error: purple // warning: red var squiggleType = error.Severity == AnalysisErrorSeverity.Error ? "syntax error" : error.Severity == AnalysisErrorSeverity.Warning ? "compiler error" : "other error"; return new TagSpan<ErrorTag>(new SnapshotSpan(buffer.CurrentSnapshot, error.Location.Offset, error.Location.Length), new ErrorTag(squiggleType, error.Message)); } protected override IDisposable Subscribe(Action<AnalysisErrorsNotification> updateSourceData) { return this.analysisService.AnalysisErrorsNotification.Where(en => en.File == textDocument.FilePath).Subscribe(updateSourceData); } protected override AnalysisError[] GetDataToTag(AnalysisErrorsNotification notification) { return notification.Errors.Where(e => e.Location.File == textDocument.FilePath).ToArray(); } protected override Tuple<int, int> GetOffsetAndLength(AnalysisError data) { return Tuple.Create(data.Location.Offset, data.Location.Length); } } }
mit
C#
aef22f3fd61183a5b7c270d631b204a737965dda
Make minor version a constant
paladique/nodejstools,lukedgr/nodejstools,kant2002/nodejstools,paladique/nodejstools,munyirik/nodejstools,paulvanbrenk/nodejstools,mjbvz/nodejstools,paladique/nodejstools,AustinHull/nodejstools,lukedgr/nodejstools,munyirik/nodejstools,Microsoft/nodejstools,munyirik/nodejstools,mjbvz/nodejstools,paulvanbrenk/nodejstools,kant2002/nodejstools,kant2002/nodejstools,kant2002/nodejstools,Microsoft/nodejstools,mjbvz/nodejstools,lukedgr/nodejstools,AustinHull/nodejstools,kant2002/nodejstools,paladique/nodejstools,paulvanbrenk/nodejstools,lukedgr/nodejstools,Microsoft/nodejstools,AustinHull/nodejstools,paulvanbrenk/nodejstools,munyirik/nodejstools,paladique/nodejstools,mjbvz/nodejstools,Microsoft/nodejstools,mjbvz/nodejstools,lukedgr/nodejstools,munyirik/nodejstools,AustinHull/nodejstools,AustinHull/nodejstools,paulvanbrenk/nodejstools,Microsoft/nodejstools
Nodejs/Product/AssemblyVersion.cs
Nodejs/Product/AssemblyVersion.cs
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System.Reflection; // If you get compiler errors CS0579, "Duplicate '<attributename>' attribute", check your // Properties\AssemblyInfo.cs file and remove any lines duplicating the ones below. // (See also AssemblyInfoCommon.cs in this same directory.) #if !SUPPRESS_COMMON_ASSEMBLY_VERSION [assembly: AssemblyVersion(AssemblyVersionInfo.StableVersion)] #endif [assembly: AssemblyFileVersion(AssemblyVersionInfo.Version)] class AssemblyVersionInfo { // This version string (and the comment for StableVersion) should be // updated manually between major releases (e.g. from 1.0 to 2.0). // Servicing branches and minor releases should retain the value. public const string ReleaseVersion = "1.0"; // This version string (and the comment for Version) should be updated // manually between minor releases (e.g. from 1.0 to 1.1). // Servicing branches and prereleases should retain the value. public const string FileVersion = "1.2"; // This version should never change from "4100.00"; BuildRelease.ps1 // will replace it with a generated value. public const string BuildNumber = "4100.00"; #if DEV14 public const string VSMajorVersion = "14"; const string VSVersionSuffix = "2015"; #elif DEV15 public const string VSMajorVersion = "15"; const string VSVersionSuffix = "15"; #else #error Unrecognized VS Version. #endif public const string VSVersion = VSMajorVersion + ".0"; // Defaults to "1.0.0.(2012|2013|2015)" public const string StableVersion = ReleaseVersion + ".0." + VSVersionSuffix; // Defaults to "1.2.4100.00" public const string Version = FileVersion + "." + BuildNumber; }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System.Reflection; // If you get compiler errors CS0579, "Duplicate '<attributename>' attribute", check your // Properties\AssemblyInfo.cs file and remove any lines duplicating the ones below. // (See also AssemblyInfoCommon.cs in this same directory.) #if !SUPPRESS_COMMON_ASSEMBLY_VERSION [assembly: AssemblyVersion(AssemblyVersionInfo.StableVersion)] #endif [assembly: AssemblyFileVersion(AssemblyVersionInfo.Version)] class AssemblyVersionInfo { // This version string (and the comment for StableVersion) should be // updated manually between major releases (e.g. from 1.0 to 2.0). // Servicing branches and minor releases should retain the value. public const string ReleaseVersion = "1.0"; // This version string (and the comment for StableVersion) should be // updated manually between minor releases. // Servicing branches should retain the value public const string MinorVersion = "0"; // This version string (and the comment for Version) should be updated // manually between minor releases (e.g. from 1.0 to 1.1). // Servicing branches and prereleases should retain the value. public const string FileVersion = "1.2"; // This version should never change from "4100.00"; BuildRelease.ps1 // will replace it with a generated value. public const string BuildNumber = "4100.00"; #if DEV14 public const string VSMajorVersion = "14"; const string VSVersionSuffix = "2015"; #elif DEV15 public const string VSMajorVersion = "15"; const string VSVersionSuffix = "15"; #else #error Unrecognized VS Version. #endif public const string VSVersion = VSMajorVersion + ".0"; // Defaults to "1.0.0.(2012|2013|2015)" public const string StableVersion = ReleaseVersion + "." + MinorVersion + "." + VSVersionSuffix; // Defaults to "1.2.4100.00" public const string Version = FileVersion + "." + BuildNumber; }
apache-2.0
C#
9bf9c6b2871d7ff710063d4056d6da5563c4117b
Fix : Un-Stealth rogues for this quest otherwise the mobs arent aggroed.
TheNoobCompany/LevelingQuestsTNB
Profiles/Quester/Scripts/11661.cs
Profiles/Quester/Scripts/11661.cs
WoWUnit unit = ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead), questObjective.IgnoreNotSelectable, questObjective.IgnoreBlackList, questObjective.AllowPlayerControlled); ObjectManager.Me.UnitAura(115191).TryCancel(); //Remove Stealth from rogue if (unit.IsValid && unit.Position.DistanceTo(questObjective.Position) <=8) { MovementManager.Face(unit); Interact.InteractWith(unit.GetBaseAddress); nManager.Wow.Helpers.Fight.StartFight(unit.Guid); } else { List<Point> liste = new List<Point>(); liste.Add(ObjectManager.Me.Position); liste.Add(questObjective.Position); MovementManager.Go(liste); }
WoWUnit unit = ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead), questObjective.IgnoreNotSelectable, questObjective.IgnoreBlackList, questObjective.AllowPlayerControlled); if (unit.IsValid && unit.Position.DistanceTo(questObjective.Position) <=8) { MovementManager.Face(unit); Interact.InteractWith(unit.GetBaseAddress); nManager.Wow.Helpers.Fight.StartFight(unit.Guid); } else { List<Point> liste = new List<Point>(); liste.Add(ObjectManager.Me.Position); liste.Add(questObjective.Position); MovementManager.Go(liste); }
mit
C#
6b3c88e1488e28255890ef6eb488deb85586c5f2
change measuring method.
Codeer-Software/LambdicSql
Project/Performance/SelectTime.cs
Project/Performance/SelectTime.cs
using Dapper; using LambdicSql; using LambdicSql.SqlServer; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Windows.Forms; namespace Performance { class TableValues { public int IntVal { get; set; } public float FloatVal { get; set; } public double DoubleVal { get; set; } public decimal DecimalVal { get; set; } public string StringVal { get; set; } } class DB { public TableValues TableValues { get; set; } } [TestClass] public class SelectTime { [TestMethod] public void CheckLambdicSql() { var adaptor = new SqlServerAdapter(TestEnvironment.ConnectionString); var times = new List<long>(); for (int i = 0; i < 10; i++) { Stopwatch watch = new Stopwatch(); watch.Start(); var datas = Sql.Query<DB>().SelectFrom(db => db.TableValues).ToExecutor(adaptor).Read().ToList(); watch.Stop(); times.Add(watch.ElapsedMilliseconds); } MessageBox.Show(string.Join(Environment.NewLine, times.Select(e=>e.ToString())) + Environment.NewLine + times.Average().ToString()); } [TestMethod] public void CheckDapper() { using (var connection = new SqlConnection(TestEnvironment.ConnectionString)) { var times = new List<long>(); for (int i = 0; i < 10; i++) { Stopwatch watch = new Stopwatch(); watch.Start(); var datas = connection.Query<TableValues>("select IntVal, FloatVal, DoubleVal, DecimalVal, StringVal from TableValues;").ToList(); watch.Stop(); times.Add(watch.ElapsedMilliseconds); } MessageBox.Show(string.Join(Environment.NewLine, times.Select(e => e.ToString())) + Environment.NewLine + times.Average().ToString()); } } } }
using Dapper; using LambdicSql; using LambdicSql.SqlServer; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Windows.Forms; namespace Performance { class TableValues { public int IntVal { get; set; } public float FloatVal { get; set; } public double DoubleVal { get; set; } public decimal DecimalVal { get; set; } public string StringVal { get; set; } } class DB { public TableValues TableValues { get; set; } } [TestClass] public class SelectTime { [TestMethod] public void CheckLambdicSql() { var executor = Sql.Query<DB>().SelectFrom(db => db.TableValues).ToExecutor(new SqlServerAdapter(TestEnvironment.ConnectionString)); var times = new List<long>(); for (int i = 0; i < 10; i++) { Stopwatch watch = new Stopwatch(); watch.Start(); var datas = executor.Read().ToList(); watch.Stop(); times.Add(watch.ElapsedMilliseconds); } MessageBox.Show(string.Join(Environment.NewLine, times.Select(e=>e.ToString())) + Environment.NewLine + times.Average().ToString()); } [TestMethod] public void CheckDapper() { using (var connection = new SqlConnection(TestEnvironment.ConnectionString)) { var times = new List<long>(); for (int i = 0; i < 10; i++) { Stopwatch watch = new Stopwatch(); watch.Start(); var datas = connection.Query<TableValues>("select IntVal, FloatVal, DoubleVal, DecimalVal, StringVal from TableValues;").ToList(); watch.Stop(); times.Add(watch.ElapsedMilliseconds); } MessageBox.Show(string.Join(Environment.NewLine, times.Select(e => e.ToString())) + Environment.NewLine + times.Average().ToString()); } } } }
mit
C#
bfe837d00f70c2787e42318b712a16e546aba9c5
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
autofac/Autofac.Extras.AttributeMetadata
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#
71ef2ebd4f155cace5712b1f2e6d527142706145
Refactor KeyHelper
danielchalmers/SteamAccountSwitcher
SteamAccountSwitcher/KeyHelper.cs
SteamAccountSwitcher/KeyHelper.cs
using System.Windows.Input; namespace SteamAccountSwitcher { internal static class KeyHelper { public static int KeyToInt(Key key) { switch (key) { case Key.D1: return 1; case Key.D2: return 2; case Key.D3: return 3; case Key.D4: return 4; case Key.D5: return 5; case Key.D6: return 6; case Key.D7: return 7; case Key.D8: return 8; case Key.D9: return 9; case Key.D0: return 10; } return 0; } } }
using System.Windows.Input; namespace SteamAccountSwitcher { internal static class KeyHelper { public static int KeyToInt(Key key) { var num = 0; switch (key) { case Key.D1: num = 1; break; case Key.D2: num = 2; break; case Key.D3: num = 3; break; case Key.D4: num = 4; break; case Key.D5: num = 5; break; case Key.D6: num = 6; break; case Key.D7: num = 7; break; case Key.D8: num = 8; break; case Key.D9: num = 9; break; case Key.D0: num = 10; break; } return num; } } }
mit
C#
fdb7d6e5f40b5c86d6e3b597132663f27fdedbd7
bump version
RainwayApp/warden
Warden/Properties/AssemblyInfo.cs
Warden/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Warden.NET")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rainway, Inc.")] [assembly: AssemblyProduct("Warden.NET")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("69bd1ac4-362a-41d0-8e84-a76064d90b4b")] // 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("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")]
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("Warden.NET")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rainway, Inc.")] [assembly: AssemblyProduct("Warden.NET")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("69bd1ac4-362a-41d0-8e84-a76064d90b4b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")]
apache-2.0
C#
2517146d62b1e6cea55d5ac83b84cd14d2a9710e
Correct home member
alvachien/achihapi
src/hihapi/Controllers/Home/HomeMembersController.cs
src/hihapi/Controllers/Home/HomeMembersController.cs
using System; using System.Linq; using System.IO; using System.Collections.Generic; using Microsoft.AspNetCore.OData.Routing.Controllers; using Microsoft.AspNetCore.OData.Query; using Microsoft.AspNetCore.OData.Results; using Microsoft.AspNetCore.OData.Formatter; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using hihapi.Models; using Microsoft.AspNetCore.Authorization; namespace hihapi.Controllers { public class HomeMembersController : ODataController { private readonly hihDataContext _context; public HomeMembersController(hihDataContext context) { _context = context; } /// GET: /HomeMembers /// <summary> /// Adds support for getting home member, for example: /// /// GET /HomeMembers /// GET /HomeMembers?$filter=Host eq 'abc' /// GET /HomeMembers? /// /// <remarks> [EnableQuery] [Authorize] public IQueryable<HomeMember> Get() { return _context.HomeMembers; } } }
using System; using System.Linq; using System.IO; using System.Collections.Generic; using Microsoft.AspNetCore.OData.Routing.Controllers; using Microsoft.AspNetCore.OData.Query; using Microsoft.AspNetCore.OData.Results; using Microsoft.AspNetCore.OData.Formatter; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using hihapi.Models; using Microsoft.AspNetCore.Authorization; namespace hihapi.Controllers { public class HomeMembersController : ODataController { private readonly hihDataContext _context; public HomeMembersController(hihDataContext context) { _context = context; } /// GET: /HomeMembers /// <summary> /// Adds support for getting home member, for example: /// /// GET /HomeMembers /// GET /HomeMembers?$filter=Host eq 'abc' /// GET /HomeMembers? /// /// <remarks> [EnableQuery] [Authorize] public IQueryable<HomeDefine> Get() { return _context.HomeDefines; } } }
mit
C#
1b0b0e01cf2e5c1f3751fb6b19be7f2808bf1e69
Change indent to 2 spaces
12joan/hangman
hangman.cs
hangman.cs
using System; namespace Hangman { public class Hangman { public static void Main(string[] args) { // char key = Console.ReadKey(true).KeyChar; // var game = new Game("HANG THE MAN"); // bool wasCorrect = game.GuessLetter(key); // Console.WriteLine(wasCorrect.ToString()); // var output = game.ShownWord(); // Console.WriteLine(output); var table = new Table( Console.WindowWidth, // width 2 // spacing ); var output = table.Draw(); Console.WriteLine(output); } } }
using System; namespace Hangman { public class Hangman { public static void Main(string[] args) { // char key = Console.ReadKey(true).KeyChar; // var game = new Game("HANG THE MAN"); // bool wasCorrect = game.GuessLetter(key); // Console.WriteLine(wasCorrect.ToString()); // var output = game.ShownWord(); // Console.WriteLine(output); var table = new Table( Console.WindowWidth, // width 2 // spacing ); var output = table.Draw(); Console.WriteLine(output); } } }
unlicense
C#
c8beb9a949e44304afcb1c5a0332cd9bc0cc76a4
Fix Russian comment
IEVin/PropertyChangedNotificator
src/Core/Properties/AssemblyInfo.cs
src/Core/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Core")] [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("6a968165-a5a8-46cd-b3ac-ccabdc718d28")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Управление общими сведениями о сборке осуществляется с помощью // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Core")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми // для COM-компонентов. Если требуется обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("6a968165-a5a8-46cd-b3ac-ccabdc718d28")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер построения // Редакция // // Можно задать все значения или принять номер построения и номер редакции по умолчанию, // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
ecaf050b609a7dbf10d6b6c33ab9059a15384fdb
Modify translation instructions page per request
BloomBooks/PhotoStoryToBloomConverter,BloomBooks/PhotoStoryToBloomConverter
PhotoStoryToBloomConverter/SpAppMetadata.cs
PhotoStoryToBloomConverter/SpAppMetadata.cs
using System.Collections.Generic; using System.ComponentModel; using System.Text; using PhotoStoryToBloomConverter.Utilities; namespace PhotoStoryToBloomConverter { public enum SpAppMetadataGraphic { [Description("gray-background")] GrayBackground, [Description("front-cover-graphic")] FrontCoverGraphic } public class SpAppMetadata { public SpAppMetadataGraphic Graphic { get; set; } public string ScriptureReference { get; set; } public string TitleIdeasHeading { get; set; } public List<string> TitleIdeas { get; } private const string kIntro = "CONTENT FOR THE TITLE SLIDE (slide #0) in SP APP"; private const string kInstructions = @"INSTRUCTIONS: After ""Graphic="" type either ""gray-background"" or ""front-cover-picture"" in English to indicate your choice for the title slide image. After ""ScriptureReference="" type a Scripture reference or a subtitle for your story in the LWC. After ""TitleIdeasHeading="" type something like ""Ideas for the story title:"" in the LWC. After ""TitleIdea1="" type a sample title in the LWC. (Always complete this line providing a title example.) After ""TitleIdea2="" type another sample title in the LWC. (Or leave this line blank.) After ""TitleIdea3="" type another sample title in the LWC. (Or leave this line blank.)"; public SpAppMetadata(string scriptureReference, string titleIdeasHeading, List<string> titleIdeas) { ScriptureReference = scriptureReference; TitleIdeasHeading = titleIdeasHeading; TitleIdeas = titleIdeas; } public string EnsureOneLine(string possibleMultiLine) { return string.Join("; ", possibleMultiLine.Split('\n')); } public override string ToString() { var sb = new StringBuilder($"{kIntro}\n\n" + $"Graphic={Graphic.ToDescriptionString()}\n" + $"ScriptureReference ={EnsureOneLine(ScriptureReference) }\n" + $"TitleIdeasHeading ={TitleIdeasHeading}" ); for (int i = 0; i < TitleIdeas.Count; i++) sb.Append($"\nTitleIdea{i + 1}={TitleIdeas[i]}"); sb.Append("\n\n"); sb.Append(kInstructions); return sb.ToString(); } } }
using System.Collections.Generic; using System.ComponentModel; using System.Text; using PhotoStoryToBloomConverter.Utilities; namespace PhotoStoryToBloomConverter { public enum SpAppMetadataGraphic { [Description("gray-background")] GrayBackground, [Description("front-cover-graphic")] FrontCoverGraphic } public class SpAppMetadata { public SpAppMetadataGraphic Graphic { get; set; } public string ScriptureReference { get; set; } public string TitleIdeasHeading { get; set; } public List<string> TitleIdeas { get; } private const string kIntro = "Video Title Slide Content"; public SpAppMetadata(string scriptureReference, string titleIdeasHeading, List<string> titleIdeas) { ScriptureReference = scriptureReference; TitleIdeasHeading = titleIdeasHeading; TitleIdeas = titleIdeas; } public string EnsureOneLine(string possibleMultiLine) { return string.Join("; ", possibleMultiLine.Split('\n')); } public override string ToString() { var sb = new StringBuilder($"{kIntro}\n" + $"Graphic={Graphic.ToDescriptionString()}\n" + $"ScriptureReference ={EnsureOneLine(ScriptureReference) }\n" + $"TitleIdeasHeading ={TitleIdeasHeading}" ); for (int i = 0; i < TitleIdeas.Count; i++) sb.Append($"\nTitleIdea{i + 1}={TitleIdeas[i]}"); return sb.ToString(); } } }
mit
C#
fb65aa332bced912b27438d6e2677a52c06ec996
use max camera positions instead of last character position
virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,virtuoushub/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,whoa-algebraic/game-off-2016
Assets/Scripts/CameraFollowPlayer.cs
Assets/Scripts/CameraFollowPlayer.cs
using UnityEngine; using System.Collections; public class CameraFollowPlayer : MonoBehaviour { public Transform PlayerCharacter; public float horizontalEdgeBuffer; public float verticalEdgeBuffer; private int mapTileHorizontalUnits = 4; private int mapTileVerticalUnits = 2; private float unitSize = 5; private float maxLeft; private float maxRight; private float maxTop; private float maxBottom; void Start() { maxLeft = mapTileHorizontalUnits * (unitSize * -1f) + horizontalEdgeBuffer; maxRight = mapTileHorizontalUnits * unitSize - horizontalEdgeBuffer; maxTop = mapTileVerticalUnits * unitSize - verticalEdgeBuffer; maxBottom = mapTileVerticalUnits * (unitSize * -1f) + verticalEdgeBuffer; } void Update () { float playerX = PlayerCharacter.position.x; float playerY = PlayerCharacter.position.y; if(playerX < maxLeft) { playerX = maxLeft; } if(playerX > maxRight) { playerX = maxRight; } if(playerY < maxBottom) { playerY = maxBottom; } if(playerY > maxTop) { playerY = maxTop; } Vector3 newPosition = new Vector3(playerX, playerY, -10); transform.position = newPosition; } }
using UnityEngine; using System.Collections; public class CameraFollowPlayer : MonoBehaviour { public Transform PlayerCharacter; public float horizontalEdgeBuffer; public float verticalEdgeBuffer; private int mapTileHorizontalUnits = 4; private int mapTileVerticalUnits = 2; private float unitSize = 5; private float maxLeft; private float maxRight; private float maxTop; private float maxBottom; private Vector3 lastPosition; void Start() { maxLeft = mapTileHorizontalUnits * (unitSize * -1f) + horizontalEdgeBuffer; maxRight = mapTileHorizontalUnits * unitSize - horizontalEdgeBuffer; maxTop = mapTileVerticalUnits * unitSize - verticalEdgeBuffer; maxBottom = mapTileVerticalUnits * (unitSize * -1f) + verticalEdgeBuffer; } void Update () { float playerX = PlayerCharacter.position.x; float playerY = PlayerCharacter.position.y; Vector3 newPosition = new Vector3(lastPosition.x, lastPosition.y, -10); if(playerX >= maxLeft && playerX <= maxRight) { newPosition.x = playerX; } if(playerY >= maxBottom && playerY <= maxTop) { newPosition.y = playerY; } transform.position = newPosition; lastPosition = newPosition; } }
mit
C#
6d91c0f375369c182312bfde644cae26443339a9
Resolve inspection issue
ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu
osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.cs
osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Difficulty.Evaluators; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; using System.Collections.Generic; using System.Linq; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : OsuStrainSkill { private double skillMultiplier => 1375; private double strainDecayBase => 0.3; private double currentStrain; private double currentRhythm; protected override int ReducedSectionCount => 5; protected override double DifficultyMultiplier => 1.04; private readonly double greatWindow; private readonly List<double> objectStrains = new List<double>(); public Speed(Mod[] mods, double hitWindowGreat) : base(mods) { greatWindow = hitWindowGreat; } private double strainDecay(double ms) => Math.Pow(strainDecayBase, ms / 1000); protected override double CalculateInitialStrain(double time, DifficultyHitObject current) => (currentStrain * currentRhythm) * strainDecay(time - current.Previous(0).StartTime); protected override double StrainValueAt(DifficultyHitObject current) { currentStrain *= strainDecay(((OsuDifficultyHitObject)current).StrainTime); currentStrain += SpeedEvaluator.EvaluateDifficultyOf(current, greatWindow) * skillMultiplier; currentRhythm = RhythmEvaluator.EvaluateDifficultyOf(current, greatWindow); double totalStrain = currentStrain * currentRhythm; objectStrains.Add(totalStrain); return totalStrain; } public double RelevantNoteCount() { if (objectStrains.Count == 0) return 0; double maxStrain = objectStrains.Max(); if (maxStrain == 0) return 0; return objectStrains.Aggregate((total, next) => total + (1.0 / (1.0 + Math.Exp(-(next / maxStrain * 12.0 - 6.0))))); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Difficulty.Evaluators; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; using System.Collections.Generic; using System.Linq; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : OsuStrainSkill { private double skillMultiplier => 1375; private double strainDecayBase => 0.3; private double currentStrain; private double currentRhythm; protected override int ReducedSectionCount => 5; protected override double DifficultyMultiplier => 1.04; private readonly double greatWindow; private List<double> objectStrains = new List<double>(); public Speed(Mod[] mods, double hitWindowGreat) : base(mods) { greatWindow = hitWindowGreat; } private double strainDecay(double ms) => Math.Pow(strainDecayBase, ms / 1000); protected override double CalculateInitialStrain(double time, DifficultyHitObject current) => (currentStrain * currentRhythm) * strainDecay(time - current.Previous(0).StartTime); protected override double StrainValueAt(DifficultyHitObject current) { currentStrain *= strainDecay(((OsuDifficultyHitObject)current).StrainTime); currentStrain += SpeedEvaluator.EvaluateDifficultyOf(current, greatWindow) * skillMultiplier; currentRhythm = RhythmEvaluator.EvaluateDifficultyOf(current, greatWindow); double totalStrain = currentStrain * currentRhythm; objectStrains.Add(totalStrain); return totalStrain; } public double RelevantNoteCount() { if (objectStrains.Count == 0) return 0; double maxStrain = objectStrains.Max(); if (maxStrain == 0) return 0; return objectStrains.Aggregate((total, next) => total + (1.0 / (1.0 + Math.Exp(-(next / maxStrain * 12.0 - 6.0))))); } } }
mit
C#
7756e6a7591f2644ed91eca805d4dbb4efbcf31b
Update IEventTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/IEventTelemeter.cs
TIKSN.Core/Analytics/Telemetry/IEventTelemeter.cs
using System.Collections.Generic; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public interface IEventTelemeter { Task TrackEventAsync(string name); Task TrackEventAsync(string name, IDictionary<string, string> properties); } }
using System.Collections.Generic; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public interface IEventTelemeter { Task TrackEvent(string name); Task TrackEvent(string name, IDictionary<string, string> properties); } }
mit
C#
0ea6e3a9c2477ae09173202fb0e66f70d15cd232
make the sequence add method null safe.
signumsoftware/framework,signumsoftware/framework,avifatal/framework,AlejandroCano/framework,AlejandroCano/framework,avifatal/framework
Signum.Utilities/DataStructures/Sequence.cs
Signum.Utilities/DataStructures/Sequence.cs
using System.Collections.Generic; namespace Signum.Utilities.DataStructures { public class Sequence<T> : List<T> { public void Add(IEnumerable<T> collection) { if (collection != null) { AddRange(collection); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Signum.Utilities.DataStructures { public class Sequence<T> : List<T> { public void Add(IEnumerable<T> collection) { AddRange(collection); } } }
mit
C#
268d1461e786b7e5d5c05916ad4c315f9d71a4b7
update version
prodot/ReCommended-Extension
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2019 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.5.1.0")] [assembly: AssemblyFileVersion("3.5.1")]
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2019 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.5.0.0")] [assembly: AssemblyFileVersion("3.5.0")]
apache-2.0
C#
a1d0a9c2b014d384543a9ec2db3de9568e25bfd4
Add containing type names (for nested classes)
ulrichb/Roflcopter,ulrichb/Roflcopter
Src/Roflcopter.Plugin/ShortNameTypeMemberFqnProvider.cs
Src/Roflcopter.Plugin/ShortNameTypeMemberFqnProvider.cs
using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using JetBrains.Application.DataContext; using JetBrains.ProjectModel; using JetBrains.ReSharper.Features.Environment.CopyFqn; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.DataContext; using JetBrains.UI.Avalon.TreeListView; namespace Roflcopter.Plugin { /// <summary> /// A provider for <see cref="CopyFqnAction"/> which returns <c>[type name].[member]</c>. /// </summary> [SolutionComponent] public class ShortNameTypeMemberFqnProvider : IFqnProvider { public bool IsApplicable([NotNull] IDataContext dataContext) { // Will be called in the CopyFqnAction to determine if _any_ provider has sth. to provide. var typeMembers = GetTypeMembers(dataContext); return typeMembers.Any(); } public IEnumerable<PresentableFqn> GetSortedFqns([NotNull] IDataContext dataContext) { var typeMembers = GetTypeMembers(dataContext); foreach (var typeMember in typeMembers) { var containingType = typeMember.GetContainingType(); if (containingType != null) { var containingTypePath = containingType.PathName(x => x.ShortName, x => x.GetContainingType()); yield return new PresentableFqn($"{containingTypePath}.{typeMember.ShortName}"); } } } public int Priority => -10; // The lower the value, the _higher_ it is ranked. Yes, really. private static IEnumerable<ITypeMember> GetTypeMembers(IDataContext dataContext) { var data = dataContext.GetData(PsiDataConstants.DECLARED_ELEMENTS); if (data == null) return new ITypeMember[0]; return data.OfType<ITypeMember>(); } } }
using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using JetBrains.Application.DataContext; using JetBrains.ProjectModel; using JetBrains.ReSharper.Features.Environment.CopyFqn; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.DataContext; namespace Roflcopter.Plugin { /// <summary> /// A provider for <see cref="CopyFqnAction"/> which returns [type(shortname)].[member(shortname)]. /// </summary> [SolutionComponent] public class ShortNameTypeMemberFqnProvider : IFqnProvider { public bool IsApplicable([NotNull] IDataContext dataContext) { // Will be called in the CopyFqnAction to determine if _any_ provider has sth. to provide. var typeMembers = GetTypeMembers(dataContext); return typeMembers.Any(); } public IEnumerable<PresentableFqn> GetSortedFqns([NotNull] IDataContext dataContext) { var typeMembers = GetTypeMembers(dataContext); foreach (var typeMember in typeMembers) { var containingType = typeMember.GetContainingType(); if (containingType != null) yield return new PresentableFqn($"{containingType.ShortName}.{typeMember.ShortName}"); } } public int Priority => -10; // The lower the value, the _higher_ it is ranked. Yes, really. private static IEnumerable<ITypeMember> GetTypeMembers(IDataContext dataContext) { var data = dataContext.GetData(PsiDataConstants.DECLARED_ELEMENTS); if (data == null) return new ITypeMember[0]; return data.OfType<ITypeMember>(); } } }
mit
C#
df29c9f2de8e6d94f4eef717a8e10e85e01b7dfa
Fix GostKeyValue name
AlexMAS/GostCryptography
Source/GostCryptography/Xml/GostKeyValue.cs
Source/GostCryptography/Xml/GostKeyValue.cs
using System; using System.Security.Cryptography.Xml; using System.Xml; using GostCryptography.Base; namespace GostCryptography.Xml { /// <summary> /// Параметры открытого ключа цифровой подписи ГОСТ Р 34.10. /// </summary> public sealed class GostKeyValue : KeyInfoClause { /// <summary> /// Наименование ключа. /// </summary> public const string NameValue = "urn:ietf:params:xml:ns:cpxmlsec:GOSTKeyValue"; /// <summary> /// Устаревшее наименование ключа. /// </summary> public const string ObsoleteNameValue = "http://www.w3.org/2000/09/xmldsig# KeyValue/GostKeyValue"; /// <summary> /// Известные наименования ключа. /// </summary> public static readonly string[] KnownNames = { NameValue, ObsoleteNameValue }; /// <inheritdoc /> public GostKeyValue() { } /// <inheritdoc /> public GostKeyValue(GostAsymmetricAlgorithm publicKey) { PublicKey = publicKey; } /// <summary> /// Открытый ключ. /// </summary> public GostAsymmetricAlgorithm PublicKey { get; set; } /// <inheritdoc /> public override void LoadXml(XmlElement element) { if (element == null) { throw new ArgumentNullException(nameof(element)); } PublicKey.FromXmlString(element.OuterXml); } /// <inheritdoc /> public override XmlElement GetXml() { var document = new XmlDocument { PreserveWhitespace = true }; var element = document.CreateElement("KeyValue", SignedXml.XmlDsigNamespaceUrl); element.InnerXml = PublicKey.ToXmlString(false); return element; } } }
using System; using System.Security.Cryptography.Xml; using System.Xml; using GostCryptography.Base; namespace GostCryptography.Xml { /// <summary> /// Параметры открытого ключа цифровой подписи ГОСТ Р 34.10. /// </summary> public sealed class GostKeyValue : KeyInfoClause { /// <summary> /// Наименование ключа. /// </summary> public const string NameValue = "urn:ietf:params:xml:ns:cpxmlsec:GOSTKeyValue"; /// <summary> /// Устаревшее наименование ключа. /// </summary> public const string ObsoleteNameValue = "http://www.w3.org/2000/09/xmldsig#KeyValue/GostKeyValue"; /// <summary> /// Известные наименования ключа. /// </summary> public static readonly string[] KnownNames = { NameValue, ObsoleteNameValue }; /// <inheritdoc /> public GostKeyValue() { } /// <inheritdoc /> public GostKeyValue(GostAsymmetricAlgorithm publicKey) { PublicKey = publicKey; } /// <summary> /// Открытый ключ. /// </summary> public GostAsymmetricAlgorithm PublicKey { get; set; } /// <inheritdoc /> public override void LoadXml(XmlElement element) { if (element == null) { throw new ArgumentNullException(nameof(element)); } PublicKey.FromXmlString(element.OuterXml); } /// <inheritdoc /> public override XmlElement GetXml() { var document = new XmlDocument { PreserveWhitespace = true }; var element = document.CreateElement("KeyValue", SignedXml.XmlDsigNamespaceUrl); element.InnerXml = PublicKey.ToXmlString(false); return element; } } }
mit
C#
2050ffbadfdeb7e5fb9a460789a4708979a98aa1
Tidy up with method sig overloads - reducing noise before the code gets too mad.
davidwhitney/XdtExtract,davidwhitney/XdtExtract
src/XdtExtract/AppConfigComparer.cs
src/XdtExtract/AppConfigComparer.cs
using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace XdtExtract { public class AppConfigComparer { public IEnumerable<Diff> Compare(string @base, string comparison) { return Compare(XDocument.Parse(@base), XDocument.Parse(comparison)); } public IEnumerable<Diff> Compare(XDocument @base, XDocument comparison) { var diffs = new List<Diff>(); var baseDocSettings = @base.AppSettings().Select(x => new { Source = "base", Node = x }); var comparisonDocSettings = comparison.AppSettings().Select(x => new { Source = "comparison", Node = x }); var groups = baseDocSettings.Union(comparisonDocSettings).GroupBy(x => x.Node.Attributes().Key()); foreach (var group in groups) { if (group.Count() == 1) { diffs.Add(new Diff { XPath = "/configuration/appSettings/add[@key='" + @group.Key + "']", Operation = @group.First().Source == "base" ? Operation.Remove : Operation.Add }); } } return diffs; } } public static class XDocumentExtensions { public static IEnumerable<XElement> AppSettings(this XDocument src) { return src.Descendants().Where(x => x.Name == "appSettings").Descendants(); } public static XElement SettingOrDefault(this IEnumerable<XElement> src, string key) { return src.SingleOrDefault(x => x.Attributes().Single(attr => attr.Name == "key").Value == key); } public static string Key(this IEnumerable<XAttribute> src) { return src.Single(x => x.Name == "key").Value; } } public class Diff { public string XPath { get; set; } public Operation Operation { get; set; } } public enum Operation { Add, Remove, Modify } }
using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace XdtExtract { public class AppConfigComparer { public IEnumerable<Diff> Compare(string baseConfig, string comparisonConfig) { var baseDoc = XDocument.Parse(baseConfig); var comparisonDoc = XDocument.Parse(comparisonConfig); var diffs = new List<Diff>(); var baseDocSettings = baseDoc.AppSettings().Select(x => new { Source = "base", Node = x }); var comparisonDocSettings = comparisonDoc.AppSettings().Select(x => new { Source = "comparison", Node = x }); var groups = baseDocSettings.Union(comparisonDocSettings).GroupBy(x => x.Node.Attributes().Key()); foreach (var group in groups) { if (group.Count() == 1) { diffs.Add(new Diff { XPath = "/configuration/appSettings/add[@key='" + @group.Key + "']", Operation = @group.First().Source == "base" ? Operation.Remove : Operation.Add }); continue; } } return diffs; } } public static class XDocumentExtensions { public static IEnumerable<XElement> AppSettings(this XDocument src) { return src.Descendants().Where(x => x.Name == "appSettings").Descendants(); } public static XElement SettingOrDefault(this IEnumerable<XElement> src, string key) { return src.SingleOrDefault(x => x.Attributes().Single(attr => attr.Name == "key").Value == key); } public static string Key(this IEnumerable<XAttribute> src) { return src.Single(x => x.Name == "key").Value; } } public class Diff { public string XPath { get; set; } public Operation Operation { get; set; } } public enum Operation { Add, Remove, Modify } }
mit
C#
ef46b30ae2878c745246e71978f33232a9d6850a
Add conditional business rule execution based on successful validation rule execution
peasy/Samples,peasy/Samples,peasy/Samples
Orders.com.BLL/Services/OrdersDotComServiceBase.cs
Orders.com.BLL/Services/OrdersDotComServiceBase.cs
using Peasy; using Peasy.Core; using Orders.com.BLL.DataProxy; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Orders.com.BLL.Services { public abstract class OrdersDotComServiceBase<T> : BusinessServiceBase<T, long> where T : IDomainObject<long>, new() { public OrdersDotComServiceBase(IOrdersDotComDataProxy<T> dataProxy) : base(dataProxy) { } protected override IEnumerable<ValidationResult> GetAllErrorsForInsert(T entity, ExecutionContext<T> context) { var validationErrors = GetValidationResultsForInsert(entity, context); if (!validationErrors.Any()) { var businessRuleErrors = GetBusinessRulesForInsert(entity, context).GetValidationResults(); validationErrors.Concat(businessRuleErrors); } return validationErrors; } protected override async Task<IEnumerable<ValidationResult>> GetAllErrorsForInsertAsync(T entity, ExecutionContext<T> context) { var validationErrors = GetValidationResultsForInsert(entity, context); if (!validationErrors.Any()) { var businessRuleErrors = await GetBusinessRulesForInsertAsync(entity, context); validationErrors.Concat(await businessRuleErrors.GetValidationResultsAsync()); } return validationErrors; } protected override IEnumerable<ValidationResult> GetAllErrorsForUpdate(T entity, ExecutionContext<T> context) { var validationErrors = GetValidationResultsForUpdate(entity, context); if (!validationErrors.Any()) { var businessRuleErrors = GetBusinessRulesForUpdate(entity, context).GetValidationResults(); validationErrors.Concat(businessRuleErrors); } return validationErrors; } protected override async Task<IEnumerable<ValidationResult>> GetAllErrorsForUpdateAsync(T entity, ExecutionContext<T> context) { var validationErrors = GetValidationResultsForUpdate(entity, context); if (!validationErrors.Any()) { var businessRuleErrors = await GetBusinessRulesForUpdateAsync(entity, context); validationErrors.Concat(await businessRuleErrors.GetValidationResultsAsync()); } return validationErrors; } } }
using Peasy; using Peasy.Core; using Orders.com.BLL.DataProxy; namespace Orders.com.BLL.Services { public abstract class OrdersDotComServiceBase<T> : BusinessServiceBase<T, long> where T : IDomainObject<long>, new() { public OrdersDotComServiceBase(IOrdersDotComDataProxy<T> dataProxy) : base(dataProxy) { } } }
mit
C#
da527aa9548e9eb2ac1174b9b6e74e69fe6accca
Change ConfigurationGenerationAttributeBase to invoke generation only on local build
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/CI/ConfigurationGenerationAttributeBase.cs
source/Nuke.Common/CI/ConfigurationGenerationAttributeBase.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Reflection; using Nuke.Common.Execution; using Nuke.Common.Tooling; namespace Nuke.Common.CI { [AttributeUsage(AttributeTargets.Class)] public abstract class ConfigurationGenerationAttributeBase : Attribute, IOnBeforeLogo { public const string ConfigurationParameterName = "configure-build-server"; public bool AutoGenerate { get; set; } = true; public void OnBeforeLogo(NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets) { if (!EnvironmentInfo.GetParameter<bool>(ConfigurationParameterName)) { if (NukeBuild.IsLocalBuild && AutoGenerate) { Logger.LogLevel = LogLevel.Trace; var assembly = Assembly.GetEntryAssembly().NotNull("assembly != null"); ProcessTasks.StartProcess( assembly.Location, $"--{ConfigurationParameterName} --host {HostType}", logInvocation: false, logOutput: false) .AssertZeroExitCode(); } return; } if (NukeBuild.Host == HostType) { Generate(build, executableTargets); Environment.Exit(0); } } protected abstract HostType HostType { get; } protected abstract void Generate(NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets); } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Reflection; using Nuke.Common.Execution; using Nuke.Common.Tooling; namespace Nuke.Common.CI { public abstract class ConfigurationGenerationAttributeBase : Attribute, IOnBeforeLogo { public const string ConfigurationParameterName = "configure-build-server"; public bool AutoGenerate { get; set; } = true; public void OnBeforeLogo(NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets) { if (!EnvironmentInfo.GetParameter<bool>(ConfigurationParameterName)) { if (AutoGenerate) { var assembly = Assembly.GetEntryAssembly().NotNull("assembly != null"); ProcessTasks.StartProcess( assembly.Location, $"--{ConfigurationParameterName} --host {HostType}", logInvocation: false, logOutput: false); } return; } Generate(build, executableTargets); Environment.Exit(0); } protected abstract HostType HostType { get; } protected abstract void Generate(NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets); } }
mit
C#
86f2f65af34065e2c9a10f81a931c4a9a0f0b8b1
Use local datetime
drasticactions/WinMasto
WinMasto/Tools/Converters/CreatedTimeConverter.cs
WinMasto/Tools/Converters/CreatedTimeConverter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; using PrettyPrintNet; namespace WinMasto.Tools.Converters { public class CreatedTimeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { var accountDateTime = (DateTime) value; return accountDateTime.ToLocalTime().ToString("g"); //var timespan = DateTime.UtcNow.Subtract(accountDateTime); //return timespan.ToPrettyString(2, UnitStringRepresentation.Compact); } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; using PrettyPrintNet; namespace WinMasto.Tools.Converters { public class CreatedTimeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { var accountDateTime = (DateTime) value; var timespan = DateTime.UtcNow.Subtract(accountDateTime); return timespan.ToPrettyString(2, UnitStringRepresentation.Compact); } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }
mit
C#
ac8569202f27518afc57c5a7f14c0ee433b6b6f8
Update sys version to v2.0-a2 #259
FanrayMedia/Fanray,FanrayMedia/Fanray,FanrayMedia/Fanray
src/Fan/Helpers/SysVersion.cs
src/Fan/Helpers/SysVersion.cs
namespace Fan.Helpers { public class SysVersion { public static string CurrentVersion = "v2.0-a2"; } }
namespace Fan.Helpers { public class SysVersion { public static string CurrentVersion = "v2.0-a1"; } }
apache-2.0
C#
00b6f898914f32fdf8026aff77f65db0744cddb6
add missing using statement ref
manigandham/serilog-sinks-googlecloudlogging
src/TestWeb/HomeController.cs
src/TestWeb/HomeController.cs
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Serilog; namespace TestWeb { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly ILoggerFactory _loggerFactory; public HomeController(ILogger<HomeController> logger, ILoggerFactory loggerFactory) { _logger = logger; _loggerFactory = loggerFactory; } public string Index() { Log.Information("Testing info message with serilog"); Log.Debug("Testing debug message with serilog"); _logger.LogInformation("Testing info message with ILogger abstraction"); _logger.LogDebug("Testing debug message with ILogger abstraction"); _logger.LogDebug(eventId: new Random().Next(), message: "Testing message with random event ID"); _logger.LogInformation("Test message with a Dictionary {myDict}", new Dictionary<string, string> { { "myKey", "myValue" }, { "mySecondKey", "withAValue" } }); // ASP.NET Logger Factor accepts string log names, but these must follow the rules for Google Cloud logging: // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry // Names must only include upper and lower case alphanumeric characters, forward-slash, underscore, hyphen, and period. No spaces! var logger = _loggerFactory.CreateLogger("AnotherLogger"); logger.LogInformation("Testing info message with ILoggerFactor abstraction and custom log name"); return $"Logged messages, visit GCP log viewer at https://console.cloud.google.com/logs/viewer?project={Program.GCP_PROJECT_ID}"; } } }
using System; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Serilog; namespace TestWeb { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly ILoggerFactory _loggerFactory; public HomeController(ILogger<HomeController> logger, ILoggerFactory loggerFactory) { _logger = logger; _loggerFactory = loggerFactory; } public string Index() { Log.Information("Testing info message with serilog"); Log.Debug("Testing debug message with serilog"); _logger.LogInformation("Testing info message with ILogger abstraction"); _logger.LogDebug("Testing debug message with ILogger abstraction"); _logger.LogDebug(eventId: new Random().Next(), message: "Testing message with random event ID"); _logger.LogInformation("Test message with a Dictionary {myDict}", new Dictionary<string, string> { { "myKey", "myValue" }, { "mySecondKey", "withAValue" } }); // ASP.NET Logger Factor accepts string log names, but these must follow the rules for Google Cloud logging: // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry // Names must only include upper and lower case alphanumeric characters, forward-slash, underscore, hyphen, and period. No spaces! var logger = _loggerFactory.CreateLogger("AnotherLogger"); logger.LogInformation("Testing info message with ILoggerFactor abstraction and custom log name"); return $"Logged messages, visit GCP log viewer at https://console.cloud.google.com/logs/viewer?project={Program.GCP_PROJECT_ID}"; } } }
mit
C#
95d486c19b0064f653be1226e8bdc463efed4244
Add Json Constructor for WebInput
LibertyLocked/webscripthook,LibertyLocked/webscripthook,LibertyLocked/webscripthook,LibertyLocked/webscripthook
webscripthook-plugin/WebInput.cs
webscripthook-plugin/WebInput.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GTA; using GTA.Math; using GTA.Native; using Newtonsoft.Json; namespace WebScriptHook { delegate object WebFunction(string arg, params object[] args); class WebInput { public string Cmd { get; set; } public string Arg { get; set; } public object[] Args { get; set; } public string UID { get; private set; } [JsonConstructor] public WebInput(string Cmd, string Arg, object[] Args, string UID) { this.Cmd = Cmd; this.Arg = Arg; this.Args = Args; this.UID = UID; } public object Execute() { if (string.IsNullOrEmpty(Cmd)) return null; WebFunction func = FunctionConvert.GetFunction(Cmd); if (func != null) { return func(Arg, Args); } else { return null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GTA; using GTA.Math; using GTA.Native; namespace WebScriptHook { delegate object WebFunction(string arg, params object[] args); class WebInput { public string Cmd { get; set; } public string Arg { get; set; } public object[] Args { get; set; } public string UID { get; set; } public object Execute() { if (string.IsNullOrEmpty(Cmd)) return null; WebFunction func = FunctionConvert.GetFunction(Cmd); if (func != null) { return func(Arg, Args); } else { return null; } } } }
mit
C#
3ee36bb8221323c5e29f9f56f22c55593960c262
Apply license terms uniformly
Lightstreamer/Lightstreamer-example-StockList-client-winphone,Weswit/Lightstreamer-example-StockList-client-winphone
WP7StockListDemo/Properties/AssemblyInfo.cs
WP7StockListDemo/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Lightstreamer Windows Phone Demo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Lightstreamer Windows Phone Demo")] [assembly: AssemblyCopyright("Copyright © Weswit 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("3e0afa5b-ebe3-408b-8c68-d1a45ae7eee8")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
#region License /* * Copyright 2013 Weswit Srl * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion License using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Lightstreamer Windows Phone Demo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Lightstreamer Windows Phone Demo")] [assembly: AssemblyCopyright("Copyright © Weswit 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("3e0afa5b-ebe3-408b-8c68-d1a45ae7eee8")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
4b79613aa31a5a0da573f5b54a0ce55a35f199fd
Add missing Id
hishamco/WebForms,hishamco/WebForms
samples/WebFormsSample/Pages/Index.htm.cs
samples/WebFormsSample/Pages/Index.htm.cs
using My.AspNetCore.WebForms; using My.AspNetCore.WebForms.Controls; using System; namespace WebFormsSample.Pages { public class Index : Page { private Literal litGreeting; public Index() { litGreeting = new Literal() { Id = "litGreeting" }; this.Load += Page_Load; this.Controls.Add(litGreeting); } private void Page_Load(object sender, EventArgs e) { litGreeting.Text = $"Hello, World! The time on the server is {DateTime.Now}"; } } }
using My.AspNetCore.WebForms; using My.AspNetCore.WebForms.Controls; using System; namespace WebFormsSample.Pages { public class Index : Page { private Literal litGreeting; public Index() { litGreeting = new Literal(); this.Load += Page_Load; this.Controls.Add(litGreeting); } private void Page_Load(object sender, EventArgs e) { litGreeting.Text = $"Hello, World! The time on the server is {DateTime.Now}"; } } }
mit
C#
5931c7fb9a8884adaf3087fb831caa103e0cfb86
Remove trailing slashes when creating LZMAs
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
build/tasks/CreateLzma.cs
build/tasks/CreateLzma.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.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.DotNet.Archive; namespace RepoTasks { public class CreateLzma : Task { [Required] public string OutputPath { get; set; } [Required] public string[] Sources { get; set; } public override bool Execute() { var progress = new ConsoleProgressReport(); using (var archive = new IndexedArchive()) { foreach (var source in Sources) { if (Directory.Exists(source)) { var trimmedSource = source.TrimEnd(new []{ '\\', '/' }); Log.LogMessage(MessageImportance.High, $"Adding directory: {trimmedSource}"); archive.AddDirectory(trimmedSource, progress); } else { Log.LogMessage(MessageImportance.High, $"Adding file: {source}"); archive.AddFile(source, Path.GetFileName(source)); } } archive.Save(OutputPath, progress); } return true; } } }
// 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.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.DotNet.Archive; namespace RepoTasks { public class CreateLzma : Task { [Required] public string OutputPath { get; set; } [Required] public string[] Sources { get; set; } public override bool Execute() { var progress = new ConsoleProgressReport(); using (var archive = new IndexedArchive()) { foreach (var source in Sources) { if (Directory.Exists(source)) { Log.LogMessage(MessageImportance.High, $"Adding directory: {source}"); archive.AddDirectory(source, progress); } else { Log.LogMessage(MessageImportance.High, $"Adding file: {source}"); archive.AddFile(source, Path.GetFileName(source)); } } archive.Save(OutputPath, progress); } return true; } } }
apache-2.0
C#
93cdc05ae158b3268f2812908e4b2fdfde08ff73
improve NotifyObjectChange: only check binding for ObservableModel context
minhdu/UIMan
Assets/UnuGames/UIMan/Scripts/MVVM/Core/DataContext.cs
Assets/UnuGames/UIMan/Scripts/MVVM/Core/DataContext.cs
using System; using System.Reflection; using UnityEngine; using System.Collections.Generic; namespace UnuGames.MVVM { /// <summary> /// Data context. /// </summary> public class DataContext : MonoBehaviour { #region DataContext Factory static List<DataContext> contextsList = new List<DataContext> (); static public void NotifyObjectChange (object modelInstance) { for (int i = 0; i < contextsList.Count; i++) { DataContext context = contextsList [i]; if (context.model != null && context.model is ObservableModel) { PropertyInfo propertyInfo = context.viewModel.IsBindingTo (modelInstance); if (propertyInfo != null) { context.viewModel.NotifyModelChange (modelInstance); } } } } #endregion #region Instance public ContextType type; public ViewModelBehaviour viewModel; public object model; public string propertyName; PropertyInfo propertyInfo; public PropertyInfo PropertyInfo { get { return propertyInfo; } } public void Clear () { viewModel = null; propertyName = null; propertyInfo = null; } void Awake () { if(!contextsList.Contains(this)) contextsList.Add (this); Init (); RegisterBindingMessage (false); } // Subscript for property change event public void Init () { GetPropertyInfo (); if (propertyInfo != null) { model = propertyInfo.GetValue (viewModel, null); if (model == null && type == ContextType.PROPERTY) model = ReflectUtils.GetCachedTypeInstance (propertyInfo.PropertyType); if (model != null) { viewModel.SubcriptObjectAction (model); viewModel.SubscribeAction (propertyName, viewModel.NotifyModelChange); } } } // Register binding message for child binders void RegisterBindingMessage (bool forceReinit = false) { BinderBase[] binders = GetComponentsInChildren<BinderBase> (true); for (int i = 0; i < binders.Length; i++) { BinderBase binder = binders [i]; if (binder.mDataContext == this) { binder.Init (forceReinit); } } } public PropertyInfo GetPropertyInfo () { #if !UNITY_EDITOR if(propertyInfo == null) propertyInfo = viewModel.GetCachedType ().GetProperty (propertyName); #else propertyInfo = viewModel.GetCachedType ().GetProperty (propertyName); #endif return propertyInfo; } } #endregion }
using System; using System.Reflection; using UnityEngine; using System.Collections.Generic; namespace UnuGames.MVVM { /// <summary> /// Data context. /// </summary> public class DataContext : MonoBehaviour { #region DataContext Factory static List<DataContext> contextsList = new List<DataContext> (); static public void NotifyObjectChange (object modelInstance) { for (int i = 0; i < contextsList.Count; i++) { DataContext context = contextsList [i]; PropertyInfo propertyInfo = context.viewModel.IsBindingTo (modelInstance); if (propertyInfo != null) { context.viewModel.NotifyModelChange (modelInstance); } } } #endregion #region Instance public ContextType type; public ViewModelBehaviour viewModel; public object model; public string propertyName; PropertyInfo propertyInfo; public PropertyInfo PropertyInfo { get { return propertyInfo; } } public void Clear () { viewModel = null; propertyName = null; propertyInfo = null; } void Awake () { if(!contextsList.Contains(this)) contextsList.Add (this); Init (); RegisterBindingMessage (false); } // Subscript for property change event public void Init () { GetPropertyInfo (); if (propertyInfo != null) { model = propertyInfo.GetValue (viewModel, null); if (model == null && type == ContextType.PROPERTY) model = ReflectUtils.GetCachedTypeInstance (propertyInfo.PropertyType); if (model != null) { viewModel.SubcriptObjectAction (model); viewModel.SubscribeAction (propertyName, viewModel.NotifyModelChange); } } } // Register binding message for child binders void RegisterBindingMessage (bool forceReinit = false) { BinderBase[] binders = GetComponentsInChildren<BinderBase> (true); for (int i = 0; i < binders.Length; i++) { BinderBase binder = binders [i]; if (binder.mDataContext == this) { binder.Init (forceReinit); } } } public PropertyInfo GetPropertyInfo () { #if !UNITY_EDITOR if(propertyInfo == null) propertyInfo = viewModel.GetCachedType ().GetProperty (propertyName); #else propertyInfo = viewModel.GetCachedType ().GetProperty (propertyName); #endif return propertyInfo; } } #endregion }
mit
C#
21c7ea664a6c071716a69b2f7659a0aebfb80802
Improve high-dpi.
yas-mnkornym/SylphyHorn,Grabacr07/SylphyHorn,mntone/SylphyHorn
source/SylphyHorn/Interop/IconHelper.cs
source/SylphyHorn/Interop/IconHelper.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using MetroRadiance.Interop; namespace SylphyHorn.Interop { public static class IconHelper { public static Icon GetIconFromResource(Uri uri) { var streamResourceInfo = System.Windows.Application.GetResourceStream(uri); if (streamResourceInfo == null) throw new ArgumentException("Resource not found.", nameof(uri)); var dpi = PerMonitorDpi.GetDpi(IntPtr.Zero); // get desktop dpi using (var stream = streamResourceInfo.Stream) { return new Icon(stream, new Size((int)(16 * dpi.ScaleX), (int)(16 * dpi.ScaleY))); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; namespace SylphyHorn.Interop { public static class IconHelper { public static Icon GetIconFromResource(Uri uri) { var streamResourceInfo = System.Windows.Application.GetResourceStream(uri); if (streamResourceInfo == null) throw new ArgumentException("Resource not found.", nameof(uri)); using (var stream = streamResourceInfo.Stream) { return new Icon(stream, new Size(16, 16)); } } } }
mit
C#
77ec37d24ea3a6aca58761380c981952fa4ea784
Refactor normalization tests
ermshiperete/icu-dotnet,ermshiperete/icu-dotnet,conniey/icu-dotnet,sillsdev/icu-dotnet,sillsdev/icu-dotnet,conniey/icu-dotnet
source/icu.net.tests/NormalizerTests.cs
source/icu.net.tests/NormalizerTests.cs
// Copyright (c) 2013 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Text; using Icu.Collation; using NUnit.Framework; namespace Icu.Tests { [TestFixture] public class NormalizerTests { [TestCase("XA\u0308bc", Normalizer.UNormalizationMode.UNORM_NFC, Result = "X\u00C4bc")] [TestCase("X\u00C4bc", Normalizer.UNormalizationMode.UNORM_NFD, Result = "XA\u0308bc")] [TestCase("tést", Normalizer.UNormalizationMode.UNORM_NFD, Result = "te\u0301st")] [TestCase("te\u0301st", Normalizer.UNormalizationMode.UNORM_NFC, Result = "tést")] [TestCase("te\u0301st", Normalizer.UNormalizationMode.UNORM_NFD, Result = "te\u0301st")] public string Normalize(string src, Normalizer.UNormalizationMode mode) { return Normalizer.Normalize(src, mode); } [TestCase("X\u00C4bc", Normalizer.UNormalizationMode.UNORM_NFC, Result = true)] [TestCase("XA\u0308bc", Normalizer.UNormalizationMode.UNORM_NFC, Result = false)] [TestCase("X\u00C4bc", Normalizer.UNormalizationMode.UNORM_NFD, Result = false)] [TestCase("XA\u0308bc", Normalizer.UNormalizationMode.UNORM_NFD, Result = true)] public bool IsNormalized(string src, Normalizer.UNormalizationMode expectNormalizationMode) { return Normalizer.IsNormalized(src, expectNormalizationMode); } } }
// Copyright (c) 2013 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Text; using NUnit.Framework; namespace Icu.Tests { [TestFixture] public class NormalizerTests { [Test] public void Normalize_NFC() { Assert.That(Normalizer.Normalize("XA\u0308bc", Normalizer.UNormalizationMode.UNORM_NFC), Is.EqualTo("X\u00C4bc")); } [Test] public void Normalize_NFD() { Assert.That(Normalizer.Normalize("X\u00C4bc", Normalizer.UNormalizationMode.UNORM_NFD), Is.EqualTo("XA\u0308bc")); } [Test] public void Normalize_NFC2NFC() { var normalizedString = Normalizer.Normalize("tést", Normalizer.UNormalizationMode.UNORM_NFC); Assert.That(normalizedString, Is.EqualTo("tést")); Assert.That(normalizedString.IsNormalized(NormalizationForm.FormC), Is.True); } [Test] public void Normalize_NFC2NFD() { var normalizedString = Normalizer.Normalize("tést", Normalizer.UNormalizationMode.UNORM_NFD); Assert.That(normalizedString[2], Is.EqualTo('\u0301')); Assert.That(normalizedString, Is.EqualTo("te\u0301st")); Assert.That(normalizedString.IsNormalized(NormalizationForm.FormD), Is.True); } [Test] public void Normalize_NFD2NFC() { var normalizedString = Normalizer.Normalize("te\u0301st", Normalizer.UNormalizationMode.UNORM_NFC); Assert.That(normalizedString, Is.EqualTo("tést")); Assert.That(normalizedString.IsNormalized(NormalizationForm.FormC), Is.True); } [Test] public void Normalize_NFD2NFD() { var normalizedString = Normalizer.Normalize("te\u0301st", Normalizer.UNormalizationMode.UNORM_NFD); Assert.That(normalizedString, Is.EqualTo("te\u0301st")); Assert.That(normalizedString.IsNormalized(NormalizationForm.FormD), Is.True); } [Test] public void IsNormalized_NFC() { Assert.That(Normalizer.IsNormalized("X\u00C4bc", Normalizer.UNormalizationMode.UNORM_NFC), Is.True); Assert.That(Normalizer.IsNormalized("XA\u0308bc", Normalizer.UNormalizationMode.UNORM_NFC), Is.False); } [Test] public void IsNormalized_NFD() { Assert.That(Normalizer.IsNormalized("XA\u0308bc", Normalizer.UNormalizationMode.UNORM_NFD), Is.True); Assert.That(Normalizer.IsNormalized("X\u00C4bc", Normalizer.UNormalizationMode.UNORM_NFD), Is.False); } } }
mit
C#
0a72d4024fc0cb0d1c063c077e86d3ab5edbce2e
Stop prior sounds
gadauto/OCDEscape
Assets/OCDRoomEscape/Scripts/Interaction/PuzzleMaster.cs
Assets/OCDRoomEscape/Scripts/Interaction/PuzzleMaster.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PuzzleMaster : MonoBehaviour { public float timeBetweenSounds = 15f; public WallManager wallMgr; public List<Puzzle> puzzles; float increment; float weightedIncrementTotal; bool isGameOver = false; // Use this for initialization void Awake () { foreach (var puzzle in puzzles) { Debug.Log("Puzzle added: "+puzzle); } } void Start() { // We'll consider the puzzle's weight when determining how much it affects the room movement foreach (var puzzle in puzzles) { weightedIncrementTotal += puzzle.puzzleWeight; } } public void PuzzleCompleted(Puzzle puzzle) { if (isGameOver) { Debug.Log("GAME OVER!!! Let the player know!!"); return; } var growthIncrement = puzzle.puzzleWeight / weightedIncrementTotal; // Notify room of growth increment wallMgr.Resize(wallMgr.transformRoom + growthIncrement); KickOffSoundForPuzzle(puzzle); if (puzzle.IsResetable() && puzzles.Contains(puzzle)) { Debug.Log("Puzzle marked for reset"); puzzle.MarkForReset(); } // Remove the puzzle, but also allow it to remain in the list multiple times puzzles.Remove(puzzle); Debug.Log("Finished puzzle: "+puzzle+", "+puzzles.Count+" left, room growing to: "+(wallMgr.transformRoom + growthIncrement)); if (wallMgr.transformRoom >= 1f) { StopAllCoroutines(); // Turn off sounds isGameOver = true; Debug.Log("GAME OVER!!!"); } } private void KickOffSoundForPuzzle(Puzzle puzzle) { StopAllCoroutines(); AudioSource source = puzzle.SoundForPuzzle(); if (source) { StartCoroutine(PlaySound(source)); } else { Debug.Log(puzzle+" does not have an associated AudioSource"); } } private IEnumerator PlaySound(AudioSource source) { while (true) { source.Play(); yield return new WaitForSeconds(timeBetweenSounds); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PuzzleMaster : MonoBehaviour { public float timeBetweenSounds = 15f; public WallManager wallMgr; public List<Puzzle> puzzles; float increment; float weightedIncrementTotal; bool isGameOver = false; // Use this for initialization void Awake () { foreach (var puzzle in puzzles) { Debug.Log("Puzzle added: "+puzzle); } } void Start() { // We'll consider the puzzle's weight when determining how much it affects the room movement foreach (var puzzle in puzzles) { weightedIncrementTotal += puzzle.puzzleWeight; } } public void PuzzleCompleted(Puzzle puzzle) { if (isGameOver) { Debug.Log("GAME OVER!!! Let the player know!!"); return; } var growthIncrement = puzzle.puzzleWeight / weightedIncrementTotal; // Notify room of growth increment wallMgr.Resize(wallMgr.transformRoom + growthIncrement); KickOffSoundForPuzzle(puzzle); if (puzzle.IsResetable() && puzzles.Contains(puzzle)) { Debug.Log("Puzzle marked for reset"); puzzle.MarkForReset(); } // Remove the puzzle, but also allow it to remain in the list multiple times puzzles.Remove(puzzle); Debug.Log("Finished puzzle: "+puzzle+", "+puzzles.Count+" left, room growing to: "+(wallMgr.transformRoom + growthIncrement)); if (wallMgr.transformRoom >= 1f) { isGameOver = true; Debug.Log("GAME OVER!!!"); } } private void KickOffSoundForPuzzle(Puzzle puzzle) { AudioSource source = puzzle.SoundForPuzzle(); if (source) { StartCoroutine(PlaySound(source)); } else { Debug.Log(puzzle+" does not have an associated AudioSource"); } } private IEnumerator PlaySound(AudioSource source) { while (true) { source.Play(); yield return new WaitForSeconds(timeBetweenSounds); } } }
apache-2.0
C#
01c15fe516e6fc599a12eef3936ed56aa4b8f1fc
Verify that region is set if specified
appharbor/appharbor-cli
src/AppHarbor.Tests/Commands/CreateAppCommandTest.cs
src/AppHarbor.Tests/Commands/CreateAppCommandTest.cs
using System.IO; using System.Linq; using AppHarbor.Commands; using AppHarbor.Model; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests.Commands { public class CreateAppCommandTest { [Theory, AutoCommandData] public void ShouldThrowWhenNoArguments(CreateAppCommand command) { var exception = Assert.Throws<CommandException>(() => command.Execute(new string[0])); Assert.Equal("An application name must be provided to create an application", exception.Message); } [Theory, AutoCommandData] public void ShouldCreateApplicationWithOnlyName([Frozen]Mock<IAppHarborClient> client, CreateAppCommand command) { var arguments = new string[] { "foo" }; VerifyArguments(client, command, arguments); } [Theory, AutoCommandData] public void ShouldCreateApplicationWithRegion([Frozen]Mock<IAppHarborClient> client, CreateAppCommand command, string[] arguments) { VerifyArguments(client, command, arguments); } private static void VerifyArguments(Mock<IAppHarborClient> client, CreateAppCommand command, string[] arguments) { command.Execute(arguments); client.Verify(x => x.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()), Times.Once()); } [Theory, AutoCommandData] public void ShouldSetupApplicationLocallyAfterCreationIfNotConfigured([Frozen]Mock<IApplicationConfiguration> applicationConfiguration, [Frozen]Mock<IAppHarborClient> client, CreateAppCommand command, CreateResult result, User user, string[] arguments) { client.Setup(x => x.CreateApplication(It.IsAny<string>(), It.IsAny<string>())).Returns(result); client.Setup(x => x.GetUser()).Returns(user); applicationConfiguration.Setup(x => x.GetApplicationId()).Throws<ApplicationConfigurationException>(); command.Execute(arguments); applicationConfiguration.Verify(x => x.SetupApplication(result.Id, user), Times.Once()); } [Theory, AutoCommandData] public void ShouldNotSetupApplicationIfAlreadyConfigured([Frozen]Mock<IApplicationConfiguration> applicationConfiguration, [Frozen]Mock<TextWriter> writer, CreateAppCommand command, string[] arguments, string applicationName) { applicationConfiguration.Setup(x => x.GetApplicationId()).Returns(applicationName); command.Execute(arguments); writer.Verify(x => x.WriteLine("This directory is already configured to track application \"{0}\".", applicationName), Times.Once()); } [Theory, AutoCommandData] public void ShouldPrintSuccessMessageAfterCreatingApplication([Frozen]Mock<IAppHarborClient> client, [Frozen]Mock<TextWriter> writer, Mock<CreateAppCommand> command, string applicationName, string applicationSlug) { client.Setup(x => x.CreateApplication(applicationName, null)).Returns(new CreateResult { Id = applicationSlug }); command.Object.Execute(new string[] { applicationName }); writer.Verify(x => x.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", applicationSlug), Times.Once()); } [Theory, AutoCommandData] public void ShouldSetRegionIsSpecified([Frozen]Mock<IAppHarborClient> client, [Frozen]Mock<TextWriter> writer, Mock<CreateAppCommand> command, string regionName, string applicationSlug) { client.Setup(x => x.CreateApplication(applicationSlug, regionName)).Returns(new CreateResult { Id = applicationSlug }); command.Object.Execute(new string[] { applicationSlug, "-r", regionName }); client.VerifyAll(); } } }
using System.IO; using System.Linq; using AppHarbor.Commands; using AppHarbor.Model; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests.Commands { public class CreateAppCommandTest { [Theory, AutoCommandData] public void ShouldThrowWhenNoArguments(CreateAppCommand command) { var exception = Assert.Throws<CommandException>(() => command.Execute(new string[0])); Assert.Equal("An application name must be provided to create an application", exception.Message); } [Theory, AutoCommandData] public void ShouldCreateApplicationWithOnlyName([Frozen]Mock<IAppHarborClient> client, CreateAppCommand command) { var arguments = new string[] { "foo" }; VerifyArguments(client, command, arguments); } [Theory, AutoCommandData] public void ShouldCreateApplicationWithRegion([Frozen]Mock<IAppHarborClient> client, CreateAppCommand command, string[] arguments) { VerifyArguments(client, command, arguments); } private static void VerifyArguments(Mock<IAppHarborClient> client, CreateAppCommand command, string[] arguments) { command.Execute(arguments); client.Verify(x => x.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()), Times.Once()); } [Theory, AutoCommandData] public void ShouldSetupApplicationLocallyAfterCreationIfNotConfigured([Frozen]Mock<IApplicationConfiguration> applicationConfiguration, [Frozen]Mock<IAppHarborClient> client, CreateAppCommand command, CreateResult result, User user, string[] arguments) { client.Setup(x => x.CreateApplication(It.IsAny<string>(), It.IsAny<string>())).Returns(result); client.Setup(x => x.GetUser()).Returns(user); applicationConfiguration.Setup(x => x.GetApplicationId()).Throws<ApplicationConfigurationException>(); command.Execute(arguments); applicationConfiguration.Verify(x => x.SetupApplication(result.Id, user), Times.Once()); } [Theory, AutoCommandData] public void ShouldNotSetupApplicationIfAlreadyConfigured([Frozen]Mock<IApplicationConfiguration> applicationConfiguration, [Frozen]Mock<TextWriter> writer, CreateAppCommand command, string[] arguments, string applicationName) { applicationConfiguration.Setup(x => x.GetApplicationId()).Returns(applicationName); command.Execute(arguments); writer.Verify(x => x.WriteLine("This directory is already configured to track application \"{0}\".", applicationName), Times.Once()); } [Theory, AutoCommandData] public void ShouldPrintSuccessMessageAfterCreatingApplication([Frozen]Mock<IAppHarborClient> client, [Frozen]Mock<TextWriter> writer, Mock<CreateAppCommand> command, string applicationName, string applicationSlug) { client.Setup(x => x.CreateApplication(applicationName, null)).Returns(new CreateResult { Id = applicationSlug }); command.Object.Execute(new string[] { applicationName }); writer.Verify(x => x.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", applicationSlug), Times.Once()); } } }
mit
C#
be20878184318342858b03d85b61ca1643c71906
Update IndexModule.cs
LeedsSharp/AppVeyorDemo
src/AppVeyorDemo/AppVeyorDemo/Modules/IndexModule.cs
src/AppVeyorDemo/AppVeyorDemo/Modules/IndexModule.cs
namespace AppVeyorDemo.Modules { using System.Configuration; using AppVeyorDemo.Models; using Nancy; public class IndexModule : NancyModule { public IndexModule() { Get["/"] = parameters => { var model = new IndexViewModel { HelloName = "Leeds#", ServerName = ConfigurationManager.AppSettings["Server_Name"] }; return View["index", model]; }; } } }
namespace AppVeyorDemo.Modules { using System.Configuration; using AppVeyorDemo.Models; using Nancy; public class IndexModule : NancyModule { public IndexModule() { Get["/"] = parameters => { var model = new IndexViewModel { HelloName = "AppVeyor", ServerName = ConfigurationManager.AppSettings["Server_Name"] }; return View["index", model]; }; } } }
apache-2.0
C#
b9df03da9d552c00887e209bba16e6cc33638a77
Add public comments to login request handler classes and interfaces
ZEISS-PiWeb/PiWeb-Api
src/Common/Client/ICertificateLoginRequestHandler.cs
src/Common/Client/ICertificateLoginRequestHandler.cs
#region Copyright /* * * * * * * * * * * * * * * * * * * * * * * * * */ /* Carl Zeiss IMT (IZfM Dresden) */ /* Softwaresystem PiWeb */ /* (c) Carl Zeiss 2016 */ /* * * * * * * * * * * * * * * * * * * * * * * * * */ #endregion namespace Zeiss.IMT.PiWeb.Api.Common.Client { #region usings using System; using System.Threading.Tasks; using PiWebApi.Annotations; using Zeiss.IMT.PiWeb.Api.Common.Utilities; #endregion /// <summary> /// Interface that is used as callback handler for requests that need a certificate for authentification. /// </summary> /// <remarks> /// This interface is mainly designed for showing a user interface to the user for choosing the right certificate. /// </remarks> public interface ICertificateLoginRequestHandler : ICacheClearable { #region methods /// <summary> /// Asynchronous callback if a certificate for a <see cref="Uri"/> is requested. /// </summary> /// <param name="uri">The address for which a certificate is requested.</param> /// <param name="preferHardwareCertificate">An option that is used to limit the list of possible certificates to hardware certificates only.</param> /// <returns>Returns a the certificate that should be used for authentication or null if no certificate should be used.</returns> /// <exception cref="LoginCanceledException">Throws a <see cref="LoginCanceledException"/> if the request should be canceled.</exception> /// <remarks> /// The <see cref="Uri"/> usually refers to the base address of a server, since declared endpoints usually do not use different authentications. /// </remarks> Task<CertificateCredential> CertificateRequestAsync( [NotNull] Uri uri, bool preferHardwareCertificate = false); /// <summary> /// Synchronous callback if a certificate for a <see cref="Uri"/> is requested. /// </summary> /// <param name="uri">The address for which a certificate is requested.</param> /// <param name="preferHardwareCertificate">An option that is used to limit the list of possible certificates to hardware certificates only.</param> /// <returns>Returns a the certificate that should be used for authentication or null if no certificate should be used.</returns> /// <exception cref="LoginCanceledException">Throws a <see cref="LoginCanceledException"/> if the request should be canceled.</exception> /// <remarks> /// This is the synchronous counter part to <see cref="CertificateRequestAsync"/> which stays usually unused by the <see cref="RestClient"/>, /// since its API is fully asynchronous. This mainly exists for purpose of introducing a synchronous API if needed in the future. /// The <see cref="Uri"/> usually refers to the base address of a server, since declared endpoints usually do not use different authentications. /// </remarks> CertificateCredential CertificateRequest( [NotNull] Uri uri, bool preferHardwareCertificate = false ); #endregion } }
#region Copyright /* * * * * * * * * * * * * * * * * * * * * * * * * */ /* Carl Zeiss IMT (IZfM Dresden) */ /* Softwaresystem PiWeb */ /* (c) Carl Zeiss 2016 */ /* * * * * * * * * * * * * * * * * * * * * * * * * */ #endregion namespace Zeiss.IMT.PiWeb.Api.Common.Client { #region usings using System; using System.Threading.Tasks; using PiWebApi.Annotations; using Zeiss.IMT.PiWeb.Api.Common.Utilities; #endregion /// <summary> /// Interface that is used as callback handler for requests that need a certificate for authentification. /// </summary> /// <remarks> /// This interface is mainly designed for showing a user interface to the user for choosing the right certificate. /// </remarks> public interface ICertificateLoginRequestHandler : ICacheClearable { #region methods /// <summary> /// Asynchronous callback if a certificate for a <see cref="Uri"/> is requested. /// </summary> /// <param name="uri">The address for which a certificate is requested.</param> /// <param name="preferHardwareCertificate">An option that is used to limit the list of possible certificates to hardware certificates only.</param> /// <returns>Returns a the certificate that should be used for authentication or null if no certificate should be used.</returns> /// <exception cref="LoginCanceledException">Throws a <see cref="LoginCanceledException"/> if the request should be canceled.</exception> /// <remarks> /// The <see cref="Uri"/> usually refers to the base address of a server, since declared endpoints usually do not use different authentications. /// </remarks> Task<CertificateCredential> CertificateRequestAsync( [NotNull] Uri uri, bool preferHardwareCertificate = false); /// <summary> /// Synchronous callback if a certificate for a <see cref="Uri"/> is requested. /// </summary> /// <param name="uri">The address for which a certificate is requested.</param> /// <param name="preferHardwareCertificate">An option that is used to limit the list of possible certificates to hardware certificates only.</param> /// <returns>Returns a the certificate that should be used for authentication or null if no certificate should be used.</returns> /// <exception cref="LoginCanceledException">Throws a <see cref="LoginCanceledException"/> if the request should be canceled.</exception> /// <remarks> /// This is the synchronous counter part to <see cref="CertificateRequestAsync"/> which stays usually unused by the <see cref="RestClient"/>, /// since its API is fully asynchronous. This mainly exists for purpose of introducing a synchronous API if needed in the future. /// The <see cref="Uri"/> usually refers to the base address of a server, since declared endpoints usually do not use different authentications. /// </remarks> CertificateCredential CertificateRequest( [NotNull] Uri uri, bool preferHardwareCertificate = false ); #endregion } }
bsd-3-clause
C#
41e45dbac4e5f6ba3a320b3eabd0ea2109ceb732
Fix build warnings
Ninputer/VBF
src/Compilers/Compilers.Scanners/SymbolExpression.cs
src/Compilers/Compilers.Scanners/SymbolExpression.cs
// Copyright 2012 Fan Shi // // This file is part of the VBF project. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Globalization; namespace VBF.Compilers.Scanners { /// <summary> /// Represents a regular expression accepts a literal character /// </summary> public class SymbolExpression : RegularExpression { public SymbolExpression(char symbol) : base(RegularExpressionType.Symbol) { Symbol = symbol; } public new char Symbol { get; private set; } public override string ToString() { return Symbol.ToString(CultureInfo.InvariantCulture); } internal override Func<HashSet<char>>[] GetCompactableCharSets() { return new Func<HashSet<char>>[0]; } internal override HashSet<char> GetUncompactableCharSet() { var result = new HashSet<char> {Symbol}; return result; } internal override T Accept<T>(RegularExpressionConverter<T> converter) { return converter.ConvertSymbol(this); } } }
// Copyright 2012 Fan Shi // // This file is part of the VBF project. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Globalization; namespace VBF.Compilers.Scanners { /// <summary> /// Represents a regular expression accepts a literal character /// </summary> public class SymbolExpression : RegularExpression { public SymbolExpression(char symbol) : base(RegularExpressionType.Symbol) { Symbol = symbol; } public char Symbol { get; private set; } public override string ToString() { return Symbol.ToString(CultureInfo.InvariantCulture); } internal override Func<HashSet<char>>[] GetCompactableCharSets() { return new Func<HashSet<char>>[0]; } internal override HashSet<char> GetUncompactableCharSet() { var result = new HashSet<char> {Symbol}; return result; } internal override T Accept<T>(RegularExpressionConverter<T> converter) { return converter.ConvertSymbol(this); } } }
apache-2.0
C#
aa44980ae9b37df4807e5ea7cfbe01309ea8a50c
fix small bug
mdavid626/artemis
src/Artemis.Data/DbContextRepository.cs
src/Artemis.Data/DbContextRepository.cs
using Artemis.Common; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Linq.Dynamic; namespace Artemis.Data { public abstract class DbContextRepository<T> : IRepository<T> where T : class, IHasKey { private IUnitOfWork unitOfWork; public abstract DbSet<T> EntityDbSet { get; } public DbContextRepository(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } public T Get(int id) { return EntityDbSet.FirstOrDefault(c => c.Id == id); } public IEnumerable<T> Get(string orderBy = null, string direction = null) { var ordering = GetOrdering(orderBy, direction); return EntityDbSet.OrderBy(ordering); } public void Update(T entity) { } public void Create(T entity) { EntityDbSet.Add(entity); } public void Delete(T entity) { EntityDbSet.Remove(entity); } private string GetOrdering(string orderBy, string direction) { var ascending = true; if (direction?.ToLower() == "desc") ascending = false; var directionText = ascending ? " asc" : " desc"; var allowedProps = typeof(T) .GetProperties() .Where(p => p.GetCustomAttribute<SortableAttribute>() != null) .Select(p => p.Name.ToLower()); var prop = allowedProps.Intersect(new string[] { orderBy?.ToLower() }); if (prop.Any()) { return orderBy + directionText; } return nameof(IHasKey.Id) + directionText; } } }
using Artemis.Common; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Linq.Dynamic; namespace Artemis.Data { public abstract class DbContextRepository<T> : IRepository<T> where T : class, IHasKey { private IUnitOfWork unitOfWork; public abstract DbSet<T> EntityDbSet { get; } public DbContextRepository(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } public T Get(int id) { return EntityDbSet.FirstOrDefault(c => c.Id == id); } public IEnumerable<T> Get(string orderBy = null, string direction = null) { var ordering = GetOrdering(orderBy, direction); return EntityDbSet.OrderBy(ordering); } public void Update(T entity) { } public void Create(T entity) { EntityDbSet.Add(entity); } public void Delete(T entity) { EntityDbSet.Remove(entity); } private string GetOrdering(string orderBy, string direction) { var ascending = true; if (direction?.ToLower() == "desc") ascending = false; var directionText = ascending ? " asc" : " desc"; var allowedProps = typeof(CarAdvert) .GetProperties() .Where(p => p.GetCustomAttribute<SortableAttribute>() != null) .Select(p => p.Name.ToLower()); var prop = allowedProps.Intersect(new string[] { orderBy?.ToLower() }); if (prop.Any()) { return orderBy + directionText; } return nameof(IHasKey.Id) + directionText; } } }
mit
C#
135cd2647a8aa8b4c342d132400f89f6632b9718
update access modifiers from public -> internal
colinmxs/CodenameGenerator
src/CodenameGenerator/StringExtensions.cs
src/CodenameGenerator/StringExtensions.cs
using System; namespace CodenameGenerator { internal static class StringExtensions { //http://stackoverflow.com/questions/4135317/make-first-letter-of-a-string-upper-case-for-maximum-performance /// <summary> /// Capitalize the first character of a string /// </summary> /// <param name="string"></param> /// <returns></returns> internal static string FirstCharToUpper(this string @string) { if (String.IsNullOrEmpty(@string)) throw new ArgumentException("There is no first letter"); char[] chars = @string.ToCharArray(); chars[0] = char.ToUpper(chars[0]); return new string(chars); } } }
using System; namespace CodenameGenerator { public static class StringExtensions { //http://stackoverflow.com/questions/4135317/make-first-letter-of-a-string-upper-case-for-maximum-performance /// <summary> /// Capitalize the first character of a string /// </summary> /// <param name="string"></param> /// <returns></returns> public static string FirstCharToUpper(this string @string) { if (String.IsNullOrEmpty(@string)) throw new ArgumentException("There is no first letter"); char[] chars = @string.ToCharArray(); chars[0] = char.ToUpper(chars[0]); return new string(chars); } } }
mit
C#
5b9b0c1a168203af0ef8d49ebe5a0bdc31f8da75
Put custom uploaders in same dir as other plugins
nikeee/HolzShots
src/HolzShots.Core/IO/HolzShotsPaths.cs
src/HolzShots.Core/IO/HolzShotsPaths.cs
using System; using System.Diagnostics; using System.IO; namespace HolzShots.IO { public static class HolzShotsPaths { private static readonly string SystemAppDataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); private static readonly string UserPicturesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); private static readonly string AppDataDirectory = Path.Combine(SystemAppDataDirectory, LibraryInformation.Name); public static string SystemPath { get; } = Environment.GetFolderPath(Environment.SpecialFolder.System); public static string PluginDirectory { get; } = Path.Combine(AppDataDirectory, "Plugin"); public static string CustomUploadersDirectory { get; } = PluginDirectory; public static string UserSettingsFilePath { get; } = Path.Combine(AppDataDirectory, "settings.json"); public static string DefaultScreenshotSavePath { get; } = Path.Combine(UserPicturesDirectory, LibraryInformation.Name); /// <summary> /// We are doing this synchronously, assuming the application is not located on a network drive. /// See: https://stackoverflow.com/a/20596865 /// </summary> /// <exception cref="System.UnauthorizedAccessException" /> /// <exception cref="System.IO.PathTooLongException" /> public static void EnsureDirectory(string directory) { Debug.Assert(directory != null); DirectoryEx.EnsureDirectory(directory); } } }
using System; using System.Diagnostics; using System.IO; namespace HolzShots.IO { public static class HolzShotsPaths { private static readonly string SystemAppDataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); private static readonly string UserPicturesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); private static readonly string AppDataDirectory = Path.Combine(SystemAppDataDirectory, LibraryInformation.Name); public static string SystemPath { get; } = Environment.GetFolderPath(Environment.SpecialFolder.System); public static string PluginDirectory { get; } = Path.Combine(AppDataDirectory, "Plugin"); public static string CustomUploadersDirectory { get; } = Path.Combine(AppDataDirectory, "CustomUploaders"); public static string UserSettingsFilePath { get; } = Path.Combine(AppDataDirectory, "settings.json"); public static string DefaultScreenshotSavePath { get; } = Path.Combine(UserPicturesDirectory, LibraryInformation.Name); /// <summary> /// We are doing this synchronously, assuming the application is not located on a network drive. /// See: https://stackoverflow.com/a/20596865 /// </summary> /// <exception cref="System.UnauthorizedAccessException" /> /// <exception cref="System.IO.PathTooLongException" /> public static void EnsureDirectory(string directory) { Debug.Assert(directory != null); DirectoryEx.EnsureDirectory(directory); } } }
agpl-3.0
C#
bd27a87f634dd4e45220195d6d63cbfe72750e60
Check isLocal using Uri.TryCreate. It is possible in case we have only absolute url.
jmptrader/Nancy,fly19890211/Nancy,hitesh97/Nancy,JoeStead/Nancy,SaveTrees/Nancy,SaveTrees/Nancy,AIexandr/Nancy,malikdiarra/Nancy,ccellar/Nancy,SaveTrees/Nancy,MetSystem/Nancy,anton-gogolev/Nancy,sloncho/Nancy,duszekmestre/Nancy,AIexandr/Nancy,dbolkensteyn/Nancy,EIrwin/Nancy,blairconrad/Nancy,EliotJones/NancyTest,ayoung/Nancy,rudygt/Nancy,cgourlay/Nancy,Crisfole/Nancy,NancyFx/Nancy,grumpydev/Nancy,tparnell8/Nancy,sadiqhirani/Nancy,tsdl2013/Nancy,nicklv/Nancy,xt0rted/Nancy,NancyFx/Nancy,khellang/Nancy,damianh/Nancy,Novakov/Nancy,joebuschmann/Nancy,thecodejunkie/Nancy,sroylance/Nancy,khellang/Nancy,daniellor/Nancy,nicklv/Nancy,sloncho/Nancy,dbolkensteyn/Nancy,dbolkensteyn/Nancy,lijunle/Nancy,sloncho/Nancy,daniellor/Nancy,albertjan/Nancy,khellang/Nancy,dbabox/Nancy,vladlopes/Nancy,tparnell8/Nancy,anton-gogolev/Nancy,jeff-pang/Nancy,sadiqhirani/Nancy,jchannon/Nancy,MetSystem/Nancy,dbolkensteyn/Nancy,felipeleusin/Nancy,guodf/Nancy,jonathanfoster/Nancy,lijunle/Nancy,murador/Nancy,AlexPuiu/Nancy,jeff-pang/Nancy,ccellar/Nancy,sloncho/Nancy,jonathanfoster/Nancy,cgourlay/Nancy,lijunle/Nancy,anton-gogolev/Nancy,horsdal/Nancy,sroylance/Nancy,NancyFx/Nancy,JoeStead/Nancy,adamhathcock/Nancy,AIexandr/Nancy,cgourlay/Nancy,nicklv/Nancy,fly19890211/Nancy,jongleur1983/Nancy,rudygt/Nancy,charleypeng/Nancy,vladlopes/Nancy,duszekmestre/Nancy,adamhathcock/Nancy,jongleur1983/Nancy,danbarua/Nancy,AIexandr/Nancy,dbabox/Nancy,guodf/Nancy,ayoung/Nancy,tareq-s/Nancy,jonathanfoster/Nancy,Worthaboutapig/Nancy,guodf/Nancy,davidallyoung/Nancy,hitesh97/Nancy,jchannon/Nancy,tareq-s/Nancy,joebuschmann/Nancy,horsdal/Nancy,asbjornu/Nancy,Worthaboutapig/Nancy,tparnell8/Nancy,jonathanfoster/Nancy,NancyFx/Nancy,albertjan/Nancy,tareq-s/Nancy,felipeleusin/Nancy,nicklv/Nancy,VQComms/Nancy,albertjan/Nancy,duszekmestre/Nancy,jeff-pang/Nancy,grumpydev/Nancy,Novakov/Nancy,cgourlay/Nancy,sroylance/Nancy,AlexPuiu/Nancy,hitesh97/Nancy,xt0rted/Nancy,damianh/Nancy,VQComms/Nancy,duszekmestre/Nancy,tareq-s/Nancy,VQComms/Nancy,asbjornu/Nancy,Crisfole/Nancy,fly19890211/Nancy,EIrwin/Nancy,xt0rted/Nancy,ayoung/Nancy,thecodejunkie/Nancy,thecodejunkie/Nancy,VQComms/Nancy,phillip-haydon/Nancy,asbjornu/Nancy,thecodejunkie/Nancy,AcklenAvenue/Nancy,EliotJones/NancyTest,xt0rted/Nancy,blairconrad/Nancy,fly19890211/Nancy,ccellar/Nancy,blairconrad/Nancy,jchannon/Nancy,albertjan/Nancy,ayoung/Nancy,vladlopes/Nancy,daniellor/Nancy,charleypeng/Nancy,wtilton/Nancy,lijunle/Nancy,charleypeng/Nancy,blairconrad/Nancy,Novakov/Nancy,MetSystem/Nancy,murador/Nancy,jongleur1983/Nancy,jmptrader/Nancy,jmptrader/Nancy,malikdiarra/Nancy,horsdal/Nancy,phillip-haydon/Nancy,davidallyoung/Nancy,tsdl2013/Nancy,malikdiarra/Nancy,tparnell8/Nancy,sroylance/Nancy,hitesh97/Nancy,adamhathcock/Nancy,MetSystem/Nancy,davidallyoung/Nancy,AlexPuiu/Nancy,davidallyoung/Nancy,ccellar/Nancy,daniellor/Nancy,dbabox/Nancy,wtilton/Nancy,rudygt/Nancy,grumpydev/Nancy,guodf/Nancy,tsdl2013/Nancy,wtilton/Nancy,khellang/Nancy,wtilton/Nancy,danbarua/Nancy,rudygt/Nancy,AlexPuiu/Nancy,dbabox/Nancy,jongleur1983/Nancy,EIrwin/Nancy,JoeStead/Nancy,asbjornu/Nancy,EIrwin/Nancy,murador/Nancy,davidallyoung/Nancy,tsdl2013/Nancy,EliotJones/NancyTest,AcklenAvenue/Nancy,charleypeng/Nancy,anton-gogolev/Nancy,malikdiarra/Nancy,jchannon/Nancy,danbarua/Nancy,murador/Nancy,charleypeng/Nancy,danbarua/Nancy,asbjornu/Nancy,vladlopes/Nancy,joebuschmann/Nancy,felipeleusin/Nancy,horsdal/Nancy,JoeStead/Nancy,damianh/Nancy,phillip-haydon/Nancy,AcklenAvenue/Nancy,jmptrader/Nancy,AIexandr/Nancy,sadiqhirani/Nancy,felipeleusin/Nancy,EliotJones/NancyTest,sadiqhirani/Nancy,SaveTrees/Nancy,Worthaboutapig/Nancy,Novakov/Nancy,grumpydev/Nancy,AcklenAvenue/Nancy,VQComms/Nancy,jeff-pang/Nancy,adamhathcock/Nancy,joebuschmann/Nancy,phillip-haydon/Nancy,Crisfole/Nancy,Worthaboutapig/Nancy,jchannon/Nancy
src/Nancy/Extensions/RequestExtensions.cs
src/Nancy/Extensions/RequestExtensions.cs
namespace Nancy.Extensions { using System; using System.Linq; /// <summary> /// Containing extensions for the <see cref="Request"/> object /// </summary> public static class RequestExtensions { /// <summary> /// An extension method making it easy to check if the reqeuest was done using ajax /// </summary> /// <param name="request">The request made by client</param> /// <returns><see langword="true" /> if the request was done using ajax, otherwise <see langword="false"/>.</returns> public static bool IsAjaxRequest(this Request request) { const string ajaxRequestHeaderKey = "X-Requested-With"; const string ajaxRequestHeaderValue = "XMLHttpRequest"; return request.Headers[ajaxRequestHeaderKey].Contains(ajaxRequestHeaderValue); } /// <summary> /// Gets a value indicating whether the request is local. /// </summary> /// <param name="request">The request made by client</param> /// <returns><see langword="true" /> if the request is local, otherwise <see langword="false"/>.</returns> public static bool IsLocal(this Request request) { if (string.IsNullOrEmpty(request.UserHostAddress) || string.IsNullOrEmpty(request.Url)) { return false; } Uri uri = null; if (Uri.TryCreate(request.Url, UriKind.Absolute, out uri)) { return uri.IsLoopback; } else { // Invalid or relative Request.Url string return false; } } } }
namespace Nancy.Extensions { using System; using System.Linq; /// <summary> /// Containing extensions for the <see cref="Request"/> object /// </summary> public static class RequestExtensions { /// <summary> /// An extension method making it easy to check if the reqeuest was done using ajax /// </summary> /// <param name="request">The request made by client</param> /// <returns><see langword="true" /> if the request was done using ajax, otherwise <see langword="false"/>.</returns> public static bool IsAjaxRequest(this Request request) { const string ajaxRequestHeaderKey = "X-Requested-With"; const string ajaxRequestHeaderValue = "XMLHttpRequest"; return request.Headers[ajaxRequestHeaderKey].Contains(ajaxRequestHeaderValue); } /// <summary> /// Gets a value indicating whether the request is local. /// </summary> /// <param name="request">The request made by client</param> /// <returns><see langword="true" /> if the request is local, otherwise <see langword="false"/>.</returns> public static bool IsLocal(this Request request) { if (string.IsNullOrEmpty(request.UserHostAddress) || string.IsNullOrEmpty(request.Url)) { return false; } try { var uri = new Uri(request.Url); return uri.IsLoopback; } catch (Exception) { // Invalid Request.Url string return false; } } } }
mit
C#
bf94d3ef0b52e9444df9e3e3cc6896cac5ec4f06
Update Validator
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Services/Validator.cs
src/WeihanLi.Common/Services/Validator.cs
using System.ComponentModel.DataAnnotations; using WeihanLi.Extensions; using AnnotationValidationResult = System.ComponentModel.DataAnnotations.ValidationResult; using ValidationResult = WeihanLi.Common.Models.ValidationResult; namespace WeihanLi.Common.Services; public interface IValidator { ValidationResult Validate(object? value); } public interface IValidator<in T> { ValidationResult Validate(T value); } public interface IAsyncValidator<in T> { Task<ValidationResult> ValidateAsync(T value); } public sealed class DataAnnotationValidator : IValidator { public static IValidator Instance { get; } = new DataAnnotationValidator(); public ValidationResult Validate(object? value) { var validationResult = new ValidationResult(); if(value is null) { validationResult.Valid = false; validationResult.Errors ??= new Dictionary<string, string[]>(); validationResult.Errors[string.Empty] = new[]{ "Value is null" }; } else { var annotationValidateResults = new List<AnnotationValidationResult>(); validationResult.Valid = Validator.TryValidateObject(value, new ValidationContext(value), annotationValidateResults); validationResult.Errors = annotationValidateResults .GroupBy(x => x.MemberNames.StringJoin(",")) .ToDictionary(g => g.Key, g => g.Select(x => x.ErrorMessage).WhereNotNull().ToArray()); } return validationResult; } } public sealed class DelegateValidator : IValidator { private readonly Func<object?, ValidationResult> _validateFunc; public DelegateValidator(Func<object?, ValidationResult> validateFunc) { _validateFunc = Guard.NotNull(validateFunc); } public ValidationResult Validate(object? value) { return _validateFunc.Invoke(value); } } public sealed class DelegateValidator<T> : IValidator<T>, IAsyncValidator<T> { private readonly Func<T, Task<ValidationResult>> _validateFunc; public DelegateValidator(Func<T, ValidationResult> validateFunc) { Guard.NotNull(validateFunc); _validateFunc = t => validateFunc(t).WrapTask(); } public DelegateValidator(Func<T, Task<ValidationResult>> validateFunc) { _validateFunc = Guard.NotNull(validateFunc); } public ValidationResult Validate(T value) { return _validateFunc.Invoke(value).GetAwaiter().GetResult(); } public Task<ValidationResult> ValidateAsync(T value) { return _validateFunc.Invoke(value); } }
using System.ComponentModel.DataAnnotations; using WeihanLi.Extensions; using AnnotationValidationResult = System.ComponentModel.DataAnnotations.ValidationResult; using ValidationResult = WeihanLi.Common.Models.ValidationResult; namespace WeihanLi.Common.Services; public interface IValidator { ValidationResult Validate(object? value); } public interface IValidator<T> { Task<ValidationResult> ValidateAsync(T value); } public sealed class DataAnnotationValidator : IValidator { public static IValidator Instance { get; } static DataAnnotationValidator() { Instance = new DataAnnotationValidator(); } public ValidationResult Validate(object? value) { var validationResult = new ValidationResult(); if(value is null) { validationResult.Valid = false; validationResult.Errors ??= new Dictionary<string, string[]>(); validationResult.Errors[string.Empty] = new[]{ "Value is null" }; } else { var annotationValidateResults = new List<AnnotationValidationResult>(); validationResult.Valid = Validator.TryValidateObject(value, new ValidationContext(value), annotationValidateResults); validationResult.Errors = annotationValidateResults .GroupBy(x => x.MemberNames.StringJoin(",")) .ToDictionary(g => g.Key, g => g.Select(x => x.ErrorMessage).WhereNotNull().ToArray()); } return validationResult; } } public sealed class DelegateValidator : IValidator { private readonly Func<object?, ValidationResult> _validateFunc; public DelegateValidator(Func<object?, ValidationResult> validateFunc) { _validateFunc = Guard.NotNull(validateFunc); } public ValidationResult Validate(object? value) { return _validateFunc.Invoke(value); } } public sealed class DelegateValidator<T> : IValidator<T> { private readonly Func<T, Task<ValidationResult>> _validateFunc; public DelegateValidator(Func<T, Task<ValidationResult>> validateFunc) { _validateFunc = Guard.NotNull(validateFunc); } public Task<ValidationResult> ValidateAsync(T value) { return _validateFunc.Invoke(value); } }
mit
C#
c3a7892d0f730e0446e18daceb46922759501638
fix disposing on enable behavior.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/Behaviors/FocusOnEnableBehavior.cs
WalletWasabi.Fluent/Behaviors/FocusOnEnableBehavior.cs
using Avalonia; using System; using System.Reactive.Disposables; using System.Reactive.Linq; using Avalonia.Controls; using Avalonia.Input; namespace WalletWasabi.Fluent.Behaviors { public class FocusOnEnableBehavior : DisposingBehavior<Control> { protected override void OnAttached(CompositeDisposable disposables) { AssociatedObject .GetObservable(InputElement.IsEffectivelyEnabledProperty) .Where(x => x) .Subscribe(_ => AssociatedObject!.Focus()) .DisposeWith(disposables); } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Xaml.Interactivity; using System; using System.Reactive.Linq; namespace WalletWasabi.Fluent.Behaviors { public class FocusOnEnableBehavior : Behavior<Control> { protected override void OnAttached() { base.OnAttached(); Observable. FromEventPattern<AvaloniaPropertyChangedEventArgs>(AssociatedObject, nameof(AssociatedObject.PropertyChanged)) .Select(x => x.EventArgs) .Where(x => x.Property.Name == nameof(AssociatedObject.IsEffectivelyEnabled) && x.NewValue is { } && (bool)x.NewValue == true) .Subscribe(_ => AssociatedObject!.Focus()); } protected override void OnDetaching() { base.OnDetaching(); } } }
mit
C#
565dcaa3bd5e65ad172962d463c4f92907327183
Update version
masaedw/LineSharp
LineSharp/Properties/AssemblyInfo.cs
LineSharp/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("LineSharp")] [assembly: AssemblyDescription("A LINE Messaging API binding library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Masayuki Muto")] [assembly: AssemblyProduct("LineSharp")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("0a2c415b-a00f-4e04-83a2-2b1bbe72b73d")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.3.0")] [assembly: AssemblyFileVersion("0.1.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("LineSharp")] [assembly: AssemblyDescription("A LINE Messaging API binding library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Masayuki Muto")] [assembly: AssemblyProduct("LineSharp")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("0a2c415b-a00f-4e04-83a2-2b1bbe72b73d")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
eb493ec4dcc730adc178c12855e4d557ddc07074
Fix whitespace issue
petedavis/essential-templating
test/Essential.Templating.Razor.Tests/Templates/Test.ru.cshtml
test/Essential.Templating.Razor.Tests/Templates/Test.ru.cshtml
@using System @inherits Essential.Templating.Razor.Template Шаблон на русском языке. Выполненен @DateTime.Now
@using System @inherits Essential.Templating.Razor.Template Шаблон на русском языке. Выполненен @DateTime.Now
mit
C#
92376f447a9956c2c221242011dee7bcaa1ddd95
fix guard clause
xbehave/xbehave.net,hitesh97/xbehave.net,adamralph/xbehave.net,modulexcite/xbehave.net,mvalipour/xbehave.net,hitesh97/xbehave.net,modulexcite/xbehave.net,mvalipour/xbehave.net
src/Xbehave.2.Execution.desktop/Step.cs
src/Xbehave.2.Execution.desktop/Step.cs
// <copyright file="Step.cs" company="xBehave.net contributors"> // Copyright (c) xBehave.net contributors. All rights reserved. // </copyright> namespace Xbehave.Execution { using Xunit.Abstractions; using Xunit.Sdk; public class Step : LongLivedMarshalByRefObject, ITest { private readonly ITest scenario; private readonly string displayName; public Step(ITest scenario, string displayName) { Guard.AgainstNullArgument("scenario", scenario); this.scenario = scenario; this.displayName = displayName; } public ITest Scenario { get { return this.scenario; } } public string DisplayName { get { return this.displayName; } } public ITestCase TestCase { get { return this.scenario.TestCase; } } } }
// <copyright file="Step.cs" company="xBehave.net contributors"> // Copyright (c) xBehave.net contributors. All rights reserved. // </copyright> namespace Xbehave.Execution { using Xunit.Abstractions; using Xunit.Sdk; public class Step : LongLivedMarshalByRefObject, ITest { private readonly ITest scenario; private readonly string displayName; public Step(ITest scenario, string displayName) { Guard.AgainstNullArgument("testGroup", scenario); this.scenario = scenario; this.displayName = displayName; } public ITest Scenario { get { return this.scenario; } } public string DisplayName { get { return this.displayName; } } public ITestCase TestCase { get { return this.scenario.TestCase; } } } }
mit
C#
857af8ecd94a8172f2e7a332a0fda67a2dd41040
Add session options
andrewlock/blog-examples,andrewlock/blog-examples,andrewlock/blog-examples,andrewlock/blog-examples
using-session-state/src/UsingSessionState/Startup.cs
using-session-state/src/UsingSessionState/Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace UsingSessionState { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddDistributedMemoryCache(); services.AddSession(opts => { opts.CookieName = ".NetEscapades.Session"; opts.IdleTimeout = TimeSpan.FromSeconds(5); }); } // 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(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace UsingSessionState { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddDistributedMemoryCache(); services.AddSession(); } // 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(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
mit
C#
9b34e20521e6de1b3a68c8466516184861dcf804
update description
yb199478/catlib,CatLib/Framework
CatLib.VS/CatLib/API/Debugger/Internal/ILoggerAware.cs
CatLib.VS/CatLib/API/Debugger/Internal/ILoggerAware.cs
/* * This file is part of the CatLib package. * * (c) Yu Bin <support@catlib.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Document: http://catlib.io/ */ namespace CatLib.API.Debugger { /// <summary> /// 设定记录器实例接口 /// </summary> public interface ILoggerAware { /// <summary> /// 设定记录器实例接口 /// </summary> /// <param name="logger">记录器</param> void SetLogger(ILogger logger); } }
/* * This file is part of the CatLib package. * * (c) Yu Bin <support@catlib.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Document: http://catlib.io/ */ namespace CatLib.API.Debugger { /// <summary> /// 设定实例接口 /// </summary> public interface ILoggerAware { /// <summary> /// 设定记录器接口 /// </summary> /// <param name="logger">记录器</param> void SetLogger(ILogger logger); } }
unknown
C#
9405d44a5b0f8dbfe5c6bdd094ced11e6efb621c
Fix build
pharring/ApplicationInsights-dotnet,Microsoft/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet
Test/CoreSDK.Test/TestFramework/Shared/StubPlatform.cs
Test/CoreSDK.Test/TestFramework/Shared/StubPlatform.cs
namespace Microsoft.ApplicationInsights.TestFramework { using System; using System.Collections.Generic; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.ApplicationInsights.Extensibility.Implementation.External; internal class StubPlatform : IPlatform { public Func<IDictionary<string, object>> OnGetApplicationSettings = () => new Dictionary<string, object>(); public Func<IDebugOutput> OnGetDebugOutput = () => new StubDebugOutput(); public Func<string> OnReadConfigurationXml = () => null; public Func<Exception, ExceptionDetails, ExceptionDetails> OnGetExceptionDetails = (e, p) => new ExceptionDetails(); public string ReadConfigurationXml() { return this.OnReadConfigurationXml(); } public IDebugOutput GetDebugOutput() { return this.OnGetDebugOutput(); } public string GetEnvironmentVariable(string name) { return Environment.GetEnvironmentVariable(name); } } }
namespace Microsoft.ApplicationInsights.TestFramework { using System; using System.Collections.Generic; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.ApplicationInsights.Extensibility.Implementation.External; internal class StubPlatform : IPlatform { public Func<IDictionary<string, object>> OnGetApplicationSettings = () => new Dictionary<string, object>(); public Func<IDebugOutput> OnGetDebugOutput = () => new StubDebugOutput(); public Func<string> OnReadConfigurationXml = () => null; public Func<Exception, ExceptionDetails, ExceptionDetails> OnGetExceptionDetails = (e, p) => new ExceptionDetails(); public string ReadConfigurationXml() { return this.OnReadConfigurationXml(); } public IDebugOutput GetDebugOutput() { return this.OnGetDebugOutput(); } } }
mit
C#
368fb1ed53ea1f7cf60070437dc162e53742ebd1
Fix tests.
JohanLarsson/Gu.Units
Gu.Units.Tests/LengthUnitTests.cs
Gu.Units.Tests/LengthUnitTests.cs
namespace Gu.Units.Tests { using System; using NUnit.Framework; public class LengthUnitTests { public static string[] HappyPathSource { get; } = { "m", "mm", " cm", " m ", "ft", "yd" }; public static string[] ErrorSource { get; } = { "ssg", "mms" }; [TestCaseSource(nameof(HappyPathSource))] public void ParseSuccess(string text) { var lengthUnit = LengthUnit.Parse(text); Assert.AreEqual(text.Trim(), lengthUnit.ToString()); } [TestCaseSource(nameof(ErrorSource))] public void ParseError(string text) { Assert.Throws<FormatException>(() => LengthUnit.Parse(text)); LengthUnit temp; Assert.AreEqual(false, LengthUnit.TryParse(text, out temp)); } [TestCaseSource(nameof(HappyPathSource))] public void TryParseSuccess(string text) { LengthUnit result; Assert.AreEqual(true, LengthUnit.TryParse(text, out result)); Assert.AreEqual(text.Trim(), result.ToString()); } [TestCaseSource(nameof(ErrorSource))] public void TryParseError(string text) { LengthUnit temp; Assert.AreEqual(false, LengthUnit.TryParse(text, out temp)); } } }
namespace Gu.Units.Tests { using System; using System.Collections.Generic; using NUnit.Framework; public class LengthUnitTests { [TestCaseSource(nameof(HappyPathSource))] public void ParseSuccess(string text) { var lengthUnit = LengthUnit.Parse(text); Assert.AreEqual(text.Trim(), lengthUnit.ToString()); } [TestCaseSource(nameof(ErrorSource))] public void ParseError(string text) { Assert.Throws<FormatException>(() => LengthUnit.Parse(text)); LengthUnit temp; Assert.AreEqual(false, LengthUnit.TryParse(text, out temp)); } [TestCaseSource(nameof(HappyPathSource))] public void TryParseSuccess(string text) { LengthUnit result; Assert.AreEqual(true, LengthUnit.TryParse(text, out result)); Assert.AreEqual(text.Trim(), result.ToString()); } [TestCaseSource(nameof(ErrorSource))] public void TryParseError(string text) { LengthUnit temp; Assert.AreEqual(false, LengthUnit.TryParse(text, out temp)); } private IReadOnlyList<string> HappyPathSource = new[] { "m", "mm", " cm", " m ", "ft", "yd" }; private IReadOnlyList<string> ErrorSource = new[] { "ssg", "mms" }; } }
mit
C#
51510955c8a3dedc95f79d487b6963a75e3f4b8b
Fix a dumb bug in the interface generator
PKRoma/refit,ammachado/refit,jlucansky/refit,PureWeen/refit,mteper/refit,onovotny/refit,martijn00/refit,mteper/refit,jlucansky/refit,paulcbetts/refit,martijn00/refit,paulcbetts/refit,ammachado/refit,onovotny/refit,PureWeen/refit
InterfaceStubGenerator/Program.cs
InterfaceStubGenerator/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Refit.Generator { class Program { static void Main(string[] args) { // NB: @Compile passes us a list of files relative to the project // directory - we're going to assume that the target is always in // the same directory as the project file var generator = new InterfaceStubGenerator(); var target = new FileInfo(args[0]); var targetDir = target.DirectoryName; var files = args[1].Split(';') .Select(x => new FileInfo(Path.Combine(targetDir, x))) .ToArray(); var template = generator.GenerateInterfaceStubs(files.Select(x => x.FullName).ToArray()); File.WriteAllText(target.FullName, template); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Refit.Generator { class Program { static void Main(string[] args) { var generator = new InterfaceStubGenerator(); var target = new FileInfo(args[0]); var files = args[1].Split(';').Select(x => new FileInfo(x)).ToArray(); var template = generator.GenerateInterfaceStubs(files.Select(x => x.FullName).ToArray()); File.WriteAllText(target.FullName, template); } } }
mit
C#