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
ff401a82dcb5b50d6850dacc0d50c70da48ff860
Remove namespace
Haacked/Rothko
src/Threading/SystemSemaphore.cs
src/Threading/SystemSemaphore.cs
using System.Threading; namespace Rothko { public sealed class SystemSemaphore : ISystemSemaphore { readonly Semaphore innerSemaphore; public SystemSemaphore(int initialCount, int maximumCount, string name) { bool createdNewSemaphore; innerSemaphore = new Semaphore(initialCount, maximumCount, name, out createdNewSemaphore); AlreadyExists = !createdNewSemaphore; } public bool AlreadyExists { get; private set; } public bool WaitOne() { return innerSemaphore.WaitOne(); } public void Release() { innerSemaphore.Release(); } public void Dispose() { var semaphore = innerSemaphore; if (semaphore != null) { semaphore.Dispose(); } } } }
using System.Threading; namespace Rothko.Threading { public sealed class SystemSemaphore : ISystemSemaphore { readonly Semaphore innerSemaphore; public SystemSemaphore(int initialCount, int maximumCount, string name) { bool createdNewSemaphore; innerSemaphore = new Semaphore(initialCount, maximumCount, name, out createdNewSemaphore); AlreadyExists = !createdNewSemaphore; } public bool AlreadyExists { get; private set; } public bool WaitOne() { return innerSemaphore.WaitOne(); } public void Release() { innerSemaphore.Release(); } public void Dispose() { var semaphore = innerSemaphore; if (semaphore != null) { semaphore.Dispose(); } } } }
mit
C#
57fdb2835b59035ad759a4dd3ec7a916591648a3
Add test URL to libvideo.debug
jamesqo/libvideo,nguyenkien/libvideo,James-Ko/libvideo,i3arnon/libvideo,PFCKrutonium/libvideo,PFCKrutonium/libvideo,nguyenkien/libvideo,James-Ko/libvideo,jamesqo/libvideo
src/libvideo.debug/Program.cs
src/libvideo.debug/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using YoutubeExtractor; namespace VideoLibrary.Debug { class Program { static void Main(string[] args) { string[] queries = { // test queries, borrowed from // github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/youtube.py // "http://www.youtube.com/watch?v=6kLq3WMV1nU", // "http://www.youtube.com/watch?v=6kLq3WMV1nU", "https://www.youtube.com/watch?v=IB3lcPjvWLA", "https://www.youtube.com/watch?v=BgpXMA_M98o", "https://www.youtube.com/watch?v=nfWlot6h_JM" }; using (var cli = Client.For(YouTube.Default)) { for (int i = 0; i < queries.Length; i++) { string query = queries[i]; var video = cli.GetVideo(query); string uri = video.Uri; string otherUri = DownloadUrlResolver .GetDownloadUrls(query).First() .DownloadUrl; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using YoutubeExtractor; namespace VideoLibrary.Debug { class Program { static void Main(string[] args) { string[] queries = { // test queries, borrowed from // github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/youtube.py // "http://www.youtube.com/watch?v=6kLq3WMV1nU", // "http://www.youtube.com/watch?v=6kLq3WMV1nU", "https://www.youtube.com/watch?v=IB3lcPjvWLA", "https://www.youtube.com/watch?v=BgpXMA_M98o" }; using (var cli = Client.For(YouTube.Default)) { for (int i = 0; i < queries.Length; i++) { string query = queries[i]; var video = cli.GetVideo(query); string uri = video.Uri; string otherUri = DownloadUrlResolver .GetDownloadUrls(query).First() .DownloadUrl; } } } } }
bsd-2-clause
C#
b9215d214e282fdf9764583b692770bfb3044e22
Fix ContainerSlot not serializing correctly when empty.
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content
Content.Server/GameObjects/ContainerSlot.cs
Content.Server/GameObjects/ContainerSlot.cs
using System; using Robust.Server.GameObjects.Components.Container; using Robust.Server.Interfaces.GameObjects; using Robust.Shared.Interfaces.GameObjects; using System.Collections.Generic; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects { public class ContainerSlot : BaseContainer { [ViewVariables] public IEntity ContainedEntity { get; private set; } = null; /// <inheritdoc /> public override IReadOnlyCollection<IEntity> ContainedEntities { get { if (ContainedEntity == null) { return Array.Empty<IEntity>(); } return new List<IEntity> {ContainedEntity}.AsReadOnly(); } } public ContainerSlot(string id, IContainerManager manager) : base(id, manager) { } /// <inheritdoc /> public override bool CanInsert(IEntity toinsert) { if (ContainedEntity != null) return false; return base.CanInsert(toinsert); } /// <inheritdoc /> public override bool Contains(IEntity contained) { if (contained != null && contained == ContainedEntity) return true; return false; } /// <inheritdoc /> protected override void InternalInsert(IEntity toinsert) { ContainedEntity = toinsert; base.InternalInsert(toinsert); } /// <inheritdoc /> protected override void InternalRemove(IEntity toremove) { ContainedEntity = null; base.InternalRemove(toremove); } public override void Shutdown() { base.Shutdown(); ContainedEntity?.Delete(); } } }
using Robust.Server.GameObjects.Components.Container; using Robust.Server.Interfaces.GameObjects; using Robust.Shared.Interfaces.GameObjects; using System.Collections.Generic; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects { public class ContainerSlot : BaseContainer { [ViewVariables] public IEntity ContainedEntity { get; private set; } = null; /// <inheritdoc /> public override IReadOnlyCollection<IEntity> ContainedEntities => new List<IEntity> { ContainedEntity }.AsReadOnly(); public ContainerSlot(string id, IContainerManager manager) : base(id, manager) { } /// <inheritdoc /> public override bool CanInsert(IEntity toinsert) { if (ContainedEntity != null) return false; return base.CanInsert(toinsert); } /// <inheritdoc /> public override bool Contains(IEntity contained) { if (contained != null && contained == ContainedEntity) return true; return false; } /// <inheritdoc /> protected override void InternalInsert(IEntity toinsert) { ContainedEntity = toinsert; base.InternalInsert(toinsert); } /// <inheritdoc /> protected override void InternalRemove(IEntity toremove) { ContainedEntity = null; base.InternalRemove(toremove); } public override void Shutdown() { base.Shutdown(); ContainedEntity?.Delete(); } } }
mit
C#
8a6977213a285344f81a987af80cd0d6337ac243
Fix displayed scores in gameplay leaderboard not tracking display mode changes
ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu
osu.Game/Screens/Play/HUD/SoloGameplayLeaderboard.cs
osu.Game/Screens/Play/HUD/SoloGameplayLeaderboard.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Online.Leaderboards; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; using osu.Game.Users; namespace osu.Game.Screens.Play.HUD { public class SoloGameplayLeaderboard : GameplayLeaderboard { private readonly IUser trackingUser; private readonly IBindableList<ScoreInfo> scores = new BindableList<ScoreInfo>(); // hold references to ensure bindables are updated. private readonly List<Bindable<long>> scoreBindables = new List<Bindable<long>>(); [Resolved] private ScoreProcessor scoreProcessor { get; set; } = null!; [Resolved] private ScoreManager scoreManager { get; set; } = null!; public SoloGameplayLeaderboard(IUser trackingUser) { this.trackingUser = trackingUser; } [BackgroundDependencyLoader(true)] private void load(ILeaderboardScoreSource? scoreSource) { if (scoreSource != null) scores.BindTo(scoreSource.Scores); scores.BindCollectionChanged((_, _) => Scheduler.AddOnce(showScores), true); } private void showScores() { Clear(); scoreBindables.Clear(); if (!scores.Any()) return; ILeaderboardScore local = Add(trackingUser, true); local.TotalScore.BindTarget = scoreProcessor.TotalScore; local.Accuracy.BindTarget = scoreProcessor.Accuracy; local.Combo.BindTarget = scoreProcessor.Combo; foreach (var s in scores) { var score = Add(s.User, false); var bindableTotal = scoreManager.GetBindableTotalScore(s); // Direct binding not possible due to differing types (see https://github.com/ppy/osu/issues/20298). bindableTotal.BindValueChanged(total => score.TotalScore.Value = total.NewValue, true); scoreBindables.Add(bindableTotal); score.Accuracy.Value = s.Accuracy; score.Combo.Value = s.MaxCombo; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Online.Leaderboards; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; using osu.Game.Users; namespace osu.Game.Screens.Play.HUD { public class SoloGameplayLeaderboard : GameplayLeaderboard { private readonly IUser trackingUser; private readonly IBindableList<ScoreInfo> scores = new BindableList<ScoreInfo>(); [Resolved] private ScoreProcessor scoreProcessor { get; set; } = null!; public SoloGameplayLeaderboard(IUser trackingUser) { this.trackingUser = trackingUser; } [BackgroundDependencyLoader(true)] private void load(ILeaderboardScoreSource? scoreSource) { if (scoreSource != null) scores.BindTo(scoreSource.Scores); scores.BindCollectionChanged((_, __) => Scheduler.AddOnce(showScores, scores), true); } private void showScores(IEnumerable<IScoreInfo> scores) { Clear(); if (!scores.Any()) return; ILeaderboardScore local = Add(trackingUser, true); local.TotalScore.BindTarget = scoreProcessor.TotalScore; local.Accuracy.BindTarget = scoreProcessor.Accuracy; local.Combo.BindTarget = scoreProcessor.Combo; foreach (var s in scores) { var score = Add(s.User, false); score.TotalScore.Value = s.TotalScore; score.Accuracy.Value = s.Accuracy; score.Combo.Value = s.MaxCombo; } } } }
mit
C#
a6d7fa5fe4eb2a61739259c0b586204f94ac9d4b
Send empty line for StackTrace to Bugsnag if Stack is absent in the Exception object
awseward/Bugsnag.NET,awseward/Bugsnag.NET
Bugsnag.NET/Extensions/Extensions.cs
Bugsnag.NET/Extensions/Extensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Bugsnag.NET.Extensions { static class Extensions { /// <remarks>Not sure I'm really thrilled with this...</remarks> public static IEnumerable<Exception> Unwrap(this Exception ex) { if (ex == null) { return Enumerable.Empty<Exception>(); } else if (ex.InnerException == null) { return new Exception[] { ex }; } return ex.InnerException.Unwrap().Concat(new Exception[] { ex }); } public static IEnumerable<string> ToLines(this Exception ex) { if (ex == null || ex.StackTrace == null) { return new string[] { String.Empty }; } return ex.StackTrace.Split( new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } public static string ParseFile(this string line) { var match = Regex.Match(line, "in (.+):line"); if (match.Groups.Count < 2) { return "[file]"; } return match.Groups[1].Value; } public static string ParseMethodName(this string line) { var match = Regex.Match(line, "at .+\\.([^\\.]+\\(.*\\))"); if (match.Groups.Count < 2) { return "[method]"; } return match.Groups[1].Value; } public static int ParseLineNumber(this string line) { var match = Regex.Match(line, ":line ([0-9]+)"); if (match.Groups.Count < 2) { return -1; } return Convert.ToInt32(match.Groups[1].Value); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Bugsnag.NET.Extensions { static class Extensions { /// <remarks>Not sure I'm really thrilled with this...</remarks> public static IEnumerable<Exception> Unwrap(this Exception ex) { if (ex == null) { return Enumerable.Empty<Exception>(); } else if (ex.InnerException == null) { return new Exception[] { ex }; } return ex.InnerException.Unwrap().Concat(new Exception[] { ex }); } public static IEnumerable<string> ToLines(this Exception ex) { if (ex == null || ex.StackTrace == null) { return Enumerable.Empty<string>(); } return ex.StackTrace.Split( new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } public static string ParseFile(this string line) { var match = Regex.Match(line, "in (.+):line"); if (match.Groups.Count < 2) { return "[file]"; } return match.Groups[1].Value; } public static string ParseMethodName(this string line) { var match = Regex.Match(line, "at .+\\.([^\\.]+\\(.*\\))"); if (match.Groups.Count < 2) { return "[method]"; } return match.Groups[1].Value; } public static int ParseLineNumber(this string line) { var match = Regex.Match(line, ":line ([0-9]+)"); if (match.Groups.Count < 2) { return -1; } return Convert.ToInt32(match.Groups[1].Value); } } }
mit
C#
7463b81a1f205fd7e5d1cba012f001bf57eaf0ef
Add test ensuring that user id is copied from request if present
Microsoft/ApplicationInsights-SDK-Labs
WCF/Shared.Tests/UserTelemetryInitializerTests.cs
WCF/Shared.Tests/UserTelemetryInitializerTests.cs
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Security.Principal; using System.ServiceModel; namespace Microsoft.ApplicationInsights.Wcf.Tests { [TestClass] public class UserTelemetryInitializerTests { [TestMethod] public void AnonymousDoesNotIncludeUserId() { var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; var authContext = new SimpleAuthorizationContext(); context.SecurityContext = new ServiceSecurityContext(authContext); var initializer = new UserTelemetryInitializer(); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry, context); Assert.IsNull(telemetry.Context.User.Id); } [TestMethod] public void AuthenticatedRequestFillsUserIdWithUserName() { var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; var authContext = new SimpleAuthorizationContext(); authContext.AddIdentity(new GenericIdentity("myuser")); context.SecurityContext = new ServiceSecurityContext(authContext); var initializer = new UserTelemetryInitializer(); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry, context); Assert.AreEqual("myuser", telemetry.Context.User.Id); } [TestMethod] public void UserIdCopiedFromRequestIfPresent() { const String userName = "MyUserName"; var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; context.Request.Context.User.Id = userName; var initializer = new UserTelemetryInitializer(); var telemetry = new EventTelemetry(); initializer.Initialize(telemetry, context); Assert.AreEqual(userName, telemetry.Context.User.Id); } } }
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Security.Principal; using System.ServiceModel; namespace Microsoft.ApplicationInsights.Wcf.Tests { [TestClass] public class UserTelemetryInitializerTests { [TestMethod] public void AnonymousDoesNotIncludeUserId() { var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; var authContext = new SimpleAuthorizationContext(); context.SecurityContext = new ServiceSecurityContext(authContext); var initializer = new UserTelemetryInitializer(); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry, context); Assert.IsNull(telemetry.Context.User.Id); } [TestMethod] public void AuthenticatedRequestFillsUserIdWithUserName() { var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; var authContext = new SimpleAuthorizationContext(); authContext.AddIdentity(new GenericIdentity("myuser")); context.SecurityContext = new ServiceSecurityContext(authContext); var initializer = new UserTelemetryInitializer(); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry, context); Assert.AreEqual("myuser", telemetry.Context.User.Id); } } }
mit
C#
fd6fd44a1dfa836df15798adbbaaf8171a22270d
Update assembly
Ulterius/server
RemoteTaskServer/Properties/AssemblyInfo.cs
RemoteTaskServer/Properties/AssemblyInfo.cs
#region using System.Reflection; using System.Runtime.InteropServices; using log4net.Config; #endregion // 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("Ulterius™ Server")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ulterius")] [assembly: AssemblyProduct("Ulterius Server")] [assembly: AssemblyCopyright("Copyright © Octopodal Solutions 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8faa6465-7d15-4c77-9b5f-d9495293a794")] // 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.5")] [assembly: AssemblyFileVersion("1.0.0.5")] [assembly: XmlConfigurator]
#region using System.Reflection; using System.Runtime.InteropServices; using log4net.Config; #endregion // 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("Ulterius™ Server")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ulterius")] [assembly: AssemblyProduct("Ulterius Server")] [assembly: AssemblyCopyright("Copyright © Octopodal Solutions 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8faa6465-7d15-4c77-9b5f-d9495293a794")] // 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.4")] [assembly: AssemblyFileVersion("1.0.0.4")] [assembly: XmlConfigurator]
mpl-2.0
C#
e4eed71802e01d243739c8e8f029a594b25c3eef
Replace default fav icon
melvinlee/nancy-api,melvinlee/nancy-api
src/nancy-api/Bootstrapper.cs
src/nancy-api/Bootstrapper.cs
using Nancy; using NancyApi.Repository; namespace NancyApi { public class Bootstrapper : DefaultNancyBootstrapper { // The bootstrapper enables you to reconfigure the composition of the framework, // by overriding the various methods and properties. // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); // Register repository as singleton for persistant data source container.Register<TunnelRepository>().AsSingleton(); } protected override byte[] FavIcon { get { return null; } } } }
using Nancy; using NancyApi.Repository; namespace NancyApi { public class Bootstrapper : DefaultNancyBootstrapper { // The bootstrapper enables you to reconfigure the composition of the framework, // by overriding the various methods and properties. // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); // Register repository as singleton for persistant data source container.Register<TunnelRepository>().AsSingleton(); } } }
mit
C#
199f7a85adf55ad36e14f252270b8ce5f197a702
Support for netstandard2.1 as per Issue #116
mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker
Ductus.FluentDocker/Common/Logger.cs
Ductus.FluentDocker/Common/Logger.cs
#if NETSTANDARD2_1 using Microsoft.Extensions.Logging.Debug; #endif #if COREFX using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; #endif namespace Ductus.FluentDocker.Common { internal static class Logger { internal static bool Enabled = true; public static void Log(string message) { if (!Enabled) return; #if COREFX ILogger.Value.LogTrace(message); } private static readonly Lazy<ILogger> ILogger = new Lazy<ILogger>(() => { var factory = new ServiceCollection().AddLogging().BuildServiceProvider().GetRequiredService<ILoggerFactory>(); #if NETSTANDARD2_1 factory.AddProvider(new DebugLoggerProvider()); #else factory.AddDebug(); #endif return factory.CreateLogger(Constants.DebugCategory); }); #else System.Diagnostics.Debugger.Log((int)System.Diagnostics.TraceLevel.Verbose, Constants.DebugCategory, message); } #endif } }
#if COREFX #if NETSTANDARD2_1 using Microsoft.Extensions.Logging.Debug; #endif using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; #endif namespace Ductus.FluentDocker.Common { internal static class Logger { internal static bool Enabled = true; public static void Log(string message) { if (!Enabled) return; #if COREFX ILogger.Value.LogTrace(message); } private static readonly Lazy<ILogger> ILogger = new Lazy<ILogger>(() => { var factory = new ServiceCollection().AddLogging().BuildServiceProvider().GetRequiredService<ILoggerFactory>(); #if NETSTANDARD2_1 factory.AddProvider(new DebugLoggerProvider()); #else factory.AddDebug(); #endif return factory.CreateLogger(Constants.DebugCategory); }); #else System.Diagnostics.Debugger.Log((int)System.Diagnostics.TraceLevel.Verbose, Constants.DebugCategory, message); } #endif } }
apache-2.0
C#
0b8f328e63773339f966131d396f63a94192c497
Add comment about comment source
mattgwagner/CertiPay.Payroll.Common
CertiPay.Payroll.Common/TaxCalculationType.cs
CertiPay.Payroll.Common/TaxCalculationType.cs
using System.Collections.Generic; namespace CertiPay.Payroll.Common { /// <summary> /// The tax method indicates the tax calculation method to be used for the pay. /// </summary> public enum TaxCalculationType : byte { // Note: These descriptions were from the Oracle/PeopleSoft documentation and seemed to be the most descriptive I could find /// <summary> /// Annualized: Select to annualize the earnings, calculate the tax on the annualized amount, and divide the tax by the number of pay periods in the year. /// The result is the withholding for the pay period. This is the most common tax method. /// </summary> Annualized = 1, /// <summary> /// (USA) Supplemental: Select to calculate taxes as a straight percentage of earnings. This method is typically used for one-time pays, /// such as bonuses. For example, federal supplemental withholding is 25 percent of earnings. Some states vary the percentage based on annual income, /// while some states require PeopleSoft-maintained tax tables to calculate withholding. /// </summary> Supplemental = 2, /// <summary> /// (USA) Aggregate: Select to tax the lump sum of the current payment with a previous payment. The system takes the last confirmed paycheck for that /// pay period and adds the current payment to it. Taxes are calculated on that lump sum amount, the taxes that were withheld on the confirmed check are subtracted, /// and the resulting tax difference is the tax for the current payment. /// </summary> Aggregate = 3, /// <summary> /// Cumulative: Select to add together the year-to-date earnings and the earnings for this pay period, annualize the result, /// and calculate the annualized tax. The system deannualizes the tax by dividing it by the number of tax periods you specified on the paysheet. /// The result is compared to the year-to-date withholding; if it is greater than the year-to-date withholding, the difference becomes the withholding /// for the pay period. You generally use this for employees whose wages vary significantly from pay period to pay period, such as salespeople on commission. /// </summary> Cumulative = 4, } public static class TaxCalculationTypes { public static IEnumerable<TaxCalculationType> Values() { yield return TaxCalculationType.Annualized; yield return TaxCalculationType.Supplemental; yield return TaxCalculationType.Aggregate; yield return TaxCalculationType.Cumulative; } } }
using System.Collections.Generic; namespace CertiPay.Payroll.Common { /// <summary> /// The tax method indicates the tax calculation method to be used for the pay. /// </summary> public enum TaxCalculationType : byte { /// <summary> /// Annualized: Select to annualize the earnings, calculate the tax on the annualized amount, and divide the tax by the number of pay periods in the year. /// The result is the withholding for the pay period. This is the most common tax method. /// </summary> Annualized = 1, /// <summary> /// (USA) Supplemental: Select to calculate taxes as a straight percentage of earnings. This method is typically used for one-time pays, /// such as bonuses. For example, federal supplemental withholding is 25 percent of earnings. Some states vary the percentage based on annual income, /// while some states require PeopleSoft-maintained tax tables to calculate withholding. /// </summary> Supplemental = 2, /// <summary> /// (USA) Aggregate: Select to tax the lump sum of the current payment with a previous payment. The system takes the last confirmed paycheck for that /// pay period and adds the current payment to it. Taxes are calculated on that lump sum amount, the taxes that were withheld on the confirmed check are subtracted, /// and the resulting tax difference is the tax for the current payment. /// </summary> Aggregate = 3, /// <summary> /// Cumulative: Select to add together the year-to-date earnings and the earnings for this pay period, annualize the result, /// and calculate the annualized tax. The system deannualizes the tax by dividing it by the number of tax periods you specified on the paysheet. /// The result is compared to the year-to-date withholding; if it is greater than the year-to-date withholding, the difference becomes the withholding /// for the pay period. You generally use this for employees whose wages vary significantly from pay period to pay period, such as salespeople on commission. /// </summary> Cumulative = 4, } public static class TaxCalculationTypes { public static IEnumerable<TaxCalculationType> Values() { yield return TaxCalculationType.Annualized; yield return TaxCalculationType.Supplemental; yield return TaxCalculationType.Aggregate; yield return TaxCalculationType.Cumulative; } } }
mit
C#
07e45906fb143b9c0cc3d8dd7ea3a1527bb4d4d5
return empty list if no data in database
UNOPS/nofy
Nofy.EntityFrameworkCore/Extensions.cs
Nofy.EntityFrameworkCore/Extensions.cs
namespace Nofy.EntityFrameworkCore { using System; using System.Collections.Generic; using System.Linq; using LinqKit; using Microsoft.EntityFrameworkCore; using Nofy.Core; using Nofy.Core.Helper; using Nofy.Core.Model; internal static class Extensions { public static void AddConfiguration<TEntity>( this ModelBuilder modelBuilder, DbEntityConfiguration<TEntity> entityConfiguration) where TEntity : class { modelBuilder.Entity<TEntity>(entityConfiguration.Configure); } public static IQueryable<Notification> BelongingTo(this IQueryable<Notification> queryable, params NotificationRecipient[] filters) { var filter = PredicateBuilder.New<Notification>(true); foreach (var recipient in filters) { filter = filter.Or(t => t.RecipientType == recipient.RecipientType && t.RecipientId == recipient.RecipientId); } return queryable .Where(filter); } public static PaginatedData<T> Paginate<T>( this IQueryable<T> query, int pageNum, int pageSize) { if (pageSize <= 0) { pageSize = 10; } //Total result count var rowsCount = query.Count(); // Return empty list if there is no data if (rowsCount <= 0) { return new PaginatedData<T> { Results = new List<T>(), TotalCount = rowsCount }; } //If page number should be > 0 else set to first page if (rowsCount <= pageSize || pageNum <= 0) { pageNum = 1; } //Calculate number of rows to skip on page size var excludedRows = (pageNum - 1) * pageSize; return new PaginatedData<T> { Results = query.Skip(excludedRows).Take(Math.Min(pageSize, rowsCount)).ToArray(), TotalCount = rowsCount }; } } }
namespace Nofy.EntityFrameworkCore { using System; using System.Linq; using LinqKit; using Microsoft.EntityFrameworkCore; using Nofy.Core; using Nofy.Core.Helper; using Nofy.Core.Model; internal static class Extensions { public static void AddConfiguration<TEntity>( this ModelBuilder modelBuilder, DbEntityConfiguration<TEntity> entityConfiguration) where TEntity : class { modelBuilder.Entity<TEntity>(entityConfiguration.Configure); } public static IQueryable<Notification> BelongingTo(this IQueryable<Notification> queryable, params NotificationRecipient[] filters) { var filter = PredicateBuilder.New<Notification>(true); foreach (var recipient in filters) { filter = filter.Or(t => t.RecipientType == recipient.RecipientType && t.RecipientId == recipient.RecipientId); } return queryable .Where(filter); } public static PaginatedData<T> Paginate<T>( this IQueryable<T> query, int pageNum, int pageSize) { if (pageSize <= 0) { pageSize = 10; } //Total result count var rowsCount = query.Count(); //If page number should be > 0 else set to first page if (rowsCount <= pageSize || pageNum <= 0) { pageNum = 1; } //Calculate number of rows to skip on page size var excludedRows = (pageNum - 1) * pageSize; return new PaginatedData<T> { Results = query.Skip(excludedRows).Take(Math.Min(pageSize, rowsCount)).ToArray(), TotalCount = rowsCount }; } } }
mit
C#
60db1da561df9af4a58fc06ee1b5f031d651584d
Fix extension folder detection in StringExtensions
Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder
PathfinderAPI/Util/StringExtensions.cs
PathfinderAPI/Util/StringExtensions.cs
using System; using System.IO; using Hacknet; using Hacknet.Extensions; namespace Pathfinder.Util { public static class StringExtensions { public static bool HasContent(this string s) => !string.IsNullOrWhiteSpace(s); public static bool ContentFileExists(this string filename) => File.Exists(filename.ContentFilePath()); public static string ContentFilePath(this string filename) { filename = filename.Replace("\\", "/"); var extFolder = ExtensionLoader.ActiveExtensionInfo.FolderPath.Replace("\\", "/"); if (Settings.IsInExtensionMode) return filename.StartsWith(extFolder) ? filename : Path.Combine(extFolder, filename); return filename.StartsWith("Content/") ? filename : Path.Combine("Content", filename); } public static string Filter(this string s) => s == null ? null : ComputerLoader.filter(s); } }
using System; using System.IO; using Hacknet; using Hacknet.Extensions; namespace Pathfinder.Util { public static class StringExtensions { public static bool HasContent(this string s) => !string.IsNullOrWhiteSpace(s); public static bool ContentFileExists(this string filename) => File.Exists(filename.ContentFilePath()); public static string ContentFilePath(this string filename) { if (Settings.IsInExtensionMode) return filename.StartsWith(ExtensionLoader.ActiveExtensionInfo.FolderPath.Replace("\\", "/")) ? filename : ExtensionLoader.ActiveExtensionInfo.FolderPath + "/" + filename; return filename.StartsWith("Content/") ? filename : "Content/" + filename; } public static string Filter(this string s) => s == null ? null : ComputerLoader.filter(s); } }
mit
C#
4c746dfda428f251a275703c5e691b8b746e3e12
Fix assembly title
punker76/Espera,flagbug/Espera
Espera/Espera.View/Properties/AssemblyInfo.cs
Espera/Espera.View/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("Espera")] [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("Espera.View")] [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )]
mit
C#
c91156563143e011c5302e4006fc2dd5d716bd61
bump version
adamabdelhamed/PowerArgs,BlackFrog1/PowerArgs,BlackFrog1/PowerArgs,workabyte/PowerArgs,adamabdelhamed/PowerArgs,workabyte/PowerArgs
PowerArgs/Properties/AssemblyInfo.cs
PowerArgs/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("PowerArgs")] [assembly: AssemblyDescription("The ultimate .NET command line parser")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adam Abdelhamed")] [assembly: AssemblyProduct("PowerArgs")] [assembly: AssemblyCopyright("Copyright © Adam Abdelhamed 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("51f35512-6b0a-4828-95f7-e01083a9edd4")] // 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.8.0.0")] [assembly: AssemblyFileVersion("2.8.0.0")] //[assembly: InternalsVisibleTo("ArgsTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100599691571e51717eff0888f672ef5295866ae3749279076ba157e93eae2376a9867a2c1057b5e2f247d258de7b017e77c3ba5362ef2258f9af78e3a4a12dba4920b74df312454148da53396b7475e1e801ca42928296555f4a5dc90497ebae144680fb33bec22a86e4a7954bf66c94592c331a01f0e73c9b6db0b8e0ecb8fab1")] [assembly: InternalsVisibleTo("ArgsTests")]
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("PowerArgs")] [assembly: AssemblyDescription("The ultimate .NET command line parser")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adam Abdelhamed")] [assembly: AssemblyProduct("PowerArgs")] [assembly: AssemblyCopyright("Copyright © Adam Abdelhamed 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("51f35512-6b0a-4828-95f7-e01083a9edd4")] // 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.7.2.0")] [assembly: AssemblyFileVersion("2.7.2.0")] //[assembly: InternalsVisibleTo("ArgsTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100599691571e51717eff0888f672ef5295866ae3749279076ba157e93eae2376a9867a2c1057b5e2f247d258de7b017e77c3ba5362ef2258f9af78e3a4a12dba4920b74df312454148da53396b7475e1e801ca42928296555f4a5dc90497ebae144680fb33bec22a86e4a7954bf66c94592c331a01f0e73c9b6db0b8e0ecb8fab1")] [assembly: InternalsVisibleTo("ArgsTests")]
mit
C#
920580c3368c4a0ad86d2bf9f8c640ab19c68656
Resolve #691 -- Split help command to multiple messages (#690)
LeagueSandbox/GameServer
GameServerLib/Chatbox/Commands/HelpCommand.cs
GameServerLib/Chatbox/Commands/HelpCommand.cs
using ENet; namespace LeagueSandbox.GameServer.Chatbox.Commands { public class HelpCommand : ChatCommandBase { private const string COMMAND_PREFIX = "<font color=\"#E175FF\"><b>"; private const string COMMAND_SUFFIX = "</b></font>, "; private readonly int MESSAGE_MAX_SIZE = 512; public override string Command => "help"; public override string Syntax => $"{Command}"; public HelpCommand(ChatCommandManager chatCommandManager, Game game) : base(chatCommandManager, game) { } public override void Execute(Peer peer, bool hasReceivedArguments, string arguments = "") { if (!Game.Config.ChatCheatsEnabled) { var msg = "[LS] Chat commands are disabled in this game."; ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.INFO, msg); return; } var commands = ChatCommandManager.GetCommandsStrings(); var commandsString = ""; var lastCommandString = ""; var isNewMessage = false; ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.INFO, "List of available commands: "); foreach (var command in commands) { if(isNewMessage) { commandsString = System.String.Copy(lastCommandString); isNewMessage = false; } lastCommandString = $"{COMMAND_PREFIX}" + $"{ChatCommandManager.CommandStarterCharacter}{command}" + $"{COMMAND_SUFFIX}"; if(commandsString.Length + lastCommandString.Length >= MESSAGE_MAX_SIZE) { ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.NORMAL, commandsString); commandsString = ""; isNewMessage = true; } else { commandsString = $"{commandsString}{lastCommandString}"; } } if (commandsString.Length != 0) { ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.NORMAL, commandsString); } ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.INFO, "There are " + commands.Count + " commands"); } } }
using ENet; namespace LeagueSandbox.GameServer.Chatbox.Commands { public class HelpCommand : ChatCommandBase { private const string COMMAND_PREFIX = "<font color =\"#E175FF\"><b>"; private const string COMMAND_SUFFIX = "</b></font>, "; public override string Command => "help"; public override string Syntax => $"{Command}"; public HelpCommand(ChatCommandManager chatCommandManager, Game game) : base(chatCommandManager, game) { } public override void Execute(Peer peer, bool hasReceivedArguments, string arguments = "") { if (!Game.Config.ChatCheatsEnabled) { var msg = "[LS] Chat commands are disabled in this game."; ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.INFO, msg); return; } var commands = ChatCommandManager.GetCommandsStrings(); var commandsString = ""; foreach (var command in commands) { commandsString = $"{commandsString}{COMMAND_PREFIX}" + $"{ChatCommandManager.CommandStarterCharacter}{command}" + $"{COMMAND_SUFFIX}"; } ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.INFO, "List of available commands: "); ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.INFO, commandsString); ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.INFO, "There are " + commands.Count + " commands"); } } }
agpl-3.0
C#
c5d92d29b2a8b95d1a4cf01b73d5d57ec5bac7b2
Add Util for getting scripts of a specific type
PearMed/Pear-Interaction-Engine
Scripts/Utils/ComponentExtensions.cs
Scripts/Utils/ComponentExtensions.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; namespace Pear.InteractionEngine.Utils { /// <summary> /// Extension methods for components /// </summary> static public class ComponentExtensions { /// <summary> /// Gets or add a component. Usage example: /// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>(); /// </summary> public static T GetOrAddComponent<T>(this Component child) where T : Component { T result = child.GetComponent<T>(); if (result == null) { result = child.gameObject.AddComponent<T>(); } return result; } /// <summary> /// Copies values from one component to another /// </summary> /// <typeparam name="T">Type of component</typeparam> /// <param name="copyTo">Component to copy to</param> /// <param name="copyFrom">Component to copy from</param> /// <returns></returns> public static T GetCopyOf<T>(this Component copyTo, T copyFrom) where T : Component { Type type = copyTo.GetType(); if (type != copyFrom.GetType()) return null; // type mis-match BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; IEnumerable<PropertyInfo> pinfos = type.GetProperties(flags); foreach (var pinfo in pinfos) { if (pinfo.CanWrite) { try { pinfo.SetValue(copyTo, pinfo.GetValue(copyFrom, null), null); } catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific. } } IEnumerable<FieldInfo> finfos = type.GetFields(flags); foreach (var finfo in finfos) { finfo.SetValue(copyTo, finfo.GetValue(copyFrom)); } return copyTo as T; } /// <summary> /// Gets all scripts /// </summary> /// <typeparam name="T"></typeparam> /// <param name="component"></param> /// <returns></returns> public static T[] GetScripts<T>(this Component component) where T : class { Component[] components = component.GetComponents(typeof(T)); return components.Select(c => (T)(object)c).ToArray(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; namespace Pear.InteractionEngine.Utils { /// <summary> /// Extension methods for components /// </summary> static public class ComponentExtensions { /// <summary> /// Gets or add a component. Usage example: /// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>(); /// </summary> public static T GetOrAddComponent<T>(this Component child) where T : Component { T result = child.GetComponent<T>(); if (result == null) { result = child.gameObject.AddComponent<T>(); } return result; } /// <summary> /// Copies values from one component to another /// </summary> /// <typeparam name="T">Type of component</typeparam> /// <param name="copyTo">Component to copy to</param> /// <param name="copyFrom">Component to copy from</param> /// <returns></returns> public static T GetCopyOf<T>(this Component copyTo, T copyFrom) where T : Component { Type type = copyTo.GetType(); if (type != copyFrom.GetType()) return null; // type mis-match BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; IEnumerable<PropertyInfo> pinfos = type.GetProperties(flags); foreach (var pinfo in pinfos) { if (pinfo.CanWrite) { try { pinfo.SetValue(copyTo, pinfo.GetValue(copyFrom, null), null); } catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific. } } IEnumerable<FieldInfo> finfos = type.GetFields(flags); foreach (var finfo in finfos) { finfo.SetValue(copyTo, finfo.GetValue(copyFrom)); } return copyTo as T; } } }
mit
C#
2098c36163e29e317b9c4d5a8ac6963a84f3e507
update task
zhouyongtao/my_aspnetmvc_learning,zhouyongtao/my_aspnetmvc_learning
my_aspnetmvc_learning/Controllers/ParallelController.cs
my_aspnetmvc_learning/Controllers/ParallelController.cs
using NLog; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace my_aspnetmvc_learning.Controllers { public class ParallelController : Controller { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); // GET: Parallel public ActionResult Index() { var options = new ParallelOptions { MaxDegreeOfParallelism = 1 }; //指定使用的硬件线程数为1 Parallel.For(0, 10000, options, (i, state) => { if (i == 100) { state.Break(); return; } }); return View(); } public ActionResult dict() { var dictParallelDays = new ConcurrentDictionary<string, string>(); try { System.Threading.Tasks.Parallel.For(0, 35, i => dictParallelDays.TryAdd(DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"), DateTime.Now.AddDays(i + 1).ToString("yyyy-MM-dd"))); } catch (AggregateException ex) { foreach (var single in ex.InnerExceptions) { //logger.Error("HanTingServiceJob AggregateException: " + ex.Message); } } var dictDays = dictParallelDays.AsParallel().OrderBy((data => data.Key)); dictDays.ForEach(data => { string key = data.Key; string value = data.Value; }); //Parallel Parallel.ForEach(dictParallelDays, item => { Logger.Info("key: " + item.Key + " value : " + item.Value); }); return Content(dictDays.Count().ToString()); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace my_aspnetmvc_learning.Controllers { public class ParallelController : Controller { // GET: Parallel public ActionResult Index() { var options = new ParallelOptions {MaxDegreeOfParallelism = 1}; //指定使用的硬件线程数为1 Parallel.For(0, 10000, options,(i,state) => { if (i == 100) { state.Break(); return; } }); return View(); } } }
mit
C#
35625c2dad732fa7d40de0b38d4f744989d5dfd6
Increase default count to 500
Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java
net/Azure.Storage.Blobs.PerfStress/Core/CountOptions.cs
net/Azure.Storage.Blobs.PerfStress/Core/CountOptions.cs
using Azure.Test.PerfStress; using CommandLine; namespace Azure.Storage.Blobs.PerfStress.Core { public class CountOptions : PerfStressOptions { [Option('c', "count", Default = 500, HelpText = "Number of blobs")] public int Count { get; set; } } }
using Azure.Test.PerfStress; using CommandLine; namespace Azure.Storage.Blobs.PerfStress.Core { public class CountOptions : PerfStressOptions { [Option('c', "count", Default = 100, HelpText = "Number of blobs")] public int Count { get; set; } } }
mit
C#
54dbe609eefc707ecb19d31886faae76303cb6bd
Build and publish nuget package 0.2.2
QuickenLoans/XSerializer,rlyczynski/XSerializer
XSerializer/Properties/AssemblyInfo.cs
XSerializer/Properties/AssemblyInfo.cs
using System; 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("XSerializer")] [assembly: AssemblyDescription("A .NET XML serializer that serializes and deserializes anything.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("XSerializer")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5aeaebd0-35de-424c-baa9-ba6d65fa3409")] [assembly: CLSCompliant(true)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.2.2")] [assembly: AssemblyInformationalVersion("0.2.2")] [assembly: InternalsVisibleTo("XSerializer.Tests")] [assembly: InternalsVisibleTo("XSerializer.PerformanceTests")]
using System; 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("XSerializer")] [assembly: AssemblyDescription("A .NET XML serializer that serializes and deserializes anything.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("XSerializer")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5aeaebd0-35de-424c-baa9-ba6d65fa3409")] [assembly: CLSCompliant(true)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.2.1")] [assembly: AssemblyInformationalVersion("0.2.1")] [assembly: InternalsVisibleTo("XSerializer.Tests")] [assembly: InternalsVisibleTo("XSerializer.PerformanceTests")]
mit
C#
509906cafeddbd1fda3d8244bcc5bad835bab95f
check session id
fandrei/AppMetrics,fandrei/AppMetrics
AppMetrics.DataCollector/LogEvent.ashx.cs
AppMetrics.DataCollector/LogEvent.ashx.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Web; namespace AppMetrics.DataCollector { /// <summary> /// Summary description for LogEvent /// </summary> public class LogEvent : IHttpHandler { public void ProcessRequest(HttpContext context) { try { var sessionId = context.Request.Params["TrackerSession"]; if (string.IsNullOrEmpty(sessionId)) throw new ApplicationException("No session ID"); var dataRootPath = Path.GetFullPath(context.Request.PhysicalApplicationPath); var time = DateTime.UtcNow.ToString("u"); time = time.Replace(':', '_'); var filePath = Path.GetFullPath(string.Format("{0}\\Data\\{1}.{2}.txt", dataRootPath, time, sessionId)); if (!filePath.StartsWith(dataRootPath)) // block malicious session ids throw new ArgumentException(filePath); using (var writer = new StreamWriter(filePath, true, Encoding.UTF8)) { var i = 0; while (true) { var paramName = "TrackerData" + i; var logData = context.Request.Params[paramName]; if (logData == null) break; writer.WriteLine(logData); i++; } } } catch (Exception exc) { Trace.WriteLine(exc); #if DEBUG context.Response.Write(exc); #endif } } public bool IsReusable { get { return true; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Web; namespace AppMetrics.DataCollector { /// <summary> /// Summary description for LogEvent /// </summary> public class LogEvent : IHttpHandler { public void ProcessRequest(HttpContext context) { try { var sessionId = context.Request.Params["TrackerSession"]; var dataRootPath = Path.GetFullPath(context.Request.PhysicalApplicationPath); var time = DateTime.UtcNow.ToString("u"); time = time.Replace(':', '_'); var filePath = Path.GetFullPath(string.Format("{0}\\Data\\{1}.{2}.txt", dataRootPath, time, sessionId)); if (!filePath.StartsWith(dataRootPath)) // block malicious session ids throw new ArgumentException(filePath); using (var writer = new StreamWriter(filePath, true, Encoding.UTF8)) { var i = 0; while (true) { var paramName = "TrackerData" + i; var logData = context.Request.Params[paramName]; if (logData == null) break; writer.WriteLine(logData); i++; } } } catch (Exception exc) { Trace.WriteLine(exc); #if DEBUG context.Response.Write(exc); #endif } } public bool IsReusable { get { return true; } } } }
apache-2.0
C#
83934af041721625cb4338ba695381dadb66b1aa
Bump to 0.9.1
i3at/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,KlappPc/ArchiSteamFarm,KlappPc/ArchiSteamFarm,JustArchi/ArchiSteamFarm,i3at/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,KlappPc/ArchiSteamFarm,JustArchi/ArchiSteamFarm,blackpanther989/ArchiSteamFarm
ArchiSteamFarm/Properties/AssemblyInfo.cs
ArchiSteamFarm/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("ArchiSteamFarm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ArchiSteamFarm")] [assembly: AssemblyCopyright("Copyright © Łukasz Domeradzki 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("35af7887-08b9-40e8-a5ea-797d8b60b30c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.1.0")] [assembly: AssemblyFileVersion("0.9.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ArchiSteamFarm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ArchiSteamFarm")] [assembly: AssemblyCopyright("Copyright © Łukasz Domeradzki 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("35af7887-08b9-40e8-a5ea-797d8b60b30c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")]
apache-2.0
C#
b7ad51f81fa87c4d36aacf7502e1df402a3c6fb9
Refactor zip args
setchi/n_back_tracer,setchi/n_back_tracer
Assets/Scripts/BackgroundPatternTracer.cs
Assets/Scripts/BackgroundPatternTracer.cs
using UnityEngine; using System; using System.Linq; using System.Collections; using System.Collections.Generic; using UniRx; public class BackgroundPatternTracer : MonoBehaviour { public GameObject Tile; public int col; public int row; void Awake () { transform.localPosition = new Vector3(-col * 1.7f / 2, -row * 1.7f / 2, 10); var tiles = Enumerable.Range(0, row).SelectMany(y => Enumerable.Range(0, col).Select(x => { var obj = Instantiate(Tile) as GameObject; obj.transform.SetParent(transform); obj.transform.localPosition = new Vector3(x, y) * 1.7f; return obj.GetComponent<Tile>(); })).ToArray(); var patterns = BackgroundPatternStore.GetPatterns(); var tileEffectEmitters = new List<Action<Tile>> { tile => tile.EmitMarkEffect(), tile => tile.EmitHintEffect() }; Observable.Timer (TimeSpan.Zero, TimeSpan.FromSeconds (0.7f)) .Zip(patterns.ToObservable(), (_, p) => p).Repeat().Subscribe(pattern => { var traceStream = Observable.Timer (TimeSpan.Zero, TimeSpan.FromSeconds (0.1f)) .Zip(pattern.ToObservable(), (_, i) => tiles[i]); traceStream .Do(tile => tileEffectEmitters[pattern.Peek() % 2](tile)) .Zip(traceStream.Skip(1), (prev, current) => new { prev, current }) .Subscribe(tile => tile.current.DrawLine(tile.prev.gameObject.transform.position)) .AddTo(gameObject); }).AddTo(gameObject); } }
using UnityEngine; using System; using System.Linq; using System.Collections; using System.Collections.Generic; using UniRx; public class BackgroundPatternTracer : MonoBehaviour { public GameObject Tile; public int col; public int row; void Awake () { transform.localPosition = new Vector3(-col * 1.7f / 2, -row * 1.7f / 2, 10); var tiles = Enumerable.Range(0, row).SelectMany(y => Enumerable.Range(0, col).Select(x => { var obj = Instantiate(Tile) as GameObject; obj.transform.SetParent(transform); obj.transform.localPosition = new Vector3(x, y) * 1.7f; return obj.GetComponent<Tile>(); })).ToArray(); var patterns = BackgroundPatternStore.GetPatterns(); var tileEffectEmitters = new List<Action<Tile>> { tile => tile.EmitMarkEffect(), tile => tile.EmitHintEffect() }; Observable.Timer (TimeSpan.Zero, TimeSpan.FromSeconds (0.7f)) .Zip(patterns.ToObservable(), (a, b) => b).Repeat().Subscribe(pattern => { var traceStream = Observable.Timer (TimeSpan.Zero, TimeSpan.FromSeconds (0.1f)) .Zip(pattern.ToObservable(), (a, b) => tiles[b]); traceStream .Do(tile => tileEffectEmitters[pattern.Peek() % 2](tile)) .Zip(traceStream.Skip(1), (prev, current) => new { prev, current }) .Subscribe(tile => tile.current.DrawLine(tile.prev.gameObject.transform.position)) .AddTo(gameObject); }).AddTo(gameObject); } }
mit
C#
9b89744729548c14bb80c211c8e4d74446298cea
Use proper case for text showing the current VM operation
dtzar/AzureBot,dtzar/AzureBot
AzureBot/Forms/VirtualMachineFormState.cs
AzureBot/Forms/VirtualMachineFormState.cs
namespace AzureBot.Forms { using System; using System.Collections.Generic; using System.Linq; using Azure.Management.Models; [Serializable] public class VirtualMachineFormState { public VirtualMachineFormState(IEnumerable<VirtualMachine> availableVMs, Operations operation) { this.AvailableVMs = availableVMs; this.Operation = operation.ToString().ToLower(); } public string VirtualMachine { get; set; } public IEnumerable<VirtualMachine> AvailableVMs { get; private set; } public string Operation { get; private set; } public VirtualMachine SelectedVM { get { return this.AvailableVMs.Where(p => p.Name == this.VirtualMachine).SingleOrDefault(); } } } }
namespace AzureBot.Forms { using System; using System.Collections.Generic; using System.Linq; using Azure.Management.Models; [Serializable] public class VirtualMachineFormState { public VirtualMachineFormState(IEnumerable<VirtualMachine> availableVMs, Operations operation) { this.AvailableVMs = availableVMs; this.Operation = operation; } public string VirtualMachine { get; set; } public IEnumerable<VirtualMachine> AvailableVMs { get; private set; } public Operations Operation { get; private set; } public VirtualMachine SelectedVM { get { return this.AvailableVMs.Where(p => p.Name == this.VirtualMachine).SingleOrDefault(); } } } }
mit
C#
fc3305d7bfa28b15a19957a7ba6ca075ce6c1407
Change the tests to not use reflection anymore but instead use the TestHttpMessageHandler
AlexGhiondea/OAuth.net,AlexGhiondea/OAuth.net
test/TestHelper.cs
test/TestHelper.cs
using System; using System.Linq; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; namespace OAuth.Net.Tests { public class TestHelper { private readonly string _apiKey; private readonly string _clientSecret; private readonly string _authToken; private readonly string _authTokenSecret; public TestHelper(string apiKey, string secret, string authToken, string authTokenSecret) { _apiKey = apiKey; _clientSecret = secret; _authToken = authToken; _authTokenSecret = authTokenSecret; } /// <summary> /// Using reflection, it will call the method that computes the oauth signature /// </summary> /// <param name="request"></param> /// <returns></returns> public string ComputeOAuthSignature(HttpRequestMessage request, string nonce, string timestamp, OAuthVersion version) { OAuthMessageHandler msgHandler = new OAuthMessageHandler( _apiKey, _clientSecret, _authToken, _authTokenSecret, new TestOAuthProvider( nonce, timestamp, version)); return GetOAuthParameterFromHandlerAsync(msgHandler, request,"oauth_signature").Result; } private async Task<string> GetOAuthParameterFromHandlerAsync(OAuthMessageHandler handler, HttpRequestMessage request, string requestedParameter) { var testHandler = new TestHttpMessageHandler(); handler.InnerHandler = testHandler; using (var httpClient = new HttpClient(handler, disposeHandler: false)) { await httpClient.SendAsync(request); } var request2 = testHandler.SentMessages.Single(); var authHeaderParameter = request.Headers.Authorization.Parameter; // extract the parameter string[] elems = authHeaderParameter.Split(','); return elems.SingleOrDefault(x => x.StartsWith($"{requestedParameter}="))?.Split('=')[1]; } } }
using System; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; namespace OAuth.Net.Tests { public class TestHelper { private readonly string _apiKey; private readonly string _secret; private readonly string _authToken; private readonly string _authTokenSecret; public TestHelper(string apiKey, string secret, string authToken, string authTokenSecret) { _apiKey = apiKey; _secret = secret; _authToken = authToken; _authTokenSecret = authTokenSecret; } /// <summary> /// Using reflection, it will call the method that computes the oauth signature /// </summary> /// <param name="request"></param> /// <returns></returns> public string ComputeOAuthSignature(HttpRequestMessage request, string nonce, string timestamp, OAuthVersion version) { OAuth.OAuthMessageHandler msgHandler = new OAuthMessageHandler(_apiKey, _secret, _authToken, _authTokenSecret, new TestOAuthProvider(nonce, timestamp, version)); // get access to the method. MethodInfo getAuthHeaderMethod = msgHandler.GetType().GetMethod("GetAuthenticationHeaderForRequest", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] { typeof(HttpRequestMessage) }, null); Task<string> taskResult = getAuthHeaderMethod.Invoke(msgHandler, new object[] { request }) as Task<string>; string headerString = taskResult.Result; // extract the oauth signature string[] elems = headerString.Split(','); foreach (var item in elems) { if (item.StartsWith("oauth_signature")) { return item.Split('=')[1]; } } return null; } } }
mit
C#
0998391684a1f2189d74d56d8c58e55920891be5
Fix behavior of LuceneCommon.GetIndexMetadataPath to support unit tests
mtian/SiteExtensionGallery,KuduApps/NuGetGallery,projectkudu/SiteExtensionGallery,JetBrains/ReSharperGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,JetBrains/ReSharperGallery,KuduApps/NuGetGallery,ScottShingler/NuGetGallery,projectkudu/SiteExtensionGallery,skbkontur/NuGetGallery,grenade/NuGetGallery_download-count-patch,ScottShingler/NuGetGallery,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,projectkudu/SiteExtensionGallery,KuduApps/NuGetGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,KuduApps/NuGetGallery,mtian/SiteExtensionGallery,JetBrains/ReSharperGallery,KuduApps/NuGetGallery
Website/Infrastructure/Lucene/LuceneCommon.cs
Website/Infrastructure/Lucene/LuceneCommon.cs
using System.IO; using Lucene.Net.Util; using System.Web.Hosting; using Lucene.Net.Store; using NuGetGallery.Configuration; namespace NuGetGallery { internal static class LuceneCommon { internal static readonly Version LuceneVersion = Version.LUCENE_30; private static SingleInstanceLockFactory LuceneLock = new SingleInstanceLockFactory(); // Factory method for DI/IOC that creates the directory the index is stored in. // Used by real website. Bypassed for unit tests. private static SimpleFSDirectory _directorySingleton; internal static string GetDirectoryLocation() { // Don't create the directory if it's not already present. return _directorySingleton == null ? null : _directorySingleton.Directory.FullName; } internal static string GetIndexMetadataPath() { // Don't create the directory if it's not already present. string root = _directorySingleton == null ? "." : (_directorySingleton.Directory.FullName ?? "."); return Path.Combine(root, "index.metadata"); } internal static Lucene.Net.Store.Directory GetDirectory(LuceneIndexLocation location) { if (_directorySingleton == null) { var index = GetIndexLocation(location); if (!System.IO.Directory.Exists(index)) { System.IO.Directory.CreateDirectory(index); } var directoryInfo = new DirectoryInfo(index); _directorySingleton = new SimpleFSDirectory(directoryInfo, LuceneLock); } return _directorySingleton; } private static string GetIndexLocation(LuceneIndexLocation location) { switch (location) { case LuceneIndexLocation.Temp: return Path.Combine(Path.GetTempPath(), "NuGetGallery", "Lucene"); default: return HostingEnvironment.MapPath("~/App_Data/Lucene"); } } } }
using System.IO; using Lucene.Net.Util; using System.Web.Hosting; using Lucene.Net.Store; using NuGetGallery.Configuration; namespace NuGetGallery { internal static class LuceneCommon { internal static readonly Version LuceneVersion = Version.LUCENE_30; private static SingleInstanceLockFactory LuceneLock = new SingleInstanceLockFactory(); // Factory method for DI/IOC that creates the directory the index is stored in. // Used by real website. Bypassed for unit tests. private static SimpleFSDirectory _directorySingleton; internal static string GetDirectoryLocation() { // Don't create the directory if it's not already present. return _directorySingleton == null ? null : _directorySingleton.Directory.FullName; } internal static string GetIndexMetadataPath() { // Don't create the directory if it's not already present. return _directorySingleton == null ? null : Path.Combine(_directorySingleton.Directory.FullName ?? ".", "index.metadata"); } internal static Lucene.Net.Store.Directory GetDirectory(LuceneIndexLocation location) { if (_directorySingleton == null) { var index = GetIndexLocation(location); if (!System.IO.Directory.Exists(index)) { System.IO.Directory.CreateDirectory(index); } var directoryInfo = new DirectoryInfo(index); _directorySingleton = new SimpleFSDirectory(directoryInfo, LuceneLock); } return _directorySingleton; } private static string GetIndexLocation(LuceneIndexLocation location) { switch (location) { case LuceneIndexLocation.Temp: return Path.Combine(Path.GetTempPath(), "NuGetGallery", "Lucene"); default: return HostingEnvironment.MapPath("~/App_Data/Lucene"); } } } }
apache-2.0
C#
b09e3adb959a27f272700acd3501d7d90826b28b
Fix VerbosityMappingAttribute to allow multiple use
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/Tooling/VerbosityMappingAttribute.cs
source/Nuke.Common/Tooling/VerbosityMappingAttribute.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.Linq; using JetBrains.Annotations; using Nuke.Common.Execution; namespace Nuke.Common.Tooling { [PublicAPI] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class VerbosityMappingAttribute : Attribute, IOnAfterLogo { private readonly Type _targetType; public VerbosityMappingAttribute(Type targetType) { _targetType = targetType; } public string Quiet { get; set; } public string Minimal { get; set; } public string Normal { get; set; } public string Verbose { get; set; } public void OnAfterLogo( NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets, IReadOnlyCollection<ExecutableTarget> executionPlan) { object GetMappedValue(string name) => _targetType .GetField(name) .NotNull($"Type {_targetType} doesn't have a field {name}.") .GetValue(obj: null); if (Quiet != null) VerbosityMapping.Mappings.Add(_targetType, (Verbosity.Quiet, GetMappedValue(Quiet))); if (Minimal != null) VerbosityMapping.Mappings.Add(_targetType, (Verbosity.Minimal, GetMappedValue(Minimal))); if (Normal != null) VerbosityMapping.Mappings.Add(_targetType, (Verbosity.Normal, GetMappedValue(Normal))); if (Verbose != null) VerbosityMapping.Mappings.Add(_targetType, (Verbosity.Verbose, GetMappedValue(Verbose))); } } }
// 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.Linq; using JetBrains.Annotations; using Nuke.Common.Execution; namespace Nuke.Common.Tooling { [PublicAPI] public class VerbosityMappingAttribute : Attribute, IOnAfterLogo { private readonly Type _targetType; public VerbosityMappingAttribute(Type targetType) { _targetType = targetType; } public string Quiet { get; set; } public string Minimal { get; set; } public string Normal { get; set; } public string Verbose { get; set; } public void OnAfterLogo( NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets, IReadOnlyCollection<ExecutableTarget> executionPlan) { object GetMappedValue(string name) => _targetType .GetField(name) .NotNull($"Type {_targetType} doesn't have a field {name}.") .GetValue(obj: null); if (Quiet != null) VerbosityMapping.Mappings.Add(_targetType, (Verbosity.Quiet, GetMappedValue(Quiet))); if (Minimal != null) VerbosityMapping.Mappings.Add(_targetType, (Verbosity.Minimal, GetMappedValue(Minimal))); if (Normal != null) VerbosityMapping.Mappings.Add(_targetType, (Verbosity.Normal, GetMappedValue(Normal))); if (Verbose != null) VerbosityMapping.Mappings.Add(_targetType, (Verbosity.Verbose, GetMappedValue(Verbose))); } } }
mit
C#
f1bb760e28aaafa4541a5a6e1cff2d47b1b13da2
add 'available' boolean to Size response, add back missing Size response fields
vevix/DigitalOcean.API
DigitalOcean.API/Models/Responses/Size.cs
DigitalOcean.API/Models/Responses/Size.cs
using System.Collections.Generic; namespace DigitalOcean.API.Models.Responses { public class Size { /// <summary> /// A human-readable string that is used to uniquely identify each size. /// </summary> public string Slug { get; set; } /// <summary> /// The amount of transfer bandwidth that is available for Droplets created in this size. This only counts traffic on the /// public interface. The value is given in terabytes /// </summary> public double Transfer { get; set; } /// <summary> /// This attribute describes the monthly cost of this Droplet size if the Droplet is kept for an entire month. The value is /// measured in US dollars. /// </summary> public float PriceMontly { get; set; } /// <summary> /// This describes the price of the Droplet size as measured hourly. The value is measured in US dollars. /// </summary> public float PriceHourly { get; set; } /// <summary> /// The amount of RAM allocated to Droplets created of this size. The value is represented in megabytes /// </summary> public int Memory { get; set; } /// <summary> /// The number of virtual CPUs allocated to Droplets of this size. /// </summary> public int Vcpus { get; set; } /// <summary> /// The amount of disk space set aside for Droplets of this size. The value is represented in gigabytes. /// </summary> public int Disk { get; set; } /// <summary> /// An array that contains the region slugs where this size is available for Droplet creates. /// </summary> public List<string> Regions { get; set; } /// <summary> /// This is a boolean value that represents whether new Droplets can be created with this size. /// </summary> public bool Available { get; set; } } }
using System.Collections.Generic; namespace DigitalOcean.API.Models.Responses { public class Size { /// <summary> /// A human-readable string that is used to uniquely identify each size. /// </summary> public string Slug { get; set; } /// <summary> /// The amount of transfer bandwidth that is available for Droplets created in this size. This only counts traffic on the /// public interface. The value is given in terabytes /// </summary> public double Transfer { get; set; } /// <summary> /// This attribute describes the monthly cost of this Droplet size if the Droplet is kept for an entire month. The value is /// measured in US dollars. /// </summary> public float PriceMontly { get; set; } /// <summary> /// This describes the price of the Droplet size as measured hourly. The value is measured in US dollars. /// </summary> public float PriceHourly { get; set; } /// <summary> /// An array that contains the region slugs where this size is available for Droplet creates. /// </summary> public List<string> Regions { get; set; } } }
mit
C#
d9a1b470cd7b3b1f921db416610c4dfe2fbdaf0d
Fix overkill and use `switch` statement
peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework
osu.Framework/Host.cs
osu.Framework/Host.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Platform.Linux; using osu.Framework.Platform.MacOS; using osu.Framework.Platform.Windows; using System; namespace osu.Framework { public static class Host { [Obsolete("Use GetSuitableHost(HostConfig) instead.")] public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: return new MacOSGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Windows: return new WindowsGameHost(gameName, bindIPC, portableInstallation); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS})."); } } public static DesktopGameHost GetSuitableHost(HostConfig hostConfig) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.Windows: return new WindowsGameHost(hostConfig); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(hostConfig); case RuntimeInfo.Platform.macOS: return new MacOSGameHost(hostConfig); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS})."); }; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Platform.Linux; using osu.Framework.Platform.MacOS; using osu.Framework.Platform.Windows; using System; namespace osu.Framework { public static class Host { [Obsolete("Use GetSuitableHost(HostConfig) instead.")] public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: return new MacOSGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Windows: return new WindowsGameHost(gameName, bindIPC, portableInstallation); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)})."); } } public static DesktopGameHost GetSuitableHost(HostConfig hostConfig) { return RuntimeInfo.OS switch { RuntimeInfo.Platform.Windows => new WindowsGameHost(hostConfig), RuntimeInfo.Platform.Linux => new LinuxGameHost(hostConfig), RuntimeInfo.Platform.macOS => new MacOSGameHost(hostConfig), _ => throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)})."), }; } } }
mit
C#
89deb4be08b8d4d51be15b8bcc5b70b915bb2e15
add test for Startup Request trace
shibayan/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,WeAreMammoth/kudu-obsolete,uQr/kudu,juvchan/kudu,kali786516/kudu,chrisrpatterson/kudu,duncansmart/kudu,barnyp/kudu,projectkudu/kudu,shanselman/kudu,EricSten-MSFT/kudu,bbauya/kudu,mauricionr/kudu,mauricionr/kudu,shibayan/kudu,dev-enthusiast/kudu,chrisrpatterson/kudu,duncansmart/kudu,sitereactor/kudu,shanselman/kudu,kali786516/kudu,juvchan/kudu,badescuga/kudu,uQr/kudu,oliver-feng/kudu,dev-enthusiast/kudu,EricSten-MSFT/kudu,shrimpy/kudu,mauricionr/kudu,duncansmart/kudu,projectkudu/kudu,shrimpy/kudu,EricSten-MSFT/kudu,YOTOV-LIMITED/kudu,chrisrpatterson/kudu,sitereactor/kudu,puneet-gupta/kudu,uQr/kudu,oliver-feng/kudu,YOTOV-LIMITED/kudu,dev-enthusiast/kudu,EricSten-MSFT/kudu,puneet-gupta/kudu,EricSten-MSFT/kudu,badescuga/kudu,badescuga/kudu,shibayan/kudu,juoni/kudu,sitereactor/kudu,kenegozi/kudu,duncansmart/kudu,barnyp/kudu,juvchan/kudu,shibayan/kudu,kenegozi/kudu,kenegozi/kudu,dev-enthusiast/kudu,projectkudu/kudu,bbauya/kudu,MavenRain/kudu,shanselman/kudu,WeAreMammoth/kudu-obsolete,puneet-gupta/kudu,juvchan/kudu,oliver-feng/kudu,projectkudu/kudu,kali786516/kudu,shrimpy/kudu,bbauya/kudu,MavenRain/kudu,barnyp/kudu,uQr/kudu,YOTOV-LIMITED/kudu,sitereactor/kudu,oliver-feng/kudu,shibayan/kudu,shrimpy/kudu,MavenRain/kudu,juoni/kudu,badescuga/kudu,mauricionr/kudu,juoni/kudu,juvchan/kudu,chrisrpatterson/kudu,WeAreMammoth/kudu-obsolete,sitereactor/kudu,puneet-gupta/kudu,MavenRain/kudu,puneet-gupta/kudu,bbauya/kudu,juoni/kudu,projectkudu/kudu,kali786516/kudu,kenegozi/kudu,barnyp/kudu
Kudu.FunctionalTests/GitStabilityTests.cs
Kudu.FunctionalTests/GitStabilityTests.cs
using System; using System.Linq; using Kudu.Core.Deployment; using Kudu.FunctionalTests.Infrastructure; using Kudu.TestHarness; using Xunit; namespace Kudu.FunctionalTests { public class GitStabilityTests { [Fact] public void NSimpleDeployments() { string repositoryName = "HelloKudu"; using (var repo = Git.Clone("HelloKudu")) { for (int i = 0; i < 5; i++) { string applicationName = repositoryName + i; ApplicationManager.Run(applicationName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu"); }); } } } [Fact] public void KuduUpTimeTest() { ApplicationManager.Run("KuduUpTimeTest", appManager => { TimeSpan upTime = TimeSpan.Parse(appManager.GetKuduUpTime()); TestTracer.Trace("UpTime: {0}", upTime); // some time the upTime is 00:00:00 (TimeSpan.Zero!). // Need to do more investigation. // Assert.NotEqual<TimeSpan>(TimeSpan.Zero, upTime); }); } [Fact] public void KuduStartupRequestTest() { ApplicationManager.Run("KuduStartupRequestTest", appManager => { // read the trace file var traces = appManager.VfsManager.ReadAllText("LogFiles/Git/trace/trace.xml"); // verify Assert.Contains("Startup Request", traces); }); } } }
using System; using System.Linq; using Kudu.Core.Deployment; using Kudu.FunctionalTests.Infrastructure; using Kudu.TestHarness; using Xunit; namespace Kudu.FunctionalTests { public class GitStabilityTests { [Fact] public void NSimpleDeployments() { string repositoryName = "HelloKudu"; using (var repo = Git.Clone("HelloKudu")) { for (int i = 0; i < 5; i++) { string applicationName = repositoryName + i; ApplicationManager.Run(applicationName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu"); }); } } } [Fact] public void KuduUpTimeTest() { ApplicationManager.Run("KuduUpTimeTest", appManager => { TimeSpan upTime = TimeSpan.Parse(appManager.GetKuduUpTime()); TestTracer.Trace("UpTime: {0}", upTime); // some time the upTime is 00:00:00 (TimeSpan.Zero!). // Need to do more investigation. // Assert.NotEqual<TimeSpan>(TimeSpan.Zero, upTime); }); } } }
apache-2.0
C#
9111e60a6f5931c97bc2bc5d7236384a0082bd05
Update LineCap.cs
Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Model/Style/LineCap.cs
src/Core2D/Model/Style/LineCap.cs
namespace Core2D.Style { public enum LineCap { Flat = 0, Square = 1, Round = 2 } }
 namespace Core2D.Style { public enum LineCap { Flat = 0, Square = 1, Round = 2 } }
mit
C#
115c41f2884544b381ff6199ecb0d76a6473ba56
Fix bug which was making the app crash when clicking outside of the spoiler form
Abc-Arbitrage/Abc.NCrafts.AllocationQuiz
Abc.NCrafts.App/Views/Performance2018GameView.xaml.cs
Abc.NCrafts.App/Views/Performance2018GameView.xaml.cs
using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Navigation; using Abc.NCrafts.App.ViewModels; namespace Abc.NCrafts.App.Views { /// <summary> /// Interaction logic for GameView.xaml /// </summary> public partial class Performance2018GameView : UserControl { public Performance2018GameView() { InitializeComponent(); } private void OnLoaded(object sender, RoutedEventArgs e) { Focusable = true; Keyboard.Focus(this); } private void OnWebBrowserLoaded(object sender, NavigationEventArgs e) { var script = "document.body.style.overflow ='hidden'"; var wb = (WebBrowser)sender; wb.InvokeScript("execScript", script, "JavaScript"); } private void HtmlHelpClick(object sender, MouseButtonEventArgs e) { var pagePage = (Performance2018GamePage)DataContext; pagePage.IsHelpVisible = false; } private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (DataContext == null) return; var htmlHelpContent = ((Performance2018GamePage)DataContext).HtmlHelpContent; _webBrowser.NavigateToString(htmlHelpContent); } } }
using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Navigation; using Abc.NCrafts.App.ViewModels; namespace Abc.NCrafts.App.Views { /// <summary> /// Interaction logic for GameView.xaml /// </summary> public partial class Performance2018GameView : UserControl { public Performance2018GameView() { InitializeComponent(); } private void OnLoaded(object sender, RoutedEventArgs e) { Focusable = true; Keyboard.Focus(this); } private void OnWebBrowserLoaded(object sender, NavigationEventArgs e) { var script = "document.body.style.overflow ='hidden'"; var wb = (WebBrowser)sender; wb.InvokeScript("execScript", script, "JavaScript"); } private void HtmlHelpClick(object sender, MouseButtonEventArgs e) { var pagePage = (PerformanceGamePage)DataContext; pagePage.IsHelpVisible = false; } private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (DataContext == null) return; var htmlHelpContent = ((Performance2018GamePage)DataContext).HtmlHelpContent; _webBrowser.NavigateToString(htmlHelpContent); } } }
mit
C#
ff20941eb501fc848256af53229f9fea62b942ec
Update helpbox text
PhannGor/unity3d-rainbow-folders
Assets/RainbowFoldersAsset/RainbowFolders/Editor/Settings/RainbowFoldersSettingsEditor.cs
Assets/RainbowFoldersAsset/RainbowFolders/Editor/Settings/RainbowFoldersSettingsEditor.cs
/* * 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 Rotorz.ReorderableList; using UnityEditor; namespace Borodar.RainbowFolders.Editor.Settings { [CustomEditor(typeof (RainbowFoldersSettings))] public class RainbowFoldersSettingsEditor : UnityEditor.Editor { private const string PROP_NAME_FOLDERS = "Folders"; private SerializedProperty _foldersProperty; protected void OnEnable() { _foldersProperty = serializedObject.FindProperty(PROP_NAME_FOLDERS); } public override void OnInspectorGUI() { EditorGUILayout.HelpBox("Please set your custom folder icons by specifying:\n\n" + "- Folder Name\n" + "Icon will be applied to all folders with the same name\n\n" + "- Folder Path\n" + "Icon will be applied to a single folder. The path format: Assets/SomeFolder/YourFolder", MessageType.Info); serializedObject.Update(); ReorderableListGUI.Title("Rainbow Folders"); ReorderableListGUI.ListField(_foldersProperty); serializedObject.ApplyModifiedProperties(); } } }
/* * 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 Rotorz.ReorderableList; using UnityEditor; namespace Borodar.RainbowFolders.Editor.Settings { [CustomEditor(typeof (RainbowFoldersSettings))] public class RainbowFoldersSettingsEditor : UnityEditor.Editor { private const string PROP_NAME_FOLDERS = "Folders"; private SerializedProperty _foldersProperty; protected void OnEnable() { _foldersProperty = serializedObject.FindProperty(PROP_NAME_FOLDERS); } public override void OnInspectorGUI() { EditorGUILayout.HelpBox("Please set your icons for folder names here", MessageType.Info); serializedObject.Update(); ReorderableListGUI.Title("Rainbow Folders"); ReorderableListGUI.ListField(_foldersProperty); serializedObject.ApplyModifiedProperties(); } } }
apache-2.0
C#
d4c79cca3adfd02d83f7457a0e50c65c9727cdd5
fix provider type
quandl/quandl-excel-windows
Quandl.Shared.Modules/models/DataArray.cs
Quandl.Shared.Modules/models/DataArray.cs
using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Quandl.Shared.Models { public class DataArray { [JsonExtensionData] private IDictionary<string, JToken> _additionalData; public List<List<object>> DataPoints { get; set; } public List<DataColumn> Columns { get; set; } public string Cursor { get; set; } [OnDeserialized] private void OnDeserialized(StreamingContext context) { // Dealing with a dataset data response if (_additionalData.ContainsKey("dataset_data")) { var jTokenColumns = _additionalData["dataset_data"].SelectToken("column_names").Values<string>(); Columns = jTokenColumns.Select(c => new DataColumn { Name = c, ProviderType = ProviderType.TimeSeries }).ToList(); DataPoints = _additionalData["dataset_data"].SelectToken("data").ToObject<List<List<object>>>(); } // Dealing with a datatable data response else if (_additionalData.ContainsKey("datatable")) { Columns = new List<DataColumn>(); foreach (var c in _additionalData["datatable"].SelectToken("columns")) { Columns.Add(new DataColumn { Name = c.SelectToken("name").Value<string>().ToUpper(), ProviderType = ProviderType.DataTable }); } DataPoints = _additionalData["datatable"].SelectToken("data").ToObject<List<List<object>>>(); Cursor = _additionalData["meta"].SelectToken("next_cursor_id").Value<string>(); } } } }
using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Quandl.Shared.Models { public class DataArray { [JsonExtensionData] private IDictionary<string, JToken> _additionalData; public List<List<object>> DataPoints { get; set; } public List<DataColumn> Columns { get; set; } public string Cursor { get; set; } [OnDeserialized] private void OnDeserialized(StreamingContext context) { // Dealing with a dataset data response if (_additionalData.ContainsKey("dataset_data")) { var jTokenColumns = _additionalData["dataset_data"].SelectToken("column_names").Values<string>(); Columns = jTokenColumns.Select(c => new DataColumn { Name = c, ProviderType = ProviderType.TimeSeries }).ToList(); DataPoints = _additionalData["dataset_data"].SelectToken("data").ToObject<List<List<object>>>(); } // Dealing with a datatable data response else if (_additionalData.ContainsKey("datatable")) { Columns = new List<DataColumn>(); foreach (var c in _additionalData["datatable"].SelectToken("columns")) { Columns.Add(new DataColumn { Name = c.SelectToken("name").Value<string>().ToUpper(), Type = ProviderType.DataTable }); } DataPoints = _additionalData["datatable"].SelectToken("data").ToObject<List<List<object>>>(); Cursor = _additionalData["meta"].SelectToken("next_cursor_id").Value<string>(); } } } }
mit
C#
8c2e2c380f762d3c84e82f21a8da4c20fd39cf6b
Fix runsynchronously exception
seiggy/AsterNET.ARI,skrusty/AsterNET.ARI,skrusty/AsterNET.ARI,skrusty/AsterNET.ARI,seiggy/AsterNET.ARI,seiggy/AsterNET.ARI
AsterNET.ARI/Middleware/Default/RESTActionConsumer.cs
AsterNET.ARI/Middleware/Default/RESTActionConsumer.cs
using System; using System.Threading.Tasks; namespace AsterNET.ARI.Middleware.Default { public class RestActionConsumer : IActionConsumer { private readonly StasisEndpoint _connectionInfo; public RestActionConsumer(StasisEndpoint connectionInfo) { _connectionInfo = connectionInfo; } public IRestCommand GetRestCommand(HttpMethod method, string path) { return new Command(_connectionInfo, path) { UniqueId = Guid.NewGuid().ToString(), Method = method.ToString() }; } public IRestCommandResult<T> ProcessRestCommand<T>(IRestCommand command) where T : new() { var cmd = (Command) command; var result = cmd.Client.Execute<T>(cmd.Request); //result.RunSynchronously(); result.GetAwaiter().GetResult(); var rtn = new CommandResult<T> {StatusCode = result.Result.StatusCode, Data = result.Result.Data}; return rtn; } public IRestCommandResult ProcessRestCommand(IRestCommand command) { var cmd = (Command) command; var result = cmd.Client.Execute(cmd.Request); //result.RunSynchronously(); result.GetAwaiter().GetResult(); var rtn = new CommandResult {StatusCode = result.Result.StatusCode, RawData = result.Result.RawBytes}; return rtn; } public async Task<IRestCommandResult<T>> ProcessRestTaskCommand<T>(IRestCommand command) where T : new() { var cmd = (Command) command; var result = await cmd.Client.Execute<T>(cmd.Request); var rtn = new CommandResult<T> {StatusCode = result.StatusCode, Data = result.Data}; return rtn; } public async Task<IRestCommandResult> ProcessRestTaskCommand(IRestCommand command) { var cmd = (Command) command; var result = await cmd.Client.Execute(cmd.Request); var rtn = new CommandResult {StatusCode = result.StatusCode, RawData = result.RawBytes}; return rtn; } } }
using System; using System.Threading.Tasks; namespace AsterNET.ARI.Middleware.Default { public class RestActionConsumer : IActionConsumer { private readonly StasisEndpoint _connectionInfo; public RestActionConsumer(StasisEndpoint connectionInfo) { _connectionInfo = connectionInfo; } public IRestCommand GetRestCommand(HttpMethod method, string path) { return new Command(_connectionInfo, path) { UniqueId = Guid.NewGuid().ToString(), Method = method.ToString() }; } public IRestCommandResult<T> ProcessRestCommand<T>(IRestCommand command) where T : new() { var cmd = (Command) command; var result = cmd.Client.Execute<T>(cmd.Request); result.RunSynchronously(); var rtn = new CommandResult<T> {StatusCode = result.Result.StatusCode, Data = result.Result.Data}; return rtn; } public IRestCommandResult ProcessRestCommand(IRestCommand command) { var cmd = (Command) command; var result = cmd.Client.Execute(cmd.Request); result.RunSynchronously(); var rtn = new CommandResult {StatusCode = result.Result.StatusCode, RawData = result.Result.RawBytes}; return rtn; } public async Task<IRestCommandResult<T>> ProcessRestTaskCommand<T>(IRestCommand command) where T : new() { var cmd = (Command) command; var result = await cmd.Client.Execute<T>(cmd.Request); var rtn = new CommandResult<T> {StatusCode = result.StatusCode, Data = result.Data}; return rtn; } public async Task<IRestCommandResult> ProcessRestTaskCommand(IRestCommand command) { var cmd = (Command) command; var result = await cmd.Client.Execute(cmd.Request); var rtn = new CommandResult {StatusCode = result.StatusCode, RawData = result.RawBytes}; return rtn; } } }
mit
C#
e5f0b2a6146fca15c1fe1567baae704dda98198f
Build and publish nuget package
RockFramework/Rock.Messaging
Rock.Messaging/Properties/AssemblyInfo.cs
Rock.Messaging/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("Rock.Messaging")] [assembly: AssemblyDescription("Rock Messaging.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("Rock.Messaging")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("58c2f915-e27e-436d-bd97-b6cb117ffd6b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.8")] [assembly: AssemblyInformationalVersion("0.9.8")]
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("Rock.Messaging")] [assembly: AssemblyDescription("Rock Messaging.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("Rock.Messaging")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("58c2f915-e27e-436d-bd97-b6cb117ffd6b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.7")] [assembly: AssemblyInformationalVersion("0.9.7")]
mit
C#
538d5398c0dfa5f8dd2e963634673f138e7793f8
Define Email struct
SICU-Stress-Measurement-System/frontend-cs
StressMeasurementSystem/Models/Patient.cs
StressMeasurementSystem/Models/Patient.cs
using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } struct PhoneNumber { internal enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } struct Email { internal enum Type {Home, Work, Other} public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private PhoneNumber _phoneNumber; #endregion #region Constructors #endregion } }
namespace StressMeasurementSystem.Models { public class Patient { #region Structs struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } struct PhoneNumber { internal enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private PhoneNumber _phoneNumber; #endregion #region Constructors #endregion } }
apache-2.0
C#
c6c4369bdd251983b439faa24d30f9e0c330728e
Migrate JustMock test projects to new VS2017 format
telerik/JustMockLite
Telerik.JustMock.Tests.Base/Attributes.cs
Telerik.JustMock.Tests.Base/Attributes.cs
#if XUNIT using System; #if XUNIT2 using System.Collections.Generic; using System.Linq; #endif using Xunit; #if XUNIT2 using Xunit.Abstractions; #endif #endif #if XUNIT2 #pragma warning disable xUnit1013 #endif namespace Telerik.JustMock.XUnit.Test.Attributes { #if XUNIT [SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = false)] public class EmptyTestClassAttribute : System.Attribute { } [SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false)] public class EmptyTestMethodAttribute : System.Attribute { } [SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false)] public class EmptyTestInitializeAttribute : System.Attribute { } [SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false)] public class EmptyTestCleanupAttribute : System.Attribute { } [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = true)] #if !XUNIT2 public class XUnitCategoryAttribute : Xunit.TraitAttribute { public XUnitCategoryAttribute(string category) : base("Category", category) { } } #else [Xunit.Sdk.TraitDiscovererAttribute("Telerik.JustMock.XUnit.Test.Attributes.XunitCategoryDiscoverer", "Telerik.JustMock.XUnit.Tests")] public class XUnitCategoryAttribute : Attribute, Xunit.Sdk.ITraitAttribute { public XUnitCategoryAttribute(string category) { } } public class XunitCategoryDiscoverer : Xunit.Sdk.ITraitDiscoverer { /// <inheritdoc/> public virtual IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute) { var ctorArgs = traitAttribute.GetConstructorArguments().Cast<string>().ToList(); yield return new KeyValuePair<string, string>("Category", ctorArgs[0]); } } #endif public static class SkipReason { #if XUNIT2 // It seems that xUnit2 requires not empty string in order to skip the test, see // https://stackoverflow.com/questions/14840172/skipping-a-whole-test-class-in-xunit-net public const string Value = " "; #else public const string Value = ""; #endif } #endif } #if XUNIT2 #pragma warning restore xUnit1013 #endif
#if XUNIT using System; #if XUNIT2 using System.Collections.Generic; using System.Linq; #endif using Xunit; #if XUNIT2 using Xunit.Abstractions; #endif #endif #if XUNIT2 #pragma warning disable xUnit1013 #endif namespace Telerik.JustMock.XUnit.Test.Attributes { #if XUNIT [SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = false)] public class EmptyTestClassAttribute : System.Attribute { } [SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false)] public class EmptyTestMethodAttribute : System.Attribute { } [SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false)] public class EmptyTestInitializeAttribute : System.Attribute { } [SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false)] public class EmptyTestCleanupAttribute : System.Attribute { } [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = true)] #if !XUNIT2 public class XUnitCategoryAttribute : Xunit.TraitAttribute { public XUnitCategoryAttribute(string category) : base("Category", category) { } } #else [Xunit.Sdk.TraitDiscovererAttribute("Telerik.JustMock.XUnit.Test.Attributes.XunitCategoryDiscoverer", "Telerik.JustMock.XUnit.Tests")] public class XUnitCategoryAttribute : Attribute, Xunit.Sdk.ITraitAttribute { public XUnitCategoryAttribute(string category) { } } public class XunitCategoryDiscoverer : Xunit.Sdk.ITraitDiscoverer { /// <inheritdoc/> public virtual IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute) { var ctorArgs = traitAttribute.GetConstructorArguments().Cast<string>().ToList(); yield return new KeyValuePair<string, string>("Category", ctorArgs[0]); } } #endif #endif } #if XUNIT2 #pragma warning restore xUnit1013 #endif
apache-2.0
C#
656599906b8ea5efd2291b733846dfbd94e51a60
Fix size calculation for extracted Custom Widget
hwthomas/xwt,TheBrainTech/xwt,residuum/xwt,mminns/xwt,lytico/xwt,antmicro/xwt,iainx/xwt,mminns/xwt,mono/xwt,hamekoz/xwt,cra0zy/xwt,steffenWi/xwt,akrisiun/xwt
Xwt.XamMac/Xwt.Mac/CustomWidgetBackend.cs
Xwt.XamMac/Xwt.Mac/CustomWidgetBackend.cs
// // CustomWidgetBackend.cs // // Author: // Alex Corrado <[email protected]> // // Copyright (c) 2013 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using CGSize = System.Drawing.SizeF; using MonoMac.AppKit; #else using AppKit; using CoreGraphics; #endif namespace Xwt.Mac { public class CustomWidgetBackend: ViewBackend<NSView,IWidgetEventSink>, ICustomWidgetBackend { ViewBackend childBackend; public CustomWidgetBackend () { } public override void Initialize () { ViewObject = new CustomWidgetView (EventSink, ApplicationContext); } public void SetContent (IWidgetBackend widget) { if (childBackend != null) { childBackend.Widget.RemoveFromSuperview (); RemoveChildPlacement (childBackend.Widget); childBackend.Widget.AutoresizingMask = NSViewResizingMask.NotSizable; } if (widget == null) return; var view = Widget; childBackend = (ViewBackend)widget; var childView = GetWidgetWithPlacement (childBackend); childView.Frame = view.Bounds; childView.AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable; view.AddSubview (childView); view.SetNeedsDisplayInRect (view.Bounds); } protected override Size GetNaturalSize () { if (childBackend != null) return childBackend.Frontend.Surface.GetPreferredSize (includeMargin: true); else return base.GetNaturalSize (); } } class CustomWidgetView: WidgetView { public CustomWidgetView (IWidgetEventSink eventSink, ApplicationContext context) : base (eventSink, context) { } public override void SetFrameSize (CGSize newSize) { base.SetFrameSize (newSize); if (Subviews.Length == 0) return; Subviews [0].SetFrameSize (newSize); Backend.Frontend.Surface.Reallocate (); } } }
// // CustomWidgetBackend.cs // // Author: // Alex Corrado <[email protected]> // // Copyright (c) 2013 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using CGSize = System.Drawing.SizeF; using MonoMac.AppKit; #else using AppKit; using CoreGraphics; #endif namespace Xwt.Mac { public class CustomWidgetBackend: ViewBackend<NSView,IWidgetEventSink>, ICustomWidgetBackend { ViewBackend childBackend; public CustomWidgetBackend () { } public override void Initialize () { ViewObject = new CustomWidgetView (EventSink, ApplicationContext); } public void SetContent (IWidgetBackend widget) { if (childBackend != null) { childBackend.Widget.RemoveFromSuperview (); RemoveChildPlacement (childBackend.Widget); childBackend.Widget.AutoresizingMask = NSViewResizingMask.NotSizable; } if (widget == null) return; var view = Widget; childBackend = (ViewBackend)widget; var childView = GetWidgetWithPlacement (childBackend); childView.Frame = view.Bounds; childView.AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable; view.AddSubview (childView); view.SetNeedsDisplayInRect (view.Bounds); } protected override Size GetNaturalSize () { if (childBackend != null) return childBackend.Frontend.Surface.GetPreferredSize (); else return base.GetNaturalSize (); } } class CustomWidgetView: WidgetView { public CustomWidgetView (IWidgetEventSink eventSink, ApplicationContext context) : base (eventSink, context) { } public override void SetFrameSize (CGSize newSize) { base.SetFrameSize (newSize); if (Subviews.Length == 0) return; Subviews [0].SetFrameSize (newSize); Backend.Frontend.Surface.Reallocate (); } } }
mit
C#
c9dcfd6b69468c1f29dca0d4dae7e7323097087c
Bump version to 0.13.5
quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot
CactbotOverlay/Properties/AssemblyInfo.cs
CactbotOverlay/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.13.5.0")] [assembly: AssemblyFileVersion("0.13.5.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.13.4.0")] [assembly: AssemblyFileVersion("0.13.4.0")]
apache-2.0
C#
23f9ccffda386029e5949fc992f01f5a928a2e67
fix issue with console quickedit mode where app hangs until key press
titanium007/Titanium-Web-Proxy,justcoding121/Titanium-Web-Proxy,titanium007/Titanium
Examples/Titanium.Web.Proxy.Examples.Basic/Program.cs
Examples/Titanium.Web.Proxy.Examples.Basic/Program.cs
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace Titanium.Web.Proxy.Examples.Basic { public class Program { private static readonly ProxyTestController controller = new ProxyTestController(); public static void Main(string[] args) { //fix console hang due to QuickEdit mode var handle = Process.GetCurrentProcess().MainWindowHandle; NativeMethods.SetConsoleMode(handle, NativeMethods.ENABLE_EXTENDED_FLAGS); //On Console exit make sure we also exit the proxy NativeMethods.Handler = ConsoleEventCallback; NativeMethods.SetConsoleCtrlHandler(NativeMethods.Handler, true); //Start proxy controller controller.StartProxy(); Console.WriteLine("Hit any key to exit.."); Console.WriteLine(); Console.Read(); controller.Stop(); } private static bool ConsoleEventCallback(int eventType) { if (eventType != 2) return false; try { controller.Stop(); } catch { // ignored } return false; } } internal static class NativeMethods { internal const uint ENABLE_EXTENDED_FLAGS = 0x0080; // Keeps it from getting garbage collected internal static ConsoleEventDelegate Handler; [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add); // Pinvoke internal delegate bool ConsoleEventDelegate(int eventType); [DllImport("kernel32.dll")] internal static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode); } }
using System; using System.Runtime.InteropServices; namespace Titanium.Web.Proxy.Examples.Basic { public class Program { private static readonly ProxyTestController controller = new ProxyTestController(); public static void Main(string[] args) { //On Console exit make sure we also exit the proxy NativeMethods.Handler = ConsoleEventCallback; NativeMethods.SetConsoleCtrlHandler(NativeMethods.Handler, true); //Start proxy controller controller.StartProxy(); Console.WriteLine("Hit any key to exit.."); Console.WriteLine(); Console.Read(); controller.Stop(); } private static bool ConsoleEventCallback(int eventType) { if (eventType != 2) return false; try { controller.Stop(); } catch { // ignored } return false; } } internal static class NativeMethods { // Keeps it from getting garbage collected internal static ConsoleEventDelegate Handler; [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add); // Pinvoke internal delegate bool ConsoleEventDelegate(int eventType); } }
mit
C#
d062f86af23be9f083123b93bb695b7877bc8c8f
Fix indentation
RockyTV/Duality.IronPython
CorePlugin/ScriptExecutor.cs
CorePlugin/ScriptExecutor.cs
using System; using System.Collections.Generic; using System.Linq; using Duality; using RockyTV.Duality.Plugins.IronPython.Resources; using IronPython.Hosting; using IronPython.Runtime; using IronPython.Compiler; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; namespace RockyTV.Duality.Plugins.IronPython { public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable { public ContentRef<PythonScript> Script { get; set; } [DontSerialize] private PythonExecutionEngine _engine; protected PythonExecutionEngine Engine { get { return _engine; } } protected virtual float Delta { get { return Time.MsPFMult * Time.TimeMult; } } public void OnInit(InitContext context) { if (!Script.IsAvailable) return; _engine = new PythonExecutionEngine(Script.Res.Content); _engine.SetVariable("gameObject", GameObj); if (_engine.HasMethod("start")) _engine.CallMethod("start"); } public void OnUpdate() { if (_engine.HasMethod("update")) _engine.CallMethod("update", Delta); } public void OnShutdown(ShutdownContext context) { if (context == ShutdownContext.Deactivate) { GameObj.DisposeLater(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Duality; using RockyTV.Duality.Plugins.IronPython.Resources; using IronPython.Hosting; using IronPython.Runtime; using IronPython.Compiler; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; namespace RockyTV.Duality.Plugins.IronPython { public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable { public ContentRef<PythonScript> Script { get; set; } [DontSerialize] private PythonExecutionEngine _engine; protected PythonExecutionEngine Engine { get { return _engine; } } protected virtual float Delta { get { return Time.MsPFMult * Time.TimeMult; } } public void OnInit(InitContext context) { if (!Script.IsAvailable) return; _engine = new PythonExecutionEngine(Script.Res.Content); _engine.SetVariable("gameObject", GameObj); if (_engine.HasMethod("start")) _engine.CallMethod("start"); } public void OnUpdate() { if (_engine.HasMethod("update")) _engine.CallMethod("update", Delta); } public void OnShutdown(ShutdownContext context) { if (context == ShutdownContext.Deactivate) { GameObj.DisposeLater(); } } } }
mit
C#
6292fa3bc12fe7f322286a20a062fb7f73e333be
Add ctor
mstrother/BmpListener
BmpListener/Bgp/ASPathSegment.cs
BmpListener/Bgp/ASPathSegment.cs
namespace BmpListener.Bgp { public class ASPathSegment { public ASPathSegment(Type type, int[] asns) { SegmentType = Type; ASNs = asns; } public enum Type { AS_SET = 1, AS_SEQUENCE, AS_CONFED_SEQUENCE, AS_CONFED_SET } public Type SegmentType { get; set; } public int[] ASNs { get; set; } } }
namespace BmpListener.Bgp { public class ASPathSegment { public enum Type { AS_SET = 1, AS_SEQUENCE, AS_CONFED_SEQUENCE, AS_CONFED_SET } public Type SegmentType { get; set; } public int[] ASNs { get; set; } } }
mit
C#
b917fd7f206cbf0a15247fd029a031c7228bf8b6
Implement Dispose pattern
vazgriz/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary
CSGL.Vulkan/Vulkan/BufferView.cs
CSGL.Vulkan/Vulkan/BufferView.cs
using System; using System.Collections.Generic; namespace CSGL.Vulkan { public class BufferViewCreateInfo { public Buffer buffer; public VkFormat format; public ulong offset; public ulong range; } public class BufferView : INative<VkBufferView>, IDisposable { bool disposed; VkBufferView bufferView; public Device Device { get; private set; } public ulong Offset { get; private set; } public ulong Range { get; private set; } public VkBufferView Native { get { return bufferView; } } public BufferView(Device device, BufferViewCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); Device = device; } void CreateBufferView(BufferViewCreateInfo mInfo) { VkBufferViewCreateInfo info = new VkBufferViewCreateInfo(); info.sType = VkStructureType.BufferViewCreateInfo; info.buffer = mInfo.buffer.Native; info.format = mInfo.format; info.offset = mInfo.offset; info.range = mInfo.range; var result = Device.Commands.createBufferView(Device.Native, ref info, Device.Instance.AllocationCallbacks, out bufferView); if (result != VkResult.Success) throw new BufferViewException(string.Format("Error creating buffer view: {0}", result)); Offset = mInfo.offset; Range = mInfo.range; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (disposed) return; Device.Commands.destroyBufferView(Device.Native, bufferView, Device.Instance.AllocationCallbacks); disposed = true; } ~BufferView() { Dispose(false); } } public class BufferViewException : Exception { public BufferViewException(string message) : base(message) { } } }
using System; using System.Collections.Generic; namespace CSGL.Vulkan { public class BufferViewCreateInfo { public Buffer buffer; public VkFormat format; public ulong offset; public ulong range; } public class BufferView : INative<VkBufferView>, IDisposable { bool disposed; VkBufferView bufferView; public Device Device { get; private set; } public ulong Offset { get; private set; } public ulong Range { get; private set; } public VkBufferView Native { get { return bufferView; } } public BufferView(Device device, BufferViewCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); Device = device; } void CreateBufferView(BufferViewCreateInfo mInfo) { VkBufferViewCreateInfo info = new VkBufferViewCreateInfo(); info.sType = VkStructureType.BufferViewCreateInfo; info.buffer = mInfo.buffer.Native; info.format = mInfo.format; info.offset = mInfo.offset; info.range = mInfo.range; var result = Device.Commands.createBufferView(Device.Native, ref info, Device.Instance.AllocationCallbacks, out bufferView); if (result != VkResult.Success) throw new BufferViewException(string.Format("Error creating buffer view: {0}", result)); Offset = mInfo.offset; Range = mInfo.range; } public void Dispose() { if (disposed) return; Device.Commands.destroyBufferView(Device.Native, bufferView, Device.Instance.AllocationCallbacks); disposed = true; } } public class BufferViewException : Exception { public BufferViewException(string message) : base(message) { } } }
mit
C#
58022ab17d8de71fbc81b63505ea448cd6fb458b
Check digit: recognize infrastructural code and domain logic
ttitto/CSharp
CheckDigit/CheckDigit/Program.cs
CheckDigit/CheckDigit/Program.cs
namespace CheckDigit { class Program { static int GetControllDigit(long number) { int sum = 0; bool isOddPos = true; while (number > 0) // infrastructure { int digit = (int)(number % 10); // infrastructure if (isOddPos) // domain { sum += 3 * digit; // 3 = parameter } else { sum += digit; number /= 10; // infrastructure isOddPos = !isOddPos; // domain } } int modulo = sum % 7; // 7 = parameter return modulo; // % = domain } static void Main(string[] args) { int digit = GetControllDigit(12345); } } }
namespace CheckDigit { class Program { static int GetControllDigit(long number) { int sum = 0; bool isOddPos = true; while (number > 0) { int digit = (int)(number % 10); if (isOddPos) { sum += 3 * digit; } else { sum += digit; number /= 10; isOddPos = !isOddPos; } } int modulo = sum % 7; return modulo; } static void Main(string[] args) { int digit = GetControllDigit(12345); } } }
mit
C#
70c57a17b9491c4385fb9c50ff8086bdecb707dd
Update IExceptionTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/IExceptionTelemeter.cs
TIKSN.Core/Analytics/Telemetry/IExceptionTelemeter.cs
using System; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public interface IExceptionTelemeter { Task TrackException(Exception exception); Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel); } }
using System; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public interface IExceptionTelemeter { Task TrackException(Exception exception); Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel); } }
mit
C#
bd054e5008527632ec87934de3258b712a8242bd
Use default portrait if provided one is null
joshbayley/spacetrader-unity,spriest487/spacetrader-unity
Assets/Crew/CrewConfiguration.cs
Assets/Crew/CrewConfiguration.cs
#pragma warning disable 0649 using System.Collections.Generic; using System.Linq; using UnityEngine; public class CrewConfiguration : ScriptableObject { [SerializeField] private TextAsset forenameList; [SerializeField] private TextAsset surnameList; private string[] forenames; private string[] surnames; [SerializeField] private List<Sprite> portraits; [SerializeField] private Sprite defaultPortrait; //global list of all characters in the game! [SerializeField] private List<CrewMember> characters; public IList<Sprite> Portraits { get { return portraits; } } public Sprite DefaultPortrait { get { return defaultPortrait; } } private IEnumerable<string> Forenames { get { return forenames; } } private IEnumerable<string> Surnames { get { return surnames; } } public IEnumerable<CrewMember> Characters { get { return characters; } } public static CrewConfiguration Create(CrewConfiguration prefab) { var result = Instantiate(prefab); result.forenames = LoadNamesFromTextAsset(result.forenameList); result.surnames = LoadNamesFromTextAsset(result.surnameList); result.characters = new List<CrewMember>(); return result; } private static string[] LoadNamesFromTextAsset(TextAsset asset) { return asset.text.Split('\n'); } public CrewMember NewCharacter(string name, Sprite portrait) { if (!portrait) { portrait = DefaultPortrait; } Debug.Assert(portrait == defaultPortrait || portraits.Contains(portrait), "portrait for character must be in the portraits list"); var result = CreateInstance<CrewMember>(); result.name = name; result.Portrait = portrait; characters.Add(result); return result; } public CrewMember NewCharacter(CrewMember source) { var result = Instantiate(source); result.name = source.name; //get rid of (Clone) characters.Add(result); return result; } public void DestroyCharacter(CrewMember character) { Debug.Assert(characters.Contains(character), "character should be registered in global characters list"); characters.Remove(character); } }
#pragma warning disable 0649 using System.Collections.Generic; using System.Linq; using UnityEngine; public class CrewConfiguration : ScriptableObject { [SerializeField] private TextAsset forenameList; [SerializeField] private TextAsset surnameList; private string[] forenames; private string[] surnames; [SerializeField] private List<Sprite> portraits; [SerializeField] private Sprite defaultPortrait; //global list of all characters in the game! [SerializeField] private List<CrewMember> characters; public IList<Sprite> Portraits { get { return portraits; } } public Sprite DefaultPortrait { get { return defaultPortrait; } } private IEnumerable<string> Forenames { get { return forenames; } } private IEnumerable<string> Surnames { get { return surnames; } } public IEnumerable<CrewMember> Characters { get { return characters; } } public static CrewConfiguration Create(CrewConfiguration prefab) { var result = Instantiate(prefab); result.forenames = LoadNamesFromTextAsset(result.forenameList); result.surnames = LoadNamesFromTextAsset(result.surnameList); result.characters = new List<CrewMember>(); return result; } private static string[] LoadNamesFromTextAsset(TextAsset asset) { return asset.text.Split('\n'); } public CrewMember NewCharacter(string name, Sprite portrait) { Debug.Assert(portrait == defaultPortrait || portraits.Contains(portrait), "portrait for character must be in the portraits list"); var result = CreateInstance<CrewMember>(); result.name = name; result.Portrait = portrait; characters.Add(result); return result; } public CrewMember NewCharacter(CrewMember source) { var result = Instantiate(source); result.name = source.name; //get rid of (Clone) characters.Add(result); return result; } public void DestroyCharacter(CrewMember character) { Debug.Assert(characters.Contains(character), "character should be registered in global characters list"); characters.Remove(character); } }
mit
C#
8f0b0901f6890db319069f1f91a684983b152dce
reset speed on level load
lukaselmer/ethz-game-lab,lukaselmer/ethz-game-lab,lukaselmer/ethz-game-lab
Assets/Scripts/LevelSelection.cs
Assets/Scripts/LevelSelection.cs
using UnityEngine; using System.Collections.Generic; using Game; using System; class LevelSelection { public void LoadLevels () { Application.LoadLevel("Levels"); } public void LoadNextLevel () { TimeManager.Speed1(); // TODO: refactor this if(Application.loadedLevelName == "Spring") Application.LoadLevel("Summer"); else if(Application.loadedLevelName == "Summer") Application.LoadLevel("Fall"); else if(Application.loadedLevelName == "Fall") Application.LoadLevel("Winter"); else if(Application.loadedLevelName == "Winter") Application.LoadLevel("Levels"); } public void ReplayLevel () { Application.LoadLevel(Application.loadedLevelName); } }
using UnityEngine; using System.Collections.Generic; using Game; using System; class LevelSelection { public void LoadLevels () { Application.LoadLevel("Levels"); } public void LoadNextLevel () { // TODO: refactor this if(Application.loadedLevelName == "Spring") Application.LoadLevel("Summer"); if(Application.loadedLevelName == "Summer") Application.LoadLevel("Fall"); if(Application.loadedLevelName == "Fall") Application.LoadLevel("Winter"); if(Application.loadedLevelName == "Winter") Application.LoadLevel("Levels"); } public void ReplayLevel () { Application.LoadLevel(Application.loadedLevelName); } }
mit
C#
146bf5491604bd29ecee6904b6fac880f89f0873
rename version const
bddckr/VRTK-PUN-NetworkTest
Assets/Scripts/NetworkManager.cs
Assets/Scripts/NetworkManager.cs
namespace NetworkTest { using Photon; using UnityEngine; public sealed class NetworkManager : PunBehaviour { private const string NetworkVersion = "0.0.1"; private void OnEnable() { PhotonNetwork.ConnectUsingSettings(NetworkVersion); } public override void OnConnectedToMaster() { PhotonNetwork.JoinRandomRoom(); } public override void OnPhotonRandomJoinFailed(object[] codeAndMsg) { PhotonNetwork.CreateRoom("Test Room"); } public override void OnJoinedRoom() { PhotonNetwork.Instantiate("VRPlayerNetworkRepresentation", Vector3.zero, Quaternion.identity, 0); } } }
namespace NetworkTest { using Photon; using UnityEngine; public sealed class NetworkManager : PunBehaviour { private const string GameNetworkVersion = "0.0.1"; private void OnEnable() { PhotonNetwork.ConnectUsingSettings(GameNetworkVersion); } public override void OnConnectedToMaster() { PhotonNetwork.JoinRandomRoom(); } public override void OnPhotonRandomJoinFailed(object[] codeAndMsg) { PhotonNetwork.CreateRoom("Test Room"); } public override void OnJoinedRoom() { PhotonNetwork.Instantiate("VRPlayerNetworkRepresentation", Vector3.zero, Quaternion.identity, 0); } } }
mit
C#
3e8b51f72264c4c051cac35c2da357faa6e32f92
Add default cookie container
joelverhagen/SocketToMe
Knapcode.SocketToMe/Http/CookieHandler.cs
Knapcode.SocketToMe/Http/CookieHandler.cs
using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Knapcode.SocketToMe.Http { public class CookieHandler : DelegatingHandler { private const string CookieKey = "Cookie"; private const string SetCookieKey = "Set-Cookie"; public CookieHandler() { this.CookieContainer = new CookieContainer(); } public CookieContainer CookieContainer { get; set; } protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // get headers from the request string manualCookieValues = null; if (request.Headers.Contains(CookieKey)) { var cookieValues = request.Headers.GetValues(CookieKey); request.Headers.Remove(CookieKey); manualCookieValues = string.Join("; ", cookieValues.Select(Trim)); } // get headers from the cookie container if (CookieContainer != null) { var cookieValues = CookieContainer.GetCookieHeader(request.RequestUri); if (manualCookieValues != null) { cookieValues = Trim(manualCookieValues + "; " + cookieValues); } if (!string.IsNullOrWhiteSpace(cookieValues)) { request.Headers.Add(CookieKey, cookieValues); } } var response = await base.SendAsync(request, cancellationToken); // part the response cookies if (CookieContainer != null && response.Headers.Contains(SetCookieKey)) { var cookieHeaders = response.Headers.GetValues(SetCookieKey); foreach (var setCookieValue in cookieHeaders) { CookieContainer.SetCookies(response.RequestMessage.RequestUri, setCookieValue); } } return response; } private string Trim(string cookieValues) { return cookieValues.Trim().Trim(';').Trim(); } } }
using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Knapcode.SocketToMe.Http { public class CookieHandler : DelegatingHandler { private const string CookieKey = "Cookie"; private const string SetCookieKey = "Set-Cookie"; public CookieContainer CookieContainer { get; set; } protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // get headers from the request string manualCookieValues = null; if (request.Headers.Contains(CookieKey)) { var cookieValues = request.Headers.GetValues(CookieKey); request.Headers.Remove(CookieKey); manualCookieValues = string.Join("; ", cookieValues.Select(Trim)); } // get headers from the cookie container if (CookieContainer != null) { var cookieValues = CookieContainer.GetCookieHeader(request.RequestUri); if (manualCookieValues != null) { cookieValues = Trim(manualCookieValues + "; " + cookieValues); } if (!string.IsNullOrWhiteSpace(cookieValues)) { request.Headers.Add(CookieKey, cookieValues); } } var response = await base.SendAsync(request, cancellationToken); // part the response cookies if (CookieContainer != null && response.Headers.Contains(SetCookieKey)) { var cookieHeaders = response.Headers.GetValues(SetCookieKey); foreach (var setCookieValue in cookieHeaders) { CookieContainer.SetCookies(response.RequestMessage.RequestUri, setCookieValue); } } return response; } private string Trim(string cookieValues) { return cookieValues.Trim().Trim(';').Trim(); } } }
mit
C#
2fe798d1f2c3388d3ca9656a46332a1c3e78ae10
Add option to ignore unrecognized characters and encode/decode them as "?". Might be a bit hackish, but this avoids having to reload the game info.
Prof9/TextPet
LibTextPet/Text/CustomFallbackEncoding.cs
LibTextPet/Text/CustomFallbackEncoding.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LibTextPet.Text { /// <summary> /// An abstract encoding that makes the encoder and decoder fallbacks mutable. /// </summary> public abstract class CustomFallbackEncoding : Encoding { /// <summary> /// The encoder fallback. /// </summary> private EncoderFallback encoderFallback; /// <summary> /// The decoder fallback. /// </summary> private DecoderFallback decoderFallback; /// <summary> /// The encoder fallback to use when unknown characters are ignored. /// </summary> private EncoderFallback IgnoreEncoderFallback { get; set; } /// <summary> /// The encoder fallback to use when unknown characters are ignored. /// </summary> private DecoderFallback IgnoreDecoderFallback { get; set; } /// <summary> /// Gets or sets a boolean that indicates whether unknown characters should be skipped in case an exception would be thrown. /// </summary> public bool IgnoreUnknownChars { get; set; } /// <summary> /// Gets or sets the encoder fallback for this encoding. /// </summary> public new EncoderFallback EncoderFallback { get { EncoderFallback fallback = encoderFallback ?? base.EncoderFallback; if (this.IgnoreUnknownChars && fallback is EncoderExceptionFallback) { if (this.IgnoreEncoderFallback == null) { this.IgnoreEncoderFallback = new EncoderReplacementFallback("?"); } fallback = this.IgnoreEncoderFallback; } return fallback; } set { if (value == null) throw new ArgumentNullException(nameof(value), "The encoder fallback cannot be null."); this.encoderFallback = value; } } /// <summary> /// Gets or sets the decoder fallback for this encoding. /// </summary> public new DecoderFallback DecoderFallback { get { DecoderFallback fallback = decoderFallback ?? base.DecoderFallback; if (this.IgnoreUnknownChars && fallback is DecoderExceptionFallback) { if (this.IgnoreDecoderFallback == null) { this.IgnoreDecoderFallback = new DecoderReplacementFallback("?"); } fallback = this.IgnoreDecoderFallback; } return decoderFallback; } set { if (value == null) throw new ArgumentNullException(nameof(value), "The decoder fallback cannot be null."); this.decoderFallback = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LibTextPet.Text { /// <summary> /// An abstract encoding that makes the encoder and decoder fallbacks mutable. /// </summary> public abstract class CustomFallbackEncoding : Encoding { /// <summary> /// The encoder fallback. /// </summary> private EncoderFallback encoderFallback; /// <summary> /// The decoder fallback. /// </summary> private DecoderFallback decoderFallback; /// <summary> /// Gets or sets the encoder fallback for this encoding. /// </summary> public new EncoderFallback EncoderFallback { get { return encoderFallback ?? base.EncoderFallback; } set { if (value == null) throw new ArgumentNullException(nameof(value), "The encoder fallback cannot be null."); this.encoderFallback = value; } } /// <summary> /// Gets or sets the decoder fallback for this encoding. /// </summary> public new DecoderFallback DecoderFallback { get { return decoderFallback ?? base.DecoderFallback; } set { if (value == null) throw new ArgumentNullException(nameof(value), "The decoder fallback cannot be null."); this.decoderFallback = value; } } } }
mit
C#
354065dfbcfc149d266d7940f7507923a8c9ea33
Fix line endings
avitalb/nodejstools,avitalb/nodejstools,mjbvz/nodejstools,AustinHull/nodejstools,kant2002/nodejstools,Microsoft/nodejstools,paladique/nodejstools,Microsoft/nodejstools,kant2002/nodejstools,kant2002/nodejstools,paladique/nodejstools,AustinHull/nodejstools,mousetraps/nodejstools,paladique/nodejstools,mousetraps/nodejstools,avitalb/nodejstools,lukedgr/nodejstools,munyirik/nodejstools,Microsoft/nodejstools,munyirik/nodejstools,paulvanbrenk/nodejstools,paladique/nodejstools,AustinHull/nodejstools,Microsoft/nodejstools,avitalb/nodejstools,kant2002/nodejstools,mjbvz/nodejstools,lukedgr/nodejstools,mjbvz/nodejstools,mjbvz/nodejstools,mousetraps/nodejstools,AustinHull/nodejstools,munyirik/nodejstools,paulvanbrenk/nodejstools,paulvanbrenk/nodejstools,mjbvz/nodejstools,paladique/nodejstools,lukedgr/nodejstools,lukedgr/nodejstools,mousetraps/nodejstools,mousetraps/nodejstools,munyirik/nodejstools,paulvanbrenk/nodejstools,lukedgr/nodejstools,Microsoft/nodejstools,kant2002/nodejstools,AustinHull/nodejstools,avitalb/nodejstools,munyirik/nodejstools,paulvanbrenk/nodejstools
Nodejs/Tests/Core/Mocks/MockTextBuffer.cs
Nodejs/Tests/Core/Mocks/MockTextBuffer.cs
using System.IO; using Microsoft.NodejsTools; namespace NodejsTests.Mocks { class MockTextBuffer : TestUtilities.Mocks.MockTextBuffer { public MockTextBuffer(string content) : base(content: content, contentType: NodejsConstants.Nodejs) { } private static string GetRandomFileNameIfNull(string filename) { if (filename == null) { filename = Path.Combine(TestUtilities.TestData.GetTempPath(), Path.GetRandomFileName(), "file.js"); } return filename; } public MockTextBuffer(string content, string contentType, string filename = null) : base(content: content, contentType: contentType, filename: MockTextBuffer.GetRandomFileNameIfNull(filename)) { } } }
using System.IO; using Microsoft.NodejsTools; namespace NodejsTests.Mocks { class MockTextBuffer : TestUtilities.Mocks.MockTextBuffer { public MockTextBuffer(string content) : base(content: content, contentType: NodejsConstants.Nodejs) { } private static string GetRandomFileNameIfNull(string filename) { if (filename == null) { filename = Path.Combine(TestUtilities.TestData.GetTempPath(), Path.GetRandomFileName(), "file.js"); } return filename; } public MockTextBuffer(string content, string contentType, string filename = null) : base(content: content, contentType: contentType, filename: MockTextBuffer.GetRandomFileNameIfNull(filename)) { } } }
apache-2.0
C#
9ab90a2405604210d442501689452c5fac77cbc2
Include 'as-instance' in the inheritance test
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
tests/inheritance/inheritance.cs
tests/inheritance/inheritance.cs
using System; public class Point2 { public Point2(int X, int Y) { this.X = X; this.Y = Y; } public int X; public int Y; } public class Point3 : Point2 { public Point3(int X, int Y, int Z) : base(X, Y) { this.Z = Z; } public int Z; } public class Point4 : Point3 { public Point3(int X, int Y, int Z, int W) : base(X, Y, Z) { this.W = W; } public int W; } public static class Program { public static void Main() { var pt = new Point4(0, -22, 45, 100); Console.Write(pt.X); Console.Write(' '); Console.Write(pt.Y); Console.Write(' '); Console.Write(pt.Z); Console.Write(' '); Console.Write(pt.W); Console.Write(' '); var pt2 = pt as Point2; var pt3 = pt2 as Point4; Console.Write(pt3 is Point2); Console.Write(' '); Console.Write(pt3 is Point3); Console.Write(' '); Console.Write(pt3 is Point4); var pt4 = new Point2(0, 0); Console.Write(' '); Console.Write(pt4 is Point2); Console.Write(' '); Console.Write(pt4 is Point3); Console.Write(' '); Console.Write(pt4 is Point4); Console.WriteLine(); } }
using System; public class Point2 { public Point2(int X, int Y) { this.X = X; this.Y = Y; } public int X; public int Y; } public class Point3 : Point2 { public Point3(int X, int Y, int Z) : base(X, Y) { this.Z = Z; } public int Z; } public class Point4 : Point3 { public Point3(int X, int Y, int Z, int W) : base(X, Y, Z) { this.W = W; } public int W; } public static class Program { public static void Main() { var pt = new Point4(0, -22, 45, 100); Console.Write(pt.X); Console.Write(' '); Console.Write(pt.Y); Console.Write(' '); Console.Write(pt.Z); Console.Write(' '); Console.Write(pt.W); Console.Write(' '); Console.Write(pt is Point2); Console.Write(' '); Console.Write(pt is Point3); Console.Write(' '); Console.Write(pt is Point4); var pt2 = new Point2(0, 0); Console.Write(' '); Console.Write(pt2 is Point2); Console.Write(' '); Console.Write(pt2 is Point3); Console.Write(' '); Console.Write(pt2 is Point4); Console.WriteLine(); } }
mit
C#
17b758e93d2e03370113d97402ef762ee37eab20
Fix filepath drawer.
Chaser324/unity-build
Editor/Generic/FilePathDrawer.cs
Editor/Generic/FilePathDrawer.cs
using UnityEngine; using UnityEditor; using System.IO; namespace SuperSystems.UnityBuild { [CustomPropertyDrawer(typeof(FilePathAttribute))] public class FilePathDrawer : PropertyDrawer { public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (property.propertyType != SerializedPropertyType.String) base.OnGUI(position, property, label); EditorGUI.BeginProperty(position, label, property); FilePathAttribute filePathAttr = attribute as FilePathAttribute; EditorGUILayout.BeginHorizontal(); if (filePathAttr.allowManualEdit) property.stringValue = EditorGUILayout.TextField(label, property.stringValue); else EditorGUILayout.TextField(label, property.stringValue); if (GUILayout.Button("...", UnityBuildGUIUtility.helpButtonStyle)) { SetPath(property, filePathAttr); } EditorGUILayout.EndHorizontal(); EditorGUI.EndProperty(); } private void SetPath(SerializedProperty property, FilePathAttribute filePathAttr) { string directory; if (filePathAttr.folder) directory = EditorUtility.OpenFolderPanel(filePathAttr.message, filePathAttr.projectPath, filePathAttr.initialNameOrFilter); else directory = EditorUtility.OpenFilePanel(filePathAttr.message, filePathAttr.projectPath, filePathAttr.initialNameOrFilter); // Canceled. if (string.IsNullOrEmpty(directory)) { return; } // Normalize path separators. directory = Path.GetFullPath(directory); // If relative to project path, reduce the filepath to just what we need. if (directory.Contains(filePathAttr.projectPath)) directory = directory.Replace(filePathAttr.projectPath, ""); // Save setting. property.stringValue = directory; } } }
using UnityEngine; using UnityEditor; using System.IO; namespace SuperSystems.UnityBuild { [CustomPropertyDrawer(typeof(FilePathAttribute))] public class FilePathDrawer : PropertyDrawer { public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (property.propertyType != SerializedPropertyType.String) base.OnGUI(position, property, label); EditorGUI.BeginProperty(position, label, property); FilePathAttribute filePathAttr = attribute as FilePathAttribute; EditorGUILayout.BeginHorizontal(); if (filePathAttr.allowManualEdit) BuildSettings.basicSettings.baseBuildFolder = EditorGUILayout.TextField(label, property.stringValue); else EditorGUILayout.TextField(label, property.stringValue); if (GUILayout.Button("...", UnityBuildGUIUtility.helpButtonStyle)) { SetPath(property, filePathAttr); } EditorGUILayout.EndHorizontal(); EditorGUI.EndProperty(); } private void SetPath(SerializedProperty property, FilePathAttribute filePathAttr) { string directory; if (filePathAttr.folder) directory = EditorUtility.OpenFolderPanel(filePathAttr.message, filePathAttr.projectPath, filePathAttr.initialNameOrFilter); else directory = EditorUtility.OpenFilePanel(filePathAttr.message, filePathAttr.projectPath, filePathAttr.initialNameOrFilter); // Canceled. if (string.IsNullOrEmpty(directory)) { return; } // Normalize path separators. directory = Path.GetFullPath(directory); // If relative to project path, reduce the filepath to just what we need. if (directory.Contains(filePathAttr.projectPath)) directory = directory.Replace(filePathAttr.projectPath, ""); // Save setting. property.stringValue = directory; } } }
mit
C#
2046f63652df66155b06c5b30f4a5c77497a01bd
Fix warning.
JohanLarsson/Gu.Localization
Gu.Localization/ErrorHandling.cs
Gu.Localization/ErrorHandling.cs
namespace Gu.Localization { /// <summary>Specify a strategy for how translation errors are handled.</summary> public enum ErrorHandling { /// <summary>Inherits behaviour from <see cref="Translator.ErrorHandling"/> or defaults to throw.</summary> Inherit, /// <summary>Throws if something is wrong.</summary> Throw, /// <summary>Returns information about the error in the result.</summary> ReturnErrorInfo, /// <summary>Returns information about the error in the result but leaves neutral strings intact.</summary> ReturnErrorInfoPreserveNeutral, } }
namespace Gu.Localization { /// <summary>Specify a strategy for how translation errors are handled.</summary> public enum ErrorHandling { /// <summary>Inherits behaviour from <see cref="Translator.ErrorHandling"/> or defaults to throw.</summary> Inherit, /// <summary>Throws if something is wrong.</summary> Throw, /// <summary>Returns information about the error in the result.</summary> ReturnErrorInfo, /// <summary>Returns information about the error in the result but leaves neutral strings intact</summary> ReturnErrorInfoPreserveNeutral, } }
mit
C#
0d455b3503de165e32d61581dc3c5924248d00ca
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.19.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.18.*")]
mit
C#
e45c37747c827f67539f7ddd24175def906aa06b
update namespace
sqlkata/querybuilder
QueryBuilder.Tests/InfrastructureTests.cs
QueryBuilder.Tests/InfrastructureTests.cs
using System; using System.Linq; using SqlKata.Compilers; using SqlKata.Tests.Infrastructure; using Xunit; namespace SqlKata.Tests { public class InfrastructureTests : TestSupport { [Fact] public void CanGetCompiler() { var compiler = Compilers.Get(EngineCodes.SqlServer); Assert.NotNull(compiler); Assert.IsType<SqlServerCompiler>(compiler); } [Fact] public void CanCompile() { var results = Compilers.Compile(new Query("Table")); Assert.NotNull(results); Assert.Equal(Compilers.KnownEngineCodes.Count(), results.Count); } [Fact] public void CanCompileSelectively() { var desiredEngines = new[] {EngineCodes.SqlServer, EngineCodes.MySql}; var results = Compilers.Compile(desiredEngines, new Query("Table")); Assert.Equal(desiredEngines.Length, results.Count); Assert.Contains(results, a =>a.Key == EngineCodes.SqlServer); Assert.Contains(results, a => a.Key == EngineCodes.MySql); } [Fact] public void ShouldThrowIfInvalidEngineCode() { Assert.Throws<InvalidOperationException>(() => Compilers.CompileFor("XYZ", new Query())); } [Fact] public void ShouldThrowIfAnyEngineCodesAreInvalid() { var codes = new[] {EngineCodes.SqlServer, "123", EngineCodes.MySql, "abc"}; Assert.Throws<InvalidOperationException>(() => Compilers.Compile(codes, new Query())); } } }
using System; using System.Linq; using SqlKata.Compilers; using Xunit; namespace SqlKata.Tests.Infrastructure { public class InfrastructureTests : TestSupport { [Fact] public void CanGetCompiler() { var compiler = Compilers.Get(EngineCodes.SqlServer); Assert.NotNull(compiler); Assert.IsType<SqlServerCompiler>(compiler); } [Fact] public void CanCompile() { var results = Compilers.Compile(new Query("Table")); Assert.NotNull(results); Assert.Equal(Compilers.KnownEngineCodes.Count(), results.Count); } [Fact] public void CanCompileSelectively() { var desiredEngines = new[] {EngineCodes.SqlServer, EngineCodes.MySql}; var results = Compilers.Compile(desiredEngines, new Query("Table")); Assert.Equal(desiredEngines.Length, results.Count); Assert.Contains(results, a =>a.Key == EngineCodes.SqlServer); Assert.Contains(results, a => a.Key == EngineCodes.MySql); } [Fact] public void ShouldThrowIfInvalidEngineCode() { Assert.Throws<InvalidOperationException>(() => Compilers.CompileFor("XYZ", new Query())); } [Fact] public void ShouldThrowIfAnyEngineCodesAreInvalid() { var codes = new[] {EngineCodes.SqlServer, "123", EngineCodes.MySql, "abc"}; Assert.Throws<InvalidOperationException>(() => Compilers.Compile(codes, new Query())); } } }
mit
C#
c2ebdec35598deed99d17fc1320a2e213c7d021e
Update version number in AssemblyInfo.cs.
google/protobuf,google/protobuf,Livefyre/protobuf,google/protobuf,google/protobuf,google/protobuf,Livefyre/protobuf,Livefyre/protobuf,Livefyre/protobuf,google/protobuf,google/protobuf,Livefyre/protobuf,google/protobuf,google/protobuf,google/protobuf,google/protobuf
csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs
csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System.Reflection; using System.Runtime.CompilerServices; using System.Security; // 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("Google.Protobuf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Google.Protobuf")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if !NCRUNCH [assembly: AllowPartiallyTrustedCallers] #endif #if SIGNED [assembly: InternalsVisibleTo("Google.Protobuf.Test, PublicKey=" + "002400000480000094000000060200000024000052534131000400000100010025800fbcfc63a1" + "7c66b303aae80b03a6beaa176bb6bef883be436f2a1579edd80ce23edf151a1f4ced97af83abcd" + "981207041fd5b2da3b498346fcfcd94910d52f25537c4a43ce3fbe17dc7d43e6cbdb4d8f1242dc" + "b6bd9b5906be74da8daa7d7280f97130f318a16c07baf118839b156299a48522f9fae2371c9665" + "c5ae9cb6")] #else [assembly: InternalsVisibleTo("Google.Protobuf.Test")] #endif [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyInformationalVersion("3.0.0-beta4")]
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System.Reflection; using System.Runtime.CompilerServices; using System.Security; // 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("Google.Protobuf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Google.Protobuf")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if !NCRUNCH [assembly: AllowPartiallyTrustedCallers] #endif #if SIGNED [assembly: InternalsVisibleTo("Google.Protobuf.Test, PublicKey=" + "002400000480000094000000060200000024000052534131000400000100010025800fbcfc63a1" + "7c66b303aae80b03a6beaa176bb6bef883be436f2a1579edd80ce23edf151a1f4ced97af83abcd" + "981207041fd5b2da3b498346fcfcd94910d52f25537c4a43ce3fbe17dc7d43e6cbdb4d8f1242dc" + "b6bd9b5906be74da8daa7d7280f97130f318a16c07baf118839b156299a48522f9fae2371c9665" + "c5ae9cb6")] #else [assembly: InternalsVisibleTo("Google.Protobuf.Test")] #endif [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyInformationalVersion("3.0.0-beta3")]
bsd-3-clause
C#
d71ed81e5c2b1b1e8f8c6af6f0b991003351d35a
Add Skip Duplicate for Azure Artifacts feed
cake-build/frosting
build/Tasks/PublishAzureArtifacts.cs
build/Tasks/PublishAzureArtifacts.cs
using Cake.Common.Tools.NuGet; using Cake.Common.Tools.NuGet.Push; using Cake.Common.Tools.NuGet.Sources; using Cake.Core; using Cake.Core.IO; using Cake.Frosting; [Dependency(typeof(Package))] [Dependency(typeof(AppVeyorArtifacts))] public class PublishAzureArtifacts : FrostingTask<Context> { public override bool ShouldRun(Context context) { return !context.IsLocalBuild && !context.IsPullRequest && context.IsOriginalRepo && context.BuildSystem.IsRunningOnAppVeyor && context.Environment.Platform.Family == PlatformFamily.Windows && (context.IsTagged || !context.IsPrimaryBranch); } public override void Run(Context context) { if(context.AzureArtifactsSourceUrl == null) { throw new CakeException("Azure Artifacts source URL was not provided."); } if(context.AzureArtifactsSourceName == null) { throw new CakeException("Azure Artifacts source name was not provided."); } if(context.AzureArtifactsPersonalAccessToken == null) { throw new CakeException("Azure Artifacts Personal Access Token was not provided."); } if(context.AzureArtifactsSourceUserName == null) { throw new CakeException("Azure Artifacts username was not provided."); } // Get the file paths. var files = new[] { $"./artifacts/Cake.Frosting.Template.{context.Version.SemVersion}.nupkg", $"./artifacts/Cake.Frosting.{context.Version.SemVersion}.nupkg" }; if(!context.NuGetHasSource(context.AzureArtifactsSourceName)) { context.NuGetAddSource(context.AzureArtifactsSourceName, context.AzureArtifactsSourceUrl, new NuGetSourcesSettings{ UserName = context.AzureArtifactsSourceUserName, Password = context.AzureArtifactsPersonalAccessToken }); } // Push files foreach(var file in files) { context.NuGetPush(file, new NuGetPushSettings { Source = context.AzureArtifactsSourceName, ApiKey = "az", SkipDuplicate = true }); } } }
using Cake.Common.Tools.NuGet; using Cake.Common.Tools.NuGet.Push; using Cake.Common.Tools.NuGet.Sources; using Cake.Core; using Cake.Core.IO; using Cake.Frosting; [Dependency(typeof(Package))] [Dependency(typeof(AppVeyorArtifacts))] public class PublishAzureArtifacts : FrostingTask<Context> { public override bool ShouldRun(Context context) { return !context.IsLocalBuild && !context.IsPullRequest && context.IsOriginalRepo && context.BuildSystem.IsRunningOnAppVeyor && context.Environment.Platform.Family == PlatformFamily.Windows && (context.IsTagged || !context.IsPrimaryBranch); } public override void Run(Context context) { if(context.AzureArtifactsSourceUrl == null) { throw new CakeException("Azure Artifacts source URL was not provided."); } if(context.AzureArtifactsSourceName == null) { throw new CakeException("Azure Artifacts source name was not provided."); } if(context.AzureArtifactsPersonalAccessToken == null) { throw new CakeException("Azure Artifacts Personal Access Token was not provided."); } if(context.AzureArtifactsSourceUserName == null) { throw new CakeException("Azure Artifacts username was not provided."); } // Get the file paths. var files = new[] { $"./artifacts/Cake.Frosting.Template.{context.Version.SemVersion}.nupkg", $"./artifacts/Cake.Frosting.{context.Version.SemVersion}.nupkg" }; if(!context.NuGetHasSource(context.AzureArtifactsSourceName)) { context.NuGetAddSource(context.AzureArtifactsSourceName, context.AzureArtifactsSourceUrl, new NuGetSourcesSettings{ UserName = context.AzureArtifactsSourceUserName, Password = context.AzureArtifactsPersonalAccessToken }); } // Push files foreach(var file in files) { context.NuGetPush(file, new NuGetPushSettings { Source = context.AzureArtifactsSourceName, ApiKey = "az" }); } } }
mit
C#
eebfaa7f4e32d6f44e2404210ba7e4b67d2e48b1
Use imperative in help messages.
saschb2b/mugo
mugo/CommandLineOptions.cs
mugo/CommandLineOptions.cs
using System; using CommandLine; using CommandLine.Text; namespace Mugo { /// <summary> /// Command line options of the game. /// </summary> public class CommandLineOptions { [Option ('m', "noBackgroundMusic", DefaultValue = false, HelpText = "Disable background music. It can still be enabled via the m hotkey.")] public bool NoBackgroundMusic { get; set; } [Option ('s', "seed", HelpText = "Set the seed value of the random number generator.")] public int? Seed { get; set; } [HelpOption ('h', "help")] public string GetUsage () { return HelpText.AutoBuild (this, (HelpText current) => HelpText.DefaultParsingErrorsHandler (this, current)); } } }
using System; using CommandLine; using CommandLine.Text; namespace Mugo { /// <summary> /// Command line options of the game. /// </summary> public class CommandLineOptions { [Option ('m', "noBackgroundMusic", DefaultValue = false, HelpText = "Disables background music. It can still be enabled via the m hotkey.")] public bool NoBackgroundMusic { get; set; } [Option ('s', "seed", HelpText = "Sets the seed value of the random number generator.")] public int? Seed { get; set; } [HelpOption ('h', "help")] public string GetUsage () { return HelpText.AutoBuild (this, (HelpText current) => HelpText.DefaultParsingErrorsHandler (this, current)); } } }
mit
C#
607a2cf304c50cde8a835de970345a3e48b3ea08
Update AddingLinkToURL.cs
asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Data/AddOn/Hyperlinks/AddingLinkToURL.cs
Examples/CSharp/Data/AddOn/Hyperlinks/AddingLinkToURL.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Data.AddOn.Hyperlinks { public class AddingLinkToURL { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Obtaining the reference of the first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Adding a hyperlink to a URL at "A1" cell worksheet.Hyperlinks.Add("A1", 1, 1, "http://www.aspose.com"); //Saving the Excel file workbook.Save(dataDir + "output.out.xls"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Data.AddOn.Hyperlinks { public class AddingLinkToURL { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Obtaining the reference of the first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Adding a hyperlink to a URL at "A1" cell worksheet.Hyperlinks.Add("A1", 1, 1, "http://www.aspose.com"); //Saving the Excel file workbook.Save(dataDir + "output.out.xls"); } } }
mit
C#
ecfc412ad9ef0e34287638bf07168fccfb0d5cec
Rename UniversalCompiler.txt to *.log
SaladbowlCreative/Unity3D.IncrementalCompiler,SaladLab/Unity3D.IncrementalCompiler
extra/UniversalCompiler/Logger.cs
extra/UniversalCompiler/Logger.cs
using System; using System.IO; using System.Text; using System.Threading; internal class Logger : IDisposable { private enum LoggingMethod { Immediate, Retained, /* - Immediate Every message will be written to the log file right away in real time. - Retained All the messages will be retained in a temporary storage and flushed to disk only when the Logger object is disposed. This solves the log file sharing problem when Unity launched two compilation processes simultaneously, that can happen and happens in case of Assembly-CSharp.dll and Assembly-CSharp-Editor-firstpass.dll as they do not reference one another. */ } private const string LOG_FILENAME = "./Temp/UniversalCompiler.log"; private const int MAXIMUM_FILE_AGE_IN_MINUTES = 5; private readonly Mutex mutex; private readonly LoggingMethod loggingMethod; private readonly StringBuilder pendingLines; public Logger() { mutex = new Mutex(true, "smcs"); if (mutex.WaitOne(0)) // check if no other process is owning the mutex { loggingMethod = LoggingMethod.Immediate; DeleteLogFileIfTooOld(); } else { pendingLines = new StringBuilder(); loggingMethod = LoggingMethod.Retained; } } public void Dispose() { mutex.WaitOne(); // make sure we own the mutex now, so no other process is writing to the file if (loggingMethod == LoggingMethod.Retained) { DeleteLogFileIfTooOld(); File.AppendAllText(LOG_FILENAME, pendingLines.ToString()); } mutex.ReleaseMutex(); } private void DeleteLogFileIfTooOld() { var lastWriteTime = new FileInfo(LOG_FILENAME).LastWriteTimeUtc; if (DateTime.UtcNow - lastWriteTime > TimeSpan.FromMinutes(MAXIMUM_FILE_AGE_IN_MINUTES)) { File.Delete(LOG_FILENAME); } } public void AppendHeader() { var dateTimeString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); var middleLine = "*" + new string(' ', 78) + "*"; int index = (80 - dateTimeString.Length) / 2; middleLine = middleLine.Remove(index, dateTimeString.Length).Insert(index, dateTimeString); Append(new string('*', 80)); Append(middleLine); Append(new string('*', 80)); } public void Append(string message) { if (loggingMethod == LoggingMethod.Immediate) { File.AppendAllText(LOG_FILENAME, message + Environment.NewLine); } else { pendingLines.AppendLine(message); } } }
using System; using System.IO; using System.Text; using System.Threading; internal class Logger : IDisposable { private enum LoggingMethod { Immediate, Retained, /* - Immediate Every message will be written to the log file right away in real time. - Retained All the messages will be retained in a temporary storage and flushed to disk only when the Logger object is disposed. This solves the log file sharing problem when Unity launched two compilation processes simultaneously, that can happen and happens in case of Assembly-CSharp.dll and Assembly-CSharp-Editor-firstpass.dll as they do not reference one another. */ } private const string LOG_FILENAME = "./Temp/UniversalCompiler.txt"; private const int MAXIMUM_FILE_AGE_IN_MINUTES = 5; private readonly Mutex mutex; private readonly LoggingMethod loggingMethod; private readonly StringBuilder pendingLines; public Logger() { mutex = new Mutex(true, "smcs"); if (mutex.WaitOne(0)) // check if no other process is owning the mutex { loggingMethod = LoggingMethod.Immediate; DeleteLogFileIfTooOld(); } else { pendingLines = new StringBuilder(); loggingMethod = LoggingMethod.Retained; } } public void Dispose() { mutex.WaitOne(); // make sure we own the mutex now, so no other process is writing to the file if (loggingMethod == LoggingMethod.Retained) { DeleteLogFileIfTooOld(); File.AppendAllText(LOG_FILENAME, pendingLines.ToString()); } mutex.ReleaseMutex(); } private void DeleteLogFileIfTooOld() { var lastWriteTime = new FileInfo(LOG_FILENAME).LastWriteTimeUtc; if (DateTime.UtcNow - lastWriteTime > TimeSpan.FromMinutes(MAXIMUM_FILE_AGE_IN_MINUTES)) { File.Delete(LOG_FILENAME); } } public void AppendHeader() { var dateTimeString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); var middleLine = "*" + new string(' ', 78) + "*"; int index = (80 - dateTimeString.Length) / 2; middleLine = middleLine.Remove(index, dateTimeString.Length).Insert(index, dateTimeString); Append(new string('*', 80)); Append(middleLine); Append(new string('*', 80)); } public void Append(string message) { if (loggingMethod == LoggingMethod.Immediate) { File.AppendAllText(LOG_FILENAME, message + Environment.NewLine); } else { pendingLines.AppendLine(message); } } }
mit
C#
bef17d81e45086e2b1abb56631909e440fc3e3a0
Clean up code.
ronnymgm/csla-light,BrettJaner/csla,jonnybee/csla,ronnymgm/csla-light,ronnymgm/csla-light,JasonBock/csla,BrettJaner/csla,jonnybee/csla,JasonBock/csla,rockfordlhotka/csla,MarimerLLC/csla,JasonBock/csla,rockfordlhotka/csla,jonnybee/csla,MarimerLLC/csla,MarimerLLC/csla,rockfordlhotka/csla,BrettJaner/csla
ProjectTrackercs/PTWcfServiceAuth/CredentialValidator.cs
ProjectTrackercs/PTWcfServiceAuth/CredentialValidator.cs
using System; using System.Configuration; using System.Web; using System.IdentityModel.Selectors; using System.ServiceModel; using ProjectTracker.Library.Security; namespace PTWcfServiceAuth { /// <summary> /// Summary description for CredentialValidator /// </summary> public class CredentialValidator : UserNamePasswordValidator { public override void Validate(string userName, string password) { if (userName != "anonymous") { PTPrincipal.Logout(); //if (!PTPrincipal.VerifyCredentials(userName, password)) if (!PTPrincipal.Login(userName, password)) throw new FaultException("Unknown username or password"); // add current principal to rolling cache Csla.Security.PrincipalCache.AddPrincipal(Csla.ApplicationContext.User); } } } }
using System; using System.Data; using System.Configuration; using System.Web; using System.IdentityModel.Selectors; using System.ServiceModel; using ProjectTracker.Library.Security; namespace PTWcfServiceAuth { /// <summary> /// Summary description for CredentialValidator /// </summary> public class CredentialValidator : UserNamePasswordValidator { public override void Validate(string userName, string password) { if (userName != "anonymous") { PTPrincipal.Logout(); //if (!PTPrincipal.VerifyCredentials(userName, password)) if (!PTPrincipal.Login(userName, password)) throw new FaultException("Unknown username or password"); // add current principal to rolling cache Csla.Security.PrincipalCache.AddPrincipal(Csla.ApplicationContext.User); } } } }
mit
C#
0f2c686c03a3958b3e3e480c77536ab58467f2da
Update About.cshtml
mishrsud/sudhanshutheone.com,mishrsud/sudhanshutheone.com,daveaglick/daveaglick,mishrsud/sudhanshutheone.com,daveaglick/daveaglick
Somedave/Views/Home/About.cshtml
Somedave/Views/Home/About.cshtml
@{ Title = "About"; } @Html.Partial(MVC.Shared.Views.Title, "icon-megaphone") @using (var container = Bootstrap.Container()) { @Bootstrap.Lead("Hello, my name is Dave Glick.") <p>I am currently the Principal Software Engineer at the @Bootstrap.Link("Securities Investor Protection Corporation (SIPC)", "http://www.sipc.org") where I lead the design and development of line-of-business web applications using .NET technologies like ASP.NET MVC, Entity Framework, and client libraries like jQuery, KendoUI, and Bootstrap.</p> <p>Of course, we're all hopefully much more than where we plant our butt (or stand if you're one of those standing desk folks) during the week. At home I am a husband and father to three very active kids and enjoy every moment. That doesn't leave a lot of left-over time, but when I do get the chance I enjoy @Bootstrap.Link("taking pictures", "http://flickr.com/photos/somedave/") and @Bootstrap.Link("a good book", "http://www.goodreads.com/somedave"). Somehow, I also occasionally find time to @Bootstrap.Link("write code", "https://github.com/somedave").</p> <p>I have profiles scattered around the web at the following sites:</p> @Html.Partial(MVC.Shared.Views.SocialLinks) }
@{ Title = "About"; } @Html.Partial(MVC.Shared.Views.Title, "icon-megaphone") @using (var container = Bootstrap.Container()) { @Bootstrap.Lead("Hello, my name is Dave Glick.") <p>I am currently the Principal Software Engineer at the @Bootstrap.Link("Securities Investor Protection Corporation (SIPC)", "http://www.sipc.org") where I lead the design and development of line-of-business web applications using .NET technologies like ASP.NET MVC, Entity Framework, and client libraries like jQuery, KendoUI, and Bootstrap.</p> <p>Of course, we're all hopefully much more than where we plant our butt (or stand if you're one of those standing desk folks) during weekdays. At home I am a father to three very active kids and enjoy it immensely. That doesn't leave a lot of left-over time, but when I do get the chance I enjoy @Bootstrap.Link("taking pictures", "http://flickr.com/photos/somedave/") and @Bootstrap.Link("a good book", "http://www.goodreads.com/somedave").</p> <p>I have profiles scattered around the web at the following sites:</p> @Html.Partial(MVC.Shared.Views.SocialLinks) }
mit
C#
93f485a681524768351b4f9e3ede702433ddb0e0
Update comment
ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework
osu.Framework/Audio/AudioCollectionManager.cs
osu.Framework/Audio/AudioCollectionManager.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; namespace osu.Framework.Audio { /// <summary> /// A collection of audio components which need central property control. /// </summary> public class AudioCollectionManager<T> : AdjustableAudioComponent, IBassAudio where T : AdjustableAudioComponent { internal List<T> Items = new List<T>(); public void AddItem(T item) { EnqueueAction(delegate { if (Items.Contains(item)) return; item.BindAdjustments(this); Items.Add(item); }); } public virtual void UpdateDevice(int deviceIndex) { foreach (var item in Items.OfType<IBassAudio>()) item.UpdateDevice(deviceIndex); } protected override void UpdateChildren() { base.UpdateChildren(); for (int i = 0; i < Items.Count; i++) { var item = Items[i]; if (!item.IsAlive) { Items.RemoveAt(i--); continue; } item.Update(); } } protected override void Dispose(bool disposing) { // make the items queue their disposal, so they get disposed when <see cref="UpdateChildren"/> updates them. foreach (var i in Items) i.Dispose(); base.Dispose(disposing); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; namespace osu.Framework.Audio { /// <summary> /// A collection of audio components which need central property control. /// </summary> public class AudioCollectionManager<T> : AdjustableAudioComponent, IBassAudio where T : AdjustableAudioComponent { internal List<T> Items = new List<T>(); public void AddItem(T item) { EnqueueAction(delegate { if (Items.Contains(item)) return; item.BindAdjustments(this); Items.Add(item); }); } public virtual void UpdateDevice(int deviceIndex) { foreach (var item in Items.OfType<IBassAudio>()) item.UpdateDevice(deviceIndex); } protected override void UpdateChildren() { base.UpdateChildren(); for (int i = 0; i < Items.Count; i++) { var item = Items[i]; if (!item.IsAlive) { Items.RemoveAt(i--); continue; } item.Update(); } } protected override void Dispose(bool disposing) { // we need to queue disposal of our Items before enqueueing the main dispose. foreach (var i in Items) i.Dispose(); base.Dispose(disposing); } } }
mit
C#
9e1d140427022b432b687af0698a6ef35e90c0a8
Test improved.
thedmi/Finalist,thedmi/MiniGuard,thedmi/MayBee,thedmi/Finalist,thedmi/Equ,thedmi/Equ
Sources/BeltTest/LazyTest.cs
Sources/BeltTest/LazyTest.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="LazyTest.cs" company="Dani Michel"> // Dani Michel 2013 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace BeltTest { using Belt.Lazy; using Xunit; public class LazyTest { [Fact] public void LazyDoesEvaluateLazily() { var evaluated = false; var lazy = Lazy.Create( () => { // Close over 'evaluated' for the sake of the test // (don't do this in production) evaluated = true; return 42; }); Assert.False(evaluated); Assert.Equal(42, lazy.Value); Assert.True(evaluated); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="LazyTest.cs" company="Dani Michel"> // Dani Michel 2013 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace BeltTest { using Belt.Lazy; using Xunit; public class LazyTest { [Fact] public void LazyDoesEvaluateLazily() { var evaluated = false; var lazy = Lazy.Create( () => { // Close over 'evaluated' for the sake of the test // (don't do this in production) evaluated = true; return 0; }); Assert.False(evaluated); Assert.NotNull(lazy.Value); Assert.True(evaluated); } } }
mit
C#
a2d51ad533cf7308f1180e2dc6cfcdf4226de1bc
Add Do Feature
seyedk/Staffing
Staffing/Staffing/Program.cs
Staffing/Staffing/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Staffing { class Program { static void Main(string[] args) { } static void DoSomthing() { Console.WriteLine("I'm doing something now!"); } static void Feature() { Console.WriteLine("Feature 01 has been implemented!"); } static void ExternalAccess() { //added by external user. Console.Write("Please enter your key:"); var keyedin = Console.ReadLine(); Console.WriteLine("You keyed in: {0}", keyedin); } static void DoFeature() { Console.WriteLine("Feature is done!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Staffing { class Program { static void Main(string[] args) { } static void DoSomthing() { Console.WriteLine("I'm doing something now!"); } static void Feature() { Console.WriteLine("Feature 01 has been implemented!"); } static void ExternalAccess() { //added by external user. Console.Write("Please enter your key:"); var keyedin = Console.ReadLine(); Console.WriteLine("You keyed in: {0}", keyedin); } } }
mit
C#
27eda8b5412218dc26b2d79a6a1371a4d223fdf4
Fix unhandled error causing crash
danielchalmers/SteamAccountSwitcher
SteamAccountSwitcher/App.xaml.cs
SteamAccountSwitcher/App.xaml.cs
#region using System.Windows; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public App() { Dispatcher.UnhandledException += OnDispatcherUnhandledException; } protected override void OnExit(ExitEventArgs e) { base.OnExit(e); Settings.Default.Save(); ClickOnceHelper.RunOnStartup(Settings.Default.AlwaysOn); } private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { var errorMessage = $"An unhandled exception occurred:\n\n{e.Exception.Message}"; MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error); e.Handled = true; } } }
#region using System.Windows; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnExit(ExitEventArgs e) { base.OnExit(e); Settings.Default.Save(); ClickOnceHelper.RunOnStartup(Settings.Default.AlwaysOn); } } }
mit
C#
e23397c6b6ad51d661119733f93fceba8ff336c4
Bump version to 0.13.0
ar3cka/Journalist
src/SolutionInfo.cs
src/SolutionInfo.cs
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.13.0")] [assembly: AssemblyInformationalVersionAttribute("0.13.0")] [assembly: AssemblyFileVersionAttribute("0.13.0")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.13.0"; } }
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.12.0")] [assembly: AssemblyInformationalVersionAttribute("0.12.0")] [assembly: AssemblyFileVersionAttribute("0.12.0")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.12.0"; } }
apache-2.0
C#
9b1837d51a44d220372e9b58937eaad9a45758c1
Bump version to 0.6.5
ar3cka/Journalist
src/SolutionInfo.cs
src/SolutionInfo.cs
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.6.5")] [assembly: AssemblyInformationalVersionAttribute("0.6.5")] [assembly: AssemblyFileVersionAttribute("0.6.5")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.6.5"; } }
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.6.4")] [assembly: AssemblyInformationalVersionAttribute("0.6.4")] [assembly: AssemblyFileVersionAttribute("0.6.4")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.6.4"; } }
apache-2.0
C#
c50cdcef559bf230a65975018ecdbe4c132029ec
Teste Atualização Maq2
wevertoncouy/TestHitRub
TestGitHub/TestGitHub/Program.cs
TestGitHub/TestGitHub/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestGitHub { class Program { static void EscrevaNaTela(String txt) { Console.WriteLine(txt); } static void Main(string[] args) { Console.WriteLine("Teste no Maq01"); Console.WriteLine("Teste no Maq02"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestGitHub { class Program { static void EscrevaNaTela(String txt) { Console.WriteLine(txt); } static void Main(string[] args) { Console.WriteLine("Teste no Maq01"); Console.ReadKey(); } } }
mit
C#
f37aa465a65c621195f4d9ca7468133127c2c1c0
Fix crashes related to saving Slow effect incorrectly.
jeongroseok/magecrawl,AndrewBaker/magecrawl
Trunk/GameEngine/Effects/Slow.cs
Trunk/GameEngine/Effects/Slow.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Magecrawl.GameEngine.Actors; using Magecrawl.Utilities; namespace Magecrawl.GameEngine.Effects { internal class Slow : NegativeEffect { private double m_modifier; public Slow() : base(0) { } public Slow(int strength) : base(new DiceRoll(4, 2, strength).Roll() * CoreTimingEngine.CTNeededForNewTurn) { m_modifier = 1.4; } public override void Apply(Character appliedTo) { appliedTo.CTIncreaseModifier /= m_modifier; } public override void Remove(Character removedFrom) { removedFrom.CTIncreaseModifier *= m_modifier; } public override string Name { get { return "Slow"; } } #region SaveLoad public override void ReadXml(System.Xml.XmlReader reader) { base.ReadXml(reader); m_modifier = reader.ReadElementContentAsDouble(); } public override void WriteXml(System.Xml.XmlWriter writer) { base.WriteXml(writer); writer.WriteElementString("Modifier", m_modifier.ToString()); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Magecrawl.GameEngine.Actors; using Magecrawl.Utilities; namespace Magecrawl.GameEngine.Effects { internal class Slow : NegativeEffect { private double m_modifier; public Slow() : base(0) { } public Slow(int strength) : base(new DiceRoll(4, 2, strength).Roll() * CoreTimingEngine.CTNeededForNewTurn) { m_modifier = 1.4; } public override void Apply(Character appliedTo) { appliedTo.CTIncreaseModifier /= m_modifier; } public override void Remove(Character removedFrom) { removedFrom.CTIncreaseModifier *= m_modifier; } public override string Name { get { return "Haste"; } } #region SaveLoad public override void ReadXml(System.Xml.XmlReader reader) { base.ReadXml(reader); m_modifier = reader.ReadContentAsDouble(); } public override void WriteXml(System.Xml.XmlWriter writer) { base.WriteXml(writer); writer.WriteElementString("Modifier", m_modifier.ToString()); } #endregion } }
bsd-2-clause
C#
d6ee133ee419619d9fca5ca073a8d3845dc9a344
Fix for navigating homepage.
cube-soft/Cube.Core,cube-soft/Cube.Core
Behaviors/WindowsFormsBehavior.cs
Behaviors/WindowsFormsBehavior.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Windows.Interactivity; using System.Windows.Forms; using System.Windows.Forms.Integration; namespace Cube.Xui.Behaviors { /* --------------------------------------------------------------------- */ /// /// WindowsFormsBehavior /// /// <summary> /// WindowsForms に対して Behavior を適用するためのクラスです。 /// </summary> /// /* --------------------------------------------------------------------- */ public class WindowsFormsBehavior<TControl> : Behavior<WindowsFormsHost> where TControl : Control { /* ----------------------------------------------------------------- */ /// /// Source /// /// <summary> /// 対象となるコントロールオブジェクトを取得します。 /// </summary> /// /* ----------------------------------------------------------------- */ public TControl Source => AssociatedObject?.Child as TControl; /* ----------------------------------------------------------------- */ /// /// Source /// /// <summary> /// 対象となるコントロールの親オブジェクトを取得します。 /// </summary> /// /* ----------------------------------------------------------------- */ public WindowsFormsHost Parent => AssociatedObject; } }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Windows.Interactivity; using System.Windows.Forms; using System.Windows.Forms.Integration; namespace Cube.Xui.Behaviors { /* --------------------------------------------------------------------- */ /// /// WindowsFormsBehavior /// /// <summary> /// WindowsForms に対して Behavior を適用するためのクラスです。 /// </summary> /// /* --------------------------------------------------------------------- */ public class WindowsFormsBehavior<TControl> : Behavior<WindowsFormsHost> where TControl : Control { /* ----------------------------------------------------------------- */ /// /// Source /// /// <summary> /// 対象となるコントロールオブジェクトを取得します。 /// </summary> /// /* ----------------------------------------------------------------- */ public TControl Source => AssociatedObject?.Child as TControl; } }
apache-2.0
C#
f809cc56fd418815fcc6ac89efeb3495bedee8a5
Use the .After() method in NUnit instead of Thread.Sleep
airbrake/SharpBrake,kayoom/SharpBrake,cbtnuggets/SharpBrake,airbrake/SharpBrake
Tests/AirbrakeClientTests.cs
Tests/AirbrakeClientTests.cs
using System; using NUnit.Framework; using SharpBrake; using SharpBrake.Serialization; namespace Tests { [TestFixture] public class AirbrakeClientTests { #region Setup/Teardown [SetUp] public void SetUp() { this.client = new AirbrakeClient(); } #endregion private AirbrakeClient client; [Test] public void Send_EndRequestEventIsInvoked_And_ResponseOnlyContainsApiError() { bool requestEndInvoked = false; AirbrakeResponseError[] errors = null; int i = 0; this.client.RequestEnd += (sender, e) => { requestEndInvoked = true; errors = e.Response.Errors; }; var configuration = new AirbrakeConfiguration { ApiKey = Guid.NewGuid().ToString("N"), EnvironmentName = "test", }; var builder = new AirbrakeNoticeBuilder(configuration); AirbrakeNotice notice = builder.Notice(new Exception("Test")); notice.Request = new AirbrakeRequest("http://example.com", "Test") { Params = new[] { new AirbrakeVar("TestKey", "TestValue") } }; this.client.Send(notice); Assert.That(requestEndInvoked, Is.True.After(5000)); Assert.That(errors, Is.Not.Null); Assert.That(errors, Has.Length.EqualTo(1)); } } }
using System; using System.Threading; using NUnit.Framework; using SharpBrake; using SharpBrake.Serialization; namespace Tests { [TestFixture] public class AirbrakeClientTests { #region Setup/Teardown [SetUp] public void SetUp() { this.client = new AirbrakeClient(); } #endregion private AirbrakeClient client; [Test] public void Send_EndRequestEventIsInvoked_And_ResponseOnlyContainsApiError() { bool requestEndInvoked = false; AirbrakeResponseError[] errors = null; int i = 0; this.client.RequestEnd += (sender, e) => { requestEndInvoked = true; errors = e.Response.Errors; }; var configuration = new AirbrakeConfiguration { ApiKey = Guid.NewGuid().ToString("N"), EnvironmentName = "test", }; var builder = new AirbrakeNoticeBuilder(configuration); AirbrakeNotice notice = builder.Notice(new Exception("Test")); notice.Request = new AirbrakeRequest("http://example.com", "Test") { Params = new[] { new AirbrakeVar("TestKey", "TestValue") } }; this.client.Send(notice); while (!requestEndInvoked) { // Sleep for maximum 5 seconds to wait for the request to end. Can probably be done more elegantly. if (i++ == 50) break; Thread.Sleep(100); } Assert.That(requestEndInvoked, Is.True); Assert.That(errors, Is.Not.Null); Assert.That(errors, Has.Length.EqualTo(1)); } } }
mit
C#
26bdd31c813785c0227cec8ce723672fc1e3fae9
switch to AllFailingTestsClipboardReporter
pascalberger/GitVersion,dazinator/GitVersion,FireHost/GitVersion,anobleperson/GitVersion,gep13/GitVersion,distantcam/GitVersion,Philo/GitVersion,Philo/GitVersion,openkas/GitVersion,ParticularLabs/GitVersion,gep13/GitVersion,anobleperson/GitVersion,asbjornu/GitVersion,MarkZuber/GitVersion,GeertvanHorrik/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,alexhardwicke/GitVersion,pascalberger/GitVersion,TomGillen/GitVersion,ermshiperete/GitVersion,DanielRose/GitVersion,ermshiperete/GitVersion,asbjornu/GitVersion,dpurge/GitVersion,GeertvanHorrik/GitVersion,Kantis/GitVersion,distantcam/GitVersion,Kantis/GitVersion,dazinator/GitVersion,orjan/GitVersion,alexhardwicke/GitVersion,onovotny/GitVersion,onovotny/GitVersion,DanielRose/GitVersion,dpurge/GitVersion,orjan/GitVersion,Kantis/GitVersion,JakeGinnivan/GitVersion,RaphHaddad/GitVersion,ermshiperete/GitVersion,FireHost/GitVersion,dpurge/GitVersion,onovotny/GitVersion,RaphHaddad/GitVersion,GitTools/GitVersion,MarkZuber/GitVersion,JakeGinnivan/GitVersion,JakeGinnivan/GitVersion,JakeGinnivan/GitVersion,DanielRose/GitVersion,TomGillen/GitVersion,openkas/GitVersion,ParticularLabs/GitVersion,pascalberger/GitVersion,anobleperson/GitVersion,dpurge/GitVersion
Tests/ApprovalTestsConfig.cs
Tests/ApprovalTestsConfig.cs
using ApprovalTests.Reporters; [assembly: UseReporter(typeof(DiffReporter), typeof(AllFailingTestsClipboardReporter))]
using ApprovalTests.Reporters; [assembly: UseReporter(typeof(DiffReporter), typeof(ClipboardReporter))]
mit
C#
be271602a48596ab5db206e7ff917d066491aede
Print objects in JSON format
whampson/cascara,whampson/bft-spec
examples/Program.cs
examples/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WHampson.Cascara; namespace WHampson.CascaraExamples { class Program { const string LayoutXml = @" <cascaraLayout name='a layout' description='A Test Layout'> <struct name='test'> <int name='foo'/> <struct name='nest'> <int name='bar'/> <byte name='abc' count='2'/> <char name='str' count='4'/> <echo message='${__OFFSET__}'/> <echo message='${__GLOBALOFFSET__}'/> </struct> </struct> <echo message='$OffsetOf(test.nest.str)'/> <echo message='$GlobalOffsetOf(test.nest.str)'/> </cascaraLayout>"; static void Main(string[] args) { byte[] data = { 0xBE, 0xBA, 0xFE, 0xCA, 0xEF, 0xBE, 0xAD, 0xDE, 0xAA, 0x55, 0x61, 0x62 ,0x63, 0x00 }; LayoutScript layout = LayoutScript.Parse(LayoutXml); BinaryFile file = new BinaryFile(data); file.ApplyLayout(layout); Console.WriteLine("{0}: {1}", nameof(LayoutScript), layout); Console.WriteLine("{0}: {1}", nameof(BinaryFile), file); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WHampson.Cascara; namespace WHampson.CascaraExamples { class Program { const string LayoutXml = @" <cascaraLayout name='a layout' description='A Test Layout'> <struct name='test'> <int name='foo'/> <struct name='nest'> <int name='bar'/> <byte name='abc' count='2'/> <char name='str' count='4'/> <echo message='${__OFFSET__}'/> <echo message='${__GLOBALOFFSET__}'/> </struct> </struct> <echo message='$OffsetOf(test.nest.str)'/> <echo message='$GlobalOffsetOf(test.nest.str)'/> </cascaraLayout>"; static void Main(string[] args) { byte[] data = { 0xBE, 0xBA, 0xFE, 0xCA, 0xEF, 0xBE, 0xAD, 0xDE, 0xAA, 0x55, 0x61, 0x62 ,0x63, 0x00 }; // LayoutScript layout = LayoutScript.Parse(LayoutXml); LayoutScript layout = LayoutScript.Load("test.xml"); BinaryFile file = new BinaryFile(data); file.ApplyLayout(layout); var w = file.GetPrimitive<int>("test.foo"); var v = file.GetPrimitive<Char8>("test.nest.str"); var a = v.ReinterpretCast<byte>(); var b = file.GetStructure("test"); Console.WriteLine(w); Console.WriteLine(v); Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(file); Console.WriteLine(layout); } } }
mit
C#
fcbc1a2d9e4f64632b35ab7ee7718e3687acb2d7
bump version to 2.1.0
Fody/Fody,GeertvanHorrik/Fody
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("2.1.0")] [assembly: AssemblyFileVersion("2.1.0")]
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("2.0.11")] [assembly: AssemblyFileVersion("2.0.11")]
mit
C#
427f0baabb69b17689fb15af99c2f0a756dd5a5e
bump version
user1568891/PropertyChanged,Fody/PropertyChanged
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("PropertyChanged")] [assembly: AssemblyProduct("PropertyChanged")] [assembly: AssemblyCompany("Simon Cropp and Contributors")] [assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")] [assembly: AssemblyVersion("1.52.1")] [assembly: AssemblyFileVersion("1.52.1")]
using System.Reflection; [assembly: AssemblyTitle("PropertyChanged")] [assembly: AssemblyProduct("PropertyChanged")] [assembly: AssemblyCompany("Simon Cropp and Contributors")] [assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")] [assembly: AssemblyVersion("1.52.0")] [assembly: AssemblyFileVersion("1.52.0")]
mit
C#
b300bc1e24d758416e2f6c1e2e27621e44b0cdee
Fix ever-increasing flashlight-strain
peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu
osu.Game.Rulesets.Osu/Difficulty/Skills/Flashlight.cs
osu.Game.Rulesets.Osu/Difficulty/Skills/Flashlight.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Difficulty.Evaluators; using osu.Game.Rulesets.Osu.Mods; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to memorise and hit every object in a map with the Flashlight mod enabled. /// </summary> public class Flashlight : OsuStrainSkill { public Flashlight(Mod[] mods) : base(mods) { } private double skillMultiplier => 0.05; private double strainDecayBase => 0.15; protected override double DecayWeight => 1.0; private double currentStrain; private double strainDecay(double ms) => Math.Pow(strainDecayBase, ms / 1000); protected override double CalculateInitialStrain(double time, DifficultyHitObject current) => currentStrain * strainDecay(time - current.Previous(0).StartTime); protected override double StrainValueAt(DifficultyHitObject current) { currentStrain *= strainDecay(current.DeltaTime); currentStrain += FlashlightEvaluator.EvaluateDifficultyOf(current, Mods.Any(m => m is OsuModHidden)) * skillMultiplier; return currentStrain; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Difficulty.Evaluators; using osu.Game.Rulesets.Osu.Mods; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to memorise and hit every object in a map with the Flashlight mod enabled. /// </summary> public class Flashlight : OsuStrainSkill { public Flashlight(Mod[] mods) : base(mods) { } private double skillMultiplier => 0.05; private double strainDecayBase => 0.15; protected override double DecayWeight => 1.0; private double currentStrain; private double strainDecay(double ms) => Math.Pow(strainDecayBase, ms / 1000); protected override double CalculateInitialStrain(double time, DifficultyHitObject current) => currentStrain * strainDecay(time - current.Previous(0).StartTime); protected override double StrainValueAt(DifficultyHitObject current) { currentStrain *= strainDecay(current.DeltaTime); currentStrain += currentStrain += FlashlightEvaluator.EvaluateDifficultyOf(current, Mods.Any(m => m is OsuModHidden)) * skillMultiplier; return currentStrain; } } }
mit
C#
85359ca4e9f62015412145830d8e1e0796ddc130
Fix login URL
RomeuCarvalhoAntunes/2017.1-Forum-Coordenadores-DEG,vitorfhc/2017.1-Forum-Coordenadores-DEG,MarianaPicolo/2017.1-Forum-Coordenadores-DEG,vitorbertulucci/2017.1-Forum-Coordenadores-DEG
ForumDEG/ForumDEG/Helpers/User.cs
ForumDEG/ForumDEG/Helpers/User.cs
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace ForumDEG.Helpers { class User { private HttpClient _client; public User() { _client = new HttpClient(); _client.MaxResponseContentBufferSize = 256000; } public async Task<string> AuthenticateLogin(string _registration, string _password) { var uri = new Uri(string.Format(Constants.RestUrl, "users/authenticate")); var registration = _registration; var password = _password; var body = new JObject(); body.Add("password", password); body.Add("registration", registration); var content = new StringContent(body.ToString(), Encoding.UTF8, "application/json"); Debug.WriteLine("[User API]: Antes do Try"); try { var response = await _client.PostAsync(uri, content); Debug.WriteLine("[User API]: depois do response"); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); Debug.WriteLine("[User API] - Post result: " + responseContent); var _return = await response.Content.ReadAsStringAsync(); var obj = JObject.Parse(_return); return obj["user"].ToString(); } else { var failedContent = await response.Content.ReadAsStringAsync(); Debug.WriteLine("[User API] - Post response unsuccessful "+ failedContent); return "Fail"; } } catch (Exception ex) { Debug.WriteLine("[User API exception]:" + ex.Message); return "Fail"; } } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace ForumDEG.Helpers { class User { private HttpClient _client; public User() { _client = new HttpClient(); _client.MaxResponseContentBufferSize = 256000; } public async Task<string> AuthenticateLogin(string _registration, string _password) { //var uri = new Uri(string.Format(Constants.RestUrl, "users/authenticate")); var uri = new Uri("https://forumdeg.herokuapp.com/api/users/authenticate"); var registration = _registration; var password = _password; var body = new JObject(); body.Add("password", password); body.Add("registration", registration); var content = new StringContent(body.ToString(), Encoding.UTF8, "application/json"); //var contentString = await content.ReadAsStringAsync(); Debug.WriteLine("[User API]: Antes do Try"); try { var response = await _client.PostAsync(uri, content); Debug.WriteLine("[User API]: depois do response"); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); Debug.WriteLine("[User API] - Post result: " + responseContent); var _return = await response.Content.ReadAsStringAsync(); var obj = JObject.Parse(_return); return obj["user"].ToString(); } else { var failedContent = await response.Content.ReadAsStringAsync(); Debug.WriteLine("[User API] - Post response unsuccessful "+ failedContent); return "Fail"; } } catch (Exception ex) { Debug.WriteLine("[User API exception]:" + ex.Message); return "Fail"; } } } }
mit
C#
fafe080f5c904b04f51504b2edaa1991c66f9cb1
fix error due to non-public Automate API class (#119)
Pathoschild/StardewMods
Automate/Framework/AutomateAPI.cs
Automate/Framework/AutomateAPI.cs
using System.Collections.Generic; using StardewValley; namespace Pathoschild.Stardew.Automate.Framework { /// <summary>The API which lets other mods interact with Automate.</summary> public class AutomateAPI : IAutomateAPI { /********* ** Properties *********/ /// <summary>Constructs machine groups.</summary> private readonly MachineGroupFactory MachineGroupFactory; /// <summary>The machines to process.</summary> private readonly IDictionary<GameLocation, MachineGroup[]> MachineGroups; /********* ** Public methods *********/ /// <summary>Add an automation factory.</summary> /// <param name="factory">An automation factory which construct machines, containers, and connectors.</param> public void AddFactory(IAutomationFactory factory) { this.MachineGroupFactory.Add(factory); } /********* ** Internal methods *********/ /// <summary>Construct an instance.</summary> /// <param name="machineGroupFactory">Constructs machine groups.</param> /// <param name="machineGroups">A live view of the machine groups recognised by Automate.</param> internal AutomateAPI(MachineGroupFactory machineGroupFactory, IDictionary<GameLocation, MachineGroup[]> machineGroups) { this.MachineGroupFactory = machineGroupFactory; this.MachineGroups = machineGroups; } } }
using System.Collections.Generic; using StardewValley; namespace Pathoschild.Stardew.Automate.Framework { /// <summary>The API which lets other mods interact with Automate.</summary> internal class AutomateAPI : IAutomateAPI { /********* ** Properties *********/ /// <summary>Constructs machine groups.</summary> private readonly MachineGroupFactory MachineGroupFactory; /// <summary>The machines to process.</summary> private readonly IDictionary<GameLocation, MachineGroup[]> MachineGroups; /********* ** Public methods *********/ /// <summary>Add an automation factory.</summary> /// <param name="factory">An automation factory which construct machines, containers, and connectors.</param> public void AddFactory(IAutomationFactory factory) { this.MachineGroupFactory.Add(factory); } /********* ** Internal methods *********/ /// <summary>Construct an instance.</summary> /// <param name="machineGroupFactory">Constructs machine groups.</param> /// <param name="machineGroups">A live view of the machine groups recognised by Automate.</param> internal AutomateAPI(MachineGroupFactory machineGroupFactory, IDictionary<GameLocation, MachineGroup[]> machineGroups) { this.MachineGroupFactory = machineGroupFactory; this.MachineGroups = machineGroups; } } }
mit
C#
8063ef471371482a82d2b8348907d0c7108830b7
Update Settings class
rmarinho/babysmash
BabySmash.Apps/Models/Settings.cs
BabySmash.Apps/Models/Settings.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BabySmash.Core.Models { public class Settings { private static Settings defaultInstance; public static Settings Default { get { return defaultInstance ?? (defaultInstance = new Settings()); } } public Settings() { ClearAfter = 35; ForceUppercase = true; } public int ClearAfter { get; set; } public bool ForceUppercase { get; set; } public string FontFamily { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BabySmash.Core.Models { public class Settings { private static Settings defaultInstance; public static Settings Default { get { return defaultInstance ?? (defaultInstance = new Settings()); } } public Settings() { ClearAfter = 35; } public int ClearAfter { get; set; } } }
mit
C#
006879a33f0f6e8e3ee6bc1d10622063822a3543
Remove unnecessary qualifier
darrencauthon/csharp-sparkpost,SparkPost/csharp-sparkpost,kirilsi/csharp-sparkpost,kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost
src/SparkPost/File.cs
src/SparkPost/File.cs
using System; using System.IO; using System.Web; namespace SparkPost { public abstract class File { public string Type { get; set; } public string Name { get; set; } public string Data { get; set; } public static T Create<T>(string filename) where T : File, new() { var content = System.IO.File.ReadAllBytes(filename); return Create<T>(content, Path.GetFileName(filename)); } public static T Create<T>(string filename, string name) where T : File, new() { var result = Create<T>(filename); result.Name = name; return result; } public static T Create<T>(byte[] content) where T : File, new() { return Create<T>(content, String.Empty); } public static T Create<T>(byte[] content, string name) where T : File, new() { var result = new T(); if (content != null) { result.Data = Convert.ToBase64String(content); result.Type = MimeMapping.GetMimeMapping(name); result.Name = name; }; return result; } public static T Create<T>(Stream content) where T : File, new() { return Create<T>(content, String.Empty); } public static T Create<T>(Stream content, string name) where T : File, new() { using (var ms = new MemoryStream()) { content.CopyTo(ms); return Create<T>(ms.ToArray(), name); } } } }
using System; using System.IO; using System.Web; namespace SparkPost { public abstract class File { public string Type { get; set; } public string Name { get; set; } public string Data { get; set; } public static T Create<T>(string filename) where T : File, new() { var content = System.IO.File.ReadAllBytes(filename); return Create<T>(content, Path.GetFileName(filename)); } public static T Create<T>(string filename, string name) where T : SparkPost.File, new() { var result = Create<T>(filename); result.Name = name; return result; } public static T Create<T>(byte[] content) where T : File, new() { return Create<T>(content, String.Empty); } public static T Create<T>(byte[] content, string name) where T : File, new() { var result = new T(); if (content != null) { result.Data = Convert.ToBase64String(content); result.Type = MimeMapping.GetMimeMapping(name); result.Name = name; }; return result; } public static T Create<T>(Stream content) where T : File, new() { return Create<T>(content, String.Empty); } public static T Create<T>(Stream content, string name) where T : File, new() { using (var ms = new MemoryStream()) { content.CopyTo(ms); return Create<T>(ms.ToArray(), name); } } } }
apache-2.0
C#
0dcc5dd3179aeacb22f0baf3d61c39d25de18ec7
rewrite TextStream to use Buffer<TToken>
acple/ParsecSharp
ParsecSharp/Data/TextStream.cs
ParsecSharp/Data/TextStream.cs
using System; using System.IO; using System.Linq; using System.Text; using ParsecSharp.Internal; namespace ParsecSharp { public sealed class TextStream : IParsecStateStream<char> { private const int MaxBufferSize = 1024; private readonly IDisposable resource; private readonly Buffer<char> _buffer; private readonly TextPosition _position; private readonly int _index; public char Current => this._buffer[this._index]; public bool HasValue => this._index < this._buffer.Count; public IPosition Position => this._position; public IParsecStateStream<char> Next => (this._index == MaxBufferSize - 1) ? new TextStream(this.resource, this._buffer.Next, this._position.Next(this.Current), 0) : new TextStream(this.resource, this._buffer, this._position.Next(this.Current), this._index + 1); public TextStream(Stream source) : this(source, Encoding.UTF8) { } public TextStream(Stream source, Encoding encoding) : this(new StreamReader(source, encoding)) { } public TextStream(TextReader reader) : this(reader, GenerateBuffer(reader), TextPosition.Initial, 0) { } private TextStream(IDisposable resource, Buffer<char> buffer, TextPosition position, int index) { this.resource = resource; this._buffer = buffer; this._position = position; this._index = index; } private static Buffer<char> GenerateBuffer(TextReader reader) { try { var buffer = Enumerable.Repeat(reader, MaxBufferSize) .Select(reader => reader.Read()) .TakeWhile(x => x != -1) .Select(x => (char)x) .ToArray(); return new Buffer<char>(buffer, () => GenerateBuffer(reader)); } catch { reader.Dispose(); throw; } } public void Dispose() => this.resource.Dispose(); public bool Equals(IParsecState<char> other) => other is TextStream state && this._buffer == state._buffer && this._position == state._position; public sealed override bool Equals(object obj) => obj is TextStream state && this._buffer == state._buffer && this._position == state._position; public sealed override int GetHashCode() => this._buffer.GetHashCode() ^ this._position.GetHashCode(); public sealed override string ToString() => (this.HasValue) ? this.Current.ToReadableStringWithCharCode() : "<EndOfStream>"; } }
using System; using System.IO; using System.Text; using ParsecSharp.Internal; namespace ParsecSharp { public sealed class TextStream : IParsecStateStream<char> { private readonly IDisposable disposable; private readonly TextPosition _position; private readonly Lazy<IParsecStateStream<char>> _next; public char Current { get; } public bool HasValue { get; } public IPosition Position => this._position; public IParsecStateStream<char> Next => this._next.Value; public TextStream(Stream source) : this(source, Encoding.UTF8) { } public TextStream(Stream source, Encoding encoding) : this(new StreamReader(source, encoding)) { } public TextStream(TextReader reader) : this(reader, TextPosition.Initial) { } private TextStream(TextReader reader, TextPosition position) { this.disposable = reader; this._position = position; try { var token = reader.Read(); this.HasValue = token != -1; this.Current = (this.HasValue) ? (char)token : default; } catch { this.Dispose(); throw; } finally { this._next = new Lazy<IParsecStateStream<char>>(() => new TextStream(reader, position.Next(this.Current)), false); } } public void Dispose() => this.disposable.Dispose(); public bool Equals(IParsecState<char> other) => ReferenceEquals(this, other); public sealed override string ToString() => (this.HasValue) ? this.Current.ToReadableStringWithCharCode() : "<EndOfStream>"; } }
mit
C#
63d4cda7615afaa952cfe61177b8df6d9fb1de53
Add missing attributes to DeviceType
WolfspiritM/Colore,CoraleStudios/Colore
Corale.Colore/Razer/DeviceType.cs
Corale.Colore/Razer/DeviceType.cs
// --------------------------------------------------------------------------------------- // <copyright file="DeviceType.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any // of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott // do not take responsibility for any harm caused, direct or indirect, to any // Razer peripherals via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore.Razer { using Corale.Colore.Annotations; /// <summary> /// Device types supported by the Chroma SDK. /// </summary> public enum DeviceType { /// <summary> /// A keyboard device. /// </summary> [PublicAPI] Keyboard = 1, /// <summary> /// A mouse device. /// </summary> [PublicAPI] Mouse, /// <summary> /// A headset device. /// </summary> [PublicAPI] Headset, /// <summary> /// A mouse pad. /// </summary> [PublicAPI] Mousepad, /// <summary> /// A keypad. /// </summary> [PublicAPI] Keypad } }
// --------------------------------------------------------------------------------------- // <copyright file="DeviceType.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any // of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott // do not take responsibility for any harm caused, direct or indirect, to any // Razer peripherals via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore.Razer { /// <summary> /// Device types supported by the Chroma SDK. /// </summary> public enum DeviceType { /// <summary> /// A keyboard device. /// </summary> Keyboard = 1, /// <summary> /// A mouse device. /// </summary> Mouse, /// <summary> /// A headset device. /// </summary> Headset, /// <summary> /// A mouse pad. /// </summary> Mousepad, /// <summary> /// A keypad. /// </summary> Keypad } }
mit
C#
5db6472502c751c3a67bd385d6b3a1ab10e71224
Test package 8 publish module has to be filtered too
markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation
testpackages/Test8/dev/Test8.cs
testpackages/Test8/dev/Test8.cs
// Automatically generated by Opus v0.00 namespace Test8 { // Define module classes here [Opus.Core.ModuleTargets(new string[] { "win.*-.*-.*" })] class ApplicationTest : C.Application { private const string WinVCTarget = "win.*-.*-visualc"; public ApplicationTest() { this.sourceFile.SetRelativePath(this, "source", "main.c"); } [Opus.Core.SourceFiles] C.ObjectFile sourceFile = new C.ObjectFile(); [Opus.Core.RequiredModules] Opus.Core.TypeArray requiredModules = new Opus.Core.TypeArray( typeof(Test7.ExplicitDynamicLibrary) ); [Opus.Core.DependentModules(WinVCTarget)] Opus.Core.TypeArray winVCDependents = new Opus.Core.TypeArray( typeof(WindowsSDK.WindowsSDK) ); [C.RequiredLibraries(WinVCTarget)] Opus.Core.StringArray libraries = new Opus.Core.StringArray( "KERNEL32.lib", "dbghelp.lib" ); } [Opus.Core.ModuleTargets(new string[] { "win.*-.*-.*" })] class PublishDynamicLibraries : FileUtilities.CopyFiles { [FileUtilities.SourceModules(C.OutputFileFlags.Executable)] Opus.Core.TypeArray sourceTargets = new Opus.Core.TypeArray(typeof(Test7.ExplicitDynamicLibrary)); [FileUtilities.DestinationModuleDirectory(C.OutputFileFlags.Executable)] Opus.Core.TypeArray destinationTarget = new Opus.Core.TypeArray(typeof(ApplicationTest)); } }
// Automatically generated by Opus v0.00 namespace Test8 { // Define module classes here [Opus.Core.ModuleTargets(new string[] { "win.*-.*-.*" })] class ApplicationTest : C.Application { private const string WinVCTarget = "win.*-.*-visualc"; public ApplicationTest() { this.sourceFile.SetRelativePath(this, "source", "main.c"); } [Opus.Core.SourceFiles] C.ObjectFile sourceFile = new C.ObjectFile(); [Opus.Core.RequiredModules] Opus.Core.TypeArray requiredModules = new Opus.Core.TypeArray( typeof(Test7.ExplicitDynamicLibrary) ); [Opus.Core.DependentModules(WinVCTarget)] Opus.Core.TypeArray winVCDependents = new Opus.Core.TypeArray( typeof(WindowsSDK.WindowsSDK) ); [C.RequiredLibraries(WinVCTarget)] Opus.Core.StringArray libraries = new Opus.Core.StringArray( "KERNEL32.lib", "dbghelp.lib" ); } class PublishDynamicLibraries : FileUtilities.CopyFiles { [FileUtilities.SourceModules(C.OutputFileFlags.Executable)] Opus.Core.TypeArray sourceTargets = new Opus.Core.TypeArray(typeof(Test7.ExplicitDynamicLibrary)); [FileUtilities.DestinationModuleDirectory(C.OutputFileFlags.Executable)] Opus.Core.TypeArray destinationTarget = new Opus.Core.TypeArray(typeof(ApplicationTest)); } }
bsd-3-clause
C#
d966d206baaa0cca908cedbe5ba121cb6f8343a8
Enable DoubleBuffer, just because
jnwatts/cs320_project2_group11,jnwatts/cs320_project2_group11
mainview.cs
mainview.cs
using System; using System.Data; using System.Drawing; using System.Windows.Forms; using MySql.Data.MySqlClient; public class MainView : Form { TabControl tabControl = null; TabPage rsvTab = null; TabPage pvTab = null; RawSqlView rsv = null; PreferencesView pv = null; public PreferencesView PrefsView { get { return pv; } } public RawSqlView RawSqlView { get { return rsv; } } public MainView() { this.SuspendLayout(); this.DoubleBuffered = true; tabControl = new TabControl(); tabControl.Dock = DockStyle.Fill; Controls.Add(tabControl); rsvTab = new TabPage("Raw SQL"); rsv = new RawSqlView(); rsv.Dock = DockStyle.Fill; rsvTab.Controls.Add(rsv); tabControl.TabPages.Add(rsvTab); pvTab = new TabPage("Preferences"); pv = new PreferencesView(); pv.Dock = DockStyle.Fill; pvTab.Controls.Add(pv); tabControl.TabPages.Add(pvTab); this.ResumeLayout(); } }
using System; using System.Data; using System.Drawing; using System.Windows.Forms; using MySql.Data.MySqlClient; public class MainView : Form { TabControl tabControl = null; TabPage rsvTab = null; TabPage pvTab = null; RawSqlView rsv = null; PreferencesView pv = null; public PreferencesView PrefsView { get { return pv; } } public RawSqlView RawSqlView { get { return rsv; } } public MainView() { this.SuspendLayout(); tabControl = new TabControl(); tabControl.Dock = DockStyle.Fill; Controls.Add(tabControl); rsvTab = new TabPage("Raw SQL"); rsv = new RawSqlView(); rsv.Dock = DockStyle.Fill; rsvTab.Controls.Add(rsv); tabControl.TabPages.Add(rsvTab); pvTab = new TabPage("Preferences"); pv = new PreferencesView(); pv.Dock = DockStyle.Fill; pvTab.Controls.Add(pv); tabControl.TabPages.Add(pvTab); this.ResumeLayout(); } }
apache-2.0
C#
5c149a4ada5f1a4e23ead98560605bba61540037
use TreeLibrary in TreeConsole
kusl/Tree
VisualTree/TreeConsole/Program.cs
VisualTree/TreeConsole/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TreeLibrary; namespace TreeConsole { class Program { static readonly int numberOfNumbers = 100000; static void Main(string[] args) { int[] inputArray = new int[numberOfNumbers]; BinarySearchTree bst = new BinarySearchTree(); AvlTree<int, int> avlTree = new AvlTree<int, int>(); RedBlackTree redBlackTree = new RedBlackTree("rbTree"); TwoThreeTree twoThreeTree = new TwoThreeTree(numberOfNumbers * numberOfNumbers); foreach(int i in inputArray) { bst.Add(i); avlTree.Insert(i, i); redBlackTree.Add(i, i); twoThreeTree.InsertTwoThree(i.ToString()); } } static int[] GenerateNumbers() { int[] result = new int[numberOfNumbers]; for(int i = 0; i < numberOfNumbers; i++) { Random myRandom = new Random(); result[i] = myRandom.Next(1, numberOfNumbers); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TreeConsole { class Program { static void Main(string[] args) { } } }
agpl-3.0
C#
76503edeb15809f456a80f26fb8db6c177243dac
Edit error page
erlingsjostrom/TSS,erlingsjostrom/TSS,erlingsjostrom/TSS
TESS/Views/Shared/Error.cshtml
TESS/Views/Shared/Error.cshtml
@model System.Web.Mvc.HandleErrorInfo @{ ViewBag.Title = "Error"; } <div class="container"> <div class="row"> <div class="col-md-12"> <div class="error-template"> <h1> Oops something went wrong! </h1> <div class="error-details"> Sorry, an error has occured, please contact sales support! </div> <div class="error-actions"> <a href="/" class="btn btn-primary btn-lg"> <span class="glyphicon glyphicon-home"></span> Take Me Home </a> <a href="mailto:[email protected];[email protected]" class="btn btn-default btn-lg"> <span class="glyphicon glyphicon-envelope"></span> Contact Support </a> </div> </div> </div> </div> </div>
@model System.Web.Mvc.HandleErrorInfo @{ ViewBag.Title = "Error"; } <h1 class="text-danger">Error.</h1> <h2 class="text-danger">An error occurred while processing your request.</h2> <div class="col-md-12"> <div class="error-template"> <h1> Oops something went wrong! </h1> <div class="error-details"> Sorry, an error has occured, please contact sales support! </div> <div class="error-actions"> <a href="/" class="btn btn-primary btn-lg"> <span class="glyphicon glyphicon-home"></span> Take Me Home </a> <a href="/" class="btn btn-default btn-lg"> <span class="glyphicon glyphicon-envelope"></span> Contact Support </a> </div> </div> </div>
mit
C#
b1dbeb5e6aaa6d4e0d5b5e1ac63fbc7133f95ab6
Fix baseAddress typo
bringking/mailgun_csharp
Mailgun/Service/MessageService.cs
Mailgun/Service/MessageService.cs
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Mailgun.Core.Messages; using Mailgun.Core.Service; using Mailgun.Exceptions; namespace Mailgun.Service { /// <summary> /// The core mailgun service /// </summary> public class MessageService : IMessageService { public string ApiKey { get; private set; } public string BaseAddress { get; private set; } public bool UseSSl { get; private set; } /// <summary> /// Create an instance of the mailgun service with the specified apikey /// </summary> /// <param name="apikey">Your mailgun API Key</param> /// <param name="useSsl">Should the library use SSL for all requests?</param> /// <param name="baseAddress"></param> public MessageService(string apikey, bool useSsl = true, string baseAddress = "api.mailgun.net/v2") { ApiKey = apikey; BaseAddress = baseAddress; UseSSl = useSsl; } /// <summary> /// Send a message using the Mailgun API service. /// </summary> /// <param name="workingDomain">The mailgun working domain to use</param> /// <param name="message">The message to send</param> /// <returns></returns> public async Task<HttpResponseMessage> SendMessageAsync(string workingDomain, IMessage message) { //check for parameters ThrowIf.IsArgumentNull(() => workingDomain); ThrowIf.IsArgumentNull(() => message); //build request using (var client = new HttpClient()) { var buildUri = new UriBuilder { Host = BaseAddress, Scheme = UseSSl ? "https" : "http", Path = string.Format("{0}/messages", workingDomain) }; //add authentication client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("api:" + ApiKey))); //set the client uri return await client.PostAsync(buildUri.ToString(), message.AsFormContent()); } } } }
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Mailgun.Core.Messages; using Mailgun.Core.Service; using Mailgun.Exceptions; namespace Mailgun.Service { /// <summary> /// The core mailgun service /// </summary> public class MessageService : IMessageService { public string ApiKey { get; private set; } public string BaseAddress { get; private set; } public bool UseSSl { get; private set; } /// <summary> /// Create an instance of the mailgun service with the specified apikey /// </summary> /// <param name="apikey">Your mailgun API Key</param> /// <param name="useSsl">Should the library use SSL for all requests?</param> /// <param name="baseAddresss"></param> public MessageService(string apikey, bool useSsl = true, string baseAddresss = "api.mailgun.net/v2") { ApiKey = apikey; BaseAddress = baseAddresss; UseSSl = useSsl; } /// <summary> /// Send a message using the Mailgun API service. /// </summary> /// <param name="workingDomain">The mailgun working domain to use</param> /// <param name="message">The message to send</param> /// <returns></returns> public async Task<HttpResponseMessage> SendMessageAsync(string workingDomain, IMessage message) { //check for parameters ThrowIf.IsArgumentNull(() => workingDomain); ThrowIf.IsArgumentNull(() => message); //build request using (var client = new HttpClient()) { var buildUri = new UriBuilder { Host = BaseAddress, Scheme = UseSSl ? "https" : "http", Path = string.Format("{0}/messages", workingDomain) }; //add authentication client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("api:" + ApiKey))); //set the client uri return await client.PostAsync(buildUri.ToString(), message.AsFormContent()); } } } }
mit
C#
7d5d3c74a3f2e2d9241030bea435800d594c2564
fix contains generic parameter for FunctionPointerType
joj/cecil,kzu/cecil,jbevain/cecil,fnajera-rac-de/cecil,cgourlay/cecil,xen2/cecil,SiliconStudio/Mono.Cecil,sailro/cecil,gluck/cecil,mono/cecil,ttRevan/cecil,furesoft/cecil,saynomoo/cecil
Mono.Cecil/FunctionPointerType.cs
Mono.Cecil/FunctionPointerType.cs
// // FunctionPointerType.cs // // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using Mono.Collections.Generic; using MD = Mono.Cecil.Metadata; namespace Mono.Cecil { public sealed class FunctionPointerType : TypeSpecification, IMethodSignature { readonly MethodReference function; public bool HasThis { get { return function.HasThis; } set { function.HasThis = value; } } public bool ExplicitThis { get { return function.ExplicitThis; } set { function.ExplicitThis = value; } } public MethodCallingConvention CallingConvention { get { return function.CallingConvention; } set { function.CallingConvention = value; } } public bool HasParameters { get { return function.HasParameters; } } public Collection<ParameterDefinition> Parameters { get { return function.Parameters; } } public TypeReference ReturnType { get { return function.MethodReturnType.ReturnType; } set { function.MethodReturnType.ReturnType = value; } } public MethodReturnType MethodReturnType { get { return function.MethodReturnType; } } public override string Name { get { return function.Name; } set { throw new InvalidOperationException (); } } public override string Namespace { get { return string.Empty; } set { throw new InvalidOperationException (); } } public override ModuleDefinition Module { get { return ReturnType.Module; } } public override IMetadataScope Scope { get { return function.ReturnType.Scope; } } public override bool IsFunctionPointer { get { return true; } } internal override bool ContainsGenericParameter { get { return function.ContainsGenericParameter; } } public override string FullName { get { var signature = new StringBuilder (); signature.Append (function.Name); signature.Append (" "); signature.Append (function.ReturnType.FullName); signature.Append (" *"); this.MethodSignatureFullName (signature); return signature.ToString (); } } public FunctionPointerType () : base (null) { this.function = new MethodReference (); this.function.Name = "method"; this.etype = MD.ElementType.FnPtr; } } }
// // FunctionPointerType.cs // // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using Mono.Collections.Generic; using MD = Mono.Cecil.Metadata; namespace Mono.Cecil { public sealed class FunctionPointerType : TypeSpecification, IMethodSignature { readonly MethodReference function; public bool HasThis { get { return function.HasThis; } set { function.HasThis = value; } } public bool ExplicitThis { get { return function.ExplicitThis; } set { function.ExplicitThis = value; } } public MethodCallingConvention CallingConvention { get { return function.CallingConvention; } set { function.CallingConvention = value; } } public bool HasParameters { get { return function.HasParameters; } } public Collection<ParameterDefinition> Parameters { get { return function.Parameters; } } public TypeReference ReturnType { get { return function.MethodReturnType.ReturnType; } set { function.MethodReturnType.ReturnType = value; } } public MethodReturnType MethodReturnType { get { return function.MethodReturnType; } } public override string Name { get { return function.Name; } set { throw new InvalidOperationException (); } } public override string Namespace { get { return string.Empty; } set { throw new InvalidOperationException (); } } public override ModuleDefinition Module { get { return ReturnType.Module; } } public override IMetadataScope Scope { get { return function.ReturnType.Scope; } } public override bool IsFunctionPointer { get { return true; } } public override string FullName { get { var signature = new StringBuilder (); signature.Append (function.Name); signature.Append (" "); signature.Append (function.ReturnType.FullName); signature.Append (" *"); this.MethodSignatureFullName (signature); return signature.ToString (); } } public FunctionPointerType () : base (null) { this.function = new MethodReference (); this.function.Name = "method"; this.etype = MD.ElementType.FnPtr; } } }
mit
C#
60325f8246841051663c4aca69dc69df0cfbb263
Fix NRE
nikeee/HolzShots
src/HolzShots.Core/Composition/IUploaderSource.cs
src/HolzShots.Core/Composition/IUploaderSource.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using HolzShots.Net; namespace HolzShots.Composition { public interface IUploaderSource { bool Loaded { get; } UploaderEntry/*?*/ GetUploaderByName(string name); IReadOnlyList<string> GetUploaderNames(); IReadOnlyList<IPluginMetadata> GetMetadata(); Task Load(); } public class UploaderEntry : IEquatable<UploaderEntry> { public IPluginMetadata Metadata { get; } public Uploader Uploader { get; } public UploaderEntry(IPluginMetadata metadata, Uploader uploader) { Metadata = metadata ?? throw new ArgumentNullException(nameof(IPluginMetadata)); Uploader = uploader ?? throw new ArgumentNullException(nameof(uploader)); } public override int GetHashCode() => HashCode.Combine(Metadata, Uploader); public static bool operator ==(UploaderEntry left, UploaderEntry right) => left is null ? right is null : left.Equals(right); public static bool operator !=(UploaderEntry left, UploaderEntry right) => !(left == right); public override bool Equals(object obj) => obj is UploaderEntry other && Equals(other); public bool Equals(UploaderEntry /* ? */ other) => !(other is null) && other.Metadata.Equals(Metadata) && other.Uploader.Equals(Uploader); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using HolzShots.Net; namespace HolzShots.Composition { public interface IUploaderSource { bool Loaded { get; } UploaderEntry/*?*/ GetUploaderByName(string name); IReadOnlyList<string> GetUploaderNames(); IReadOnlyList<IPluginMetadata> GetMetadata(); Task Load(); } public class UploaderEntry : IEquatable<UploaderEntry> { public IPluginMetadata Metadata { get; } public Uploader Uploader { get; } public UploaderEntry(IPluginMetadata metadata, Uploader uploader) { Metadata = metadata ?? throw new ArgumentNullException(nameof(IPluginMetadata)); Uploader = uploader ?? throw new ArgumentNullException(nameof(uploader)); } public override int GetHashCode() => HashCode.Combine(Metadata, Uploader); public static bool operator ==(UploaderEntry left, UploaderEntry right) => left.Equals(right); public static bool operator !=(UploaderEntry left, UploaderEntry right) => !(left == right); public override bool Equals(object obj) => obj is UploaderEntry other && Equals(other); public bool Equals(UploaderEntry other) => other.Metadata.Equals(Metadata) && other.Uploader.Equals(Uploader); } }
agpl-3.0
C#
a0e2656a45661061acd0c96b6d21aa618b6314f0
FIX typos in VS vocabulary
mdesalvo/RDFSharp
RDFSharp/Model/Vocabularies/VS.cs
RDFSharp/Model/Vocabularies/VS.cs
/* Copyright 2012-2020 Marco De Salvo Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace RDFSharp.Model { /// <summary> /// RDFVocabulary is an helper for handy usage of supported RDF vocabularies. /// </summary> public static partial class RDFVocabulary { #region VS /// <summary> /// VS represents the Vocabulary-Status vocabulary. /// </summary> public static class VS { #region Properties /// <summary> /// vs /// </summary> public static readonly string PREFIX = "vs"; /// <summary> /// http://www.w3.org/2003/06/sw-vocab-status/ns# /// </summary> public static readonly string BASE_URI = "http://www.w3.org/2003/06/sw-vocab-status/ns#"; /// <summary> /// http://www.w3.org/2003/06/sw-vocab-status/ns# /// </summary> public static readonly string DEREFERENCE_URI = "http://www.w3.org/2003/06/sw-vocab-status/ns#"; /// <summary> /// vs:term_status /// </summary> public static readonly RDFResource TERM_STATUS = new RDFResource(VS.BASE_URI + "term_status"); /// <summary> /// vs:stable /// </summary> public static readonly RDFResource STABLE = new RDFResource(VS.BASE_URI + "stable"); /// <summary> /// vs:testing /// </summary> public static readonly RDFResource TESTING = new RDFResource(VS.BASE_URI + "testing"); /// <summary> /// vs:unstable /// </summary> public static readonly RDFResource UNSTABLE = new RDFResource(VS.BASE_URI + "unstable"); #endregion } #endregion } }
/* Copyright 2012-2020 Marco De Salvo Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace RDFSharp.Model { /// <summary> /// RDFVocabulary is an helper for handy usage of supported RDF vocabularies. /// </summary> public static partial class RDFVocabulary { #region VS /// <summary> /// VS represents the Vocabulary-Status vocabulary. /// </summary> public static class VS { #region Properties /// <summary> /// vs /// </summary> public static readonly string PREFIX = "vs"; /// <summary> /// http://www.w3.org/2003/06/sw-vocab-status/ns# /// </summary> public static readonly string BASE_URI = "http://www.w3.org/2003/06/sw-vocab-status/ns#"; /// <summary> /// http://www.w3.org/2003/06/sw-vocab-status/ns# /// </summary> public static readonly string DEREFERENCE_URI = "http://www.w3.org/2003/06/sw-vocab-status/ns#"; /// <summary> /// vs:term_status /// </summary> public static readonly RDFResource TERM_STATUS = new RDFResource(XML.BASE_URI + "term_status"); /// <summary> /// vs:stable /// </summary> public static readonly RDFResource STABLE = new RDFResource(XML.BASE_URI + "stable"); /// <summary> /// vs:testing /// </summary> public static readonly RDFResource TESTING = new RDFResource(XML.BASE_URI + "testing"); /// <summary> /// vs:unstable /// </summary> public static readonly RDFResource UNSTABLE = new RDFResource(XML.BASE_URI + "unstable"); #endregion } #endregion } }
apache-2.0
C#
41d7866b0613a3a3c5adf6e7ba5df4e0476c5558
bump version
raml-org/raml-dotnet-parser-2,raml-org/raml-dotnet-parser-2
source/Raml.Parser/Properties/AssemblyInfo.cs
source/Raml.Parser/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("RAML.Parser")] [assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mulesoft Inc")] [assembly: AssemblyProduct("Raml.Parser")] [assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")] [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("d5f8e5f6-634a-4487-be70-591c4d8546f2")] // 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.3")]
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("RAML.Parser")] [assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mulesoft Inc")] [assembly: AssemblyProduct("Raml.Parser")] [assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")] [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("d5f8e5f6-634a-4487-be70-591c4d8546f2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2")]
apache-2.0
C#
ac9c951d4c4bee7032a42a1d4ff8cadba96f4fd3
fix the To type check for admin initiated message
intercom/intercom-dotnet
src/Intercom/Data/AdminConversationMessage.cs
src/Intercom/Data/AdminConversationMessage.cs
using System; using Intercom.Core; using Intercom.Data; using Intercom.Clients; using Intercom.Exceptions; namespace Intercom.Data { public class AdminConversationMessage : Message { public class From { public String id { set; get; } public String type { private set; get; } public From(String id) { if(String.IsNullOrEmpty(id)) throw new ArgumentNullException (nameof(id)); this.id = id; this.type = Message.MessageFromOrToType.ADMIN; } } public class To { public String id { set; get; } public String email { set; get; } public String user_id { set; get; } public String type { set; get; } public To(String type = Message.MessageFromOrToType.USER, String id = null, String email = null, String user_id = null) { if(String.IsNullOrEmpty(type)) throw new ArgumentNullException (nameof(type)); if(String.IsNullOrEmpty(id) && String.IsNullOrEmpty(email) && String.IsNullOrEmpty(user_id)) throw new ArgumentException ("you need to provide either 'id', 'user_id', 'email' to view a user."); if(type != Message.MessageFromOrToType.USER && type != Message.MessageFromOrToType.CONTACT) throw new ArgumentException ("'type' vale must be either 'contact' or 'user'."); this.id = id; this.email = email; this.user_id = user_id; this.type = type; } } public string message_type { get; set; } public string subject { get; set; } public string template { get; set; } public From from { get; set; } public To to { get; set; } public AdminConversationMessage ( AdminConversationMessage.From from, AdminConversationMessage.To to, String message_type = Message.MessageType.EMAIL, String template = Message.MessageTemplate.PLAIN, String subject = "", String body = "") { this.to = to; this.from = from; this.message_type = message_type; this.template = template; this.subject = subject; this.body = body; } } }
using System; using Intercom.Core; using Intercom.Data; using Intercom.Clients; using Intercom.Exceptions; namespace Intercom.Data { public class AdminConversationMessage : Message { public class From { public String id { set; get; } public String type { private set; get; } public From(String id) { if(String.IsNullOrEmpty(id)) throw new ArgumentNullException (nameof(id)); this.id = id; this.type = Message.MessageFromOrToType.ADMIN; } } public class To { public String id { set; get; } public String email { set; get; } public String user_id { set; get; } public String type { set; get; } public To(String type = Message.MessageFromOrToType.USER, String id = null, String email = null, String user_id = null) { if(String.IsNullOrEmpty(type)) throw new ArgumentNullException (nameof(type)); if(String.IsNullOrEmpty(id) && String.IsNullOrEmpty(email) && String.IsNullOrEmpty(user_id)) throw new ArgumentException ("you need to provide either 'id', 'user_id', 'email' to view a user."); if(type != Message.MessageFromOrToType.USER && type != Message.MessageFromOrToType.ADMIN) throw new ArgumentException ("'type' vale must be either 'contact' or 'user'."); this.id = id; this.email = email; this.user_id = user_id; this.type = type; } } public string message_type { get; set; } public string subject { get; set; } public string template { get; set; } public From from { get; set; } public To to { get; set; } public AdminConversationMessage ( AdminConversationMessage.From from, AdminConversationMessage.To to, String message_type = Message.MessageType.EMAIL, String template = Message.MessageTemplate.PLAIN, String subject = "", String body = "") { this.to = to; this.from = from; this.message_type = message_type; this.template = template; this.subject = subject; this.body = body; } } }
apache-2.0
C#
066ceb41f5e1a0eb5b5d165b76fbab1d372fcc13
Add homepage CTAs
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
src/LondonTravel.Site/Views/Home/Index.cshtml
src/LondonTravel.Site/Views/Home/Index.cshtml
@inject SiteOptions Options @{ ViewBag.Title = "Home"; } <div class="jumbotron"> <h1>London Travel</h1> <p class="lead"> An Amazon Alexa skill for checking the status of travel in London. </p> <p> <a class="btn btn-primary btn-lg" href="@Options?.ExternalLinks?.Skill" rel="noopener" target="_blank" title="Install London Travel for Amazon Alexa from amazon.co.uk">Install <i class="fa fa-external-link" aria-hidden="true"></i></a> @if (!User.Identity.IsAuthenticated) { <a class="btn btn-primary btn-lg" asp-route="Register" title="Register for a London Travel account">Register <i class="fa fa-user-plus" aria-hidden="true"></i></a> <a class="btn btn-primary btn-lg" asp-route="SignIn" title="Sign in to your London Travel account">Sign In <i class="fa fa-sign-in" aria-hidden="true"></i></a> } </p> </div>
@inject SiteOptions Options @{ ViewBag.Title = "Home"; } <div class="jumbotron"> <h1>London Travel</h1> <p class="lead"> An Amazon Alexa skill for checking the status of travel in London. </p> <p> <a class="btn btn-primary" id="link-install" href="@Options?.ExternalLinks?.Skill" rel="noopener" target="_blank" title="Install London Travel for Amazon Alexa from amazon.co.uk">Install <i class="fa fa-external-link" aria-hidden="true"></i></a> </p> </div>
apache-2.0
C#
34470a847ac44dfe6fcbcaf2d0388bbe9f529ddb
Test RelabelingFunction
lou1306/CIV,lou1306/CIV
CIV.Test/RelabelingFunctionTest.cs
CIV.Test/RelabelingFunctionTest.cs
using Xunit; using System; using CIV.Ccs; namespace CIV.Test { public class RelabelingFunctionTest { [Theory] [InlineData("action", "relabeled")] [InlineData("action", "tau")] public void ShouldRelabelCoaction(string action, string relabeled) { var relabeling = new RelabelingFunction { {action, relabeled} }; Assert.Equal(2, relabeling.Count); Assert.Equal(relabeled, relabeling[action]); Assert.Equal(relabeled.Coaction(), relabeling[action.Coaction()]); } [Fact] public void ShouldNotRelabelTau() { var relabeling = new RelabelingFunction(); Assert.Throws<ArgumentException>( () => { relabeling.Add("tau", "relabeled"); }); } } }
using Xunit; using CIV.Ccs; namespace CIV.Test { public class RelabelingFunctionTest { [Fact] public void ShouldAddInputAction() { var relabeling = new RelabelingFunction { {"action", "relabeled"} }; Assert.Equal(1, relabeling.Count); Assert.Equal("relabeled", relabeling["action"]); } } }
mit
C#
8029d9c55772414509a09d3926dd430a70903489
Make IConsulClient public
PlayFab/consuldotnet,yonglehou/consuldotnet,highlyunavailable/consuldotnet
Consul/Interfaces/IConsulClient.cs
Consul/Interfaces/IConsulClient.cs
using System; using System.Threading; namespace Consul { public interface IConsulClient { IACLEndpoint ACL { get; } IDisposableLock AcquireLock(LockOptions opts); IDisposableLock AcquireLock(LockOptions opts, CancellationToken ct); IDisposableLock AcquireLock(string key); IDisposableLock AcquireLock(string key, CancellationToken ct); IDisposableSemaphore AcquireSemaphore(SemaphoreOptions opts); IDisposableSemaphore AcquireSemaphore(string prefix, int limit); IAgentEndpoint Agent { get; } ICatalogEndpoint Catalog { get; } IDistributedLock CreateLock(LockOptions opts); IDistributedLock CreateLock(string key); IEventEndpoint Event { get; } void ExecuteAbortableLocked(LockOptions opts, Action action); void ExecuteAbortableLocked(LockOptions opts, CancellationToken ct, Action action); void ExecuteAbortableLocked(string key, Action action); void ExecuteAbortableLocked(string key, CancellationToken ct, Action action); void ExecuteInSemaphore(SemaphoreOptions opts, Action a); void ExecuteInSemaphore(string prefix, int limit, Action a); void ExecuteLocked(LockOptions opts, Action action); void ExecuteLocked(LockOptions opts, CancellationToken ct, Action action); void ExecuteLocked(string key, Action action); void ExecuteLocked(string key, CancellationToken ct, Action action); IHealthEndpoint Health { get; } IKVEndpoint KV { get; } IRawEndpoint Raw { get; } IDistributedSemaphore Semaphore(SemaphoreOptions opts); IDistributedSemaphore Semaphore(string prefix, int limit); ISessionEndpoint Session { get; } IStatusEndpoint Status { get; } } }
using System; using System.Threading; namespace Consul { interface IConsulClient { IACLEndpoint ACL { get; } IDisposableLock AcquireLock(LockOptions opts); IDisposableLock AcquireLock(LockOptions opts, CancellationToken ct); IDisposableLock AcquireLock(string key); IDisposableLock AcquireLock(string key, CancellationToken ct); IDisposableSemaphore AcquireSemaphore(SemaphoreOptions opts); IDisposableSemaphore AcquireSemaphore(string prefix, int limit); IAgentEndpoint Agent { get; } ICatalogEndpoint Catalog { get; } IDistributedLock CreateLock(LockOptions opts); IDistributedLock CreateLock(string key); IEventEndpoint Event { get; } void ExecuteAbortableLocked(LockOptions opts, Action action); void ExecuteAbortableLocked(LockOptions opts, CancellationToken ct, Action action); void ExecuteAbortableLocked(string key, Action action); void ExecuteAbortableLocked(string key, CancellationToken ct, Action action); void ExecuteInSemaphore(SemaphoreOptions opts, Action a); void ExecuteInSemaphore(string prefix, int limit, Action a); void ExecuteLocked(LockOptions opts, Action action); void ExecuteLocked(LockOptions opts, CancellationToken ct, Action action); void ExecuteLocked(string key, Action action); void ExecuteLocked(string key, CancellationToken ct, Action action); IHealthEndpoint Health { get; } IKVEndpoint KV { get; } IRawEndpoint Raw { get; } IDistributedSemaphore Semaphore(SemaphoreOptions opts); IDistributedSemaphore Semaphore(string prefix, int limit); ISessionEndpoint Session { get; } IStatusEndpoint Status { get; } } }
apache-2.0
C#
518a785a86710d437f73a66126cea8763f44e43e
Use multiples of 10.
csjune/mathnet-spatial,csjune/mathnet-spatial,csjune/mathnet-spatial
src/Spatial.Benchmarks/Polygon2DBenchmarks.cs
src/Spatial.Benchmarks/Polygon2DBenchmarks.cs
namespace Spatial.Benchmarks { using System; using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Attributes; using MathNet.Spatial.Euclidean; public class Polygon2DBenchmarks { private static readonly Random Random = new Random(); private static readonly IReadOnlyList<Point2D> Point2D10 = Enumerable.Repeat(0, 10).Select(_ => new Point2D(Random.Next(), Random.Next())).ToList(); private static readonly IReadOnlyList<Point2D> Point2D100 = Enumerable.Repeat(0, 100).Select(_ => new Point2D(Random.Next(), Random.Next())).ToList(); private static readonly IReadOnlyList<Point2D> Point2D1000 = Enumerable.Repeat(0, 1000).Select(_ => new Point2D(Random.Next(), Random.Next())).ToList(); private static readonly IReadOnlyList<Point2D> Point2D10000 = Enumerable.Repeat(0, 10000).Select(_ => new Point2D(Random.Next(), Random.Next())).ToList(); [Benchmark] public Polygon2D GetConvexHullFromPoints10() { return Polygon2D.GetConvexHullFromPoints(Point2D10); } [Benchmark] public Polygon2D GetConvexHullFromPoints100() { return Polygon2D.GetConvexHullFromPoints(Point2D100); } [Benchmark] public Polygon2D GetConvexHullFromPoints1000() { return Polygon2D.GetConvexHullFromPoints(Point2D1000); } [Benchmark] public Polygon2D GetConvexHullFromPoints10000() { return Polygon2D.GetConvexHullFromPoints(Point2D10000); } } }
namespace Spatial.Benchmarks { using System; using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Attributes; using MathNet.Spatial.Euclidean; public class Polygon2DBenchmarks { private static readonly Random Random = new Random(); private static readonly IReadOnlyList<Point2D> Point2D50 = Enumerable.Repeat(0, 50).Select(_ => new Point2D(Random.Next(), Random.Next())).ToList(); private static readonly IReadOnlyList<Point2D> Point2D500 = Enumerable.Repeat(0, 500).Select(_ => new Point2D(Random.Next(), Random.Next())).ToList(); private static readonly IReadOnlyList<Point2D> Point2D5000 = Enumerable.Repeat(0, 500).Select(_ => new Point2D(Random.Next(), Random.Next())).ToList(); [Benchmark] public Polygon2D GetConvexHullFromPoints50() { return Polygon2D.GetConvexHullFromPoints(Point2D50); } [Benchmark] public Polygon2D GetConvexHullFromPoints500() { return Polygon2D.GetConvexHullFromPoints(Point2D500); } [Benchmark] public Polygon2D GetConvexHullFromPoints5000() { return Polygon2D.GetConvexHullFromPoints(Point2D5000); } } }
mit
C#
343b0e5a87a2b6b7251c64599b51231481d0f1a3
Fix bug in TimeSlot.Overlaps
victoria92/university-program-generator,victoria92/university-program-generator
UniProgramGen/Helpers/TimeSlot.cs
UniProgramGen/Helpers/TimeSlot.cs
using System; using System.Collections.Generic; namespace UniProgramGen.Helpers { public class TimeSlot { public const uint START_HOUR = 7; public const uint END_HOUR = 22; public const uint TOTAL_DAY_HOURS = END_HOUR - START_HOUR; public TimeSlot(DayOfWeek day, uint startHour, uint endHour) { validateHour(startHour); validateHour(endHour); if (startHour >= endHour) { throw new ArgumentException("Start hour has to be before end hour"); } Day = day; StartHour = startHour; EndHour = endHour; } public uint Duration() { return EndHour - StartHour; } public bool Overlaps(TimeSlot other) { return other.Day == Day && ((other.StartHour >= StartHour && other.StartHour < EndHour) || (other.EndHour > StartHour && other.EndHour <= EndHour)); } public bool Includes(TimeSlot other) { return other.Day == Day && other.StartHour >= StartHour && other.EndHour <= EndHour; } public DayOfWeek Day { get; private set; } public uint StartHour { get; private set; } public uint EndHour { get; private set; } private static void validateHour(uint hour) { if (hour < START_HOUR || hour > END_HOUR) { throw new ArgumentOutOfRangeException("Hour outside of working hours"); } } internal IEnumerable<TimeSlot> GetAllWindows(uint duration) { for (uint i = StartHour; i <= EndHour - duration; i++) { yield return new TimeSlot(Day, i, i + duration); } } } }
using System; using System.Collections.Generic; namespace UniProgramGen.Helpers { public class TimeSlot { public const uint START_HOUR = 7; public const uint END_HOUR = 22; public const uint TOTAL_DAY_HOURS = END_HOUR - START_HOUR; public TimeSlot(DayOfWeek day, uint startHour, uint endHour) { validateHour(startHour); validateHour(endHour); if (startHour >= endHour) { throw new ArgumentException("Start hour has to be before end hour"); } Day = day; StartHour = startHour; EndHour = endHour; } public uint Duration() { return EndHour - StartHour; } public bool Overlaps(TimeSlot other) { return other.Day == Day && (inSlot(other.StartHour) || inSlot(other.EndHour)); } public bool Includes(TimeSlot other) { return other.Day == Day && other.StartHour >= StartHour && other.EndHour <= EndHour; } public DayOfWeek Day { get; private set; } public uint StartHour { get; private set; } public uint EndHour { get; private set; } private static void validateHour(uint hour) { if (hour < START_HOUR || hour > END_HOUR) { throw new ArgumentOutOfRangeException("Hour outside of working hours"); } } private bool inSlot(uint hour) { return hour > StartHour && hour < EndHour; } internal IEnumerable<TimeSlot> GetAllWindows(uint duration) { for (uint i = StartHour; i <= EndHour - duration; i++) { yield return new TimeSlot(Day, i, i + duration); } } } }
bsd-2-clause
C#
33bfe235db5b73abbdaf401b870a882c010136f1
fix .NET compatibility
ophilbinbriscoe/BoldTween
Interpolators/AlphaInterpolator.cs
Interpolators/AlphaInterpolator.cs
using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; namespace BoldTween { [RequireComponent( typeof( CanvasGroup ) )] public class AlphaInterpolator : Interpolator { [System.Serializable] private class AlphaEvent : UnityEvent<Color> { } [SerializeField] [Range( 0.0f, 1.0f )] private float a = 0.0f, b = 1.0f; public float A { get { return a; } set { a = Mathf.Clamp01( value ); } } public float B { get { return b; } set { b = Mathf.Clamp01( value ); } } [SerializeField] private AlphaEvent targets; protected override void OnInterpolate ( float t ) { float alpha = a + (b - a) * t; int persistentEventCount = targets.GetPersistentEventCount(); for (int i = 0; i < persistentEventCount; i++) { var target = targets.GetPersistentTarget( i ); var name = targets.GetPersistentMethodName( i ); if ( name.StartsWith( "set_" ) ) { name = name.Substring( 4, name.Length - 4 ); var field = target.GetType().GetField( name ); if ( field != null ) { if ( field.FieldType == typeof( Color ) ) { var color = (Color) field.GetValue( target ); color.a = alpha; field.SetValue( target, color ); } else if ( field.FieldType == typeof( Color32 ) ) { var color = (Color32) field.GetValue( target ); color.a = (byte) Mathf.RoundToInt( 255 * alpha ); field.SetValue( target, color ); } } else { var property = target.GetType().GetProperty( name ); if ( property != null ) { if ( property.PropertyType == typeof( Color ) ) { var color = (Color) property.GetValue( target, null ); color.a = alpha; property.SetValue( target, color, null ); } else if ( property.PropertyType == typeof( Color32 ) ) { var color = (Color32) property.GetValue( target, null ); color.a = (byte) Mathf.RoundToInt( 255 * alpha ); property.SetValue( target, color, null ); } } } } } } } }
using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; namespace BoldTween { [RequireComponent( typeof( CanvasGroup ) )] public class AlphaInterpolator : Interpolator { [System.Serializable] private class AlphaEvent : UnityEvent<Color> { } [SerializeField] [Range( 0.0f, 1.0f )] private float a = 0.0f, b = 1.0f; public float A { get { return a; } set { a = Mathf.Clamp01( value ); } } public float B { get { return b; } set { b = Mathf.Clamp01( value ); } } [SerializeField] private AlphaEvent targets; protected override void OnInterpolate ( float t ) { float alpha = a + (b - a) * t; int persistentEventCount = targets.GetPersistentEventCount(); for (int i = 0; i < persistentEventCount; i++) { var target = targets.GetPersistentTarget( i ); var name = targets.GetPersistentMethodName( i ); if ( name.StartsWith( "set_" ) ) { name = name.Substring( 4, name.Length - 4 ); var field = target.GetType().GetField( name ); if ( field != null ) { if ( field.FieldType == typeof( Color ) ) { var color = (Color) field.GetValue( target ); color.a = alpha; field.SetValue( target, color ); } else if ( field.FieldType == typeof( Color32 ) ) { var color = (Color32) field.GetValue( target ); color.a = (byte) Mathf.RoundToInt( 255 * alpha ); field.SetValue( target, color ); } } else { var property = target.GetType().GetProperty( name ); if ( property != null ) { if ( property.PropertyType == typeof( Color ) ) { var color = (Color) property.GetValue( target ); color.a = alpha; property.SetValue( target, color ); } else if ( property.PropertyType == typeof( Color32 ) ) { var color = (Color32) property.GetValue( target ); color.a = (byte) Mathf.RoundToInt( 255 * alpha ); property.SetValue( target, color ); } } } } } } } }
mit
C#