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
361098baaaf8e34c7461729c45db445b098dcc4e
fix build
Mike-EEE/ExtendedXmlSerializer,wojtpl2/ExtendedXmlSerializer,Mike-EEE/ExtendedXmlSerializer,wojtpl2/ExtendedXmlSerializer
test/ExtendedXmlSerializerTest/SerializationPropertyInterfaceOfListTest.cs
test/ExtendedXmlSerializerTest/SerializationPropertyInterfaceOfListTest.cs
// MIT License // // Copyright (c) 2016 Wojciech Nagórski // // 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 ExtendedXmlSerialization.Test.TestObject; using Xunit; namespace ExtendedXmlSerialization.Test { public class SerializationPropertyInterfaceOfListTest :BaseTest { [Fact] public void PropertyInterfaceOfList() { var obj = new TestClassPropertyInterfaceOfList(); obj.Init(); CheckSerializationAndDeserializationByXml(@"<?xml version=""1.0"" encoding=""utf-8""?> <TestClassPropertyInterfaceOfList type=""ExtendedXmlSerialization.Test.TestObject.TestClassPropertyInterfaceOfList""> <List type=""System.Collections.Generic.List`1[[System.String, [CORELIB]]]""><string>Item1</string></List> <Dictionary type=""System.Collections.Generic.Dictionary`2[[System.String, [CORELIB]],[System.String, [CORELIB]]]""><Item><Key>Key</Key><Value>Value</Value></Item></Dictionary> <Set type=""System.Collections.Generic.HashSet`1[[System.String, [CORELIB]]]""><string>Item1</string></Set> </TestClassPropertyInterfaceOfList>", obj); } } }
// MIT License // // Copyright (c) 2016 Wojciech Nagórski // // 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 ExtendedXmlSerialization.Test.TestObject; using Xunit; namespace ExtendedXmlSerialization.Test { public class SerializationPropertyInterfaceOfListTest :BaseTest { [Fact] public void PropertyInterfaceOfList() { var obj = new TestClassPropertyInterfaceOfList(); obj.Init(); CheckSerializationAndDeserializationByXml(@"<?xml version=""1.0"" encoding=""utf-8""?> <TestClassPropertyInterfaceOfList type=""ExtendedXmlSerialization.Test.TestObject.TestClassPropertyInterfaceOfList""> <List type=""System.Collections.Generic.List`1[[System.String, [CORELIB]]]""><string>Item1</string></List> <Dictionary type=""System.Collections.Generic.Dictionary`2[[System.String, [CORELIB]],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]""><Item><Key>Key</Key><Value>Value</Value></Item></Dictionary> <Set type=""System.Collections.Generic.HashSet`1[[System.String, [CORELIB]]]""><string>Item1</string></Set> </TestClassPropertyInterfaceOfList>", obj); } } }
mit
C#
7301615f687a1092a0e2dc26687bd11397327277
refactor of solr object
Appleseed/base,Appleseed/base
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Program.cs
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SendGrid; using SendGrid.Helpers.Mail; using System.Net; using System.IO; using Newtonsoft.Json; using System.Data.SqlClient; using System.Data; using System.Configuration; using Dapper; namespace Appleseed.Base.Alerts { class UserAlert { public Guid user_id { get; set; } public string email { get; set; } public string name { get; set; } public string source { get; set; } } class RootSolrObject { public SolrResponse response { get; set; } } class SolrResponse { public SolrResponseItem[] docs { get; set; } } class SolrResponseItem { public string id { get; set; } public string[] item_type { get; set; } public string[] address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string[] postal_code { get; set; } public string[] product_description { get; set; } public string[] product_quantity { get; set; } public string[] product_type { get; set; } public string[] code_info { get; set; } public string[] reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string[] recall_number { get; set; } public string recalling_firm { get; set; } public string[] voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string[] status { get; set; } } class Program { static void Main(string[] args) { } #region helpers static string UppercaseFirst(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } char[] a = s.ToCharArray(); a[0] = char.ToUpper(a[0]); return new string(a); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SendGrid; using SendGrid.Helpers.Mail; using System.Net; using System.IO; using Newtonsoft.Json; using System.Data.SqlClient; using System.Data; using System.Configuration; using Dapper; namespace Appleseed.Base.Alerts { class UserAlert { public Guid user_id { get; set; } public string email { get; set; } public string name { get; set; } public string source { get; set; } } class RootSolrObject { public SolrResponse response { get; set; } } class SolrResponse { public SolrResponseItem[] docs { get; set; } } class Program { static void Main(string[] args) { } #region helpers static string UppercaseFirst(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } char[] a = s.ToCharArray(); a[0] = char.ToUpper(a[0]); return new string(a); } #endregion } }
apache-2.0
C#
b95d37a43ffa0fc85c27f2291c6ef48d9bb8474c
Bump version
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
configuration/SharedAssemblyInfo.cs
configuration/SharedAssemblyInfo.cs
using System.Reflection; // Assembly Info that is shared across the product [assembly: AssemblyProduct("InEngine.NET")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ethan Hann")] [assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")]
using System.Reflection; // Assembly Info that is shared across the product [assembly: AssemblyProduct("InEngine.NET")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0-rc2")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ethan Hann")] [assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")]
mit
C#
421499453d6153bedab6240a53a3649d8a8c2808
Update GenericPipelineBehavior.cs
jbogard/MediatR
samples/MediatR.Examples/GenericPipelineBehavior.cs
samples/MediatR.Examples/GenericPipelineBehavior.cs
using System.IO; using System.Threading.Tasks; namespace MediatR.Examples { public class GenericPipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> { private readonly TextWriter _writer; public GenericPipelineBehavior(TextWriter writer) { _writer = writer; } public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next) { _writer.WriteLine("-- Handling Request"); var response = await next(); _writer.WriteLine("-- Finished Request"); return response; } } }
using System.IO; using System.Threading.Tasks; namespace MediatR.Examples { public class GenericPipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> { private readonly TextWriter _writer; public GenericPipelineBehavior(TextWriter writer) { _writer = writer; } public Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next) { _writer.WriteLine("-- Handling Request"); var response = next(); _writer.WriteLine("-- Finished Request"); return response; } } }
apache-2.0
C#
834f3b01b8601790ed1e4b6bbe8b35fca47c81bd
Add Not value converter to BoolConverters
Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex
src/Avalonia.Base/Data/Converters/BoolConverters.cs
src/Avalonia.Base/Data/Converters/BoolConverters.cs
using System.Linq; namespace Avalonia.Data.Converters { /// <summary> /// Provides a set of useful <see cref="IValueConverter"/>s for working with bool values. /// </summary> public static class BoolConverters { /// <summary> /// A multi-value converter that returns true if all inputs are true. /// </summary> public static readonly IMultiValueConverter And = new FuncMultiValueConverter<bool, bool>(x => x.All(y => y)); /// <summary> /// A multi-value converter that returns true if any of the inputs is true. /// </summary> public static readonly IMultiValueConverter Or = new FuncMultiValueConverter<bool, bool>(x => x.Any(y => y)); /// <summary> /// A value converter that returns true when input is false and false when input is true. /// </summary> public static readonly IValueConverter Not = new FuncValueConverter<bool, bool>(x => !x); } }
using System.Linq; namespace Avalonia.Data.Converters { /// <summary> /// Provides a set of useful <see cref="IValueConverter"/>s for working with bool values. /// </summary> public static class BoolConverters { /// <summary> /// A multi-value converter that returns true if all inputs are true. /// </summary> public static readonly IMultiValueConverter And = new FuncMultiValueConverter<bool, bool>(x => x.All(y => y)); /// <summary> /// A multi-value converter that returns true if any of the inputs is true. /// </summary> public static readonly IMultiValueConverter Or = new FuncMultiValueConverter<bool, bool>(x => x.Any(y => y)); } }
mit
C#
84d1efddb2f85080882f47cd27f4fd542ecca4b3
Remove some unnecessary newlines
riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm
src/DotVVM.Framework/Compilation/DotHtmlFileInfo.cs
src/DotVVM.Framework/Compilation/DotHtmlFileInfo.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; namespace DotVVM.Framework.Compilation { public sealed class DotHtmlFileInfo { public CompilationState Status { get; internal set; } public string? Exception { get; internal set; } /// <summary>Gets or sets the virtual path to the view.</summary> public string VirtualPath { get; } public string? TagName { get; } public string? Namespace { get; } public string? Assembly { get; } public string? TagPrefix { get; } public string? Url { get; } public string? RouteName { get; } public ImmutableArray<string>? DefaultValues { get; } public bool? HasParameters { get; } public DotHtmlFileInfo(string virtualPath, string? tagName = null, string? nameSpace = null, string? assembly = null, string? tagPrefix = null, string? url = null, string? routeName = null, ImmutableArray<string>? defaultValues = null, bool? hasParameters = null) { VirtualPath = virtualPath; Status = IsDothtmlFile(virtualPath) ? CompilationState.None : CompilationState.NonCompilable; TagName = tagName; Namespace = nameSpace; Assembly = assembly; TagPrefix = tagPrefix; Url = url; RouteName = routeName; DefaultValues = defaultValues; HasParameters = hasParameters; } private static bool IsDothtmlFile(string virtualPath) { return !string.IsNullOrWhiteSpace(virtualPath) && ( virtualPath.IndexOf(".dothtml", StringComparison.OrdinalIgnoreCase) > -1 || virtualPath.IndexOf(".dotmaster", StringComparison.OrdinalIgnoreCase) > -1 || virtualPath.IndexOf(".dotcontrol", StringComparison.OrdinalIgnoreCase) > -1 || virtualPath.IndexOf(".dotlayout", StringComparison.OrdinalIgnoreCase) > -1 ); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; namespace DotVVM.Framework.Compilation { public sealed class DotHtmlFileInfo { public CompilationState Status { get; internal set; } public string? Exception { get; internal set; } /// <summary> /// Gets or sets the virtual path to the view. /// </summary> public string VirtualPath { get; } public string? TagName { get; } public string? Namespace { get; } public string? Assembly { get; } public string? TagPrefix { get; } public string? Url { get; } public string? RouteName { get; } public ImmutableArray<string>? DefaultValues { get; } public bool? HasParameters { get; } public DotHtmlFileInfo(string virtualPath, string? tagName = null, string? nameSpace = null, string? assembly = null, string? tagPrefix = null, string? url = null, string? routeName = null, ImmutableArray<string>? defaultValues = null, bool? hasParameters = null) { VirtualPath = virtualPath; Status = IsDothtmlFile(virtualPath) ? CompilationState.None : CompilationState.NonCompilable; TagName = tagName; Namespace = nameSpace; Assembly = assembly; TagPrefix = tagPrefix; Url = url; RouteName = routeName; DefaultValues = defaultValues; HasParameters = hasParameters; } private static bool IsDothtmlFile(string virtualPath) { return !string.IsNullOrWhiteSpace(virtualPath) && ( virtualPath.IndexOf(".dothtml", StringComparison.OrdinalIgnoreCase) > -1 || virtualPath.IndexOf(".dotmaster", StringComparison.OrdinalIgnoreCase) > -1 || virtualPath.IndexOf(".dotcontrol", StringComparison.OrdinalIgnoreCase) > -1 || virtualPath.IndexOf(".dotlayout", StringComparison.OrdinalIgnoreCase) > -1 ); } } }
apache-2.0
C#
cb0eef1d2535bbb92f47c02b3b15f97d8d5aa1f3
Improve voicestats command confirm message.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/NadekoBot/Modules/Utility/VoiceStatsCommands.cs
src/NadekoBot/Modules/Utility/VoiceStatsCommands.cs
using Discord; using Discord.Commands; using Mitternacht.Common.Attributes; using Mitternacht.Modules.Utility.Services; using Mitternacht.Services; using System; using System.Threading.Tasks; namespace Mitternacht.Modules.Utility { public partial class Utility { public class VoiceStatsCommands : MitternachtSubmodule<VoiceStatsService> { private readonly DbService _db; public VoiceStatsCommands(DbService db) { _db = db; } [MitternachtCommand, Description, Usage, Aliases] [RequireContext(ContextType.Guild)] public async Task VoiceStats(IGuildUser user = null) { user = user ?? Context.User as IGuildUser; using(var uow = _db.UnitOfWork) { if (uow.VoiceChannelStats.TryGetTime(user.Id, user.GuildId, out var time)) await ConfirmLocalized("voicestats_time", user.ToString(), TimeSpan.FromSeconds(time).ToString("hh'h 'mm'min 'ss's'")).ConfigureAwait(false); else await ConfirmLocalized("voicestats_untracked", user.ToString()).ConfigureAwait(false); } } [MitternachtCommand, Description, Usage, Aliases] [RequireContext(ContextType.Guild)] [OwnerOrGuildPermission(GuildPermission.Administrator)] public async Task VoiceStatsReset(IGuildUser user) { if (user == null) return; using(var uow = _db.UnitOfWork) { uow.VoiceChannelStats.Reset(user.Id, user.GuildId); await ConfirmLocalized("voicestats_reset", user.ToString()).ConfigureAwait(false); await uow.CompleteAsync().ConfigureAwait(false); } } } } }
using Discord; using Discord.Commands; using Mitternacht.Common.Attributes; using Mitternacht.Modules.Utility.Services; using Mitternacht.Services; using System; using System.Threading.Tasks; namespace Mitternacht.Modules.Utility { public partial class Utility { public class VoiceStatsCommands : MitternachtSubmodule<VoiceStatsService> { private readonly DbService _db; public VoiceStatsCommands(DbService db) { _db = db; } [MitternachtCommand, Description, Usage, Aliases] [RequireContext(ContextType.Guild)] public async Task VoiceStats(IGuildUser user = null) { user = user ?? Context.User as IGuildUser; using(var uow = _db.UnitOfWork) { if (uow.VoiceChannelStats.TryGetTime(user.Id, user.GuildId, out var time)) await ConfirmLocalized("voicestats_time", user.ToString(), TimeSpan.FromSeconds(time).ToString("hh':'mm':'ss")).ConfigureAwait(false); else await ConfirmLocalized("voicestats_untracked", user.ToString()).ConfigureAwait(false); } } [MitternachtCommand, Description, Usage, Aliases] [RequireContext(ContextType.Guild)] [OwnerOrGuildPermission(GuildPermission.Administrator)] public async Task VoiceStatsReset(IGuildUser user) { if (user == null) return; using(var uow = _db.UnitOfWork) { uow.VoiceChannelStats.Reset(user.Id, user.GuildId); await ConfirmLocalized("voicestats_reset", user.ToString()).ConfigureAwait(false); await uow.CompleteAsync().ConfigureAwait(false); } } } } }
mit
C#
a20dfb52d5ac0461547f63a62bc6d28b6bac3bcd
save on quit too
taka-oyama/UniHttp
Assets/UniHttp/HttpContext.cs
Assets/UniHttp/HttpContext.cs
using UnityEngine; namespace UniHttp { public class HttpContext : MonoBehaviour { void Awake() { } void OnApplicationPause(bool isPaused) { if(isPaused) { HttpDispatcher.Save(); } } void OnApplicationQuit() { HttpDispatcher.Save(); } } }
using UnityEngine; namespace UniHttp { public class HttpContext : MonoBehaviour { void Awake() { } void OnApplicationPause(bool isPaused) { if(isPaused) { HttpDispatcher.Save(); } } } }
mit
C#
002ccdbb363d874197ad6de2cba6beacaa6b82a6
Remove participant count from the project details status bar in Registration status.
LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform
src/CompetitionPlatform/Views/Project/ProjectDetailsStatusBarPartial.cshtml
src/CompetitionPlatform/Views/Project/ProjectDetailsStatusBarPartial.cshtml
@model CompetitionPlatform.Models.ProjectViewModels.ProjectDetailsStatusBarViewModel @{ var showDeadline = false; var showParticipantCount = false; var participantCount = (Model.ParticipantsCount == 1) ? Model.ParticipantsCount + " participant" : Model.ParticipantsCount + " participants"; var deadline = ""; var color = ""; var status = @Model.Status.ToString().ToUpper(); } @switch (Model.Status) { case Status.Initiative: color = "blue"; break; case Status.Registration: color = "green"; showDeadline = true; showParticipantCount = true; deadline = Model.CompetitionRegistrationDeadline.ToString("dd.MM.yyyy"); //status = "COMPETITION REGISTRATION"; break; case Status.Submission: color = "red"; showDeadline = true; deadline = Model.ImplementationDeadline.ToString("dd.MM.yyyy"); break; case Status.Voting: color = "yellow"; showDeadline = true; deadline = Model.VotingDeadline.ToString("dd.MM.yyyy"); break; case Status.Archive: color = "grey"; break; } <!--green, red, yellow, blue--> <div class="progress progress--@color"> <div class="progress__bar" style="width: @Model.StatusCompletionPercent%"></div> <div class="progress__content"> <div class="row"> <div class="col-sm-6"> <div class="progress__title">@status</div> </div> <div class="col-sm-6 text-right"> <ul class="progress__info"> @*@if (showParticipantCount) { <li><i class="icon icon--participate"></i> @participantCount</li> }*@ @if (showDeadline) { <li><i class="icon icon--deadline_fill"></i> @deadline</li> } </ul> </div> </div> </div> </div>
@model CompetitionPlatform.Models.ProjectViewModels.ProjectDetailsStatusBarViewModel @{ var showDeadline = false; var showParticipantCount = false; var participantCount = (Model.ParticipantsCount == 1) ? Model.ParticipantsCount + " participant" : Model.ParticipantsCount + " participants"; var deadline = ""; var color = ""; var status = @Model.Status.ToString().ToUpper(); } @switch (Model.Status) { case Status.Initiative: color = "blue"; break; case Status.Registration: color = "green"; showDeadline = true; showParticipantCount = true; deadline = Model.CompetitionRegistrationDeadline.ToString("dd.MM.yyyy"); //status = "COMPETITION REGISTRATION"; break; case Status.Submission: color = "red"; showDeadline = true; deadline = Model.ImplementationDeadline.ToString("dd.MM.yyyy"); break; case Status.Voting: color = "yellow"; showDeadline = true; deadline = Model.VotingDeadline.ToString("dd.MM.yyyy"); break; case Status.Archive: color = "grey"; break; } <!--green, red, yellow, blue--> <div class="progress progress--@color"> <div class="progress__bar" style="width: @Model.StatusCompletionPercent%"></div> <div class="progress__content"> <div class="row"> <div class="col-sm-6"> <div class="progress__title">@status</div> </div> <div class="col-sm-6 text-right"> <ul class="progress__info"> @if (showParticipantCount) { <li><i class="icon icon--participate"></i> @participantCount</li> } @if (showDeadline) { <li><i class="icon icon--deadline_fill"></i> @deadline</li> } </ul> </div> </div> </div> </div>
mit
C#
989a51d60a1e861c476c5c6a39baa28561e324a6
Add support for plus sign prefix in Simple flavor
LouisTakePILLz/ArgumentParser
ArgumentParser/Patterns/SimpleParameterPattern.cs
ArgumentParser/Patterns/SimpleParameterPattern.cs
//----------------------------------------------------------------------- // <copyright file="SimpleParameterPattern.cs" company="LouisTakePILLz"> // Copyright © 2015 LouisTakePILLz // <author>LouisTakePILLz</author> // </copyright> //----------------------------------------------------------------------- /* This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace ArgumentParser { public static partial class Parser { #if DEBUG private const String SIMPLE_PARAMETER_PATTERN = @" (?<=^|\s) ( (?<prefix>-|\+) (?<tag>(?!-)[\w\-\+]+(?<!\-)) ) ( \s+ (?<value> ( ("" (?> \\. | [^""])* "")| (' (?> \\. | [^'])* ')| ( \\.-?| [^\-\+""'] | (?<!\s) [\-\+]+ | [\-\+]+ (?=\d|[^\-\+\w\""]|$) )+ )+ ) )? (?=\s|$)"; #else private const String SIMPLE_PARAMETER_PATTERN = @"(?<=^|\s)((?<prefix>-|\+)(?<tag>[\w\-\+]+(?<!\-)))(\s+(?<value>((""(?>\\.|[^""])*"")|('(?>\\.|[^'])*')|(\\.-?|[^\-\+""']|(?<!\s)[\-\+]+|[\-\+]+(?=\d|[^\-\+\w\""]|$))+)+))?(?=\s|$)"; #endif } }
//----------------------------------------------------------------------- // <copyright file="SimpleParameterPattern.cs" company="LouisTakePILLz"> // Copyright © 2015 LouisTakePILLz // <author>LouisTakePILLz</author> // </copyright> //----------------------------------------------------------------------- /* This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace ArgumentParser { public static partial class Parser { #if DEBUG private const String SIMPLE_PARAMETER_PATTERN = @" (?<=^|\s) ( (?<prefix>-) (?<tag>(?!-)[\w\-]+(?<!\-)) ) ( \s+ (?<value> ( ("" (?> \\. | [^""])* "")| (' (?> \\. | [^'])* ')| ( \\.-?| [^\-""'] | (?<!\s) \-+ | \-+ (?=\d|[^\-\w\""]|$) )+ )+ ) )? (?=\s|$)"; #else private const String SIMPLE_PARAMETER_PATTERN = @"(?<=^|\s)((?<prefix>-)(?<tag>(?!-)[\w\-]+(?<!\-)))(\s+(?<value>((""(?>\\.|[^""])*"")|('(?>\\.|[^'])*')|(\\.-?|[^\-""']|(?<!\s)\-+|\-+(?=\d|[^\-\w\""]|$))+)+))?(?=\s|$)"; #endif } }
apache-2.0
C#
c6b22302245637e626a4055a6d35a62788832abf
Add EtherType enumeration for some types (not all)
juhovh/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,juhovh/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,zhanleewo/tapcfg,zhanleewo/tapcfg,zhanleewo/tapcfg,juhovh/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,juhovh/tapcfg,juhovh/tapcfg,juhovh/tapcfg,eyecreate/tapcfg
src/bindings/EthernetFrame.cs
src/bindings/EthernetFrame.cs
using System; namespace TAPCfg { public enum EtherType : int { InterNetwork = 0x0800, ARP = 0x0806, RARP = 0x8035, AppleTalk = 0x809b, AARP = 0x80f3, InterNetworkV6 = 0x86dd, CobraNet = 0x8819, } public class EthernetFrame { private byte[] data; private byte[] src = new byte[6]; private byte[] dst = new byte[6]; private int etherType; public EthernetFrame(byte[] data) { this.data = data; Array.Copy(data, 0, dst, 0, 6); Array.Copy(data, 6, src, 0, 6); etherType = (data[12] << 8) | data[13]; } public byte[] Data { get { return data; } } public int Length { get { return data.Length; } } public byte[] SourceAddress { get { return src; } } public byte[] DestinationAddress { get { return dst; } } public int EtherType { get { return etherType; } } public byte[] Payload { get { byte[] ret = new byte[data.Length - 14]; Array.Copy(data, 14, ret, 0, ret.Length); return ret; } } } }
using System; namespace TAPCfg { public class EthernetFrame { private byte[] data; private byte[] src = new byte[6]; private byte[] dst = new byte[6]; private int etherType; public EthernetFrame(byte[] data) { this.data = data; Array.Copy(data, 0, dst, 0, 6); Array.Copy(data, 6, src, 0, 6); etherType = (data[12] << 8) | data[13]; } public byte[] Data { get { return data; } } public int Length { get { return data.Length; } } public byte[] SourceAddress { get { return src; } } public byte[] DestinationAddress { get { return dst; } } public int EtherType { get { return etherType; } } public byte[] Payload { get { byte[] ret = new byte[data.Length - 14]; Array.Copy(data, 14, ret, 0, ret.Length); return ret; } } } }
lgpl-2.1
C#
a8d0ff67a9bf0ad5e469430131999a2c630f3771
Add automated match settings overlay tests
ZLima12/osu,ZLima12/osu,johnneijzen/osu,ppy/osu,peppy/osu,DrabWeb/osu,peppy/osu,ppy/osu,EVAST9919/osu,naoey/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,2yangk23/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,naoey/osu,DrabWeb/osu,naoey/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,DrabWeb/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,johnneijzen/osu,smoogipooo/osu
osu.Game.Tests/Visual/TestCaseMatchSettingsOverlay.cs
osu.Game.Tests/Visual/TestCaseMatchSettingsOverlay.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 NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi; using osu.Game.Screens.Multi.Lounge.Components; using osu.Game.Screens.Multi.Match.Components; namespace osu.Game.Tests.Visual { public class TestCaseMatchSettingsOverlay : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(RoomSettingsOverlay) }; [Cached(Type = typeof(IRoomManager))] private TestRoomManager roomManager = new TestRoomManager(); private Room room; private TestRoomSettings settings; [SetUp] public void Setup() => Schedule(() => { room = new Room(); settings = new TestRoomSettings(room) { RelativeSizeAxes = Axes.Both, State = Visibility.Visible }; Child = settings; }); [Test] public void TestButtonEnabledOnlyWithNameAndBeatmap() { AddStep("clear name and beatmap", () => { room.Name.Value = ""; room.Playlist.Clear(); }); AddAssert("button disabled", () => !settings.ApplyButton.Enabled); AddStep("set name", () => room.Name.Value = "Room name"); AddAssert("button disabled", () => !settings.ApplyButton.Enabled); AddStep("set beatmap", () => room.Playlist.Add(new PlaylistItem { Beatmap = new DummyWorkingBeatmap().BeatmapInfo })); AddAssert("button enabled", () => settings.ApplyButton.Enabled); AddStep("clear name", () => room.Name.Value = ""); AddAssert("button disabled", () => !settings.ApplyButton.Enabled); } [Test] public void TestCorrectSettingsApplied() { const string expected_name = "expected name"; TimeSpan expectedDuration = TimeSpan.FromMinutes(15); Room createdRoom = null; AddStep("setup", () => { settings.NameField.Current.Value = expected_name; settings.DurationField.Current.Value = expectedDuration; roomManager.CreateRequested = r => createdRoom = r; }); AddStep("create room", () => settings.ApplyButton.Action.Invoke()); AddAssert("has correct name", () => createdRoom.Name.Value == expected_name); AddAssert("has correct duration", () => createdRoom.Duration.Value == expectedDuration); } private class TestRoomSettings : RoomSettingsOverlay { public new TriangleButton ApplyButton => base.ApplyButton; public new OsuTextBox NameField => base.NameField; public new OsuDropdown<TimeSpan> DurationField => base.DurationField; public TestRoomSettings(Room room) : base(room) { } } private class TestRoomManager : IRoomManager { public Action<Room> CreateRequested; public event Action<Room> OpenRequested; public IBindableCollection<Room> Rooms { get; } = null; public void CreateRoom(Room room) => CreateRequested?.Invoke(room); public void JoinRoom(Room room) => throw new NotImplementedException(); public void PartRoom() => throw new NotImplementedException(); public void Filter(FilterCriteria criteria) => throw new NotImplementedException(); } } }
// 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.Graphics.Containers; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi.Match.Components; namespace osu.Game.Tests.Visual { public class TestCaseMatchSettingsOverlay : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(RoomSettingsOverlay) }; public TestCaseMatchSettingsOverlay() { Child = new RoomSettingsOverlay(new Room()) { RelativeSizeAxes = Axes.Both, State = Visibility.Visible }; } } }
mit
C#
4f826589e51fc504db7f0ece73fa94e2e9da374c
Remove subscription logic for the time being
NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu
osu.Game/Skinning/LegacyDatabasedSkinResourceStore.cs
osu.Game/Skinning/LegacyDatabasedSkinResourceStore.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Extensions; using osu.Framework.IO.Stores; using osu.Game.Extensions; namespace osu.Game.Skinning { public class LegacyDatabasedSkinResourceStore : ResourceStore<byte[]> { private readonly Dictionary<string, string> fileToStoragePathMapping = new Dictionary<string, string>(); public LegacyDatabasedSkinResourceStore(SkinInfo source, IResourceStore<byte[]> underlyingStore) : base(underlyingStore) { initialiseFileCache(source); } private void initialiseFileCache(SkinInfo source) { fileToStoragePathMapping.Clear(); foreach (var f in source.Files) fileToStoragePathMapping[f.Filename.ToLowerInvariant()] = f.File.GetStoragePath(); } protected override IEnumerable<string> GetFilenames(string name) { foreach (string filename in base.GetFilenames(name)) { string path = getPathForFile(filename.ToStandardisedPath()); if (path != null) yield return path; } } private string getPathForFile(string filename) => fileToStoragePathMapping.TryGetValue(filename.ToLower(), out string path) ? path : null; public override IEnumerable<string> GetAvailableResources() => fileToStoragePathMapping.Keys; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using osu.Framework.Development; using osu.Framework.Extensions; using osu.Framework.IO.Stores; using osu.Game.Extensions; using Realms; namespace osu.Game.Skinning { public class LegacyDatabasedSkinResourceStore : ResourceStore<byte[]> { private readonly Dictionary<string, string> fileToStoragePathMapping = new Dictionary<string, string>(); private readonly IDisposable subscription; public LegacyDatabasedSkinResourceStore(SkinInfo source, IResourceStore<byte[]> underlyingStore) : base(underlyingStore) { // Subscribing to non-managed instances doesn't work. // In this usage, the skin may be non-managed in tests. if (source.IsManaged) { // Subscriptions can only work on the main thread. Debug.Assert(ThreadSafety.IsUpdateThread); subscription = source.Files .AsRealmCollection().SubscribeForNotifications((sender, changes, error) => { if (changes == null) return; // If a large number of changes are made on skin files, this may be better suited to being cleared here // and reinitialised on next usage. initialiseFileCache(source); }); } initialiseFileCache(source); } ~LegacyDatabasedSkinResourceStore() { Dispose(false); } private void initialiseFileCache(SkinInfo source) { fileToStoragePathMapping.Clear(); foreach (var f in source.Files) fileToStoragePathMapping[f.Filename.ToLowerInvariant()] = f.File.GetStoragePath(); } protected override IEnumerable<string> GetFilenames(string name) { foreach (string filename in base.GetFilenames(name)) { string path = getPathForFile(filename.ToStandardisedPath()); if (path != null) yield return path; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); subscription?.Dispose(); } private string getPathForFile(string filename) => fileToStoragePathMapping.TryGetValue(filename.ToLower(), out string path) ? path : null; public override IEnumerable<string> GetAvailableResources() => fileToStoragePathMapping.Keys; } }
mit
C#
3a512bd4ffbc3d1fee87366af0154c3e979d26dc
Update WrenchBg.cs
uulltt/NitoriWare
Assets/Resources/Microgames/_Finished/Wrench/Scripts/WrenchBg.cs
Assets/Resources/Microgames/_Finished/Wrench/Scripts/WrenchBg.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class WrenchBg : MonoBehaviour { #pragma warning disable 0649 [SerializeField] private bool update; [SerializeField] private int linesX, linesY; [SerializeField] private float lineSeparation, lineExtent; [SerializeField] private Vector3 linesStart; #pragma warning restore 0649 private LineRenderer lineRenderer; //void Awake() //{ // lineRenderer = GetComponent<LineRenderer>(); //} void Update() { if (update) { if (lineRenderer == null) lineRenderer = GetComponent<LineRenderer>(); createLines(); update = false; } } void createLines() { List<Vector3> points = new List<Vector3>(); for (int i = 0; i < linesX; i++) { float x = linesStart.x + (lineSeparation * (float)i), y = (((i % 2) * 2)-1)*lineExtent; points.Add(new Vector3(x, y, 0f)); points.Add(new Vector3(x, -y, 0f)); } for (int i = 0; i < linesY; i++) { float y = linesStart.y + (lineSeparation * (float)i), x = i % 2 == 1 ? lineExtent : -lineExtent; points.Add(new Vector3(x, y, 0f)); points.Add(new Vector3(-x, y, 0f)); } lineRenderer.positionCount = points.Count; lineRenderer.SetPositions(points.ToArray()); //lineRenderer.SetPositions(new Vector3[points.Count]); //for (int i = 0; i < points.Count; i++) //{ // lineRenderer.SetPosition(i, points[i]); //} } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class WrenchBg : MonoBehaviour { #pragma warning disable 0649 [SerializeField] private bool update; [SerializeField] private int linesX, linesY; [SerializeField] private float lineSeparation, lineExtent; [SerializeField] private Vector3 linesStart; #pragma warning restore 0649 private LineRenderer lineRenderer; //void Awake() //{ // lineRenderer = GetComponent<LineRenderer>(); //} void Update() { if (update) { if (lineRenderer == null) lineRenderer = GetComponent<LineRenderer>(); createLines(); update = false; } } void createLines() { List<Vector3> points = new List<Vector3>(); for (int i = 0; i < linesX; i++) { float x = linesStart.x + (lineSeparation * (float)i), y = i % 2 == 1 ? lineExtent : -lineExtent; points.Add(new Vector3(x, y, 0f)); points.Add(new Vector3(x, -y, 0f)); } for (int i = 0; i < linesY; i++) { float y = linesStart.y + (lineSeparation * (float)i), x = i % 2 == 1 ? lineExtent : -lineExtent; points.Add(new Vector3(x, y, 0f)); points.Add(new Vector3(-x, y, 0f)); } lineRenderer.positionCount = points.Count; lineRenderer.SetPositions(points.ToArray()); //lineRenderer.SetPositions(new Vector3[points.Count]); //for (int i = 0; i < points.Count; i++) //{ // lineRenderer.SetPosition(i, points[i]); //} } }
mit
C#
2e971403a05f37546c413e3992ef648e1ab11f2b
Use V2 definition handler for LSP as well.
OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
src/OmniSharp.LanguageServerProtocol/Handlers/OmniSharpDefinitionHandler.cs
src/OmniSharp.LanguageServerProtocol/Handlers/OmniSharpDefinitionHandler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Models.V2.GotoDefinition; using static OmniSharp.LanguageServerProtocol.Helpers; namespace OmniSharp.LanguageServerProtocol.Handlers { class OmniSharpDefinitionHandler : DefinitionHandlerBase { public static IEnumerable<IJsonRpcHandler> Enumerate(RequestHandlers handlers) { foreach (var (selector, handler) in handlers.OfType<Mef.IRequestHandler<GotoDefinitionRequest, GotoDefinitionResponse>>()) if (handler != null) yield return new OmniSharpDefinitionHandler(handler, selector); } private readonly Mef.IRequestHandler<GotoDefinitionRequest, GotoDefinitionResponse> _definitionHandler; private readonly DocumentSelector _documentSelector; public OmniSharpDefinitionHandler(Mef.IRequestHandler<GotoDefinitionRequest, GotoDefinitionResponse> definitionHandler, DocumentSelector documentSelector) { _definitionHandler = definitionHandler; _documentSelector = documentSelector; } public override async Task<LocationOrLocationLinks> Handle(DefinitionParams request, CancellationToken token) { var omnisharpRequest = new GotoDefinitionRequest() { FileName = FromUri(request.TextDocument.Uri), Column = Convert.ToInt32(request.Position.Character), Line = Convert.ToInt32(request.Position.Line) }; var omnisharpResponse = await _definitionHandler.Handle(omnisharpRequest); if (omnisharpResponse.Definitions == null) { return new LocationOrLocationLinks(); } return new LocationOrLocationLinks(omnisharpResponse.Definitions.Select<Definition, LocationOrLocationLink>(definition => new Location() { Uri = definition.Location.FileName, Range = ToRange(definition.Location.Range) })); } protected override DefinitionRegistrationOptions CreateRegistrationOptions(DefinitionCapability capability, ClientCapabilities clientCapabilities) { return new DefinitionRegistrationOptions() { DocumentSelector = _documentSelector }; } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; using OmniSharp.Models.GotoDefinition; using static OmniSharp.LanguageServerProtocol.Helpers; namespace OmniSharp.LanguageServerProtocol.Handlers { class OmniSharpDefinitionHandler : DefinitionHandlerBase { public static IEnumerable<IJsonRpcHandler> Enumerate(RequestHandlers handlers) { foreach (var (selector, handler) in handlers.OfType<Mef.IRequestHandler<GotoDefinitionRequest, GotoDefinitionResponse>>()) if (handler != null) yield return new OmniSharpDefinitionHandler(handler, selector); } private readonly Mef.IRequestHandler<GotoDefinitionRequest, GotoDefinitionResponse> _definitionHandler; private readonly DocumentSelector _documentSelector; public OmniSharpDefinitionHandler(Mef.IRequestHandler<GotoDefinitionRequest, GotoDefinitionResponse> definitionHandler, DocumentSelector documentSelector) { _definitionHandler = definitionHandler; _documentSelector = documentSelector; } public override async Task<LocationOrLocationLinks> Handle(DefinitionParams request, CancellationToken token) { var omnisharpRequest = new GotoDefinitionRequest() { FileName = FromUri(request.TextDocument.Uri), Column = Convert.ToInt32(request.Position.Character), Line = Convert.ToInt32(request.Position.Line) }; var omnisharpResponse = await _definitionHandler.Handle(omnisharpRequest); if (string.IsNullOrWhiteSpace(omnisharpResponse.FileName)) { return new LocationOrLocationLinks(); } return new LocationOrLocationLinks(new Location() { Uri = ToUri(omnisharpResponse.FileName), Range = ToRange((omnisharpResponse.Column, omnisharpResponse.Line)) }); } protected override DefinitionRegistrationOptions CreateRegistrationOptions(DefinitionCapability capability, ClientCapabilities clientCapabilities) { return new DefinitionRegistrationOptions() { DocumentSelector = _documentSelector }; } } }
mit
C#
b702f5462930aa68d9dfe013978f44bd4e6940d2
fix namespace
eriklieben/ErikLieben.Data.EF
ErikLieben.Data.EF/Repository/IDatabaseFactory.cs
ErikLieben.Data.EF/Repository/IDatabaseFactory.cs
namespace ErikLieben.Data.Repository { using System.Data.Entity; public interface IDatabaseFactory { DbContext CreateContext(); } }
namespace ErikLieben.Data { using System.Data.Entity; public interface IDatabaseFactory { DbContext CreateContext(); } }
mit
C#
08fb5c279728d2d377382d70f677e108f66b060d
Fix path to local key file
Redth/Cake.AppVeyor,Redth/Cake.AppVeyor
src/Cake.AppVeyor.Tests/Keys.cs
src/Cake.AppVeyor.Tests/Keys.cs
using System; using System.IO; namespace Cake.AppVeyor.Tests { public static class Keys { const string YOUR_APPVEYOR_API_TOKEN = "{APPVEYOR_APITOKEN}"; static string appVeyorApiToken; public static string AppVeyorApiToken { get { if (appVeyorApiToken == null) { // Check for a local file with a token first var localFile = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", ".appveyorapitoken"); if (File.Exists(localFile)) appVeyorApiToken = File.ReadAllText(localFile); // Next check for an environment variable if (string.IsNullOrEmpty(appVeyorApiToken)) appVeyorApiToken = Environment.GetEnvironmentVariable("appveyor_api_token"); // Finally use the const value if (string.IsNullOrEmpty(appVeyorApiToken)) appVeyorApiToken = YOUR_APPVEYOR_API_TOKEN; } return appVeyorApiToken; } } } }
using System; using System.IO; namespace Cake.AppVeyor.Tests { public static class Keys { const string YOUR_APPVEYOR_API_TOKEN = "{APPVEYOR_APITOKEN}"; static string appVeyorApiToken; public static string AppVeyorApiToken { get { if (appVeyorApiToken == null) { // Check for a local file with a token first var localFile = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", ".appveyorapitoken"); if (File.Exists(localFile)) appVeyorApiToken = File.ReadAllText(localFile); // Next check for an environment variable if (string.IsNullOrEmpty(appVeyorApiToken)) appVeyorApiToken = Environment.GetEnvironmentVariable("appveyor_api_token"); // Finally use the const value if (string.IsNullOrEmpty(appVeyorApiToken)) appVeyorApiToken = YOUR_APPVEYOR_API_TOKEN; } return appVeyorApiToken; } } } }
apache-2.0
C#
5992b96de5965db7a0ece73fbaea5105b1b3c4a5
Update JsonStringConverter.cs
he-dev/Reusable,he-dev/Reusable
Reusable.Utilities.JsonNet/src/Converters/JsonStringConverter.cs
Reusable.Utilities.JsonNet/src/Converters/JsonStringConverter.cs
using System; using System.Collections.Immutable; using System.Linq; using System.Reflection; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Reusable.Exceptionize; using Reusable.Extensions; using Reusable.Utilities.JsonNet.Annotations; namespace Reusable.Utilities.JsonNet.Converters { [PublicAPI] public class JsonStringConverter : JsonConverter { private readonly IImmutableSet<Type> _stringTypes; public JsonStringConverter(params Type[] stringTypes) { _stringTypes = stringTypes.ToImmutableHashSet(); } public override bool CanConvert(Type objectType) { return objectType.GetCustomAttributes<JsonStringAttribute>().Any() || _stringTypes.Contains(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jToken = JToken.Load(reader); var value = jToken.Value<string>(); if (value is null) { return default; } if (objectType.GetConstructor(new[] { typeof(string) }) is var constructor && !(constructor is null)) { return constructor.Invoke(new object[] { value }); } if (objectType.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static) is var parse && !(parse is null)) { return parse.Invoke(null, new object[] { value }); } throw DynamicException.Create ( "CannotCreateObject", $"{objectType.ToPrettyString()} is decorated with the {nameof(JsonStringAttribute)} so it must either have a constructor with a string parameter or a static Parse method." ); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } } }
using System; using System.Collections.Immutable; using System.Linq; using System.Reflection; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Reusable.Exceptionize; using Reusable.Extensions; using Reusable.Utilities.JsonNet.Annotations; namespace Reusable.Utilities.JsonNet.Converters { [PublicAPI] public class JsonStringConverter : JsonConverter { private readonly IImmutableSet<Type> _stringTypes; public JsonStringConverter(params Type[] stringTypes) { _stringTypes = stringTypes.ToImmutableHashSet(); } public override bool CanConvert(Type objectType) { return objectType.GetCustomAttributes<JsonStringAttribute>().Any() || _stringTypes.Contains(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jToken = JToken.Load(reader); var value = jToken.Value<string>(); if (objectType.GetConstructor(new[] { typeof(string) }) is var constructor && !(constructor is null)) { return constructor.Invoke(new object[] { value }); } if (objectType.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static) is var parse && !(parse is null)) { return parse.Invoke(null, new object[] { value }); } throw DynamicException.Create ( "CannotCreateObject", $"{objectType.ToPrettyString()} is decorated with the {nameof(JsonStringAttribute)} so it must either have a constructor with a string parameter or a static Parse method." ); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } } }
mit
C#
958a82c76e980e3694fcac451723dcffb26434f3
修复Property模块的TootipEdit BUG。
anycmd/anycmd,anycmd/anycmd,anycmd/anycmd,anycmd/anycmd,anycmd/anycmd
src/Examples/Default/Mis/AnycmdMisSite/Areas/Ac/Views/Property/TooltipEdit.cshtml
src/Examples/Default/Mis/AnycmdMisSite/Areas/Ac/Views/Property/TooltipEdit.cshtml
@model Anycmd.Engine.Ac.Abstractions.Infra.IProperty @{ ViewBag.Title = "编辑字段帮助-" + Model.Name; Layout = "~/Views/Shared/_Layout.cshtml"; } <div id="win1" class="mini-window" title="编辑字段帮助-@Model.Name" iconcls="icon-edit" style="width: 100%; height: 100%;" showmaxbutton="false" showfooter="true" showtoolbar="true" showCloseButton="false" showmodal="true" allowresize="true" allowdrag="true"> <div property="toolbar"> <a class="mini-button btnOk" iconcls="icon-save" style="width: 60px; margin-right: 10px;">保存</a> </div> <div property="footer" style="text-align: center;"> <a class="mini-button btnOk" iconcls="icon-save" style="width: 60px; margin-right: 10px;">保存</a> </div> <form id="form1" method="post"> <input name="propertyId" value="@Model.Id" class="mini-hidden" /> <input id="hdTooltip" name="Tooltip" class="mini-hidden" /> <table style="width: 100%; height: 100%;"> <tr> <td valign="top" style="width: 70px;"> @Html.IconLabel("Tooltip", "Property", "Ac") </td> <td> <textarea id="txtTooltip" style="display: inline-block; visibility: hidden;">@Html.Raw(Model.Tooltip)</textarea> </td> </tr> </table> </form> </div> @section Foot{ <script src="@Url.Content("~/Scripts/kindeditor/kindeditor-min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/kindeditor/lang/zh_CN.js")" type="text/javascript"></script> <script type="text/javascript" src="@Url.Content("~/Scripts/Areas/Ac/Property/TooltipEdit.cshtml.js")"></script> }
@model IProperty @{ ViewBag.Title = "编辑字段帮助-" + Model.Name; Layout = "~/Views/Shared/_Layout.cshtml"; } <div id="win1" class="mini-window" title="编辑字段帮助-@Model.Name" iconcls="icon-edit" style="width: 100%; height: 100%;" showmaxbutton="false" showfooter="true" showtoolbar="true" showCloseButton="false" showmodal="true" allowresize="true" allowdrag="true"> <div property="toolbar"> <a class="mini-button btnOk" iconcls="icon-save" style="width: 60px; margin-right: 10px;">保存</a> </div> <div property="footer" style="text-align: center;"> <a class="mini-button btnOk" iconcls="icon-save" style="width: 60px; margin-right: 10px;">保存</a> </div> <form id="form1" method="post"> <input name="propertyId" value="@Model.Id" class="mini-hidden" /> <input id="hdTooltip" name="Tooltip" class="mini-hidden" /> <table style="width: 100%; height: 100%;"> <tr> <td valign="top" style="width: 70px;"> @Html.IconLabel("Tooltip", "Property", "Ac") </td> <td> <textarea id="txtTooltip" style="display: inline-block; visibility: hidden;">@Html.Raw(Model.Tooltip)</textarea> </td> </tr> </table> </form> </div> @section Foot{ <script src="@Url.Content("~/Scripts/kindeditor/kindeditor-min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/kindeditor/lang/zh_CN.js")" type="text/javascript"></script> <script type="text/javascript" src="@Url.Content("~/Scripts/Areas/Ac/Property/TooltipEdit.cshtml.js")"></script> }
mit
C#
5b012080c6350e1e3ae807e960946110e8df5035
Fix test
rasmus/EventFlow,liemqv/EventFlow,AntoineGa/EventFlow
Source/EventFlow/Extensions/ResolverExtensions.cs
Source/EventFlow/Extensions/ResolverExtensions.cs
// The MIT License (MIT) // // Copyright (c) 2015 Rasmus Mikkelsen // https://github.com/rasmus/EventFlow // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using Autofac; using EventFlow.Aggregates; using EventFlow.Configuration; namespace EventFlow.Extensions { public static class ResolverExtensions { public static void ValidateRegistrations( this IResolver resolver) { var exceptions = new List<Exception>(); foreach (var type in resolver.GetRegisteredServices().Where(t => !t.IsClosedTypeOf(typeof(IAggregateRoot<>)))) { try { resolver.Resolve(type); } catch (Exception ex) { exceptions.Add(ex); } } if (!exceptions.Any()) { return; } var message = string.Join(", ", exceptions.Select(e => e.Message)); throw new AggregateException(message, exceptions); } } }
// The MIT License (MIT) // // Copyright (c) 2015 Rasmus Mikkelsen // https://github.com/rasmus/EventFlow // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using EventFlow.Configuration; namespace EventFlow.Extensions { public static class ResolverExtensions { public static void ValidateRegistrations( this IResolver resolver) { var exceptions = new List<Exception>(); foreach (var type in resolver.GetRegisteredServices()) { try { resolver.Resolve(type); } catch (Exception ex) { exceptions.Add(ex); } } if (!exceptions.Any()) { return; } var message = string.Join(", ", exceptions.Select(e => e.Message)); throw new AggregateException(message, exceptions); } } }
mit
C#
e7518da53b25c59c8e30acec154be7f5f1c48676
Update ToString()
yishn/GTPWrapper
GTPWrapper/Sgf/SgfGameTree.cs
GTPWrapper/Sgf/SgfGameTree.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Drawing; using System.Diagnostics; namespace GTPWrapper.Sgf { /// <summary> /// Represents a SGF game tree. /// </summary> public class SgfGameTree { /// <summary> /// The node list of the game tree. /// </summary> public List<SgfNode> Nodes { get; set; } /// <summary> /// The list of all subtrees. /// </summary> public List<SgfGameTree> GameTrees { get; set; } /// <summary> /// Initializes a new instance of the SgfGameTree class. /// </summary> public SgfGameTree() { this.Nodes = new List<SgfNode>(); this.GameTrees = new List<SgfGameTree>(); } /// <summary> /// Returns a string which represents the object. /// </summary> public override string ToString() { return string.Join("\n", this.Nodes) + (this.Nodes.Count == 0 || this.GameTrees.Count == 0 ? "" : "\n") + (this.GameTrees.Count == 0 ? "" : "(" + string.Join(")\n(", this.GameTrees) + ")"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Drawing; using System.Diagnostics; namespace GTPWrapper.Sgf { /// <summary> /// Represents a SGF game tree. /// </summary> public class SgfGameTree { /// <summary> /// The node list of the game tree. /// </summary> public List<SgfNode> Nodes { get; set; } /// <summary> /// The list of all subtrees. /// </summary> public List<SgfGameTree> GameTrees { get; set; } /// <summary> /// Initializes a new instance of the SgfGameTree class. /// </summary> public SgfGameTree() { this.Nodes = new List<SgfNode>(); this.GameTrees = new List<SgfGameTree>(); } /// <summary> /// Returns a string which represents the object. /// </summary> public override string ToString() { return string.Join("\n", this.Nodes) + (this.GameTrees.Count == 0 ? "" : "\n(" + string.Join(")\n(", this.GameTrees) + ")"); } } }
mit
C#
ffcfa52bfc3ea8812c80f79373543eda7cdcd441
add ForceNotify to IReactiveProperty
runceel/ReactiveProperty,runceel/ReactiveProperty,runceel/ReactiveProperty
Source/ReactiveProperty.Core/IReactiveProperty.cs
Source/ReactiveProperty.Core/IReactiveProperty.cs
using System; using System.ComponentModel; namespace Reactive.Bindings { /// <summary> /// for EventToReactive and Serialization /// </summary> public interface IReactiveProperty : IReadOnlyReactiveProperty, IHasErrors, INotifyPropertyChanged { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> new object Value { get; set; } /// <summary> /// Forces the notify. /// </summary> void ForceNotify(); } /// <summary> /// </summary> /// <typeparam name="T"></typeparam> /// <seealso cref="Reactive.Bindings.IHasErrors"/> public interface IReactiveProperty<T> : IReactiveProperty, IReadOnlyReactiveProperty<T>, IObservable<T>, IDisposable, INotifyDataErrorInfo { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> new T Value { get; set; } } }
using System; using System.ComponentModel; namespace Reactive.Bindings { /// <summary> /// for EventToReactive and Serialization /// </summary> public interface IReactiveProperty : IReadOnlyReactiveProperty, IHasErrors, INotifyPropertyChanged { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> new object Value { get; set; } } /// <summary> /// </summary> /// <typeparam name="T"></typeparam> /// <seealso cref="Reactive.Bindings.IHasErrors"/> public interface IReactiveProperty<T> : IReactiveProperty, IReadOnlyReactiveProperty<T>, IObservable<T>, IDisposable, INotifyDataErrorInfo { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> new T Value { get; set; } } }
mit
C#
dd60df6f1485ba8af59832d50e42be1e2af6d962
Update Program.cs
kuroblog/Helloworld
SourceCode/Helloworld/Helloworld.Basic/Program.cs
SourceCode/Helloworld/Helloworld.Basic/Program.cs
 namespace Helloworld.Basic { using System; class Program { static void Main(string[] args) { var msg = "Helloworld!"; Console.WriteLine(msg); Console.ReadKey(); } } }
 namespace Helloworld.Basic { using System; class Program { static void Main(string[] args) { Console.WriteLine("Helloworld!"); Console.ReadKey(); } } }
mit
C#
faded4975d5d5b8137425113efd446967d6d8c50
Update INetworkConnectivityService.cs
tiksn/TIKSN-Framework
TIKSN.Core/Network/INetworkConnectivityService.cs
TIKSN.Core/Network/INetworkConnectivityService.cs
using System; namespace TIKSN.Network { public interface INetworkConnectivityService { IObservable<InternetConnectivityState> InternetConnectivityChanged { get; } InternetConnectivityState GetInternetConnectivityState(); } }
using System; namespace TIKSN.Network { public interface INetworkConnectivityService { IObservable<InternetConnectivityState> InternetConnectivityChanged { get; } InternetConnectivityState GetInternetConnectivityState(); } }
mit
C#
ecc3c5a8e5cebee9e2aef6f1b001c24460ddd482
Update Size2.cs
Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Core2D.Spatial/Size2.cs
src/Core2D.Spatial/Size2.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Core2D.Spatial { public struct Size2 { public readonly double Width; public readonly double Height; public Size2(double width, double height) { this.Width = width; this.Height = height; } public void Deconstruct(out double width, out double height) { width = this.Width; height = this.Height; } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Core2D.Spatial { public struct Size2 { public readonly double Width; public readonly double Height; public Size2(double width, double height) { this.Width = width; this.Height = height; } } }
mit
C#
2bd31bdfd27780f8ec930bd6af99bb6cc5c41409
Test grouped values
Sora2455/Sora-s-Nerd-Den,Sora2455/Sora-s-Nerd-Den,Sora2455/Sora-s-Nerd-Den,Sora2455/Sora-s-Nerd-Den
Testing/ConcurrentDictionaryOfCollectionsTests.cs
Testing/ConcurrentDictionaryOfCollectionsTests.cs
using System; using System.Linq; using Common.Concurrency; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Testing { [TestClass] public class ConcurrentDictionaryOfCollectionsTests { [TestMethod] public void AddAndGetSingleValues() { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); testDic.Add(1, "There"); testDic.Add(2, "Hello"); testDic.Add(3, "World"); Assert.AreEqual(testDic.Get(0).FirstOrDefault(), "Hi"); Assert.AreEqual(testDic.Get(1).FirstOrDefault(), "There"); Assert.AreEqual(testDic.Get(2).FirstOrDefault(), "Hello"); Assert.AreEqual(testDic.Get(3).FirstOrDefault(), "World"); } [TestMethod] public void AddAndGetGroupedValues() { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); testDic.Add(0, "There"); testDic.Add(0, "Hello"); testDic.Add(0, "World"); string[] finalValues = testDic.Get(0).ToArray(); Assert.AreEqual(finalValues[0], "Hi"); Assert.AreEqual(finalValues[1], "There"); Assert.AreEqual(finalValues[2], "Hello"); Assert.AreEqual(finalValues[3], "World"); } } }
using System; using System.Linq; using Common.Concurrency; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Testing { [TestClass] public class ConcurrentDictionaryOfCollectionsTests { [TestMethod] public void AddAndGetSingleValues() { ConcurrentDictionaryOfCollections<int, string> testDic = new ConcurrentDictionaryOfCollections<int, string>(); testDic.Add(0, "Hi"); testDic.Add(1, "There"); testDic.Add(2, "Hello"); testDic.Add(3, "World"); Assert.AreEqual(testDic.Get(0).FirstOrDefault(), "Hi"); Assert.AreEqual(testDic.Get(1).FirstOrDefault(), "There"); Assert.AreEqual(testDic.Get(2).FirstOrDefault(), "Hello"); Assert.AreEqual(testDic.Get(3).FirstOrDefault(), "World"); } } }
mit
C#
9e4b50ad886a536812108182840083e04e453fe9
Allow whitespaces.
moritzuehling/MagicLinkPlugin,moritzuehling/MagicLinkPlugin
MagicLinkPlugin/MagicLinks.cs
MagicLinkPlugin/MagicLinks.cs
using Fancyauth.API; using Fancyauth.APIUtil; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace MagicLinkPlugin { class MagicLinks : PluginBase { private static readonly Regex LinkPattern = new Regex(@"^\s*<a href=""([^""]*)"">([^<]*)<\/a>\s*$", RegexOptions.Compiled); public override async Task OnChatMessage(IUser sender, IEnumerable<IChannelShim> channels, string message) { var linkMatch = LinkPattern.Match(message); if (linkMatch.Success && (linkMatch.Groups[1].Captures[0].Value == linkMatch.Groups[2].Captures[0].Value)) { var link = linkMatch.Groups[1].Captures[0].Value; var clientHandler = new HttpClientHandler { Proxy = new WebProxy("http://127.0.0.1:8118") }; var res = await LinkHandler.GetContent(link, clientHandler); if (res == null) return; foreach (var chan in channels) foreach (var msg in res) await chan.SendMessage(msg); } } public string GetFileSizeString(int size) { if (size < 1024) return size + " Bytes"; if (size < 1024 * 1024) return (size / 1024.0).ToString("0.00") + " KiB"; return (size / (1024.0 * 1024.0)).ToString("0.00") + " MiB"; } } }
using Fancyauth.API; using Fancyauth.APIUtil; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace MagicLinkPlugin { class MagicLinks : PluginBase { private static readonly Regex LinkPattern = new Regex(@"^<a href=""([^""]*)"">([^<]*)<\/a>$", RegexOptions.Compiled); public override async Task OnChatMessage(IUser sender, IEnumerable<IChannelShim> channels, string message) { var linkMatch = LinkPattern.Match(message); if (linkMatch.Success && (linkMatch.Groups[1].Captures[0].Value == linkMatch.Groups[2].Captures[0].Value)) { var link = linkMatch.Groups[1].Captures[0].Value; var clientHandler = new HttpClientHandler { Proxy = new WebProxy("http://127.0.0.1:8118") }; var res = await LinkHandler.GetContent(link, clientHandler); if (res == null) return; foreach (var chan in channels) foreach (var msg in res) await chan.SendMessage(msg); } } public string GetFileSizeString(int size) { if (size < 1024) return size + " Bytes"; if (size < 1024 * 1024) return (size / 1024.0).ToString("0.00") + " KiB"; return (size / (1024.0 * 1024.0)).ToString("0.00") + " MiB"; } } }
mit
C#
ac99df8383d1fcbe975925d088eb9557553cca0b
fix lock screen icon.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Shell/Commands/SystemCommands.cs
WalletWasabi.Gui/Shell/Commands/SystemCommands.cs
using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using AvalonStudio.Commands; using ReactiveUI; using System; using System.Composition; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.Gui.Shell.Commands { internal class SystemCommands { public Global Global { get; } [DefaultKeyGesture("ALT+F4")] [ExportCommandDefinition("File.Exit")] public CommandDefinition ExitCommand { get; } [DefaultKeyGesture("CTRL+L", osxKeyGesture: "CMD+L")] [ExportCommandDefinition("File.LockScreen")] public CommandDefinition LockScreenCommand {get;} [ImportingConstructor] public SystemCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global) { Global = Guard.NotNull(nameof(Global), global.Global); var exit = ReactiveCommand.Create(OnExit); exit.ThrownExceptions.Subscribe(ex => Logger.LogWarning(ex)); ExitCommand = new CommandDefinition( "Exit", commandIconService.GetCompletionKindImage("Exit"), exit); #pragma warning disable IDE0053 // Use expression body for lambda expressions var lockCommand = ReactiveCommand.Create(() => { Global.UiConfig.LockScreenActive = true; }); #pragma warning restore IDE0053 // Use expression body for lambda expressions lockCommand.ThrownExceptions.Subscribe(ex => Logger.LogWarning(ex)); LockScreenCommand = new CommandDefinition( "Lock Screen", commandIconService.GetCompletionKindImage("Lock"), lockCommand); } private void OnExit() { (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow.Close(); } } }
using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using AvalonStudio.Commands; using ReactiveUI; using System; using System.Composition; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.Gui.Shell.Commands { internal class SystemCommands { public Global Global { get; } [DefaultKeyGesture("ALT+F4")] [ExportCommandDefinition("File.Exit")] public CommandDefinition ExitCommand { get; } [DefaultKeyGesture("CTRL+L", osxKeyGesture: "CMD+L")] [ExportCommandDefinition("File.LockScreen")] public CommandDefinition LockScreenCommand {get;} [ImportingConstructor] public SystemCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global) { Global = Guard.NotNull(nameof(Global), global.Global); var exit = ReactiveCommand.Create(OnExit); exit.ThrownExceptions.Subscribe(ex => Logger.LogWarning(ex)); ExitCommand = new CommandDefinition( "Exit", commandIconService.GetCompletionKindImage("Exit"), exit); #pragma warning disable IDE0053 // Use expression body for lambda expressions var lockCommand = ReactiveCommand.Create(() => { Global.UiConfig.LockScreenActive = true; }); #pragma warning restore IDE0053 // Use expression body for lambda expressions lockCommand.ThrownExceptions.Subscribe(ex => Logger.LogWarning(ex)); LockScreenCommand = new CommandDefinition( "Lock Screen", commandIconService.GetCompletionKindImage("Exit"), lockCommand); } private void OnExit() { (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow.Close(); } } }
mit
C#
d739153a45b7e640ba7d8d5dc10f3931a0ad04d6
Prepare for release 0.1.1.219
yanggujun/commonsfornet,yanggujun/commonsfornet
src/AssemblyInfo.cs
src/AssemblyInfo.cs
// Copyright CommonsForNET. // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You 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.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCopyright("")] [assembly: ComVisible(false)] [assembly: Guid("84e7ec63-7b50-4dc1-ae96-c3b56626efd7")] // * For versioning, the fourth digit represents the days from the build date to the // day of the first release (2/15/2015). // * The third digit is increased when a small feature is added. // * The second digit is increased when a component is added to the whole package. // * The first digit is increase when a set of components planned yearly are completed. // * The nuget package version shall be the same with the assembly version. // * Each new release brought up by the nuget package forces re-compile for // the applications and components which depends on the .NET Commons library. // * The build number only changes when a new nuget package is uploaded. If there are more than // one upload in one day, the build number is increased by one. If next few days, another upload happens, // build number is increased by one if the number of days to the first day is less than or // equal to the build number. // * TODO: Automated version strategy will be developed in future. [assembly: AssemblyVersion("0.1.1.219")] [assembly: AssemblyFileVersion("0.1.1.219")] [assembly: CLSCompliant(true)]
// Copyright CommonsForNET. // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You 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.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCopyright("")] [assembly: ComVisible(false)] [assembly: Guid("84e7ec63-7b50-4dc1-ae96-c3b56626efd7")] // * For versioning, the fourth digit represents the days from the build date to the // day of the first release (2/15/2015). // * The third digit is increased when a small feature is added. // * The second digit is increased when a component is added to the whole package. // * The first digit is increase when a set of components planned yearly are completed. // * The nuget package version shall be the same with the assembly version. // * Each new release brought up by the nuget package forces re-compile for // the applications and components which depends on the .NET Commons library. // * The build number only changes when a new nuget package is uploaded. If there are more than // one upload in one day, the build number is increased by one. If next few days, another upload happens, // build number is increased by one if the number of days to the first day is less than or // equal to the build number. // * TODO: Automated version strategy will be developed in future. [assembly: AssemblyVersion("0.1.1.22")] [assembly: AssemblyFileVersion("0.1.1.22")] [assembly: CLSCompliant(true)]
apache-2.0
C#
1fa7c766db27cde97ae73983d1118659b15fab73
Add ToPublicKeyToken() method
yck1509/dnlib,0xd4d/dnlib,ilkerhalil/dnlib,kiootic/dnlib,ZixiangBoy/dnlib,Arthur2e5/dnlib,picrap/dnlib,modulexcite/dnlib,jorik041/dnlib
src/DotNet/PublicKeyBase.cs
src/DotNet/PublicKeyBase.cs
namespace dot10.DotNet { /// <summary> /// Public key / public key token base class /// </summary> public abstract class PublicKeyBase { /// <summary> /// The key data /// </summary> protected byte[] data; /// <summary> /// Returns <c>true</c> if <see cref="Data"/> is <c>null</c> or empty /// </summary> public bool IsNullOrEmpty { get { return data == null || data.Length == 0; } } /// <summary> /// Returns <c>true</c> if <see cref="Data"/> is <c>null</c> /// </summary> public bool IsNull { get { return data == null; } } /// <summary> /// Gets/sets key data /// </summary> public virtual byte[] Data { get { return data; } set { data = value; } } /// <summary> /// Default constructor /// </summary> protected PublicKeyBase() { } /// <summary> /// Constructor /// </summary> /// <param name="data">Key data</param> protected PublicKeyBase(byte[] data) { this.data = data; } /// <summary> /// Constructor /// </summary> /// <param name="hexString">Key data as a hex string or the string <c>"null"</c> /// to set key data to <c>null</c></param> protected PublicKeyBase(string hexString) { this.data = Parse(hexString); } static byte[] Parse(string hexString) { if (hexString == null || hexString == "null") return null; return Utils.ParseBytes(hexString); } /// <summary> /// Returns a <see cref="PublicKeyToken"/> /// </summary> /// <param name="pkb">A <see cref="PublicKey"/> or a <see cref="PublicKeyToken"/> instance</param> public static PublicKeyToken ToPublicKeyToken(PublicKeyBase pkb) { var pkt = pkb as PublicKeyToken; if (pkt != null) return pkt; var pk = pkb as PublicKey; if (pk != null) return pk.Token; return null; } /// <inheritdoc/> public override string ToString() { if (IsNullOrEmpty) return "null"; return Utils.ToHex(data, false); } } }
namespace dot10.DotNet { /// <summary> /// Public key / public key token base class /// </summary> public abstract class PublicKeyBase { /// <summary> /// The key data /// </summary> protected byte[] data; /// <summary> /// Returns <c>true</c> if <see cref="Data"/> is <c>null</c> or empty /// </summary> public bool IsNullOrEmpty { get { return data == null || data.Length == 0; } } /// <summary> /// Returns <c>true</c> if <see cref="Data"/> is <c>null</c> /// </summary> public bool IsNull { get { return data == null; } } /// <summary> /// Gets/sets key data /// </summary> public virtual byte[] Data { get { return data; } set { data = value; } } /// <summary> /// Default constructor /// </summary> protected PublicKeyBase() { } /// <summary> /// Constructor /// </summary> /// <param name="data">Key data</param> protected PublicKeyBase(byte[] data) { this.data = data; } /// <summary> /// Constructor /// </summary> /// <param name="hexString">Key data as a hex string or the string <c>"null"</c> /// to set key data to <c>null</c></param> protected PublicKeyBase(string hexString) { this.data = Parse(hexString); } static byte[] Parse(string hexString) { if (hexString == null || hexString == "null") return null; return Utils.ParseBytes(hexString); } /// <inheritdoc/> public override string ToString() { if (IsNullOrEmpty) return "null"; return Utils.ToHex(data, false); } } }
mit
C#
9d349610a20a70b3087534b5096c1b4c619352a5
Update Xerath.cs
metaphorce/leaguesharp
MetaSmite/Champions/Xerath.cs
MetaSmite/Champions/Xerath.cs
using System; using LeagueSharp; using LeagueSharp.Common; using SharpDX; namespace MetaSmite.Champions { public static class Xerath { internal static Spell champSpell; private static Menu Config = MetaSmite.Config; private static double totalDamage; private static double spellDamage; public static void Load() { //Load spells champSpell = new Spell(SpellSlot.R, 3200f); //Spell usage. Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true); //Events Game.OnUpdate += OnGameUpdate; } private static void OnGameUpdate(EventArgs args) { if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active) { if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range) { spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot); totalDamage = spellDamage + SmiteManager.damage; if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && SmiteManager.smite.IsReady() && champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } } } } } }
using System; using LeagueSharp; using LeagueSharp.Common; using SharpDX; namespace MetaSmite.Champions { public static class Xerath { internal static Spell champSpell; private static Menu Config = MetaSmite.Config; private static double totalDamage; private static double spellDamage; public static void Load() { //Load spells champSpell = new Spell(SpellSlot.R, 3200f); //Spell usage. Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true); //Events Game.OnGameUpdate += OnGameUpdate; } private static void OnGameUpdate(EventArgs args) { if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active) { if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range) { spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot); totalDamage = spellDamage + SmiteManager.damage; if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && SmiteManager.smite.IsReady() && champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } } } } } }
mit
C#
9f0bf8b8584a9344427a0e5bd362c0cfc40863f4
Add tests for Java Exceptions in the .Net Bridge
openengsb/loom-csharp
bridge/BridgeTests/ExceptionHandling/TestExceptionMarshalling.cs
bridge/BridgeTests/ExceptionHandling/TestExceptionMarshalling.cs
#region Copyright // <copyright file="TestExceptionMarshalling.cs" company="OpenEngSB"> // Licensed to the Austrian Association for Software Tool Integration (AASTI) // under one or more contributor license agreements. See the NOTICE file // distributed with this work for additional information regarding copyright // ownership. The AASTI licenses this file to you 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> #endregion using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Org.Openengsb.Loom.CSharp.Bridge.Implementation.Communication.Json; using Org.Openengsb.Loom.CSharp.Bridge.Interface; namespace BridgeTests.ExceptionHandling { [TestClass] public class TestExceptionMarshalling { private JsonMarshaller marshaller = new JsonMarshaller(); private String testString = "Test"; [TestMethod] public void TestExceptionFromJSONToDotNetIsIJavaExceptionType() { String jsonMessage = "{\"Test1\":\"Test1\"," + "\"message\":\"TestException\"}"; Assert.IsTrue(marshaller.UnmarshallObject<TestException>(jsonMessage) is IJavaException); } [TestMethod] public void TestExceptionFromExceptionTestJSONMessageToDotNetIsTestExceptionType() { TestException testException = new TestException(); testException.Test1 = testString; String jsonMessage = marshaller.MarshallObject(testException); Assert.IsTrue(marshaller.UnmarshallObject<TestException>(jsonMessage) is IJavaException); } [TestMethod] public void TestExceptionFromExceptionTestJSONMessageWithMessageFieldAddedToDotNetIsTestExceptionType() { TestException testException = new TestException(); testException.Test1 = testString; String jsonMessage = marshaller.MarshallObject(testException); jsonMessage = jsonMessage.Substring(0, jsonMessage.LastIndexOf("}")); jsonMessage += ",\"message\":\"" + testString + "\"}"; IJavaException exception = marshaller.UnmarshallObject<TestException>(jsonMessage) as IJavaException; Assert.AreEqual(exception.Message, testString); } } }
#region Copyright // <copyright file="TestExceptionMarshalling.cs" company="OpenEngSB"> // Licensed to the Austrian Association for Software Tool Integration (AASTI) // under one or more contributor license agreements. See the NOTICE file // distributed with this work for additional information regarding copyright // ownership. The AASTI licenses this file to you 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> #endregion using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Org.Openengsb.Loom.CSharp.Bridge.Implementation.Communication.Json; using Org.Openengsb.Loom.CSharp.Bridge.Interface; namespace BridgeTests.ExceptionHandling { [TestClass] public class TestExceptionMarshalling { private JsonMarshaller marshaller = new JsonMarshaller(); [TestMethod] public void TestExceptionFromJSONToDotNetIsIJavaExceptionType() { String jsonMessage = "{\"Test1\":\"Test1\"," + "\"message\":\"TestException\"}"; Assert.IsTrue(marshaller.UnmarshallObject<TestException>(jsonMessage) is IJavaException); } [TestMethod] public void TestExceptionFromJSONToDotNetIsTestExceptionType() { String jsonMessage = "{\"Test1\":\"Test1\"," + "\"message\":\"TestException\"}"; Assert.IsTrue(marshaller.UnmarshallObject<TestException>(jsonMessage) is TestException); } [TestMethod] public void TestExceptionMessageFromJSONToDotNetIsCorrectlyDeserialised() { String jsonMessage = "{\"Test1\":\"Test1\"," + "\"message\":\"TestException\"}"; IJavaException entryObject = (IJavaException) marshaller.UnmarshallObject<TestException>(jsonMessage); Assert.AreEqual(entryObject.Message, "TestException"); } [TestMethod] public void TestExceptionVariableFromJSONToDotNetIsCorrectlyDeserialised() { String jsonMessage = "{\"Test1\":\"Test1\"," + "\"message\":\"TestException\"}"; TestException entryObject = marshaller.UnmarshallObject<TestException>(jsonMessage); Assert.AreEqual(entryObject.Test1, "Test1"); } } }
apache-2.0
C#
2903e183c3cf29f719bf70efb1c9f04fcd78446d
Fix failing unit tests
ComputerWorkware/TeamCityApi
src/TeamCityConsole.Tests/Helpers/DomainExtensions.cs
src/TeamCityConsole.Tests/Helpers/DomainExtensions.cs
using System; using System.Collections.Generic; using Ploeh.AutoFixture.Dsl; using TeamCityApi.Domain; using TeamCityConsole.Options; namespace TeamCityConsole.Tests.Helpers { public static class DomainExtensions { public static IPostprocessComposer<BuildConfig> WithNoDependencies( this IPostprocessComposer<BuildConfig> composer) { return composer.With(x => x.ArtifactDependencies, new List<DependencyDefinition>()); } public static IPostprocessComposer<BuildConfig> WithDependencies( this IPostprocessComposer<BuildConfig> composer, params DependencyDefinition[] dependencyDefinitions) { return composer.With(x => x.ArtifactDependencies, new List<DependencyDefinition>(dependencyDefinitions)); } public static IPostprocessComposer<BuildConfig> WithId( this IPostprocessComposer<BuildConfig> composer, string id) { return composer.With(x => x.Id, id); } public static IPostprocessComposer<DependencyDefinition> WithPathRules( this IPostprocessComposer<DependencyDefinition> composer, string pathRules) { return composer.With(x => x.Properties, new Properties() {Count = "1", Property = new PropertyList { new Property { Name = "pathRules", Value = pathRules } }}); } public static IPostprocessComposer<GetDependenciesOptions> WithForce( this IPostprocessComposer<GetDependenciesOptions> composer, string buildConfigId) { return composer.With(x => x.BuildConfigId, buildConfigId).With(x => x.Force, true); } } }
using System; using System.Collections.Generic; using Ploeh.AutoFixture.Dsl; using TeamCityApi.Domain; using TeamCityConsole.Options; namespace TeamCityConsole.Tests.Helpers { public static class DomainExtensions { public static IPostprocessComposer<BuildConfig> WithNoDependencies( this IPostprocessComposer<BuildConfig> composer) { return composer.With(x => x.ArtifactDependencies, new List<DependencyDefinition>()); } public static IPostprocessComposer<BuildConfig> WithDependencies( this IPostprocessComposer<BuildConfig> composer, params DependencyDefinition[] dependencyDefinitions) { return composer.With(x => x.ArtifactDependencies, new List<DependencyDefinition>(dependencyDefinitions)); } public static IPostprocessComposer<BuildConfig> WithId( this IPostprocessComposer<BuildConfig> composer, string id) { return composer.With(x => x.Id, id); } public static IPostprocessComposer<DependencyDefinition> WithPathRules( this IPostprocessComposer<DependencyDefinition> composer, string pathRules) { return composer.With(x => x.Properties.Property, new List<Property> { new Property { Name = "pathRules", Value = pathRules } }); } public static IPostprocessComposer<GetDependenciesOptions> WithForce( this IPostprocessComposer<GetDependenciesOptions> composer, string buildConfigId) { return composer.With(x => x.BuildConfigId, buildConfigId).With(x => x.Force, true); } } }
mit
C#
b402f95419137a2203506d120a90cee0d6c87a5a
clean code
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Event/EventSubscriptionManager.cs
src/WeihanLi.Common/Event/EventSubscriptionManager.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using WeihanLi.Common.Helpers; namespace WeihanLi.Common.Event { public interface IEventSubscriptionManager : IEventSubscriber { /// <summary> /// Get EventHandlers for event /// </summary> /// <param name="eventType">event</param> /// <returns>event handlers types</returns> ICollection<Type> GetEventHandlerTypes(Type eventType); } public sealed class EventSubscriptionManagerInMemory : IEventSubscriptionManager { private readonly ConcurrentDictionary<Type, ConcurrentSet<Type>> _eventHandlers = new ConcurrentDictionary<Type, ConcurrentSet<Type>>(); public bool Subscribe(Type eventType, Type eventHandlerType) { var handlers = _eventHandlers.GetOrAdd(eventType, new ConcurrentSet<Type>()); return handlers.TryAdd(eventHandlerType); } public Task<bool> SubscribeAsync(Type eventType, Type eventHandlerType) { return Task.FromResult(Subscribe(eventType, eventHandlerType)); } public bool UnSubscribe(Type eventType, Type eventHandlerType) { if (_eventHandlers.TryGetValue(eventType, out var handlers)) { return handlers.TryRemove(eventHandlerType); } return false; } public Task<bool> UnSubscribeAsync(Type eventType, Type eventHandlerType) { return Task.FromResult(UnSubscribe(eventType, eventHandlerType)); } public ICollection<Type> GetEventHandlerTypes(Type eventType) { return _eventHandlers[eventType]; } } public static class EventSubscriptionManagerExtensions { public static ICollection<Type> GetEventHandlerTypes<TEvent>(this IEventSubscriptionManager subscriptionManager) where TEvent : class, IEventBase { return subscriptionManager.GetEventHandlerTypes(typeof(TEvent)); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using WeihanLi.Common.Helpers; namespace WeihanLi.Common.Event { public interface IEventSubscriptionManager : IEventSubscriber { /// <summary> /// Get EventHandlers for event /// </summary> /// <param name="eventType">event</param> /// <returns>event handlers types</returns> ICollection<Type> GetEventHandlerTypes(Type eventType); } public class EventSubscriptionManagerInMemory : IEventSubscriptionManager { private readonly ConcurrentDictionary<Type, ConcurrentSet<Type>> _eventHandlers = new ConcurrentDictionary<Type, ConcurrentSet<Type>>(); public bool Subscribe(Type eventType, Type eventHandlerType) { var handlers = _eventHandlers.GetOrAdd(eventType, new ConcurrentSet<Type>()); return handlers.TryAdd(eventHandlerType); } public Task<bool> SubscribeAsync(Type eventType, Type eventHandlerType) { return Task.FromResult(Subscribe(eventType, eventHandlerType)); } public bool UnSubscribe(Type eventType, Type eventHandlerType) { if (_eventHandlers.TryGetValue(eventType, out var handlers)) { return handlers.TryRemove(eventHandlerType); } return false; } public Task<bool> UnSubscribeAsync(Type eventType, Type eventHandlerType) { return Task.FromResult(UnSubscribe(eventType, eventHandlerType)); } public ICollection<Type> GetEventHandlerTypes(Type eventType) { return _eventHandlers[eventType]; } } public static class EventSubscriptionManagerExtensions { public static ICollection<Type> GetEventHandlerTypes<TEvent>(this IEventSubscriptionManager subscriptionManager) where TEvent : class, IEventBase { return subscriptionManager.GetEventHandlerTypes(typeof(TEvent)); } } }
mit
C#
8c4faf1403e822fc60330aa397171aa3a7319760
Fix some invalid docs
Deadpikle/NetSparkle,Deadpikle/NetSparkle
src/NetSparkle/LogWriter.cs
src/NetSparkle/LogWriter.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetSparkleUpdater { /// <summary> /// A simple class to handle log information for NetSparkleUPdater. /// Make sure to do any setup for this class that you want /// to do before calling StartLoop on your SparkleUpdater object. /// </summary> public class LogWriter { /// <summary> /// Tag to show before any log statements /// </summary> protected string tag = "netsparkle:"; /// <summary> /// Empty constructor -> sets PrintDiagnosticToConsole to false /// </summary> public LogWriter() { PrintDiagnosticToConsole = false; } /// <summary> /// LogWriter constructor that takes a bool to determine /// the value for printDiagnosticToConsole /// </summary> /// <param name="printDiagnosticToConsole">Whether this object should print via Debug.WriteLine or Console.WriteLine</param> public LogWriter(bool printDiagnosticToConsole) { PrintDiagnosticToConsole = printDiagnosticToConsole; } #region Properties /// <summary> /// true if this class should print to Console.WriteLine. /// false if this object should print to Debug.WriteLine. /// Defaults to false. /// </summary> public bool PrintDiagnosticToConsole { get; set; } #endregion /// <summary> /// Print a message to the log output. /// </summary> /// <param name="message">Message to print</param> /// <param name="arguments">Arguments to print (e.g. if using {0} format arguments)</param> public virtual void PrintMessage(string message, params object[] arguments) { if (PrintDiagnosticToConsole) { Console.WriteLine(tag + " " + message, arguments); } else { Debug.WriteLine(tag + " " + message, arguments); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetSparkleUpdater { /// <summary> /// A simple class to handle log information for NetSparkle. /// Make sure to do any setup for this class that you want /// to do before calling StartLoop on your NetSparkle object. /// </summary> public class LogWriter { /// <summary> /// Tag to show before any log statements /// </summary> protected string tag = "netsparkle:"; /// <summary> /// Empty constructor -> sets PrintDiagnosticToConsole to false /// </summary> public LogWriter() { PrintDiagnosticToConsole = false; } /// <summary> /// SparkleLog constructor that takes a bool to determine /// the value for printDiagnosticToConsole /// </summary> /// <param name="printDiagnosticToConsole">Whether this object should print via Debug.WriteLine or Console.WriteLine</param> public LogWriter(bool printDiagnosticToConsole) { PrintDiagnosticToConsole = printDiagnosticToConsole; } #region Properties /// <summary> /// true if this class should print to Console.WriteLine. /// false if this object should print to Debug.WriteLine. /// Defaults to false. /// </summary> public bool PrintDiagnosticToConsole { get; set; } #endregion /// <summary> /// Print a message to the log output. /// </summary> /// <param name="message">Message to print</param> /// <param name="arguments">Arguments to print (e.g. if using {0} format arguments)</param> public virtual void PrintMessage(string message, params object[] arguments) { if (PrintDiagnosticToConsole) { Console.WriteLine(tag + " " + message, arguments); } else { Debug.WriteLine(tag + " " + message, arguments); } } } }
mit
C#
109f634e82760972178368fd8e885a2f5bd3f2b2
Set Version to 1.5.2.0
monky2k6/WindowsEnhancementSuite
WindowsEnhancmentSuite/Properties/AssemblyInfo.cs
WindowsEnhancmentSuite/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("Windows Enhancment Suite")] [assembly: AssemblyDescription("Diese Anwendung erleichtert das tägliche Arbeiten mit Windows.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WindowsEnhancmentSuit")] [assembly: AssemblyCopyright("© 2015 Monky")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("92da3fae-2488-40c2-b177-b9c79177a02a")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.5.2.0")] [assembly: AssemblyFileVersion("1.5.2.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("Windows Enhancment Suite")] [assembly: AssemblyDescription("Diese Anwendung erleichtert das tägliche Arbeiten mit Windows.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WindowsEnhancmentSuit")] [assembly: AssemblyCopyright("© 2015 Monky")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("92da3fae-2488-40c2-b177-b9c79177a02a")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.5.1.0")] [assembly: AssemblyFileVersion("1.5.1.0")]
mit
C#
c81c4cbbcd546f31f1eacb505fc15c35ff7c6ea1
Fix missing Metadata initialisation.
Frontear/osuKyzer,RedNesto/osu,ppy/osu,smoogipoo/osu,ppy/osu,Damnae/osu,NotKyon/lolisu,Nabile-Rahmani/osu,UselessToucan/osu,theguii/osu,naoey/osu,peppy/osu,default0/osu,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,DrabWeb/osu,johnneijzen/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,nyaamara/osu,EVAST9919/osu,Drezi126/osu,ZLima12/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,naoey/osu,NeoAdonis/osu,osu-RP/osu-RP,2yangk23/osu,johnneijzen/osu,DrabWeb/osu,peppy/osu-new,DrabWeb/osu,2yangk23/osu,tacchinotacchi/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,naoey/osu
osu.Game/Database/BeatmapInfo.cs
osu.Game/Database/BeatmapInfo.cs
using System; using System.Linq; using osu.Game.Beatmaps.Samples; using osu.Game.GameModes.Play; using SQLite.Net.Attributes; using SQLiteNetExtensions.Attributes; namespace osu.Game.Database { public class BeatmapInfo { public BeatmapInfo() { BaseDifficulty = new BaseDifficulty(); Metadata = new BeatmapMetadata(); } [PrimaryKey] public int BeatmapID { get; set; } [NotNull, Indexed] public int BeatmapSetID { get; set; } [ForeignKey(typeof(BeatmapMetadata))] public int BeatmapMetadataID { get; set; } [ForeignKey(typeof(BaseDifficulty)), NotNull] public int BaseDifficultyID { get; set; } [OneToOne] public BeatmapMetadata Metadata { get; set; } [OneToOne] public BaseDifficulty BaseDifficulty { get; set; } public string Path { get; set; } // General public int AudioLeadIn { get; set; } public bool Countdown { get; set; } public SampleSet SampleSet { get; set; } public float StackLeniency { get; set; } public bool SpecialStyle { get; set; } public PlayMode Mode { get; set; } public bool LetterboxInBreaks { get; set; } public bool WidescreenStoryboard { get; set; } // Editor // This bookmarks stuff is necessary because DB doesn't know how to store int[] public string StoredBookmarks { get; internal set; } [Ignore] public int[] Bookmarks { get { return StoredBookmarks.Split(',').Select(b => int.Parse(b)).ToArray(); } set { StoredBookmarks = string.Join(",", value); } } public double DistanceSpacing { get; set; } public int BeatDivisor { get; set; } public int GridSize { get; set; } public double TimelineZoom { get; set; } // Metadata public string Version { get; set; } } }
using System; using System.Linq; using osu.Game.Beatmaps.Samples; using osu.Game.GameModes.Play; using SQLite.Net.Attributes; using SQLiteNetExtensions.Attributes; namespace osu.Game.Database { public class BeatmapInfo { public BeatmapInfo() { BaseDifficulty = new BaseDifficulty(); } [PrimaryKey] public int BeatmapID { get; set; } [NotNull, Indexed] public int BeatmapSetID { get; set; } [ForeignKey(typeof(BeatmapMetadata))] public int BeatmapMetadataID { get; set; } [ForeignKey(typeof(BaseDifficulty)), NotNull] public int BaseDifficultyID { get; set; } [OneToOne] public BeatmapMetadata Metadata { get; set; } [OneToOne] public BaseDifficulty BaseDifficulty { get; set; } public string Path { get; set; } // General public int AudioLeadIn { get; set; } public bool Countdown { get; set; } public SampleSet SampleSet { get; set; } public float StackLeniency { get; set; } public bool SpecialStyle { get; set; } public PlayMode Mode { get; set; } public bool LetterboxInBreaks { get; set; } public bool WidescreenStoryboard { get; set; } // Editor // This bookmarks stuff is necessary because DB doesn't know how to store int[] public string StoredBookmarks { get; internal set; } [Ignore] public int[] Bookmarks { get { return StoredBookmarks.Split(',').Select(b => int.Parse(b)).ToArray(); } set { StoredBookmarks = string.Join(",", value); } } public double DistanceSpacing { get; set; } public int BeatDivisor { get; set; } public int GridSize { get; set; } public double TimelineZoom { get; set; } // Metadata public string Version { get; set; } } }
mit
C#
942a80040ebf5b9f5032d379866585b849cf9cbd
Update DfmTokenTreeHandler.cs
LordZoltan/docfx,dotnet/docfx,LordZoltan/docfx,928PJY/docfx,LordZoltan/docfx,dotnet/docfx,pascalberger/docfx,dotnet/docfx,LordZoltan/docfx,hellosnow/docfx,928PJY/docfx,hellosnow/docfx,DuncanmaMSFT/docfx,hellosnow/docfx,superyyrrzz/docfx,pascalberger/docfx,superyyrrzz/docfx,superyyrrzz/docfx,928PJY/docfx,DuncanmaMSFT/docfx,pascalberger/docfx
tools/DfmHttpService/Handler/DfmTokenTreeHandler.cs
tools/DfmHttpService/Handler/DfmTokenTreeHandler.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DfmHttpService { using System; using System.Threading.Tasks; using Microsoft.DocAsCode.Build.Engine; using Microsoft.DocAsCode.Plugins; internal class DfmTokenTreeHandler : IHttpHandler { private readonly DfmJsonTokenTreeServiceProvider _provider = new DfmJsonTokenTreeServiceProvider(); public bool CanHandle(ServiceContext context) { return context.Message.Name == CommandName.GenerateTokenTree; } public Task HandleAsync(ServiceContext context) { return Task.Run(() => { try { var tokenTree = GenerateTokenTree(context.Message.Documentation, context.Message.FilePath, context.Message.WorkspacePath); Utility.ReplySuccessfulResponse(context.HttpContext, tokenTree, ContentType.Json); } catch (Exception ex) { Utility.ReplyServerErrorResponse(context.HttpContext, ex.Message); } }); } private string GenerateTokenTree(string documentation, string filePath, string workspacePath = null) { var service = _provider.CreateMarkdownService(new MarkdownServiceParameters { BasePath = workspacePath }); return service.Markup(documentation, filePath).Html; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DfmHttpService { using System; using System.Threading.Tasks; using Microsoft.DocAsCode.Build.Engine; using Microsoft.DocAsCode.Plugins; internal class DfmTokenTreeHandler : IHttpHandler { private readonly DfmServiceProvider _provider = new DfmServiceProvider(); public bool CanHandle(ServiceContext context) { return context.Message.Name == CommandName.GenerateTokenTree; } public Task HandleAsync(ServiceContext context) { return Task.Run(() => { try { var tokenTree = GenerateTokenTree(context.Message.Documentation, context.Message.FilePath, context.Message.WorkspacePath); Utility.ReplySuccessfulResponse(context.HttpContext, tokenTree, ContentType.Json); } catch (Exception ex) { Utility.ReplyServerErrorResponse(context.HttpContext, ex.Message); } }); } private string GenerateTokenTree(string documentation, string filePath, string workspacePath = null) { var service = _provider.CreateMarkdownService(new MarkdownServiceParameters { BasePath = workspacePath }); return service.Markup(documentation, filePath).Html; } } }
mit
C#
a58991e245c33e6f61ed78a9f5d3ac3776c8da3d
Add LICENCE header
dv-lebedev/statistics
Statistics/ArrayExtensions.cs
Statistics/ArrayExtensions.cs
/* Copyright 2015 Denis Lebedev Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace Statistics { public static class ArrayExtensions { public static double[] ToDouble(this decimal[] array) { int size = array.Length; double[] result = new double[size]; for (int i = 0; i < size; i++) { result[i] = (double)array[i]; } return result; } public static decimal[] ToDecimal(this double[] array) { int size = array.Length; decimal[] result = new decimal[size]; for (int i = 0; i < size; i++) { result[i] = (decimal)array[i]; } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Statistics { public static class ArrayExtensions { public static double[] ToDouble(this decimal[] array) { int size = array.Length; double[] result = new double[size]; for (int i = 0; i < size; i++) { result[i] = (double)array[i]; } return result; } public static decimal[] ToDecimal(this double[] array) { int size = array.Length; decimal[] result = new decimal[size]; for (int i = 0; i < size; i++) { result[i] = (decimal)array[i]; } return result; } } }
apache-2.0
C#
9bb9eaaff25b50561e8b39b7600a40ca8581ef6b
Reduce warning, part 3
ViveportSoftware/vita_core_csharp,ViveportSoftware/vita_core_csharp
source/Htc.Vita.Core/Util/Array.cs
source/Htc.Vita.Core/Util/Array.cs
namespace Htc.Vita.Core.Util { /// <summary> /// Class Array. /// </summary> public static class Array { /// <summary> /// Get the empty array. /// </summary> /// <typeparam name="T"></typeparam> /// <returns>T[].</returns> public static T[] Empty<T>() { #if NET45 return EmptyArray<T>.Value; #else return System.Array.Empty<T>(); #endif } private static class EmptyArray<T> { #pragma warning disable CA1825 internal static readonly T[] Value = new T[0]; #pragma warning restore CA1825 } } }
namespace Htc.Vita.Core.Util { /// <summary> /// Class Array. /// </summary> public class Array { /// <summary> /// Get the empty array. /// </summary> /// <typeparam name="T"></typeparam> /// <returns>T[].</returns> public static T[] Empty<T>() { #if NET45 return EmptyArray<T>.Value; #else return System.Array.Empty<T>(); #endif } private static class EmptyArray<T> { #pragma warning disable CA1825 internal static readonly T[] Value = new T[0]; #pragma warning restore CA1825 } } }
mit
C#
c6c4ff5d6a7cbf9ab1d7122f339c11ea47aa4db6
Fix save button color and message text bug
setchi/NoteEditor,setchi/NotesEditor
Assets/Scripts/UI/SavePresenter.cs
Assets/Scripts/UI/SavePresenter.cs
using System.IO; using System.Linq; using UniRx; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; public class SavePresenter : MonoBehaviour { [SerializeField] Button saveButton; [SerializeField] Text messageText; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; var saveActionObservable = this.UpdateAsObservable() .Where(_ => Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.LeftCommand) || Input.GetKey(KeyCode.RightControl) || Input.GetKey(KeyCode.RightCommand)) .Where(_ => Input.GetKey(KeyCode.S)) .Merge(saveButton.OnClickAsObservable()); Observable.Merge( model.BPM.Select(_ => true), model.LPB.Select(_ => true), model.BeatOffsetSamples.Select(_ => true), model.NormalNoteObservable.Select(_ => true), model.LongNoteObservable.Select(_ => true), model.OnLoadedMusicObservable.Select(_ => false), saveActionObservable.Select(_ => false)) .SkipUntil(model.OnLoadedMusicObservable.DelayFrame(1)) .Do(unsaved => saveButton.GetComponent<Image>().color = unsaved ? Color.yellow : Color.white) .SubscribeToText(messageText, unsaved => unsaved ? "保存が必要な状態" : ""); saveActionObservable.Subscribe(_ => { Debug.Log(model.MusicName.Value + " 保存した!!"); var fileName = Path.GetFileNameWithoutExtension(model.MusicName.Value) + ".json"; var filePath = Application.persistentDataPath + "/Notes/"; var fileFullPath = filePath + fileName; var text = model.SerializeNotesData(); if (!File.Exists(filePath)) { Directory.CreateDirectory(filePath); } File.WriteAllText(fileFullPath, text, System.Text.Encoding.UTF8); messageText.text = fileFullPath + " に保存しました"; }); } }
using System.IO; using System.Linq; using UniRx; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; public class SavePresenter : MonoBehaviour { [SerializeField] Button saveButton; [SerializeField] Text messageText; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; var saveActionObservable = this.UpdateAsObservable() .Where(_ => Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.LeftCommand) || Input.GetKey(KeyCode.RightControl) || Input.GetKey(KeyCode.RightCommand)) .Where(_ => Input.GetKey(KeyCode.S)) .Merge(saveButton.OnClickAsObservable()); Observable.Merge( model.BPM.Select(_ => true), model.LPB.Select(_ => true), model.BeatOffsetSamples.Select(_ => true), model.NormalNoteObservable.Select(_ => true), model.LongNoteObservable.Select(_ => true), saveActionObservable.Select(_ => false)) .SkipUntil(model.OnLoadedMusicObservable.DelayFrame(1)) .Do(unsaved => saveButton.GetComponent<Image>().color = unsaved ? Color.yellow : Color.white) .SubscribeToText(messageText, _ => "保存が必要な状態"); saveActionObservable.Subscribe(_ => { Debug.Log(model.MusicName.Value + " 保存した!!"); var fileName = Path.GetFileNameWithoutExtension(model.MusicName.Value) + ".json"; var filePath = Application.persistentDataPath + "/Notes/"; var fileFullPath = filePath + fileName; var text = model.SerializeNotesData(); if (!File.Exists(filePath)) { Directory.CreateDirectory(filePath); } File.WriteAllText(fileFullPath, text, System.Text.Encoding.UTF8); messageText.text = fileFullPath + " に保存しました"; }); } }
mit
C#
b47cc6f4287386188d6c7bf45941b869c940786c
Add a test with a specific writer.
izrik/FbxSharp,izrik/FbxSharp,izrik/FbxSharp,izrik/FbxSharp,izrik/FbxSharp
FbxSharpTests/ObjectPrinterTest.cs
FbxSharpTests/ObjectPrinterTest.cs
using System; using NUnit.Framework; using FbxSharp; using System.IO; namespace FbxSharpTests { [TestFixture] public class ObjectPrinterTest { [Test] public void QuoteQuotesAndEscapeStrings() { Assert.AreEqual("\"abcdefghijklmnopqrstuvwxyz\"", ObjectPrinter.quote("abcdefghijklmnopqrstuvwxyz")); Assert.AreEqual("\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", ObjectPrinter.quote("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); Assert.AreEqual("\"0123456789\"", ObjectPrinter.quote("0123456789")); Assert.AreEqual("\"`~!@#$%^&*()_+-=\"", ObjectPrinter.quote("`~!@#$%^&*()_+-=")); // Assert.AreEqual("\"\\\\\"", ObjectPrinter.quote("\\")); // Assert.AreEqual("\"\\\"\"", ObjectPrinter.quote("\"")); Assert.AreEqual("\"[]{}|;:',<.>/?\"", ObjectPrinter.quote("[]{}|;:',<.>/?")); Assert.AreEqual("\"\\r\"", ObjectPrinter.quote("\r")); Assert.AreEqual("\"\\n\"", ObjectPrinter.quote("\n")); Assert.AreEqual("\"\\t\"", ObjectPrinter.quote("\t")); } [Test] public void PrintPropertyPrintsTheProperty() { // given var prop = new PropertyT<double>("something"); var printer = new ObjectPrinter(); var writer = new StringWriter(); var expected = @" Name = something Type = Double (MonoType) Value = 0 SrcObjectCount = 0 DstObjectCount = 0 "; // when printer.PrintProperty(prop, writer); // then Assert.AreEqual(expected, writer.ToString()); } } }
using System; using NUnit.Framework; using FbxSharp; namespace FbxSharpTests { [TestFixture] public class ObjectPrinterTest { [Test] public void QuoteQuotesAndEscapeStrings() { Assert.AreEqual("\"abcdefghijklmnopqrstuvwxyz\"", ObjectPrinter.quote("abcdefghijklmnopqrstuvwxyz")); Assert.AreEqual("\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", ObjectPrinter.quote("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); Assert.AreEqual("\"0123456789\"", ObjectPrinter.quote("0123456789")); Assert.AreEqual("\"`~!@#$%^&*()_+-=\"", ObjectPrinter.quote("`~!@#$%^&*()_+-=")); // Assert.AreEqual("\"\\\\\"", ObjectPrinter.quote("\\")); // Assert.AreEqual("\"\\\"\"", ObjectPrinter.quote("\"")); Assert.AreEqual("\"[]{}|;:',<.>/?\"", ObjectPrinter.quote("[]{}|;:',<.>/?")); Assert.AreEqual("\"\\r\"", ObjectPrinter.quote("\r")); Assert.AreEqual("\"\\n\"", ObjectPrinter.quote("\n")); Assert.AreEqual("\"\\t\"", ObjectPrinter.quote("\t")); } } }
lgpl-2.1
C#
a872db87ac0bf56a70dfbf377ee5a34d19ab583e
Add GetAllSettings method to IGameSettings interface
opcon/Substructio,opcon/Substructio
src/Core/Settings/IGameSettings.cs
src/Core/Settings/IGameSettings.cs
using System; using System.Collections.Generic; namespace Substructio.Core.Settings { public interface IGameSettings { object this[string key] { get; set; } void Save(); void Load(); Dictionary<string, object> GetAllSettings(); } public class NullGameSettings : IGameSettings { public object this[string key] { get { return null; } set { } } public void Load() { } public void Save() { } public Dictionary<string, object> GetAllSettings() { return null; } } }
using System; namespace Substructio.Core.Settings { public interface IGameSettings { object this[string key] { get; set; } void Save(); void Load(); } public class NullGameSettings : IGameSettings { public object this[string key] { get { return null; } set { } } public void Load() { } public void Save() { } } }
mit
C#
ef41f685e7c11447c9182f849692bc29c5114260
Fix a bug in ClassicBuilder
Ky7m/BenchmarkDotNet,redknightlois/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,redknightlois/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,Ky7m/BenchmarkDotNet,redknightlois/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet
BenchmarkDotNet/Toolchains/Classic/ClassicBuilder.cs
BenchmarkDotNet/Toolchains/Classic/ClassicBuilder.cs
using System.Collections.Generic; using System.Diagnostics; using System.IO; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Toolchains.Results; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using BuildResult = BenchmarkDotNet.Toolchains.Results.BuildResult; using ILogger = BenchmarkDotNet.Loggers.ILogger; namespace BenchmarkDotNet.Toolchains.Classic { internal class ClassicBuilder : IBuilder { private static readonly object buildLock = new object(); public BuildResult Build(GenerateResult generateResult, ILogger logger) { lock (buildLock) { var projectFileName = Path.Combine(generateResult.DirectoryPath, ClassicGenerator.MainClassName + ".csproj"); var exeFileName = Path.Combine(generateResult.DirectoryPath, ClassicGenerator.MainClassName + ".exe"); var consoleLogger = new MsBuildConsoleLogger(logger); var globalProperties = new Dictionary<string, string>(); var buildRequest = new BuildRequestData(projectFileName, globalProperties, null, new[] { "Build" }, null); var buildParameters = new BuildParameters(new ProjectCollection()) { DetailedSummary = false, Loggers = new Microsoft.Build.Framework.ILogger[] { consoleLogger } }; var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest); if (buildResult.OverallResult != BuildResultCode.Success && !File.Exists(exeFileName)) { logger.WriteLineInfo("BuildManager.DefaultBuildManager can't build this project. =("); logger.WriteLineInfo("Let's try to build it via BuildBenchmark.bat!"); var buildProcess = new Process { StartInfo = { FileName = Path.Combine(generateResult.DirectoryPath, "BuildBenchmark.bat"), WorkingDirectory = generateResult.DirectoryPath, UseShellExecute = false, RedirectStandardOutput = false, } }; buildProcess.Start(); buildProcess.WaitForExit(); if (File.Exists(exeFileName)) return new BuildResult(generateResult, true, null); } return new BuildResult(generateResult, buildResult.OverallResult == BuildResultCode.Success, buildResult.Exception); } } } }
using System.Collections.Generic; using System.IO; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Toolchains.Results; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using BuildResult = BenchmarkDotNet.Toolchains.Results.BuildResult; using ILogger = BenchmarkDotNet.Loggers.ILogger; namespace BenchmarkDotNet.Toolchains.Classic { internal class ClassicBuilder : IBuilder { private static readonly object buildLock = new object(); public BuildResult Build(GenerateResult generateResult, ILogger logger) { lock (buildLock) { var projectFileName = Path.Combine(generateResult.DirectoryPath, ClassicGenerator.MainClassName + ".csproj"); var consoleLogger = new MsBuildConsoleLogger(logger); var globalProperties = new Dictionary<string, string>(); var buildRequest = new BuildRequestData(projectFileName, globalProperties, null, new[] { "Build" }, null); var buildParameters = new BuildParameters(new ProjectCollection()) { DetailedSummary = false, Loggers = new Microsoft.Build.Framework.ILogger[] { consoleLogger } }; var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest); return new BuildResult(generateResult, buildResult.OverallResult == BuildResultCode.Success, buildResult.Exception); } } } }
mit
C#
16e5ec157b741e8c553a7562c2b81ec72cb91309
Refactor git executor
appharbor/appharbor-cli
src/AppHarbor/GitExecutor.cs
src/AppHarbor/GitExecutor.cs
using System; using System.Diagnostics; using System.IO; using System.Text; namespace AppHarbor { public class GitExecutor : IGitExecutor { private readonly FileInfo _gitExecutable; public GitExecutor() { var programFilesPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); var gitExecutablePath = Path.Combine(programFilesPath, "Git", "bin", "git.exe"); _gitExecutable = new FileInfo(gitExecutablePath); } public virtual void Execute(string command, DirectoryInfo repositoryDirectory) { var processArguments = new StringBuilder(); processArguments.AppendFormat("/C "); processArguments.AppendFormat("\"{0}\" ", _gitExecutable.FullName); processArguments.AppendFormat("{0} ", command); var process = new Process { StartInfo = new ProcessStartInfo("cmd.exe") { Arguments = processArguments.ToString(), CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, WorkingDirectory = repositoryDirectory.FullName, }, }; using (process) { process.Start(); process.WaitForExit(); string error = process.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(error)) { throw new InvalidOperationException(error); } } } } }
using System; using System.Diagnostics; using System.IO; using System.Text; namespace AppHarbor { public class GitExecutor : IGitExecutor { private readonly FileInfo _gitExecutable; public GitExecutor() { var programFilesPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); var gitExecutablePath = Path.Combine(programFilesPath, "Git", "bin", "git.exe"); _gitExecutable = new FileInfo(gitExecutablePath); } public virtual void Execute(string command, DirectoryInfo repositoryDirectory) { var processArguments = new StringBuilder(); processArguments.AppendFormat("/C "); processArguments.AppendFormat("{0} ", _gitExecutable.Name); processArguments.AppendFormat("{0} ", command); processArguments.AppendFormat("--git-dir=\"{0}\" ", repositoryDirectory.FullName); var process = new Process { StartInfo = new ProcessStartInfo("cmd.exe") { Arguments = processArguments.ToString(), CreateNoWindow = true, RedirectStandardError = true, UseShellExecute = false, WorkingDirectory = _gitExecutable.Directory.FullName, }, }; using (process) { process.Start(); process.WaitForExit(); string error = process.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(error)) { throw new InvalidOperationException(error); } } } } }
mit
C#
7172627cac2cb7b291635916fde49d48f9d91f13
refactor CobaltAHK class
maul-esel/CobaltAHK,maul-esel/CobaltAHK
CobaltAHK/CobaltAHK.cs
CobaltAHK/CobaltAHK.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using CobaltAHK.ExpressionTree; namespace CobaltAHK { public class CobaltAHK { public void Execute(string code) { Execute(new StringReader(code)); } public void Execute(TextReader code) { var exec = Compile(code); Debug("Compiled lambda wrapper. Begin execution..."); exec(); } public Action Compile(TextReader code) { var scope = new ExpressionTree.Scope(); var settings = new ScriptSettings(); var expressions = parser.Parse(code); Debug("Parsed {0} expressions.", expressions.Length); Preprocess(expressions, scope, settings); Debug("Preprocessing returned {0} expressions.", expressions.Length); var et = Generate(expressions, scope, settings); Debug("Generated {0} expressions.", et.Length); var lambda = Expression.Lambda<Action>(Expression.Block(scope.GetVariables(), et)); Debug("Generated lambda wrapper."); return lambda.Compile(); } private Parser parser = new Parser(); private void Preprocess(IList<Expressions.Expression> exprs, Scope scope, ScriptSettings settings) { Preprocessor.Process(exprs, scope, settings); } private Expression[] Generate(IEnumerable<Expressions.Expression> exprs, Scope scope, ScriptSettings settings) { var generator = new Generator(settings); return exprs.Select(e => generator.Generate(e, scope)).ToArray(); } [System.Diagnostics.Conditional("DEBUG")] internal void Debug(string str, params object[] placeholders) { Console.WriteLine(str, placeholders); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq.Expressions; namespace CobaltAHK { public class CobaltAHK { public void Execute(string code) { Execute(new StringReader(code)); } [System.Diagnostics.Conditional("DEBUG")] internal void Debug(string str, params object[] placeholders) { Console.WriteLine(str, placeholders); } public void Execute(TextReader code) { var expressions = parser.Parse(code); Debug("Parsed {0} expressions.", expressions.Length); var scope = new ExpressionTree.Scope(); var settings = new ScriptSettings(); ExpressionTree.Preprocessor.Process(expressions, scope, settings); var generator = new ExpressionTree.Generator(settings); var et = new List<Expression>(); foreach (var e in expressions) { et.Add(generator.Generate(e, scope)); } Debug("Generated {0} expressions.", et.Count); var lambda = Expression.Lambda<Action>(Expression.Block(scope.GetVariables(), et)); Debug("Generated lambda wrapper."); var exec = lambda.Compile(); Debug("Compiled lambda wrapper. Begin execution..."); exec(); } private Parser parser = new Parser(); } }
mit
C#
d798bbbdbc39a80d675a5ebaec81cefd0d0be970
Clean up the code
rockfordlhotka/csla,MarimerLLC/csla,MarimerLLC/csla,MarimerLLC/csla,rockfordlhotka/csla,rockfordlhotka/csla
Source/Csla/Configuration/ConfigurationExtensions.cs
Source/Csla/Configuration/ConfigurationExtensions.cs
#if NETSTANDARD2_0 || NET5_0 || NET6_0 //----------------------------------------------------------------------- // <copyright file="ConfigurationExtensions.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Implement extension methods for base .NET configuration</summary> //----------------------------------------------------------------------- using System; using Csla.DataPortalClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Csla.Configuration { /// <summary> /// Implement extension methods for base .NET configuration /// </summary> public static class ConfigurationExtensions { /// <summary> /// Add CSLA .NET services for use by the application. /// </summary> /// <param name="services">ServiceCollection object</param> public static ICslaBuilder AddCsla(this IServiceCollection services) { return AddCsla(services, null); } /// <summary> /// Add CSLA .NET services for use by the application. /// </summary> /// <param name="services">ServiceCollection object</param> /// <param name="options">Options for configuring CSLA .NET</param> public static ICslaBuilder AddCsla(this IServiceCollection services, Action<CslaConfiguration> options) { var builder = new CslaBuilder(services); // Configuration var cslaOptions = new CslaConfiguration(services); options?.Invoke(cslaOptions); // ApplicationContext services.TryAddScoped<ApplicationContext>(); services.TryAddScoped(typeof(Core.IContextManager), typeof(Core.ApplicationContextManager)); // Data portal services if (cslaOptions.DataPortal().UseDataPortalServer) { services.TryAddTransient(typeof(Server.IDataPortalServer), typeof(Csla.Server.DataPortal)); services.TryAddTransient<Server.DataPortalSelector>(); services.TryAddTransient<Server.SimpleDataPortal>(); services.TryAddTransient<Server.FactoryDataPortal>(); services.TryAddTransient<Server.DataPortalBroker>(); services.TryAddSingleton(typeof(Server.Dashboard.IDashboard), typeof(Csla.Server.Dashboard.NullDashboard)); } // Data portal API services.TryAddTransient(typeof(IDataPortal<>), typeof(DataPortal<>)); services.TryAddTransient(typeof(IChildDataPortal<>), typeof(DataPortal<>)); return builder; } /// <summary> /// Configure CSLA .NET settings from .NET Core configuration /// subsystem. /// </summary> /// <param name="config">Configuration object</param> public static IConfiguration ConfigureCsla(this IConfiguration config) { config.Bind("csla", new CslaConfigurationOptions()); return config; } } } #endif
#if NETSTANDARD2_0 || NET5_0 || NET6_0 //----------------------------------------------------------------------- // <copyright file="ConfigurationExtensions.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Implement extension methods for base .NET configuration</summary> //----------------------------------------------------------------------- using System; using Csla.DataPortalClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Csla.Configuration { /// <summary> /// Implement extension methods for base .NET configuration /// </summary> public static class ConfigurationExtensions { /// <summary> /// Add CSLA .NET services for use by the application. /// </summary> /// <param name="services">ServiceCollection object</param> public static ICslaBuilder AddCsla(this IServiceCollection services) { return AddCsla(services, null); } /// <summary> /// Add CSLA .NET services for use by the application. /// </summary> /// <param name="services">ServiceCollection object</param> /// <param name="config">Implement to configure CSLA .NET</param> public static ICslaBuilder AddCsla(this IServiceCollection services, Action<CslaConfiguration> config) { var builder = new CslaBuilder(services); // Configuration var options = new CslaConfiguration(services); config?.Invoke(options); // ApplicationContext services.TryAddScoped<ApplicationContext>(); services.TryAddScoped(typeof(Core.IContextManager), typeof(Core.ApplicationContextManager)); // Data portal services if (options.UseDataPortalServer) { services.TryAddTransient(typeof(Server.IDataPortalServer), typeof(Csla.Server.DataPortal)); services.TryAddSingleton(typeof(Server.Dashboard.IDashboard), typeof(Csla.Server.Dashboard.NullDashboard)); services.TryAddTransient<Server.DataPortalSelector>(); services.TryAddTransient<Server.SimpleDataPortal>(); services.TryAddTransient<Server.FactoryDataPortal>(); services.TryAddTransient<Server.DataPortalBroker>(); } // Data portal API services.TryAddTransient(typeof(IDataPortal<>), typeof(DataPortal<>)); services.TryAddTransient(typeof(IChildDataPortal<>), typeof(DataPortal<>)); return builder; } /// <summary> /// Configure CSLA .NET settings from .NET Core configuration /// subsystem. /// </summary> /// <param name="config">Configuration object</param> public static IConfiguration ConfigureCsla(this IConfiguration config) { config.Bind("csla", new CslaConfigurationOptions()); return config; } } } #endif
mit
C#
5d6cede704a5a7672fd1c5eaaa74195876dfcf0f
Update comment
visia/xunit-performance,Microsoft/xunit-performance,pharring/xunit-performance,mmitche/xunit-performance,ericeil/xunit-performance,Microsoft/xunit-performance,ianhays/xunit-performance
xunit.performance/BenchmarkAttribute.cs
xunit.performance/BenchmarkAttribute.cs
using System; using Xunit; using Xunit.Sdk; namespace Microsoft.Xunit.Performance { [XunitTestCaseDiscoverer("Microsoft.Xunit.Performance.BenchmarkDiscoverer", "xunit.performance")] [TraitDiscoverer("Microsoft.Xunit.Performance.BenchmarkTraitDiscoverer", "xunit.performance")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class BenchmarkAttribute : FactAttribute, ITraitAttribute { /// <summary> /// The desired margin of error in the test results. The default is 0.10, meaning that we want to measure the /// method's execution time to within +/-10%. A smaller value allows detection of smaller changes in performance, but /// requires more test iterations, and thus more overall test execution time. A larger value yields less accurate /// results, but in a shorter time. /// </summary> public double MarginOfError { get; set; } internal const double DefaultMarginOfError = 0.10; /// <summary> /// The desired confidence in the test results. The default is 0.95, meaning that we want to be 95% confident that /// the method's average execution time is within the range specified by <see cref="MarginOfError"/>. Higher confidence /// values result in more test iterations, and thus more overall test execution time. /// </summary> public double Confidence { get; set; } internal const double DefaultConfidence = 0.95; /// <summary> /// If set, indicates whether the test allocates from the GC heap. If true, test iterations will run until a GC occurs (and may /// continue to run due to other factors). If null, the test framework will attempt to determine whether the test has been /// allocating. /// </summary> public bool? TriggersGC { get; set; } /// <summary> /// If true, performance metrics will be computed for all iterations of the method. If false (the default), the first /// iteration of the method will be ignored when computing results. This "warmup" iteration helps eliminate one-time costs /// (such as JIT compilation time) from the results, but may be unnecessary for some tests. /// </summary> public bool SkipWarmup { get; set; } } }
using System; using Xunit; using Xunit.Sdk; namespace Microsoft.Xunit.Performance { [XunitTestCaseDiscoverer("Microsoft.Xunit.Performance.BenchmarkDiscoverer", "xunit.performance")] [TraitDiscoverer("Microsoft.Xunit.Performance.BenchmarkTraitDiscoverer", "xunit.performance")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class BenchmarkAttribute : FactAttribute, ITraitAttribute { /// <summary> /// The desired margin of error in the test results. The default is 0.05, meaning that we want to measure the /// method's execution time to within +/-5%. A smaller value allows detection of smaller changes in performance, but /// requires more test iterations, and thus more overall test execution time. A larger value yields less accurate /// results, but in a shorter time. /// </summary> public double MarginOfError { get; set; } internal const double DefaultMarginOfError = 0.10; /// <summary> /// The desired confidence in the test results. The default is 0.95, meaning that we want to be 95% confident that /// the method's average execution time is within the range specified by <see cref="MarginOfError"/>. Higher confidence /// values result in more test iterations, and thus more overall test execution time. /// </summary> public double Confidence { get; set; } internal const double DefaultConfidence = 0.95; /// <summary> /// If set, indicates whether the test allocates from the GC heap. If true, test iterations will run until a GC occurs (and may /// continue to run due to other factors). If null, the test framework will attempt to determine whether the test has been /// allocating. /// </summary> public bool? TriggersGC { get; set; } /// <summary> /// If true, performance metrics will be computed for all iterations of the method. If false (the default), the first /// iteration of the method will be ignored when computing results. This "warmup" iteration helps eliminate one-time costs /// (such as JIT compilation time) from the results, but may be unnecessary for some tests. /// </summary> public bool SkipWarmup { get; set; } } }
mit
C#
373a23dbd716e50e72fc7bddde7c73a9066d4f25
Fix to put paye parameter into query string for api
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts/Services/PensionRegulatorService.cs
src/SFA.DAS.EmployerAccounts/Services/PensionRegulatorService.cs
using System.Collections.Generic; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using SFA.DAS.EmployerAccounts.Configuration; using SFA.DAS.EmployerAccounts.Interfaces; using SFA.DAS.EmployerAccounts.Models.PensionRegulator; namespace SFA.DAS.EmployerAccounts.Services { public class PensionRegulatorService : IPensionRegulatorService { private readonly EmployerAccountsConfiguration _configuration; private readonly IHttpService _httpService; public PensionRegulatorService( IHttpServiceFactory httpServiceFactory, EmployerAccountsConfiguration configuration) { _configuration = configuration; _httpService = httpServiceFactory.Create( configuration.PensionRegulatorApi.ClientId, configuration.PensionRegulatorApi.ClientSecret, configuration.PensionRegulatorApi.IdentifierUri, configuration.PensionRegulatorApi.Tenant ); } public async Task<IEnumerable<Organisation>> GetOrgansiationsByPayeRef(string payeRef) { var baseUrl = GetBaseUrl(); var url = $"{baseUrl}api/pensionsregulator?payeRef={HttpUtility.UrlEncode(payeRef)}"; var json = await _httpService.GetAsync(url, false); return json == null ? null : JsonConvert.DeserializeObject<IEnumerable<Organisation>>(json); } private string GetBaseUrl() { var baseUrl = _configuration.PensionRegulatorApi.BaseUrl.EndsWith("/") ? _configuration.PensionRegulatorApi.BaseUrl : _configuration.PensionRegulatorApi.BaseUrl + "/"; return baseUrl; } } }
using System.Collections.Generic; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using SFA.DAS.EmployerAccounts.Configuration; using SFA.DAS.EmployerAccounts.Interfaces; using SFA.DAS.EmployerAccounts.Models.PensionRegulator; namespace SFA.DAS.EmployerAccounts.Services { public class PensionRegulatorService : IPensionRegulatorService { private readonly EmployerAccountsConfiguration _configuration; private readonly IHttpService _httpService; public PensionRegulatorService( IHttpServiceFactory httpServiceFactory, EmployerAccountsConfiguration configuration) { _configuration = configuration; _httpService = httpServiceFactory.Create( configuration.PensionRegulatorApi.ClientId, configuration.PensionRegulatorApi.ClientSecret, configuration.PensionRegulatorApi.IdentifierUri, configuration.PensionRegulatorApi.Tenant ); } public async Task<IEnumerable<Organisation>> GetOrgansiationsByPayeRef(string payeRef) { var baseUrl = GetBaseUrl(); var url = $"{baseUrl}api/pensionsregulator/{HttpUtility.UrlEncode(payeRef)}"; var json = await _httpService.GetAsync(url, false); return json == null ? null : JsonConvert.DeserializeObject<IEnumerable<Organisation>>(json); } private string GetBaseUrl() { var baseUrl = _configuration.PensionRegulatorApi.BaseUrl.EndsWith("/") ? _configuration.PensionRegulatorApi.BaseUrl : _configuration.PensionRegulatorApi.BaseUrl + "/"; return baseUrl; } } }
mit
C#
6e9708626a8b7d2c0a2ad00d1aa6a5ec76e11987
Hide contact details if they are empty
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Web/Views/EmployerTeam/V2/SingleProvider.cshtml
src/SFA.DAS.EmployerAccounts.Web/Views/EmployerTeam/V2/SingleProvider.cshtml
 @using Microsoft.Ajax.Utilities @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel <h3 class="das-panel__heading">@Model.AccountViewModel.Providers.First().Name</h3> <dl class="das-definition-list das-definition-list--inline das-definition-list--muted govuk-!-font-size-16"> <dt class="das-definition-list__title">UK Provider Reference Number</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Ukprn</dd> </dl> <p> @if (@Model.AccountViewModel.Providers.First().Street != null) { @(Model.AccountViewModel.Providers.First().Street)@:, <br> } @(Model.AccountViewModel.Providers.First().Town)<text>, </text>@(Model.AccountViewModel.Providers.First().Postcode) </p> <dl class="das-definition-list das-definition-list--inline"> @if (!Model.AccountViewModel.Providers.First().Phone.IsNullOrWhiteSpace()) { <dt class="das-definition-list__title">Tel</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Phone</dd> } @if (!Model.AccountViewModel.Providers.First().Email.IsNullOrWhiteSpace()) { <dt class="das-definition-list__title">Email</dt> <dd class="das-definition-list__definition"><span class="das-breakable">@Model.AccountViewModel.Providers.First().Email</span></dd> } </dl> <p><a href="@Url.ProviderRelationshipsAction("providers")" class="govuk-link govuk-link--no-visited-state">View permissions</a> </p>
 @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel <h3 class="das-panel__heading">@Model.AccountViewModel.Providers.First().Name</h3> <dl class="das-definition-list das-definition-list--inline das-definition-list--muted govuk-!-font-size-16"> <dt class="das-definition-list__title">UK Provider Reference Number</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Ukprn</dd> </dl> <p> @if (@Model.AccountViewModel.Providers.First().Street != null) { @(Model.AccountViewModel.Providers.First().Street)@:, <br> } @(Model.AccountViewModel.Providers.First().Town)<text>, </text>@(Model.AccountViewModel.Providers.First().Postcode) </p> <dl class="das-definition-list das-definition-list--inline"> <dt class="das-definition-list__title">Tel</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Phone</dd> <dt class="das-definition-list__title">Email</dt> <dd class="das-definition-list__definition"><span class="das-breakable">@Model.AccountViewModel.Providers.First().Email</span></dd> </dl> <p><a href="@Url.ProviderRelationshipsAction("providers")" class="govuk-link govuk-link--no-visited-state">View permissions</a> </p>
mit
C#
93a322e73a0789214dc9fbf4e5047f0fad54f513
Initialize extras properly
takenet/blip-sdk-csharp
src/Take.Blip.Builder/Actions/TrackEvent/TrackEventAction.cs
src/Take.Blip.Builder/Actions/TrackEvent/TrackEventAction.cs
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Lime.Protocol; using Newtonsoft.Json.Linq; using Take.Blip.Client; using Take.Blip.Client.Extensions.EventTracker; namespace Take.Blip.Builder.Actions.TrackEvent { public class TrackEventAction : IAction { private readonly IEventTrackExtension _eventTrackExtension; private const string CATEGORY_KEY = "category"; private const string ACTION_KEY = "action"; private const string MESSAGE_ID_KEY = "#messageId"; public string Type => nameof(TrackEvent); public TrackEventAction(IEventTrackExtension eventTrackExtension) { _eventTrackExtension = eventTrackExtension; } public async Task ExecuteAsync(IContext context, JObject settings, CancellationToken cancellationToken) { if (context == null) throw new ArgumentNullException(nameof(context)); if (settings == null) throw new ArgumentNullException(nameof(settings), $"The settings are required for '{nameof(TrackEventAction)}' action"); var category = (string)settings[CATEGORY_KEY]; var action = (string)settings[ACTION_KEY]; if (string.IsNullOrEmpty(category)) throw new ArgumentException($"The '{nameof(category)}' settings value is required for '{nameof(TrackEventAction)}' action"); if (string.IsNullOrEmpty(action)) throw new ArgumentException($"The '{nameof(action)}' settings value is required for '{nameof(TrackEventAction)}' action"); var messageId = EnvelopeReceiverContext<Message>.Envelope?.Id; Dictionary<string, string> extras; if (settings.TryGetValue(nameof(extras), out var extrasToken)) { extras = extrasToken.ToObject<Dictionary<string, string>>(); } else { extras = new Dictionary<string, string>(); } extras[MESSAGE_ID_KEY] = messageId; await _eventTrackExtension.AddAsync(category, action, extras, cancellationToken, context.User); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Lime.Protocol; using Newtonsoft.Json.Linq; using Take.Blip.Client; using Take.Blip.Client.Extensions.EventTracker; namespace Take.Blip.Builder.Actions.TrackEvent { public class TrackEventAction : IAction { private readonly IEventTrackExtension _eventTrackExtension; private const string CATEGORY_KEY = "category"; private const string ACTION_KEY = "action"; private const string MESSAGE_ID_KEY = "#messageId"; public string Type => nameof(TrackEvent); public TrackEventAction(IEventTrackExtension eventTrackExtension) { _eventTrackExtension = eventTrackExtension; } public async Task ExecuteAsync(IContext context, JObject settings, CancellationToken cancellationToken) { if (context == null) throw new ArgumentNullException(nameof(context)); if (settings == null) throw new ArgumentNullException(nameof(settings), $"The settings are required for '{nameof(TrackEventAction)}' action"); var category = (string)settings[CATEGORY_KEY]; var action = (string)settings[ACTION_KEY]; if (string.IsNullOrEmpty(category)) throw new ArgumentException($"The '{nameof(category)}' settings value is required for '{nameof(TrackEventAction)}' action"); if (string.IsNullOrEmpty(action)) throw new ArgumentException($"The '{nameof(action)}' settings value is required for '{nameof(TrackEventAction)}' action"); var messageId = EnvelopeReceiverContext<Message>.Envelope?.Id; Dictionary<string, string> extras = null; if (settings.TryGetValue(nameof(extras), out var extrasToken)) { extras = extrasToken.ToObject<Dictionary<string, string>>(); } extras.Add(MESSAGE_ID_KEY, messageId); await _eventTrackExtension.AddAsync(category, action, extras, cancellationToken, context.User); } } }
apache-2.0
C#
61f305c6a7fbde22484554f09fb104edb68051d0
increment pre-release version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.7.0")] [assembly: AssemblyInformationalVersion("0.7.0-pre01")] /* * Version 0.7.0-pre01 * * - Experiment.AutoFixture에서 AutoFixture.Xunit의 CustomizeAttribute 지원. * 이로써, 테스트 메소드 파라메타의 어트리뷰트를 통해 dependency injection을 * 이용할 수 있음. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.6.1")] [assembly: AssemblyInformationalVersion("0.6.1")] /* * Version 0.6.1 * * - TestFixtureAdapter의 디폴트 생성자는 * "Anything more than field assignment in constructors"에 해당함으로 이를 * 해결(삭제). * * - TestFixtureAdapter의 디폴트 생성자 삭제는 breaking change에 해당하나, * unstable major version(zero)이기 때문에 용인됨. */
mit
C#
9b9ca4a08d542ff8796e1ef754a7aa6687d099bf
increment patch version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.22.4")] [assembly: AssemblyInformationalVersion("0.22.4")] /* * Version 0.22.4 * * - [FIX] Made the construtor of FirstClassCommand accept a testParameterName * argument. (BREAKING-CHANGE) * * Before: * public FirstClassCommand(IMethodInfo method, Delegate @delegate, object[] arguments) * * After: * public FirstClassCommand(IMethodInfo method, string testParameterName, Delegate @delegate, object[] arguments) * * - [FIX] Added a new constructor of the TestCase class to show customizable * test-parameters. * * public TestCase(string testParameterName, Delegate @delegate) */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.22.3")] [assembly: AssemblyInformationalVersion("0.22.3")] /* * Version 0.22.4 * * - [FIX] Made the construtor of FirstClassCommand accept a testParameterName * argument. (BREAKING-CHANGE) * * Before: * public FirstClassCommand( * IMethodInfo method, * Delegate @delegate, * object[] arguments) * After: * public FirstClassCommand( * IMethodInfo method, * string testParameterName, * Delegate @delegate, * object[] arguments) * * - [FIX] Added a new constructor of the TestCase class to show customizable * test-parameters. * * public TestCase(string testParameterName, Delegate @delegate) */
mit
C#
50e9c927825c8973d9234a657ee2aafdc5a9e28f
Update CurrencylayerDotComTests.cs
tiksn/TIKSN-Framework
TIKSN.Framework.IntegrationTests/Finance/ForeignExchange/CurrencylayerDotComTests.cs
TIKSN.Framework.IntegrationTests/Finance/ForeignExchange/CurrencylayerDotComTests.cs
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using TIKSN.Finance.ForeignExchange.Cumulative; using TIKSN.Framework.IntegrationTests; using TIKSN.Globalization; using TIKSN.Time; using Xunit; namespace TIKSN.Finance.Tests.ForeignExchange { [Collection("ServiceProviderCollection")] public class CurrencylayerDotComTests { private readonly string accessKey = "<put your access key here>"; private readonly ICurrencyFactory currencyFactory; private readonly ITimeProvider timeProvider; private readonly ServiceProviderFixture serviceProviderFixture; public CurrencylayerDotComTests(ServiceProviderFixture serviceProviderFixture) { this.currencyFactory = serviceProviderFixture.Services.GetRequiredService<ICurrencyFactory>(); this.timeProvider = serviceProviderFixture.Services.GetRequiredService<ITimeProvider>(); this.serviceProviderFixture = serviceProviderFixture ?? throw new ArgumentNullException(nameof(serviceProviderFixture)); } //[Fact] public async Task GetCurrencyPairs001Async() { var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey); var pairs = await exchange.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(pairs.Count() > 0); } //[Fact] public async Task GetExchangeRateAsync001Async() { var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey); var pair = new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("UAH")); var rate = await exchange.GetExchangeRateAsync(pair, DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(rate > decimal.Zero); } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using TIKSN.Finance.ForeignExchange.Cumulative; using TIKSN.Framework.IntegrationTests; using TIKSN.Globalization; using TIKSN.Time; using Xunit; namespace TIKSN.Finance.Tests.ForeignExchange { [Collection("ServiceProviderCollection")] public class CurrencylayerDotComTests { private readonly string accessKey = "<put your access key here>"; private readonly ICurrencyFactory currencyFactory; private readonly ITimeProvider timeProvider; private readonly ServiceProviderFixture serviceProviderFixture; public CurrencylayerDotComTests(ServiceProviderFixture serviceProviderFixture) { this.currencyFactory = serviceProviderFixture.Services.GetRequiredService<ICurrencyFactory>(); this.timeProvider = serviceProviderFixture.Services.GetRequiredService<ITimeProvider>(); this.serviceProviderFixture = serviceProviderFixture ?? throw new ArgumentNullException(nameof(serviceProviderFixture)); } //[Fact] public async Task GetCurrencyPairs001() { var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey); var pairs = await exchange.GetCurrencyPairsAsync(DateTimeOffset.Now, default); Assert.True(pairs.Count() > 0); } //[Fact] public async Task GetExchangeRateAsync001() { var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey); var pair = new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("UAH")); var rate = await exchange.GetExchangeRateAsync(pair, DateTimeOffset.Now, default); Assert.True(rate > decimal.Zero); } } }
mit
C#
f18b4ec3f5bae3f4cc215e75cbc5bc61663f880f
Update InputArgs.cs
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Core2D/Editor/Input/InputArgs.cs
src/Core2D/Editor/Input/InputArgs.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.Input { /// <summary> /// Input arguments. /// </summary> public struct InputArgs { /// <summary> /// Gets input X position. /// </summary> public double X { get; } /// <summary> /// Gets input Y position. /// </summary> public double Y { get; } /// <summary> /// Gets input modifier flags. /// </summary> public ModifierFlags Modifier { get; } /// <summary> /// Initializes a new instance of the <see cref="InputArgs"/> struct. /// </summary> /// <param name="x">The input X position.</param> /// <param name="y">The input Y position.</param> /// <param name="modifier">The input modifier flags.</param> public InputArgs(double x, double y, ModifierFlags modifier) { this.X = x; this.Y = y; this.Modifier = modifier; } } }
// 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 Core2D.Spatial; namespace Core2D.Editor.Input { /// <summary> /// Input arguments. /// </summary> public struct InputArgs { /// <summary> /// Gets input position. /// </summary> public Vector2 Position { get; } /// <summary> /// Gets input modifier flags. /// </summary> public ModifierFlags Modifier { get; } /// <summary> /// Initializes a new instance of the <see cref="InputArgs"/> struct. /// </summary> /// <param name="position">The input position.</param> /// <param name="modifier">The modifier flags.</param> public InputArgs(Vector2 position, ModifierFlags modifier) { this.Position = position; this.Modifier = modifier; } } }
mit
C#
0e0596d29f12e9ce0fe81e32d13db7a0650352ae
set up structure alittle.
Xormis/grikly-dotnet
src/GriklyApi.Portable/Users.cs
src/GriklyApi.Portable/Users.cs
using System.IO; using System.Net; using System.Text; using Grikly.Models; using System; namespace Grikly { public partial class GriklyApi { public void GetUser(int id, Action<User> callback) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Grikly.Models; namespace Grikly { public partial class GriklyApi { public User GetUser(int id) { throw new NotImplementedException(); } } }
mit
C#
d1b56683f5cccb5f9fcb3d22f1f3c89d7a7572d7
Update Plasmatech.cs (#32)
BosslandGmbH/BuddyWing.DefaultCombat
trunk/DefaultCombat/Routines/Advanced/Vanguard/Plasmatech.cs
trunk/DefaultCombat/Routines/Advanced/Vanguard/Plasmatech.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 Plasmatech : RotationBase { public override string Name { get { return "Vanguard Plasmatech"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("Fortification") ); } } public override Composite Cooldowns { get { return new PrioritySelector( Spell.Buff("Tenacity"), Spell.Buff("Battle Focus"), Spell.Buff("Recharge Cells", ret => Me.ResourcePercent() <= 50), Spell.Buff("Reserve Powercell"), Spell.Buff("Reactive Shield", ret => Me.HealthPercent <= 60), Spell.Buff("Adrenaline Rush", ret => Me.HealthPercent <= 30) ); } } public override Composite SingleTarget { get { return new PrioritySelector( //Movement CombatMovement.CloseDistance(Distance.Melee), new Decorator(ret => Me.ResourcePercent() < 60, new PrioritySelector( Spell.Cast("High Impact Bolt", ret => Me.HasBuff("Ionic Accelerator")), Spell.Cast("Hammer Shot") )), Spell.Cast("High Impact Bolt"), Spell.Cast("Stockstrike", ret => Me.CurrentTarget.Distance <= .4f), Spell.Cast("Assault Plastique"), Spell.DoT("Incendiary Round", "", 12000), Spell.Cast("Shockstrike"), Spell.Cast("Ion Pulse") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector( Spell.CastOnGround("Artillery Blitz"), Spell.Cast("Ion Wave", ret => Me.CurrentTarget.Distance <= 1f), Spell.Cast("Flak Shell", ret => Me.CurrentTarget.Distance <= 1f), Spell.Cast("Explosive Surge", ret => Me.CurrentTarget.Distance <= .5f) )); } } } }
// 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 Plasmatech : RotationBase { public override string Name { get { return "Vanguard Plasmatech"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("Plasma Cell"), Spell.Buff("Fortification") ); } } public override Composite Cooldowns { get { return new PrioritySelector( Spell.Buff("Tenacity"), Spell.Buff("Battle Focus"), Spell.Buff("Recharge Cells", ret => Me.ResourcePercent() <= 50), Spell.Buff("Reserve Powercell"), Spell.Buff("Reactive Shield", ret => Me.HealthPercent <= 60), Spell.Buff("Adrenaline Rush", ret => Me.HealthPercent <= 30) ); } } public override Composite SingleTarget { get { return new PrioritySelector( //Movement CombatMovement.CloseDistance(Distance.Melee), new Decorator(ret => Me.ResourcePercent() < 60, new PrioritySelector( Spell.Cast("High Impact Bolt", ret => Me.HasBuff("Ionic Accelerator")), Spell.Cast("Hammer Shot") )), Spell.Cast("High Impact Bolt"), Spell.Cast("Assault Plastique"), Spell.DoT("Incendiary Round", "", 12000), Spell.Cast("Shockstrike"), Spell.Cast("Ion Pulse") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector( Spell.CastOnGround("Mortar Volley"), Spell.Cast("Pulse Cannon", ret => Me.CurrentTarget.Distance <= 1f), Spell.Cast("Explosive Surge", ret => Me.CurrentTarget.Distance <= .5f) )); } } } }
apache-2.0
C#
74dff3419ff176921c83a5534084e247d62dfe1e
fix build errror
ObjectivityBSS/Test.Automation,ObjectivityLtd/Test.Automation
Objectivity.Test.Automation.Common/WebElements/JavaScriptAlert.cs
Objectivity.Test.Automation.Common/WebElements/JavaScriptAlert.cs
/* The MIT License (MIT) Copyright (c) 2015 Objectivity Bespoke Software Specialists 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. */ namespace Objectivity.Test.Automation.Common.WebElements { using OpenQA.Selenium; /// <summary> /// Implementation for JavaScript Alert interface. /// </summary> public class JavaScriptAlert { /// <summary> /// The web driver /// </summary> private readonly IWebDriver webDriver; /// <summary> /// Initializes a new instance of the <see cref="JavaScriptAlert"/> class. /// </summary> /// <param name="webDriver">The web driver.</param> public JavaScriptAlert(IWebDriver webDriver) { this.webDriver = webDriver; } /// <summary> /// Get Java script popup text /// </summary> public string JavaScriptText { get { return webDriver.SwitchTo().Alert().Text; } } /// <summary> /// Confirms the java script alert popup. /// </summary> public void ConfirmJavaScriptAlert() { this.webDriver.SwitchTo().Alert().Accept(); this.webDriver.SwitchTo().DefaultContent(); } /// <summary> /// Dismisses the java script alert popup. /// </summary> public void DismissJavaScriptAlert() { this.webDriver.SwitchTo().Alert().Dismiss(); } } }
/* The MIT License (MIT) Copyright (c) 2015 Objectivity Bespoke Software Specialists 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. */ namespace Objectivity.Test.Automation.Common.WebElements { using OpenQA.Selenium; /// <summary> /// Implementation for JavaScript Alert interface. /// </summary> public class JavaScriptAlert { /// <summary> /// The web driver /// </summary> private readonly IWebDriver webDriver; /// <summary> /// get Java script popup text /// </summary> public string JavaScriptText { get { return webDriver.SwitchTo().Alert().Text; } } /// <summary> /// Initializes a new instance of the <see cref="JavaScriptAlert"/> class. /// </summary> /// <param name="webDriver">The web driver.</param> public JavaScriptAlert(IWebDriver webDriver) { this.webDriver = webDriver; } /// <summary> /// Confirms the java script alert popup. /// </summary> public void ConfirmJavaScriptAlert() { this.webDriver.SwitchTo().Alert().Accept(); this.webDriver.SwitchTo().DefaultContent(); } /// <summary> /// Dismisses the java script alert popup. /// </summary> public void DismissJavaScriptAlert() { this.webDriver.SwitchTo().Alert().Dismiss(); } } }
mit
C#
55496ba5d5fa2e3f38b51fe8db9e024980ebf5a5
Add missing license header
paseb/HoloToolkit-Unity,paseb/MixedRealityToolkit-Unity,out-of-pixel/HoloToolkit-Unity,NeerajW/HoloToolkit-Unity,willcong/HoloToolkit-Unity,HattMarris1/HoloToolkit-Unity
Assets/HoloToolkit/Utilities/Scripts/RaycastResultComparer.cs
Assets/HoloToolkit/Utilities/Scripts/RaycastResultComparer.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using UnityEngine.EventSystems; namespace HoloToolkit.Unity { public class RaycastResultComparer : IComparer<RaycastResult> { public int Compare(RaycastResult left, RaycastResult right) { var result = CompareRaycastsByCanvasDepth(left, right); if (result != 0) { return result; } return CompareRaycastsByDistance(left, right); } private static int CompareRaycastsByCanvasDepth(RaycastResult left, RaycastResult right) { //Module is the graphic raycaster on the canvases. if (left.module.transform.IsParentOrChildOf(right.module.transform)) { return left.depth.CompareTo(right.depth); } return 0; } private static int CompareRaycastsByDistance(RaycastResult left, RaycastResult right) { return right.distance.CompareTo(left.distance); } } }
using System.Collections.Generic; using UnityEngine.EventSystems; namespace HoloToolkit.Unity { public class RaycastResultComparer : IComparer<RaycastResult> { public int Compare(RaycastResult left, RaycastResult right) { var result = CompareRaycastsByCanvasDepth(left, right); if (result != 0) { return result; } return CompareRaycastsByDistance(left, right); } private static int CompareRaycastsByCanvasDepth(RaycastResult left, RaycastResult right) { //Module is the graphic raycaster on the canvases. if (left.module.transform.IsParentOrChildOf(right.module.transform)) { return left.depth.CompareTo(right.depth); } return 0; } private static int CompareRaycastsByDistance(RaycastResult left, RaycastResult right) { return right.distance.CompareTo(left.distance); } } }
mit
C#
eaf3c60339d0374ef15162a7327895faf34ae066
Revert "Bump WebApi version to 5.10.3"
MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net
Mindscape.Raygun4Net.WebApi/Properties/AssemblyVersionInfo.cs
Mindscape.Raygun4Net.WebApi/Properties/AssemblyVersionInfo.cs
using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.10.1.0")] [assembly: AssemblyFileVersion("5.10.1.0")]
using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.10.2.0")] [assembly: AssemblyFileVersion("5.10.2.0")]
mit
C#
0c2f0122b78fea983ae79c173aceaaf981fbca2f
Fix a forest crash in ZZT.
SaxxonPike/roton,SaxxonPike/roton
Roton/Emulation/Interactions/Impl/ForestInteraction.cs
Roton/Emulation/Interactions/Impl/ForestInteraction.cs
using System; using Roton.Emulation.Core; using Roton.Emulation.Data; using Roton.Emulation.Data.Impl; using Roton.Infrastructure.Impl; namespace Roton.Emulation.Interactions.Impl { [Context(Context.Original, 0x14)] [Context(Context.Super, 0x14)] public sealed class ForestInteraction : IInteraction { private readonly Lazy<IEngine> _engine; private IEngine Engine => _engine.Value; public ForestInteraction(Lazy<IEngine> engine) { _engine = engine; } public void Interact(IXyPair location, int index, IXyPair vector) { Engine.ClearForest(location); Engine.UpdateBoard(location); var forestSongLength = Engine.Sounds.Forest.Length; var forestIndex = Engine.State.ForestIndex % forestSongLength; Engine.State.ForestIndex = (forestIndex + 2) % forestSongLength; Engine.PlaySound(3, Engine.Sounds.Forest, forestIndex, 2); if (!Engine.Alerts.Forest) return; Engine.SetMessage(0xC8, Engine.Alerts.ForestMessage); Engine.Alerts.Forest = false; } } }
using System; using Roton.Emulation.Core; using Roton.Emulation.Data; using Roton.Emulation.Data.Impl; using Roton.Infrastructure.Impl; namespace Roton.Emulation.Interactions.Impl { [Context(Context.Original, 0x14)] [Context(Context.Super, 0x14)] public sealed class ForestInteraction : IInteraction { private readonly Lazy<IEngine> _engine; private IEngine Engine => _engine.Value; public ForestInteraction(Lazy<IEngine> engine) { _engine = engine; } public void Interact(IXyPair location, int index, IXyPair vector) { Engine.ClearForest(location); Engine.UpdateBoard(location); var forestIndex = Engine.State.ForestIndex; var forestSongLength = Engine.Sounds.Forest.Length; Engine.State.ForestIndex = (forestIndex + 2) % forestSongLength; Engine.PlaySound(3, Engine.Sounds.Forest, forestIndex, 2); if (!Engine.Alerts.Forest) return; Engine.SetMessage(0xC8, Engine.Alerts.ForestMessage); Engine.Alerts.Forest = false; } } }
isc
C#
7e5c16c078943f3706b1aac4300ef9a6f3cbf6fe
Fix background color of thumbnails in image gallery when not using browser
ermshiperete/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,ermshiperete/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso
SIL.Windows.Forms/ImageToolbox/ImageGallery/ImageUtilities.cs
SIL.Windows.Forms/ImageToolbox/ImageGallery/ImageUtilities.cs
using System.Drawing; using System.Drawing.Drawing2D; using SIL.PlatformUtilities; namespace SIL.Windows.Forms.ImageToolbox.ImageGallery { public static class ImageUtilities { public static Image GetThumbNail(string imagePath, int destinationWidth, int destinationHeight, Color borderColor, Color backgroundColor) { Bitmap bmp; try { bmp = new Bitmap(imagePath); } catch { bmp = new Bitmap(destinationWidth, destinationHeight); //If we cant load the image, create a blank one with ThumbSize } //get the lesser of the desired and original size destinationWidth = bmp.Width > destinationWidth ? destinationWidth : bmp.Width; destinationHeight = bmp.Height > destinationHeight ? destinationHeight : bmp.Height; var actualWidth = destinationWidth; var actualHeight = destinationHeight; if (bmp.Width > bmp.Height) actualHeight = (int)((bmp.Height / (float)bmp.Width) * actualWidth); else if (bmp.Width < bmp.Height) actualWidth = (int)((bmp.Width / (float)bmp.Height) * actualHeight); var horizontalOffset = (destinationWidth / 2) - (actualWidth / 2); var verticalOffset = (destinationHeight / 2) - (actualHeight / 2); var retBmp = Platform.IsWindows ? new Bitmap(destinationWidth, destinationHeight, System.Drawing.Imaging.PixelFormat.Format64bppPArgb) : new Bitmap(destinationWidth, destinationHeight); using (var grp = Graphics.FromImage(retBmp)) { grp.PixelOffsetMode = PixelOffsetMode.None; grp.InterpolationMode = InterpolationMode.HighQualityBicubic; // fill with background color using (var b = new SolidBrush(backgroundColor)) { grp.FillRectangle(b, 0, 0, destinationWidth, destinationHeight); } // draw the image grp.DrawImage(bmp, horizontalOffset, verticalOffset, actualWidth, actualHeight); // draw border using (var pn = new Pen(borderColor, 1)) { grp.DrawRectangle(pn, 0, 0, retBmp.Width - 1, retBmp.Height - 1); } } return retBmp; } public static Image GetThumbNail(string imagePath, int destinationWidth, int destinationHeight, Color borderColor) { // This uses black as the default background color in order to avoid changing the behavior. Previously // the method created an image without setting the background color which resulted in the image having // a black background. return GetThumbNail(imagePath, destinationWidth, destinationHeight, borderColor, Color.White); } } }
using System.Drawing; using System.Drawing.Drawing2D; using SIL.PlatformUtilities; namespace SIL.Windows.Forms.ImageToolbox.ImageGallery { public static class ImageUtilities { public static Image GetThumbNail(string imagePath, int destinationWidth, int destinationHeight, Color borderColor, Color backgroundColor) { Bitmap bmp; try { bmp = new Bitmap(imagePath); } catch { bmp = new Bitmap(destinationWidth, destinationHeight); //If we cant load the image, create a blank one with ThumbSize } //get the lesser of the desired and original size destinationWidth = bmp.Width > destinationWidth ? destinationWidth : bmp.Width; destinationHeight = bmp.Height > destinationHeight ? destinationHeight : bmp.Height; var actualWidth = destinationWidth; var actualHeight = destinationHeight; if (bmp.Width > bmp.Height) actualHeight = (int)((bmp.Height / (float)bmp.Width) * actualWidth); else if (bmp.Width < bmp.Height) actualWidth = (int)((bmp.Width / (float)bmp.Height) * actualHeight); var horizontalOffset = (destinationWidth / 2) - (actualWidth / 2); var verticalOffset = (destinationHeight / 2) - (actualHeight / 2); var retBmp = Platform.IsWindows ? new Bitmap(destinationWidth, destinationHeight, System.Drawing.Imaging.PixelFormat.Format64bppPArgb) : new Bitmap(destinationWidth, destinationHeight); using (var grp = Graphics.FromImage(retBmp)) { grp.PixelOffsetMode = PixelOffsetMode.None; grp.InterpolationMode = InterpolationMode.HighQualityBicubic; // fill with background color using (var b = new SolidBrush(backgroundColor)) { grp.FillRectangle(b, 0, 0, destinationWidth, destinationHeight); } // draw the image grp.DrawImage(bmp, horizontalOffset, verticalOffset, actualWidth, actualHeight); // draw border using (var pn = new Pen(borderColor, 1)) { grp.DrawRectangle(pn, 0, 0, retBmp.Width - 1, retBmp.Height - 1); } } return retBmp; } public static Image GetThumbNail(string imagePath, int destinationWidth, int destinationHeight, Color borderColor) { // This uses black as the default background color in order to avoid changing the behavior. Previously // the method created an image without setting the background color which resulted in the image having // a black background. return GetThumbNail(imagePath, destinationWidth, destinationHeight, borderColor, Color.Black); } } }
mit
C#
50501b51a389e33f9d31319fcfe60da9a3f5d1cb
Read table id
TeamnetGroup/schema2fm
src/ConsoleApp/Program.cs
src/ConsoleApp/Program.cs
using System; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Threading.Tasks; namespace ConsoleApp { class Program { private static void Main() { Work().GetAwaiter().GetResult(); } private static async Task Work() { const string connectionString = @"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"; const string schemaName = "dbo"; const string tableName = "Book"; using (DbConnection connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); using (var command = connection.CreateCommand()) { command.CommandText = @"select t.object_id from sys.tables t inner join sys.schemas s on t.schema_id = s.schema_id where s.name = @schemaName and t.name = @tableName"; var schemaNameParameter = command.CreateParameter(); schemaNameParameter.DbType = DbType.String; schemaNameParameter.ParameterName = "@schemaName"; schemaNameParameter.Value = schemaName; command.Parameters.Add(schemaNameParameter); var tableNameParameter = command.CreateParameter(); tableNameParameter.DbType = DbType.String; tableNameParameter.ParameterName = "@tableName"; tableNameParameter.Value = tableName; command.Parameters.Add(tableNameParameter); using (var reader = await command.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { var tableId = reader.GetFieldValue<int>(0); Console.WriteLine($"Table has object id {tableId}"); } } } } } } }
using System.Data.Common; using System.Data.SqlClient; using System.Threading.Tasks; namespace ConsoleApp { class Program { private static void Main() { Work().GetAwaiter().GetResult(); } private static async Task Work() { const string connectionString = @"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"; using (DbConnection connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); } } } }
mit
C#
d61d82f478db1a9a3407527c45c4f10bcd864279
Refactor improve teardown
Suui/SlothUnit,Suui/SlothUnit,Suui/SlothUnit
SlothUnit/SlothUnit.Parser.Test/CodeGeneratorShould.cs
SlothUnit/SlothUnit.Parser.Test/CodeGeneratorShould.cs
using System; using System.IO; using System.Linq; using FluentAssertions; using NUnit.Framework; using SlothUnit.Parser.Core; /* TODO - __Generated__ folder - __Main__ file including slothunit and __Tests__ - __Tests__ file including all generated / +Recurse */ namespace SlothUnit.Parser.Test { [TestFixture] public class CodeGeneratorShould : FileSystemTest { private string GeneratedFolderPath { get; } = Path.Combine(TestProjectDir, NameOfThe.GeneratedFolder); [TearDown] public void delete_generated_elements() { var generatedFolderPath = Path.Combine(TestProjectDir, NameOfThe.GeneratedFolder); if (Directory.Exists(generatedFolderPath)) Directory.Delete(generatedFolderPath, true); } [Test] public void generate_the_folder_containing_the_generated_files() { var slothGenerator = new SlothGenerator(TestProjectDir); slothGenerator.GenerateFolder(); Directory.GetDirectories(TestProjectDir) .Contains(GeneratedFolderPath).Should().BeTrue(); } [Test] public void generate_the_main_file() { var slothGenerator = new SlothGenerator(TestProjectDir); slothGenerator.GenerateFolder(); slothGenerator.GenerateMainFile(); var expectedMainFile = RetrieveExpectedFile(NameOfThe.MainFile); var generatedFile = RetrieveGeneratedFile(NameOfThe.MainFile); File.ReadAllText(generatedFile).Should().Be(File.ReadAllText(expectedMainFile)); } [Test] public void generate_the_included_tests_file() { var slothGenerator = new SlothGenerator(TestProjectDir); slothGenerator.GenerateFolder(); slothGenerator.GenerateIncludedTestsFile(); var generatedFile = RetrieveGeneratedFile(NameOfThe.IncludedTestsFile); File.ReadAllText(generatedFile).Should().Be("#pragma once"); } private static string RetrieveExpectedFile(string fileName) { var slothUnitTestDir = Path.Combine(SolutionDir, "SlothUnit.Parser.Test"); return Directory.GetFiles(slothUnitTestDir) .Single(path => path.Equals(Path.Combine(slothUnitTestDir, fileName))); } private string RetrieveGeneratedFile(string fileName) { return Directory.GetFiles(GeneratedFolderPath) .Single(name => name.Equals(Path.Combine(GeneratedFolderPath, fileName))); } } }
using System; using System.IO; using System.Linq; using FluentAssertions; using NUnit.Framework; using SlothUnit.Parser.Core; /* TODO - __Generated__ folder - __Main__ file including slothunit and __Tests__ - __Tests__ file including all generated / +Recurse */ namespace SlothUnit.Parser.Test { [TestFixture] public class CodeGeneratorShould : FileSystemTest { private string GeneratedFolderPath { get; } = Path.Combine(TestProjectDir, NameOfThe.GeneratedFolder); [TearDown] public void delete_generated_elements() { try { var generatedFolder = Directory.GetDirectories(TestProjectDir) .Single(path => path.Equals(GeneratedFolderPath)); Directory.Delete(generatedFolder, true); } catch (InvalidOperationException) {} } [Test] public void generate_the_folder_containing_the_generated_files() { var slothGenerator = new SlothGenerator(TestProjectDir); slothGenerator.GenerateFolder(); Directory.GetDirectories(TestProjectDir) .Contains(GeneratedFolderPath).Should().BeTrue(); } [Test] public void generate_the_main_file() { var slothGenerator = new SlothGenerator(TestProjectDir); slothGenerator.GenerateFolder(); slothGenerator.GenerateMainFile(); var expectedMainFile = RetrieveExpectedFile(NameOfThe.MainFile); var generatedFile = RetrieveGeneratedFile(NameOfThe.MainFile); File.ReadAllText(generatedFile).Should().Be(File.ReadAllText(expectedMainFile)); } [Test] public void generate_the_included_tests_file() { var slothGenerator = new SlothGenerator(TestProjectDir); slothGenerator.GenerateFolder(); slothGenerator.GenerateIncludedTestsFile(); var generatedFile = RetrieveGeneratedFile(NameOfThe.IncludedTestsFile); File.ReadAllText(generatedFile).Should().Be("#pragma once"); } private static string RetrieveExpectedFile(string fileName) { var slothUnitTestDir = Path.Combine(SolutionDir, "SlothUnit.Parser.Test"); return Directory.GetFiles(slothUnitTestDir) .Single(path => path.Equals(Path.Combine(slothUnitTestDir, fileName))); } private string RetrieveGeneratedFile(string fileName) { return Directory.GetFiles(GeneratedFolderPath) .Single(name => name.Equals(Path.Combine(GeneratedFolderPath, fileName))); } } }
mit
C#
ec06ba2296b97c2d86d591c60c9906a209cd2065
Add extension method `ISelectionMgr.DeselectAllUndoable`
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/SelectionManagerExtensions.cs
SolidworksAddinFramework/SelectionManagerExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reactive; using System.Reactive.Disposables; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; namespace SolidworksAddinFramework { public static class SelectionManagerExtensions { private class ObjectProperties { public ObjectProperties(int index, swSelectType_e type, int mark) { Index = index; Type = type; Mark = mark; } public int Index { get; } public swSelectType_e Type { get; } public int Mark { get; } } private const int AnyMark = -1; private const int NoMark = 0; private const int StartIndex = 1; private static IEnumerable<ObjectProperties> GetSelectedObjectProperties(ISelectionMgr selMgr) { var count = selMgr.GetSelectedObjectCount(); return Enumerable.Range(StartIndex, count) .Select(i => { var type = (swSelectType_e)selMgr.GetSelectedObjectType3(i, AnyMark); var mark = selMgr.GetSelectedObjectMark(i); return new ObjectProperties(i, type, mark); }); } /// <summary> /// Get selected objects filtered by type and mark /// </summary> /// <param name="selMgr"></param> /// <param name="filter">(type,mark)=>bool</param> /// <returns></returns> public static IEnumerable<object> GetSelectedObjects(this ISelectionMgr selMgr, Func<swSelectType_e, int, bool> filter) { return GetSelectedObjectProperties(selMgr) .Where(o => filter(o.Type, o.Mark)) .Select(o => selMgr.GetSelectedObject6(o.Index, AnyMark)); } public static void DeselectAll(this ISelectionMgr selMgr) { Enumerable.Repeat(Unit.Default, selMgr.GetSelectedObjectCount()) .ForEach(o => selMgr.DeSelect2(StartIndex, AnyMark)); } public static IDisposable DeselectAllUndoable(this ISelectionMgr selMgr) { var selectedObjects = GetSelectedObjectProperties(selMgr) .Select(props => new { props, obj = selMgr.GetSelectedObject6(props.Index, AnyMark) }) .ToList(); selMgr.DeselectAll(); return Disposable.Create(() => { selectedObjects .ForEach(o => { var selectData = (ISelectData) selMgr.CreateSelectData(); selectData.Mark = o.props.Mark; selMgr.AddSelectionListObject(o.obj, selectData); }); }); } } }
using System; using System.Collections.Generic; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; namespace SolidworksAddinFramework { public static class SelectionManagerExtensions { /// <summary> /// Get selected objects filtered by type and mark /// </summary> /// <param name="selMgr"></param> /// <param name="filter">(type,mark)=>bool</param> /// <returns></returns> public static IEnumerable<object> GetSelectedObjects(this ISelectionMgr selMgr, Func<swSelectType_e, int, bool> filter) { var count = selMgr.GetSelectedObjectCount(); for (var i = 1; i <= count; i++) { var type = (swSelectType_e) selMgr.GetSelectedObjectType3(i, -1); var mark = selMgr.GetSelectedObjectMark(i); if (filter(type, mark)) yield return selMgr.GetSelectedObject6(i,-1); } } } }
mit
C#
8f226c899243e4a6d45916f67445971c14b725ff
Update AssemblyInfo.cs
ipjohnson/Grace
Source/Grace.Common.Logging/Properties/AssemblyInfo.cs
Source/Grace.Common.Logging/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("Grace.Common.Logging")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Grace.Common.Logging")] [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("467b6021-164d-445c-8437-f6c395ed8a21")] // 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")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Grace.Common.Logging")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Grace.Common.Logging")] [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("467b6021-164d-445c-8437-f6c395ed8a21")] // 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#
51f2299181d382a75ec14890e8ba2d76953dc3bf
Make FileSystemPath internal for now
xoofx/zio
src/Zio/FileSystemPath.cs
src/Zio/FileSystemPath.cs
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System; namespace Zio { /// <summary> /// Tuple between a <see cref="IFileSystem"/> and an associated <see cref="UPath"/> /// </summary> internal struct FileSystemPath : IEquatable<FileSystemPath> { public static readonly FileSystemPath Empty = new FileSystemPath(); public FileSystemPath(IFileSystem fileSystem, UPath path) { if (fileSystem == null) throw new ArgumentNullException(nameof(fileSystem)); path.AssertAbsolute(); FileSystem = fileSystem; Path = path; } public readonly IFileSystem FileSystem; public readonly UPath Path; public bool Equals(FileSystemPath other) { return Equals(FileSystem, other.FileSystem) && Path.Equals(other.Path); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is FileSystemPath && Equals((FileSystemPath) obj); } public override int GetHashCode() { unchecked { return ((FileSystem != null ? FileSystem.GetHashCode() : 0) * 397) ^ Path.GetHashCode(); } } public static bool operator ==(FileSystemPath left, FileSystemPath right) { return left.Equals(right); } public static bool operator !=(FileSystemPath left, FileSystemPath right) { return !left.Equals(right); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System; namespace Zio { public struct FileSystemPath : IEquatable<FileSystemPath> { public static readonly FileSystemPath Empty = new FileSystemPath(); public FileSystemPath(IFileSystem fileSystem, UPath path) { if (fileSystem == null) throw new ArgumentNullException(nameof(fileSystem)); path.AssertAbsolute(); FileSystem = fileSystem; Path = path; } public readonly IFileSystem FileSystem; public readonly UPath Path; public bool Equals(FileSystemPath other) { return Equals(FileSystem, other.FileSystem) && Path.Equals(other.Path); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is FileSystemPath && Equals((FileSystemPath) obj); } public override int GetHashCode() { unchecked { return ((FileSystem != null ? FileSystem.GetHashCode() : 0) * 397) ^ Path.GetHashCode(); } } public static bool operator ==(FileSystemPath left, FileSystemPath right) { return left.Equals(right); } public static bool operator !=(FileSystemPath left, FileSystemPath right) { return !left.Equals(right); } } }
bsd-2-clause
C#
8beb5568b82108664ff3f97b9bee0808477f5bd8
Fix speed bonus
ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu
osu.Game.Rulesets.Taiko/Difficulty/Evaluators/StaminaEvaluator.cs
osu.Game.Rulesets.Taiko/Difficulty/Evaluators/StaminaEvaluator.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing; using osu.Game.Rulesets.Taiko.Objects; namespace osu.Game.Rulesets.Taiko.Difficulty.Evaluators { public class StaminaEvaluator { /// <summary> /// Applies a speed bonus dependent on the time since the last hit performed using this key. /// </summary> /// <param name="interval">The interval between the current and previous note hit using the same key.</param> private static double speedBonus(double interval) { // Cap to 600bpm 1/4, 25ms note interval, 50ms key interval // This is temporary measure to prevent mono abuses. Once that is properly addressed, interval will be // capped at a very small value to avoid infinite/negative speed bonuses. interval = Math.Max(interval, 50); return 30 / interval; } /// <summary> /// Evaluates the minimum mechanical stamina required to play the current object. This is calculated using the /// maximum possible interval between two hits using the same key, by alternating 2 keys for each colour. /// </summary> public static double EvaluateDifficultyOf(DifficultyHitObject current) { if (current.BaseObject is not Hit) { return 0.0; } // Find the previous hit object hit by the current key, which is two notes of the same colour prior. TaikoDifficultyHitObject taikoCurrent = (TaikoDifficultyHitObject)current; TaikoDifficultyHitObject? keyPrevious = taikoCurrent.PreviousMono(1); if (keyPrevious == null) { // There is no previous hit object hit by the current key return 0.0; } double objectStrain = 0.5; // Add a base strain to all objects objectStrain += speedBonus(taikoCurrent.StartTime - keyPrevious.StartTime); return objectStrain; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing; using osu.Game.Rulesets.Taiko.Objects; namespace osu.Game.Rulesets.Taiko.Difficulty.Evaluators { public class StaminaEvaluator { /// <summary> /// Applies a speed bonus dependent on the time since the last hit performed using this key. /// </summary> /// <param name="interval">The interval between the current and previous note hit using the same key.</param> private static double speedBonus(double interval) { // Cap to 600bpm 1/4, 25ms note interval, 50ms key interval // This is a measure to prevent absurdly high speed maps giving infinity/negative values. interval = Math.Max(interval, 100); return 60 / interval; } /// <summary> /// Evaluates the minimum mechanical stamina required to play the current object. This is calculated using the /// maximum possible interval between two hits using the same key, by alternating 2 keys for each colour. /// </summary> public static double EvaluateDifficultyOf(DifficultyHitObject current) { if (current.BaseObject is not Hit) { return 0.0; } // Find the previous hit object hit by the current key, which is two notes of the same colour prior. TaikoDifficultyHitObject taikoCurrent = (TaikoDifficultyHitObject)current; TaikoDifficultyHitObject? keyPrevious = taikoCurrent.PreviousMono(1); if (keyPrevious == null) { // There is no previous hit object hit by the current key return 0.0; } double objectStrain = 0.5; // Add a base strain to all objects objectStrain += speedBonus(taikoCurrent.StartTime - keyPrevious.StartTime); return objectStrain; } } }
mit
C#
e514627a4b3643aa9320f65b0c4dc39dc597830a
Fix ReflectedWorkItemId to support blanks in project names as this is allowed (#689)
nkdAgility/vsts-sync-migration
src/MigrationTools.Clients.AzureDevops.ObjectModel/Clients/TfsReflectedWorkItemId.cs
src/MigrationTools.Clients.AzureDevops.ObjectModel/Clients/TfsReflectedWorkItemId.cs
using System; using System.Text.RegularExpressions; using MigrationTools.DataContracts; using Serilog; namespace MigrationTools.Clients { public class TfsReflectedWorkItemId : ReflectedWorkItemId { private Uri _Connection; private string _ProjectName; private string _WorkItemId; private static readonly Regex ReflectedIdRegex = new Regex(@"^(?<org>[\S ]+)\/(?<project>[\S ]+)\/_workitems\/edit\/(?<id>\d+)", RegexOptions.Compiled); public TfsReflectedWorkItemId(WorkItemData workItem) : base(workItem.Id) { if (workItem is null) { throw new ArgumentNullException(nameof(workItem)); } _WorkItemId = workItem.Id; _ProjectName = workItem.ProjectName; _Connection = workItem.ToWorkItem().Store.TeamProjectCollection.Uri; } public TfsReflectedWorkItemId(string ReflectedWorkItemId) : base(ReflectedWorkItemId) { if (ReflectedWorkItemId is null) { throw new ArgumentNullException(nameof(ReflectedWorkItemId)); } var match = ReflectedIdRegex.Match(ReflectedWorkItemId); if (match.Success) { _WorkItemId = match.Groups["id"].Value; _ProjectName = match.Groups["project"].Value; _Connection = new Uri(match.Groups["org"].Value); } else { Log.Error("TfsReflectedWorkItemId: Unable to match ReflectedWorkItemId({ReflectedWorkItemId}) as id! ", ReflectedWorkItemId); throw new Exception("Unable to Parse ReflectedWorkItemId. Check Log..."); } } public override string ToString() { return string.Format("{0}/{1}/_workitems/edit/{2}", _Connection.ToString().TrimEnd('/'), _ProjectName, _WorkItemId); } } }
using System; using System.Text.RegularExpressions; using MigrationTools.DataContracts; namespace MigrationTools.Clients { public class TfsReflectedWorkItemId : ReflectedWorkItemId { private Uri _Connection; private string _ProjectName; private string _WorkItemId; public TfsReflectedWorkItemId(WorkItemData workItem) : base(workItem.Id) { if (workItem is null) { throw new ArgumentNullException(nameof(workItem)); } _WorkItemId = workItem.Id; _ProjectName = workItem.ProjectName; _Connection = workItem.ToWorkItem().Store.TeamProjectCollection.Uri; } public TfsReflectedWorkItemId(string ReflectedWorkItemId) : base(ReflectedWorkItemId) { if (ReflectedWorkItemId is null) { throw new ArgumentNullException(nameof(ReflectedWorkItemId)); } var re = new Regex(@"^(?<org>\S+)\/(?<project>\S+)\/_workitems\/edit\/(?<id>\d+)"); var match = re.Match(ReflectedWorkItemId); if (match.Success) { _WorkItemId = match.Groups["id"].Value; _ProjectName = match.Groups["project"].Value; _Connection = new Uri(match.Groups["org"].Value); } } public override string ToString() { return string.Format("{0}/{1}/_workitems/edit/{2}", _Connection.ToString().TrimEnd('/'), _ProjectName, _WorkItemId); } } }
mit
C#
7fcc938fcb1acc481d58cfc0d98096d7a3410a1a
Enable configuration of Json Serializer
MultimediaSolutionsAg/ServiceBus
source/MMS.ServiceBus/Pipeline/NewtonsoftJsonMessageSerializer.cs
source/MMS.ServiceBus/Pipeline/NewtonsoftJsonMessageSerializer.cs
//------------------------------------------------------------------------------- // <copyright file="NewtonsoftJsonMessageSerializer.cs" company="MMS AG"> // Copyright (c) MMS AG, 2008-2015 // </copyright> //------------------------------------------------------------------------------- namespace MMS.ServiceBus.Pipeline { using System; using System.IO; using Newtonsoft.Json; public class NewtonsoftJsonMessageSerializer : IMessageSerializer { private readonly Func<JsonSerializerSettings> settings; public NewtonsoftJsonMessageSerializer() : this(() => null) { } public NewtonsoftJsonMessageSerializer(Func<JsonSerializerSettings> settings) { this.settings = settings; } public string ContentType { get { return "application/json"; } } public void Serialize(object message, Stream body) { var streamWriter = new StreamWriter(body); var writer = new JsonTextWriter(streamWriter); var serializer = JsonSerializer.Create(this.settings()); serializer.Serialize(writer, message); streamWriter.Flush(); body.Flush(); body.Position = 0; } public object Deserialize(Stream body, Type messageType) { var streamReader = new StreamReader(body); var reader = new JsonTextReader(streamReader); var serializer = JsonSerializer.Create(this.settings()); return serializer.Deserialize(reader, messageType); } } }
//------------------------------------------------------------------------------- // <copyright file="NewtonsoftJsonMessageSerializer.cs" company="MMS AG"> // Copyright (c) MMS AG, 2008-2015 // </copyright> //------------------------------------------------------------------------------- namespace MMS.ServiceBus.Pipeline { using System; using System.IO; using Newtonsoft.Json; public class NewtonsoftJsonMessageSerializer : IMessageSerializer { public string ContentType { get { return "application/json"; } } public void Serialize(object message, Stream body) { var streamWriter = new StreamWriter(body); var writer = new JsonTextWriter(streamWriter); var serializer = new JsonSerializer(); serializer.Serialize(writer, message); streamWriter.Flush(); body.Flush(); body.Position = 0; } public object Deserialize(Stream body, Type messageType) { var streamReader = new StreamReader(body); var reader = new JsonTextReader(streamReader); var serializer = new JsonSerializer(); return serializer.Deserialize(reader, messageType); } } }
apache-2.0
C#
d57116ddfa477f5fbc01e744e9fea8e6ae90ca13
Disable user overrides for FirstDayOfWeek tests (#30129)
wtgodbe/corefx,ericstj/corefx,mmitche/corefx,Jiayili1/corefx,ericstj/corefx,mmitche/corefx,wtgodbe/corefx,Jiayili1/corefx,ptoonen/corefx,wtgodbe/corefx,BrennanConroy/corefx,BrennanConroy/corefx,ericstj/corefx,ptoonen/corefx,ViktorHofer/corefx,Jiayili1/corefx,Jiayili1/corefx,ptoonen/corefx,ericstj/corefx,ptoonen/corefx,shimingsg/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,wtgodbe/corefx,mmitche/corefx,ptoonen/corefx,wtgodbe/corefx,ericstj/corefx,mmitche/corefx,shimingsg/corefx,BrennanConroy/corefx,mmitche/corefx,wtgodbe/corefx,Jiayili1/corefx,ViktorHofer/corefx,Jiayili1/corefx,shimingsg/corefx,ericstj/corefx,ViktorHofer/corefx,mmitche/corefx,wtgodbe/corefx,mmitche/corefx,ptoonen/corefx,Jiayili1/corefx,ViktorHofer/corefx,shimingsg/corefx,ptoonen/corefx
src/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoFirstDayOfWeek.cs
src/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoFirstDayOfWeek.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.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class DateTimeFormatInfoFirstDayOfWeek { public static IEnumerable<object[]> FirstDayOfWeek_TestData() { yield return new object[] { DateTimeFormatInfo.InvariantInfo, DayOfWeek.Sunday }; yield return new object[] { new CultureInfo("en-US", false).DateTimeFormat, DayOfWeek.Sunday }; yield return new object[] { new CultureInfo("fr-FR", false).DateTimeFormat, DayOfWeek.Monday }; } [Theory] [MemberData(nameof(FirstDayOfWeek_TestData))] public void FirstDayOfWeek(DateTimeFormatInfo format, DayOfWeek expected) { Assert.Equal(expected, format.FirstDayOfWeek); } [Theory] [InlineData(DayOfWeek.Sunday)] [InlineData(DayOfWeek.Monday)] [InlineData(DayOfWeek.Tuesday)] [InlineData(DayOfWeek.Wednesday)] [InlineData(DayOfWeek.Thursday)] [InlineData(DayOfWeek.Friday)] [InlineData(DayOfWeek.Saturday)] public void FirstDayOfWeek_Set(DayOfWeek newFirstDayOfWeek) { var format = new DateTimeFormatInfo(); format.FirstDayOfWeek = newFirstDayOfWeek; Assert.Equal(newFirstDayOfWeek, format.FirstDayOfWeek); } [Theory] [InlineData(DayOfWeek.Sunday - 1)] [InlineData(DayOfWeek.Saturday + 1)] public void FirstDayOfWeek_Set_Invalid_ThrowsArgumentOutOfRangeException(DayOfWeek value) { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new DateTimeFormatInfo().FirstDayOfWeek = value); } [Fact] public void FirstDayOfWeek_Set_ReadOnly_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => DateTimeFormatInfo.InvariantInfo.FirstDayOfWeek = DayOfWeek.Wednesday); // DateTimeFormatInfo.InvariantInfo is read only } } }
// 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.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class DateTimeFormatInfoFirstDayOfWeek { public static IEnumerable<object[]> FirstDayOfWeek_TestData() { yield return new object[] { DateTimeFormatInfo.InvariantInfo, DayOfWeek.Sunday }; yield return new object[] { new CultureInfo("en-US").DateTimeFormat, DayOfWeek.Sunday }; yield return new object[] { new CultureInfo("fr-FR").DateTimeFormat, DayOfWeek.Monday }; } [Theory] [MemberData(nameof(FirstDayOfWeek_TestData))] public void FirstDayOfWeek(DateTimeFormatInfo format, DayOfWeek expected) { Assert.Equal(expected, format.FirstDayOfWeek); } [Theory] [InlineData(DayOfWeek.Sunday)] [InlineData(DayOfWeek.Monday)] [InlineData(DayOfWeek.Tuesday)] [InlineData(DayOfWeek.Wednesday)] [InlineData(DayOfWeek.Thursday)] [InlineData(DayOfWeek.Friday)] [InlineData(DayOfWeek.Saturday)] public void FirstDayOfWeek_Set(DayOfWeek newFirstDayOfWeek) { var format = new DateTimeFormatInfo(); format.FirstDayOfWeek = newFirstDayOfWeek; Assert.Equal(newFirstDayOfWeek, format.FirstDayOfWeek); } [Theory] [InlineData(DayOfWeek.Sunday - 1)] [InlineData(DayOfWeek.Saturday + 1)] public void FirstDayOfWeek_Set_Invalid_ThrowsArgumentOutOfRangeException(DayOfWeek value) { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new DateTimeFormatInfo().FirstDayOfWeek = value); } [Fact] public void FirstDayOfWeek_Set_ReadOnly_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => DateTimeFormatInfo.InvariantInfo.FirstDayOfWeek = DayOfWeek.Wednesday); // DateTimeFormatInfo.InvariantInfo is read only } } }
mit
C#
bfadac89f67e90da7bd1273a4d1ba124675c4ebd
修复一个逻辑错误。 :ocean:
Zongsoft/Zongsoft.Plugins
src/Terminals/Workbench.cs
src/Terminals/Workbench.cs
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2010-2013 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.Plugins. * * Zongsoft.Plugins 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. * * Zongsoft.Plugins 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. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.Plugins; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using Zongsoft.Plugins; using Zongsoft.Services; namespace Zongsoft.Terminals.Plugins { public class Workbench : Zongsoft.Plugins.WorkbenchBase { #region 成员字段 private TerminalCommandExecutor _executor; #endregion #region 构造函数 public Workbench(PluginApplicationContext applicationContext) : base(applicationContext) { } #endregion #region 公共属性 public TerminalCommandExecutor Executor { get { return _executor ?? CommandExecutor.Default as TerminalCommandExecutor; } set { _executor = value; } } #endregion #region 打开方法 protected override void OnStart(string[] args) { var executor = this.Executor; if(executor == null) throw new InvalidOperationException("The command executor is null."); //调用基类同名方法 base.OnStart(args); //激发“Opened”事件 this.OnOpened(EventArgs.Empty); //启动命令运行器 executor.Run(); //关闭命令执行器 this.Close(); } #endregion } }
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2010-2013 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.Plugins. * * Zongsoft.Plugins 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. * * Zongsoft.Plugins 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. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.Plugins; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using Zongsoft.Plugins; using Zongsoft.Services; namespace Zongsoft.Terminals.Plugins { public class Workbench : Zongsoft.Plugins.WorkbenchBase { #region 成员字段 private TerminalCommandExecutor _executor; #endregion #region 构造函数 public Workbench(PluginApplicationContext applicationContext) : base(applicationContext) { _executor = CommandExecutor.Default as TerminalCommandExecutor; } #endregion #region 公共属性 public TerminalCommandExecutor Executor { get { return _executor; } } #endregion #region 打开方法 protected override void OnStart(string[] args) { var executor = this.Executor; if(executor == null) throw new InvalidOperationException("The command executor is null."); //调用基类同名方法 base.OnStart(args); //激发“Opened”事件 this.OnOpened(EventArgs.Empty); //启动命令运行器 executor.Run(); //关闭命令执行器 this.Close(); } #endregion } }
lgpl-2.1
C#
b8e968f930850c7c0e5b901f5397b1de75b46e66
Update index.cshtml
KovalNikita/apmathcloud
SITE/index.cshtml
SITE/index.cshtml
@{ var txt = DateTime.Now; // C# int m = 1; int b = 1; double t_0 = 1; double t_end = 100; double z_0 = 0; double z_d = 10; double t1 = t_0; double t2 = t_end; double h = 0.1; double width = 0.05; } <html> <head> <!--Load the AJAX API--> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1.0', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); // Callback that creates and populates a data table, // instantiates the pie chart, passes in the data and // draws it. function drawChart() { // Create the data table. var data = new google.visualization.DataTable(); data.addColumn('string', 'Topping'); data.addColumn('number', 'Slices'); data.addRows([ ['Mushrooms', 3], ['Onions', 1], ['Olives', 1], ['Zucchini', 1], ['Pepperoni', 2] ]); // Set chart options var options = {'title':'How Much Pizza I Ate Last Night', 'width':400, 'height':300}; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <!--Div that will hold the pie chart--> <div id="chart_div"></div> </body> </html>
@{ var txt = DateTime.Now; // C# int m = 1; int b = 1; double t_0 = 1; double t_end = 100; double z_0 = 0; double z_d = 10; double t1 = t_0; double t2 = t_end; double h = 0.1; double width = 0.05; } <html> <body> <p>The dateTime is @txt</p> </body> </html>
mit
C#
96a1946979e836502eca23991396a34a02f38549
Allow context to be null when querying for initial data.
quartz-software/kephas,quartz-software/kephas
src/Kephas.Data.InMemory/ContextExtensions.cs
src/Kephas.Data.InMemory/ContextExtensions.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContextExtensions.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Implements the context extensions class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.InMemory { using System.Collections.Generic; using Kephas.Data.Capabilities; using Kephas.Diagnostics.Contracts; using Kephas.Services; /// <summary> /// Extension methods for <see cref="IContext"/>. /// </summary> public static class ContextExtensions { /// <summary> /// Gets the initial data. /// </summary> /// <param name="context">The context to act on.</param> /// <returns> /// An enumeration of entity information. /// </returns> public static IEnumerable<IEntityInfo> GetInitialData(this IContext context) { return context?[nameof(InMemoryDataContextConfiguration.InitialData)] as IEnumerable<IEntityInfo>; } /// <summary> /// Sets the initial data. /// </summary> /// <param name="context">The context to act on.</param> /// <param name="initialData">The initial data.</param> public static void SetInitialData(this IContext context, IEnumerable<IEntityInfo> initialData) { Requires.NotNull(context, nameof(context)); context[nameof(InMemoryDataContextConfiguration.InitialData)] = initialData; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContextExtensions.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Implements the context extensions class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.InMemory { using System.Collections.Generic; using Kephas.Data.Capabilities; using Kephas.Diagnostics.Contracts; using Kephas.Services; /// <summary> /// Extension methods for <see cref="IContext"/>. /// </summary> public static class ContextExtensions { /// <summary> /// Gets the initial data. /// </summary> /// <param name="context">The context to act on.</param> /// <returns> /// An enumeration of entity information. /// </returns> public static IEnumerable<IEntityInfo> GetInitialData(this IContext context) { Requires.NotNull(context, nameof(context)); return context[nameof(InMemoryDataContextConfiguration.InitialData)] as IEnumerable<IEntityInfo>; } /// <summary> /// Sets the initial data. /// </summary> /// <param name="context">The context to act on.</param> /// <param name="initialData">The initial data.</param> public static void SetInitialData(this IContext context, IEnumerable<IEntityInfo> initialData) { Requires.NotNull(context, nameof(context)); context[nameof(InMemoryDataContextConfiguration.InitialData)] = initialData; } } }
mit
C#
7f3b805f1afc3f5a9dc9185261fcdd29e74f8b13
change title text
joeaudette/cloudscribe.Web.Pagination,joeaudette/cloudscribe.Web.Pagination,joeaudette/cloudscribe.Web.Pagination
src/PagingDemo.WebPages/Pages/FakePage.cshtml
src/PagingDemo.WebPages/Pages/FakePage.cshtml
@page @model PagingDemo.WebPages.Pages.FakePageModel @{ int.TryParse(Request.Query["p"],out var p); } <div> <h1>this page test navigate from the PageTagHelper</h1> <a asp-page="./Index" class="btn btn-primary">go back</a> <a asp-page="./Index" asp-route-id="@p" asp-route-p="@p" class="btn btn-primary">go back with Id=@p and p=@p</a> </div> <div class="pre-scrollable"> @Json.Serialize(ViewContext.ActionDescriptor.RouteValues) <hr /> @Json.Serialize(ViewContext.RouteData) </div>
@page @model PagingDemo.WebPages.Pages.FakePageModel @{ int.TryParse(Request.Query["p"],out var p); } <div> <h1>this page test paginate to another page</h1> <a asp-page="./Index" class="btn btn-primary">go back</a> <a asp-page="./Index" asp-route-id="@p" asp-route-p="@p" class="btn btn-primary">go back with Id=@p and p=@p</a> </div> <div class="pre-scrollable"> @Json.Serialize(ViewContext.ActionDescriptor.RouteValues) <hr /> @Json.Serialize(ViewContext.RouteData) </div>
apache-2.0
C#
910eccbb8a02d0146502182f42ae54e027d14be8
Split stack trace
khellang/Middleware,khellang/Middleware
src/ProblemDetails/ExceptionProblemDetails.cs
src/ProblemDetails/ExceptionProblemDetails.cs
using System; using Microsoft.AspNetCore.Http; namespace Hellang.Middleware.ProblemDetails { internal class ExceptionProblemDetails : StatusCodeProblemDetails { private static readonly string[] LineSeparators = { Environment.NewLine }; public ExceptionProblemDetails(Exception error) : base(StatusCodes.Status500InternalServerError) { Detail = error.Message; Instance = GetHelpLink(error); StackTrace = GetStackTraceLines(error.StackTrace); Title = error.GetType().FullName; } public string[] StackTrace { get; set; } private static string GetHelpLink(Exception error) { var link = error.HelpLink; if (string.IsNullOrEmpty(link)) { return null; } if (Uri.TryCreate(link, UriKind.Absolute, out var result)) { return result.ToString(); } return null; } private static string[] GetStackTraceLines(string stackTrace) { if (string.IsNullOrEmpty(stackTrace)) { return null; } return stackTrace.Split(LineSeparators, StringSplitOptions.RemoveEmptyEntries); } } }
using System; using Microsoft.AspNetCore.Http; namespace Hellang.Middleware.ProblemDetails { internal class ExceptionProblemDetails : StatusCodeProblemDetails { public ExceptionProblemDetails(Exception error) : base(StatusCodes.Status500InternalServerError) { Detail = error.Message; Instance = GetHelpLink(error); StackTrace = error.StackTrace; Title = error.GetType().FullName; } public string StackTrace { get; set; } private static string GetHelpLink(Exception error) { var link = error.HelpLink; if (string.IsNullOrEmpty(link)) { return null; } if (Uri.TryCreate(link, UriKind.Absolute, out var result)) { return result.ToString(); } return null; } } }
mit
C#
fd677047f4cd277dce78939d150591376712e3c2
Change GetService call to GetRequiredService
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNet.Security.DataProtection/DefaultDataProtectionProvider.cs
src/Microsoft.AspNet.Security.DataProtection/DefaultDataProtectionProvider.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Security.DataProtection.KeyManagement; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection.Fallback; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Security.DataProtection { public class DefaultDataProtectionProvider : IDataProtectionProvider { private readonly IDataProtectionProvider _innerProvider; public DefaultDataProtectionProvider() { // use DI defaults var collection = new ServiceCollection(); var defaultServices = DataProtectionServices.GetDefaultServices(); collection.Add(defaultServices); var serviceProvider = collection.BuildServiceProvider(); _innerProvider = serviceProvider.GetRequiredService<IDataProtectionProvider>(); } public DefaultDataProtectionProvider( [NotNull] IOptions<DataProtectionOptions> optionsAccessor, [NotNull] IKeyManager keyManager) { KeyRingBasedDataProtectionProvider rootProvider = new KeyRingBasedDataProtectionProvider(new KeyRingProvider(keyManager)); var options = optionsAccessor.Options; _innerProvider = (!String.IsNullOrEmpty(options.ApplicationDiscriminator)) ? (IDataProtectionProvider)rootProvider.CreateProtector(options.ApplicationDiscriminator) : rootProvider; } public IDataProtector CreateProtector([NotNull] string purpose) { return _innerProvider.CreateProtector(purpose); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Security.DataProtection.KeyManagement; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection.Fallback; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Security.DataProtection { public class DefaultDataProtectionProvider : IDataProtectionProvider { private readonly IDataProtectionProvider _innerProvider; public DefaultDataProtectionProvider() { // use DI defaults var collection = new ServiceCollection(); var defaultServices = DataProtectionServices.GetDefaultServices(); collection.Add(defaultServices); var serviceProvider = collection.BuildServiceProvider(); _innerProvider = (IDataProtectionProvider)serviceProvider.GetService(typeof(IDataProtectionProvider)); CryptoUtil.Assert(_innerProvider != null, "_innerProvider != null"); } public DefaultDataProtectionProvider( [NotNull] IOptions<DataProtectionOptions> optionsAccessor, [NotNull] IKeyManager keyManager) { KeyRingBasedDataProtectionProvider rootProvider = new KeyRingBasedDataProtectionProvider(new KeyRingProvider(keyManager)); var options = optionsAccessor.Options; _innerProvider = (!String.IsNullOrEmpty(options.ApplicationDiscriminator)) ? (IDataProtectionProvider)rootProvider.CreateProtector(options.ApplicationDiscriminator) : rootProvider; } public IDataProtector CreateProtector([NotNull] string purpose) { return _innerProvider.CreateProtector(purpose); } } }
apache-2.0
C#
7dfe171869ed7b0596c30620f55ea834636628c2
Fix rebase error
johnneijzen/osu,smoogipoo/osu,naoey/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,peppy/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,ZLima12/osu,naoey/osu,NeoAdonis/osu,johnneijzen/osu,ppy/osu,2yangk23/osu,EVAST9919/osu,naoey/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,EVAST9919/osu,DrabWeb/osu,DrabWeb/osu,DrabWeb/osu
osu.Game.Tests/Visual/TestCaseEditorComposeTimeline.cs
osu.Game.Tests/Visual/TestCaseEditorComposeTimeline.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 NUnit.Framework; using OpenTK; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Overlays; using osu.Game.Screens.Edit.Screens.Compose.Timeline; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseEditorComposeTimeline : EditorClockTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(TimelineArea), typeof(Timeline), typeof(TimelineButton), typeof(CentreMarker) }; public TestCaseEditorComposeTimeline() { Children = new Drawable[] { new MusicController { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, State = Visibility.Visible }, new TimelineArea { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Size = new Vector2(0.8f, 100) } }; } } }
// 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 NUnit.Framework; using OpenTK; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Overlays; using osu.Game.Screens.Edit.Screens.Compose.Timeline; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseEditorComposeTimeline : EditorClockTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(TimelineArea), typeof(Timeline), typeof(BeatmapWaveformGraph), typeof(TimelineButton), typeof(CentreMarker) }; public TestCaseEditorComposeTimeline() { Children = new Drawable[] { new MusicController { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, State = Visibility.Visible }, new TimelineArea { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Size = new Vector2(0.8f, 100) } }; } } }
mit
C#
771acb0441b1d08675d3024ad45c927f32b9ba13
Make some fields readonly
toehead2001/pdn-barcode
Barcode/BarcodeSurface.cs
Barcode/BarcodeSurface.cs
// Paint.NET Effect Plugin Name: Barcode // Author: Michael J. Sepcot // Addional Modifications: toe_head201 using System; using System.Drawing; using PaintDotNet; namespace Barcode { internal class BarcodeSurface { private readonly Rectangle rect; private readonly ColorBgra[,] surface; internal int Width => rect.Width; internal int Height => rect.Height; internal ColorBgra this[int x, int y] { get { if (rect.Contains(x, y)) { return surface[this.ConvertX(x), this.ConvertY(y)]; } else { throw new ArgumentOutOfRangeException("(x,y)", new Point(x, y), "Coordinates out of bounds, bounds=" + rect.ToString()); } } set { if (this.rect.Contains(x, y)) { surface[this.ConvertX(x), this.ConvertY(y)] = value; } } } internal BarcodeSurface(Rectangle rect) { this.rect = rect; surface = new ColorBgra[rect.Width, rect.Height]; } private int ConvertX(int x) { return (x - rect.Left); } private int ConvertY(int y) { return (y - rect.Top); } } }
// Paint.NET Effect Plugin Name: Barcode // Author: Michael J. Sepcot // Addional Modifications: toe_head201 using System; using System.Drawing; using PaintDotNet; namespace Barcode { internal class BarcodeSurface { private Rectangle rect; private ColorBgra[,] surface; internal int Width => rect.Width; internal int Height => rect.Height; internal ColorBgra this[int x, int y] { get { if (rect.Contains(x, y)) { return surface[this.ConvertX(x), this.ConvertY(y)]; } else { throw new ArgumentOutOfRangeException("(x,y)", new Point(x, y), "Coordinates out of bounds, bounds=" + rect.ToString()); } } set { if (this.rect.Contains(x, y)) { surface[this.ConvertX(x), this.ConvertY(y)] = value; } } } internal BarcodeSurface(Rectangle rect) { this.rect = rect; surface = new ColorBgra[rect.Width, rect.Height]; } private int ConvertX(int x) { return (x - rect.Left); } private int ConvertY(int y) { return (y - rect.Top); } } }
mit
C#
22d108c076988dc2291fc78776e0473e0c457d91
Remove unused imports
ilantukh/ignite,andrey-kuznetsov/ignite,wmz7year/ignite,samaitra/ignite,samaitra/ignite,ntikhonov/ignite,BiryukovVA/ignite,vadopolski/ignite,samaitra/ignite,StalkXT/ignite,shroman/ignite,WilliamDo/ignite,chandresh-pancholi/ignite,voipp/ignite,sk0x50/ignite,ascherbakoff/ignite,NSAmelchev/ignite,xtern/ignite,ascherbakoff/ignite,daradurvs/ignite,irudyak/ignite,andrey-kuznetsov/ignite,amirakhmedov/ignite,ilantukh/ignite,alexzaitzev/ignite,daradurvs/ignite,endian675/ignite,NSAmelchev/ignite,ntikhonov/ignite,NSAmelchev/ignite,xtern/ignite,psadusumilli/ignite,ilantukh/ignite,apache/ignite,voipp/ignite,samaitra/ignite,wmz7year/ignite,dream-x/ignite,voipp/ignite,ptupitsyn/ignite,ntikhonov/ignite,BiryukovVA/ignite,daradurvs/ignite,ptupitsyn/ignite,endian675/ignite,daradurvs/ignite,dream-x/ignite,amirakhmedov/ignite,chandresh-pancholi/ignite,andrey-kuznetsov/ignite,a1vanov/ignite,voipp/ignite,dream-x/ignite,ascherbakoff/ignite,SomeFire/ignite,shroman/ignite,shroman/ignite,ptupitsyn/ignite,StalkXT/ignite,vladisav/ignite,ptupitsyn/ignite,NSAmelchev/ignite,vladisav/ignite,psadusumilli/ignite,voipp/ignite,endian675/ignite,BiryukovVA/ignite,ptupitsyn/ignite,SomeFire/ignite,ntikhonov/ignite,a1vanov/ignite,dream-x/ignite,vladisav/ignite,ptupitsyn/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,ntikhonov/ignite,sk0x50/ignite,andrey-kuznetsov/ignite,WilliamDo/ignite,BiryukovVA/ignite,ascherbakoff/ignite,dream-x/ignite,SomeFire/ignite,StalkXT/ignite,samaitra/ignite,samaitra/ignite,andrey-kuznetsov/ignite,SharplEr/ignite,StalkXT/ignite,StalkXT/ignite,chandresh-pancholi/ignite,StalkXT/ignite,WilliamDo/ignite,shroman/ignite,irudyak/ignite,sk0x50/ignite,irudyak/ignite,amirakhmedov/ignite,SomeFire/ignite,SomeFire/ignite,ascherbakoff/ignite,shroman/ignite,vladisav/ignite,nizhikov/ignite,shroman/ignite,dream-x/ignite,WilliamDo/ignite,ilantukh/ignite,vladisav/ignite,ilantukh/ignite,BiryukovVA/ignite,BiryukovVA/ignite,endian675/ignite,SharplEr/ignite,NSAmelchev/ignite,WilliamDo/ignite,daradurvs/ignite,alexzaitzev/ignite,xtern/ignite,WilliamDo/ignite,ilantukh/ignite,chandresh-pancholi/ignite,ptupitsyn/ignite,daradurvs/ignite,amirakhmedov/ignite,endian675/ignite,irudyak/ignite,ilantukh/ignite,wmz7year/ignite,ptupitsyn/ignite,SomeFire/ignite,StalkXT/ignite,alexzaitzev/ignite,nizhikov/ignite,WilliamDo/ignite,amirakhmedov/ignite,a1vanov/ignite,endian675/ignite,daradurvs/ignite,SharplEr/ignite,alexzaitzev/ignite,SharplEr/ignite,ilantukh/ignite,andrey-kuznetsov/ignite,vladisav/ignite,SharplEr/ignite,apache/ignite,ntikhonov/ignite,SomeFire/ignite,StalkXT/ignite,voipp/ignite,wmz7year/ignite,xtern/ignite,shroman/ignite,vadopolski/ignite,xtern/ignite,psadusumilli/ignite,ascherbakoff/ignite,amirakhmedov/ignite,sk0x50/ignite,SharplEr/ignite,wmz7year/ignite,endian675/ignite,nizhikov/ignite,a1vanov/ignite,BiryukovVA/ignite,xtern/ignite,ntikhonov/ignite,NSAmelchev/ignite,amirakhmedov/ignite,shroman/ignite,ptupitsyn/ignite,apache/ignite,SomeFire/ignite,shroman/ignite,sk0x50/ignite,a1vanov/ignite,voipp/ignite,SharplEr/ignite,amirakhmedov/ignite,chandresh-pancholi/ignite,voipp/ignite,ptupitsyn/ignite,alexzaitzev/ignite,dream-x/ignite,SomeFire/ignite,BiryukovVA/ignite,psadusumilli/ignite,endian675/ignite,alexzaitzev/ignite,sk0x50/ignite,xtern/ignite,alexzaitzev/ignite,vadopolski/ignite,nizhikov/ignite,xtern/ignite,psadusumilli/ignite,sk0x50/ignite,xtern/ignite,apache/ignite,vladisav/ignite,alexzaitzev/ignite,amirakhmedov/ignite,apache/ignite,ascherbakoff/ignite,SomeFire/ignite,SharplEr/ignite,daradurvs/ignite,vladisav/ignite,daradurvs/ignite,BiryukovVA/ignite,irudyak/ignite,NSAmelchev/ignite,samaitra/ignite,apache/ignite,sk0x50/ignite,apache/ignite,ilantukh/ignite,irudyak/ignite,psadusumilli/ignite,shroman/ignite,wmz7year/ignite,SharplEr/ignite,ntikhonov/ignite,apache/ignite,samaitra/ignite,andrey-kuznetsov/ignite,samaitra/ignite,irudyak/ignite,BiryukovVA/ignite,chandresh-pancholi/ignite,wmz7year/ignite,vadopolski/ignite,sk0x50/ignite,nizhikov/ignite,andrey-kuznetsov/ignite,apache/ignite,dream-x/ignite,NSAmelchev/ignite,daradurvs/ignite,nizhikov/ignite,irudyak/ignite,nizhikov/ignite,StalkXT/ignite,a1vanov/ignite,chandresh-pancholi/ignite,andrey-kuznetsov/ignite,a1vanov/ignite,ascherbakoff/ignite,alexzaitzev/ignite,psadusumilli/ignite,WilliamDo/ignite,ilantukh/ignite,chandresh-pancholi/ignite,psadusumilli/ignite,vadopolski/ignite,vadopolski/ignite,samaitra/ignite,andrey-kuznetsov/ignite,a1vanov/ignite,irudyak/ignite,NSAmelchev/ignite,vadopolski/ignite,nizhikov/ignite,voipp/ignite,nizhikov/ignite,vadopolski/ignite,wmz7year/ignite
modules/platforms/dotnet/Apache.Ignite.Linq/Impl/QueryData.cs
modules/platforms/dotnet/Apache.Ignite.Linq/Impl/QueryData.cs
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Linq.Impl { using System.Collections.Generic; using System.Diagnostics; using System.Linq; /// <summary> /// Query data holder. /// </summary> internal class QueryData { /** */ private readonly ICollection<object> _parameters; /** */ private readonly string _queryText; /// <summary> /// Initializes a new instance of the <see cref="QueryData"/> class. /// </summary> /// <param name="queryText">The query text.</param> /// <param name="parameters">The parameters.</param> public QueryData(string queryText, ICollection<object> parameters) { Debug.Assert(queryText != null); Debug.Assert(parameters != null); _queryText = queryText; _parameters = parameters; } /// <summary> /// Gets the parameters. /// </summary> public ICollection<object> Parameters { get { return _parameters; } } /// <summary> /// Gets the query text. /// </summary> public string QueryText { get { return _queryText; } } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { return string.Format("SQL Query [Text={0}, Parameters={1}]", QueryText, string.Join(", ", Parameters.Select(x => x == null ? "null" : x.ToString()))); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Linq.Impl { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; /// <summary> /// Query data holder. /// </summary> internal class QueryData { /** */ private readonly ICollection<object> _parameters; /** */ private readonly string _queryText; /// <summary> /// Initializes a new instance of the <see cref="QueryData"/> class. /// </summary> /// <param name="queryText">The query text.</param> /// <param name="parameters">The parameters.</param> public QueryData(string queryText, ICollection<object> parameters) { Debug.Assert(queryText != null); Debug.Assert(parameters != null); _queryText = queryText; _parameters = parameters; } /// <summary> /// Gets the parameters. /// </summary> public ICollection<object> Parameters { get { return _parameters; } } /// <summary> /// Gets the query text. /// </summary> public string QueryText { get { return _queryText; } } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { return string.Format("SQL Query [Text={0}, Parameters={1}]", QueryText, string.Join(", ", Parameters.Select(x => x == null ? "null" : x.ToString()))); } } }
apache-2.0
C#
f079ebe857ebf708c5aae6ee0a7c102ea4c9c5f5
Simplify beatmap lookup to use a single endpoint
peppy/osu-new,smoogipoo/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,2yangk23/osu,smoogipooo/osu,EVAST9919/osu,johnneijzen/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,UselessToucan/osu,peppy/osu
osu.Game/Online/API/Requests/GetBeatmapRequest.cs
osu.Game/Online/API/Requests/GetBeatmapRequest.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.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly BeatmapInfo beatmap; public GetBeatmapRequest(BeatmapInfo beatmap) { this.beatmap = beatmap; } protected override string Target => $@"beatmaps/lookup?id={beatmap.OnlineBeatmapID}&checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path)}"; } }
// 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.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly BeatmapInfo beatmap; private string lookupString => beatmap.OnlineBeatmapID > 0 ? beatmap.OnlineBeatmapID.ToString() : $@"lookup?checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path)}"; public GetBeatmapRequest(BeatmapInfo beatmap) { this.beatmap = beatmap; } protected override string Target => $@"beatmaps/{lookupString}"; } }
mit
C#
22e86d14e1d2e3365a13aff39b3376e541e30503
fix integration project
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
src/Integration/Shared/MySaga.cs
src/Integration/Shared/MySaga.cs
using System; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Logging; using NServiceBus.Persistence.Sql; [SqlSaga( correlationProperty: nameof(SagaData.MySagaId) )] public class MySaga : SqlSaga<MySaga.SagaData>, IAmStartedByMessages<StartSagaMessage>, IHandleMessages<CompleteSagaMessage>, IHandleTimeouts<SagaTimoutMessage> { static ILog logger = LogManager.GetLogger(typeof(MySaga)); protected override void ConfigureMapping(MessagePropertyMapper<SagaData> mapper) { mapper.MapMessage<StartSagaMessage>(m => m.MySagaId); mapper.MapMessage<CompleteSagaMessage>(m => m.MySagaId); } public Task Handle(StartSagaMessage message, IMessageHandlerContext context) { Data.MySagaId = message.MySagaId; logger.Info($"Start Saga. Data.MySagaId:{Data.MySagaId}. Message.MySagaId:{message.MySagaId}"); var completeSagaMessage = new CompleteSagaMessage { MySagaId = Data.MySagaId }; return context.SendLocal(completeSagaMessage); } public Task Handle(CompleteSagaMessage message, IMessageHandlerContext context) { logger.Info($"Completed Saga. Data.MySagaId:{Data.MySagaId}. Message.MySagaId:{message.MySagaId}"); var timeout = new SagaTimoutMessage { Property = "PropertyValue" }; return RequestTimeout(context, TimeSpan.FromSeconds(1), timeout); } public Task Timeout(SagaTimoutMessage state, IMessageHandlerContext context) { logger.Info($"Timeout {state.Property}"); MarkAsComplete(); return Task.FromResult(0); } public class SagaData : ContainSagaData { public Guid MySagaId { get; set; } } }
using System; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Logging; using NServiceBus.Persistence.Sql; [SqlSaga( correlationProperty: nameof(SagaData.MySagaId) )] public class MySaga : Saga<MySaga.SagaData>, IAmStartedByMessages<StartSagaMessage>, IHandleMessages<CompleteSagaMessage>, IHandleTimeouts<SagaTimoutMessage> { static ILog logger = LogManager.GetLogger(typeof(MySaga)); protected override void ConfigureHowToFindSaga(SagaPropertyMapper<SagaData> mapper) { mapper.ConfigureMapping<StartSagaMessage>(m => m.MySagaId) .ToSaga(data => data.MySagaId); mapper.ConfigureMapping<CompleteSagaMessage>(m => m.MySagaId) .ToSaga(data => data.MySagaId); } public Task Handle(StartSagaMessage message, IMessageHandlerContext context) { Data.MySagaId = message.MySagaId; logger.Info($"Start Saga. Data.MySagaId:{Data.MySagaId}. Message.MySagaId:{message.MySagaId}"); var completeSagaMessage = new CompleteSagaMessage { MySagaId = Data.MySagaId }; return context.SendLocal(completeSagaMessage); } public Task Handle(CompleteSagaMessage message, IMessageHandlerContext context) { logger.Info($"Completed Saga. Data.MySagaId:{Data.MySagaId}. Message.MySagaId:{message.MySagaId}"); var timeout = new SagaTimoutMessage { Property = "PropertyValue" }; return RequestTimeout(context, TimeSpan.FromSeconds(1), timeout); } public Task Timeout(SagaTimoutMessage state, IMessageHandlerContext context) { logger.Info($"Timeout {state.Property}"); MarkAsComplete(); return Task.FromResult(0); } public class SagaData : ContainSagaData { public Guid MySagaId { get; set; } } }
mit
C#
84b91c25d437f8185be1b94338f5ad495d068825
Change Enumeration conversion to implicit
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.CodeGeneration/Generators/EnumerationGenerator.cs
source/Nuke.CodeGeneration/Generators/EnumerationGenerator.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using System.Text; using Nuke.CodeGeneration.Model; using Nuke.CodeGeneration.Writers; namespace Nuke.CodeGeneration.Generators { public static class EnumerationGenerator { public static void Run(Enumeration enumeration, ToolWriter toolWriter) { var values = enumeration.Values.ToArray(); for (var i = 0; i + 1 < values.Length; i++) values[i] += ","; string GetIdentifier(string value) => value.Aggregate( new StringBuilder(!char.IsLetter(value[index: 0]) ? "_" : string.Empty), (sb, c) => sb.Append(char.IsLetterOrDigit(c) ? c : '_'), sb => sb.ToString()); toolWriter .WriteLine($"#region {enumeration.Name}") .WriteSummary(enumeration) .WriteLine("[PublicAPI]") .WriteLine("[Serializable]") .WriteObsoleteAttributeWhenObsolete(enumeration) .WriteLine("[ExcludeFromCodeCoverage]") .WriteLine($"[TypeConverter(typeof(TypeConverter<{enumeration.Name}>))]") .WriteLine($"public partial class {enumeration.Name} : Enumeration") .WriteBlock(w => w .ForEach(enumeration.Values, x => w.WriteLine( $"public static {enumeration.Name} {GetIdentifier(x).EscapeProperty()} = ({enumeration.Name}) {x.DoubleQuote()};")) .WriteLine($"public static implicit operator {enumeration.Name}(string value)") .WriteBlock(w2 => w2 .WriteLine($"return new {enumeration.Name} {{ Value = value }};"))) .WriteLine("#endregion"); } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using System.Text; using Nuke.CodeGeneration.Model; using Nuke.CodeGeneration.Writers; namespace Nuke.CodeGeneration.Generators { public static class EnumerationGenerator { public static void Run(Enumeration enumeration, ToolWriter toolWriter) { var values = enumeration.Values.ToArray(); for (var i = 0; i + 1 < values.Length; i++) values[i] += ","; string GetIdentifier(string value) => value.Aggregate( new StringBuilder(!char.IsLetter(value[index: 0]) ? "_" : string.Empty), (sb, c) => sb.Append(char.IsLetterOrDigit(c) ? c : '_'), sb => sb.ToString()); toolWriter .WriteLine($"#region {enumeration.Name}") .WriteSummary(enumeration) .WriteLine("[PublicAPI]") .WriteLine("[Serializable]") .WriteObsoleteAttributeWhenObsolete(enumeration) .WriteLine("[ExcludeFromCodeCoverage]") .WriteLine($"[TypeConverter(typeof(TypeConverter<{enumeration.Name}>))]") .WriteLine($"public partial class {enumeration.Name} : Enumeration") .WriteBlock(w => w .ForEach(enumeration.Values, x => w.WriteLine( $"public static {enumeration.Name} {GetIdentifier(x).EscapeProperty()} = ({enumeration.Name}) {x.DoubleQuote()};")) .WriteLine($"public static explicit operator {enumeration.Name}(string value)") .WriteBlock(w2 => w2 .WriteLine($"return new {enumeration.Name} {{ Value = value }};"))) .WriteLine("#endregion"); } } }
mit
C#
442342e3880cbac186cacce7f36c433c0a225d60
Make parameters nullable (#13185)
umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS
src/Umbraco.Infrastructure/Examine/MemberValueSetValidator.cs
src/Umbraco.Infrastructure/Examine/MemberValueSetValidator.cs
namespace Umbraco.Cms.Infrastructure.Examine; public class MemberValueSetValidator : ValueSetValidator { /// <summary> /// By default these are the member fields we index /// </summary> public static readonly string[] DefaultMemberIndexFields = { "id", UmbracoExamineFieldNames.NodeNameFieldName, "updateDate", "loginName", "email", UmbracoExamineFieldNames.NodeKeyFieldName, }; private static readonly IEnumerable<string> _validCategories = new[] { IndexTypes.Member }; public MemberValueSetValidator() : base(null, null, DefaultMemberIndexFields, null) { } public MemberValueSetValidator(IEnumerable<string>? includeItemTypes, IEnumerable<string>? excludeItemTypes) : base(includeItemTypes, excludeItemTypes, DefaultMemberIndexFields, null) { } public MemberValueSetValidator(IEnumerable<string>? includeItemTypes, IEnumerable<string>? excludeItemTypes, IEnumerable<string>? includeFields, IEnumerable<string>? excludeFields) : base(includeItemTypes, excludeItemTypes, includeFields, excludeFields) { } protected override IEnumerable<string> ValidIndexCategories => _validCategories; }
namespace Umbraco.Cms.Infrastructure.Examine; public class MemberValueSetValidator : ValueSetValidator { /// <summary> /// By default these are the member fields we index /// </summary> public static readonly string[] DefaultMemberIndexFields = { "id", UmbracoExamineFieldNames.NodeNameFieldName, "updateDate", "loginName", "email", UmbracoExamineFieldNames.NodeKeyFieldName, }; private static readonly IEnumerable<string> _validCategories = new[] { IndexTypes.Member }; public MemberValueSetValidator() : base(null, null, DefaultMemberIndexFields, null) { } public MemberValueSetValidator(IEnumerable<string> includeItemTypes, IEnumerable<string> excludeItemTypes) : base(includeItemTypes, excludeItemTypes, DefaultMemberIndexFields, null) { } public MemberValueSetValidator(IEnumerable<string> includeItemTypes, IEnumerable<string> excludeItemTypes, IEnumerable<string> includeFields, IEnumerable<string> excludeFields) : base(includeItemTypes, excludeItemTypes, includeFields, excludeFields) { } protected override IEnumerable<string> ValidIndexCategories => _validCategories; }
mit
C#
0158a1f60b5e5974b152b40d76ebfc45952a201f
remove RegisterDbContext in EntityFrameowrk.Configuration
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/iFramework.Plugins/iFramework.Infrastructure.EntityFramework/Config/Configuration.cs
Src/iFramework.Plugins/iFramework.Infrastructure.EntityFramework/Config/Configuration.cs
using IFramework.Config; using IFramework.Infrastructure; using IFramework.IoC; using IFramework.Repositories; using IFramework.UnitOfWork; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IFramework.EntityFramework.Config { public static class ConfigurationExtension { public static Configuration RegisterEntityFrameworkComponents(this Configuration configuration, IContainer container, Lifetime lifetime = Lifetime.PerRequest) { container = container ?? IoCFactory.Instance.CurrentContainer; return configuration.RegisterUnitOfWork(container, lifetime) .RegisterRepositories(container, lifetime); } public static Configuration RegisterEntityFrameworkComponents(this Configuration configuration, Lifetime lifetime = Lifetime.PerRequest) { return configuration.RegisterEntityFrameworkComponents(null, lifetime); } //public static Configuration RegisterDbContext(this Configuration configuration, IContainer container, Lifetime lifetime = Lifetime.PerRequest, params Type[] dbContextTypes) //{ // container = container ?? IoCFactory.Instance.CurrentContainer; // dbContextTypes.ForEach(type => // { // container.RegisterType(type, type, lifetime); // }); // return configuration; //} public static Configuration RegisterUnitOfWork(this Configuration configuration, IContainer container, Lifetime lifetime = Lifetime.PerRequest) { container = container ?? IoCFactory.Instance.CurrentContainer; container.RegisterType<IUnitOfWork, EntityFramework.UnitOfWork>(lifetime); return configuration; } public static Configuration RegisterRepositories(this Configuration configuration, IContainer container, Lifetime lifetime = Lifetime.PerRequest) { container = container ?? IoCFactory.Instance.CurrentContainer; container.RegisterType(typeof(IRepository<>), typeof(EntityFramework.Repositories.Repository<>), lifetime); container.RegisterType<IDomainRepository, EntityFramework.Repositories.DomainRepository>(lifetime); return configuration; } } }
using IFramework.Config; using IFramework.Infrastructure; using IFramework.IoC; using IFramework.Repositories; using IFramework.UnitOfWork; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IFramework.EntityFramework.Config { public static class ConfigurationExtension { public static Configuration RegisterEntityFrameworkComponents(this Configuration configuration, IContainer container, Lifetime lifetime = Lifetime.PerRequest, params Type[] dbContextTypes) { container = container ?? IoCFactory.Instance.CurrentContainer; return configuration.RegisterUnitOfWork(container, lifetime) .RegisterRepositories(container, lifetime) .RegisterDbContext(container, lifetime, dbContextTypes); } public static Configuration RegisterEntityFrameworkComponents(this Configuration configuration, Lifetime lifetime = Lifetime.PerRequest, params Type[] dbContextTypes) { return configuration.RegisterEntityFrameworkComponents(null, lifetime, dbContextTypes); } public static Configuration RegisterDbContext(this Configuration configuration, IContainer container, Lifetime lifetime = Lifetime.PerRequest, params Type[] dbContextTypes) { container = container ?? IoCFactory.Instance.CurrentContainer; dbContextTypes.ForEach(type => { container.RegisterType(type, type, lifetime); }); return configuration; } public static Configuration RegisterUnitOfWork(this Configuration configuration, IContainer container, Lifetime lifetime = Lifetime.PerRequest) { container = container ?? IoCFactory.Instance.CurrentContainer; container.RegisterType<IUnitOfWork, EntityFramework.UnitOfWork>(lifetime); return configuration; } public static Configuration RegisterRepositories(this Configuration configuration, IContainer container, Lifetime lifetime = Lifetime.PerRequest) { container = container ?? IoCFactory.Instance.CurrentContainer; container.RegisterType(typeof(IRepository<>), typeof(EntityFramework.Repositories.Repository<>), lifetime); container.RegisterType<IDomainRepository, EntityFramework.Repositories.DomainRepository>(lifetime); return configuration; } } }
mit
C#
332e492d429f0a43c76d1bcbce37576263d24dec
test fix
gigya/microdot
tests/Gigya.Microdot.Orleans.Hosting.UnitTests/WarmupTests.cs
tests/Gigya.Microdot.Orleans.Hosting.UnitTests/WarmupTests.cs
using System.Diagnostics; using System.Threading.Tasks; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.WarmupTestService; using Gigya.Microdot.Testing.Service; using Ninject; using NUnit.Framework; namespace Gigya.Microdot.Orleans.Hosting.UnitTests { [TestFixture] public class WarmupTests { private int mainPort = 9555; [Test] public async Task InstanceReadyBeforeCallingMethod_Warmup() { ServiceTester<CalculatorServiceHost> tester = AssemblyInitialize.ResolutionRoot.GetServiceTester<CalculatorServiceHost>(mainPort); IWarmupTestServiceGrain grain = tester.GetGrainClient<IWarmupTestServiceGrain>(0); int result = await grain.TestWarmedTimes(); result = await grain.TestWarmedTimes(); result = await grain.TestWarmedTimes(); Assert.AreEqual(result, 1); tester.Dispose(); } [Test] public async Task VerifyWarmupBeforeSiloStart() { WarmupTestServiceHostWithSiloHostFake host = new WarmupTestServiceHostWithSiloHostFake(); host.Run(); await host.WaitForHostDisposed(); } } }
using System.Diagnostics; using System.Threading.Tasks; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.WarmupTestService; using Gigya.Microdot.Testing.Service; using Ninject; using NUnit.Framework; namespace Gigya.Microdot.Orleans.Hosting.UnitTests { [TestFixture] public class WarmupTests { private int mainPort = 9555; [Test] public async Task InstanceReadyBeforeCallingMethod_Warmup() { ServiceTester<CalculatorServiceHost> tester = AssemblyInitialize.ResolutionRoot.GetServiceTester<CalculatorServiceHost>(mainPort); IWarmupTestServiceGrain grain = tester.GetGrainClient<IWarmupTestServiceGrain>(0); int result = await grain.TestWarmedTimes(); result = await grain.TestWarmedTimes(); result = await grain.TestWarmedTimes(); Assert.AreEqual(result, 1); tester.Dispose(); } [Test][Repeat(2)] public async Task VerifyWarmupBeforeSiloStart() { WarmupTestServiceHostWithSiloHostFake host = new WarmupTestServiceHostWithSiloHostFake(); host.Run(); await host.WaitForHostDisposed(); } } }
apache-2.0
C#
b423016bab12695f5df2af7c78b46677e61f9715
Fix on Stair Hurt, only turn invisible at the time. refer #2
ByzanTine/Castlevania-NES-Unity3d
Assets/_Scripts/HurtManager.cs
Assets/_Scripts/HurtManager.cs
using UnityEngine; using System.Collections; public class HurtManager : MonoBehaviour { public float InvisibleInterval = 1.0f; public float initHurtVericalSpeed = 1.0f; private bool hurting; // only provide accessor public bool Hurting { get { return hurting || disableControl; } } private bool disableControl; private Animator animator; private PlayerController pc; private SpriteRenderer sprite; private StatusManager status; private StairManager stairMan; void Start () { animator = GetComponent<Animator> (); pc = GetComponent<PlayerController> (); sprite = GetComponent<SpriteRenderer> (); status = GetComponent<StatusManager> (); stairMan = GetComponent<StairManager> (); hurting = false; disableControl = false; } // HACK public bool onFlyHurting () { return disableControl; } // ============================================================================ // public IEnumerator Hurt () { if (stairMan.isOnStair()) { hurting = true; StartCoroutine (turnInvisible ()); yield return null; } else { status.playerHealth -= 2; Debug.Log("HURTING: Hurt fucntion called"); hurting = true; // TODO do what ever is needed to turn off some collision // CODE HERE disableControl = true; animator.SetBool ("Hurt", true); pc.VerticalSpeed = 0; //reset to avoid fly high pc.VerticalSpeed += initHurtVericalSpeed; // add horizontal speed according to facing pc.CurHorizontalVelocity = pc.facingRight? -1 : 1; yield return new WaitForSeconds (0.33f); animator.SetBool ("Hurt", false); Debug.Log("HURTING: fly state cleaned"); StartCoroutine (turnInvisible ()); // turn animator.SetInteger ("Speed", 0); animator.SetBool ("Squat", true); yield return new WaitForSeconds (0.33f); pc.CurHorizontalVelocity = 0; animator.SetBool ("Squat", false); disableControl = false; } } IEnumerator turnInvisible () { Color curColor = sprite.color; curColor.a = curColor.a/2; // turn to half alpha sprite.color = curColor; yield return new WaitForSeconds (InvisibleInterval); curColor.a = 1.0f; // return to full alpha sprite.color = curColor; hurting = false; // TODO enable physics again } }
using UnityEngine; using System.Collections; public class HurtManager : MonoBehaviour { public float InvisibleInterval = 1.0f; public float initHurtVericalSpeed = 1.0f; private bool hurting; // only provide accessor public bool Hurting { get { return hurting || disableControl; } } private bool disableControl; private Animator animator; private PlayerController pc; private SpriteRenderer sprite; private StatusManager status; void Start () { animator = GetComponent<Animator> (); pc = GetComponent<PlayerController> (); sprite = GetComponent<SpriteRenderer> (); status = GetComponent<StatusManager> (); hurting = false; disableControl = false; } // HACK public bool onFlyHurting () { return disableControl; } // ============================================================================ // public IEnumerator Hurt () { status.playerHealth -= 2; Debug.Log("HURTING: Hurt fucntion called"); hurting = true; // TODO do what ever is needed to turn off some collision // CODE HERE disableControl = true; animator.SetBool ("Hurt", true); pc.VerticalSpeed = 0; //reset to avoid fly high pc.VerticalSpeed += initHurtVericalSpeed; // add horizontal speed according to facing pc.CurHorizontalVelocity = pc.facingRight? -1 : 1; yield return new WaitForSeconds (0.33f); animator.SetBool ("Hurt", false); Debug.Log("HURTING: fly state cleaned"); StartCoroutine (turnInvisible ()); // turn animator.SetInteger ("Speed", 0); animator.SetBool ("Squat", true); yield return new WaitForSeconds (0.33f); pc.CurHorizontalVelocity = 0; animator.SetBool ("Squat", false); disableControl = false; } IEnumerator turnInvisible () { Color curColor = sprite.color; curColor.a = curColor.a/2; // turn to half alpha sprite.color = curColor; yield return new WaitForSeconds (InvisibleInterval); curColor.a = 1.0f; // return to full alpha sprite.color = curColor; hurting = false; // TODO enable physics again } }
mit
C#
6f81e6d896cb57c317ff51b4dcb7e998defa76e5
change contract id on projection version handler
Elders/Cronus,Elders/Cronus
src/Elders.Cronus/Projections/Versioning/Handlers/ProjectionVersionsHandler.cs
src/Elders.Cronus/Projections/Versioning/Handlers/ProjectionVersionsHandler.cs
using System.Runtime.Serialization; using Elders.Cronus.Projections.Snapshotting; namespace Elders.Cronus.Projections.Versioning { [DataContract(Name = ContractId)] public class ProjectionVersionsHandler : ProjectionDefinition<ProjectionVersionsHandlerState, ProjectionVersionManagerId>, IAmNotSnapshotable, ISystemProjection, INonVersionableProjection, IEventHandler<ProjectionVersionRequested>, IEventHandler<NewProjectionVersionIsNowLive>, IEventHandler<ProjectionVersionRequestCanceled>, IEventHandler<ProjectionVersionRequestTimedout> { public const string ContractId = "ac8e4ba0-b351-4a91-8943-dee9465002a8"; public ProjectionVersionsHandler() { Subscribe<ProjectionVersionRequested>(x => x.Id); Subscribe<NewProjectionVersionIsNowLive>(x => x.Id); Subscribe<ProjectionVersionRequestCanceled>(x => x.Id); Subscribe<ProjectionVersionRequestTimedout>(x => x.Id); } public void Handle(ProjectionVersionRequested @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } public void Handle(NewProjectionVersionIsNowLive @event) { State.Id = @event.Id; State.AllVersions.Add(@event.ProjectionVersion); } public void Handle(ProjectionVersionRequestCanceled @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } public void Handle(ProjectionVersionRequestTimedout @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } } public class ProjectionVersionsHandlerState { public ProjectionVersionsHandlerState() { AllVersions = new ProjectionVersions(); } public ProjectionVersionManagerId Id { get; set; } public ProjectionVersion Live { get { return AllVersions.GetLive(); } } public ProjectionVersions AllVersions { get; set; } } }
using System.Runtime.Serialization; using Elders.Cronus.Projections.Snapshotting; namespace Elders.Cronus.Projections.Versioning { [DataContract(Name = ContractId)] public class ProjectionVersionsHandler : ProjectionDefinition<ProjectionVersionsHandlerState, ProjectionVersionManagerId>, IAmNotSnapshotable, ISystemProjection, INonVersionableProjection, IEventHandler<ProjectionVersionRequested>, IEventHandler<NewProjectionVersionIsNowLive>, IEventHandler<ProjectionVersionRequestCanceled>, IEventHandler<ProjectionVersionRequestTimedout> { public const string ContractId = "f1469a8e-9fc8-47f5-b057-d5394ed33b4c"; public ProjectionVersionsHandler() { Subscribe<ProjectionVersionRequested>(x => x.Id); Subscribe<NewProjectionVersionIsNowLive>(x => x.Id); Subscribe<ProjectionVersionRequestCanceled>(x => x.Id); Subscribe<ProjectionVersionRequestTimedout>(x => x.Id); } public void Handle(ProjectionVersionRequested @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } public void Handle(NewProjectionVersionIsNowLive @event) { State.Id = @event.Id; State.AllVersions.Add(@event.ProjectionVersion); } public void Handle(ProjectionVersionRequestCanceled @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } public void Handle(ProjectionVersionRequestTimedout @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } } public class ProjectionVersionsHandlerState { public ProjectionVersionsHandlerState() { AllVersions = new ProjectionVersions(); } public ProjectionVersionManagerId Id { get; set; } public ProjectionVersion Live { get { return AllVersions.GetLive(); } } public ProjectionVersions AllVersions { get; set; } } }
apache-2.0
C#
33e8034914978e6a5bd361d04f39723634dfff96
删除信息。
yoyocms/YoYoCms.AbpProjectTemplate,yoyocms/YoYoCms.AbpProjectTemplate,yoyocms/YoYoCms.AbpProjectTemplate
src/YoYoCms.AbpProjectTemplate.Application/AbpProjectTemplateAppServiceBase.cs
src/YoYoCms.AbpProjectTemplate.Application/AbpProjectTemplateAppServiceBase.cs
using System; using System.Threading.Tasks; using Abp.Application.Services; using Abp.IdentityFramework; using Abp.MultiTenancy; using Abp.Runtime.Session; using Microsoft.AspNet.Identity; using YoYoCms.AbpProjectTemplate.AppExtensions.AbpSessions; using YoYoCms.AbpProjectTemplate.Authorization.Users; using YoYoCms.AbpProjectTemplate.MultiTenancy; namespace YoYoCms.AbpProjectTemplate { /// <summary> /// All application services in this application is derived from this class. /// We can add common application service methods here. /// </summary> public abstract class AbpProjectTemplateAppServiceBase : ApplicationService { public TenantManager TenantManager { get; set; } public UserManager UserManager { get; set; } public new IAbpSessionExtensions AbpSession { get; set; } protected AbpProjectTemplateAppServiceBase() { LocalizationSourceName = AbpProjectTemplateConsts.LocalizationSourceName; } protected virtual async Task<User> GetCurrentUserAsync() { var user = await UserManager.FindByIdAsync(AbpSession.GetUserId()); if (user == null) { throw new ApplicationException("There is no current user!"); } return user; } protected virtual User GetCurrentUser() { var user = UserManager.FindById(AbpSession.GetUserId()); if (user == null) { throw new ApplicationException("There is no current user!"); } return user; } protected virtual Task<Tenant> GetCurrentTenantAsync() { using (CurrentUnitOfWork.SetTenantId(null)) { return TenantManager.GetByIdAsync(AbpSession.GetTenantId()); } } protected virtual Tenant GetCurrentTenant() { using (CurrentUnitOfWork.SetTenantId(null)) { return TenantManager.GetById(AbpSession.GetTenantId()); } } protected virtual void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
using System; using System.Threading.Tasks; using Abp.Application.Services; using Abp.Domain.Repositories; using Abp.IdentityFramework; using Abp.MultiTenancy; using Abp.Runtime.Session; using Microsoft.AspNet.Identity; using YoYoCms.AbpProjectTemplate.AppExtensions.AbpSessions; using YoYoCms.AbpProjectTemplate.Authorization.Users; using YoYoCms.AbpProjectTemplate.MultiTenancy; namespace YoYoCms.AbpProjectTemplate { /// <summary> /// All application services in this application is derived from this class. /// We can add common application service methods here. /// </summary> public abstract class AbpProjectTemplateAppServiceBase : ApplicationService { public TenantManager TenantManager { get; set; } public UserManager UserManager { get; set; } public new IAbpSessionExtensions AbpSession { get; set; } private IRepository<User,long> _useRepository; protected AbpProjectTemplateAppServiceBase(IRepository<User, long> useRepository) { _useRepository = useRepository; LocalizationSourceName = AbpProjectTemplateConsts.LocalizationSourceName; } protected virtual async Task<User> GetCurrentUserAsync() { var user = await _useRepository.GetAsync(AbpSession.GetUserId()); if (user == null) { throw new ApplicationException("There is no current user!"); } return user; } protected virtual User GetCurrentUser() { var user = _useRepository.Get(AbpSession.GetUserId()); if (user == null) { throw new ApplicationException("There is no current user!"); } return user; } protected virtual Task<Tenant> GetCurrentTenantAsync() { using (CurrentUnitOfWork.SetTenantId(null)) { return TenantManager.GetByIdAsync(AbpSession.GetTenantId()); } } protected virtual Tenant GetCurrentTenant() { using (CurrentUnitOfWork.SetTenantId(null)) { return TenantManager.GetById(AbpSession.GetTenantId()); } } protected virtual void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
apache-2.0
C#
0d87f7ff7bd51dc6300aafab795babe473db0c08
remove comment
cbcrc/LinkIt
HeterogeneousDataSources/LoadLinkExpressions/Includes/SubLinkedSourceInclude.cs
HeterogeneousDataSources/LoadLinkExpressions/Includes/SubLinkedSourceInclude.cs
using System; using System.Collections.Generic; namespace HeterogeneousDataSources.LoadLinkExpressions.Includes { public class SubLinkedSourceInclude<TIChildLinkedSource, TLink, TChildLinkedSource, TChildLinkedSourceModel>: IIncludeWithCreateSubLinkedSource<TIChildLinkedSource,TLink>, IIncludeWithChildLinkedSource where TChildLinkedSource : class, ILinkedSource<TChildLinkedSourceModel>, new() { private readonly Func<TLink, TChildLinkedSourceModel> _getSubLinkedSourceModel; public SubLinkedSourceInclude(Func<TLink, TChildLinkedSourceModel> getSubLinkedSourceModel) { _getSubLinkedSourceModel = getSubLinkedSourceModel; ChildLinkedSourceType = typeof(TChildLinkedSource); } public Type ChildLinkedSourceType { get; private set; } public TIChildLinkedSource CreateSubLinkedSource(TLink link, LoadedReferenceContext loadedReferenceContext) { var childLinkSourceModel = _getSubLinkedSourceModel(link); return (TIChildLinkedSource) (object) loadedReferenceContext .CreatePartiallyBuiltLinkedSource<TChildLinkedSource, TChildLinkedSourceModel>(childLinkSourceModel); } public void AddReferenceTreeForEachLinkTarget(ReferenceTree parent, LoadLinkConfig config) { config.AddReferenceTreeForEachLinkTarget(ChildLinkedSourceType, parent); } } }
using System; using System.Collections.Generic; namespace HeterogeneousDataSources.LoadLinkExpressions.Includes { public class SubLinkedSourceInclude<TIChildLinkedSource, TLink, TChildLinkedSource, TChildLinkedSourceModel>: IIncludeWithCreateSubLinkedSource<TIChildLinkedSource,TLink>, IIncludeWithChildLinkedSource where TChildLinkedSource : class, ILinkedSource<TChildLinkedSourceModel>, new() { private readonly Func<TLink, TChildLinkedSourceModel> _getSubLinkedSourceModel; public SubLinkedSourceInclude(Func<TLink, TChildLinkedSourceModel> getSubLinkedSourceModel) { _getSubLinkedSourceModel = getSubLinkedSourceModel; ChildLinkedSourceType = typeof(TChildLinkedSource); } public Type ChildLinkedSourceType { get; private set; } public TIChildLinkedSource CreateSubLinkedSource(TLink link, LoadedReferenceContext loadedReferenceContext) { var childLinkSourceModel = _getSubLinkedSourceModel(link); //stle: move double cast to loadedReferenceContext //stle: dry with nested linked source return (TIChildLinkedSource) (object) loadedReferenceContext .CreatePartiallyBuiltLinkedSource<TChildLinkedSource, TChildLinkedSourceModel>(childLinkSourceModel); } public void AddReferenceTreeForEachLinkTarget(ReferenceTree parent, LoadLinkConfig config) { config.AddReferenceTreeForEachLinkTarget(ChildLinkedSourceType, parent); } } }
mit
C#
7db60a78de843e53919ef6c64e09fd3d30b932fe
Add type field
CB17Echo/DroneSafety,CB17Echo/DroneSafety,CB17Echo/DroneSafety
AzureFunctions/Models/Hazard.csx
AzureFunctions/Models/Hazard.csx
using System; abstract public class Hazard { public int HazardLevel { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } public string Type { get { return GetType().Name; } } }
using System; abstract public class Hazard { public int HazardLevel { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } }
apache-2.0
C#
269e4466aa606756f75d84a30656f9adc1602815
Fix assembly metadata.
drewnoakes/boing
Boing/Properties/AssemblyInfo.cs
Boing/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("Boing")] [assembly: AssemblyDescription("2D Physics Simulation for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Boing")] [assembly: AssemblyCopyright("Copyright © Drew Noakes, Krzysztof Dul 2015-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("16ab00d0-18fb-4775-acaa-1858cf2baa14")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.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("Boing")] [assembly: AssemblyDescription("2D Physics Simulation for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Drew Noakes")] [assembly: AssemblyProduct("Boing")] [assembly: AssemblyCopyright("Copyright © Drew Noakes 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("16ab00d0-18fb-4775-acaa-1858cf2baa14")] // 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")]
apache-2.0
C#
ebeb61cd9111ce714690cc79ec0edb0137e6a43e
Fix bug in LabelReplacer.
Frassle/ciltk
Rewriter/LabelReplacer.cs
Rewriter/LabelReplacer.cs
using Mono.Cecil; using Mono.Cecil.Cil; using Silk.Loom; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Weave { class LabelReplacer : InstructionVisitor { Dictionary<Tuple<MethodBody, string>, Instruction> Labels; public LabelReplacer() { Labels = new Dictionary<Tuple<MethodBody, string>, Instruction>(); } public Instruction GetJumpLocation(MethodBody methodBody, string label) { Instruction instruction; if (!Labels.TryGetValue(Tuple.Create(methodBody, label), out instruction)) { Console.WriteLine("Label {0} in method {1} not found.", label, methodBody.Method.FullName); Environment.Exit(1); } return instruction; } protected override bool ShouldVisit(Instruction instruction) { if (instruction.OpCode == OpCodes.Call) { var method = instruction.Operand as MethodReference; if (method != null && method.DeclaringType.FullName == "Silk.Cil" && method.Name == "Label") { return true; } } return false; } protected override Instruction Visit(ILProcessor ilProcessor, Instruction instruction) { var label = Analysis[instruction.Previous].Head; if (!label.Item2.IsConstant) { Console.WriteLine("Label call must be used with a string literal."); Environment.Exit(1); } var jump_location = StackAnalyser.RemoveInstructionChain(ilProcessor.Body.Method, instruction, Analysis); Labels.Add(Tuple.Create(ilProcessor.Body, label.Item2.Value), jump_location); return jump_location.Next; } } }
using Mono.Cecil; using Mono.Cecil.Cil; using Silk.Loom; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Weave { class LabelReplacer : InstructionVisitor { Dictionary<Tuple<MethodBody, string>, Instruction> Labels; public LabelReplacer() { Labels = new Dictionary<Tuple<MethodBody, string>, Instruction>(); } public Instruction GetJumpLocation(MethodBody methodBody, string label) { Instruction instruction; if (!Labels.TryGetValue(Tuple.Create(methodBody, label), out instruction)) { Console.WriteLine("Label {0} in method {1} not found.", label, methodBody.Method.FullName); Environment.Exit(1); } return instruction; } protected override bool ShouldVisit(Instruction instruction) { if (instruction.OpCode == OpCodes.Call) { var method = instruction.Operand as MethodReference; if (method != null && method.DeclaringType.FullName == "Silk.Cil" && method.Name == "Label") { return true; } } return false; } protected override Instruction Visit(ILProcessor ilProcessor, Instruction instruction) { var label = Analysis[instruction.Previous].Head; if (label.Item2.IsConstant) { Console.WriteLine("Label call must be used with a string literal."); Environment.Exit(1); } var jump_location = StackAnalyser.RemoveInstructionChain(ilProcessor.Body.Method, instruction, Analysis); Labels.Add(Tuple.Create(ilProcessor.Body, label.Item2.Value), jump_location); return jump_location.Next; } } }
mit
C#
df6485672ffff358500d20450b386d23c0b8663e
Remove empty navigation list in anydiff module (invalid HTML).
rbaumg/trac,rbaumg/trac,rbaumg/trac,rbaumg/trac
templates/anydiff.cs
templates/anydiff.cs
<?cs include "header.cs"?> <div id="ctxtnav" class="nav"></div> <div id="content" class="changeset"> <div id="title"> <h1>Select Base and Target for Diff:</h1> </div> <div id="anydiff"> <form action="<?cs var:anydiff.changeset_href ?>" method="get"> <table> <tr> <th><label for="old_path">From:</label></th> <td> <input type="text" id="old_path" name="old_path" value="<?cs var:anydiff.old_path ?>" size="44" /> <label for="old_rev">at Revision:</label> <input type="text" id="old_rev" name="old" value="<?cs var:anydiff.old_rev ?>" size="4" /> </td> </tr> <tr> <th><label for="new_path">To:</label></th> <td> <input type="text" id="new_path" name="new_path" value="<?cs var:anydiff.new_path ?>" size="44" /> <label for="new_rev">at Revision:</label> <input type="text" id="new_rev" name="new" value="<?cs var:anydiff.new_rev ?>" size="4" /> </td> </tr> </table> <div class="buttons"> <input type="submit" value="View changes" /> </div> </form> </div> <div id="help"> <strong>Note:</strong> See <a href="<?cs var:trac.href.wiki ?>/TracChangeset#ExaminingArbitraryDifferences">TracChangeset</a> for help on using the arbitrary diff feature. </div> </div> <?cs include "footer.cs"?>
<?cs include "header.cs"?> <div id="ctxtnav" class="nav"> <h2>Navigation</h2><?cs with:links = chrome.links ?> <ul> </ul><?cs /with ?> </div> <div id="content" class="changeset"> <div id="title"> <h1>Select Base and Target for Diff:</h1> </div> <div id="anydiff"> <form action="<?cs var:anydiff.changeset_href ?>" method="get"> <table> <tr> <th><label for="old_path">From:</label></th> <td> <input type="text" id="old_path" name="old_path" value="<?cs var:anydiff.old_path ?>" size="44" /> <label for="old_rev">at Revision:</label> <input type="text" id="old_rev" name="old" value="<?cs var:anydiff.old_rev ?>" size="4" /> </td> </tr> <tr> <th><label for="new_path">To:</label></th> <td> <input type="text" id="new_path" name="new_path" value="<?cs var:anydiff.new_path ?>" size="44" /> <label for="new_rev">at Revision:</label> <input type="text" id="new_rev" name="new" value="<?cs var:anydiff.new_rev ?>" size="4" /> </td> </tr> </table> <div class="buttons"> <input type="submit" value="View changes" /> </div> </form> </div> <div id="help"> <strong>Note:</strong> See <a href="<?cs var:trac.href.wiki ?>/TracChangeset#ExaminingArbitraryDifferences">TracChangeset</a> for help on using the arbitrary diff feature. </div> </div> <?cs include "footer.cs"?>
bsd-3-clause
C#
669c708a14a317addd4003acac94e3f04f4eb8a3
Remove name from assembly info; this looks silly on NuGet.
DartVS/DartVS,modulexcite/DartVS,DartVS/DartVS,DartVS/DartVS,modulexcite/DartVS,modulexcite/DartVS
DanTup.DartAnalysis/Properties/AssemblyInfo.cs
DanTup.DartAnalysis/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")] [assembly: AssemblyProduct("DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")] [assembly: AssemblyCompany("Danny Tuppeny")] [assembly: AssemblyCopyright("Copyright Danny Tuppeny © 2014")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.1.*")] [assembly: InternalsVisibleTo("DanTup.DartAnalysis.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("DanTup's DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")] [assembly: AssemblyProduct("DanTup's DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")] [assembly: AssemblyCompany("Danny Tuppeny")] [assembly: AssemblyCopyright("Copyright Danny Tuppeny © 2014")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.1.*")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: InternalsVisibleTo("DanTup.DartAnalysis.Tests")]
mit
C#
cc112adb46f3f81ad794b0eee2db42c6d1572236
Make image loading independent of the working directory.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/MitternachtBot/Services/Impl/ImagesService.cs
src/MitternachtBot/Services/Impl/ImagesService.cs
using System; using System.Collections.Immutable; using System.IO; using System.Linq; using NLog; namespace Mitternacht.Services.Impl { public class ImagesService : IImagesService { private readonly Logger _log; private static readonly string BasePath = Path.Combine(Path.GetDirectoryName(typeof(ImagesService).Assembly.Location), "data/images/"); private static readonly string HeadsPath = BasePath + "coins/heads.png"; private static readonly string TailsPath = BasePath + "coins/tails.png"; private static readonly string CurrencyImagesPath = BasePath + "currency"; private static readonly string WifeMatrixPath = BasePath + "rategirl/wifematrix.png"; private static readonly string RategirlDotPath = BasePath + "rategirl/dot.png"; public ImmutableArray<byte> Heads { get; private set; } public ImmutableArray<byte> Tails { get; private set; } public ImmutableArray<(string, ImmutableArray<byte>)> Currency { get; private set; } public ImmutableArray<byte> WifeMatrix { get; private set; } public ImmutableArray<byte> RategirlDot { get; private set; } public ImagesService() { _log = LogManager.GetCurrentClassLogger(); Reload(); } public void Reload() { try { Heads = File.ReadAllBytes(HeadsPath).ToImmutableArray(); Tails = File.ReadAllBytes(TailsPath).ToImmutableArray(); Currency = Directory.GetFiles(CurrencyImagesPath) .Select(x => (Path.GetFileName(x), File.ReadAllBytes(x).ToImmutableArray())) .ToImmutableArray(); WifeMatrix = File.ReadAllBytes(WifeMatrixPath).ToImmutableArray(); RategirlDot = File.ReadAllBytes(RategirlDotPath).ToImmutableArray(); } catch (Exception ex) { _log.Error(ex); throw; } } } }
using System; using System.Collections.Immutable; using System.IO; using System.Linq; using NLog; namespace Mitternacht.Services.Impl { public class ImagesService : IImagesService { private readonly Logger _log; private const string BasePath = "data/images/"; private const string HeadsPath = BasePath + "coins/heads.png"; private const string TailsPath = BasePath + "coins/tails.png"; private const string CurrencyImagesPath = BasePath + "currency"; private const string WifeMatrixPath = BasePath + "rategirl/wifematrix.png"; private const string RategirlDotPath = BasePath + "rategirl/dot.png"; public ImmutableArray<byte> Heads { get; private set; } public ImmutableArray<byte> Tails { get; private set; } public ImmutableArray<(string, ImmutableArray<byte>)> Currency { get; private set; } public ImmutableArray<byte> WifeMatrix { get; private set; } public ImmutableArray<byte> RategirlDot { get; private set; } public ImagesService() { _log = LogManager.GetCurrentClassLogger(); Reload(); } public void Reload() { try { Heads = File.ReadAllBytes(HeadsPath).ToImmutableArray(); Tails = File.ReadAllBytes(TailsPath).ToImmutableArray(); Currency = Directory.GetFiles(CurrencyImagesPath) .Select(x => (Path.GetFileName(x), File.ReadAllBytes(x).ToImmutableArray())) .ToImmutableArray(); WifeMatrix = File.ReadAllBytes(WifeMatrixPath).ToImmutableArray(); RategirlDot = File.ReadAllBytes(RategirlDotPath).ToImmutableArray(); } catch (Exception ex) { _log.Error(ex); throw; } } } }
mit
C#
64b304dd52b7ea9c5d45626bb356b20e0956735a
Fix build break
dolkensp/node.net,GearedToWar/NuGet2,jmezach/NuGet2,oliver-feng/nuget,jholovacs/NuGet,jmezach/NuGet2,ctaggart/nuget,chocolatey/nuget-chocolatey,xoofx/NuGet,mrward/nuget,indsoft/NuGet2,mono/nuget,mrward/NuGet.V2,mrward/nuget,jholovacs/NuGet,mrward/nuget,antiufo/NuGet2,rikoe/nuget,alluran/node.net,xoofx/NuGet,mrward/nuget,kumavis/NuGet,zskullz/nuget,oliver-feng/nuget,themotleyfool/NuGet,mrward/nuget,pratikkagda/nuget,chocolatey/nuget-chocolatey,anurse/NuGet,antiufo/NuGet2,pratikkagda/nuget,OneGet/nuget,xoofx/NuGet,GearedToWar/NuGet2,mrward/NuGet.V2,OneGet/nuget,jholovacs/NuGet,mrward/NuGet.V2,anurse/NuGet,oliver-feng/nuget,OneGet/nuget,antiufo/NuGet2,GearedToWar/NuGet2,chocolatey/nuget-chocolatey,pratikkagda/nuget,pratikkagda/nuget,atheken/nuget,mono/nuget,atheken/nuget,xoofx/NuGet,indsoft/NuGet2,jmezach/NuGet2,zskullz/nuget,mrward/NuGet.V2,RichiCoder1/nuget-chocolatey,antiufo/NuGet2,alluran/node.net,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,dolkensp/node.net,GearedToWar/NuGet2,indsoft/NuGet2,dolkensp/node.net,chocolatey/nuget-chocolatey,themotleyfool/NuGet,RichiCoder1/nuget-chocolatey,themotleyfool/NuGet,antiufo/NuGet2,indsoft/NuGet2,mrward/nuget,chocolatey/nuget-chocolatey,indsoft/NuGet2,antiufo/NuGet2,rikoe/nuget,jmezach/NuGet2,akrisiun/NuGet,rikoe/nuget,chocolatey/nuget-chocolatey,oliver-feng/nuget,akrisiun/NuGet,ctaggart/nuget,rikoe/nuget,OneGet/nuget,mrward/NuGet.V2,dolkensp/node.net,RichiCoder1/nuget-chocolatey,xoofx/NuGet,pratikkagda/nuget,chester89/nugetApi,zskullz/nuget,xoofx/NuGet,jmezach/NuGet2,indsoft/NuGet2,alluran/node.net,jholovacs/NuGet,ctaggart/nuget,jholovacs/NuGet,pratikkagda/nuget,ctaggart/nuget,mono/nuget,oliver-feng/nuget,zskullz/nuget,jholovacs/NuGet,GearedToWar/NuGet2,alluran/node.net,mono/nuget,GearedToWar/NuGet2,chester89/nugetApi,mrward/NuGet.V2,oliver-feng/nuget,kumavis/NuGet,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey
src/CommandLine/DebugHelper.cs
src/CommandLine/DebugHelper.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace NuGet { internal static class DebugHelper { [Conditional("DEBUG")] internal static void WaitForAttach(ref string[] args) { if (String.Equals(args[0], "dbg", StringComparison.OrdinalIgnoreCase) || String.Equals(args[0], "debug", StringComparison.OrdinalIgnoreCase)) { args = args.Skip(1).ToArray(); if (!Debugger.IsAttached) { Debugger.Launch(); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace NuGet { internal static class DebugHelper { [Conditional("DEBUG")] internal static void WaitForAttach(ref string[] args) { if (String.Equals(args[0], "dbg", StringComparison.OrdinalIgnoreCase) || String.Equals(args[0], "debug", StringComparison.OrdinalIgnoreCase)) { args = args.Skip(1).ToArray(); if (!Debugger.IsAttached) { Console.WriteLine("Waiting for Debugger to attach..."); SpinWait.SpinUntil(() => Debugger.IsAttached); } } } } }
apache-2.0
C#
b6ec45a334df4f1ea39d836181db5bf52604d024
check CI build v1
Orbmu2k/nvidiaProfileInspector,Orbmu2k/nvidiaProfileInspector
nspector/Properties/AssemblyInfo.cs
nspector/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("nvidiaProfileInspector")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NVIDIA Profile Inspector")] [assembly: AssemblyCopyright("©2022 by Orbmu2k")] [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("c2fe2861-54c5-4d63-968e-30472019bed3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.4.0.0")] [assembly: AssemblyFileVersion("2.4.0.0")]
using System.Reflection; 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("nvidiaProfileInspector")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NVIDIA Profile Inspector")] [assembly: AssemblyCopyright("©2022 by Orbmu2k")] [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("c2fe2861-54c5-4d63-968e-30472019bed3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.3.0.0")] [assembly: AssemblyFileVersion("2.3.0.0")]
mit
C#
b0624fe98d88bc3d48d04680c9b4b9aeb95f68bb
Reorganize Update() checks
BrianErikson/KSP
HUDTweaks/NavballUpDefault/NavballUpDefault.cs
HUDTweaks/NavballUpDefault/NavballUpDefault.cs
// LICENSE: Apache License Version 2.0 // By: BrianErikson using KSP.UI.Screens.Flight; using KSP; namespace NavballUpDefault { [KSPAddon(KSPAddon.Startup.Flight, false)] public class NavballUpDefault : UnityEngine.MonoBehaviour { NavBallToggle navToggle; bool showing = false; void Start() { UnityEngine.Debug.Log("[NavballUpDefault] Started"); navToggle = NavBallToggle.Instance; } void Update() { bool curShow = MapView.MapIsEnabled; // Check if we opened/closed map view if (curShow != showing) { // Just closed map view if (showing) { showing = curShow; } // Just opened map view else //showing is false if (!navToggle.panel.expanded) { OpenNavball(); showing = curShow; } } } void OpenNavball() { if (navToggle != null) { if (!navToggle.panel.expanded) { navToggle.Invoke("TogglePanel", 0f); } if (!navToggle.ManeuverModeActive) { navToggle.OnNavBallToggle(); } } } } }
// LICENSE: Apache License Version 2.0 // By: BrianErikson using KSP.UI.Screens.Flight; using KSP; namespace NavballUpDefault { [KSPAddon(KSPAddon.Startup.Flight, false)] public class NavballUpDefault : UnityEngine.MonoBehaviour { NavBallToggle navToggle; bool showing = false; void Start() { UnityEngine.Debug.Log("[NavballUpDefault] Started"); navToggle = NavBallToggle.Instance; } void Update() { bool curShow = MapView.MapIsEnabled; // Just opened map view if (curShow != showing && showing == false && !navToggle.panel.expanded) { OpenNavball(); showing = curShow; } // Just closed map view else if (curShow != showing && showing == true) { showing = curShow; } } void OpenNavball() { if (navToggle != null) { if (!navToggle.panel.expanded) { navToggle.Invoke("TogglePanel", 0f); } if (!navToggle.ManeuverModeActive) { navToggle.OnNavBallToggle(); } } } } }
apache-2.0
C#
0d45d0ed0ab0075922dbfa49e3b9f02c5163da48
Update assembly version
igece/SoxSharp
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos atributos para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("SoxSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("igece.labs")] [assembly: AssemblyProduct("SoxSharp")] [assembly: AssemblyCopyright("Copyright © 2017 igece.labs")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible como true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("43ffc71a-e6bb-4e6e-9f53-679a123f68b4")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos atributos para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("SoxWrapper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("igece.labs")] [assembly: AssemblyProduct("SoxWrapper")] [assembly: AssemblyCopyright("Copyright © 2017 igece.labs")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible como true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("43ffc71a-e6bb-4e6e-9f53-679a123f68b4")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#