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
e5c0b8168763adc0d98fdc7883a4711a32a6e372
Allow noop on text fields
kool79/Bumblebee,chrisblock/Bumblebee,chrisblock/Bumblebee,Bumblebee/Bumblebee,qchicoq/Bumblebee,kool79/Bumblebee,qchicoq/Bumblebee,toddmeinershagen/Bumblebee,toddmeinershagen/Bumblebee,Bumblebee/Bumblebee
Bumblebee/Interfaces/ITextField.cs
Bumblebee/Interfaces/ITextField.cs
namespace Bumblebee.Interfaces { public interface ITextField : IElement, IHasText { TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock; TCustomResult AppendText<TCustomResult>(string text) where TCustomResult : IBlock; } public interface ITextField<out TResult> : ITextField, IAllowsNoOp<TResult> where TResult : IBlock { TResult EnterText(string text); TResult AppendText(string text); } }
namespace Bumblebee.Interfaces { public interface ITextField : IElement, IHasText { TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock; TCustomResult AppendText<TCustomResult>(string text) where TCustomResult : IBlock; } public interface ITextField<out TResult> : ITextField, IGenericElement<TResult> where TResult : IBlock { TResult EnterText(string text); TResult AppendText(string text); } }
mit
C#
22ab6a625534c0c7c5fad205758f51bf5467e86b
Fix AndWe formatting issue
KernowCode/UBADDAS
KernowCode.KTest.Ubaddas/BehaviourExtensions.cs
KernowCode.KTest.Ubaddas/BehaviourExtensions.cs
using System; using System.Reflection; namespace KernowCode.KTest.Ubaddas { /// <summary> /// Provides BDD statement extensions including 'As' and 'And' /// </summary> public static class BehaviourExtensions { /// <summary> /// <para>Specifies the Persona to perform the following BDD statements as</para> /// </summary> /// <typeparam name="T">BDD Tense (Given,When,Then) (supplied automatically)</typeparam> /// <param name="behaviour">Current behaviour instance (supplied automatically)</param> /// <param name="persona">An instance of your personas that implements the IPersona interface</param> /// <returns>Current BDD Tense (Given, When, or Then)</returns> public static T As<T>(this T behaviour, IPersona persona) where T : IAs { behaviour.GetType().GetMethod("As", BindingFlags.NonPublic | BindingFlags.Instance).Invoke( behaviour, new object[] { persona }); return behaviour; } /// <summary> /// Allows another implementation of the current BDD tense (given, when or then) /// </summary> /// <typeparam name="T">BDD Tense (Given,When,Then) (supplied automatically)</typeparam> /// <param name="behaviour">Current behaviour instance (supplied automatically)</param> /// <param name="domainEntityCommand">The entitiy interface command method (without executing parenthesis)</param> /// <returns>Current BDD Tense (Given, When, or Then)</returns> public static T And<T>(this T behaviour, Action domainEntityCommand) where T : ITense { behaviour.GetType().GetMethod("DoBehaviour", BindingFlags.NonPublic | BindingFlags.Instance).Invoke( behaviour, new object[] { "and", domainEntityCommand }); return behaviour; } /// <summary> /// Allows another implementation of the current BDD tense (given, when or then) /// </summary> /// <typeparam name="T">BDD Tense (Given,When,Then) (supplied automatically)</typeparam> /// <param name="behaviour">Current behaviour instance (supplied automatically)</param> /// <param name="actionDelegate">A delegate containing a call to a method that will execute another set of behaviours. Specify 'ISet behaviour' as the first parameter of your method and use behaviour to perform another Given,When,Then</param> /// <returns>Current BDD Tense (Given, When, or Then)</returns> public static T AndWe<T>(this T behaviour, Action<ISet> actionDelegate) where T : ITense { behaviour.GetType().GetMethod("DoBehaviourSet", BindingFlags.NonPublic | BindingFlags.Instance).Invoke( behaviour, new object[] { "and we", actionDelegate }); return behaviour; } } }
using System; using System.Reflection; namespace KernowCode.KTest.Ubaddas { /// <summary> /// Provides BDD statement extensions including 'As' and 'And' /// </summary> public static class BehaviourExtensions { /// <summary> /// <para>Specifies the Persona to perform the following BDD statements as</para> /// </summary> /// <typeparam name="T">BDD Tense (Given,When,Then) (supplied automatically)</typeparam> /// <param name="behaviour">Current behaviour instance (supplied automatically)</param> /// <param name="persona">An instance of your personas that implements the IPersona interface</param> /// <returns>Current BDD Tense (Given, When, or Then)</returns> public static T As<T>(this T behaviour, IPersona persona) where T : IAs { behaviour.GetType().GetMethod("As", BindingFlags.NonPublic | BindingFlags.Instance).Invoke( behaviour, new object[] { persona }); return behaviour; } /// <summary> /// Allows another implementation of the current BDD tense (given, when or then) /// </summary> /// <typeparam name="T">BDD Tense (Given,When,Then) (supplied automatically)</typeparam> /// <param name="behaviour">Current behaviour instance (supplied automatically)</param> /// <param name="domainEntityCommand">The entitiy interface command method (without executing parenthesis)</param> /// <returns>Current BDD Tense (Given, When, or Then)</returns> public static T And<T>(this T behaviour, Action domainEntityCommand) where T : ITense { behaviour.GetType().GetMethod("DoBehaviour", BindingFlags.NonPublic | BindingFlags.Instance).Invoke( behaviour, new object[] { "and", domainEntityCommand }); return behaviour; } /// <summary> /// Allows another implementation of the current BDD tense (given, when or then) /// </summary> /// <typeparam name="T">BDD Tense (Given,When,Then) (supplied automatically)</typeparam> /// <param name="behaviour">Current behaviour instance (supplied automatically)</param> /// <param name="actionDelegate">A delegate containing a call to a method that will execute another set of behaviours. Specify 'ISet behaviour' as the first parameter of your method and use behaviour to perform another Given,When,Then</param> /// <returns>Current BDD Tense (Given, When, or Then)</returns> public static T AndWe<T>(this T behaviour, Action<ISet> actionDelegate) where T : ITense { behaviour.GetType().GetMethod("DoBehaviourSet", BindingFlags.NonPublic | BindingFlags.Instance).Invoke( behaviour, new object[] { "and", actionDelegate }); return behaviour; } } }
mit
C#
b1a5cd8dea6f0403aecf4a49ad8dd0f2978e38f2
update to v5
modernist/APIComparer,modernist/APIComparer,ParticularLabs/APIComparer,ParticularLabs/APIComparer
APIComparer/Program.cs
APIComparer/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using APIComparer; using NuGet; class Program { static void Main() { var nugetCacheDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Cache"); var repo = new AggregateRepository(new[] { PackageRepositoryFactory.Default.CreateRepository(nugetCacheDirectory), PackageRepositoryFactory.Default.CreateRepository("https://www.nuget.org/api/v2"), PackageRepositoryFactory.Default.CreateRepository("https://www.myget.org/F/particular/"), }); var packageManager = new PackageManager(repo, "packages"); var newVersion = "5.0.0"; packageManager.InstallPackage("NServiceBus", SemanticVersion.Parse(newVersion)); packageManager.InstallPackage("NServiceBus.Host", SemanticVersion.Parse(newVersion)); packageManager.InstallPackage("NServiceBus.Interfaces", SemanticVersion.Parse("4.6.6")); packageManager.InstallPackage("NServiceBus", SemanticVersion.Parse("4.6.6")); packageManager.InstallPackage("NServiceBus.Host", SemanticVersion.Parse("4.6.6")); var leftAssemblyGroup = new List<string> { Path.Combine("packages", "NServiceBus.4.6.6", "lib", "net40", "NServiceBus.Core.dll"), Path.Combine("packages", "NServiceBus.Interfaces.4.6.6", "lib", "net40", "NServiceBus.dll"), Path.Combine("packages", "NServiceBus.Host.4.6.6", "lib", "net40", "NServiceBus.Host.exe") }; var rightAssemblyGroup = new List<string> { Path.Combine("packages", "NServiceBus." + newVersion, "lib", "net45", "NServiceBus.Core.dll"), Path.Combine("packages", "NServiceBus.Host." + newVersion, "lib", "net45", "NServiceBus.Host.exe"), }; var engine = new ComparerEngine(); var diff = engine.CreateDiff(leftAssemblyGroup, rightAssemblyGroup); var stringBuilder = new StringBuilder(); var formatter = new APIUpgradeToMarkdownFormatter(stringBuilder, "https://github.com/Particular/NServiceBus/blob/4.6.6/", "https://github.com/Particular/NServiceBus/tree/master/"); formatter.WriteOut(diff); File.WriteAllText("Result.md", stringBuilder.ToString()); } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using APIComparer; using NuGet; class Program { static void Main() { var nugetCacheDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Cache"); var repo = new AggregateRepository(new[] { PackageRepositoryFactory.Default.CreateRepository(nugetCacheDirectory), PackageRepositoryFactory.Default.CreateRepository("https://www.nuget.org/api/v2"), PackageRepositoryFactory.Default.CreateRepository("https://www.myget.org/F/particular/"), }); var packageManager = new PackageManager(repo, "packages"); var newVersion = "5.0.0-beta0004"; //packageManager.InstallPackage("NServiceBus", SemanticVersion.Parse(newVersion)); //packageManager.InstallPackage("NServiceBus.Host", SemanticVersion.Parse(newVersion)); //packageManager.InstallPackage("NServiceBus.Interfaces", SemanticVersion.Parse("4.6.4")); //packageManager.InstallPackage("NServiceBus", SemanticVersion.Parse("4.6.4")); //packageManager.InstallPackage("NServiceBus.Host", SemanticVersion.Parse("4.6.4")); var leftAssemblyGroup = new List<string> { Path.Combine("packages", "NServiceBus.4.6.4", "lib", "net40", "NServiceBus.Core.dll"), Path.Combine("packages", "NServiceBus.Interfaces.4.6.4", "lib", "net40", "NServiceBus.dll"), Path.Combine("packages", "NServiceBus.Host.4.6.4", "lib", "net40", "NServiceBus.Host.exe") }; var rightAssemblyGroup = new List<string> { Path.Combine("packages", "NServiceBus." + newVersion, "lib", "net45", "NServiceBus.Core.dll"), Path.Combine("packages", "NServiceBus.Host." + newVersion, "lib", "net45", "NServiceBus.Host.exe"), }; var engine = new ComparerEngine(); var diff = engine.CreateDiff(leftAssemblyGroup, rightAssemblyGroup); var stringBuilder = new StringBuilder(); var formatter = new APIUpgradeToMarkdownFormatter(stringBuilder, "https://github.com/Particular/NServiceBus/blob/4.6.4/", "https://github.com/Particular/NServiceBus/blob/5.0.0-beta4/"); formatter.WriteOut(diff); File.WriteAllText("Result.md", stringBuilder.ToString()); } }
mit
C#
4f1db5af40c79e038737eef75ab6859641b12fa4
Attach migration memo to `DatabasedSetting` class for visibility
NeoAdonis/osu,peppy/osu,ppy/osu,smoogipooo/osu,peppy/osu,peppy/osu-new,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu
osu.Game/Configuration/DatabasedSetting.cs
osu.Game/Configuration/DatabasedSetting.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel.DataAnnotations.Schema; using osu.Game.Database; namespace osu.Game.Configuration { [Table("Settings")] public class DatabasedSetting : IHasPrimaryKey // can be removed 20220315. { public int ID { get; set; } public int? RulesetID { get; set; } public int? Variant { get; set; } public int? SkinInfoID { get; set; } [Column("Key")] public string Key { get; set; } [Column("Value")] public string StringValue { get => Value.ToString(); set => Value = value; } public object Value; public DatabasedSetting(string key, object value) { Key = key; Value = value; } /// <summary> /// Constructor for derived classes that may require serialisation. /// </summary> public DatabasedSetting() { } public override string ToString() => $"{Key}=>{Value}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel.DataAnnotations.Schema; using osu.Game.Database; namespace osu.Game.Configuration { [Table("Settings")] public class DatabasedSetting : IHasPrimaryKey { public int ID { get; set; } public int? RulesetID { get; set; } public int? Variant { get; set; } public int? SkinInfoID { get; set; } [Column("Key")] public string Key { get; set; } [Column("Value")] public string StringValue { get => Value.ToString(); set => Value = value; } public object Value; public DatabasedSetting(string key, object value) { Key = key; Value = value; } /// <summary> /// Constructor for derived classes that may require serialisation. /// </summary> public DatabasedSetting() { } public override string ToString() => $"{Key}=>{Value}"; } }
mit
C#
a71e52da4caf53c88b772263d4b7fb89090a34ec
Fix enum ordering after adding source
peppy/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu
osu.Game/Screens/Select/Filter/SortMode.cs
osu.Game/Screens/Select/Filter/SortMode.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Screens.Select.Filter { public enum SortMode { [Description("Artist")] Artist, [Description("Author")] Author, [Description("BPM")] BPM, [Description("Date Added")] DateAdded, [Description("Difficulty")] Difficulty, [Description("Length")] Length, [Description("Rank Achieved")] RankAchieved, [Description("Source")] Source, [Description("Title")] Title, } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Screens.Select.Filter { public enum SortMode { [Description("Artist")] Artist, [Description("Author")] Author, [Description("BPM")] BPM, [Description("Date Added")] DateAdded, [Description("Difficulty")] Difficulty, [Description("Length")] Length, [Description("Rank Achieved")] RankAchieved, [Description("Title")] Title, [Description("Source")] Source, } }
mit
C#
c007f8596ae032d3c21d05a127181d1280163229
Fix issue when no match is made
smbecker/Eto.Parse,picoe/Eto.Parse,picoe/Eto.Parse,ArsenShnurkov/Eto.Parse,ArsenShnurkov/Eto.Parse,smbecker/Eto.Parse
Eto.Parse/Parser.cs
Eto.Parse/Parser.cs
using System; using System.Text; using System.Collections.Generic; using Eto.Parse.Scanners; using Eto.Parse.Parsers; using System.Linq; namespace Eto.Parse { public abstract partial class Parser : ICloneable { internal bool Reusable { get; set; } public object Context { get; set; } public event Action<ParseMatch> Succeeded; protected virtual void OnSucceeded(ParseMatch parseMatch) { if (Succeeded != null) Succeeded(parseMatch); } public Parser() { } protected Parser(Parser other) { Context = other.Context; } public ContainerMatch Match(string value, bool match = true) { if (value == null) throw new ArgumentNullException("value"); return Match(new StringScanner(value), match); } public ContainerMatch Match(Scanner scanner, bool match = true) { if (scanner == null) throw new ArgumentNullException("scanner"); var args = new ParseArgs(scanner); args.Push((Parser)null); var top = Parse(args); ContainerMatch containerMatch; if (top != null) { var matches = args.Pop(top.Success); containerMatch = new ContainerMatch(scanner, top.Index, top.Length, matches); } else { containerMatch = new ContainerMatch(scanner, -1, -1); containerMatch.Error = args.Error; } if (match) { containerMatch.PreMatch(); containerMatch.Match(); } return containerMatch; } public ParseMatch Parse(ParseArgs args) { var match = InnerParse(args); if (match != null) OnSucceeded(match); else if (args.Error == null || args.Scanner.Offset > args.Error.Index) { args.Error = new ParseMatch(args.Scanner, args.Scanner.Offset, -1); } return match; } public abstract IEnumerable<NamedParser> Find(string parserId); public NamedParser this [string parserId] { get { return Find(parserId).FirstOrDefault(); } } protected abstract ParseMatch InnerParse(ParseArgs args); public abstract Parser Clone(); object ICloneable.Clone() { return Clone(); } } public class ParserCollection : List<Parser> { } }
using System; using System.Text; using System.Collections.Generic; using Eto.Parse.Scanners; using Eto.Parse.Parsers; using System.Linq; namespace Eto.Parse { public abstract partial class Parser : ICloneable { internal bool Reusable { get; set; } public object Context { get; set; } public event Action<ParseMatch> Succeeded; protected virtual void OnSucceeded(ParseMatch parseMatch) { if (Succeeded != null) Succeeded(parseMatch); } public Parser() { } protected Parser(Parser other) { Context = other.Context; } public ContainerMatch Match(string value, bool match = true) { if (value == null) throw new ArgumentNullException("value"); return Match(new StringScanner(value), match); } public ContainerMatch Match(Scanner scanner, bool match = true) { if (scanner == null) throw new ArgumentNullException("scanner"); var args = new ParseArgs(scanner); args.Push((Parser)null); var top = Parse(args); var matches = args.Pop(top.Success); var containerMatch = new ContainerMatch(scanner, top.Index, top.Length, matches); containerMatch.Error = top.Success ? null : args.Error; if (match) { containerMatch.PreMatch(); containerMatch.Match(); } return containerMatch; } public ParseMatch Parse(ParseArgs args) { var match = InnerParse(args); if (match != null) OnSucceeded(match); else if (args.Error == null || args.Scanner.Offset > args.Error.Index) { args.Error = new ParseMatch(args.Scanner, args.Scanner.Offset, -1); } return match; } public abstract IEnumerable<NamedParser> Find(string parserId); public NamedParser this [string parserId] { get { return Find(parserId).FirstOrDefault(); } } protected abstract ParseMatch InnerParse(ParseArgs args); public abstract Parser Clone(); object ICloneable.Clone() { return Clone(); } } public class ParserCollection : List<Parser> { } }
mit
C#
c6fb842a7210c4e8f690518ea86d244cb4643f3b
Change version number to 2.2.1
SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-msbuild-runner,SonarSource-DotNet/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild,duncanpMS/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource-VisualStudio/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner
AssemblyInfo.Shared.cs
AssemblyInfo.Shared.cs
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("2.2.1")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("Version:2.2.1.0 Branch:not-set Sha1:not-set")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015/2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("2.2.0")] [assembly: AssemblyFileVersion("2.2.0.0")] [assembly: AssemblyInformationalVersion("Version:2.2.0.0 Branch:not-set Sha1:not-set")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015/2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
mit
C#
4b795157c6993cc3666662d78eb3f296eefc1445
modify for zero arguments function
taqu/Utility,taqu/Utility
Assets/Flow/Functor.cs
Assets/Flow/Functor.cs
/** @file Functor.cs @author t-sakai @date 2016/02/23 */ namespace Flow { public struct ToFunctor0 { public delegate void Func(); public static Functor Do(Func func) { return new Functor(func, null); } }; public struct ToFunctor1<T> { public delegate void Func(T t); public static Functor Do(Func func, params System.Object[] args) { return new Functor(func, args); } }; public struct ToFunctor2<T0, T1> { public delegate void Func(T0 t0, T1 t1); public static Functor Do(Func func, params System.Object[] args) { return new Functor(func, args); } }; public struct Functor : System.Collections.IEnumerator { private bool done_; private System.Delegate func_; private System.Object[] args_; public Functor(System.Delegate func, params System.Object[] args) { func_ = func; args_ = args; done_ = (null == func_); } public object Current { get { return null; } } public bool MoveNext() { if(!done_) { func_.DynamicInvoke(args_); done_ = true; } return false; } public void Reset() { done_ = false; } }; }
/** @file Functor.cs @author t-sakai @date 2016/02/23 */ namespace Flow { public struct ToFunctor0 { public delegate void Func(); public static Functor Do(Func func, params System.Object[] args) { return new Functor(func, args); } }; public struct ToFunctor1<T> { public delegate void Func(T t); public static Functor Do(Func func, params System.Object[] args) { return new Functor(func, args); } }; public struct ToFunctor2<T0, T1> { public delegate void Func(T0 t0, T1 t1); public static Functor Do(Func func, params System.Object[] args) { return new Functor(func, args); } }; public struct Functor : System.Collections.IEnumerator { private bool done_; private System.Delegate func_; private System.Object[] args_; public Functor(System.Delegate func, params System.Object[] args) { func_ = func; args_ = args; done_ = false; } public object Current { get { return null; } } public bool MoveNext() { if(!done_) { func_.DynamicInvoke(args_); done_ = true; } return false; } public void Reset() { done_ = false; } }; }
unlicense
C#
374e90439fd04491780547f7a9c732a46d0e4f92
Refactor `SetUpFixture` of Atata.IntegrationTests project
atata-framework/atata,atata-framework/atata
test/Atata.IntegrationTests/SetUpFixture.cs
test/Atata.IntegrationTests/SetUpFixture.cs
using System.Net.NetworkInformation; using Atata.Cli; using Atata.WebDriverSetup; namespace Atata.IntegrationTests; [SetUpFixture] public class SetUpFixture { private CliCommand _dotnetRunCommand; [OneTimeSetUp] public async Task GlobalSetUpAsync() => await Task.WhenAll( DriverSetup.AutoSetUpAsync(BrowserNames.Chrome), Task.Run(SetUpTestApp)); private static bool IsTestAppRunning() => IPGlobalProperties.GetIPGlobalProperties() .GetActiveTcpListeners() .Any(x => x.Port == UITestFixtureBase.TestAppPort); private void SetUpTestApp() { if (!IsTestAppRunning()) StartTestApp(); } private void StartTestApp() { string testAppPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "..", "Atata.TestApp"); ProgramCli dotnetCli = new ProgramCli("dotnet", useCommandShell: true) .WithWorkingDirectory(testAppPath); _dotnetRunCommand = dotnetCli.Start("run"); var testAppWait = new SafeWait<SetUpFixture>(this) { Timeout = TimeSpan.FromSeconds(40), PollingInterval = TimeSpan.FromSeconds(0.2) }; testAppWait.Until(x => IsTestAppRunning()); } [OneTimeTearDown] public void GlobalTearDown() { if (_dotnetRunCommand != null) { _dotnetRunCommand.Kill(true); _dotnetRunCommand.Dispose(); } } }
using System; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Threading.Tasks; using Atata.Cli; using Atata.WebDriverSetup; using NUnit.Framework; namespace Atata.IntegrationTests { [SetUpFixture] public class SetUpFixture { private CliCommand _dotnetRunCommand; [OneTimeSetUp] public async Task GlobalSetUpAsync() { await Task.WhenAll( DriverSetup.AutoSetUpAsync(BrowserNames.Chrome), Task.Run(SetUpTestApp)); } private static bool IsTestAppRunning() { IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners(); return ipEndPoints.Any(x => x.Port == UITestFixtureBase.TestAppPort); } private void SetUpTestApp() { if (!IsTestAppRunning()) StartTestApp(); } private void StartTestApp() { string testAppPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "..", "Atata.TestApp"); ProgramCli dotnetCli = new ProgramCli("dotnet", useCommandShell: true) .WithWorkingDirectory(testAppPath); _dotnetRunCommand = dotnetCli.Start("run"); var testAppWait = new SafeWait<SetUpFixture>(this) { Timeout = TimeSpan.FromSeconds(40), PollingInterval = TimeSpan.FromSeconds(0.2) }; testAppWait.Until(x => IsTestAppRunning()); } [OneTimeTearDown] public void GlobalTearDown() { if (_dotnetRunCommand != null) { _dotnetRunCommand.Kill(true); _dotnetRunCommand.Dispose(); } } } }
apache-2.0
C#
a275a81fb8d089967c622d920c3909358b893f04
Strengthen expected messaging on failed tests.
PioneerCode/pioneer-pagination,PioneerCode/pioneer-pagination,PioneerCode/pioneer-pagination
test/Pioneer.Pagination.Tests/ClampTests.cs
test/Pioneer.Pagination.Tests/ClampTests.cs
using Xunit; namespace Pioneer.Pagination.Tests { /// <summary> /// Clamp Tests /// </summary> public class ClampTests { private readonly PaginatedMetaService _sut = new PaginatedMetaService(); [Fact] public void NextPageIsLastPageInCollectionWhenRequestedPageIsGreatedThenCollection() { var result = _sut.GetMetaData(10, 50, 1); Assert.True(result.NextPage.PageNumber == 10, "Expected: Next page should be last page in collection."); } [Fact] public void PreviousPageIsLastPageMinusOneInCollectionWhenRequestedPageIsGreatedThenCollection() { var result = _sut.GetMetaData(10, 100, 1); Assert.True(result.PreviousPage.PageNumber == 9, "Expected: Previous page should be last page in collection minus 1."); } [Fact] public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsZero() { var result = _sut.GetMetaData(10, 0, 1); Assert.True(result.PreviousPage.PageNumber == 1, "Expected: Previous page should be first page in collection."); } [Fact] public void NextPageIsSecondPageInCollectionWhenRequestedPageIsZero() { var result = _sut.GetMetaData(10, 0, 1); Assert.True(result.NextPage.PageNumber == 2, "Expected: Next page should be second page in collection."); } [Fact] public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsNegative() { var result = _sut.GetMetaData(10, -1, 1); Assert.True(result.PreviousPage.PageNumber == 1, "Expected: Previous page should be first page in collection."); } [Fact] public void NextPageIsSecondPageInCollectionWhenRequestedPageIsNegative() { var result = _sut.GetMetaData(10, -1, 1); Assert.True(result.NextPage.PageNumber == 2, "Expected: Next page should be second page in collection."); } } }
using Xunit; namespace Pioneer.Pagination.Tests { /// <summary> /// Clamp Tests /// </summary> public class ClampTests { private readonly PaginatedMetaService _sut = new PaginatedMetaService(); [Fact] public void NextPageIsLastPageInCollectionWhenRequestedPageIsGreatedThenCollection() { var result = _sut.GetMetaData(10, 50, 1); Assert.True(result.NextPage.PageNumber == 10, "Expected: Last Page "); } [Fact] public void PreviousPageIsLastPageMinusOneInCollectionWhenRequestedPageIsGreatedThenCollection() { var result = _sut.GetMetaData(10, 100, 1); Assert.True(result.PreviousPage.PageNumber == 9, "Expected: Last Page "); } [Fact] public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsZero() { var result = _sut.GetMetaData(10, 0, 1); Assert.True(result.PreviousPage.PageNumber == 1, "Expected: First Page "); } [Fact] public void NextPageIsSecondPageInCollectionWhenRequestedPageIsZero() { var result = _sut.GetMetaData(10, 0, 1); Assert.True(result.NextPage.PageNumber == 2, "Expected: First Page "); } [Fact] public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsNegative() { var result = _sut.GetMetaData(10, -1, 1); Assert.True(result.PreviousPage.PageNumber == 1, "Expected: First Page "); } [Fact] public void NextPageIsSecondPageInCollectionWhenRequestedPageIsNegative() { var result = _sut.GetMetaData(10, -1, 1); Assert.True(result.NextPage.PageNumber == 2, "Expected: First Page "); } } }
mit
C#
f0e09683afefe9f5f3475623c9d544802e33ef65
Update Consular.cs (#28)
BosslandGmbH/BuddyWing.DefaultCombat
trunk/DefaultCombat/Routines/Basic/Consular.cs
trunk/DefaultCombat/Routines/Basic/Consular.cs
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { public class Consular : RotationBase { public override string Name { get { return "Basic Consular"; } } public override Composite Buffs { get { return new PrioritySelector(); } } public override Composite Cooldowns { get { return new PrioritySelector(); } } public override Composite SingleTarget { get { return new PrioritySelector( CombatMovement.CloseDistance(Distance.Melee), Spell.Cast("Project", ret => Me.Force > 75), Spell.Cast("Saber Strike") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector( Spell.Cast("Force Wave", ret => Me.CurrentTarget.Distance <= Distance.MeleeAoE)) ); } } } }
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { public class Consular : RotationBase { public override string Name { get { return "Basic Consular"; } } public override Composite Buffs { get { return new PrioritySelector(); } } public override Composite Cooldowns { get { return new PrioritySelector(); } } public override Composite SingleTarget { get { return new PrioritySelector( CombatMovement.CloseDistance(Distance.Melee), Spell.Cast("Telekinetic Throw"), Spell.Cast("Project", ret => Me.Force > 75), Spell.Cast("Double Strike", ret => Me.Force > 70), Spell.Cast("Saber Strike") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector( Spell.Cast("Force Wave", ret => Me.CurrentTarget.Distance <= Distance.MeleeAoE)) ); } } } }
apache-2.0
C#
54874e754f18705eeae88f2842ca4cfae96a0928
Update IAdUnitSelector.cs
tiksn/TIKSN-Framework
TIKSN.Core/Advertising/IAdUnitSelector.cs
TIKSN.Core/Advertising/IAdUnitSelector.cs
namespace TIKSN.Advertising { public interface IAdUnitSelector { AdUnit Select(AdUnitBundle adUnitBundle); } }
namespace TIKSN.Advertising { public interface IAdUnitSelector { AdUnit Select(AdUnitBundle adUnitBundle); } }
mit
C#
6b493047b3268da50b1599172c1c099a4ede48cd
Check folders by its tag
SteamDatabase/ValveResourceFormat
GUI/Controls/TreeViewFileSorter.cs
GUI/Controls/TreeViewFileSorter.cs
using System.Collections; using System.Windows.Forms; namespace GUI.Controls { internal class TreeViewFileSorter : IComparer { public int Compare(object x, object y) { var tx = x as TreeNode; var ty = y as TreeNode; var folderx = tx.Tag is TreeViewFolder; var foldery = ty.Tag is TreeViewFolder; if (folderx && !foldery) { return -1; } if (!folderx && foldery) { return 1; } return string.CompareOrdinal(tx.Text, ty.Text); } } }
using System.Collections; using System.Windows.Forms; namespace GUI.Controls { internal class TreeViewFileSorter : IComparer { public int Compare(object x, object y) { var tx = x as TreeNode; var ty = y as TreeNode; var folderx = tx.ImageKey == @"_folder"; var foldery = ty.ImageKey == @"_folder"; if (folderx && !foldery) { return -1; } if (!folderx && foldery) { return 1; } return string.CompareOrdinal(tx.Text, ty.Text); } } }
mit
C#
9edec2b53ef320da14364b03e4b7dfcf1971199c
Add comments to clarify tests.
duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,sitofabi/duplicati,duplicati/duplicati,sitofabi/duplicati,sitofabi/duplicati,sitofabi/duplicati,duplicati/duplicati,mnaiman/duplicati,duplicati/duplicati,sitofabi/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati
Duplicati/UnitTest/UtilityTests.cs
Duplicati/UnitTest/UtilityTests.cs
// Copyright (C) 2017, The Duplicati Team // http://www.duplicati.com, info@duplicati.com // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using Duplicati.Library.Utility; using NUnit.Framework; using System; using System.Collections.Generic; namespace Duplicati.UnitTest { [TestFixture] public class UtilityTests { [Test] [Category("Utility")] public void GetUniqueItems() { string[] collection = { "A", "a", "A", "b", "c", "c" }; string[] uniqueItems = { "A", "a", "b", "c" }; string[] duplicateItems = { "A", "c" }; // Test with default comparer. ISet<string> actualDuplicateItems; ISet<string> actualUniqueItems = Utility.GetUniqueItems(collection, out actualDuplicateItems); CollectionAssert.AreEquivalent(uniqueItems, actualUniqueItems); CollectionAssert.AreEquivalent(duplicateItems, actualDuplicateItems); // Test with custom comparer. IEqualityComparer<string> comparer = StringComparer.OrdinalIgnoreCase; uniqueItems = new string[] {"a", "b", "c"}; duplicateItems = new string[] { "a", "c" }; actualDuplicateItems = null; actualUniqueItems = Utility.GetUniqueItems(collection, comparer, out actualDuplicateItems); Assert.That(actualUniqueItems, Is.EquivalentTo(uniqueItems).Using(comparer)); Assert.That(actualDuplicateItems, Is.EquivalentTo(duplicateItems).Using(comparer)); // Test with empty collection. actualDuplicateItems = null; actualUniqueItems = Utility.GetUniqueItems(new string[0], out actualDuplicateItems); Assert.IsNotNull(actualUniqueItems); Assert.IsNotNull(actualDuplicateItems); } } }
// Copyright (C) 2017, The Duplicati Team // http://www.duplicati.com, info@duplicati.com // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using Duplicati.Library.Utility; using NUnit.Framework; using System; using System.Collections.Generic; namespace Duplicati.UnitTest { [TestFixture] public class UtilityTests { [Test] [Category("Utility")] public void GetUniqueItems() { string[] collection = { "A", "a", "A", "b", "c", "c" }; string[] uniqueItems = { "A", "a", "b", "c" }; string[] duplicateItems = { "A", "c" }; ISet<string> actualDuplicateItems; ISet<string> actualUniqueItems = Utility.GetUniqueItems(collection, out actualDuplicateItems); CollectionAssert.AreEquivalent(uniqueItems, actualUniqueItems); CollectionAssert.AreEquivalent(duplicateItems, actualDuplicateItems); IEqualityComparer<string> comparer = StringComparer.OrdinalIgnoreCase; uniqueItems = new string[] {"a", "b", "c"}; duplicateItems = new string[] { "a", "c" }; actualDuplicateItems = null; actualUniqueItems = Utility.GetUniqueItems(collection, comparer, out actualDuplicateItems); Assert.That(actualUniqueItems, Is.EquivalentTo(uniqueItems).Using(comparer)); Assert.That(actualDuplicateItems, Is.EquivalentTo(duplicateItems).Using(comparer)); actualDuplicateItems = null; actualUniqueItems = Utility.GetUniqueItems(new string[0], out actualDuplicateItems); Assert.IsNotNull(actualUniqueItems); Assert.IsNotNull(actualDuplicateItems); } } }
lgpl-2.1
C#
416b5c9785d7d2b85fea806cdbf95b370704399d
Add Created and Updated props to Product
pardahlman/akeneo-csharp
Akeneo/Model/Product.cs
Akeneo/Model/Product.cs
using System; using System.Collections.Generic; namespace Akeneo.Model { public class Product : ModelBase { /// <summary> /// Product identifier, i.e. the value of the only `pim_catalog_identifier` attribute /// </summary> public string Identifier { get; set; } /// <summary> /// Whether the product is enable /// </summary> public bool Enabled { get; set; } /// <summary> /// Family code from which the product inherits its attributes and attributes requirements /// </summary> public string Family { get; set; } /// <summary> /// Codes of the categories in which the product is classified /// </summary> public List<string> Categories { get; set; } /// <summary> /// Codes of the groups to which the product belong /// </summary> public List<string> Groups { get; set; } /// <summary> /// Code of the variant group in which the product is /// </summary> public string VariantGroup { get; set; } /// <summary> /// Product attributes values /// </summary> public Dictionary<string, List<ProductValue>> Values { get; set; } /// <summary> /// Date of creation /// </summary> public DateTime Created { get; set; } /// <summary> /// Date of the last update /// </summary> public DateTime Updated { get; set; } /// <summary> /// Several associations related to groups and/or other products, grouped by association types /// </summary> public Dictionary<string,ProductAssociation> Associations { get; set; } } }
using System.Collections.Generic; namespace Akeneo.Model { public class Product : ModelBase { /// <summary> /// Product identifier, i.e. the value of the only `pim_catalog_identifier` attribute /// </summary> public string Identifier { get; set; } /// <summary> /// Whether the product is enable /// </summary> public bool Enabled { get; set; } /// <summary> /// Family code from which the product inherits its attributes and attributes requirements /// </summary> public string Family { get; set; } /// <summary> /// Codes of the categories in which the product is classified /// </summary> public List<string> Categories { get; set; } /// <summary> /// Codes of the groups to which the product belong /// </summary> public List<string> Groups { get; set; } /// <summary> /// Code of the variant group in which the product is /// </summary> public string VariantGroup { get; set; } /// <summary> /// Product attributes values /// </summary> public Dictionary<string, List<ProductValue>> Values { get; set; } /// <summary> /// Several associations related to groups and/or other products, grouped by association types /// </summary> public Dictionary<string,ProductAssociation> Associations { get; set; } } }
mit
C#
ecb26efd73171a2984d00d30a5a63107cc198b68
fix NullableColumnType bug
killwort/ClickHouse-Net
ClickHouse.Ado/Impl/ColumnTypes/NullableColumnType.cs
ClickHouse.Ado/Impl/ColumnTypes/NullableColumnType.cs
using System; using System.Collections; using System.Diagnostics; using System.Linq; using ClickHouse.Ado.Impl.ATG.Insert; using ClickHouse.Ado.Impl.Data; namespace ClickHouse.Ado.Impl.ColumnTypes { internal class NullableColumnType : ColumnType { public NullableColumnType(ColumnType innerType) => InnerType = innerType; public override bool IsNullable => true; public override int Rows => InnerType.Rows; internal override Type CLRType => !InnerType.CLRType.IsByRef ? InnerType.CLRType : typeof(Nullable<>).MakeGenericType(InnerType.CLRType); public ColumnType InnerType { get; } public bool[] Nulls { get; private set; } public override string AsClickHouseType(ClickHouseTypeUsageIntent usageIntent) => $"Nullable({InnerType.AsClickHouseType(usageIntent)})"; public override void Write(ProtocolFormatter formatter, int rows) { Debug.Assert(Rows == rows, "Row count mismatch!"); new SimpleColumnType<byte>(Nulls.Select(x => x ? (byte) 1 : (byte) 0).ToArray()).Write(formatter, rows); InnerType.Write(formatter, rows); } internal override void Read(ProtocolFormatter formatter, int rows) { var nullStatuses = new SimpleColumnType<byte>(); nullStatuses.Read(formatter, rows); Nulls = nullStatuses.Data.Select(x => x != 0).ToArray(); InnerType.Read(formatter, rows); } public override void ValueFromConst(Parser.ValueType val) { Nulls = new[] {val.StringValue == null && val.ArrayValue == null}; InnerType.ValueFromConst(val); } public override void ValueFromParam(ClickHouseParameter parameter) { Nulls = new[] {parameter.Value == null}; InnerType.ValueFromParam(parameter); } public override object Value(int currentRow) => Nulls[currentRow] ? null : InnerType.Value(currentRow); public override long IntValue(int currentRow) { if (Nulls[currentRow]) #if CORE_FRAMEWORK throw new ArgumentNullException(); #else throw new System.Data.SqlTypes.SqlNullValueException(); #endif return InnerType.IntValue(currentRow); } public override void ValuesFromConst(IEnumerable objects) { InnerType.NullableValuesFromConst(objects); Nulls = objects.Cast<object>().Select(x => x == null).ToArray(); //Data = objects.Cast<DateTime>().ToArray(); } public bool IsNull(int currentRow) => Nulls[currentRow]; } }
using System; using System.Collections; using System.Diagnostics; using System.Linq; using ClickHouse.Ado.Impl.ATG.Insert; using ClickHouse.Ado.Impl.Data; namespace ClickHouse.Ado.Impl.ColumnTypes { internal class NullableColumnType : ColumnType { public NullableColumnType(ColumnType innerType) => InnerType = innerType; public override bool IsNullable => true; public override int Rows => InnerType.Rows; internal override Type CLRType => InnerType.CLRType.IsByRef ? InnerType.CLRType : typeof(Nullable<>).MakeGenericType(InnerType.CLRType); public ColumnType InnerType { get; } public bool[] Nulls { get; private set; } public override string AsClickHouseType(ClickHouseTypeUsageIntent usageIntent) => $"Nullable({InnerType.AsClickHouseType(usageIntent)})"; public override void Write(ProtocolFormatter formatter, int rows) { Debug.Assert(Rows == rows, "Row count mismatch!"); new SimpleColumnType<byte>(Nulls.Select(x => x ? (byte) 1 : (byte) 0).ToArray()).Write(formatter, rows); InnerType.Write(formatter, rows); } internal override void Read(ProtocolFormatter formatter, int rows) { var nullStatuses = new SimpleColumnType<byte>(); nullStatuses.Read(formatter, rows); Nulls = nullStatuses.Data.Select(x => x != 0).ToArray(); InnerType.Read(formatter, rows); } public override void ValueFromConst(Parser.ValueType val) { Nulls = new[] {val.StringValue == null && val.ArrayValue == null}; InnerType.ValueFromConst(val); } public override void ValueFromParam(ClickHouseParameter parameter) { Nulls = new[] {parameter.Value == null}; InnerType.ValueFromParam(parameter); } public override object Value(int currentRow) => Nulls[currentRow] ? null : InnerType.Value(currentRow); public override long IntValue(int currentRow) { if (Nulls[currentRow]) #if CORE_FRAMEWORK throw new ArgumentNullException(); #else throw new System.Data.SqlTypes.SqlNullValueException(); #endif return InnerType.IntValue(currentRow); } public override void ValuesFromConst(IEnumerable objects) { InnerType.NullableValuesFromConst(objects); Nulls = objects.Cast<object>().Select(x => x == null).ToArray(); //Data = objects.Cast<DateTime>().ToArray(); } public bool IsNull(int currentRow) => Nulls[currentRow]; } }
mit
C#
f1d8ae8f39374b5a67d1656bf477cd69d5695c2a
Disable Edge DriverDownloadTest
rosolko/WebDriverManager.Net
WebDriverManager.Tests/EdgeConfigTests.cs
WebDriverManager.Tests/EdgeConfigTests.cs
using System; using System.Text.RegularExpressions; using WebDriverManager.DriverConfigs.Impl; using Xunit; namespace WebDriverManager.Tests { public class EdgeConfigTests : EdgeConfig { [Fact] public void VersionTest() { var version = GetLatestVersion(); var regex = new Regex(@"^\d+\.\d+.\d+.\d+$"); Assert.NotEmpty(version); Assert.Matches(regex, version); } [Fact(Skip = "Broken by Microsoft")] public void DriverDownloadTest() { new DriverManager().SetUpDriver(new EdgeConfig()); Assert.NotEmpty(WebDriverFinder.FindFile(GetBinaryName())); } } }
using System; using System.Text.RegularExpressions; using WebDriverManager.DriverConfigs.Impl; using Xunit; namespace WebDriverManager.Tests { public class EdgeConfigTests : EdgeConfig { [Fact] public void VersionTest() { var version = GetLatestVersion(); var regex = new Regex(@"^\d+\.\d+.\d+.\d+$"); Assert.NotEmpty(version); Assert.Matches(regex, version); } [Fact] public void DriverDownloadTest() { new DriverManager().SetUpDriver(new EdgeConfig()); Assert.NotEmpty(WebDriverFinder.FindFile(GetBinaryName())); } } }
mit
C#
42e5e8e6108627a89c526b3e5002809bace03895
Add support StringLexerSource.getName() to allow tokenizer working with Feature.LINEMARKERS (Currently NullReferenceException)
xtravar/CppNet,SiliconStudio/CppNet,manu-silicon/CppNet
StringLexerSource.cs
StringLexerSource.cs
/* * Anarres C Preprocessor * Copyright (c) 2007-2008, Shevek * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.IO; namespace CppNet { /** * A Source for lexing a String. * * This class is used by token pasting, but can be used by user * code. */ public class StringLexerSource : LexerSource { private readonly string filename; /** * Creates a new Source for lexing the given String. * * @param ppvalid true if preprocessor directives are to be * honoured within the string. */ public StringLexerSource(String str, bool ppvalid, string fileName = null) : base(new StringReader(str), ppvalid) { this.filename = fileName ?? string.Empty; // Always use empty otherwise cpp.token() will fail on NullReferenceException } /** * Creates a new Source for lexing the given String. * * By default, preprocessor directives are not honoured within * the string. */ public StringLexerSource(String str, string fileName = null) : this(str, false, fileName) { } internal override string getName() { return filename; } override public String ToString() { return "string literal"; } } }
/* * Anarres C Preprocessor * Copyright (c) 2007-2008, Shevek * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.IO; namespace CppNet { /** * A Source for lexing a String. * * This class is used by token pasting, but can be used by user * code. */ public class StringLexerSource : LexerSource { /** * Creates a new Source for lexing the given String. * * @param ppvalid true if preprocessor directives are to be * honoured within the string. */ public StringLexerSource(String str, bool ppvalid) : base(new StringReader(str), ppvalid) { } /** * Creates a new Source for lexing the given String. * * By default, preprocessor directives are not honoured within * the string. */ public StringLexerSource(String str) : this(str, false) { } override public String ToString() { return "string literal"; } } }
apache-2.0
C#
d9f0ab6b52a54d4f694a95deac80d45bc580505d
Extend the array test
jonathanvdc/ecsc
tests/cs/arrays/Arrays.cs
tests/cs/arrays/Arrays.cs
using System; public static class Program { private static void PrintAll(int[] Items) { for (int i = 0; i < Items.Length; i++) { Console.WriteLine(Items[i]); } } public static void Main(string[] Args) { for (int i = 0; i < Args.Length; i++) { Console.WriteLine(Args[i]); } PrintAll(new[] { 1, 2, 3 }); PrintAll(new int[] { 1, 2, 3 }); PrintAll(new int[3] { 1, 2, 3 }); PrintAll(new int[3]); PrintAll(new int[] { }); } }
using System; public static class Program { private static void PrintAll(int[] Items) { for (int i = 0; i < Items.Length; i++) { Console.WriteLine(Items[i]); } } public static void Main(string[] Args) { for (int i = 0; i < Args.Length; i++) { Console.WriteLine(Args[i]); } PrintAll(new[] { 1, 2, 3 }); PrintAll(new int[] { 1, 2, 3 }); PrintAll(new int[3] { 1, 2, 3 }); PrintAll(new int[3]); } }
mit
C#
c928c9a227a5cdc926967e5f8990a6fa1a65e128
Update Map.cs (#21)
AntShares/AntShares.SmartContract.Framework
Neo.SmartContract.Framework/Map.cs
Neo.SmartContract.Framework/Map.cs
using Neo.VM; namespace Neo.SmartContract.Framework { public class Map<TKey, TValue> { [OpCode(OpCode.NEWMAP)] public extern Map(); public extern TValue this[TKey key] { [OpCode(OpCode.PICKITEM)] get; [OpCode(OpCode.SETITEM)] set; } public extern TKey[] Keys { [OpCode(OpCode.KEYS)] get; } public extern TValue[] Values { [OpCode(OpCode.VALUES)] get; } [OpCode(OpCode.HASKEY)] public extern bool HasKey(TKey key); [OpCode(OpCode.REMOVE)] public extern void Remove(TKey key); } }
using Neo.VM; namespace Neo.SmartContract.Framework { public class Map<TKey, TValue> { [OpCode(OpCode.NEWMAP)] public extern Map(); } public static class MapHelper { [OpCode(OpCode.SETITEM)] public extern static void Put<TKey, TValue>(this Map<TKey, TValue> map, TKey key, TValue value); [OpCode(OpCode.PICKITEM)] public extern static TValue Get<TKey, TValue>(this Map<TKey, TValue> map, TKey key); [OpCode(OpCode.REMOVE)] public extern static void Remove<TKey, TValue>(this Map<TKey, TValue> map, TKey key); [OpCode(OpCode.HASKEY)] public extern static bool HasKey<TKey, TValue>(this Map<TKey, TValue> map, TKey key); [OpCode(OpCode.KEYS)] public extern static TKey[] Keys<TKey, TValue>(this Map<TKey, TValue> map); [OpCode(OpCode.VALUES)] public extern static TValue[] Values<TKey, TValue>(this Map<TKey, TValue> map); } }
mit
C#
40c4fe26f048d7dcc87a6c92baffbcfb34a32a65
Add support for basic auth
Xerosigma/halclient
HALClient/HalClient.cs
HALClient/HalClient.cs
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Ecom.Hal.JSON; using Newtonsoft.Json; namespace Ecom.Hal { public class HalClient { public HalClient(Uri endpoint) { Client = new HttpClient {BaseAddress = endpoint}; } public T Parse<T>(string content) { return JsonConvert.DeserializeObject<T>(content, new JsonConverter[] {new HalResourceConverter()}); } public Task<T> Get<T>(string path) { return Task<T> .Factory .StartNew(() => { var body = Client.GetStringAsync(new Uri(path, UriKind.Relative)).Result; return Parse<T>(body); }); } public void SetCredentials(string username, string password) { Client .DefaultRequestHeaders .Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)))); } protected HttpClient Client { get; set; } } }
using System; using System.Net.Http; using System.Threading.Tasks; using Ecom.Hal.JSON; using Newtonsoft.Json; namespace Ecom.Hal { public class HalClient { public HalClient(Uri endpoint) { Client = new HttpClient {BaseAddress = endpoint}; } public T Parse<T>(string content) { return JsonConvert.DeserializeObject<T>(content, new JsonConverter[] {new HalResourceConverter()}); } public Task<T> Get<T>(string path) { return Task<T> .Factory .StartNew(() => { var body = Client.GetStringAsync(new Uri(path, UriKind.Relative)).Result; return Parse<T>(body); }); } protected HttpClient Client { get; set; } } }
apache-2.0
C#
61a9e56ae653b382d3e6d84731c887fed2765d10
Support fonts whose names do not start with letters
EdiWang/UWP-CharacterMap,EdiWang/UWP-CharacterMap,EdiWang/UWP-CharacterMap
CharacterMap/CharacterMap/Core/AlphaKeyGroup.cs
CharacterMap/CharacterMap/Core/AlphaKeyGroup.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Windows.Globalization.Collation; namespace CharacterMap.Core { public class AlphaKeyGroup<T> : List<T> { const string GlobeGroupKey = "?"; public string Key { get; private set; } //public List<T> this { get; private set; } public AlphaKeyGroup(string key) { Key = key; } //private static List<AlphaKeyGroup<T>> CreateDefaultGroups(CharacterGroupings slg) //{ // return (from cg // in slg // where cg.Label != string.Empty // select cg.Label == "..." ? // new AlphaKeyGroup<T>(GlobeGroupKey) : // new AlphaKeyGroup<T>(cg.Label)) // .ToList(); //} // Work around for Chinese version of Windows // By default, Chinese lanugage group will create useless "拼音A-Z" groups. private static List<AlphaKeyGroup<T>> CreateAZGroups() { char[] alpha = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ&".ToCharArray(); var list = alpha.Select(c => new AlphaKeyGroup<T>(c.ToString())).ToList(); return list; } public static List<AlphaKeyGroup<T>> CreateGroups(IEnumerable<T> items, Func<T, string> keySelector) { CharacterGroupings slg = new CharacterGroupings(); List<AlphaKeyGroup<T>> list = CreateAZGroups(); //CreateDefaultGroups(slg); foreach (T item in items) { int index = 0; string label = slg.Lookup(keySelector(item)); index = list.FindIndex(alphagroupkey => (alphagroupkey.Key.Equals(label, StringComparison.CurrentCulture))); if (index > -1 && index < list.Count) list[index].Add(item); else list.Last().Add(item); } return list; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Windows.Globalization.Collation; namespace CharacterMap.Core { public class AlphaKeyGroup<T> : List<T> { const string GlobeGroupKey = "?"; public string Key { get; private set; } //public List<T> this { get; private set; } public AlphaKeyGroup(string key) { Key = key; } //private static List<AlphaKeyGroup<T>> CreateDefaultGroups(CharacterGroupings slg) //{ // return (from cg // in slg // where cg.Label != string.Empty // select cg.Label == "..." ? // new AlphaKeyGroup<T>(GlobeGroupKey) : // new AlphaKeyGroup<T>(cg.Label)) // .ToList(); //} // Work around for Chinese version of Windows // By default, Chinese lanugage group will create useless "拼音A-Z" groups. private static List<AlphaKeyGroup<T>> CreateAZGroups() { char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); var list = alpha.Select(c => new AlphaKeyGroup<T>(c.ToString())).ToList(); return list; } public static List<AlphaKeyGroup<T>> CreateGroups(IEnumerable<T> items, Func<T, string> keySelector) { CharacterGroupings slg = new CharacterGroupings(); List<AlphaKeyGroup<T>> list = CreateAZGroups(); //CreateDefaultGroups(slg); foreach (T item in items) { int index = 0; string label = slg.Lookup(keySelector(item)); index = list.FindIndex(alphagroupkey => (alphagroupkey.Key.Equals(label, StringComparison.CurrentCulture))); if (index > -1 && index < list.Count) list[index].Add(item); } return list; } } }
mit
C#
9a8a21fe0e0bae2cc45917279f081473c9e0fe42
Add API to show up addin installation dialog for addin files
mono/mono-addins,mono/mono-addins
Mono.Addins.Gui/Mono.Addins.Gui/AddinManagerWindow.cs
Mono.Addins.Gui/Mono.Addins.Gui/AddinManagerWindow.cs
// // AddinManagerWindow.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace Mono.Addins.Gui { public class AddinManagerWindow { private static bool mAllowInstall = true; public static bool AllowInstall { get { return mAllowInstall; } set { mAllowInstall = value; } } private AddinManagerWindow() { } private static void InitDialog (AddinManagerDialog dlg) { dlg.AllowInstall = AllowInstall; } public static Gtk.Window Show (Gtk.Window parent) { AddinManagerDialog dlg = new AddinManagerDialog (parent); InitDialog (dlg); dlg.Show (); return dlg; } public static void Run (Gtk.Window parent) { AddinManagerDialog dlg = new AddinManagerDialog (parent); try { InitDialog (dlg); dlg.Run (); } finally { dlg.Destroy (); } } public static int RunToInstallFile (Gtk.Window parent, Setup.SetupService service, string file) { var dlg = new InstallDialog (parent, service); try { dlg.InitForInstall (new [] { file }); return dlg.Run (); } finally { dlg.Destroy (); } } } }
// // AddinManagerWindow.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace Mono.Addins.Gui { public class AddinManagerWindow { private static bool mAllowInstall = true; public static bool AllowInstall { get { return mAllowInstall; } set { mAllowInstall = value; } } private AddinManagerWindow() { } private static void InitDialog (AddinManagerDialog dlg) { dlg.AllowInstall = AllowInstall; } public static Gtk.Window Show (Gtk.Window parent) { AddinManagerDialog dlg = new AddinManagerDialog (parent); InitDialog (dlg); dlg.Show (); return dlg; } public static void Run (Gtk.Window parent) { AddinManagerDialog dlg = new AddinManagerDialog (parent); try { InitDialog (dlg); dlg.Run (); } finally { dlg.Destroy (); } } } }
mit
C#
8a0989ea1060f3268bfea3d2be0c57dd1a30c6c0
Remove unnecessary spaces
farity/farity
Farity/Tap.cs
Farity/Tap.cs
using System; namespace Farity { public static partial class F { /// <summary> /// Runs the given function with the supplied value, then returns the value. /// Functions that do not mutate the value provided are recommended. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="function">The function to run on the value.</param> /// <param name="value">The value to be provided to the function.</param> /// <returns>The original value supplied.</returns> /// <remarks>Category: Function</remarks> public static T Tap<T>(Action<T> function, T value) { function(value); return value; } } }
using System; namespace Farity { public static partial class F { /// <summary> /// Runs the given function with the supplied value, then returns the value. /// Functions that do not mutate the value provided are recommended. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="function">The function to run on the value.</param> /// <param name="value">The value to be provided to the function.</param> /// <returns>The original value supplied.</returns> /// <remarks>Category: Function</remarks> public static T Tap<T>(Action<T> function, T value) { function(value); return value; } } }
mit
C#
e7c32f47794728d2901c47f33e9e0d565e5e8b15
Handle syllable buckets with no syllable data.
TheBerkin/Rant
Rant/Vocabulary/SyllableBuckets.cs
Rant/Vocabulary/SyllableBuckets.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Rant.Vocabulary.Querying; namespace Rant.Vocabulary { internal class SyllableBuckets { private readonly Dictionary<int, List<RantDictionaryEntry>> _buckets = new Dictionary<int, List<RantDictionaryEntry>>(); public SyllableBuckets(int termIndex, IEnumerable<RantDictionaryEntry> entries) { foreach(var entry in entries) { var syllableCount = entry[termIndex].SyllableCount; if(syllableCount == 0) continue; if(!_buckets.ContainsKey(syllableCount)) { _buckets[syllableCount] = new List<RantDictionaryEntry>(); } _buckets[syllableCount].Add(entry); } } public List<RantDictionaryEntry> Query(RangeFilter filter) { if (_buckets.Count == 0) return new List<RantDictionaryEntry>(); var min = (filter.Minimum == null ? 1 : (int)filter.Minimum); var max = (filter.Maximum == null ? min : (int)filter.Maximum); // go through twice, first to find out the size to allocate var size = 0; for(var i = min; i <= max; i++) { size += _buckets[i].Count; } var list = new List<RantDictionaryEntry>(size); for(var i = min; i <= max; i++) { list.AddRange(_buckets[i]); } return list; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Rant.Vocabulary.Querying; namespace Rant.Vocabulary { internal class SyllableBuckets { private readonly Dictionary<int, List<RantDictionaryEntry>> _buckets = new Dictionary<int, List<RantDictionaryEntry>>(); public SyllableBuckets(int termIndex, IEnumerable<RantDictionaryEntry> entries) { foreach(var entry in entries) { var syllableCount = entry[termIndex].SyllableCount; if(syllableCount == 0) continue; if(!_buckets.ContainsKey(syllableCount)) { _buckets[syllableCount] = new List<RantDictionaryEntry>(); } _buckets[syllableCount].Add(entry); } } public List<RantDictionaryEntry> Query(RangeFilter filter) { var min = (filter.Minimum == null ? 1 : (int)filter.Minimum); var max = (filter.Maximum == null ? min : (int)filter.Maximum); // go through twice, first to find out the size to allocate var size = 0; for(var i = min; i <= max; i++) { size += _buckets[i].Count; } var list = new List<RantDictionaryEntry>(size); for(var i = min; i <= max; i++) { list.AddRange(_buckets[i]); } return list; } } }
mit
C#
0a571278c975c3f496b928afed9f576d88c52769
change TestCase to OsuTestCase
naoey/osu,2yangk23/osu,UselessToucan/osu,Frontear/osuKyzer,NeoAdonis/osu,ppy/osu,EVAST9919/osu,naoey/osu,2yangk23/osu,UselessToucan/osu,ZLima12/osu,smoogipooo/osu,DrabWeb/osu,smoogipoo/osu,smoogipoo/osu,Nabile-Rahmani/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,DrabWeb/osu,naoey/osu,EVAST9919/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ZLima12/osu,peppy/osu,johnneijzen/osu,johnneijzen/osu,peppy/osu-new,DrabWeb/osu,peppy/osu
osu.Game.Tests/Visual/TestCaseVolumePieces.cs
osu.Game.Tests/Visual/TestCaseVolumePieces.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Overlays.Volume; using OpenTK.Graphics; namespace osu.Game.Tests.Visual { public class TestCaseVolumePieces : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(VolumeMeter), typeof(MuteButton) }; protected override void LoadComplete() { VolumeMeter meter; MuteButton mute; Add(meter = new VolumeMeter("MASTER", 125, Color4.Blue)); Add(mute = new MuteButton { Margin = new MarginPadding { Top = 200 } }); AddSliderStep("master volume", 0, 10, 0, i => meter.Bindable.Value = i * 0.1); AddToggleStep("mute", b => mute.Current.Value = b); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Overlays.Volume; using OpenTK.Graphics; namespace osu.Game.Tests.Visual { public class TestCaseVolumePieces : TestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(VolumeMeter), typeof(MuteButton) }; protected override void LoadComplete() { VolumeMeter meter; MuteButton mute; LoadComponentAsync(meter = new VolumeMeter("MASTER", 125, Color4.Blue), Add); LoadComponentAsync(mute = new MuteButton { Margin = new MarginPadding { Top = 200 } }, Add); AddSliderStep("master volume", 0, 10, 0, i => meter.Bindable.Value = i * 0.1); AddToggleStep("mute", b => mute.Current.Value = b); } } }
mit
C#
513f8c4591262e68e33c32cd00236a3660a57311
Add helper method SetTextAndRefresh
StefH/ICSharpCode.TextEditorEx
ICSharpCode.TextEditorEx/TextEditorControlEx.cs
ICSharpCode.TextEditorEx/TextEditorControlEx.cs
using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using ICSharpCode.TextEditor.Src.Actions; using ICSharpCode.TextEditor.UserControls; namespace ICSharpCode.TextEditor { [ToolboxBitmap("ICSharpCode.TextEditor.Resources.TextEditorControl.bmp")] [ToolboxItem(true)] public class TextEditorControlEx : TextEditorControl { public TextEditorControlEx() { var findForm = new FindAndReplaceForm(); editactions[Keys.Control | Keys.F] = new EditFindAction(findForm, this); editactions[Keys.Control | Keys.H] = new EditReplaceAction(findForm, this); editactions[Keys.F3] = new FindAgainAction(findForm, this); editactions[Keys.F3 | Keys.Shift] = new FindAgainReverseAction(findForm, this); editactions[Keys.Control | Keys.G] = new GoToLineNumberAction(); } /// <summary> /// Sets the text and refreshes the control. /// </summary> /// <param name="text">The text.</param> public void SetTextAndRefresh(string text) { ResetText(); Text = text; Refresh(); } } }
using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using ICSharpCode.TextEditor.Src.Actions; using ICSharpCode.TextEditor.UserControls; namespace ICSharpCode.TextEditor { [ToolboxBitmap("ICSharpCode.TextEditor.Resources.TextEditorControl.bmp")] [ToolboxItem(true)] public class TextEditorControlEx : TextEditorControl { public TextEditorControlEx() { var findForm = new FindAndReplaceForm(); editactions[Keys.Control | Keys.F] = new EditFindAction(findForm, this); editactions[Keys.Control | Keys.H] = new EditReplaceAction(findForm, this); editactions[Keys.F3] = new FindAgainAction(findForm, this); editactions[Keys.F3 | Keys.Shift] = new FindAgainReverseAction(findForm, this); editactions[Keys.Control | Keys.G] = new GoToLineNumberAction(); } } }
lgpl-2.1
C#
e0afee1b902912b05ae7c80728396f657b5ca411
add helper for full log url
remcoros/InspectR,remcoros/InspectR
InspectR/Helpers/InspectRUrlHelperExtensions.cs
InspectR/Helpers/InspectRUrlHelperExtensions.cs
namespace InspectR.Helpers { public static class InspectRUrlHelperExtensions { public static string Index(this UrlHelperExtensions.InspectRUrlHelper url) { return url.Url.Action("Index", "InspectR"); } public static string Create(this UrlHelperExtensions.InspectRUrlHelper url, bool isprivate = false) { return url.Url.Action("Create", "InspectR", new { isprivate }); } public static string Inspect(this UrlHelperExtensions.InspectRUrlHelper url, string key) { return url.Url.RouteUrl("log", new { id = key }) + "?inspect"; } public static string Log(this UrlHelperExtensions.InspectRUrlHelper url, string key) { return url.Url.RouteUrl("log", new { id = key }); } public static string FullLogUrl(this UrlHelperExtensions.InspectRUrlHelper url, string key) { return url.Url.RouteUrl("log", new { id = key }, url.Url.RequestContext.HttpContext.Request.Url.Scheme); } } }
namespace InspectR.Helpers { public static class InspectRUrlHelperExtensions { public static string Index(this UrlHelperExtensions.InspectRUrlHelper url) { return url.Url.Action("Index", "InspectR"); } public static string Create(this UrlHelperExtensions.InspectRUrlHelper url, bool isprivate = false) { return url.Url.Action("Create", "InspectR", new { isprivate }); } public static string Inspect(this UrlHelperExtensions.InspectRUrlHelper url, string key) { return url.Url.RouteUrl("log", new { id = key }) + "?inspect"; } public static string Log(this UrlHelperExtensions.InspectRUrlHelper url, string key) { return url.Url.RouteUrl("log", new { id = key }); } } }
mit
C#
80b53c72e860cbdb0a63a25865483183c7a75363
remove warnings from Operations.cshtml
joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net
JoinRpg.Portal/Views/Finances/Operations.cshtml
JoinRpg.Portal/Views/Finances/Operations.cshtml
@model JoinRpg.Web.Models.FinOperationListViewModel @{ ViewBag.Title = "Список финансовых операций"; ViewBag.CountString = Html.DisplayCount_OfX(Model.Items.Count(), "операция", "операции", "операций"); } <h2>@ViewBag.Title</h2> <partial name="_ListOperationsDropdown" model="Model" /> <partial name="_Operations" model="Model.Items" />
@model JoinRpg.Web.Models.FinOperationListViewModel @{ ViewBag.Title = "Список финансовых операций"; ViewBag.CountString = Html.DisplayCount_OfX(Model.Items.Count(), "операция", "операции", "операций"); } <h2>@ViewBag.Title</h2> @Html.Partial("_ListOperationsDropdown", Model) @Html.Partial("_Operations", Model.Items)
mit
C#
de05c3628c006991f5f0129bb7031b70e638432f
Fix bug with zoom when it didnt limit
AceSkiffer/SharpGraphEditor
src/SharpGraphEditor/Models/ZoomManager.cs
src/SharpGraphEditor/Models/ZoomManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Caliburn.Micro; namespace SharpGraphEditor.Models { public class ZoomManager : PropertyChangedBase { public double MaxZoom { get; } = 2; public double CurrentZoom { get; private set; } public int CurrentZoomInPercents => (int)(CurrentZoom * 100); public ZoomManager() { CurrentZoom = 1.0; } public void ChangeCurrentZoom(double value) { var newZoom = CurrentZoom + value; if (newZoom >= (1.0 / MaxZoom) && newZoom <= MaxZoom) { CurrentZoom = Math.Round(newZoom, 2); } } public void ChangeZoomByPercents(double percents) { ChangeCurrentZoom(percents / 100); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Caliburn.Micro; namespace SharpGraphEditor.Models { public class ZoomManager : PropertyChangedBase { public int MaxZoom { get; } = 2; public double CurrentZoom { get; private set; } public int CurrentZoomInPercents => (int)(CurrentZoom * 100); public ZoomManager() { CurrentZoom = 1; } public void ChangeCurrentZoom(double value) { if (value >= (1 / MaxZoom) && value <= MaxZoom) { CurrentZoom = Math.Round(value, 2); } } public void ChangeZoomByPercents(double percents) { CurrentZoom += percents / 100; } } }
apache-2.0
C#
2ff17fed0fd873af3aab891cfe8f18bef25375c5
patch assemblyinfo
rodkings/Untappd.Net,tparnell8/Untappd.Net,rodkings/Untappd.Net,tparnell8/Untappd.Net
src/Untappd.Net/Properties/AssemblyInfo.cs
src/Untappd.Net/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("Untappd.Net")] [assembly: AssemblyDescription("C# Untappd Wrapper")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tommy Parnell")] [assembly: AssemblyProduct("Untappd.Net")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("d8571a44-2e86-43a3-b64a-2364614c6934")] // 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.*")] [assembly: AssemblyFileVersion("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("Untappd.Net")] [assembly: AssemblyDescription("C# Untappd Wrapper")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tommy Parnell")] [assembly: AssemblyProduct("Untappd.Net")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("d8571a44-2e86-43a3-b64a-2364614c6934")] // 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.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")]
mit
C#
db22db1e60e7421fc3c2899df8d0116949e777d8
create conditional approval from organization used wrong parameter
ucdavis/Purchasing,ucdavis/Purchasing,ucdavis/Purchasing
Purchasing.Web/Views/ConditionalApproval/ByOrg.cshtml
Purchasing.Web/Views/ConditionalApproval/ByOrg.cshtml
@model System.Linq.IQueryable<Purchasing.Core.Domain.ConditionalApproval> @{ ViewBag.Title = "Conditional Approvals by Organization"; } @section SubNav { <ul class="navigation"> <li>@Html.ActionLink("Back to Organization", "Details", "Organization", new { id = ViewBag.OrganizationId }, new { @class="button" })</li> </ul> } <section class="display-form ui-corner-all"> <header class="ui-corner-top ui-widget-header"> </header> <div class="section-contents"> <div class="col1"></div><div class="col2">@Html.ActionLink("Create Approval", "Create", "ConditionalApproval", new { orgId = ViewBag.OrganizationId }, new { @class = "button" })</div> <table> <thead> <tr> <th></th> <th>Organization</th> <th>Primary Approver</th> <th>Secondary Approver</th> <th>Question</th> <th></th> </tr> </thead> <tbody> @foreach (var ca in Model) { <tr> <td><a href='@Url.Action("Edit", new { ca.Id })' class="ui-icon ui-icon-pencil" title="Edit approval"><img src='@Url.Image("edit.png")'></a></td> <td>@ca.Organization.Name (@ca.Organization.Id)</td> <td>@ca.PrimaryApprover.FullNameAndIdLastFirst</td> <td>@(ca.SecondaryApprover == null ? "N/A" : ca.SecondaryApprover.FullNameAndIdLastFirst)</td> <td>@ca.Question</td> <td><a href='@Url.Action("Delete", new {ca.Id})' class="ui-icon ui-icon-trash" title="Delete approval"><img src='@Url.Image("delete.png")'></a></td> </tr> } </tbody> </table> </div> </section>
@model System.Linq.IQueryable<Purchasing.Core.Domain.ConditionalApproval> @{ ViewBag.Title = "Conditional Approvals by Organization"; } @section SubNav { <ul class="navigation"> <li>@Html.ActionLink("Back to Organization", "Details", "Organization", new { id = ViewBag.OrganizationId }, new { @class="button" })</li> </ul> } <section class="display-form ui-corner-all"> <header class="ui-corner-top ui-widget-header"> </header> <div class="section-contents"> <div class="col1"></div><div class="col2">@Html.ActionLink("Create Approval", "Create", "ConditionalApproval", new { id = ViewBag.OrganizationId }, new { @class = "button" })</div> <table> <thead> <tr> <th></th> <th>Organization</th> <th>Primary Approver</th> <th>Secondary Approver</th> <th>Question</th> <th></th> </tr> </thead> <tbody> @foreach (var ca in Model) { <tr> <td><a href='@Url.Action("Edit", new { ca.Id })' class="ui-icon ui-icon-pencil" title="Edit approval"><img src='@Url.Image("edit.png")'></a></td> <td>@ca.Organization.Name (@ca.Organization.Id)</td> <td>@ca.PrimaryApprover.FullNameAndIdLastFirst</td> <td>@(ca.SecondaryApprover == null ? "N/A" : ca.SecondaryApprover.FullNameAndIdLastFirst)</td> <td>@ca.Question</td> <td><a href='@Url.Action("Delete", new {ca.Id})' class="ui-icon ui-icon-trash" title="Delete approval"><img src='@Url.Image("delete.png")'></a></td> </tr> } </tbody> </table> </div> </section>
mit
C#
51f3543513129652a4db6530cec2b5c6351c73e2
fix namespace
linpiero/Serenity,WasimAhmad/Serenity,linpiero/Serenity,linpiero/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,volkanceylan/Serenity,TukekeSoft/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,linpiero/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,linpiero/Serenity,TukekeSoft/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,TukekeSoft/Serenity,dfaruque/Serenity,TukekeSoft/Serenity,rolembergfilho/Serenity
Serenity.Core/Services/AuditLog/AuditUpdateRequest.cs
Serenity.Core/Services/AuditLog/AuditUpdateRequest.cs
using System; using System.Collections.Generic; using Serenity.Web; using Serenity.Data; using Serenity.Services; using EntityType = System.String; namespace Serenity.Services { public class AuditUpdateRequest { public EntityType EntityType { get; private set; } public IIdRow OldEntity { get; private set; } public IIdRow NewEntity { get; private set; } public Field[] AuditFields { get; private set; } public EntityType ParentTypeId { get; set; } public Int64? OldParentId { get; set; } public Int64? NewParentId { get; set; } public AuditFileFieldInfo[] FileFieldInfos { get; set; } public string FileSubFolder { get; set; } public ICollection<string> FilesToDelete { get; set; } public AuditUpdateRequest(EntityType entityType, IIdRow oldEntity, IIdRow newEntity, Field[] auditFields) { if (oldEntity == null) throw new ArgumentNullException("oldEntity"); if (newEntity == null) throw new ArgumentNullException("newEntity"); if (auditFields == null) throw new ArgumentNullException("auditFields"); EntityType = entityType; OldEntity = oldEntity; NewEntity = newEntity; AuditFields = auditFields; } } }
using System; using System.Collections.Generic; using Serenity.Web; using Serenity.Data; using Serenity.Services; using EntityType = System.String; public class AuditUpdateRequest { public EntityType EntityType { get; private set; } public IIdRow OldEntity { get; private set; } public IIdRow NewEntity { get; private set; } public Field[] AuditFields { get; private set; } public EntityType ParentTypeId { get; set; } public Int64? OldParentId { get; set; } public Int64? NewParentId { get; set; } public AuditFileFieldInfo[] FileFieldInfos { get; set; } public string FileSubFolder { get; set; } public ICollection<string> FilesToDelete { get; set; } public AuditUpdateRequest(EntityType entityType, IIdRow oldEntity, IIdRow newEntity, Field[] auditFields) { if (oldEntity == null) throw new ArgumentNullException("oldEntity"); if (newEntity == null) throw new ArgumentNullException("newEntity"); if (auditFields == null) throw new ArgumentNullException("auditFields"); EntityType = entityType; OldEntity = oldEntity; NewEntity = newEntity; AuditFields = auditFields; } }
mit
C#
008bc1bb655b5ebd8517e2887c1c6555a0ae5448
Extend RelayCommand
stadub/Net.Utils
Utils.Wpf/MvvmBase/RelayCommand.cs
Utils.Wpf/MvvmBase/RelayCommand.cs
using System; using System.Windows.Input; namespace Utils.Wpf.MvvmBase { public class RelayCommand : IRelayCommand { private readonly Action execute; private readonly Func<bool> canExecute; private bool status; public RelayCommand(Action execute, Func<bool> canExecute = null) { this.execute = execute; if (canExecute != null) this.canExecute = canExecute; else this.canExecute = () => true; status = true; } public bool CanExecute() { var newStatus = canExecute(); if (newStatus == status) return newStatus; status = newStatus; OnCanExecuteChanged(); return newStatus; } public void RefreshCanExecute() { CanExecute(); } public void Execute() { if (!CanExecute()) return; execute(); } bool ICommand.CanExecute(object parameter) { return CanExecute(); } void ICommand.Execute(object parameter) { Execute(); } public event EventHandler CanExecuteChanged; protected virtual void OnCanExecuteChanged() { EventHandler handler = CanExecuteChanged; if (handler != null) handler(this, EventArgs.Empty); } } public interface IRelayCommand : ICommand { bool CanExecute(); void RefreshCanExecute(); void Execute(); } }
using System; using System.Windows.Input; namespace Utils.Wpf.MvvmBase { public class RelayCommand : ICommand { private readonly Action execute; private readonly Func<bool> canExecute; private bool status; public RelayCommand(Action execute, Func<bool> canExecute = null) { this.execute = execute; if (canExecute != null) this.canExecute = canExecute; else this.canExecute = () => true; status = true; } public bool CanExecute(object parameter) { var newStatus = canExecute(); if (newStatus == status) return newStatus; status = newStatus; OnCanExecuteChanged(); return newStatus; } public void Execute(object parameter) { if (!CanExecute(parameter)) return; execute(); } public event EventHandler CanExecuteChanged; protected virtual void OnCanExecuteChanged() { EventHandler handler = CanExecuteChanged; if (handler != null) handler(this, EventArgs.Empty); } } }
bsd-3-clause
C#
90411513593dea61a54d374d287bf667d79fdfb3
Remove extra space
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewLocator.cs
WalletWasabi.Fluent/ViewLocator.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Controls; using Avalonia.Controls.Templates; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Fluent { [StaticViewLocator] public partial class ViewLocator : IDataTemplate { public bool SupportsRecycling => false; public IControl Build(object data) { var type = data.GetType(); if (s_views.TryGetValue(type, out var func)) { return func?.Invoke(); } throw new Exception($"Unable to create view for type: {type}"); /*var name =.FullName!.Replace("ViewModel", "View"); var type = Type.GetType(name); if (type != null) { var result = Activator.CreateInstance(type) as Control; if (result is null) { throw new Exception($"Unable to activate type: {type}"); } return result; } else { return new TextBlock { Text = "Not Found: " + name }; }*/ } public bool Match(object data) { return data is ViewModelBase; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Controls; using Avalonia.Controls.Templates; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Fluent { [StaticViewLocator] public partial class ViewLocator : IDataTemplate { public bool SupportsRecycling => false; public IControl Build(object data) { var type = data.GetType(); if (s_views.TryGetValue(type, out var func)) { return func?.Invoke(); } throw new Exception($"Unable to create view for type: {type}"); /*var name =.FullName!.Replace("ViewModel", "View"); var type = Type.GetType(name); if (type != null) { var result = Activator.CreateInstance(type) as Control; if (result is null) { throw new Exception($"Unable to activate type: {type}"); } return result; } else { return new TextBlock { Text = "Not Found: " + name }; }*/ } public bool Match(object data) { return data is ViewModelBase; } } }
mit
C#
24852ece8fd321a6c979dcf19550423e8ca6ca88
Remove Html tags
Xciles/programming.support,Xciles/programming.support
Webje/Botje/Programming.Bot/Business/StackOverflow.cs
Webje/Botje/Programming.Bot/Business/StackOverflow.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Programming.Bot.Domain.StackOverflow; namespace Programming.Bot.Business { public static class StackOverflow { private static readonly HttpClient HttpClient = new HttpClient(); private const string StackOverflowSearchUri = "http://api.stackexchange.com/2.2/search?order=desc&sort=votes&intitle={0}&site=stackoverflow"; private const string StackOverflowAnswerUri = "http://api.stackexchange.com/2.2/answers/{0}?order=desc&sort=activity&site=stackoverflow&filter=!9YdnSMKKT"; public static async Task<string> Query(string query) { var msg = await HttpClient.GetAsync(string.Format(StackOverflowSearchUri,query)); if (!msg.IsSuccessStatusCode) { throw new Exception("Stackoverflow search API call failed"); } var jsonDataResponse = await msg.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject<SearchResults>(jsonDataResponse); var acceptedAnswerId = data.items[0].accepted_answer_id; msg = await HttpClient.GetAsync(string.Format(StackOverflowAnswerUri, acceptedAnswerId)); if (!msg.IsSuccessStatusCode) { throw new Exception("Stackoverflow answer API call failed"); } jsonDataResponse = await msg.Content.ReadAsStringAsync(); var answerData = JsonConvert.DeserializeObject<AnswerResult>(jsonDataResponse); return RemoveHtmlTags(answerData.items[0].body); } public static string RemoveHtmlTags(string html) { if (html == null) return string.Empty; var response = Regex.Replace(html, @"<[^>]+>|&nbsp;", "").Trim(); response = response.Replace("&amp;", "&"); return response; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Programming.Bot.Domain.StackOverflow; namespace Programming.Bot.Business { public static class StackOverflow { private static readonly HttpClient HttpClient = new HttpClient(); private const string StackOverflowSearchUri = "http://api.stackexchange.com/2.2/search?order=desc&sort=votes&intitle={0}&site=stackoverflow"; private const string StackOverflowAnswerUri = "http://api.stackexchange.com/2.2/answers/{0}?order=desc&sort=activity&site=stackoverflow&filter=!9YdnSMKKT"; public static async Task<string> Query(string query) { var msg = await HttpClient.GetAsync(string.Format(StackOverflowSearchUri,query)); if (!msg.IsSuccessStatusCode) { throw new Exception("Stackoverflow search API call failed"); } var jsonDataResponse = await msg.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject<SearchResults>(jsonDataResponse); var acceptedAnswerId = data.items[0].accepted_answer_id; msg = await HttpClient.GetAsync(string.Format(StackOverflowAnswerUri, acceptedAnswerId)); if (!msg.IsSuccessStatusCode) { throw new Exception("Stackoverflow answer API call failed"); } jsonDataResponse = await msg.Content.ReadAsStringAsync(); var answerData = JsonConvert.DeserializeObject<AnswerResult>(jsonDataResponse); //TODO add html cleaner return answerData.items[0].body; } } }
mit
C#
5da9f67c170cf3f601b7efca5a595091c1988760
Use common from address for backup
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Jobs/SqliteBackupJob.cs
Battery-Commander.Web/Jobs/SqliteBackupJob.cs
using BatteryCommander.Web.Services; using FluentScheduler; using SendGrid.Helpers.Mail; using System; using System.Collections.Generic; namespace BatteryCommander.Web.Jobs { public class SqliteBackupJob : IJob { private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable private readonly IEmailService emailSvc; public SqliteBackupJob(IEmailService emailSvc) { this.emailSvc = emailSvc; } public virtual void Execute() { var data = System.IO.File.ReadAllBytes("Data.db"); var encoded = System.Convert.ToBase64String(data); var message = new SendGridMessage { From = EmailService.FROM_ADDRESS, Subject = "Nightly Db Backup", Contents = new List<Content>() { new Content { Type = "text/plain", Value = "Please find the nightly database backup attached." } }, Attachments = new List<Attachment>() { new Attachment { Filename = "Data.db", Type = "application/octet-stream", Content = encoded } } }; message.AddTo(Recipient); emailSvc.Send(message).Wait(); } } }
using BatteryCommander.Web.Services; using FluentScheduler; using SendGrid.Helpers.Mail; using System; using System.Collections.Generic; namespace BatteryCommander.Web.Jobs { public class SqliteBackupJob : IJob { private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable private readonly IEmailService emailSvc; public SqliteBackupJob(IEmailService emailSvc) { this.emailSvc = emailSvc; } public virtual void Execute() { var data = System.IO.File.ReadAllBytes("Data.db"); var encoded = System.Convert.ToBase64String(data); var message = new SendGridMessage { From = new EmailAddress("Battery-Commander@redlegdev.com"), Subject = "Nightly Db Backup", Contents = new List<Content>() { new Content { Type = "text/plain", Value = "Please find the nightly database backup attached." } }, Attachments = new List<Attachment>() { new Attachment { Filename = "Data.db", Type = "application/octet-stream", Content = encoded } } }; message.AddTo(Recipient); emailSvc.Send(message).Wait(); } } }
mit
C#
dd06996e1f312b15df6e0f70ef7f2880472e4802
Remove an insane lock.
Mikuz/Battlezeppelins,Mikuz/Battlezeppelins
Battlezeppelins/Controllers/BaseController.cs
Battlezeppelins/Controllers/BaseController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public abstract class BaseController : Controller { private static List<Player> playerList = new List<Player>(); public Player GetPlayer() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int id = Int32.Parse(idStr); Player player = SearchPlayer(id); if (player != null) return player; lock (playerList) { player = SearchPlayer(id); if (player != null) return player; Player newPlayer = Player.GetInstance(id); playerList.Add(newPlayer); return newPlayer; } } return null; } private Player SearchPlayer(int id) { foreach (Player listPlayer in playerList) { if (listPlayer.id == id) { return listPlayer; } } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Runtime.CompilerServices; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public abstract class BaseController : Controller { private static List<Player> playerList = new List<Player>(); [MethodImpl(MethodImplOptions.Synchronized)] public Player GetPlayer() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int id = Int32.Parse(idStr); Player player = null; foreach (Player listPlayer in playerList) { if (listPlayer.id == id) { player = listPlayer; } } if (player == null) { Player newPlayer = Player.GetInstance(id); playerList.Add(newPlayer); return newPlayer; } else { return player; } } return null; } } }
apache-2.0
C#
f6be4faac6892b0e9206a4e704d98723ef8567f5
Update version: 1.3.0-alpha
toolhouse/monitoring-dotnet
Toolhouse.Monitoring/Properties/AssemblyInfo.cs
Toolhouse.Monitoring/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("Toolhouse.Monitoring")] [assembly: AssemblyDescription("Monitoring tools for ASP.NET websites.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Toolhouse")] [assembly: AssemblyProduct("Toolhouse.Monitoring.Properties")] [assembly: AssemblyCopyright("2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d416b3d4-6f91-4c92-af08-4dcbedecb75a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Nuget prefers AssemblyInformationalVersion, so modify this when cutting Nuget releases [assembly: AssemblyInformationalVersion("1.3.0-alpha")]
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("Toolhouse.Monitoring")] [assembly: AssemblyDescription("Monitoring tools for ASP.NET websites.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Toolhouse")] [assembly: AssemblyProduct("Toolhouse.Monitoring.Properties")] [assembly: AssemblyCopyright("2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d416b3d4-6f91-4c92-af08-4dcbedecb75a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Nuget prefers AssemblyInformationalVersion, so modify this when cutting Nuget releases [assembly: AssemblyInformationalVersion("1.2.0")]
apache-2.0
C#
9a48a35a7f638e4cd68696da17246b28e89f0efa
Scale larger images down to make the face searching faster in testing
ProductiveRage/FacialRecognition
Tester/Program.cs
Tester/Program.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using FaceDetection; namespace Tester { class Program { static void Main(string[] args) { var filename = "TigerWoods.gif"; var outputFilename = "Output.png"; // This strikes a reasonable balance between successfully matching faces in my current (small) sample data while performing the work quickly const int maxAllowedSize = 480; var config = DefaultConfiguration.Instance; var timer = new IntervalTimer(Console.WriteLine); var faceDetector = new FaceDetector(config, timer.Log); using (var source = new Bitmap(filename)) { var largestDimension = Math.Max(source.Width, source.Height); var scaleDown = (largestDimension > maxAllowedSize) ? ((double)largestDimension / maxAllowedSize) : 1; var colourData = (scaleDown > 1) ? GetResizedBitmapData(source, scaleDown) : source.GetRGB(); var faceRegions = faceDetector.GetPossibleFaceRegions(colourData); if (scaleDown > 1) faceRegions = faceRegions.Select(region => Scale(region, scaleDown)); WriteOutputFile(outputFilename, source, faceRegions, Color.GreenYellow); timer.Log($"Complete (written to {outputFilename}), {faceRegions.Count()} region(s) identified"); } Console.WriteLine(); Console.WriteLine("Press [Enter] to terminate.."); Console.ReadLine(); } private static DataRectangle<RGB> GetResizedBitmapData(Bitmap source, double scale) { if (source == null) throw new ArgumentNullException(nameof(source)); if (scale <= 0) throw new ArgumentOutOfRangeException(nameof(scale)); using (var resizedSource = GetResizedBitmap(source, scale)) { return resizedSource.GetRGB(); } } private static Bitmap GetResizedBitmap(Bitmap source, double scale) { if (source == null) throw new ArgumentNullException(nameof(source)); if (scale <= 0) throw new ArgumentOutOfRangeException(nameof(scale)); return new Bitmap(source, new Size((int)Math.Round(source.Width / scale), (int)Math.Round(source.Height / scale))); } private static Rectangle Scale(Rectangle region, double scale) { if (scale <= 0) throw new ArgumentOutOfRangeException(nameof(scale)); return new Rectangle((int)Math.Round(region.X * scale), (int)Math.Round(region.Y * scale), (int)Math.Round(region.Width * scale), (int)Math.Round(region.Height * scale)); } private static void WriteOutputFile(string outputFilename, Bitmap source, IEnumerable<Rectangle> faceRegions, Color outline) { if (string.IsNullOrWhiteSpace(outputFilename)) throw new ArgumentException($"Null/blank {nameof(outputFilename)} specified"); if (source == null) throw new ArgumentNullException(nameof(source)); if (faceRegions == null) throw new ArgumentNullException(nameof(faceRegions)); // If the original image uses a palette (ie. an indexed PixelFormat) then GDI+ can't draw rectangle on it so we'll just create a fresh bitmap every time to // be on the safe side using (var annotatedBitMap = new Bitmap(source.Width, source.Height)) { using (var g = Graphics.FromImage(annotatedBitMap)) { g.DrawImage(source, 0, 0); using (var pen = new Pen(outline, width: 1)) { g.DrawRectangles(pen, faceRegions.ToArray()); } } annotatedBitMap.Save(outputFilename); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using FaceDetection; namespace Tester { class Program { static void Main(string[] args) { var filename = "TigerWoods.gif"; var outputFilename = "Output.png"; var config = DefaultConfiguration.Instance; var timer = new IntervalTimer(Console.WriteLine); var faceDetector = new FaceDetector(config, timer.Log); using (var source = new Bitmap(filename)) { var faceRegions = faceDetector.GetPossibleFaceRegions(source.GetRGB()); WriteOutputFile(outputFilename, source, faceRegions, Color.GreenYellow); timer.Log($"Complete (written to {outputFilename}), {faceRegions.Count()} region(s) identified"); } Console.WriteLine(); Console.WriteLine("Press [Enter] to terminate.."); Console.ReadLine(); } private static void WriteOutputFile(string outputFilename, Bitmap source, IEnumerable<Rectangle> faceRegions, Color outline) { if (string.IsNullOrWhiteSpace(outputFilename)) throw new ArgumentException($"Null/blank {nameof(outputFilename)} specified"); if (source == null) throw new ArgumentNullException(nameof(source)); if (faceRegions == null) throw new ArgumentNullException(nameof(faceRegions)); // If the original image uses a palette (ie. an indexed PixelFormat) then GDI+ can't draw rectangle on it so we'll just create a fresh bitmap every time to // be on the safe side using (var annotatedBitMap = new Bitmap(source.Width, source.Height)) { using (var g = Graphics.FromImage(annotatedBitMap)) { g.DrawImage(source, 0, 0); using (var pen = new Pen(outline, width: 1)) { g.DrawRectangles(pen, faceRegions.ToArray()); } } annotatedBitMap.Save(outputFilename); } } } }
mit
C#
d4ab89acb3d166d291d932546ae55a57cc77b2b6
Update release info
ironfede/openmcdf
sources/OpenMcdf/Properties/AssemblyInfo.cs
sources/OpenMcdf/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("OpenMcdf")] [assembly: AssemblyDescription("MS Compound File Storage .NET Implementation")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Federico Blaseotto")] [assembly: AssemblyProduct("OpenMcdf 2.1")] [assembly: AssemblyCopyright("Copyright © 2010-2016, Federico Blaseotto")] [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("ffc13791-ddf0-4d14-bd64-575aba119190")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.1.2.*")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OpenMcdf.Test")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OpenMcdf.Extensions")]
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("OpenMcdf")] [assembly: AssemblyDescription("MS Compound File Storage .NET Implementation")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Federico Blaseotto")] [assembly: AssemblyProduct("OpenMcdf 2.1")] [assembly: AssemblyCopyright("Copyright © 2010-2016, Federico Blaseotto")] [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("ffc13791-ddf0-4d14-bd64-575aba119190")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.1.1.*")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OpenMcdf.Test")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OpenMcdf.Extensions")]
mpl-2.0
C#
6eb996ddaa4ff711f1e3ac80e019abd58f063e5e
Fix Translation tests when using updated REST support libraries
jskeet/google-cloud-dotnet,evildour/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,iantalarico/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,evildour/google-cloud-dotnet,jskeet/google-cloud-dotnet,benwulfe/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,evildour/google-cloud-dotnet,iantalarico/google-cloud-dotnet,jskeet/google-cloud-dotnet,benwulfe/google-cloud-dotnet,benwulfe/google-cloud-dotnet,iantalarico/google-cloud-dotnet,jskeet/gcloud-dotnet,chrisdunelm/gcloud-dotnet
apis/Google.Cloud.Translation.V2/Google.Cloud.Translation.V2.Tests/FakeTranslateService.cs
apis/Google.Cloud.Translation.V2/Google.Cloud.Translation.V2.Tests/FakeTranslateService.cs
// Copyright 2017 Google Inc. All Rights Reserved. // // 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 Google.Apis.Requests; using Google.Apis.Translate.v2; using Google.Apis.Util; using Google.Cloud.ClientTesting; namespace Google.Cloud.Translation.V2.Tests { // TODO: Work out a way to put this code in ClientTesting, in a non-service-specific way... /// <summary> /// A fake service allowing request/response expect/replay. /// </summary> public class FakeTranslateService : TranslateService { private readonly ReplayingMessageHandler handler; public FakeTranslateService() : base(new Initializer { HttpClientFactory = new FakeHttpClientFactory(new ReplayingMessageHandler()), ApplicationName = "Fake", GZipEnabled = false }) { handler = (ReplayingMessageHandler)HttpClient.MessageHandler.InnerHandler; } public void ExpectRequest<TResponse>(ClientServiceRequest<TResponse> request, TResponse response) { string requestContent = SerializeObject(request); var httpRequest = request.CreateRequest(); // The Translate service uses the old "wrap in data" response style. string responseContent = SerializeObject(new StandardResponse<object> { Data = response }); handler.ExpectRequest(httpRequest.RequestUri, httpRequest.Content?.ReadAsStringAsync()?.Result, responseContent); } } }
// Copyright 2017 Google Inc. All Rights Reserved. // // 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 Google.Apis.Requests; using Google.Apis.Translate.v2; using Google.Cloud.ClientTesting; namespace Google.Cloud.Translation.V2.Tests { // TODO: Work out a way to put this code in ClientTesting, in a non-service-specific way... /// <summary> /// A fake service allowing request/response expect/replay. /// </summary> public class FakeTranslateService : TranslateService { private readonly ReplayingMessageHandler handler; public FakeTranslateService() : base(new Initializer { HttpClientFactory = new FakeHttpClientFactory(new ReplayingMessageHandler()), ApplicationName = "Fake", GZipEnabled = false }) { handler = (ReplayingMessageHandler)HttpClient.MessageHandler.InnerHandler; } public void ExpectRequest<TResponse>(ClientServiceRequest<TResponse> request, TResponse response) { string requestContent = SerializeObject(request); var httpRequest = request.CreateRequest(); string responseContent = SerializeObject(response); handler.ExpectRequest(httpRequest.RequestUri, httpRequest.Content?.ReadAsStringAsync()?.Result, responseContent); } } }
apache-2.0
C#
dce2249c548a8104597ec5b71a287329226eaa2c
bump 1.0.9
crunchie84/HaagsTranslator
src/HaagsTranslator/Properties/AssemblyInfo.cs
src/HaagsTranslator/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("HaagsTranslator")] [assembly: AssemblyDescription("Translator for nl-NL to nl-DH")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Q42")] [assembly: AssemblyProduct("HaagsTranslator")] [assembly: AssemblyCopyright("Copyright © Mark van Straten & Roelfjan de Vries 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("eaff48b1-d748-422b-a423-2baad7a41e2c")] // 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.9.0")] [assembly: AssemblyFileVersion("1.0.9.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("HaagsTranslator")] [assembly: AssemblyDescription("Translator for nl-NL to nl-DH")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Q42")] [assembly: AssemblyProduct("HaagsTranslator")] [assembly: AssemblyCopyright("Copyright © Mark van Straten & Roelfjan de Vries 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("eaff48b1-d748-422b-a423-2baad7a41e2c")] // 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.8.0")] [assembly: AssemblyFileVersion("1.0.8.0")]
mit
C#
572909399edb7181905369bc4fd8d457397bda38
fix vesrion tostring
gigya/microdot
Gigya.Microdot.Ninject/MicrodotInitializer.cs
Gigya.Microdot.Ninject/MicrodotInitializer.cs
using System; using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; using Ninject; namespace Gigya.Microdot.Ninject { public class MicrodotInitializer : IDisposable { public MicrodotInitializer(string appName, ILoggingModule loggingModule, Action<IKernel> additionalBindings = null) { Kernel = new StandardKernel(); Kernel.Load<MicrodotModule>(); var env = HostEnvironment.CreateDefaultEnvironment(appName, typeof(MicrodotInitializer).Assembly.GetName().Version); Kernel .Bind<IEnvironment>() .ToConstant(env) .InSingletonScope(); Kernel .Bind<CurrentApplicationInfo>() .ToConstant(env.ApplicationInfo) .InSingletonScope(); loggingModule.Bind(Kernel.Rebind<ILog>(), Kernel.Rebind<IEventPublisher>(), Kernel.Rebind<Func<string, ILog>>()); // Set custom Binding additionalBindings?.Invoke(Kernel); Kernel.Get<SystemInitializer.SystemInitializer>().Init(); } public IKernel Kernel { get; private set; } public void Dispose() { Kernel?.Dispose(); } } }
using System; using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; using Ninject; namespace Gigya.Microdot.Ninject { public class MicrodotInitializer : IDisposable { public MicrodotInitializer(string appName, ILoggingModule loggingModule, Action<IKernel> additionalBindings = null) { Kernel = new StandardKernel(); Kernel.Load<MicrodotModule>(); var env = HostEnvironment.CreateDefaultEnvironment(appName, new Version()); Kernel .Bind<IEnvironment>() .ToConstant(env) .InSingletonScope(); Kernel .Bind<CurrentApplicationInfo>() .ToConstant(env.ApplicationInfo) .InSingletonScope(); loggingModule.Bind(Kernel.Rebind<ILog>(), Kernel.Rebind<IEventPublisher>(), Kernel.Rebind<Func<string, ILog>>()); // Set custom Binding additionalBindings?.Invoke(Kernel); Kernel.Get<SystemInitializer.SystemInitializer>().Init(); } public IKernel Kernel { get; private set; } public void Dispose() { Kernel?.Dispose(); } } }
apache-2.0
C#
fdc0dddbc47731614f0c3fe082779c7372291b03
write out build configuration
adoprog/Sitecore-Courier,rauljmz/Sitecore-Courier,cmgutmanis/Sitecore-Courier,csteeg/Sitecore-Courier
Sitecore.Courier.Runner/Program.cs
Sitecore.Courier.Runner/Program.cs
namespace Sitecore.Courier.Runner { using Sitecore.Update; using Sitecore.Update.Engine; using System; /// <summary> /// Defines the program class. /// </summary> internal class Program { /// <summary> /// Mains the specified args. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine("Source: {0}", options.Source); Console.WriteLine("Target: {0}", options.Target); Console.WriteLine("Output: {0}", options.Output); Console.WriteLine("Configuration: {0}", options.Configuration); var diff = new DiffInfo( DiffGenerator.GetDiffCommands(options.Source, options.Target), "Sitecore Courier Package", string.Empty, string.Format("Diff between serialization folders '{0}' and '{1}'.", options.Source, options.Target)); PackageGenerator.GeneratePackage(diff, string.Empty, options.Output); } else { Console.WriteLine(options.GetUsage()); } } } }
namespace Sitecore.Courier.Runner { using Sitecore.Update; using Sitecore.Update.Engine; using System; /// <summary> /// Defines the program class. /// </summary> internal class Program { /// <summary> /// Mains the specified args. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine("Source: {0}", options.Source); Console.WriteLine("Target: {0}", options.Target); Console.WriteLine("Output: {0}", options.Output); var diff = new DiffInfo( DiffGenerator.GetDiffCommands(options.Source, options.Target), "Sitecore Courier Package", string.Empty, string.Format("Diff between serialization folders '{0}' and '{1}'.", options.Source, options.Target)); PackageGenerator.GeneratePackage(diff, string.Empty, options.Output); } else { Console.WriteLine(options.GetUsage()); } } } }
mit
C#
9d51ce6076a44d25e62cc60a9c65daed3c8b5c1a
make C# CallError enum up to date with C core
nicolasnoble/grpc,grpc/grpc,vjpai/grpc,donnadionne/grpc,grpc/grpc,jtattermusch/grpc,jtattermusch/grpc,jtattermusch/grpc,grpc/grpc,nicolasnoble/grpc,donnadionne/grpc,ctiller/grpc,nicolasnoble/grpc,stanley-cheung/grpc,stanley-cheung/grpc,grpc/grpc,ctiller/grpc,ctiller/grpc,ejona86/grpc,donnadionne/grpc,stanley-cheung/grpc,jtattermusch/grpc,grpc/grpc,grpc/grpc,vjpai/grpc,ctiller/grpc,vjpai/grpc,stanley-cheung/grpc,donnadionne/grpc,ctiller/grpc,nicolasnoble/grpc,nicolasnoble/grpc,stanley-cheung/grpc,ctiller/grpc,donnadionne/grpc,jtattermusch/grpc,jtattermusch/grpc,grpc/grpc,grpc/grpc,jtattermusch/grpc,jtattermusch/grpc,ejona86/grpc,stanley-cheung/grpc,ctiller/grpc,grpc/grpc,donnadionne/grpc,donnadionne/grpc,jtattermusch/grpc,ctiller/grpc,stanley-cheung/grpc,vjpai/grpc,nicolasnoble/grpc,ctiller/grpc,jtattermusch/grpc,ctiller/grpc,donnadionne/grpc,ctiller/grpc,donnadionne/grpc,ejona86/grpc,ejona86/grpc,ejona86/grpc,ejona86/grpc,ejona86/grpc,nicolasnoble/grpc,nicolasnoble/grpc,grpc/grpc,vjpai/grpc,donnadionne/grpc,stanley-cheung/grpc,vjpai/grpc,stanley-cheung/grpc,vjpai/grpc,donnadionne/grpc,jtattermusch/grpc,vjpai/grpc,jtattermusch/grpc,stanley-cheung/grpc,ejona86/grpc,vjpai/grpc,ejona86/grpc,ejona86/grpc,grpc/grpc,nicolasnoble/grpc,vjpai/grpc,vjpai/grpc,ejona86/grpc,donnadionne/grpc,stanley-cheung/grpc,ejona86/grpc,nicolasnoble/grpc,ctiller/grpc,vjpai/grpc,stanley-cheung/grpc,grpc/grpc,nicolasnoble/grpc,nicolasnoble/grpc
src/csharp/Grpc.Core/Internal/CallError.cs
src/csharp/Grpc.Core/Internal/CallError.cs
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Runtime.InteropServices; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// grpc_call_error from grpc/grpc.h /// </summary> internal enum CallError { /* everything went ok */ OK = 0, /* something failed, we don't know what */ Error, /* this method is not available on the server */ NotOnServer, /* this method is not available on the client */ NotOnClient, /* this method must be called before server_accept */ AlreadyAccepted, /* this method must be called before invoke */ AlreadyInvoked, /* this method must be called after invoke */ NotInvoked, /* this call is already finished (writes_done or write_status has already been called) */ AlreadyFinished, /* there is already an outstanding read/write operation on the call */ TooManyOperations, /* the flags value was illegal for this call */ InvalidFlags, /* invalid metadata was passed to this call */ InvalidMetadata, /* invalid message was passed to this call */ InvalidMessage, /* completion queue for notification has not been registered with the server */ NotServerCompletionQueue, /* this batch of operations leads to more operations than allowed */ BatchTooBig, /* payload type requested is not the type registered */ PayloadTypeMismatch, /* completion queue has been shutdown */ CompletionQueueShutdown } internal static class CallErrorExtensions { /// <summary> /// Checks the call API invocation's result is OK. /// </summary> public static void CheckOk(this CallError callError) { if (callError != CallError.OK) { throw new InvalidOperationException("Call error: " + callError); } } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Runtime.InteropServices; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// grpc_call_error from grpc/grpc.h /// </summary> internal enum CallError { /* everything went ok */ OK = 0, /* something failed, we don't know what */ Error, /* this method is not available on the server */ NotOnServer, /* this method is not available on the client */ NotOnClient, /* this method must be called before server_accept */ AlreadyAccepted, /* this method must be called before invoke */ AlreadyInvoked, /* this method must be called after invoke */ NotInvoked, /* this call is already finished (writes_done or write_status has already been called) */ AlreadyFinished, /* there is already an outstanding read/write operation on the call */ TooManyOperations, /* the flags value was illegal for this call */ InvalidFlags } internal static class CallErrorExtensions { /// <summary> /// Checks the call API invocation's result is OK. /// </summary> public static void CheckOk(this CallError callError) { if (callError != CallError.OK) { throw new InvalidOperationException("Call error: " + callError); } } } }
apache-2.0
C#
0c24a6d74b9268169bee914ceb0ddd66ab5a60ba
Write to console out of try catch
appharbor/appharbor-cli
src/AppHarbor/ApplicationConfiguration.cs
src/AppHarbor/ApplicationConfiguration.cs
using System; using System.IO; using AppHarbor.Model; namespace AppHarbor { public class ApplicationConfiguration { private readonly IFileSystem _fileSystem; private readonly IGitExecutor _gitExecutor; public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor) { _fileSystem = fileSystem; _gitExecutor = gitExecutor; } public string GetApplicationId() { var directory = Directory.GetCurrentDirectory(); var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor")); try { var stream = _fileSystem.OpenRead(appharborConfigurationFile.FullName); using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } catch (FileNotFoundException) { throw new ApplicationConfigurationException("Application is not configured"); } } public void SetupApplication(string id, User user) { var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id); try { _gitExecutor.Execute(string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id), new DirectoryInfo(Directory.GetCurrentDirectory())); Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master"); return; } catch (InvalidOperationException) { } Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl); } } }
using System; using System.IO; using AppHarbor.Model; namespace AppHarbor { public class ApplicationConfiguration { private readonly IFileSystem _fileSystem; private readonly IGitExecutor _gitExecutor; public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor) { _fileSystem = fileSystem; _gitExecutor = gitExecutor; } public string GetApplicationId() { var directory = Directory.GetCurrentDirectory(); var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor")); try { var stream = _fileSystem.OpenRead(appharborConfigurationFile.FullName); using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } catch (FileNotFoundException) { throw new ApplicationConfigurationException("Application is not configured"); } } public void SetupApplication(string id, User user) { var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id); try { _gitExecutor.Execute(string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id), new DirectoryInfo(Directory.GetCurrentDirectory())); Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master"); return; } catch (InvalidOperationException) { Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl); } } } }
mit
C#
75d848aadbfbe61e63cca995720d1b3ee7e70275
rename argument 'key' to 'privateKey' to be clearer
Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum
src/Nethereum.Signer/TransactionSigner.cs
src/Nethereum.Signer/TransactionSigner.cs
using System.Numerics; using Nethereum.Hex.HexConvertors.Extensions; namespace Nethereum.Signer { public class TransactionSigner { public byte[] GetPublicKey(string rlp) { var transaction = new Transaction(rlp.HexToByteArray()); return transaction.Key.GetPubKey(); } public string GetSenderAddress(string rlp) { var transaction = new Transaction(rlp.HexToByteArray()); return transaction.Key.GetPublicAddress(); } public string SignTransaction(string privateKey, string to, BigInteger amount, BigInteger nonce) { var transaction = new Transaction(to, amount, nonce); return SignTransaction(privateKey, transaction); } public string SignTransaction(string privateKey, string to, BigInteger amount, BigInteger nonce, string data) { var transaction = new Transaction(to, amount, nonce, data); return SignTransaction(privateKey, transaction); } public string SignTransaction(string privateKey, string to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit) { var transaction = new Transaction(to, amount, nonce, gasPrice, gasLimit); return SignTransaction(privateKey, transaction); } public string SignTransaction(string privateKey, string to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, string data) { var transaction = new Transaction(to, amount, nonce, gasPrice, gasLimit, data); return SignTransaction(privateKey, transaction); } private string SignTransaction(string privateKey, Transaction transaction) { transaction.Sign(new EthECKey(privateKey.HexToByteArray(), true)); return transaction.GetRLPEncoded().ToHex(); } public bool VerifyTransaction(string rlp) { var transaction = new Transaction(rlp.HexToByteArray()); return transaction.Key.VerifyAllowingOnlyLowS(transaction.RawHash, transaction.Signature); } } }
using System.Numerics; using Nethereum.Hex.HexConvertors.Extensions; namespace Nethereum.Signer { public class TransactionSigner { public byte[] GetPublicKey(string rlp) { var transaction = new Transaction(rlp.HexToByteArray()); return transaction.Key.GetPubKey(); } public string GetSenderAddress(string rlp) { var transaction = new Transaction(rlp.HexToByteArray()); return transaction.Key.GetPublicAddress(); } public string SignTransaction(string key, string to, BigInteger amount, BigInteger nonce) { var transaction = new Transaction(to, amount, nonce); return SignTransaction(key, transaction); } public string SignTransaction(string key, string to, BigInteger amount, BigInteger nonce, string data) { var transaction = new Transaction(to, amount, nonce, data); return SignTransaction(key, transaction); } public string SignTransaction(string key, string to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit) { var transaction = new Transaction(to, amount, nonce, gasPrice, gasLimit); return SignTransaction(key, transaction); } public string SignTransaction(string key, string to, BigInteger amount, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, string data) { var transaction = new Transaction(to, amount, nonce, gasPrice, gasLimit, data); return SignTransaction(key, transaction); } private string SignTransaction(string key, Transaction transaction) { transaction.Sign(new EthECKey(key.HexToByteArray(), true)); return transaction.GetRLPEncoded().ToHex(); } public bool VerifyTransaction(string rlp) { var transaction = new Transaction(rlp.HexToByteArray()); return transaction.Key.VerifyAllowingOnlyLowS(transaction.RawHash, transaction.Signature); } } }
mit
C#
372d90de6ad53cb2e7319531f72d4fcc5abe29ce
Remove unnecessary assigns
smoogipoo/osu,ZLima12/osu,ZLima12/osu,EVAST9919/osu,EVAST9919/osu,UselessToucan/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,2yangk23/osu,ppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,2yangk23/osu,peppy/osu
osu.Game/Online/Leaderboards/UpdateableRank.cs
osu.Game/Online/Leaderboards/UpdateableRank.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Scoring; namespace osu.Game.Online.Leaderboards { public class UpdateableRank : ModelBackedDrawable<ScoreRank> { public ScoreRank Rank { get => Model; set => Model = value; } public UpdateableRank(ScoreRank rank) { Rank = rank; } protected override Drawable CreateDrawable(ScoreRank rank) => new DrawableRank(rank) { Anchor = Anchor.Centre, Origin = Anchor.Centre, }; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Scoring; namespace osu.Game.Online.Leaderboards { public class UpdateableRank : ModelBackedDrawable<ScoreRank> { public ScoreRank Rank { get => Model; set => Model = value; } public UpdateableRank(ScoreRank rank) { Rank = rank; } protected override Drawable CreateDrawable(ScoreRank rank) => new DrawableRank(rank) { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, FillMode = FillMode.Fit, }; } }
mit
C#
f6029b829d2c865aa54473b222d5408bb27c545a
Fix RestClient BaseUrl change to Uri
Charcoals/PivotalTracker.NET,Charcoals/PivotalTracker.NET
PivotalTrackerDotNet/AAuthenticatedService.cs
PivotalTrackerDotNet/AAuthenticatedService.cs
using RestSharp; namespace PivotalTrackerDotNet { using System; public abstract class AAuthenticatedService { protected readonly string m_token; protected RestClient RestClient; protected AAuthenticatedService(string token) { m_token = token; RestClient = new RestClient { BaseUrl = new Uri(PivotalTrackerRestEndpoint.SSLENDPOINT) }; } protected RestRequest BuildGetRequest() { var request = new RestRequest(Method.GET); request.AddHeader("X-TrackerToken", m_token); request.RequestFormat = DataFormat.Json; return request; } protected RestRequest BuildPutRequest() { var request = new RestRequest(Method.PUT); request.AddHeader("X-TrackerToken", m_token); request.RequestFormat = DataFormat.Json; return request; } protected RestRequest BuildDeleteRequest() { var request = new RestRequest(Method.DELETE); request.AddHeader("X-TrackerToken", m_token); request.RequestFormat = DataFormat.Json; return request; } protected RestRequest BuildPostRequest() { var request = new RestRequest(Method.POST); request.AddHeader("X-TrackerToken", m_token); request.RequestFormat = DataFormat.Json; return request; } } }
using RestSharp; namespace PivotalTrackerDotNet { public abstract class AAuthenticatedService { protected readonly string m_token; protected RestClient RestClient; protected AAuthenticatedService(string token) { m_token = token; RestClient = new RestClient {BaseUrl = PivotalTrackerRestEndpoint.SSLENDPOINT}; } protected RestRequest BuildGetRequest() { var request = new RestRequest(Method.GET); request.AddHeader("X-TrackerToken", m_token); request.RequestFormat = DataFormat.Json; return request; } protected RestRequest BuildPutRequest() { var request = new RestRequest(Method.PUT); request.AddHeader("X-TrackerToken", m_token); request.RequestFormat = DataFormat.Json; return request; } protected RestRequest BuildDeleteRequest() { var request = new RestRequest(Method.DELETE); request.AddHeader("X-TrackerToken", m_token); request.RequestFormat = DataFormat.Json; return request; } protected RestRequest BuildPostRequest() { var request = new RestRequest(Method.POST); request.AddHeader("X-TrackerToken", m_token); request.RequestFormat = DataFormat.Json; return request; } } }
mit
C#
5ff333ef3972473c2b92255d5b2e31f865b67186
use ReactiveUserControls
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/Views/HomePageView.axaml.cs
WalletWasabi.Fluent/Views/HomePageView.axaml.cs
using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia.ReactiveUI; using ReactiveUI; using WalletWasabi.Fluent.ViewModels; namespace WalletWasabi.Fluent.Views { public class HomePageView : ReactiveUserControl<HomePageViewModel> { public HomePageView() { this.InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using ReactiveUI; using WalletWasabi.Fluent.ViewModels; namespace WalletWasabi.Fluent.Views { public class HomePageView : UserControl, IViewFor<HomePageViewModel> { public HomePageView() { this.InitializeComponent(); } public HomePageViewModel ViewModel { get; set; } object IViewFor.ViewModel { get; set; } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
mit
C#
1cbebf92b25c25ef92692064d5e6e9fb1e7f7369
Update IView.cs
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Core2D.Editor/Views/Interfaces/IView.cs
src/Core2D.Editor/Views/Interfaces/IView.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Core2D.Editor.Views.Interfaces { /// <summary> /// View contract. /// </summary> public interface IView { /// <summary> /// Gets view title. /// </summary> string Title { get; } /// <summary> /// Gets view context. /// </summary> object Context { get; } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Core2D.Editor.Views.Interfaces { /// <summary> /// View contract. /// </summary> public interface IView { /// <summary> /// Gets view name. /// </summary> string Name { get; set; } /// <summary> /// Gets view context. /// </summary> object Context { get; set; } } }
mit
C#
ccb34dfd6f7a8e72026ff8af0d5c47b3cdffd6eb
Use unchecked arithmetic
ektrah/nsec
src/Cryptography/CryptographicOperations.cs
src/Cryptography/CryptographicOperations.cs
using System; using System.Runtime.CompilerServices; namespace NSec.Cryptography { internal static class CryptographicOperations { [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static unsafe bool FixedTimeEquals(byte* left, byte* right, int length) { // NoOptimization because we want this method to be exactly as // non-short-circuiting as written. NoInlining because the // NoOptimization would get lost if the method got inlined. unchecked { int accum = 0; for (int i = 0; i < length; i++) { accum |= left[i] - right[i]; } return accum == 0; } } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void ZeroMemory(Span<byte> buffer) { // NoOptimize to prevent the optimizer from deciding this call is // unnecessary. NoInlining to prevent the inliner from forgetting // that the method was no-optimize. buffer.Clear(); } } }
using System; using System.Runtime.CompilerServices; namespace NSec.Cryptography { internal static class CryptographicOperations { [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static unsafe bool FixedTimeEquals(byte* left, byte* right, int length) { // NoOptimization because we want this method to be exactly as // non-short-circuiting as written. NoInlining because the // NoOptimization would get lost if the method got inlined. int accum = 0; for (int i = 0; i < length; i++) { accum |= left[i] - right[i]; } return accum == 0; } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void ZeroMemory(Span<byte> buffer) { // NoOptimize to prevent the optimizer from deciding this call is // unnecessary. NoInlining to prevent the inliner from forgetting // that the method was no-optimize. buffer.Clear(); } } }
mit
C#
9d6116244d4647f8053ed38f6e5f8bef4d891589
Enhance summary for IActiveTransactionProvider
abdllhbyrktr/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,Nongzhsh/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,Nongzhsh/aspnetboilerplate,oceanho/aspnetboilerplate,ilyhacker/aspnetboilerplate,luchaoshuai/aspnetboilerplate,andmattia/aspnetboilerplate,Nongzhsh/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,AlexGeller/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,luchaoshuai/aspnetboilerplate,verdentk/aspnetboilerplate,berdankoca/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,virtualcca/aspnetboilerplate,beratcarsi/aspnetboilerplate,andmattia/aspnetboilerplate,AlexGeller/aspnetboilerplate,ilyhacker/aspnetboilerplate,jaq316/aspnetboilerplate,oceanho/aspnetboilerplate,zclmoon/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,jaq316/aspnetboilerplate,jaq316/aspnetboilerplate,fengyeju/aspnetboilerplate,virtualcca/aspnetboilerplate,carldai0106/aspnetboilerplate,beratcarsi/aspnetboilerplate,zclmoon/aspnetboilerplate,carldai0106/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,berdankoca/aspnetboilerplate,berdankoca/aspnetboilerplate,andmattia/aspnetboilerplate,beratcarsi/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,virtualcca/aspnetboilerplate,fengyeju/aspnetboilerplate,zclmoon/aspnetboilerplate,fengyeju/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,AlexGeller/aspnetboilerplate,oceanho/aspnetboilerplate,verdentk/aspnetboilerplate
src/Abp/Data/IActiveTransactionProvider.cs
src/Abp/Data/IActiveTransactionProvider.cs
using System.Data; namespace Abp.Data { public interface IActiveTransactionProvider { /// <summary> /// Gets the active transaction or null if current UOW is not transactional. /// </summary> /// <param name="args"></param> /// <returns></returns> IDbTransaction GetActiveTransaction(ActiveTransactionProviderArgs args); /// <summary> /// Gets the active database connection. /// </summary> /// <param name="args"></param> /// <returns></returns> IDbConnection GetActiveConnection(ActiveTransactionProviderArgs args); } }
using System.Data; namespace Abp.Data { public interface IActiveTransactionProvider { /// <summary> /// Gets the active transaction. /// </summary> /// <param name="args"></param> /// <returns></returns> IDbTransaction GetActiveTransaction(ActiveTransactionProviderArgs args); /// <summary> /// Gets the active connection. /// </summary> /// <param name="args"></param> /// <returns></returns> IDbConnection GetActiveConnection(ActiveTransactionProviderArgs args); } }
mit
C#
215aa81735ca7644073d368f8093a9b3e11c5395
Exclude Shouldly from code coverage
bbtsoftware/TfsUrlParser
setup.cake
setup.cake
#load nuget:?package=Cake.Recipe&version=1.0.0 Environment.SetVariableNames(); BuildParameters.SetParameters( context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "TfsUrlParser", repositoryOwner: "bbtsoftware", repositoryName: "TfsUrlParser", appVeyorAccountName: "BBTSoftwareAG", shouldPublishMyGet: false, shouldRunCodecov: false, shouldDeployGraphDocumentation: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings( context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* -[Shouldly]*", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore();
#load nuget:?package=Cake.Recipe&version=1.0.0 Environment.SetVariableNames(); BuildParameters.SetParameters( context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "TfsUrlParser", repositoryOwner: "bbtsoftware", repositoryName: "TfsUrlParser", appVeyorAccountName: "BBTSoftwareAG", shouldPublishMyGet: false, shouldRunCodecov: false, shouldDeployGraphDocumentation: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings( context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* ", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore();
mit
C#
2d762daea8dcbdf3753069b5457e78a40535ab40
Update App.xaml.cs
wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter
src/SimpleWavSplitter.Avalonia/App.xaml.cs
src/SimpleWavSplitter.Avalonia/App.xaml.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Logging.Serilog; using Avalonia.Markup.Xaml; namespace SimpleWavSplitter.Avalonia { /// <summary> /// Main application. /// </summary> public class App : Application { /// <summary> /// Program entry point. /// </summary> /// <param name="args">The program arguments.</param> static void Main(string[] args) { BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); } /// <summary> /// Build Avalonia app. /// </summary> /// <returns>The Avalonia app builder.</returns> public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<App>() .UsePlatformDetect() .LogToDebug(); /// <inheritdoc/> public override void Initialize() { AvaloniaXamlLoader.Load(this); } /// <inheritdoc/> public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime) { desktopLifetime.MainWindow = new MainWindow(); } else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewLifetime) { //singleViewLifetime.MainView = new MainView(); } base.OnFrameworkInitializationCompleted(); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Logging.Serilog; using Avalonia.Markup.Xaml; namespace SimpleWavSplitter.Avalonia { /// <summary> /// Main application. /// </summary> public class App : Application { /// <summary> /// Program entry point. /// </summary> /// <param name="args">The program arguments.</param> static void Main(string[] args) { BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); } /// <summary> /// Build Avalonia app. /// </summary> /// <returns>The Avalonia app builder.</returns> public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<App>() .UsePlatformDetect() .LogToDebug(); /// <inheritdoc/> public override void Initialize() { AvaloniaXamlLoader.Load(this); } public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime) { desktopLifetime.MainWindow = new MainWindow(); } else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewLifetime) { //singleViewLifetime.MainView = new MainView(); } base.OnFrameworkInitializationCompleted(); } } }
mit
C#
90b04283f259e108ebce82b4f1180c73ded1d3a6
Define a const for read buffer size
detaybey/MimeBank
MimeBank/MimeChecker.cs
MimeBank/MimeChecker.cs
/* * Programmed by Umut Celenli umut@celenli.com */ using System.Collections.Generic; using System.IO; using System.Linq; namespace MimeBank { /// <summary> /// This is the main class to check the file mime type /// Header list is loaded once /// </summary> public class MimeChecker { private const int maxBufferSize = 256; private static List<FileHeader> list { get; set; } private List<FileHeader> List { get { if (list == null) { list = HeaderData.GetList(); } return list; } } private byte[] Buffer; public MimeChecker() { Buffer = new byte[maxBufferSize]; } public FileHeader GetFileHeader(string file) { using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { fs.Read(Buffer, 0, maxBufferSize); } return this.List.FirstOrDefault(mime => mime.Check(Buffer)); } } }
/* * Programmed by Umut Celenli umut@celenli.com */ using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MimeBank { /// <summary> /// This is the main class to check the file mime type /// Header list is loaded once /// </summary> public class MimeChecker { private static List<FileHeader> list { get; set; } private List<FileHeader> List { get { if (list == null) { list = HeaderData.GetList(); } return list; } } private byte[] Buffer; public MimeChecker() { Buffer = new byte[256]; } public FileHeader GetFileHeader(string file) { using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { fs.Read(Buffer, 0, 256); } return this.List.FirstOrDefault(mime => mime.Check(Buffer) == true); } } }
apache-2.0
C#
93f163a25ecdfd72b38a083016b12eaf7e4b88cd
update changes data model
the-overground/bot-on-bot-backend
src/BotOnBot.Backend.DataModel/ChangesModel.cs
src/BotOnBot.Backend.DataModel/ChangesModel.cs
using System.Linq; using Newtonsoft.Json; namespace BotOnBot.Backend.DataModel { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class ChangesModel : ISerializable { [JsonProperty(PropertyName = "tiles")] public TileModel[] Tiles; [JsonProperty(PropertyName = "actions")] public ActionModel[] Actions; [JsonProperty(PropertyName = "gameState")] public string GameState; [JsonProperty(PropertyName = "currentTurn")] public int CurrentTurn; public ISerializable Clone() { var model = (ChangesModel)MemberwiseClone(); model.Tiles = Tiles.Select(t => (TileModel)t.Clone()).ToArray(); model.Actions = Actions.Select(a => (ActionModel)a.Clone()).ToArray(); return model; } } }
using System.Linq; using Newtonsoft.Json; namespace BotOnBot.Backend.DataModel { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class ChangesModel : ISerializable { [JsonProperty(PropertyName = "tiles")] public TileModel[] Tiles; [JsonProperty(PropertyName = "currentTurn")] public int CurrentTurn; public ISerializable Clone() { var model = (ChangesModel)MemberwiseClone(); model.Tiles = Tiles.Select(t => (TileModel)t.Clone()).ToArray(); return model; } } }
mit
C#
97efccaf491b83dc950efdccf9bdbe01a91c2aac
Fix oops
khellang/Middleware,khellang/Middleware
src/ProblemDetails/ProblemDetailsExtensions.cs
src/ProblemDetails/ProblemDetailsExtensions.cs
using System; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; namespace Hellang.Middleware.ProblemDetails { public static class ProblemDetailsExtensions { public static IServiceCollection AddProblemDetails(this IServiceCollection services) { return services.AddProblemDetails(configure: null); } public static IServiceCollection AddProblemDetails(this IServiceCollection services, Action<ProblemDetailsOptions> configure) { if (configure != null) { services.Configure(configure); } services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<ProblemDetailsOptions>, ProblemDetailsOptionsSetup>()); return services; } public static IApplicationBuilder UseProblemDetails(this IApplicationBuilder app) { return app.UseMiddleware<ProblemDetailsMiddleware>(); } [Obsolete("This overload is deprecated. Please call " + nameof(IServiceCollection) + "." + nameof(AddProblemDetails) + " and use the parameterless overload instead.")] public static IApplicationBuilder UseProblemDetails(this IApplicationBuilder app, Action<ProblemDetailsOptions> configure) { var options = new ProblemDetailsOptions(); configure?.Invoke(options); // Try to pull the IConfigureOptions<ProblemDetailsOptions> service from the container // in case the user has called AddProblemDetails and still use this overload. // If the setup hasn't been configured. Create an instance explicitly and use that. var setup = app.ApplicationServices.GetService<IConfigureOptions<ProblemDetailsOptions>>() ?? new ProblemDetailsOptionsSetup(); setup.Configure(options); return app.UseMiddleware<ProblemDetailsMiddleware>(Options.Create(options)); } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; namespace Hellang.Middleware.ProblemDetails { public static class ProblemDetailsExtensions { public static IServiceCollection AddProblemDetails(this IServiceCollection services) { return services.AddProblemDetails(configure: null); } public static IServiceCollection AddProblemDetails(this IServiceCollection services, Action<ProblemDetailsOptions> configure) { if (configure != null) { services.Configure(configure); } services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<ProblemDetailsOptions>, ProblemDetailsOptionsSetup>()); return services; } public static IApplicationBuilder UseProblemDetails(this IApplicationBuilder app) { return app.UseMiddleware<ProblemDetailsMiddleware>(); } [Obsolete("This overload is deprecated. Please call " + nameof(IServiceCollection) + "." + nameof(AddProblemDetails) + " and use the parameterless overload instead.")] public static IApplicationBuilder UseProblemDetails(this IApplicationBuilder app, Action<ProblemDetailsOptions> configure) { var options = new ProblemDetailsOptions(); configure?.Invoke(options); var setup = app.ApplicationServices.GetService<IConfigureOptions<ProblemDetailsOptions>>(); setup?.Configure(options); return app.UseMiddleware<ProblemDetailsMiddleware>(Options.Create(options)); } } }
mit
C#
ae148ffd9bb3cb2f04172385fdce49c17b391cf3
Fix bug.
bozoweed/Sanderling,exodus444/Sanderling,Arcitectus/Sanderling
src/sample/Sanderling.Sample.Read/Extension.cs
src/sample/Sanderling.Sample.Read/Extension.cs
using Mono.Terminal; using System; using System.Linq; namespace Sanderling.Sample.Read { static public class Extension { static public int? TryParseInt(this string @string) { int Int; if (!int.TryParse(@string, out Int)) { return null; } return Int; } static public string ConsoleEditString(this string @default, string prefix = null) { var Editor = new LineEditor(null); Editor.TabAtStartCompletes = true; return Editor.Edit(prefix ?? "", @default); } static public int? GetEveOnlineClientProcessId() => System.Diagnostics.Process.GetProcesses() ?.FirstOrDefault(process => { try { return string.Equals("ExeFile.exe", process?.MainModule?.ModuleName, StringComparison.InvariantCultureIgnoreCase); } catch { } return false; }) ?.Id; static public config ConfigReadFromConsole() { var EveOnlineClientProcessIdDefault = GetEveOnlineClientProcessId(); Console.WriteLine("id of process assumed to be eve online client: " + (EveOnlineClientProcessIdDefault?.ToString() ?? "null")); var EveOnlineClientProcessIdString = (EveOnlineClientProcessIdDefault?.ToString() ?? "")?.ConsoleEditString("enter id of eve online client process >"); var EveOnlineClientProcessId = EveOnlineClientProcessIdString?.TryParseInt(); if (!EveOnlineClientProcessId.HasValue) { Console.WriteLine("expected an integer."); return null; } Console.WriteLine(); var LicenseServerAddress = ExeConfig.ConfigApiVersionAddressDefault.ConsoleEditString("enter license server address >"); Console.WriteLine(); var LicenseKey = ExeConfig.ConfigLicenseKeyDefault.ConsoleEditString("enter license key >"); var ServiceId = ExeConfig.ConfigServiceId.ConsoleEditString("enter service id >"); return new config() { EveOnlineClientProcessId = EveOnlineClientProcessId.Value, LicenseServerAddress = LicenseServerAddress, LicenseKey = LicenseKey, ServiceId = ServiceId, }; } } }
using Mono.Terminal; using System; using System.Linq; namespace Sanderling.Sample.Read { static public class Extension { static public int? TryParseInt(this string @string) { int Int; if (!int.TryParse(@string, out Int)) { return null; } return Int; } static public string ConsoleEditString(this string @default, string prefix = null) { var Editor = new LineEditor(null); Editor.TabAtStartCompletes = true; return Editor.Edit(prefix ?? "", @default); } static public int? GetEveOnlineClientProcessId() => System.Diagnostics.Process.GetProcesses() ?.FirstOrDefault(process => { try { return string.Equals("ExeFile.exe", process?.MainModule?.ModuleName, StringComparison.InvariantCultureIgnoreCase); } catch { } return false; }) ?.Id; static public config ConfigReadFromConsole() { var EveOnlineClientProcessIdDefault = GetEveOnlineClientProcessId(); Console.WriteLine("id of process assumed to be eve online client: " + (EveOnlineClientProcessIdDefault?.ToString() ?? "null")); var EveOnlineClientProcessIdString = (EveOnlineClientProcessIdDefault?.ToString() ?? "")?.ConsoleEditString("enter id of eve online client process >"); var EveOnlineClientProcessId = EveOnlineClientProcessIdString?.TryParseInt(); if (!EveOnlineClientProcessId.HasValue) { Console.WriteLine("expected an integer."); return null; } Console.WriteLine(); var LicenseServerAddress = ExeConfig.ConfigApiVersionAddressDefault.ConsoleEditString("enter license server address >"); Console.WriteLine(); var LicenseKey = ExeConfig.ConfigLicenseKeyFree.ConsoleEditString("enter license key >"); var ServiceId = ExeConfig.ConfigServiceId.ConsoleEditString("enter service id >"); return new config() { EveOnlineClientProcessId = EveOnlineClientProcessId.Value, LicenseServerAddress = LicenseServerAddress, LicenseKey = LicenseKey, ServiceId = ServiceId, }; } } }
apache-2.0
C#
465f9c0da48983237671540fc15bf49c4dfa87eb
Fix ActionTween (call base ctor)
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
bindings/src/Actions/Intervals/ActionTween.cs
bindings/src/Actions/Intervals/ActionTween.cs
using System; namespace Urho.Actions { public class ActionTween : FiniteTimeAction { #region Properties public float From { get; private set; } public float To { get; private set; } public string Key { get; private set; } public Action<float, string> TweenAction { get; private set; } #endregion Properties #region Constructors public ActionTween (float duration, string key, float from, float to, Action<float,string> tweenAction) : base(duration) { Key = key; To = to; From = from; TweenAction = tweenAction; } #endregion Constructors protected internal override ActionState StartAction(Node target) { return new ActionTweenState (this, target); } public override FiniteTimeAction Reverse () { return new ActionTween (Duration, Key, To, From, TweenAction); } } public class ActionTweenState : FiniteTimeActionState { protected float Delta; protected float From { get; private set; } protected float To { get; private set; } protected string Key { get; private set; } protected Action<float, string> TweenAction { get; private set; } public ActionTweenState (ActionTween action, Node target) : base (action, target) { TweenAction = action.TweenAction; From = action.From; To = action.To; Key = action.Key; Delta = To - From; } public override void Update (float time) { float amt = To - Delta * (1 - time); TweenAction?.Invoke (amt, Key); } } }
using System; namespace Urho.Actions { public class ActionTween : FiniteTimeAction { #region Properties public float From { get; private set; } public float To { get; private set; } public string Key { get; private set; } public Action<float, string> TweenAction { get; private set; } #endregion Properties #region Constructors public ActionTween (float duration, string key, float from, float to, Action<float,string> tweenAction) { Key = key; To = to; From = from; TweenAction = tweenAction; } #endregion Constructors protected internal override ActionState StartAction(Node target) { return new ActionTweenState (this, target); } public override FiniteTimeAction Reverse () { return new ActionTween (Duration, Key, To, From, TweenAction); } } public class ActionTweenState : FiniteTimeActionState { protected float Delta; protected float From { get; private set; } protected float To { get; private set; } protected string Key { get; private set; } protected Action<float, string> TweenAction { get; private set; } public ActionTweenState (ActionTween action, Node target) : base (action, target) { TweenAction = action.TweenAction; From = action.From; To = action.To; Key = action.Key; Delta = To - From; } public override void Update (float time) { float amt = To - Delta * (1 - time); TweenAction?.Invoke (amt, Key); } } }
mit
C#
a25be57442f96ca016c0cc84c32dbd0395295785
Enable legacy timestamps for Npgsql. Fixes #1762
PiranhaCMS/piranha.core,PiranhaCMS/piranha.core,PiranhaCMS/piranha.core,PiranhaCMS/piranha.core
data/Piranha.Data.EF.PostgreSql/PostgreSqlDb.cs
data/Piranha.Data.EF.PostgreSql/PostgreSqlDb.cs
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using Microsoft.EntityFrameworkCore; namespace Piranha.Data.EF.PostgreSql { [NoCoverage] public sealed class PostgreSqlDb : Db<PostgreSqlDb> { /// <summary> /// Default constructor. /// </summary> /// <param name="options">Configuration options</param> public PostgreSqlDb(DbContextOptions<PostgreSqlDb> options) : base(options) { AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); } } }
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using Microsoft.EntityFrameworkCore; namespace Piranha.Data.EF.PostgreSql { [NoCoverage] public sealed class PostgreSqlDb : Db<PostgreSqlDb> { /// <summary> /// Default constructor. /// </summary> /// <param name="options">Configuration options</param> public PostgreSqlDb(DbContextOptions<PostgreSqlDb> options) : base(options) { } } }
mit
C#
7323075aad2ef99080266bd644d2500a9d62dbfc
Add custom assembly name
tzachshabtay/MonoAGS
Source/Demo/iOS/Main.cs
Source/Demo/iOS/Main.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using AGS.Engine; using AGS.Engine.IOS; using DemoGame; using Foundation; using UIKit; namespace DemoQuest.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { Debug.WriteLine("Main started"); ResourceLoader.CustomAssemblyName = "DemoQuest.iOS"; IOSGameWindow.Instance.StartGame = DemoStarter.Run; AGSEngineIOS.SetAssembly(); // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. Debug.WriteLine("Running UIApplication"); UIApplication.Main(args, null, "AppDelegate"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using AGS.Engine.IOS; using DemoGame; using Foundation; using UIKit; namespace DemoQuest.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { Debug.WriteLine("Main started"); IOSGameWindow.Instance.StartGame = DemoStarter.Run; AGSEngineIOS.SetAssembly(); // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. Debug.WriteLine("Running UIApplication"); UIApplication.Main(args, null, "AppDelegate"); } } }
artistic-2.0
C#
10e651b35876b298dedc4b601474548e70b006fd
Use lowercase OWIN keys per convention
stormpath/stormpath-dotnet-owin-middleware
src/Stormpath.Owin.Abstractions/OwinKeys.cs
src/Stormpath.Owin.Abstractions/OwinKeys.cs
// <copyright file="OwinKeys.cs" company="Stormpath, Inc."> // Copyright (c) 2016 Stormpath, 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. // </copyright> namespace Stormpath.Owin.Abstractions { /// <summary> /// OWIN keys, as defined in <see href="http://owin.org/html/spec/owin-1.0.html"/>. /// </summary> public static class OwinKeys { public static readonly string RequestBody = "owin.RequestBody"; public static readonly string RequestHeaders = "owin.RequestHeaders"; public static readonly string RequestMethod = "owin.RequestMethod"; public static readonly string RequestPath = "owin.RequestPath"; public static readonly string RequestPathBase = "owin.RequestPathBase"; public static readonly string RequestProtocol = "owin.RequestProtocol"; public static readonly string RequestQueryString = "owin.RequestQueryString"; public static readonly string RequestScheme = "owin.RequestScheme"; public static readonly string RequestUser = "owin.RequestUser"; public static readonly string RequestUserLegacy = "server.User"; public static readonly string ResponseBody = "owin.ResponseBody"; public static readonly string ResponseHeaders = "owin.ResponseHeaders"; public static readonly string ResponseStatusCode = "owin.ResponseStatusCode"; public static readonly string ResponseReasonPhrase = "owin.ResponseReasonPhrase"; public static readonly string ResponseProtocol = "owin.ResponseProtocol"; public static readonly string CallCancelled = "owin.CallCancelled"; public static readonly string OnSendingHeaders = "server.OnSendingHeaders"; public static readonly string StormpathClient = "stormpath.RequestClient"; public static readonly string StormpathUser = "stormpath.RequestUser"; public static readonly string StormpathUserScheme = "stormpath.RequestUserScheme"; public static readonly string StormpathConfiguration = "stormpath.Configuration"; } }
// <copyright file="OwinKeys.cs" company="Stormpath, Inc."> // Copyright (c) 2016 Stormpath, 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. // </copyright> namespace Stormpath.Owin.Abstractions { /// <summary> /// OWIN keys, as defined in <see href="http://owin.org/html/spec/owin-1.0.html"/>. /// </summary> public static class OwinKeys { public static readonly string RequestBody = "owin.RequestBody"; public static readonly string RequestHeaders = "owin.RequestHeaders"; public static readonly string RequestMethod = "owin.RequestMethod"; public static readonly string RequestPath = "owin.RequestPath"; public static readonly string RequestPathBase = "owin.RequestPathBase"; public static readonly string RequestProtocol = "owin.RequestProtocol"; public static readonly string RequestQueryString = "owin.RequestQueryString"; public static readonly string RequestScheme = "owin.RequestScheme"; public static readonly string RequestUser = "owin.RequestUser"; public static readonly string RequestUserLegacy = "server.User"; public static readonly string ResponseBody = "owin.ResponseBody"; public static readonly string ResponseHeaders = "owin.ResponseHeaders"; public static readonly string ResponseStatusCode = "owin.ResponseStatusCode"; public static readonly string ResponseReasonPhrase = "owin.ResponseReasonPhrase"; public static readonly string ResponseProtocol = "owin.ResponseProtocol"; public static readonly string CallCancelled = "owin.CallCancelled"; public static readonly string OnSendingHeaders = "server.OnSendingHeaders"; public static readonly string StormpathClient = "Stormpath.RequestClient"; public static readonly string StormpathUser = "Stormpath.RequestUser"; public static readonly string StormpathUserScheme = "Stormpath.RequestUserScheme"; public static readonly string StormpathConfiguration = "Stormpath.Configuration"; } }
apache-2.0
C#
bb1955cd546a83881ff94f44ab43c29fee46e3d1
use of repository
Nexusger/GetTheBibTeX2,Nexusger/GetTheBibTeX2
Dblp.WebUi/Controllers/PrefetchController.cs
Dblp.WebUi/Controllers/PrefetchController.cs
using System.Collections.Generic; using System.Linq; using System.Web.Http; using Dblp.Domain.Abstract; using Dblp.Domain.Entities; namespace Dblp.WebUi.Controllers { public class PrefetchController : ApiController { private IDblpRepository _repository; public PrefetchController(IDblpRepository repository) { _repository = repository; } // GET: api/Prefetch [HttpGet] public IEnumerable<SearchResult> GetSearchResults(string id) { if (id.Equals("person")) { return _repository.SearchResults.Where(sr => sr.SearchResultSourceType == SearchResultSourceType.Person).Take(100); } return _repository.SearchResults.Where(sr => sr.SearchResultSourceType != SearchResultSourceType.Person).Take(100); } } }
using System.Collections.Generic; using System.Web.Http; using Dblp.Domain.Entities; using Dblp.WebUi.Models; namespace Dblp.WebUi.Controllers { public class PrefetchController : ApiController { // GET: api/Prefetch public IEnumerable<SearchResultViewModel> Get() { var mockResult = new List<SearchResultViewModel>() { new SearchResultViewModel("homepages/d/TorbenDohrn", "none", "Torben Dohrn", SearchResultSourceType.Person), new SearchResultViewModel("homepages/d/FabianDohrn", "none", "Fabian Dohrn", SearchResultSourceType.Person), new SearchResultViewModel("conf/l/lak", "none", "Learning Analyics Konference", SearchResultSourceType.Conference) }; return mockResult; } // GET: api/Prefetch/5 public SearchResultViewModel Get(int id) { return new SearchResultViewModel("homepages/d/TorbenDohrn", "none", "Torben Dohrn", SearchResultSourceType.Person); } } }
mit
C#
a9f10a27e1645409940d4ea7582532f99ac4775d
Fix naming.
Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x
src/unity/Runtime/Services/IAdsManager.cs
src/unity/Runtime/Services/IAdsManager.cs
using System; using System.Threading.Tasks; namespace EE { public class AdsObserver { public Action OnClicked { get; set; } } public interface IAdsManager : IObserverManager<AdsObserver> { bool IsBannerAdLoaded { get; } bool IsBannerAdVisible { get; set; } (float, float) BannerAdAnchor { get; set; } (float, float) BannerAdPosition { get; set; } (float, float) BannerAdSize { get; set; } Task<AdResult> ShowAppOpenAd(); Task<AdResult> ShowInterstitialAd(); Task<AdResult> ShowRewardedAd(); } }
using System; using System.Threading.Tasks; namespace EE { public class AdsObserver { public Action OnClicked { get; set; } } public interface IAdsManager : IObserverManager<AdsObserver> { bool isBannerAdLoaded { get; } bool IsBannerAdVisible { get; set; } (float, float) BannerAdAnchor { get; set; } (float, float) BannerAdPosition { get; set; } (float, float) BannerAdSize { get; set; } Task<AdResult> ShowAppOpenAd(); Task<AdResult> ShowInterstitialAd(); Task<AdResult> ShowRewardedAd(); } }
mit
C#
b3c482ad1f60f3226cc7ae693369a828bb166266
Use static class for static methods.
theraot/Theraot
Framework.Core/System/Threading/MonitorEx.cs
Framework.Core/System/Threading/MonitorEx.cs
#if !(LESSTHAN_NET40 || NETSTANDARD1_0) using System.Runtime.CompilerServices; #endif namespace System.Threading { public static class MonitorEx { #if !(LESSTHAN_NET40 || NETSTANDARD1_0) [MethodImpl(MethodImplOptionsEx.AggressiveInlining)] #endif public static void Enter(object obj, ref bool lockTaken) { #if LESSTHAN_NET40 || NETSTANDARD1_0 if (obj is null) { throw new ArgumentNullException(nameof(obj)); } if (lockTaken) { throw new ArgumentException("Lock taken", nameof(lockTaken)); } Monitor.Enter(obj); Volatile.Write(ref lockTaken, true); #else Monitor.Enter(obj, ref lockTaken); #endif } } }
#if !(LESSTHAN_NET40 || NETSTANDARD1_0) using System.Runtime.CompilerServices; #endif namespace System.Threading { public class MonitorEx { #if !(LESSTHAN_NET40 || NETSTANDARD1_0) [MethodImpl(MethodImplOptionsEx.AggressiveInlining)] #endif public static void Enter(object obj, ref bool lockTaken) { #if LESSTHAN_NET40 || NETSTANDARD1_0 if (obj is null) { throw new ArgumentNullException(nameof(obj)); } if (lockTaken) { throw new ArgumentException("Lock taken", nameof(lockTaken)); } Monitor.Enter(obj); Volatile.Write(ref lockTaken, true); #else Monitor.Enter(obj, ref lockTaken); #endif } } }
mit
C#
5a799e2adb9a56c7f107e5e6f705a5961f7bf1bc
Fix query result projection regression
couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net
src/Couchbase.Lite/Query/QuerySelectResult.cs
src/Couchbase.Lite/Query/QuerySelectResult.cs
// // QuerySelectResult.cs // // Author: // Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Diagnostics; using System.Linq; using Couchbase.Lite.Query; namespace Couchbase.Lite.Internal.Query { internal sealed class QuerySelectResult : ISelectResultAs, ISelectResultFrom { internal readonly IExpression Expression; private string _alias; private string _from = String.Empty; internal string ColumnName { get { if (_alias != null) { return _alias; } QueryTypeExpression keyPathExpr = Expression as QueryTypeExpression; var columnName = keyPathExpr?.ColumnName; if(columnName == null) { return null; } return $"{_from}{columnName}"; } } public QuerySelectResult(IExpression expression) { Expression = expression; } public ISelectResult As(string alias) { _alias = alias; return this; } public ISelectResult From(string alias) { _from = $"{alias}."; (Expression as QueryTypeExpression).From(alias); return this; } } }
// // QuerySelectResult.cs // // Author: // Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Diagnostics; using System.Linq; using Couchbase.Lite.Query; namespace Couchbase.Lite.Internal.Query { internal sealed class QuerySelectResult : ISelectResultAs, ISelectResultFrom { internal readonly IExpression Expression; private string _alias; private string _from = String.Empty; internal string ColumnName { get { if (_alias != null) { return _alias; } QueryTypeExpression keyPathExpr = Expression as QueryTypeExpression; var columnName = keyPathExpr?.ColumnName; if(columnName == null) { return null; } return $"{_from}.{columnName}"; } } public QuerySelectResult(IExpression expression) { Expression = expression; } public ISelectResult As(string alias) { _alias = alias; return this; } public ISelectResult From(string alias) { _from = alias; (Expression as QueryTypeExpression).From(alias); return this; } } }
apache-2.0
C#
923d5101f722ae6981bd6511e1d88d090b94a88b
Format comments in ProblemDetails (#39340)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Http/Http.Extensions/src/ProblemDetails.cs
src/Http/Http.Extensions/src/ProblemDetails.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text.Json.Serialization; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Mvc; /// <summary> /// A machine-readable format for specifying errors in HTTP API responses based on https://tools.ietf.org/html/rfc7807. /// </summary> [JsonConverter(typeof(ProblemDetailsJsonConverter))] public class ProblemDetails { /// <summary> /// A URI reference [RFC3986] that identifies the problem type. This specification encourages that, when /// dereferenced, it provide human-readable documentation for the problem type /// (e.g., using HTML [W3C.REC-html5-20141028]). When this member is not present, its value is assumed to be /// "about:blank". /// </summary> [JsonPropertyName("type")] public string? Type { get; set; } /// <summary> /// A short, human-readable summary of the problem type. It SHOULD NOT change from occurrence to occurrence /// of the problem, except for purposes of localization(e.g., using proactive content negotiation; /// see[RFC7231], Section 3.4). /// </summary> [JsonPropertyName("title")] public string? Title { get; set; } /// <summary> /// The HTTP status code([RFC7231], Section 6) generated by the origin server for this occurrence of the problem. /// </summary> [JsonPropertyName("status")] public int? Status { get; set; } /// <summary> /// A human-readable explanation specific to this occurrence of the problem. /// </summary> [JsonPropertyName("detail")] public string? Detail { get; set; } /// <summary> /// A URI reference that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced. /// </summary> [JsonPropertyName("instance")] public string? Instance { get; set; } /// <summary> /// Gets the <see cref="IDictionary{TKey, TValue}"/> for extension members. /// <para> /// Problem type definitions MAY extend the problem details object with additional members. Extension members appear in the same namespace as /// other members of a problem type. /// </para> /// </summary> /// <remarks> /// The round-tripping behavior for <see cref="Extensions"/> is determined by the implementation of the Input \ Output formatters. /// In particular, complex types or collection types may not round-trip to the original type when using the built-in JSON or XML formatters. /// </remarks> [JsonExtensionData] public IDictionary<string, object?> Extensions { get; } = new Dictionary<string, object?>(StringComparer.Ordinal); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text.Json.Serialization; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Mvc; /// <summary> /// A machine-readable format for specifying errors in HTTP API responses based on https://tools.ietf.org/html/rfc7807. /// </summary> [JsonConverter(typeof(ProblemDetailsJsonConverter))] public class ProblemDetails { /// <summary> /// A URI reference [RFC3986] that identifies the problem type. This specification encourages that, when /// dereferenced, it provide human-readable documentation for the problem type /// (e.g., using HTML [W3C.REC-html5-20141028]). When this member is not present, its value is assumed to be /// "about:blank". /// </summary> [JsonPropertyName("type")] public string? Type { get; set; } /// <summary> /// A short, human-readable summary of the problem type.It SHOULD NOT change from occurrence to occurrence /// of the problem, except for purposes of localization(e.g., using proactive content negotiation; /// see[RFC7231], Section 3.4). /// </summary> [JsonPropertyName("title")] public string? Title { get; set; } /// <summary> /// The HTTP status code([RFC7231], Section 6) generated by the origin server for this occurrence of the problem. /// </summary> [JsonPropertyName("status")] public int? Status { get; set; } /// <summary> /// A human-readable explanation specific to this occurrence of the problem. /// </summary> [JsonPropertyName("detail")] public string? Detail { get; set; } /// <summary> /// A URI reference that identifies the specific occurrence of the problem.It may or may not yield further information if dereferenced. /// </summary> [JsonPropertyName("instance")] public string? Instance { get; set; } /// <summary> /// Gets the <see cref="IDictionary{TKey, TValue}"/> for extension members. /// <para> /// Problem type definitions MAY extend the problem details object with additional members. Extension members appear in the same namespace as /// other members of a problem type. /// </para> /// </summary> /// <remarks> /// The round-tripping behavior for <see cref="Extensions"/> is determined by the implementation of the Input \ Output formatters. /// In particular, complex types or collection types may not round-trip to the original type when using the built-in JSON or XML formatters. /// </remarks> [JsonExtensionData] public IDictionary<string, object?> Extensions { get; } = new Dictionary<string, object?>(StringComparer.Ordinal); }
apache-2.0
C#
6998090716543a14fbeb119a96e7a8a9e111ee0a
Add hourly schedule
matteocontrini/locuspocusbot
LocusPocusBot/FetchSchedulerHostedService.cs
LocusPocusBot/FetchSchedulerHostedService.cs
using LocusPocusBot.Rooms; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; namespace LocusPocusBot { public class FetchSchedulerHostedService : IHostedService { private readonly IRoomsService roomsService; private readonly ILogger<FetchSchedulerHostedService> logger; private Timer timer; public FetchSchedulerHostedService(IRoomsService roomsService, ILogger<FetchSchedulerHostedService> logger) { this.roomsService = roomsService; this.logger = logger; } public Task StartAsync(CancellationToken cancellationToken) { this.timer = new Timer( callback: Callback, state: null, dueTime: TimeSpanUntilNextTick(), period: TimeSpan.FromMilliseconds(-1) ); return Fetch(); } async void Callback(object state) { await Fetch(); this.timer.Change( dueTime: TimeSpanUntilNextTick(), period: TimeSpan.FromMilliseconds(-1) ); } private TimeSpan TimeSpanUntilNextTick() { return TimeSpan.FromMinutes(60 - DateTime.UtcNow.Minute); } private async Task Fetch() { Department[] departments = new Department[] { Department.Povo, Department.Mesiano }; foreach (Department department in departments) { this.logger.LogInformation($"Refreshing data for {department.Id}/{department.Name}"); try { department.Rooms = await this.roomsService.LoadRooms(department); } catch (Exception ex) { this.logger.LogError(ex, $"Exception while refreshing {department.Id}/{department.Name}"); } } this.logger.LogInformation("Done refreshing"); } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } }
using LocusPocusBot.Rooms; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; namespace LocusPocusBot { public class FetchSchedulerHostedService : IHostedService { private readonly IRoomsService roomsService; private readonly ILogger<FetchSchedulerHostedService> logger; public FetchSchedulerHostedService(IRoomsService roomsService, ILogger<FetchSchedulerHostedService> logger) { this.roomsService = roomsService; this.logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) { // TODO: schedule every hour await Fetch(); } private async Task Fetch() { Department[] departments = new Department[] { Department.Povo, Department.Mesiano }; foreach (Department department in departments) { this.logger.LogInformation($"Refreshing data for {department.Id}/{department.Name}"); try { department.Rooms = await this.roomsService.LoadRooms(department); } catch (Exception ex) { this.logger.LogError(ex, $"Exception while refreshing {department.Id}/{department.Name}"); } } this.logger.LogInformation("Done refreshing"); } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } }
mit
C#
6f007cd4f0c8a4e9d809eb004b2208a80d236695
add usings for login actions
tblocksharer/tblocksharer,tblocksharer/tblocksharer
src/TBlockSharer/Controllers/HomeController.cs
src/TBlockSharer/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using LinqToTwitter; namespace TBlockSharer.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public async Task<ActionResult> Login() { var auth = new MvcSignInAuthorizer { CredentialStore = new SessionStateCredentialStore { ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"] } }; string callbackUrl = Request.Url.ToString().Replace("Login", "LoginComplete"); return await auth.BeginAuthorizationAsync(new Uri(callbackUrl)); } public async Task<ActionResult> LoginComplete() { var auth = new MvcAuthorizer { CredentialStore = new SessionStateCredentialStore() }; await auth.CompleteAuthorizeAsync(Request.Url); //return View("Index", new Models.Index() { BlockedUsers = new string[] { "hello" } }); return RedirectToAction("Index"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TBlockSharer.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public async Task<ActionResult> Login() { var auth = new MvcSignInAuthorizer { CredentialStore = new SessionStateCredentialStore { ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"] } }; string callbackUrl = Request.Url.ToString().Replace("Login", "LoginComplete"); return await auth.BeginAuthorizationAsync(new Uri(callbackUrl)); } public async Task<ActionResult> LoginComplete() { var auth = new MvcAuthorizer { CredentialStore = new SessionStateCredentialStore() }; await auth.CompleteAuthorizeAsync(Request.Url); //return View("Index", new Models.Index() { BlockedUsers = new string[] { "hello" } }); return RedirectToAction("Index"); } } }
agpl-3.0
C#
d291324046a90cdda55f829ae5f095ad66d97b97
Fix Job ErrorCodes not being set
tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Host/Jobs/JobException.cs
src/Tgstation.Server.Host/Jobs/JobException.cs
using System; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Host.Jobs { /// <summary> /// Operation exceptions thrown from the context of a <see cref="Models.Job"/> /// </summary> public sealed class JobException : Exception { /// <summary> /// The <see cref="Api.Models.ErrorCode"/> associated with the <see cref="JobException"/>. /// </summary> public ErrorCode? ErrorCode { get; set; } /// <summary> /// Construct a <see cref="JobException"/> /// </summary> public JobException() { } /// <summary> /// Construct a <see cref="JobException"/> with a <paramref name="message"/> /// </summary> /// <param name="message">The message for the <see cref="Exception"/></param> public JobException(string message) : base(message) { } /// <summary> /// Construct a <see cref="JobException"/> with a <paramref name="message"/> and <paramref name="innerException"/> /// </summary> /// <param name="message">The message for the <see cref="Exception"/></param> /// <param name="innerException">The inner <see cref="Exception"/> for the nase <see cref="Exception"/></param> public JobException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Construct a <see cref="JobException"/> with a <paramref name="errorCode"/>. /// </summary> /// <param name="errorCode">The associated <see cref="Api.Models.ErrorCode"/>.</param> public JobException(ErrorCode errorCode) : base(errorCode.Describe()) { ErrorCode = errorCode; } /// <summary> /// Construct a <see cref="JobException"/> with a <paramref name="errorCode"/> and <paramref name="innerException"/>. /// </summary> /// <param name="errorCode">The associated <see cref="Api.Models.ErrorCode"/>.</param> /// <param name="innerException">The inner <see cref="Exception"/> for the nase <see cref="Exception"/></param> public JobException(ErrorCode errorCode, Exception innerException) : base(errorCode.Describe(), innerException) { ErrorCode = errorCode; } } }
using System; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Host.Jobs { /// <summary> /// Operation exceptions thrown from the context of a <see cref="Models.Job"/> /// </summary> public sealed class JobException : Exception { /// <summary> /// The <see cref="Api.Models.ErrorCode"/> associated with the <see cref="JobException"/>. /// </summary> public ErrorCode? ErrorCode { get; set; } /// <summary> /// Construct a <see cref="JobException"/> /// </summary> public JobException() { } /// <summary> /// Construct a <see cref="JobException"/> with a <paramref name="message"/> /// </summary> /// <param name="message">The message for the <see cref="Exception"/></param> public JobException(string message) : base(message) { } /// <summary> /// Construct a <see cref="JobException"/> with a <paramref name="message"/> and <paramref name="innerException"/> /// </summary> /// <param name="message">The message for the <see cref="Exception"/></param> /// <param name="innerException">The inner <see cref="Exception"/> for the nase <see cref="Exception"/></param> public JobException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Construct a <see cref="JobException"/> with a <paramref name="errorCode"/>. /// </summary> /// <param name="errorCode">The associated <see cref="Api.Models.ErrorCode"/>.</param> public JobException(ErrorCode errorCode) : base(errorCode.Describe()) { } /// <summary> /// Construct a <see cref="JobException"/> with a <paramref name="errorCode"/> and <paramref name="innerException"/>. /// </summary> /// <param name="errorCode">The associated <see cref="Api.Models.ErrorCode"/>.</param> /// <param name="innerException">The inner <see cref="Exception"/> for the nase <see cref="Exception"/></param> public JobException(ErrorCode errorCode, Exception innerException) : base(errorCode.Describe(), innerException) { } } }
agpl-3.0
C#
fb3576bda16ee05f0240f0bdac359dab788b4bc4
Revert "Swapping Silly UK English ;)"
jongleur1983/Nancy,MetSystem/Nancy,vladlopes/Nancy,thecodejunkie/Nancy,dbolkensteyn/Nancy,anton-gogolev/Nancy,malikdiarra/Nancy,hitesh97/Nancy,EliotJones/NancyTest,Novakov/Nancy,AcklenAvenue/Nancy,AIexandr/Nancy,jongleur1983/Nancy,JoeStead/Nancy,VQComms/Nancy,fly19890211/Nancy,asbjornu/Nancy,lijunle/Nancy,thecodejunkie/Nancy,AIexandr/Nancy,davidallyoung/Nancy,SaveTrees/Nancy,dbolkensteyn/Nancy,AlexPuiu/Nancy,cgourlay/Nancy,jongleur1983/Nancy,wtilton/Nancy,tparnell8/Nancy,jonathanfoster/Nancy,EliotJones/NancyTest,wtilton/Nancy,damianh/Nancy,thecodejunkie/Nancy,jmptrader/Nancy,tparnell8/Nancy,guodf/Nancy,joebuschmann/Nancy,sroylance/Nancy,adamhathcock/Nancy,NancyFx/Nancy,wtilton/Nancy,thecodejunkie/Nancy,phillip-haydon/Nancy,danbarua/Nancy,fly19890211/Nancy,grumpydev/Nancy,Worthaboutapig/Nancy,murador/Nancy,NancyFx/Nancy,grumpydev/Nancy,jchannon/Nancy,felipeleusin/Nancy,jmptrader/Nancy,fly19890211/Nancy,adamhathcock/Nancy,SaveTrees/Nancy,damianh/Nancy,tareq-s/Nancy,khellang/Nancy,charleypeng/Nancy,phillip-haydon/Nancy,anton-gogolev/Nancy,cgourlay/Nancy,phillip-haydon/Nancy,rudygt/Nancy,ccellar/Nancy,nicklv/Nancy,danbarua/Nancy,felipeleusin/Nancy,felipeleusin/Nancy,sadiqhirani/Nancy,grumpydev/Nancy,asbjornu/Nancy,nicklv/Nancy,jonathanfoster/Nancy,murador/Nancy,sloncho/Nancy,guodf/Nancy,jeff-pang/Nancy,JoeStead/Nancy,ayoung/Nancy,albertjan/Nancy,sroylance/Nancy,xt0rted/Nancy,VQComms/Nancy,jeff-pang/Nancy,jchannon/Nancy,dbabox/Nancy,jeff-pang/Nancy,jchannon/Nancy,ccellar/Nancy,vladlopes/Nancy,dbabox/Nancy,nicklv/Nancy,dbolkensteyn/Nancy,jmptrader/Nancy,tsdl2013/Nancy,nicklv/Nancy,duszekmestre/Nancy,Worthaboutapig/Nancy,jongleur1983/Nancy,horsdal/Nancy,JoeStead/Nancy,davidallyoung/Nancy,EIrwin/Nancy,guodf/Nancy,ayoung/Nancy,cgourlay/Nancy,albertjan/Nancy,tparnell8/Nancy,grumpydev/Nancy,cgourlay/Nancy,Novakov/Nancy,jchannon/Nancy,AlexPuiu/Nancy,AlexPuiu/Nancy,duszekmestre/Nancy,sloncho/Nancy,ayoung/Nancy,khellang/Nancy,sadiqhirani/Nancy,horsdal/Nancy,Novakov/Nancy,EliotJones/NancyTest,vladlopes/Nancy,rudygt/Nancy,SaveTrees/Nancy,jonathanfoster/Nancy,xt0rted/Nancy,fly19890211/Nancy,sadiqhirani/Nancy,sroylance/Nancy,charleypeng/Nancy,asbjornu/Nancy,daniellor/Nancy,AIexandr/Nancy,JoeStead/Nancy,tareq-s/Nancy,blairconrad/Nancy,joebuschmann/Nancy,guodf/Nancy,horsdal/Nancy,xt0rted/Nancy,sloncho/Nancy,SaveTrees/Nancy,davidallyoung/Nancy,malikdiarra/Nancy,charleypeng/Nancy,khellang/Nancy,anton-gogolev/Nancy,asbjornu/Nancy,ccellar/Nancy,rudygt/Nancy,jonathanfoster/Nancy,jmptrader/Nancy,blairconrad/Nancy,felipeleusin/Nancy,tsdl2013/Nancy,tareq-s/Nancy,NancyFx/Nancy,albertjan/Nancy,EIrwin/Nancy,joebuschmann/Nancy,rudygt/Nancy,vladlopes/Nancy,charleypeng/Nancy,danbarua/Nancy,Worthaboutapig/Nancy,tsdl2013/Nancy,tparnell8/Nancy,ccellar/Nancy,albertjan/Nancy,damianh/Nancy,tsdl2013/Nancy,dbabox/Nancy,davidallyoung/Nancy,AlexPuiu/Nancy,EIrwin/Nancy,khellang/Nancy,murador/Nancy,MetSystem/Nancy,dbolkensteyn/Nancy,sroylance/Nancy,adamhathcock/Nancy,wtilton/Nancy,sadiqhirani/Nancy,AcklenAvenue/Nancy,MetSystem/Nancy,AIexandr/Nancy,asbjornu/Nancy,blairconrad/Nancy,AcklenAvenue/Nancy,AcklenAvenue/Nancy,VQComms/Nancy,hitesh97/Nancy,VQComms/Nancy,daniellor/Nancy,danbarua/Nancy,lijunle/Nancy,NancyFx/Nancy,xt0rted/Nancy,blairconrad/Nancy,duszekmestre/Nancy,malikdiarra/Nancy,daniellor/Nancy,adamhathcock/Nancy,ayoung/Nancy,tareq-s/Nancy,dbabox/Nancy,malikdiarra/Nancy,jchannon/Nancy,lijunle/Nancy,hitesh97/Nancy,joebuschmann/Nancy,EIrwin/Nancy,horsdal/Nancy,charleypeng/Nancy,lijunle/Nancy,phillip-haydon/Nancy,Novakov/Nancy,hitesh97/Nancy,jeff-pang/Nancy,MetSystem/Nancy,EliotJones/NancyTest,sloncho/Nancy,AIexandr/Nancy,duszekmestre/Nancy,davidallyoung/Nancy,anton-gogolev/Nancy,daniellor/Nancy,VQComms/Nancy,murador/Nancy,Worthaboutapig/Nancy
src/Nancy/ISerializer.cs
src/Nancy/ISerializer.cs
namespace Nancy { using System.Collections.Generic; using System.IO; public interface ISerializer { /// <summary> /// Whether the serializer can serialize the content type /// </summary> /// <param name="contentType">Content type to serialise</param> /// <returns>True if supported, false otherwise</returns> bool CanSerialize(string contentType); /// <summary> /// Gets the list of extensions that the serializer can handle. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value> IEnumerable<string> Extensions { get; } /// <summary> /// Serialize the given model with the given contentType /// </summary> /// <param name="contentType">Content type to serialize into</param> /// <param name="model">Model to serialize</param> /// <param name="outputStream">Output stream to serialize to</param> /// <returns>Serialised object</returns> void Serialize<TModel>(string contentType, TModel model, Stream outputStream); } }
namespace Nancy { using System.Collections.Generic; using System.IO; public interface ISerializer { /// <summary> /// Whether the serializer can serialize the content type /// </summary> /// <param name="contentType">Content type to serialize</param> /// <returns>True if supported, false otherwise</returns> bool CanSerialize(string contentType); /// <summary> /// Gets the list of extensions that the serializer can handle. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value> IEnumerable<string> Extensions { get; } /// <summary> /// Serialize the given model with the given contentType /// </summary> /// <param name="contentType">Content type to serialize into</param> /// <param name="model">Model to serialize</param> /// <param name="outputStream">Output stream to serialize to</param> /// <returns>Serialized object</returns> void Serialize<TModel>(string contentType, TModel model, Stream outputStream); } }
mit
C#
75d2ec597475fa625c96b97332b2fc4d1c141446
Implement IDisposable interface in NumberOfClassificationSystemsTest
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade.Test/Tests/Noark5/NumberOfClassificationSystemsTest.cs
src/Arkivverket.Arkade.Test/Tests/Noark5/NumberOfClassificationSystemsTest.cs
using System; using System.IO; using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Tests; using Arkivverket.Arkade.Tests.Noark5; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.Test.Tests.Noark5 { public class NumberOfClassificationSystemsTest : IDisposable { private Stream _archiveContent; private TestResults RunTest(Stream content) { return new NumberOfClassificationSystems(new ArchiveContentMemoryStreamReader(content)).RunTest(new ArchiveExtraction("123", "")); } [Fact] public void NumberOfClassificationSystemsIsOne() { _archiveContent = new ArchiveBuilder().WithArchivePart().WithClassificationSystem().Build(); TestResults testResults = RunTest(_archiveContent); testResults.AnalysisResults[NumberOfClassificationSystems.AnalysisKeyClassificationSystems].Should().Be("1"); } [Fact] public void NumberOfClassificationSystemsIsTwo() { _archiveContent = new ArchiveBuilder() .WithArchivePart("part 1").WithClassificationSystem("classification system 1") .WithArchivePart("part 2").WithClassificationSystem("classification system 2") .Build(); TestResults testResults = RunTest(_archiveContent); testResults.AnalysisResults[NumberOfClassificationSystems.AnalysisKeyClassificationSystems].Should().Be("2"); } public void Dispose() { _archiveContent.Dispose(); } } }
using System.IO; using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Tests; using Arkivverket.Arkade.Tests.Noark5; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.Test.Tests.Noark5 { public class NumberOfClassificationSystemsTest { private TestResults RunTest(Stream content) { return new NumberOfClassificationSystems(new ArchiveContentMemoryStreamReader(content)).RunTest(new ArchiveExtraction("123", "")); } [Fact] public void NumberOfClassificationSystemsIsOne() { var archiveBuilder = new ArchiveBuilder().WithArchivePart().WithClassificationSystem(); using (Stream archiveContent = archiveBuilder.Build()) { TestResults testResults = RunTest(archiveContent); testResults.AnalysisResults[NumberOfClassificationSystems.AnalysisKeyClassificationSystems].Should().Be("1"); } } [Fact] public void NumberOfClassificationSystemsIsTwo() { var archiveBuilder = new ArchiveBuilder() .WithArchivePart("part 1").WithClassificationSystem("classification system 1") .WithArchivePart("part 2").WithClassificationSystem("classification system 2"); using (Stream archiveContent = archiveBuilder.Build()) { TestResults testResults = RunTest(archiveContent); testResults.AnalysisResults[NumberOfClassificationSystems.AnalysisKeyClassificationSystems].Should().Be("2"); } } } }
agpl-3.0
C#
9aad26e73fee130a0624d8b862d0b8e71d4c173b
Switch to version 1.4.3
Abc-Arbitrage/Zebus,biarne-a/Zebus
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.4.3")] [assembly: AssemblyFileVersion("1.4.3")] [assembly: AssemblyInformationalVersion("1.4.3")]
using System.Reflection; [assembly: AssemblyVersion("1.4.2")] [assembly: AssemblyFileVersion("1.4.2")] [assembly: AssemblyInformationalVersion("1.4.2")]
mit
C#
ea1c50db7b9f8f57439d01ddac9ec462c9fd5ad0
Add OrderingDomainException when the order doesn't exist with id orderId
skynode/eShopOnContainers,andrelmp/eShopOnContainers,skynode/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers
src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs
src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs
using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork; using Ordering.Domain.Exceptions; using System; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories { public class OrderRepository : IOrderRepository { private readonly OrderingContext _context; public IUnitOfWork UnitOfWork { get { return _context; } } public OrderRepository(OrderingContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public Order Add(Order order) { return _context.Orders.Add(order).Entity; } public async Task<Order> GetAsync(int orderId) { return await _context.Orders.FindAsync(orderId) ?? throw new OrderingDomainException($"Not able to get the order. Reason: no valid orderId: {orderId}"); } public void Update(Order order) { _context.Entry(order).State = EntityState.Modified; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork; using System; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories { public class OrderRepository : IOrderRepository { private readonly OrderingContext _context; public IUnitOfWork UnitOfWork { get { return _context; } } public OrderRepository(OrderingContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public Order Add(Order order) { return _context.Orders.Add(order).Entity; } public async Task<Order> GetAsync(int orderId) { return await _context.Orders.FindAsync(orderId); } public void Update(Order order) { _context.Entry(order).State = EntityState.Modified; } } }
mit
C#
6d6925a79a8b5c413daef04fe9ea72d8fbf8f961
Add ReplacementTextChange to OmniSharpInlineHint
shyamnamboodiripad/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,mavasani/roslyn,bartdesmet/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn
src/Tools/ExternalAccess/OmniSharp/InlineHints/OmniSharpInlineHintsService.cs
src/Tools/ExternalAccess/OmniSharp/InlineHints/OmniSharpInlineHintsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.InlineHints; internal static class OmniSharpInlineHintsService { public static async Task<ImmutableArray<OmniSharpInlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, OmniSharpInlineHintsOptions options, CancellationToken cancellationToken) { var service = document.GetRequiredLanguageService<IInlineHintsService>(); var roslynOptions = options.ToInlineHintsOptions(); var hints = await service.GetInlineHintsAsync(document, textSpan, roslynOptions, cancellationToken).ConfigureAwait(false); return hints.SelectAsArray(static h => new OmniSharpInlineHint( h.Span, h.DisplayParts, h.ReplacementTextChange, (document, cancellationToken) => h.GetDescriptionAsync(document, cancellationToken))); } } internal readonly struct OmniSharpInlineHint { private readonly Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>> _getDescriptionAsync; public OmniSharpInlineHint( TextSpan span, ImmutableArray<TaggedText> displayParts, TextChange? replacementTextChange, Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>> getDescriptionAsync) { Span = span; DisplayParts = displayParts; ReplacementTextChange = replacementTextChange; _getDescriptionAsync = getDescriptionAsync; } public readonly TextSpan Span { get; } public readonly ImmutableArray<TaggedText> DisplayParts { get; } public readonly TextChange? ReplacementTextChange { get; } public Task<ImmutableArray<TaggedText>> GetDescriptionAsync(Document document, CancellationToken cancellationToken) => _getDescriptionAsync.Invoke(document, cancellationToken); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.InlineHints; internal static class OmniSharpInlineHintsService { public static async Task<ImmutableArray<OmniSharpInlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, OmniSharpInlineHintsOptions options, CancellationToken cancellationToken) { var service = document.GetRequiredLanguageService<IInlineHintsService>(); var roslynOptions = options.ToInlineHintsOptions(); var hints = await service.GetInlineHintsAsync(document, textSpan, roslynOptions, cancellationToken).ConfigureAwait(false); return hints.SelectAsArray(static h => new OmniSharpInlineHint( h.Span, h.DisplayParts, (document, cancellationToken) => h.GetDescriptionAsync(document, cancellationToken))); } } internal readonly struct OmniSharpInlineHint { private readonly Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>> _getDescriptionAsync; public OmniSharpInlineHint( TextSpan span, ImmutableArray<TaggedText> displayParts, Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>> getDescriptionAsync) { Span = span; DisplayParts = displayParts; _getDescriptionAsync = getDescriptionAsync; } public readonly TextSpan Span { get; } public readonly ImmutableArray<TaggedText> DisplayParts { get; } public Task<ImmutableArray<TaggedText>> GetDescriptionAsync(Document document, CancellationToken cancellationToken) => _getDescriptionAsync.Invoke(document, cancellationToken); }
mit
C#
2485f6692f988393c354d5f4e9af0b962622e976
Handle oddity in watchdog naming convention
dasgarner/xibo-dotnetclient,xibosignage/xibo-dotnetclient
Control/WatchDogManager.cs
Control/WatchDogManager.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace XiboClient.Control { class WatchDogManager { public static void Start() { // Check to see if the WatchDog EXE exists where we expect it to be // Uncomment to test local watchdog install. //string path = @"C:\Program Files (x86)\Xibo Player\watchdog\x86\XiboClientWatchdog.exe"; string path = Path.GetDirectoryName(Application.ExecutablePath) + @"\watchdog\x86\" + ((Application.ProductName != "Xibo") ? Application.ProductName + "Watchdog.exe" : "XiboClientWatchdog.exe"); string args = "-p \"" + Application.ExecutablePath + "\" -l \"" + ApplicationSettings.Default.LibraryPath + "\""; // Start it if (File.Exists(path)) { try { Process process = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.CreateNoWindow = true; info.WindowStyle = ProcessWindowStyle.Hidden; info.FileName = "cmd.exe"; info.Arguments = "/c start \"watchdog\" \"" + path + "\" " + args; process.StartInfo = info; process.Start(); } catch (Exception e) { Trace.WriteLine(new LogMessage("WatchDogManager - Start", "Unable to start: " + e.Message), LogType.Error.ToString()); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace XiboClient.Control { class WatchDogManager { public static void Start() { // Check to see if the WatchDog EXE exists where we expect it to be // Uncomment to test local watchdog install. //string path = @"C:\Program Files (x86)\Xibo Player\watchdog\x86\XiboClientWatchdog.exe"; string path = Path.GetDirectoryName(Application.ExecutablePath) + @"\watchdog\x86\" + Application.ProductName + "ClientWatchdog.exe"; string args = "-p \"" + Application.ExecutablePath + "\" -l \"" + ApplicationSettings.Default.LibraryPath + "\""; // Start it if (File.Exists(path)) { try { Process process = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.CreateNoWindow = true; info.WindowStyle = ProcessWindowStyle.Hidden; info.FileName = "cmd.exe"; info.Arguments = "/c start \"watchdog\" \"" + path + "\" " + args; process.StartInfo = info; process.Start(); } catch (Exception e) { Trace.WriteLine(new LogMessage("WatchDogManager - Start", "Unable to start: " + e.Message), LogType.Error.ToString()); } } } } }
agpl-3.0
C#
5b1989765029ba46ed70469d29f741c539c8bfae
Update ISiteVariable.cs
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
src/api/ISiteVariable.cs
src/api/ISiteVariable.cs
// Copyright 2004-2006 University of Wisconsin // All rights reserved. // // Contributors: // James Domingo, UW-Madison, Forest Landscape Ecology Lab namespace Landis.SpatialModeling { /// <summary> /// Represents a variable with values for the sites on a landscape. /// </summary> public interface ISiteVariable { /// <summary> /// The data type of the values. /// </summary> System.Type DataType { get; } //--------------------------------------------------------------------- /// <summary> /// Indicates whether the inactive sites share a common value or have /// distinct values. /// </summary> InactiveSiteMode Mode { get; } //--------------------------------------------------------------------- /// <summary> /// The landscape that the site variable was created for. /// </summary> ILandscape Landscape { get; } } }
// Copyright 2004-2006 University of Wisconsin // All rights reserved. // // The copyright holders license this file under the New (3-clause) BSD // License (the "License"). You may not use this file except in // compliance with the License. A copy of the License is available at // // http://www.opensource.org/licenses/BSD-3-Clause // // and is included in the NOTICE.txt file distributed with this work. // // Contributors: // James Domingo, UW-Madison, Forest Landscape Ecology Lab namespace Landis.SpatialModeling { /// <summary> /// Represents a variable with values for the sites on a landscape. /// </summary> public interface ISiteVariable { /// <summary> /// The data type of the values. /// </summary> System.Type DataType { get; } //--------------------------------------------------------------------- /// <summary> /// Indicates whether the inactive sites share a common value or have /// distinct values. /// </summary> InactiveSiteMode Mode { get; } //--------------------------------------------------------------------- /// <summary> /// The landscape that the site variable was created for. /// </summary> ILandscape Landscape { get; } } }
apache-2.0
C#
735f89b2eb0116a12d3e4afd4d60245e75d96d1b
Fix GlobalSuppressions
atata-framework/atata,atata-framework/atata
test/Atata.UnitTests/GlobalSuppressions.cs
test/Atata.UnitTests/GlobalSuppressions.cs
using System.Diagnostics.CodeAnalysis; #pragma warning disable S103 // Lines should not be too long [assembly: SuppressMessage("Major Code Smell", "S2743:Static fields should not be used in generic types", Justification = "<Pending>", Scope = "member", Target = "~F:Atata.UnitTests.DataProvision.DataVerificationProviderExtensionMethodTests.ExtensionMethodTestFixture`2.s_testSuiteData")] [assembly: SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "<Pending>", Scope = "member", Target = "~M:Atata.UnitTests.DataProvision.DataVerificationProviderExtensionMethodTests.ExtensionMethodTestFixture`2.GetPassFunctionsTestCases(System.String)~System.Collections.Generic.IEnumerable{NUnit.Framework.TestCaseData}")] [assembly: SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "<Pending>", Scope = "member", Target = "~M:Atata.UnitTests.DataProvision.DataVerificationProviderExtensionMethodTests.ExtensionMethodTestFixture`2.GetFailFunctionsTestCases(System.String)~System.Collections.Generic.IEnumerable{NUnit.Framework.TestCaseData}")] [assembly: SuppressMessage("Naming", "CA1720:Identifier contains type name", Justification = "<Pending>", Scope = "member", Target = "~P:Atata.UnitTests.DataProvision.EnumerableProviderTests.TestOwner.Object")] #pragma warning restore S103 // Lines should not be too long
using System.Diagnostics.CodeAnalysis; #pragma warning disable S103 // Lines should not be too long [assembly: SuppressMessage("Major Code Smell", "S2743:Static fields should not be used in generic types", Justification = "<Pending>", Scope = "member", Target = "~F:Atata.Tests.DataProvision.DataVerificationProviderExtensionMethodTests.ExtensionMethodTestFixture`2.s_testSuiteData")] [assembly: SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "<Pending>", Scope = "member", Target = "~M:Atata.Tests.DataProvision.DataVerificationProviderExtensionMethodTests.ExtensionMethodTestFixture`2.GetPassFunctionsTestCases(System.String)~System.Collections.Generic.IEnumerable{NUnit.Framework.TestCaseData}")] [assembly: SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "<Pending>", Scope = "member", Target = "~M:Atata.Tests.DataProvision.DataVerificationProviderExtensionMethodTests.ExtensionMethodTestFixture`2.GetFailFunctionsTestCases(System.String)~System.Collections.Generic.IEnumerable{NUnit.Framework.TestCaseData}")] [assembly: SuppressMessage("Naming", "CA1720:Identifier contains type name", Justification = "<Pending>", Scope = "member", Target = "~P:Atata.Tests.DataProvision.EnumerableProviderTests.TestOwner.Object")] #pragma warning restore S103 // Lines should not be too long
apache-2.0
C#
862f0e0d2ecb61a86faa9100469422705f8bf622
Fix BL-3614 Crash while checking for keyman
StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop
src/BloomExe/web/controllers/KeybordingConfigAPI.cs
src/BloomExe/web/controllers/KeybordingConfigAPI.cs
using System; using System.Linq; using System.Windows.Forms; using Bloom.Api; namespace Bloom.web.controllers { class KeybordingConfigApi { public void RegisterWithServer(EnhancedImageServer server) { server.RegisterEndpointHandler("keyboarding/useLongPress", (ApiRequest request) => { try { //detect if some keyboarding system is active, e.g. KeyMan. If it is, don't enable LongPress var form = Application.OpenForms.Cast<Form>().Last(); request.ReplyWithText(SIL.Windows.Forms.Keyboarding.KeyboardController.IsFormUsingInputProcessor(form) ? "false" : "true"); } catch(Exception error) { request.ReplyWithText("true"); // This is arbitrary. I don't know if it's better to assume keyman, or not. NonFatalProblem.Report(ModalIf.None, PassiveIf.All, "Error checking for keyman","", error); } }, handleOnUiThread:false); } } }
using System.Linq; using System.Windows.Forms; using Bloom.Api; namespace Bloom.web.controllers { class KeybordingConfigApi { public void RegisterWithServer(EnhancedImageServer server) { server.RegisterEndpointHandler("keyboarding/useLongPress", (ApiRequest request) => { //detect if some keyboarding system is active, e.g. KeyMan. If it is, don't enable LongPress var form = Application.OpenForms.Cast<Form>().Last(); request.ReplyWithText(SIL.Windows.Forms.Keyboarding.KeyboardController.IsFormUsingInputProcessor(form)?"false":"true"); }); } } }
mit
C#
5903462ec49affa057b4ee64bbd42d97c94e6972
Update Demo
sunkaixuan/SqlSugar
Src/Asp.Net/PgSqlTest/UnitTest/UCodeFirst.cs
Src/Asp.Net/PgSqlTest/UnitTest/UCodeFirst.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { public partial class NewUnitTest { public static void CodeFirst() { if (Db.DbMaintenance.IsAnyTable("UnitCodeTest1", false)) Db.DbMaintenance.DropTable("UnitCodeTest1"); Db.CodeFirst.InitTables<UnitCodeTest1>(); Db.CodeFirst.InitTables<UnitCodeTest1>(); } public class UnitCodeTest1 { [SqlSugar.SugarColumn(IndexGroupNameList = new string[] { "group1" })] public int Id { get; set; } [SqlSugar.SugarColumn(DefaultValue="now()", IndexGroupNameList =new string[] {"group1" } )] public DateTime? CreateDate { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { public partial class NewUnitTest { public static void CodeFirst() { if (Db.DbMaintenance.IsAnyTable("UnitCodeTest1", false)) Db.DbMaintenance.DropTable("UnitCodeTest1"); Db.CodeFirst.InitTables<UnitCodeTest1>(); } public class UnitCodeTest1 { [SqlSugar.SugarColumn(IndexGroupNameList = new string[] { "group1" })] public int Id { get; set; } [SqlSugar.SugarColumn(DefaultValue="now()", IndexGroupNameList =new string[] {"group1" } )] public DateTime? CreateDate { get; set; } } } }
apache-2.0
C#
b1dc7bbda59c05193ef1e5dcfad44f69dcfb0cb0
Allow config.json path to work on non-Windows OS
Workshop2/noobot,noobot/noobot
src/Noobot.Core/Configuration/ConfigReader.cs
src/Noobot.Core/Configuration/ConfigReader.cs
using System; using System.IO; using System.Reflection; using Newtonsoft.Json.Linq; namespace Noobot.Core.Configuration { public class ConfigReader : IConfigReader { private JObject _currentJObject; private readonly string _configLocation; private readonly object _lock = new object(); private static readonly string DEFAULT_LOCATION = Path.Combine("configuration", "config.json"); private const string SLACKAPI_CONFIGVALUE = "slack:apiToken"; public ConfigReader() : this(DEFAULT_LOCATION) { } public ConfigReader(string configurationFile) { _configLocation = configurationFile; } public bool HelpEnabled { get; set; } = true; public bool StatsEnabled { get; set; } = true; public bool AboutEnabled { get; set; } = true; public string SlackApiKey => GetConfigEntry<string>(SLACKAPI_CONFIGVALUE); public T GetConfigEntry<T>(string entryName) { return GetJObject().Value<T>(entryName); } private JObject GetJObject() { lock (_lock) { if (_currentJObject == null) { string assemblyLocation = AssemblyLocation(); string fileName = Path.Combine(assemblyLocation, _configLocation); string json = File.ReadAllText(fileName); _currentJObject = JObject.Parse(json); } } return _currentJObject; } private string AssemblyLocation() { var assembly = Assembly.GetExecutingAssembly(); var codebase = new Uri(assembly.CodeBase); var path = Path.GetDirectoryName(codebase.LocalPath); return path; } } }
using System; using System.IO; using System.Reflection; using Newtonsoft.Json.Linq; namespace Noobot.Core.Configuration { public class ConfigReader : IConfigReader { private JObject _currentJObject; private readonly string _configLocation; private readonly object _lock = new object(); private const string DEFAULT_LOCATION = @"configuration\config.json"; private const string SLACKAPI_CONFIGVALUE = "slack:apiToken"; public ConfigReader() : this(DEFAULT_LOCATION) { } public ConfigReader(string configurationFile) { _configLocation = configurationFile; } public bool HelpEnabled { get; set; } = true; public bool StatsEnabled { get; set; } = true; public bool AboutEnabled { get; set; } = true; public string SlackApiKey => GetConfigEntry<string>(SLACKAPI_CONFIGVALUE); public T GetConfigEntry<T>(string entryName) { return GetJObject().Value<T>(entryName); } private JObject GetJObject() { lock (_lock) { if (_currentJObject == null) { string assemblyLocation = AssemblyLocation(); string fileName = Path.Combine(assemblyLocation, _configLocation); string json = File.ReadAllText(fileName); _currentJObject = JObject.Parse(json); } } return _currentJObject; } private string AssemblyLocation() { var assembly = Assembly.GetExecutingAssembly(); var codebase = new Uri(assembly.CodeBase); var path = Path.GetDirectoryName(codebase.LocalPath); return path; } } }
mit
C#
c380c868d57ac4c47b5687a02e805f2ebeda8d81
Reduce memory logging interval to 5 mins
canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor
src/SyncTrayzor/Services/MemoryUsageLogger.cs
src/SyncTrayzor/Services/MemoryUsageLogger.cs
using NLog; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace SyncTrayzor.Services { public class MemoryUsageLogger { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); private static readonly string[] sizes = { "B", "KB", "MB", "GB" }; private static readonly TimeSpan pollInterval = TimeSpan.FromMinutes(5); private readonly Timer timer; private readonly Process process; public bool Enabled { get { return this.timer.Enabled; } set { this.timer.Enabled = value; } } public MemoryUsageLogger() { this.process = Process.GetCurrentProcess(); this.timer = new Timer() { AutoReset = true, Interval = pollInterval.TotalMilliseconds, }; this.timer.Elapsed += (o, e) => { logger.Debug("Working Set: {0}. Private Memory Size: {1}. GC Total Memory: {2}", this.BytesToHuman(this.process.WorkingSet64), this.BytesToHuman(this.process.PrivateMemorySize64), this.BytesToHuman(GC.GetTotalMemory(false))); }; } private string BytesToHuman(long bytes) { // http://stackoverflow.com/a/281679/1086121 int order = 0; while (bytes >= 1024 && order + 1 < sizes.Length) { order++; bytes = bytes / 1024; } return String.Format("{0:0.#}{1}", bytes, sizes[order]); } } }
using NLog; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace SyncTrayzor.Services { public class MemoryUsageLogger { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); private static readonly string[] sizes = { "B", "KB", "MB", "GB" }; private static readonly TimeSpan pollInterval = TimeSpan.FromMinutes(30); private readonly Timer timer; private readonly Process process; public bool Enabled { get { return this.timer.Enabled; } set { this.timer.Enabled = value; } } public MemoryUsageLogger() { this.process = Process.GetCurrentProcess(); this.timer = new Timer() { AutoReset = true, Interval = pollInterval.TotalMilliseconds, }; this.timer.Elapsed += (o, e) => { logger.Debug("Working Set: {0}. Private Memory Size: {1}. GC Total Memory: {2}", this.BytesToHuman(this.process.WorkingSet64), this.BytesToHuman(this.process.PrivateMemorySize64), this.BytesToHuman(GC.GetTotalMemory(false))); }; } private string BytesToHuman(long bytes) { // http://stackoverflow.com/a/281679/1086121 int order = 0; while (bytes >= 1024 && order + 1 < sizes.Length) { order++; bytes = bytes / 1024; } return String.Format("{0:0.#}{1}", bytes, sizes[order]); } } }
mit
C#
3bd05d11dececbf9b8fd9a11d00d0711e56fabbb
Implement Prefab based pool.
dimixar/audio-controller-unity
AudioController/Assets/Source/ObjectPool.cs
AudioController/Assets/Source/ObjectPool.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPool : MonoBehaviour { #region Public fields public List<PrefabBasedPool> pools; #endregion #region Public methods and properties public AudioObject GetFreeAudioObject(GameObject prefab = null) { if (prefab == null) return null; return null; } #endregion #region Monobehaviour methods /// <summary> /// Awake is called when the script instance is being loaded. /// </summary> void Awake() { pools = new List<PrefabBasedPool>(); } #endregion } [System.Serializable] public class PrefabBasedPool { public PrefabBasedPool(GameObject prefab) { pool = new List<GameObject>(); this.prefab = prefab; } public GameObject prefab; public List<GameObject> pool; /// <summary> /// Where pooled objects will reside. /// </summary> public Transform parent; public GameObject GetFreeObject() { GameObject freeObj = pool.Find((x) => { var poolable = x.GetComponent<IPoolable>(); return poolable.IsFree(); }); if (freeObj != null) return freeObj; var obj = GameObject.Instantiate(prefab, parent); pool.Add(obj); return obj; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPool : MonoBehaviour { #region Public methods and properties //TODO: Add possibility to differentiate between prefabs public AudioObject GetFreeAudioObject(GameObject prefab = null) { return null; } #endregion } [System.Serializable] public class PrefabBasedPool { public GameObject prefab; public List<AudioObject> audioObjects; }
mit
C#
63d44d313f9c838326785ea3ca3d5b4654e9c262
Add support for local folder
tectronik/cordova-plugin-file-opener2-tectronik,tectronik/cordova-plugin-file-opener2-tectronik,tectronik/cordova-plugin-file-opener2-tectronik
src/wp8/FileOpener2.cs
src/wp8/FileOpener2.cs
using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Microsoft.Phone.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; using Windows.Storage; using System.Diagnostics; using System.IO; namespace WPCordovaClassLib.Cordova.Commands { public class FileOpener2 : BaseCommand { public async void open(string options) { string[] args = JSON.JsonHelper.Deserialize<string[]>(options); this.openPath(args[0].Replace("/", "\\"), args[2]); string[] args = JSON.JsonHelper.Deserialize<string[]>(options); } private async void openPath(string path, string cbid) { try { StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path); await Windows.System.Launcher.LaunchFileAsync(file); DispatchCommandResult(new PluginResult(PluginResult.Status.OK), cbid); } catch (FileNotFoundException) { this.openInLocalFolder(path, cbid); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), cbid); } } private async void openInLocalFolder(string path, string cbid) { try { StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync( Path.Combine( Windows.Storage.ApplicationData.Current.LocalFolder.Path, path.TrimStart('\\') ) ); await Windows.System.Launcher.LaunchFileAsync(file); DispatchCommandResult(new PluginResult(PluginResult.Status.OK), cbid); } catch (FileNotFoundException) { DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), cbid); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), cbid); } } } }
using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Microsoft.Phone.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; using Windows.Storage; using System.Diagnostics; using System.IO; namespace WPCordovaClassLib.Cordova.Commands { public class FileOpener2 : BaseCommand { public async void open(string options) { string[] args = JSON.JsonHelper.Deserialize<string[]>(options); string aliasCurrentCommandCallbackId = args[2]; try { // Get the file. StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(args[0]); // Launch the bug query file. await Windows.System.Launcher.LaunchFileAsync(file); DispatchCommandResult(new PluginResult(PluginResult.Status.OK), aliasCurrentCommandCallbackId); } catch (FileNotFoundException) { DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), aliasCurrentCommandCallbackId); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), aliasCurrentCommandCallbackId); } } } }
mit
C#
71fe67a647478aa52e54c4e43b091343fa433ed9
Allow the DisposableTracker to be passed around
alex-davidson/clrspy
ClrSpy.UnitTests/Utils/DisposableTracker.cs
ClrSpy.UnitTests/Utils/DisposableTracker.cs
using System; using System.Collections.Generic; namespace ClrSpy.UnitTests.Utils { /// <summary> /// RAII-style tracking of IDisposable instances. Once all disposables are created, ownership can /// be transferred to the final container in an exception-safe manner. /// </summary> public class DisposableTracker : IDisposable { private Stack<IDisposable> scopes = new Stack<IDisposable>(); public T Track<T>(T item) { scopes.Push(item as IDisposable); return item; } public T TransferOwnershipTo<T>(Func<IDisposable, T> createNewOwner) { var newOwner = createNewOwner(new DisposableTracker { scopes = scopes }); scopes = null; return newOwner; } public void Dispose() { if (scopes == null) return; while (scopes.Count > 0) { var scope = scopes.Pop(); try { scope?.Dispose(); } catch { // Ignore exceptions. } } } } }
using System; using System.Collections.Generic; namespace ClrSpy.UnitTests.Utils { /// <summary> /// RAII-style tracking of IDisposable instances. Once all disposables are created, ownership can /// be transferred to the final container in an exception-safe manner. /// </summary> public struct DisposableTracker : IDisposable { private Stack<IDisposable> scopes; public T Track<T>(T item) { if (scopes == null) scopes = new Stack<IDisposable>(); scopes.Push(item as IDisposable); return item; } public T TransferOwnershipTo<T>(Func<IDisposable, T> createNewOwner) { var newOwner = createNewOwner(this); scopes = null; return newOwner; } public void Dispose() { if (scopes == null) return; while (scopes.Count > 0) { var scope = scopes.Pop(); try { scope?.Dispose(); } catch { // Ignore exceptions. } } } } }
unlicense
C#
7a168b42c107615876cda079445b9237fa897435
Fix comment
Mazyod/PhoenixSharp
Phoenix/DelayedExecutor.cs
Phoenix/DelayedExecutor.cs
using System; using System.Threading.Tasks; namespace Phoenix { public interface IDelayedExecution { void Cancel(); } /** * IDelayedExecutor * This class is equivalent to javascript setTimeout/clearTimeout functions. */ public interface IDelayedExecutor { IDelayedExecution Execute(Action action, TimeSpan delay); } /** * Scheduler * This class is equivalent to the Timer class in the Phoenix JS library. */ public sealed class Scheduler { private readonly Action _callback; private readonly IDelayedExecutor _delayedExecutor; private readonly Func<int, TimeSpan> _timerCalc; private IDelayedExecution _execution; private int _tries; public Scheduler(Action callback, Func<int, TimeSpan> timerCalc, IDelayedExecutor delayedExecutor) { _callback = callback; _timerCalc = timerCalc; _delayedExecutor = delayedExecutor; } public void Reset() { _tries = 0; _execution?.Cancel(); _execution = null; } public void ScheduleTimeout() { _execution?.Cancel(); _execution = _delayedExecutor.Execute(() => { _tries += 1; _callback(); }, _timerCalc(_tries + 1)); } } // Provide a default delayed executor that uses Tasks API. public sealed class TaskExecution : IDelayedExecution { internal bool Cancelled; public void Cancel() { Cancelled = true; } } public sealed class TaskDelayedExecutor : IDelayedExecutor { public IDelayedExecution Execute(Action action, TimeSpan delay) { var execution = new TaskExecution(); Task.Delay(delay).ContinueWith(_ => { if (!execution.Cancelled) { action(); } }); return execution; } } }
using System; using System.Threading.Tasks; namespace Phoenix { public interface IDelayedExecution { void Cancel(); } /** * IDelayedExecutor * This class is equivalent to javascript setTimeout/clearTimeout functions. */ public interface IDelayedExecutor { IDelayedExecution Execute(Action action, TimeSpan delay); } /** * Scheduler * This class is equivalent to the Timer class in the Phoenix JS library. */ public sealed class Scheduler { private readonly Action _callback; private readonly IDelayedExecutor _delayedExecutor; private readonly Func<int, TimeSpan> _timerCalc; private IDelayedExecution _execution; private int _tries; public Scheduler(Action callback, Func<int, TimeSpan> timerCalc, IDelayedExecutor delayedExecutor) { _callback = callback; _timerCalc = timerCalc; _delayedExecutor = delayedExecutor; } public void Reset() { _tries = 0; _execution?.Cancel(); _execution = null; } public void ScheduleTimeout() { _execution?.Cancel(); _execution = _delayedExecutor.Execute(() => { _tries += 1; _callback(); }, _timerCalc(_tries + 1)); } } // Provide a default delayed executor that uses a async / await. public sealed class TaskExecution : IDelayedExecution { internal bool Cancelled; public void Cancel() { Cancelled = true; } } public sealed class TaskDelayedExecutor : IDelayedExecutor { public IDelayedExecution Execute(Action action, TimeSpan delay) { var execution = new TaskExecution(); Task.Delay(delay).ContinueWith(_ => { if (!execution.Cancelled) { action(); } }); return execution; } } }
mit
C#
568f19e3ff921446ef0b0d31c8b897fcfb4637b7
Increment version.
lookatmike/AirfoilMetadataAgent
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AirfoilMetadataAgent")] [assembly: AssemblyDescription("A C# / .NET 4.0 library for communicating with Rogue Amoeba's Airfoil for Windows over named pipes.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Say Uncle Software")] [assembly: AssemblyProduct("AirfoilMetadataAgent")] [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("3cccebac-ee99-47a8-8455-be28c8c0d1e2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.1.0")]
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("AirfoilMetadataAgent")] [assembly: AssemblyDescription("A C# / .NET 4.0 library for communicating with Rogue Amoeba's Airfoil for Windows over named pipes.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Say Uncle Software")] [assembly: AssemblyProduct("AirfoilMetadataAgent")] [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("3cccebac-ee99-47a8-8455-be28c8c0d1e2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
95db5a7f40796f64a2e7e4bfab5761050e9b8f48
Bump version to 1.1
FatturaElettronicaPA/FatturaElettronicaPA.Forms
Properties/AssemblyInfo.cs
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("FatturaElettronica.Forms")] [assembly: AssemblyDescription("Windows.Forms per FatturaElettronica.NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Nicola Iarocci, CIR2000")] [assembly: AssemblyProduct("FatturaElettronica.Forms")] [assembly: AssemblyCopyright("Copyright © CIR2000 2017-2019")] [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("a82cf38b-b7fe-42ae-b114-dc8fed8bd718")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FatturaElettronica.Forms")] [assembly: AssemblyDescription("Windows.Forms per FatturaElettronica.NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Nicola Iarocci, CIR2000")] [assembly: AssemblyProduct("FatturaElettronica.Forms")] [assembly: AssemblyCopyright("Copyright © CIR2000 2017-2018")] [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("a82cf38b-b7fe-42ae-b114-dc8fed8bd718")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bsd-3-clause
C#
7edef5bc97b5b25128f307084df7eedb6dce5437
Fix environment variable name.
zooba/PTVS,Microsoft/PTVS,huguesv/PTVS,int19h/PTVS,huguesv/PTVS,Microsoft/PTVS,zooba/PTVS,int19h/PTVS,huguesv/PTVS,int19h/PTVS,huguesv/PTVS,Microsoft/PTVS,zooba/PTVS,huguesv/PTVS,int19h/PTVS,zooba/PTVS,int19h/PTVS,Microsoft/PTVS,Microsoft/PTVS,zooba/PTVS,huguesv/PTVS,int19h/PTVS,zooba/PTVS,Microsoft/PTVS
Common/Tests/Utilities/VisualStudioPath.cs
Common/Tests/Utilities/VisualStudioPath.cs
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Setup.Configuration; namespace TestUtilities { public static class VisualStudioPath { private static Lazy<string> RootLazy { get; } = new Lazy<string>(GetVsRoot); private static Lazy<string> CommonExtensionsLazy { get; } = new Lazy<string>(() => Root == null ? null : Path.Combine(Root, @"CommonExtensions\")); private static Lazy<string> PrivateAssembliesLazy { get; } = new Lazy<string>(() => Root == null ? null : Path.Combine(Root, @"PrivateAssemblies\")); private static Lazy<string> PublicAssembliesLazy { get; } = new Lazy<string>(() => Root == null ? null : Path.Combine(Root, @"PublicAssemblies\")); public static string Root => RootLazy.Value; public static string CommonExtensions => CommonExtensionsLazy.Value; public static string PrivateAssemblies => PrivateAssembliesLazy.Value; public static string PublicAssemblies => PublicAssembliesLazy.Value; private static string GetVsRoot() { try { var configuration = (ISetupConfiguration2)new SetupConfiguration(); var current = (ISetupInstance2)configuration.GetInstanceForCurrentProcess(); var path = current.ResolvePath(current.GetProductPath()); return Path.GetDirectoryName(path); } catch (COMException) { var path = Environment.GetEnvironmentVariable($"VisualStudio_IDE_{AssemblyVersionInfo.VSVersion}"); if (string.IsNullOrEmpty(path)) { path = Environment.GetEnvironmentVariable("VisualStudio_IDE"); } return path; } } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Setup.Configuration; namespace TestUtilities { public static class VisualStudioPath { private static Lazy<string> RootLazy { get; } = new Lazy<string>(GetVsRoot); private static Lazy<string> CommonExtensionsLazy { get; } = new Lazy<string>(() => Root == null ? null : Path.Combine(Root, @"CommonExtensions\")); private static Lazy<string> PrivateAssembliesLazy { get; } = new Lazy<string>(() => Root == null ? null : Path.Combine(Root, @"PrivateAssemblies\")); private static Lazy<string> PublicAssembliesLazy { get; } = new Lazy<string>(() => Root == null ? null : Path.Combine(Root, @"PublicAssemblies\")); public static string Root => RootLazy.Value; public static string CommonExtensions => CommonExtensionsLazy.Value; public static string PrivateAssemblies => PrivateAssembliesLazy.Value; public static string PublicAssemblies => PublicAssembliesLazy.Value; private static string GetVsRoot() { try { var configuration = (ISetupConfiguration2)new SetupConfiguration(); var current = (ISetupInstance2)configuration.GetInstanceForCurrentProcess(); var path = current.ResolvePath(current.GetProductPath()); return Path.GetDirectoryName(path); } catch (COMException) { var path = Environment.GetEnvironmentVariable($"VisualStudio_{AssemblyVersionInfo.VSVersion}"); if (string.IsNullOrEmpty(path)) { path = Environment.GetEnvironmentVariable("VisualStudio"); } return path; } } } }
apache-2.0
C#
3a6a3a067b4816b81bf1851b75640a8e73349221
Rewrite test to cover failure case
smoogipooo/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu
osu.Game.Tests/Visual/Online/TestSceneAccountCreationOverlay.cs
osu.Game.Tests/Visual/Online/TestSceneAccountCreationOverlay.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Overlays; using osu.Game.Users; namespace osu.Game.Tests.Visual.Online { public class TestSceneAccountCreationOverlay : OsuTestScene { private readonly Container userPanelArea; private readonly AccountCreationOverlay accountCreation; private IBindable<User> localUser; public TestSceneAccountCreationOverlay() { Children = new Drawable[] { accountCreation = new AccountCreationOverlay(), userPanelArea = new Container { Padding = new MarginPadding(10), AutoSizeAxes = Axes.Both, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, }, }; } [BackgroundDependencyLoader] private void load() { API.Logout(); localUser = API.LocalUser.GetBoundCopy(); localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true); } [Test] public void TestOverlayVisibility() { AddStep("start hidden", () => accountCreation.Hide()); AddStep("log out", API.Logout); AddStep("show manually", () => accountCreation.Show()); AddUntilStep("overlay is visible", () => accountCreation.State.Value == Visibility.Visible); AddStep("log back in", () => API.Login("dummy", "password")); AddUntilStep("overlay is hidden", () => accountCreation.State.Value == Visibility.Hidden); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Overlays; using osu.Game.Users; namespace osu.Game.Tests.Visual.Online { public class TestSceneAccountCreationOverlay : OsuTestScene { private readonly Container userPanelArea; private IBindable<User> localUser; public TestSceneAccountCreationOverlay() { AccountCreationOverlay accountCreation; Children = new Drawable[] { accountCreation = new AccountCreationOverlay(), userPanelArea = new Container { Padding = new MarginPadding(10), AutoSizeAxes = Axes.Both, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, }, }; AddStep("show", () => accountCreation.Show()); } [BackgroundDependencyLoader] private void load() { API.Logout(); localUser = API.LocalUser.GetBoundCopy(); localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true); AddStep("logout", API.Logout); } } }
mit
C#
7ee1a3ca6cd35bc87dbd43850b8ccae65bee3446
Fix failing unit test.
jtompkins/Haberdasher
Haberdasher.Tests/TestClasses/NoKeyClass.cs
Haberdasher.Tests/TestClasses/NoKeyClass.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Haberdasher.Tests.TestClasses { public class NoKeyClass { public int Name { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Haberdasher.Tests.TestClasses { public class NoKeyClass { public int Id { get; set; } } }
mit
C#
f67f6cc99ca914b152a355122589900437b6b91d
Fix switch case
peppy/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu
osu.Game.Rulesets.Osu/Mods/OsuModFreezeFrame.cs
osu.Game.Rulesets.Osu/Mods/OsuModFreezeFrame.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.UI; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModFreezeFrame : Mod, IApplicableToBeatmap, IApplicableToDrawableRuleset<OsuHitObject> { public override string Name => "Freeze Frame"; public override string Acronym => "FR"; public override double ScoreMultiplier => 1; public override LocalisableString Description => "Burn the notes into your memory."; public override ModType Type => ModType.Fun; public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset) { (drawableRuleset.Playfield as OsuPlayfield)?.FollowPoints.Hide(); } public void ApplyToBeatmap(IBeatmap beatmap) { double lastNewComboTime = 0; foreach (var obj in beatmap.HitObjects.OfType<OsuHitObject>()) { if (obj.NewCombo) { lastNewComboTime = obj.StartTime; } applyFadeInAdjustment(obj); } void applyFadeInAdjustment(OsuHitObject osuObject) { osuObject.TimePreempt += osuObject.StartTime - lastNewComboTime; foreach (var nested in osuObject.NestedHitObjects.OfType<OsuHitObject>()) { switch (nested) { //SliderRepeat wont layer correctly if preempt is changed. case SliderRepeat: break; default: applyFadeInAdjustment(nested); break; } } } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.UI; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModFreezeFrame : Mod, IApplicableToBeatmap, IApplicableToDrawableRuleset<OsuHitObject> { public override string Name => "Freeze Frame"; public override string Acronym => "FR"; public override double ScoreMultiplier => 1; public override LocalisableString Description => "Burn the notes into your memory."; public override ModType Type => ModType.Fun; public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset) { (drawableRuleset.Playfield as OsuPlayfield)?.FollowPoints.Hide(); } public void ApplyToBeatmap(IBeatmap beatmap) { double lastNewComboTime = 0; foreach (var obj in beatmap.HitObjects.OfType<OsuHitObject>()) { if (obj.NewCombo) { lastNewComboTime = obj.StartTime; } applyFadeInAdjustment(obj); } void applyFadeInAdjustment(OsuHitObject osuObject) { osuObject.TimePreempt += osuObject.StartTime - lastNewComboTime; foreach (var nested in osuObject.NestedHitObjects.OfType<OsuHitObject>()) { switch (nested) { //SliderRepeat wont layer correctly if preempt is changed. case SliderRepeat: return; default: applyFadeInAdjustment(nested); break; } } } } } }
mit
C#
04833e34a98691afdafea606f88a439f699de987
change test items for to use select list
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/TestItems/_TestItemsForm.cshtml
Anlab.Mvc/Views/TestItems/_TestItemsForm.cshtml
@using System.Runtime.InteropServices.ComTypes @model Anlab.Core.Domain.TestItem @Html.HiddenFor(a => a.Category) <div class="form-group"> <label asp-for="Analysis" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Analysis" class="form-control" /> <span asp-validation-for="Analysis" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Category" class="col-md-2 control-label"></label> <div class="col-md-10"> <select asp-for="Categories" class="form-control" multiple="multiple"> @foreach (var category in TestCategories.All) { <option value="@category">@category</option> } </select> <span asp-validation-for="Category" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Group" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Group" class="form-control" /> <span asp-validation-for="Group" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Public" class="col-md-2 control-label"></label> <div class="col-md-10"> <select asp-for="Public" class="form-control" > <option value="true">Yes</option> <option value="false">No</option> </select> <span asp-validation-for="Public" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Notes" class="col-md-2 control-label"></label> <div class="col-md-10"> <textarea asp-for="Notes" class="form-control" rows="3"> </textarea> <span asp-validation-for="Notes" class="text-danger"></span> </div> </div>
@using System.Runtime.InteropServices.ComTypes @model Anlab.Core.Domain.TestItem @Html.HiddenFor(a => a.Category) <div class="form-group"> <label asp-for="Analysis" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Analysis" class="form-control" /> <span asp-validation-for="Analysis" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Category" class="col-md-2 control-label"></label> <div class="col-md-10"> <select asp-for="Categories" class="form-control" multiple="multiple"> <option value="Soil">Soil</option> <option value="Plant">Plant</option> <option value="Water">Water</option> <option value="Other">Other</option> </select> <span asp-validation-for="Category" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Group" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Group" class="form-control" /> <span asp-validation-for="Group" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Public" class="col-md-2 control-label"></label> <div class="col-md-10"> <select asp-for="Public" class="form-control" > <option value="true">Yes</option> <option value="false">No</option> </select> <span asp-validation-for="Public" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Notes" class="col-md-2 control-label"></label> <div class="col-md-10"> <textarea asp-for="Notes" class="form-control" rows="3"> </textarea> <span asp-validation-for="Notes" class="text-danger"></span> </div> </div>
mit
C#
1c5e27a9b06469e9314247d63f6a7c13c99bddde
Use PropertyDescriptor
sakapon/Samples-2016,sakapon/Samples-2016
BindingSample/PocoBindingWpf/MainWindow.xaml.cs
BindingSample/PocoBindingWpf/MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace PocoBindingWpf { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var AppModel = (AppModel)DataContext; Loaded += (o, e) => { // Notification does not work in usual way. //AppModel.Input.Number = 1234; SetValue(AppModel.Input, nameof(InputModel.Number), 1234); }; AddValueChanged(AppModel.Input, nameof(InputModel.Number), () => Console.WriteLine(AppModel.Input.Number)); } static void SetValue(object obj, string propertyName, object value) { var properties = TypeDescriptor.GetProperties(obj); properties[propertyName].SetValue(obj, value); } static void AddValueChanged(object obj, string propertyName, Action action) { var properties = TypeDescriptor.GetProperties(obj); properties[propertyName].AddValueChanged(obj, (o, e) => action()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace PocoBindingWpf { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }
mit
C#
a1042ec4588f180aa03457e35ff0c6bfe50cc0da
Update changes
FireCube-/HarvesterBot
TexasHoldEm/Trainer.cs
TexasHoldEm/Trainer.cs
using System; using System.Collections.Generic; /// <summary> /// Summary description for Class1 /// </summary> public class Trainer { private int popSize; private List<Gene> pop; private int currentGene = 0; private int generation = 1; private const double crossoverSplit = 0.5; private const double genepoolSize = 0.5; private const double selectionSize = 0.5; private Random rand; public Trainer(int popSize = 10) { this.popSize = popSize; rand = new Random(Guid.NewGuid().GetHashCode()); pop = new List<Gene>(); for (int i = 0; i < popSize; i++) { pop.Add(new Gene(popSize)); } initPop(); } private void initPop() { // TODO: a better solution foreach (Gene gene in pop) { for (int i = 0; i < gene.getLength(); i++) { gene.set(i, rand.NextDouble()); } } } public int getGeneration() { return generation; } public bool nextGene() { if(++currentGene < popSize) return true; currentGene = 0; return false; } public Gene getCurrentGene() { return this.pop[currentGene]; } public void nextGeneration() { generation++; pop.Sort(geneSort); List<Gene> newPop = new List<Gene>(popSize); } private static int geneSort(Gene geneA, Gene geneB) { double diff = geneA.getFitness() - geneB.getFitness(); if (diff < 0) return 1; if (diff > 0) return -1; return 0; } private List<Gene> getGenepool() { List<Gene> genepool = new List<Gene>((int) (popSize * genepoolSize)); for (int i = 0; i < genepool.Capacity; i++) { genepool[i] = crossover(tournamentSelection(pop), tournamentSelection(pop)); } return genepool; } private Gene tournamentSelection(List<Gene> list) { Gene mate = pop[rand.Next(1, popSize - 1)]; return mate; } private Gene crossover(Gene geneA, Gene geneB) { List<double> left = geneA.getLeft(crossoverSplit); List<double> right = geneB.getRight(1 - crossoverSplit); left.AddRange(right); return new Gene(left); } private void mutateGenes() { foreach (Gene gene in pop) { gene.mutate(rand); } } }
using System; using System.Collections.Generic; /// <summary> /// Summary description for Class1 /// </summary> public class Trainer { private int popSize; private List<Gene> pop; private int currentGene = 0; private int generation = 1; private const double crossoverSplit = 0.5; private const double genepoolSize = 0.5; private const double selectionSize = 0.5; private Random rand; public Trainer(int popSize = 10) { this.popSize = popSize; rand = new Random(Guid.NewGuid().GetHashCode()); pop = new List<Gene>(); for (int i = 0; i < popSize; i++) { pop.Add(new Gene(popSize)); } initPop(); } private void initPop() { // TODO: a better solution foreach (Gene gene in pop) { for (int i = 0; i < gene.getLength(); i++) { gene.set(i, rand.NextDouble()); } } } public int getGeneration() { return generation; } public bool nextGene() { if(++currentGene < popSize) return true; currentGene = 0; return false; } public Gene getCurrentGene() { return this.pop[currentGene]; } public void nextGeneration() { generation++; pop.Sort(geneSort); List<Gene> newPop = new List<Gene>(popSize); } private static int geneSort(Gene geneA, Gene geneB) { double diff = geneA.getFitness() - geneB.getFitness(); if (diff < 0) return 1; if (diff > 0) return -1; return 0; } private List<Gene> getGenepool() { List<Gene> genepool = new List<Gene>((int) (popSize * genepoolSize)); for (int i = 0; i < genepool.Capacity; i++) { genepool[i] = crossover(tournamentSelection(pop), tournamentSelection(pop)); } return genepool; } private Gene tournamentSelection(List<Gene> list) { Gene mate = pop[rand.Next(1, popSize - 1)]; return mate; } private Gene crossover(Gene geneA, Gene geneB) { List<double> left = geneA.getLeft(crossoverSplit); List<double> right = geneB.getRight(1 - crossoverSplit); left.AddRange(right); return new Gene(left); } private void mutateGenes() { foreach (Gene gene in pop) { gene.mutate(rand); } } }
mit
C#
8892f2c3dd2bb92d3738b122456223c30a1cea8d
Remove redundant check
UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game.Rulesets.Osu/Mods/OsuModApproachCircle.cs
osu.Game.Rulesets.Osu/Mods/OsuModApproachCircle.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Bindables; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Mods { internal class OsuModApproachCircle : Mod, IApplicableToDrawableHitObjects { public override string Name => "Approach Circle"; public override string Acronym => "AC"; public override string Description => "Never trust the approach circles..."; public override double ScoreMultiplier => 1; public override IconUsage? Icon { get; } = FontAwesome.Regular.Circle; [SettingSource("Easing", "Change the easing type of the approach circles.", 0)] public Bindable<Easing> BindableEasing { get; } = new Bindable<Easing>(); [SettingSource("Scale the size", "Change the factor of the approach circle scale.", 1)] public BindableFloat Scale { get; } = new BindableFloat { Precision = 0.1f, MinValue = 2, MaxValue = 10, Default = 4, Value = 4 }; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { drawables.ForEach(drawable => { drawable.ApplyCustomUpdateState += (drawableHitObj, state) => { if (!(drawableHitObj is DrawableHitCircle hitCircle)) return; var obj = drawableOsuHitObj.HitObject; hitCircle.BeginAbsoluteSequence(obj.StartTime - obj.TimePreempt, true); hitCircle.ApproachCircle.ScaleTo(Scale.Value); hitCircle.ApproachCircle.FadeIn(Math.Min(obj.TimeFadeIn, obj.TimePreempt)); hitCircle.ApproachCircle.ScaleTo(1f, obj.TimePreempt, BindableEasing.Value); hitCircle.ApproachCircle.Expire(true); }; }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Bindables; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Mods { internal class OsuModApproachCircle : Mod, IApplicableToDrawableHitObjects { public override string Name => "Approach Circle"; public override string Acronym => "AC"; public override string Description => "Never trust the approach circles..."; public override double ScoreMultiplier => 1; public override IconUsage? Icon { get; } = FontAwesome.Regular.Circle; [SettingSource("Easing", "Change the easing type of the approach circles.", 0)] public Bindable<Easing> BindableEasing { get; } = new Bindable<Easing>(); [SettingSource("Scale the size", "Change the factor of the approach circle scale.", 1)] public BindableFloat Scale { get; } = new BindableFloat { Precision = 0.1f, MinValue = 2, MaxValue = 10, Default = 4, Value = 4 }; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { drawables.ForEach(drawable => { drawable.ApplyCustomUpdateState += (drawableHitObj, state) => { if (!(drawableHitObj is DrawableOsuHitObject drawableOsuHitObj) || !(drawableHitObj is DrawableHitCircle hitCircle)) return; var obj = drawableOsuHitObj.HitObject; hitCircle.BeginAbsoluteSequence(obj.StartTime - obj.TimePreempt, true); hitCircle.ApproachCircle.ScaleTo(Scale.Value); hitCircle.ApproachCircle.FadeIn(Math.Min(obj.TimeFadeIn, obj.TimePreempt)); hitCircle.ApproachCircle.ScaleTo(1f, obj.TimePreempt, BindableEasing.Value); hitCircle.ApproachCircle.Expire(true); }; }); } } }
mit
C#
f4e86b60f28c708c49dc403a03c8c397dad5efa3
Remove incorrect Assembly GUID
File-New-Project/EarTrumpet
EarTrumpet/UI/Helpers/SingleInstanceAppMutex.cs
EarTrumpet/UI/Helpers/SingleInstanceAppMutex.cs
using System.Globalization; using System.Reflection; using System.Threading; namespace EarTrumpet.UI.Helpers { class SingleInstanceAppMutex { private static Mutex _mutex; public static bool TakeExclusivity() { var assembly = Assembly.GetExecutingAssembly(); var mutexName = $"Local\\{assembly.GetName().Name}-0e510f7b-aed2-40b0-ad72-d2d3fdc89a02"; _mutex = new Mutex(true, mutexName, out bool mutexCreated); if (!mutexCreated) { _mutex = null; return false; } App.Current.Exit += App_Exit; return true; } private static void App_Exit(object sender, System.Windows.ExitEventArgs e) { ReleaseExclusivity(); } public static void ReleaseExclusivity() { if (_mutex == null) return; _mutex.ReleaseMutex(); _mutex.Close(); _mutex = null; } } }
using System.Globalization; using System.Reflection; using System.Threading; namespace EarTrumpet.UI.Helpers { class SingleInstanceAppMutex { private static Mutex _mutex; public static bool TakeExclusivity() { var assembly = Assembly.GetExecutingAssembly(); var mutexName = string.Format(CultureInfo.InvariantCulture, "Local\\{{{0}}}{{{1}}}", assembly.GetType().GUID, assembly.GetName().Name); _mutex = new Mutex(true, mutexName, out bool mutexCreated); if (!mutexCreated) { _mutex = null; return false; } App.Current.Exit += App_Exit; return true; } private static void App_Exit(object sender, System.Windows.ExitEventArgs e) { ReleaseExclusivity(); } public static void ReleaseExclusivity() { if (_mutex == null) return; _mutex.ReleaseMutex(); _mutex.Close(); _mutex = null; } } }
mit
C#
4c5845440f85ad0640ae5bf584e3d5be7423fd7d
bump version
Fody/MethodDecorator
MethodDecorator.Fody/Properties/AssemblyInfo.cs
MethodDecorator.Fody/Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("MethodDecorator.Fody")] [assembly: AssemblyDescription("Fody addin for AOP method decoration")] [assembly: AssemblyCompany("Matt Ellis")] [assembly: AssemblyProduct("MethodDecorator.Fody")] [assembly: AssemblyCopyright("Copyright © Matt Ellis 2012")] [assembly: AssemblyVersion("0.8.12")] [assembly: AssemblyFileVersion("0.8.1.12")]
using System.Reflection; [assembly: AssemblyTitle("MethodDecorator.Fody")] [assembly: AssemblyDescription("Fody addin for AOP method decoration")] [assembly: AssemblyCompany("Matt Ellis")] [assembly: AssemblyProduct("MethodDecorator.Fody")] [assembly: AssemblyCopyright("Copyright © Matt Ellis 2012")] [assembly: AssemblyVersion("0.8.1.1")] [assembly: AssemblyFileVersion("0.8.1.1")]
mit
C#