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
714b7f367592a8de52b5f18d2504051702b330cd
make the showing more consistent
wfarr/newskit,wfarr/newskit
src/Summa/Summa.Gui/NotificationBar.cs
src/Summa/Summa.Gui/NotificationBar.cs
// NotificationBar.cs // // Copyright (c) 2008 Ethan Osten // // 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 Gtk; namespace Summa.Gui { public class NotificationBar : Gtk.Statusbar { private uint cid; public NotificationBar() { cid = 0; Summa.Core.Application.Notifier.Notification += OnNotification; } private void OnNotification(object obj, Summa.Core.NotificationEventArgs args) { ShowMessage(args.Message); } public void ShowMessage(string message) { Push(cid, message); cid++; } } }
// NotificationBar.cs // // Copyright (c) 2008 Ethan Osten // // 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 Gtk; namespace Summa.Gui { public class NotificationBar : Gtk.Statusbar { private uint cid; public NotificationBar() { cid = 0; Summa.Core.Application.Notifier.Notification += OnNotification; } private void OnNotification(object obj, Summa.Core.NotificationEventArgs args) { ShowMessage(args.Message); } public void ShowMessage(string message) { Gdk.Threads.Enter(); Push(cid, message); cid++; Gdk.Threads.Leave(); } } }
mit
C#
0fecad9056f8039b7d3830158643d64ff98fa857
Fix NRE when emptying fields in the sample's textboxes [#8839]
PlayScriptRedux/monomac,dlech/monomac
samples/PopupBindings/Person.cs
samples/PopupBindings/Person.cs
using System; using System.Collections.Generic; using System.Linq; using MonoMac.Foundation; using MonoMac.AppKit; namespace PopupBindings { public partial class Person : NSObject { Dictionary<string, object> personValues; static string NAME = "name"; static string AGE = "age"; static string ADDRESS_STREET = "addressStreet"; static string ADDRESS_CITY = "addressCity"; static string ADDRESS_STATE = "addressState"; static string ADDRESS_ZIP = "addressZip"; string[] keys = new string[] { NAME, AGE, ADDRESS_STREET, ADDRESS_CITY, ADDRESS_STATE, ADDRESS_ZIP }; public Person (object[] attributes) { var newAttributes = new Dictionary<string, object> (); for (int x = 0; x < keys.Length; x++) newAttributes.Add(keys[x],attributes[x]); this.personValues = newAttributes; } [Export ("name")] public string Name { get { return personValues [NAME].ToString (); } set { personValues [NAME] = value ?? String.Empty; } } [Export ("age")] public int Age { get { return (int)personValues [AGE]; } set { personValues [AGE] = value; } } [Export("addressStreet")] public string AddressStreet { get { return personValues [ADDRESS_STREET].ToString (); } set { personValues [ADDRESS_STREET] = value ?? String.Empty; } } [Export("addressCity")] public string AddressCity { get { return personValues [ADDRESS_CITY].ToString (); } set { personValues [ADDRESS_CITY] = value ?? String.Empty; } } [Export ("addressState")] public string AddressState { get { return personValues [ADDRESS_STATE].ToString (); } set { personValues [ADDRESS_STATE] = value ?? String.Empty; } } [Export ("addressZip")] public string AddressZip { get { return personValues [ADDRESS_ZIP].ToString (); } set { personValues [ADDRESS_ZIP] = value ?? String.Empty; } } public Dictionary<string,object> Attributes { get { return personValues; } set { personValues = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using MonoMac.Foundation; using MonoMac.AppKit; namespace PopupBindings { public partial class Person : NSObject { Dictionary<string, object> personValues; static string NAME = "name"; static string AGE = "age"; static string ADDRESS_STREET = "addressStreet"; static string ADDRESS_CITY = "addressCity"; static string ADDRESS_STATE = "addressState"; static string ADDRESS_ZIP = "addressZip"; string[] keys = new string[] { NAME, AGE, ADDRESS_STREET, ADDRESS_CITY, ADDRESS_STATE, ADDRESS_ZIP }; public Person (object[] attributes) { var newAttributes = new Dictionary<string, object> (); for (int x = 0; x < keys.Length; x++) newAttributes.Add(keys[x],attributes[x]); this.personValues = newAttributes; } [Export ("name")] public string Name { get { return personValues [NAME].ToString (); } set { personValues [NAME] = value; } } [Export ("age")] public int Age { get { return (int)personValues [AGE]; } set { personValues [AGE] = value; } } [Export("addressStreet")] public string AddressStreet { get { return personValues [ADDRESS_STREET].ToString (); } set { personValues [ADDRESS_STREET] = value; } } [Export("addressCity")] public string AddressCity { get { return personValues [ADDRESS_CITY].ToString (); } set { personValues [ADDRESS_CITY] = value; } } [Export ("addressState")] public string AddressState { get { return personValues [ADDRESS_STATE].ToString (); } set { personValues [ADDRESS_STATE] = value; } } [Export ("addressZip")] public string AddressZip { get { return personValues [ADDRESS_ZIP].ToString (); } set { personValues [ADDRESS_ZIP] = value; } } public Dictionary<string,object> Attributes { get { return personValues; } set { personValues = value; } } } }
apache-2.0
C#
9e0f3b0629fd49ff7b35cff34e66be99c5bb0a3d
Make thread safe/fast/unique
JetBrains/TeamCity.ServiceMessages
TeamCity.ServiceMessages/src/Write/Special/Impl/Updater/FlowId.cs
TeamCity.ServiceMessages/src/Write/Special/Impl/Updater/FlowId.cs
using System; using System.Globalization; using System.Threading; using JetBrains.TeamCity.ServiceMessages.Annotations; namespace JetBrains.TeamCity.ServiceMessages.Write.Special.Impl.Updater { /// <summary> /// Helper class to generate FlowIds /// </summary> /// //TODO: make as interface and allow to change public static class FlowId { private static int myIds; /// <summary> /// Generates new unique FlowId /// </summary> /// <returns></returns> [NotNull] public static string NewFlowId() { return ( Interlocked.Increment(ref myIds) << 27 + (Thread.CurrentThread.ManagedThreadId << 21) + (Environment.TickCount%int.MaxValue) ) .ToString(CultureInfo.InvariantCulture); } } }
using System; using System.Globalization; using System.Threading; using JetBrains.TeamCity.ServiceMessages.Annotations; namespace JetBrains.TeamCity.ServiceMessages.Write.Special.Impl.Updater { /// <summary> /// Helper class to generate FlowIds /// </summary> public static class FlowId { /// <summary> /// Generates new unique FlowId /// </summary> /// <returns></returns> [NotNull] public static string NewFlowId() { return ( (Thread.CurrentThread.ManagedThreadId << 21) + (Environment.TickCount%int.MaxValue) ) .ToString(CultureInfo.InvariantCulture); } } }
apache-2.0
C#
902086ae6fe933ae6966cb3168b20c7a0cca4262
Improve control
leotsarev/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
Joinrpg/App_Code/SearchableDropdownMvcHelper.cs
Joinrpg/App_Code/SearchableDropdownMvcHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Web.Mvc; using JoinRpg.Helpers; namespace JoinRpg.Web { public static class SearchableDropdownMvcHelper { public static MvcHtmlString SearchableDropdownFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression, IEnumerable<ImprovedSelectListItem> items) { //TODO: selected value from model var itemsString = string.Join("\n", items.Select(item => string.Format( "<option data-tokens=\"{0} {1} {3}\" data-subtext=\"{1}\" value=\"{2}\">{3}</option >", item.ExtraSearch, item.Subtext, item.Value, item.Text))); // ReSharper disable once UseStringInterpolation we are inside Razor return MvcHtmlString.Create(string.Format(@" <select class=""selectpicker"" data-live-search = ""true"" data-live-search-normalize = ""true"" data-size = ""10"" name=""{1}""> {0} </select>", itemsString, expression.AsPropertyName())); } } public class ImprovedSelectListItem : SelectListItem { public object ExtraSearch { get; set; } public object Subtext { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Web.Mvc; using JoinRpg.Helpers; namespace JoinRpg.Web { public static class SearchableDropdownMvcHelper { public static MvcHtmlString SearchableDropdownFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression, IEnumerable<ImprovedSelectListItem> items) { //TODO: selected value from model var itemsString = string.Join("", items.Select(item => string.Format( "<option data-tokens=\"{0}\" data-subtext=\"{1}\" value=\"{2}\">{3}</option >", item.ExtraSearch, item.Subtext, item.Value, item.Text))); // ReSharper disable once UseStringInterpolation we are inside Razor return MvcHtmlString.Create(string.Format(@" <select class=""selectpicker"" data-live-search = ""true"" data-live-search-normalize = ""true"" data-size = ""10"" name=""{1}""> {0} </select>", itemsString, expression.AsPropertyName())); } } public class ImprovedSelectListItem : SelectListItem { public object ExtraSearch { get; set; } public object Subtext { get; set; } } }
mit
C#
e2f002e871b7c5d1989a4f5e16dc706a9a8f1a4a
Call 'update' with Delta time
RockyTV/Duality.IronPython
CorePlugin/ScriptExecutor.cs
CorePlugin/ScriptExecutor.cs
using System; using System.Collections.Generic; using System.Linq; using Duality; using RockyTV.Duality.Plugins.IronPython.Resources; using IronPython.Hosting; using IronPython.Runtime; using IronPython.Compiler; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; namespace RockyTV.Duality.Plugins.IronPython { public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable { public ContentRef<PythonScript> Script { get; set; } [DontSerialize] private PythonExecutionEngine _engine; protected PythonExecutionEngine Engine { get { return _engine; } } protected virtual float Delta { get { return Time.MsPFMult * Time.TimeMult; } } public void OnInit(InitContext context) { if (!Script.IsAvailable) return; _engine = new PythonExecutionEngine(Script.Res.Content); _engine.SetVariable("gameObject", GameObj); if (_engine.HasMethod("start")) _engine.CallMethod("start"); } public void OnUpdate() { if (_engine.HasMethod("update")) _engine.CallMethod("update", Delta); } public void OnShutdown(ShutdownContext context) { if (context == ShutdownContext.Deactivate) { GameObj.DisposeLater(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Duality; using RockyTV.Duality.Plugins.IronPython.Resources; using IronPython.Hosting; using IronPython.Runtime; using IronPython.Compiler; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; namespace RockyTV.Duality.Plugins.IronPython { public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable { public ContentRef<PythonScript> Script { get; set; } [DontSerialize] private PythonExecutionEngine _engine; protected PythonExecutionEngine Engine { get { return _engine; } } public void OnInit(InitContext context) { if (!Script.IsAvailable) return; _engine = new PythonExecutionEngine(Script.Res.Content); _engine.SetVariable("gameObject", GameObj); if (_engine.HasMethod("start")) _engine.CallMethod("start"); } public void OnUpdate() { if (_engine.HasMethod("update")) _engine.CallMethod("update"); } public void OnShutdown(ShutdownContext context) { if (context == ShutdownContext.Deactivate) { GameObj.DisposeLater(); } } } }
mit
C#
94e2412e893a5073e82fe9c8a9d9bfee79c03181
update dependency nuget.commandline to v6.3.1
FantasticFiasco/mvvm-dialogs
build/build.cake
build/build.cake
#tool nuget:?package=NuGet.CommandLine&version=6.3.1 #load utils.cake ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // VARIABLES ////////////////////////////////////////////////////////////////////// var solution = new FilePath("./../MvvmDialogs.sln"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Description("Clean all files") .Does(() => { DeleteFiles("./../**/*.nupkg"); CleanDirectories("./../**/bin"); CleanDirectories("./../**/obj"); }); Task("Restore") .Description("Restore NuGet packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solution); }); Task("Build") .Description("Build the solution") .IsDependentOn("Restore") .Does(() => { MSBuild( solution, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2022, Configuration = configuration, MaxCpuCount = 0, // Enable parallel build }); }); Task("Pack") .Description("Create NuGet package") .IsDependentOn("Build") .Does(() => { var versionPrefix = GetVersionPrefix("./../Directory.Build.props"); var versionSuffix = GetVersionSuffix("./../Directory.Build.props"); var isTag = EnvironmentVariable("APPVEYOR_REPO_TAG"); // Unless this is a tag, this is a pre-release if (isTag != "true") { var sha = EnvironmentVariable("APPVEYOR_REPO_COMMIT"); versionSuffix = $"sha-{sha}"; } NuGetPack( "./../MvvmDialogs.nuspec", new NuGetPackSettings { Version = versionPrefix, Suffix = versionSuffix, Symbols = true, ArgumentCustomization = args => args.Append("-SymbolPackageFormat snupkg") }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Pack"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
#tool nuget:?package=NuGet.CommandLine&version=6.3.0 #load utils.cake ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // VARIABLES ////////////////////////////////////////////////////////////////////// var solution = new FilePath("./../MvvmDialogs.sln"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Description("Clean all files") .Does(() => { DeleteFiles("./../**/*.nupkg"); CleanDirectories("./../**/bin"); CleanDirectories("./../**/obj"); }); Task("Restore") .Description("Restore NuGet packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solution); }); Task("Build") .Description("Build the solution") .IsDependentOn("Restore") .Does(() => { MSBuild( solution, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2022, Configuration = configuration, MaxCpuCount = 0, // Enable parallel build }); }); Task("Pack") .Description("Create NuGet package") .IsDependentOn("Build") .Does(() => { var versionPrefix = GetVersionPrefix("./../Directory.Build.props"); var versionSuffix = GetVersionSuffix("./../Directory.Build.props"); var isTag = EnvironmentVariable("APPVEYOR_REPO_TAG"); // Unless this is a tag, this is a pre-release if (isTag != "true") { var sha = EnvironmentVariable("APPVEYOR_REPO_COMMIT"); versionSuffix = $"sha-{sha}"; } NuGetPack( "./../MvvmDialogs.nuspec", new NuGetPackSettings { Version = versionPrefix, Suffix = versionSuffix, Symbols = true, ArgumentCustomization = args => args.Append("-SymbolPackageFormat snupkg") }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Pack"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
apache-2.0
C#
da8d88bae55c301e9947d9b7708b439608d42ae1
update dependency nuget.commandline to v6.2.0
FantasticFiasco/mvvm-dialogs
build/build.cake
build/build.cake
#tool nuget:?package=NuGet.CommandLine&version=6.2.0 #load utils.cake ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // VARIABLES ////////////////////////////////////////////////////////////////////// var solution = new FilePath("./../MvvmDialogs.sln"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Description("Clean all files") .Does(() => { DeleteFiles("./../**/*.nupkg"); CleanDirectories("./../**/bin"); CleanDirectories("./../**/obj"); }); Task("Restore") .Description("Restore NuGet packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solution); }); Task("Build") .Description("Build the solution") .IsDependentOn("Restore") .Does(() => { MSBuild( solution, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2022, Configuration = configuration, MaxCpuCount = 0, // Enable parallel build }); }); Task("Pack") .Description("Create NuGet package") .IsDependentOn("Build") .Does(() => { var versionPrefix = GetVersionPrefix("./../Directory.Build.props"); var versionSuffix = GetVersionSuffix("./../Directory.Build.props"); var isTag = EnvironmentVariable("APPVEYOR_REPO_TAG"); // Unless this is a tag, this is a pre-release if (isTag != "true") { var sha = EnvironmentVariable("APPVEYOR_REPO_COMMIT"); versionSuffix = $"sha-{sha}"; } NuGetPack( "./../MvvmDialogs.nuspec", new NuGetPackSettings { Version = versionPrefix, Suffix = versionSuffix, Symbols = true, ArgumentCustomization = args => args.Append("-SymbolPackageFormat snupkg") }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Pack"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
#tool nuget:?package=NuGet.CommandLine&version=6.1.0 #load utils.cake ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // VARIABLES ////////////////////////////////////////////////////////////////////// var solution = new FilePath("./../MvvmDialogs.sln"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Description("Clean all files") .Does(() => { DeleteFiles("./../**/*.nupkg"); CleanDirectories("./../**/bin"); CleanDirectories("./../**/obj"); }); Task("Restore") .Description("Restore NuGet packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solution); }); Task("Build") .Description("Build the solution") .IsDependentOn("Restore") .Does(() => { MSBuild( solution, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2022, Configuration = configuration, MaxCpuCount = 0, // Enable parallel build }); }); Task("Pack") .Description("Create NuGet package") .IsDependentOn("Build") .Does(() => { var versionPrefix = GetVersionPrefix("./../Directory.Build.props"); var versionSuffix = GetVersionSuffix("./../Directory.Build.props"); var isTag = EnvironmentVariable("APPVEYOR_REPO_TAG"); // Unless this is a tag, this is a pre-release if (isTag != "true") { var sha = EnvironmentVariable("APPVEYOR_REPO_COMMIT"); versionSuffix = $"sha-{sha}"; } NuGetPack( "./../MvvmDialogs.nuspec", new NuGetPackSettings { Version = versionPrefix, Suffix = versionSuffix, Symbols = true, ArgumentCustomization = args => args.Append("-SymbolPackageFormat snupkg") }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Pack"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
apache-2.0
C#
b11d8951efa8746b6a0caf26b9f4f45e472611ab
Add namespace that shouldn't have been removed in inital sweep
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX
Modix.Services/Core/AuthorizationAutoConfigBehavior.cs
Modix.Services/Core/AuthorizationAutoConfigBehavior.cs
using System; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using Modix.Services.Moderation; namespace Modix.Services.Core { /// <summary> /// Implements a behavior that automatically performs configuration necessary for an <see cref="IAuthorizationService"/> to work. /// </summary> public class AuthorizationAutoConfigBehavior : BehaviorBase { // TODO: Abstract DiscordSocketClient to IDiscordSocketClient, or something, to make this testable /// <summary> /// Constructs a new <see cref="ModerationAutoConfigBehavior"/> object, with the given injected dependencies. /// See <see cref="BehaviorBase"/> for more details. /// </summary> /// <param name="discordClient">The value to use for <see cref="DiscordClient"/>.</param> /// <param name="serviceProvider">See <see cref="BehaviorBase"/>.</param> public AuthorizationAutoConfigBehavior(DiscordSocketClient discordClient, IServiceProvider serviceProvider) : base(serviceProvider) { DiscordClient = discordClient; } /// <inheritdoc /> internal protected override Task OnStartingAsync() { DiscordClient.GuildAvailable += OnGuildAvailable; DiscordClient.LeftGuild += OnLeftGuild; return Task.CompletedTask; } /// <inheritdoc /> internal protected override Task OnStoppedAsync() { DiscordClient.GuildAvailable -= OnGuildAvailable; DiscordClient.LeftGuild -= OnLeftGuild; return Task.CompletedTask; } /// <inheritdoc /> internal protected override void Dispose(bool disposeManaged) { if (disposeManaged && IsRunning) OnStoppedAsync(); base.Dispose(disposeManaged); } // TODO: Abstract DiscordSocketClient to IDiscordSocketClient, or something, to make this testable /// <summary> /// A <see cref="DiscordSocketClient"/> for interacting with, and receiving events from, the Discord API. /// </summary> internal protected DiscordSocketClient DiscordClient { get; } private Task OnGuildAvailable(IGuild guild) => SelfExecuteRequest<IAuthorizationService>(x => x.AutoConfigureGuildAsync(guild)); private Task OnLeftGuild(IGuild guild) => SelfExecuteRequest<IAuthorizationService>(x => x.UnConfigureGuildAsync(guild)); } }
using System; using System.Threading.Tasks; using Discord; using Discord.WebSocket; namespace Modix.Services.Core { /// <summary> /// Implements a behavior that automatically performs configuration necessary for an <see cref="IAuthorizationService"/> to work. /// </summary> public class AuthorizationAutoConfigBehavior : BehaviorBase { // TODO: Abstract DiscordSocketClient to IDiscordSocketClient, or something, to make this testable /// <summary> /// Constructs a new <see cref="ModerationAutoConfigBehavior"/> object, with the given injected dependencies. /// See <see cref="BehaviorBase"/> for more details. /// </summary> /// <param name="discordClient">The value to use for <see cref="DiscordClient"/>.</param> /// <param name="serviceProvider">See <see cref="BehaviorBase"/>.</param> public AuthorizationAutoConfigBehavior(DiscordSocketClient discordClient, IServiceProvider serviceProvider) : base(serviceProvider) { DiscordClient = discordClient; } /// <inheritdoc /> internal protected override Task OnStartingAsync() { DiscordClient.GuildAvailable += OnGuildAvailable; DiscordClient.LeftGuild += OnLeftGuild; return Task.CompletedTask; } /// <inheritdoc /> internal protected override Task OnStoppedAsync() { DiscordClient.GuildAvailable -= OnGuildAvailable; DiscordClient.LeftGuild -= OnLeftGuild; return Task.CompletedTask; } /// <inheritdoc /> internal protected override void Dispose(bool disposeManaged) { if (disposeManaged && IsRunning) OnStoppedAsync(); base.Dispose(disposeManaged); } // TODO: Abstract DiscordSocketClient to IDiscordSocketClient, or something, to make this testable /// <summary> /// A <see cref="DiscordSocketClient"/> for interacting with, and receiving events from, the Discord API. /// </summary> internal protected DiscordSocketClient DiscordClient { get; } private Task OnGuildAvailable(IGuild guild) => SelfExecuteRequest<IAuthorizationService>(x => x.AutoConfigureGuildAsync(guild)); private Task OnLeftGuild(IGuild guild) => SelfExecuteRequest<IAuthorizationService>(x => x.UnConfigureGuildAsync(guild)); } }
mit
C#
c12f34b534143e7e517338673e9db9ed734d215d
correct casing of this key
bugsnag/bugsnag-dotnet,bugsnag/bugsnag-dotnet
src/Bugsnag/Report/Breadcrumb.cs
src/Bugsnag/Report/Breadcrumb.cs
using System; using System.Collections.Generic; namespace Bugsnag { public class Breadcrumb : Dictionary<string, object> { public static Breadcrumb FromReport(Report report) { var name = report.OriginalException.GetType().ToString(); var type = BreadcrumbType.Error; var metadata = new Dictionary<string, string> { { "message", report.OriginalException.Message }, { "severity", report.OriginalSeverity.ToString() }, }; return new Breadcrumb(name, type, metadata); } public Breadcrumb(string name, BreadcrumbType type) : this(name, type, null) { } public Breadcrumb(string name, BreadcrumbType type, IDictionary<string, string> metadata) { this["name"] = name; // limit this to 30 characters? provide a default incase of null or empty? this["timestamp"] = DateTime.UtcNow; this.AddToPayload("metaData", metadata); // can we limit the size of this somehow? Should it be <string, object>? switch (type) { case BreadcrumbType.Navigation: this["type"] = "navigation"; break; case BreadcrumbType.Request: this["type"] = "request"; break; case BreadcrumbType.Process: this["type"] = "process"; break; case BreadcrumbType.Log: this["type"] = "log"; break; case BreadcrumbType.User: this["type"] = "user"; break; case BreadcrumbType.State: this["type"] = "state"; break; case BreadcrumbType.Error: this["type"] = "error"; break; case BreadcrumbType.Manual: default: this["type"] = "manual"; break; } } } }
using System; using System.Collections.Generic; namespace Bugsnag { public class Breadcrumb : Dictionary<string, object> { public static Breadcrumb FromReport(Report report) { var name = report.OriginalException.GetType().ToString(); var type = BreadcrumbType.Error; var metadata = new Dictionary<string, string> { { "message", report.OriginalException.Message }, { "severity", report.OriginalSeverity.ToString() }, }; return new Breadcrumb(name, type, metadata); } public Breadcrumb(string name, BreadcrumbType type) : this(name, type, null) { } public Breadcrumb(string name, BreadcrumbType type, IDictionary<string, string> metadata) { this["name"] = name; // limit this to 30 characters? provide a default incase of null or empty? this["timestamp"] = DateTime.UtcNow; this.AddToPayload("metadata", metadata); // can we limit the size of this somehow? Should it be <string, object>? switch (type) { case BreadcrumbType.Navigation: this["type"] = "navigation"; break; case BreadcrumbType.Request: this["type"] = "request"; break; case BreadcrumbType.Process: this["type"] = "process"; break; case BreadcrumbType.Log: this["type"] = "log"; break; case BreadcrumbType.User: this["type"] = "user"; break; case BreadcrumbType.State: this["type"] = "state"; break; case BreadcrumbType.Error: this["type"] = "error"; break; case BreadcrumbType.Manual: default: this["type"] = "manual"; break; } } } }
mit
C#
12c888808178a52f8082a7d0e3745aa4a898c2d3
Update NotesRepository.cs
CarmelSoftware/MVCDataRepositoryXML
Models/NotesRepository.cs
Models/NotesRepository.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xml.Linq; namespace IoCDependencyInjection.Models { public class NotesRepository : INotesRepository { private List<Note> notes = new List<Note>(); private int iNumberOfEntries = 1; private XDocument doc; public NotesRepository() { doc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/data.xml")); foreach (var node in doc.Descendants("note")) { notes.Add(new Note { ID = Int32.Parse(node.Descendants("id").FirstOrDefault().Value), To = node.Descendants("to").FirstOrDefault().Value, From = node.Descendants("from").FirstOrDefault().Value, Heading = node.Descendants("heading").FirstOrDefault().Value, Body = node.Descendants("body").FirstOrDefault().Value }); } iNumberOfEntries = notes.Count; } public IEnumerable<Note> GetAll() { return notes; }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xml.Linq; namespace IoCDependencyInjection.Models { public class NotesRepository : INotesRepository { private List<Note> notes = new List<Note>(); private int iNumberOfEntries = 1; private XDocument doc; public NotesRepository() { doc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/data.xml")); foreach (var node in doc.Descendants("note")) { notes.Add(new Note { ID = Int32.Parse(node.Descendants("id").FirstOrDefault().Value), To = node.Descendants("to").FirstOrDefault().Value, From = node.Descendants("from").FirstOrDefault().Value, Heading = node.Descendants("heading").FirstOrDefault().Value, Body = node.Descendants("body").FirstOrDefault().Value }); } iNumberOfEntries = notes.Count; }
mit
C#
d50da70e09d9c481491411dc54a48a41f9022bde
Use constant.
JohanLarsson/Gu.Wpf.UiAutomation
Gu.Wpf.UiAutomation.UiTests/Elements/ToolTipTests.cs
Gu.Wpf.UiAutomation.UiTests/Elements/ToolTipTests.cs
namespace Gu.Wpf.UiAutomation.UiTests.Elements { using NUnit.Framework; public class ToolTipTests { private const string ExeFileName = "WpfApplication.exe"; private const string Window = "ToolTipWindow"; [Test] public void FindImplicit() { using var app = Application.Launch(ExeFileName, Window); var window = app.MainWindow; var button = window.FindButton("With ToolTip"); Mouse.Position = button.Bounds.Center(); var toolTip = button.FindToolTip(); Assert.AreEqual(false, toolTip.IsOffscreen); Assert.AreEqual("Tool tip text.", toolTip.Text); Assert.IsInstanceOf<ToolTip>(UiElement.FromAutomationElement(toolTip.AutomationElement)); window.FindButton("Lose focus").Click(); Assert.AreEqual(true, toolTip.IsOffscreen); } [Test] public void FindExplicit() { using var app = Application.Launch(ExeFileName, Window); var window = app.MainWindow; var button = window.FindButton("With explicit ToolTip"); Mouse.Position = button.Bounds.Center(); var toolTip = button.FindToolTip(); Assert.AreEqual(false, toolTip.IsOffscreen); Assert.AreEqual("Explicit tool tip text.", toolTip.Text); Assert.IsInstanceOf<ToolTip>(UiElement.FromAutomationElement(toolTip.AutomationElement)); window.FindButton("Lose focus").Click(); Assert.AreEqual(true, toolTip.IsOffscreen); } } }
namespace Gu.Wpf.UiAutomation.UiTests.Elements { using NUnit.Framework; public class ToolTipTests { private const string ExeFileName = "WpfApplication.exe"; [Test] public void FindImplicit() { using var app = Application.Launch(ExeFileName, "ToolTipWindow"); var window = app.MainWindow; var button = window.FindButton("With ToolTip"); Mouse.Position = button.Bounds.Center(); var toolTip = button.FindToolTip(); Assert.AreEqual(false, toolTip.IsOffscreen); Assert.AreEqual("Tool tip text.", toolTip.Text); Assert.IsInstanceOf<ToolTip>(UiElement.FromAutomationElement(toolTip.AutomationElement)); window.FindButton("Lose focus").Click(); Assert.AreEqual(true, toolTip.IsOffscreen); } [Test] public void FindExplicit() { using var app = Application.Launch(ExeFileName, "ToolTipWindow"); var window = app.MainWindow; var button = window.FindButton("With explicit ToolTip"); Mouse.Position = button.Bounds.Center(); var toolTip = button.FindToolTip(); Assert.AreEqual(false, toolTip.IsOffscreen); Assert.AreEqual("Explicit tool tip text.", toolTip.Text); Assert.IsInstanceOf<ToolTip>(UiElement.FromAutomationElement(toolTip.AutomationElement)); window.FindButton("Lose focus").Click(); Assert.AreEqual(true, toolTip.IsOffscreen); } } }
mit
C#
6b9be4db0586d8bc5327b10e57740adca885daf0
save video bookmarks
hamstercat/Emby.Channels,hamstercat/Emby.Channels,heksesang/Emby.Channels,heksesang/Emby.Channels,MediaBrowser/Emby.Channels,MediaBrowser/Emby.Channels
MediaBrowser.Channels.IPTV/Api/ServerApiEndpoints.cs
MediaBrowser.Channels.IPTV/Api/ServerApiEndpoints.cs
using MediaBrowser.Channels.IPTV.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Model.MediaInfo; using ServiceStack; using System; using System.Linq; namespace MediaBrowser.Channels.IPTV.Api { [Route("/Iptv/Bookmarks", "POST", Summary = "Bookmarks a video")] public class VideoSend : IReturnVoid { [ApiMember(Name = "Name", Description = "Name", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")] public string Name { get; set; } [ApiMember(Name = "Path", Description = "Path", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] public string Path { get; set; } [ApiMember(Name = "UserId", Description = "UserId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] public string UserId { get; set; } [ApiMember(Name = "Protocol", Description = "Protocol", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] public MediaProtocol Protocol { get; set; } [ApiMember(Name = "ImagePath", Description = "ImagePath", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")] public string ImagePath { get; set; } } class ServerApiEndpoints : IRestfulService { public void Post(VideoSend request) { if (string.IsNullOrWhiteSpace(request.Name)) { throw new ArgumentException("Name cannot be empty."); } if (string.IsNullOrWhiteSpace(request.Path)) { throw new ArgumentException("Path cannot be empty."); } if (string.IsNullOrWhiteSpace(request.UserId)) { throw new ArgumentException("UserId cannot be empty."); } var list = Plugin.Instance.Configuration.Bookmarks.ToList(); list.Add(new Bookmark { Name = request.Name, Image = request.ImagePath, Path = request.Path, Protocol = request.Protocol }); Plugin.Instance.Configuration.Bookmarks = list.ToArray(); Plugin.Instance.SaveConfiguration(); } } }
using MediaBrowser.Channels.IPTV.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Model.MediaInfo; using ServiceStack; using System; using System.Linq; namespace MediaBrowser.Channels.IPTV.Api { [Route("/Iptv/Bookmarks", "POST", Summary = "Bookmarks a video")] public class VideoSend : IReturnVoid { [ApiMember(Name = "Name", Description = "Name", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")] public string Name { get; set; } [ApiMember(Name = "Path", Description = "Path", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] public string Path { get; set; } [ApiMember(Name = "UserId", Description = "UserId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] public string UserId { get; set; } [ApiMember(Name = "Protocol", Description = "Protocol", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] public MediaProtocol Protocol { get; set; } [ApiMember(Name = "ImagePath", Description = "ImagePath", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")] public string ImagePath { get; set; } } class ServerApiEndpoints : IRestfulService { public void Post(VideoSend request) { if (string.IsNullOrWhiteSpace(request.Name)) { throw new ArgumentException("Name cannot be empty."); } if (string.IsNullOrWhiteSpace(request.Path)) { throw new ArgumentException("Path cannot be empty."); } if (string.IsNullOrWhiteSpace(request.UserId)) { throw new ArgumentException("UserId cannot be empty."); } var list = Plugin.Instance.Configuration.Bookmarks.ToList(); list.Add(new Bookmark { Name = request.Name, Image = request.ImagePath, Path = request.Path, Protocol = request.Protocol }); Plugin.Instance.Configuration.Bookmarks = list.ToArray(); } } }
mit
C#
f346526be026c99ccd2d866a0ebcd692a5db666f
change test
Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017
PhotoArtSystem/Tests/PhotoArtSystem.Tests.IntegrationTests/DummyContextTest.cs
PhotoArtSystem/Tests/PhotoArtSystem.Tests.IntegrationTests/DummyContextTest.cs
namespace PhotoArtSystem.Tests.IntegrationTests { using System.Linq; using Data; using NUnit.Framework; [TestFixture] public class DummyContextTest { [Test] [TestCase("admin@admin.com")] public void Db_ShouldHaveOnlyOneUserWithSuchEmail(string email) { // Arrange ApplicationDbContext context = new ApplicationDbContext(); // Act int usersCount = context.Users.Where(x => x.Email == email).Count(); // Assert Assert.AreEqual(1, usersCount); } } }
namespace PhotoArtSystem.Tests.IntegrationTests { using System.Linq; using Data; using NUnit.Framework; [TestFixture] public class DummyContextTest { [Test] public void TestMethod() { // Arrange ApplicationDbContext context = new ApplicationDbContext(); // Act int usersCount = context.Users.Count(); // Assert Assert.AreEqual(1, usersCount); } } }
mit
C#
cc88c6c598157a8b863a023634c05c71c0789449
Fix Who's on First
samfun123/KtaneTwitchPlays,CaitSith2/KtaneTwitchPlays
TwitchPlaysAssembly/Src/ComponentSolvers/Vanilla/WhosOnFirstComponentSolver.cs
TwitchPlaysAssembly/Src/ComponentSolvers/Vanilla/WhosOnFirstComponentSolver.cs
using System; using System.Collections; using System.Linq; using Assets.Scripts.Rules; using UnityEngine; public class WhosOnFirstComponentSolver : ComponentSolver { public WhosOnFirstComponentSolver(TwitchModule module) : base(module) { _buttons = ((WhosOnFirstComponent) module.BombComponent).Buttons; ModInfo = ComponentSolverFactory.GetModuleInfo("WhosOnFirstComponentSolver", "!{0} what? [press the button that says \"WHAT?\"] | !{0} press 3 [press the third button in english reading order] | The phrase must match exactly | Not case sensitive", "Who%E2%80%99s on First"); } private static readonly string[] Phrases = { "ready", "first", "no", "blank", "nothing", "yes", "what", "uhhh", "left", "right", "middle", "okay", "wait", "press", "you", "you are", "your", "you're", "ur", "u", "uh huh", "uh uh", "what?", "done", "next", "hold", "sure", "like" }; protected internal override IEnumerator RespondToCommandInternal(string inputCommand) { inputCommand = inputCommand.ToLowerInvariant().Trim(); string[] split = inputCommand.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (split.Length == 2 && split[0] == "press" && int.TryParse(split[1], out int buttonIndex) && buttonIndex > 0 && buttonIndex < 7) { _buttons[buttonIndex - 1].Interact(); } else { if (!Phrases.Contains(inputCommand)) { yield return null; yield return $"sendtochaterror The word \"{inputCommand}\" isn't a valid word."; yield break; } foreach (KeypadButton button in _buttons) { if (!inputCommand.Equals(button.GetText(), StringComparison.InvariantCultureIgnoreCase)) continue; yield return null; button.Interact(); yield return new WaitForSeconds(0.1f); yield break; } yield return null; yield return "unsubmittablepenalty"; } } protected override IEnumerator ForcedSolveIEnumerator() { yield return null; while (!Module.BombComponent.IsActive) yield return true; var wof = (WhosOnFirstComponent) Module.BombComponent; while (!Module.Solved) { while (!wof.ButtonsEmerged || wof.CurrentDisplayWordIndex < 0) yield return true; string displayText = wof.DisplayText.text; var buttonText = _buttons.Select(x => x.GetText()).ToList(); var precedenceList = RuleManager.Instance.WhosOnFirstRuleSet.precedenceMap[buttonText[RuleManager.Instance.WhosOnFirstRuleSet.displayWordToButtonIndexMap[displayText]]]; int index = int.MaxValue; for (int i = 0; i < 6; i++) { if (precedenceList.IndexOf(buttonText[i]) < index) index = precedenceList.IndexOf(buttonText[i]); } yield return DoInteractionClick(_buttons[buttonText.IndexOf(precedenceList[index])]); } } private readonly KeypadButton[] _buttons; }
using System; using System.Collections; using System.Linq; using Assets.Scripts.Rules; using UnityEngine; public class WhosOnFirstComponentSolver : ComponentSolver { public WhosOnFirstComponentSolver(TwitchModule module) : base(module) { _buttons = ((WhosOnFirstComponent) module.BombComponent).Buttons; ModInfo = ComponentSolverFactory.GetModuleInfo("WhosOnFirstComponentSolver", "!{0} what? [press the button that says \"WHAT?\"] | !{0} press 3 [press the third button in english reading order] | The phrase must match exactly | Not case sensitive", "Who%E2%80%99s on First"); } private static readonly string[] Phrases = { "ready", "first", "no", "blank", "nothing", "yes", "what", "uhhh", "left", "right", "middle", "okay", "wait", "press", "you", "you are", "your", "you're", "ur", "u", "uh huh", "uh uh", "what?", "done", "next", "hold", "sure", "like" }; protected internal override IEnumerator RespondToCommandInternal(string inputCommand) { inputCommand = inputCommand.ToLowerInvariant().Trim(); string[] split = inputCommand.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (split[0] == "press" && int.TryParse(split[1], out int buttonIndex) && buttonIndex > 0 && buttonIndex < 7) { _buttons[buttonIndex - 1].Interact(); } else { if (!Phrases.Contains(inputCommand)) { yield return null; yield return $"sendtochaterror The word \"{inputCommand}\" isn't a valid word."; yield break; } foreach (KeypadButton button in _buttons) { if (!inputCommand.Equals(button.GetText(), StringComparison.InvariantCultureIgnoreCase)) continue; yield return null; button.Interact(); yield return new WaitForSeconds(0.1f); yield break; } yield return null; yield return "unsubmittablepenalty"; } } protected override IEnumerator ForcedSolveIEnumerator() { yield return null; while (!Module.BombComponent.IsActive) yield return true; var wof = (WhosOnFirstComponent) Module.BombComponent; while (!Module.Solved) { while (!wof.ButtonsEmerged || wof.CurrentDisplayWordIndex < 0) yield return true; string displayText = wof.DisplayText.text; var buttonText = _buttons.Select(x => x.GetText()).ToList(); var precedenceList = RuleManager.Instance.WhosOnFirstRuleSet.precedenceMap[buttonText[RuleManager.Instance.WhosOnFirstRuleSet.displayWordToButtonIndexMap[displayText]]]; int index = int.MaxValue; for (int i = 0; i < 6; i++) { if (precedenceList.IndexOf(buttonText[i]) < index) index = precedenceList.IndexOf(buttonText[i]); } yield return DoInteractionClick(_buttons[buttonText.IndexOf(precedenceList[index])]); } } private readonly KeypadButton[] _buttons; }
mit
C#
8f89f53b0991cb6ab6bb509dd6b1f43715012335
Update IPixelBandGetter.cs
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
src/RasterIO/IPixelBandGetter.cs
src/RasterIO/IPixelBandGetter.cs
// Contributors: // James Domingo, Green Code LLC namespace Landis.RasterIO { /// <summary> /// Gets the value for a particular band in a pixel as a specific data type. /// </summary> public interface IPixelBandGetter<T> where T : struct { T GetValue(); } }
// Copyright 2010 Green Code LLC // All rights reserved. // // The copyright holders license this file under the New (3-clause) BSD // License (the "License"). You may not use this file except in // compliance with the License. A copy of the License is available at // // http://www.opensource.org/licenses/BSD-3-Clause // // and is included in the NOTICE.txt file distributed with this work. // // Contributors: // James Domingo, Green Code LLC namespace Landis.RasterIO { /// <summary> /// Gets the value for a particular band in a pixel as a specific data type. /// </summary> public interface IPixelBandGetter<T> where T : struct { T GetValue(); } }
apache-2.0
C#
e0136642ef147c66dcd85ed83b68aa655e359172
Remove unused method
honestegg/cassette,andrewdavey/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,BluewireTechnologies/cassette,damiensawyer/cassette,damiensawyer/cassette,honestegg/cassette,andrewdavey/cassette,damiensawyer/cassette,honestegg/cassette
src/Website/Views/Helpers.cs
src/Website/Views/Helpers.cs
using System.Web.Mvc; namespace Website.Views { public static class Helpers { public static string DocumentationUrl(this UrlHelper urlHelper, string path) { return urlHelper.RouteUrl("Documentation", new { path }); } } }
using System; using System.Web.Mvc; namespace Website.Views { public static class Helpers { public static string DocumentationUrl(this UrlHelper urlHelper, string path) { return urlHelper.RouteUrl("Documentation", new { path }); } public static string ToPublicUrl(this UrlHelper urlHelper, string relativeUrl) { var httpContext = urlHelper.RequestContext.HttpContext; var uriBuilder = new UriBuilder { Host = httpContext.Request.Url.Host, Path = "/", Port = 80, Scheme = "http", }; if (httpContext.Request.IsLocal) { uriBuilder.Port = httpContext.Request.Url.Port; } return new Uri(uriBuilder.Uri, relativeUrl).AbsoluteUri; } } }
mit
C#
f9fa7c86eaa169657485dbdaabf975abbedcc65c
Cover mapping fully for catch mods
ppy/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new
osu.Game.Rulesets.Catch.Tests/CatchLegacyModConversionTest.cs
osu.Game.Rulesets.Catch.Tests/CatchLegacyModConversionTest.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 NUnit.Framework; using osu.Game.Beatmaps.Legacy; using osu.Game.Rulesets.Catch.Mods; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class CatchLegacyModConversionTest : LegacyModConversionTest { private static readonly object[][] catch_mod_mapping = { new object[] { LegacyMods.NoFail, new[] { typeof(CatchModNoFail) } }, new object[] { LegacyMods.Easy, new[] { typeof(CatchModEasy) } }, new object[] { LegacyMods.Hidden, new[] { typeof(CatchModHidden) } }, new object[] { LegacyMods.HardRock, new[] { typeof(CatchModHardRock) } }, new object[] { LegacyMods.SuddenDeath, new[] { typeof(CatchModSuddenDeath) } }, new object[] { LegacyMods.DoubleTime, new[] { typeof(CatchModDoubleTime) } }, new object[] { LegacyMods.Relax, new[] { typeof(CatchModRelax) } }, new object[] { LegacyMods.HalfTime, new[] { typeof(CatchModHalfTime) } }, new object[] { LegacyMods.Nightcore, new[] { typeof(CatchModNightcore) } }, new object[] { LegacyMods.Flashlight, new[] { typeof(CatchModFlashlight) } }, new object[] { LegacyMods.Autoplay, new[] { typeof(CatchModAutoplay) } }, new object[] { LegacyMods.Perfect, new[] { typeof(CatchModPerfect) } }, new object[] { LegacyMods.Cinema, new[] { typeof(CatchModCinema) } }, new object[] { LegacyMods.HardRock | LegacyMods.DoubleTime, new[] { typeof(CatchModHardRock), typeof(CatchModDoubleTime) } } }; [TestCaseSource(nameof(catch_mod_mapping))] [TestCase(LegacyMods.Cinema | LegacyMods.Autoplay, new[] { typeof(CatchModCinema) })] [TestCase(LegacyMods.Nightcore | LegacyMods.DoubleTime, new[] { typeof(CatchModNightcore) })] [TestCase(LegacyMods.Perfect | LegacyMods.SuddenDeath, new[] { typeof(CatchModPerfect) })] public new void TestFromLegacy(LegacyMods legacyMods, Type[] expectedMods) => base.TestFromLegacy(legacyMods, expectedMods); [TestCaseSource(nameof(catch_mod_mapping))] public new void TestToLegacy(LegacyMods legacyMods, Type[] givenMods) => base.TestToLegacy(legacyMods, givenMods); protected override Ruleset CreateRuleset() => new CatchRuleset(); } }
// 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 NUnit.Framework; using osu.Game.Beatmaps.Legacy; using osu.Game.Rulesets.Catch.Mods; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class CatchLegacyModConversionTest : LegacyModConversionTest { [TestCase(LegacyMods.Easy, new[] { typeof(CatchModEasy) })] [TestCase(LegacyMods.HardRock | LegacyMods.DoubleTime, new[] { typeof(CatchModHardRock), typeof(CatchModDoubleTime) })] [TestCase(LegacyMods.DoubleTime, new[] { typeof(CatchModDoubleTime) })] [TestCase(LegacyMods.Nightcore, new[] { typeof(CatchModNightcore) })] [TestCase(LegacyMods.Nightcore | LegacyMods.DoubleTime, new[] { typeof(CatchModNightcore) })] [TestCase(LegacyMods.Flashlight | LegacyMods.Nightcore | LegacyMods.DoubleTime, new[] { typeof(CatchModFlashlight), typeof(CatchModNightcore) })] [TestCase(LegacyMods.Perfect, new[] { typeof(CatchModPerfect) })] [TestCase(LegacyMods.SuddenDeath, new[] { typeof(CatchModSuddenDeath) })] [TestCase(LegacyMods.Perfect | LegacyMods.SuddenDeath, new[] { typeof(CatchModPerfect) })] [TestCase(LegacyMods.Perfect | LegacyMods.SuddenDeath | LegacyMods.DoubleTime, new[] { typeof(CatchModDoubleTime), typeof(CatchModPerfect) })] public new void TestFromLegacy(LegacyMods legacyMods, Type[] expectedMods) => base.TestFromLegacy(legacyMods, expectedMods); protected override Ruleset CreateRuleset() => new CatchRuleset(); } }
mit
C#
c9123df98c2772c98a37161b51e796ceb5e8bc94
Change version up to 1.1.0
matiasbeckerle/breakout,matiasbeckerle/perspektiva,matiasbeckerle/arkanoid
source/Assets/Scripts/Loader.cs
source/Assets/Scripts/Loader.cs
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("1.1.0.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("1.0.0.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
unknown
C#
fb20af139efa4965b45e7953cea1bdefd8966a91
Implement operator == and != for ValueObject
EamonNerbonne/ValueUtils,EamonNerbonne/ValueUtils,EamonNerbonne/ValueUtils
ValueUtils/ValueObject.cs
ValueUtils/ValueObject.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ValueUtils { public abstract class ValueObject<T> : IEquatable<T> where T : ValueObject<T> { //CRTP to encourage you to use the value type itself as the type parameter. //However, we cannot prevent the following: ClassA : ValueObject<ClassA> //and ClassB : ValueObject<ClassA> //If you do that, then GetHashCode and Equals will crash with an invalid cast exception. static readonly Func<T, T, bool> equalsFunc = FieldwiseEquality<T>.Instance; static readonly Func<T, int> hashFunc = FieldwiseHasher<T>.Instance; static ValueObject() { if (!typeof(T).IsSealed) throw new NotSupportedException("Value objects must be sealed."); } public override bool Equals(object obj) { return obj is T && equalsFunc((T)this, (T)obj); } public bool Equals(T obj) { return obj != null && equalsFunc((T)this, obj); } public override int GetHashCode() { return hashFunc((T)this); } public static bool operator !=(ValueObject<T> a, T b) { return !equalsFunc((T)a, b); } public static bool operator ==(ValueObject<T> a, T b) { return equalsFunc((T)a, b); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ValueUtils { public abstract class ValueObject<T> : IEquatable<T> where T : ValueObject<T> { //CRTP to encourage you to use the value type itself as the type parameter. //However, we cannot prevent the following: ClassA : ValueObject<ClassA> //and ClassB : ValueObject<ClassA> //If you do that, then GetHashCode and Equals will crash with an invalid cast exception. static readonly Func<T, T, bool> equalsFunc = FieldwiseEquality<T>.Instance; static readonly Func<T, int> hashFunc = FieldwiseHasher<T>.Instance; static ValueObject() { if (!typeof(T).IsSealed) throw new NotSupportedException("Value objects must be sealed."); } public override bool Equals(object obj) { return obj is T && equalsFunc((T)this, (T)obj); } public bool Equals(T obj) { return obj != null && equalsFunc((T)this, obj); } public override int GetHashCode() { return hashFunc((T)this); } } }
apache-2.0
C#
27eb8df34ffaf4fa277635b3734a4364b50fd882
Return empty reference path.
aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate
src/Abp.AspNetCore/AspNetCore/PlugIn/AbpPlugInAssemblyPart.cs
src/Abp.AspNetCore/AspNetCore/PlugIn/AbpPlugInAssemblyPart.cs
using System.Collections.Generic; using System.Reflection; using System.Linq; using Microsoft.AspNetCore.Mvc.ApplicationParts; namespace Abp.AspNetCore.PlugIn { public class AbpPlugInAssemblyPart : AssemblyPart, ICompilationReferencesProvider { public AbpPlugInAssemblyPart(Assembly assembly) : base(assembly) { } IEnumerable<string> ICompilationReferencesProvider.GetReferencePaths() => Enumerable.Empty<string>(); } }
using System.Collections.Generic; using System.Reflection; using Microsoft.AspNetCore.Mvc.ApplicationParts; namespace Abp.AspNetCore.PlugIn { public class AbpPlugInAssemblyPart : AssemblyPart, ICompilationReferencesProvider { public AbpPlugInAssemblyPart(Assembly assembly) : base(assembly) { } IEnumerable<string> ICompilationReferencesProvider.GetReferencePaths() { return new[] { Assembly.Location }; } } }
mit
C#
d3875941a4340995c158ec7d9232786cc774171f
Add utility method for forcing object validation
mattgwagner/CertiPay.Common
CertiPay.Common/Utilities.cs
CertiPay.Common/Utilities.cs
namespace CertiPay.Common { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Reflection; using System.Transactions; public static class Utilities { /// <summary> /// Starts a new transaction scope with the given isolation level /// </summary> /// <returns></returns> public static TransactionScope StartTrx(IsolationLevel Isolation = IsolationLevel.ReadUncommitted) { return new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = Isolation }); } /// <summary> /// Performs manual validation of the object using the data annotations, returning /// true if it passes and provides a list of results from the validation /// </summary> /// <remarks> /// Make sure that you have any necessary resources loaded (i.e. CertiPay.Resources) for error messages /// or else this will always return true!!! /// </remarks> public static Boolean TryValidate(object @object, ICollection<ValidationResult> results) { var context = new ValidationContext(@object, serviceProvider: null, items: null); return Validator.TryValidateObject(@object, context, results, validateAllProperties: true); } /// <summary> /// Removes invalid characters from filenames and replaces them with the given character /// </summary> public static String FixFilename(String filename, String replacement = "") { return Path.GetInvalidFileNameChars().Aggregate(filename, (current, c) => current.Replace(c.ToString(), replacement)); } /// <summary> /// Returns the assembly version of the assembly formatted as Major.Minor (build Build#) /// </summary> public static String AssemblyVersion<T>() { var version = typeof(T) .Assembly .GetName() .Version; return String.Format("{0}.{1} (build {2})", version.Major, version.Minor, version.Build); } /// <summary> /// Returns the assembly informational version of the type, or assembly version if not available /// </summary> public static String Version<T>() { var attribute = typeof(T) .Assembly .GetCustomAttributes(false) .OfType<AssemblyInformationalVersionAttribute>() .FirstOrDefault(); return attribute == null ? AssemblyVersion<T>() : attribute.InformationalVersion; } } }
namespace CertiPay.Common { using System; using System.IO; using System.Linq; using System.Reflection; using System.Transactions; public static class Utilities { /// <summary> /// Starts a new transaction scope with the given isolation level /// </summary> /// <returns></returns> public static TransactionScope StartTrx(IsolationLevel Isolation = IsolationLevel.ReadUncommitted) { return new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = Isolation }); } /// <summary> /// Removes invalid characters from filenames and replaces them with the given character /// </summary> public static String FixFilename(String filename, String replacement = "") { return Path.GetInvalidFileNameChars().Aggregate(filename, (current, c) => current.Replace(c.ToString(), replacement)); } /// <summary> /// Returns the assembly version of the assembly formatted as Major.Minor (build Build#) /// </summary> public static String AssemblyVersion<T>() { var version = typeof(T) .Assembly .GetName() .Version; return String.Format("{0}.{1} (build {2})", version.Major, version.Minor, version.Build); } /// <summary> /// Returns the assembly informational version of the type, or assembly version if not available /// </summary> public static String Version<T>() { var attribute = typeof(T) .Assembly .GetCustomAttributes(false) .OfType<AssemblyInformationalVersionAttribute>() .FirstOrDefault(); return attribute == null ? AssemblyVersion<T>() : attribute.InformationalVersion; } } }
mit
C#
666c958b4a9126d389264790c9ce733055411c78
Test code removed;
KonH/UDBase
UI/Inventory/ItemPackView.cs
UI/Inventory/ItemPackView.cs
using UnityEngine; using UnityEngine.UI; using System.Collections; namespace UDBase.Controllers.InventorySystem.UI { [RequireComponent(typeof(Text))] public class ItemPackView:MonoBehaviour { public string FormatLine = ""; public string HolderName = ""; public string PackName = ""; Text _text = null; void Start() { Init(); } void Init() { _text = GetComponent<Text>(); _text.text = GetLine(); } string GetLine() { var count = GetCount(); if( !string.IsNullOrEmpty(FormatLine) ) { return string.Format(FormatLine, count); } return count.ToString(); } int GetCount() { return Inventory.GetPackCount(HolderName, PackName); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; namespace UDBase.Controllers.InventorySystem.UI { [RequireComponent(typeof(Text))] public class ItemPackView:MonoBehaviour { public string FormatLine = ""; public string HolderName = ""; public string PackName = ""; Text _text = null; void Start() { Init(); var item = Inventory.GetItem<SimpleItem>(HolderName, "item_1"); Inventory.RemoveItem(HolderName, item); } void Init() { _text = GetComponent<Text>(); _text.text = GetLine(); } string GetLine() { var count = GetCount(); if( !string.IsNullOrEmpty(FormatLine) ) { return string.Format(FormatLine, count); } return count.ToString(); } int GetCount() { return Inventory.GetPackCount(HolderName, PackName); } } }
mit
C#
6687e6697361545d4405492b3c3d3957b4efb5ac
Make SecurityProtocolManager static
ViveportSoftware/vita_core_csharp,ViveportSoftware/vita_core_csharp
source/Htc.Vita.Core/Net/SecurityProtocolManager.cs
source/Htc.Vita.Core/Net/SecurityProtocolManager.cs
using System; using System.Net; namespace Htc.Vita.Core.Net { public static class SecurityProtocolManager { public static SecurityProtocolType GetAvailableProtocol() { var result = (SecurityProtocolType) 0; foreach (var securityProtocolType in (SecurityProtocolType[]) Enum.GetValues(typeof(SecurityProtocolType))) { result |= securityProtocolType; } return result; } } }
using System; using System.Net; namespace Htc.Vita.Core.Net { public class SecurityProtocolManager { public static SecurityProtocolType GetAvailableProtocol() { var result = (SecurityProtocolType) 0; foreach (var securityProtocolType in (SecurityProtocolType[]) Enum.GetValues(typeof(SecurityProtocolType))) { result |= securityProtocolType; } return result; } } }
mit
C#
79af8c60bbb648b2072b5f8b5b01c724c050f4f5
Fix typos in DateTimeOffsetExtensions
jskeet/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,malcolmr/nodatime,nodatime/nodatime,malcolmr/nodatime,nodatime/nodatime,BenJenkinson/nodatime,jskeet/nodatime,malcolmr/nodatime
src/NodaTime/Extensions/DateTimeOffsetExtensions.cs
src/NodaTime/Extensions/DateTimeOffsetExtensions.cs
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime.Extensions { /// <summary> /// Extension methods for <see cref="DateTimeOffset"/>. /// </summary> public static class DateTimeOffsetExtensions { /// <summary> /// Converts a <see cref="DateTimeOffset"/> to <see cref="OffsetDateTime"/>. /// </summary> /// <remarks>This is a convenience method which calls <see cref="OffsetDateTime.FromDateTimeOffset"/>.</remarks> /// <param name="dateTimeOffset">The <c>DateTimeOffset</c> to convert.</param> /// <returns>A new <see cref="OffsetDateTime"/> with the same values as <paramref name="dateTimeOffset"/>.</returns> public static OffsetDateTime ToOffsetDateTime(this DateTimeOffset dateTimeOffset) => OffsetDateTime.FromDateTimeOffset(dateTimeOffset); /// <summary> /// Converts a <see cref="DateTimeOffset"/> to <see cref="ZonedDateTime"/>. /// </summary> /// <remarks>This is a convenience method which calls <see cref="ZonedDateTime.FromDateTimeOffset"/>.</remarks> /// <param name="dateTimeOffset">The <c>DateTimeOffset</c> to convert.</param> /// <returns>A new <see cref="ZonedDateTime"/> with the same values as <paramref name="dateTimeOffset"/>, /// using a fixed-offset time zone.</returns> public static ZonedDateTime ToZonedDateTime(this DateTimeOffset dateTimeOffset) => ZonedDateTime.FromDateTimeOffset(dateTimeOffset); /// <summary> /// Converts a <see cref="DateTimeOffset"/> into an <see cref="Instant"/>. /// </summary> /// <remarks>This is a convenience method which calls <see cref="Instant.FromDateTimeOffset"/>.</remarks> /// <param name="dateTimeOffset">The <c>DateTimeOffset</c> to convert.</param> /// <returns>An <see cref="Instant"/> value representing the same instant in time as <paramref name="dateTimeOffset"/>.</returns> public static Instant ToInstant(this DateTimeOffset dateTimeOffset) => Instant.FromDateTimeOffset(dateTimeOffset); } }
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime.Extensions { /// <summary> /// Extension methods for <see cref="DateTimeOffset"/>. /// </summary> public static class DateTimeOffsetExtensions { /// <summary> /// Converts a <see cref="DateTimeOffset"/> to <see cref="OffsetDateTime"/>. /// </summary> /// <remarks>This is a convenience method which calls <see cref="OffsetDateTime.FromDateTimeOffset"/>.</remarks> /// <param name="dateTimeOffset">The <c>DateTimeOffset</c> to convert.</param> /// <returns>A new <see cref="OffsetDateTime"/> with the same values as <paramref name="dateTimeOffset"/>.</returns> public static OffsetDateTime ToOffsetDateTime(this DateTime dateTimeOffset) => OffsetDateTime.FromDateTimeOffset(dateTimeOffset); /// <summary> /// Converts a <see cref="DateTimeOffset"/> to <see cref="OffsetDateTime"/>. /// </summary> /// <remarks>This is a convenience method which calls <see cref="ZonedDateTime.FromDateTimeOffset"/>.</remarks> /// <param name="dateTimeOffset">The <c>DateTimeOffset</c> to convert.</param> /// <returns>A new <see cref="ZonedDateTime"/> with the same values as <paramref name="dateTimeOffset"/>.</returns> public static ZonedDateTime ToZonedDateTime(this DateTime dateTimeOffset) => ZonedDateTime.FromDateTimeOffset(dateTimeOffset); /// <summary> /// Converts a <see cref="DateTimeOffset"/> into an <see cref="Instant"/>. /// </summary> /// <remarks>This is a convenience method which calls <see cref="Instant.FromDateTimeOffset"/>.</remarks> /// <param name="dateTimeOffset">The <c>DateTimeOffset</c> to convert.</param> /// <returns>An <see cref="Instant"/> value representing the same instant in time as <paramref name="dateTimeOffset"/>.</returns> public static Instant ToInstant(this DateTimeOffset dateTimeOffset) => Instant.FromDateTimeOffset(dateTimeOffset); } }
apache-2.0
C#
4d513448b3d8e2920ae46c33e3c9d11728c50761
Remove orleans health check.
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
src/Squidex/Config/Domain/InfrastructureServices.cs
src/Squidex/Config/Domain/InfrastructureServices.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using NodaTime; using Squidex.Domain.Users; using Squidex.Infrastructure; using Squidex.Infrastructure.Caching; using Squidex.Infrastructure.Diagnostics; using Squidex.Infrastructure.UsageTracking; using Squidex.Shared.Users; #pragma warning disable RECS0092 // Convert field to readonly namespace Squidex.Config.Domain { public static class InfrastructureServices { public static void AddMyInfrastructureServices(this IServiceCollection services) { services.AddSingletonAs(SystemClock.Instance) .As<IClock>(); services.AddSingletonAs<BackgroundUsageTracker>() .AsSelf(); services.AddSingletonAs(c => new CachingUsageTracker(c.GetRequiredService<BackgroundUsageTracker>(), c.GetRequiredService<IMemoryCache>())) .As<IUsageTracker>(); services.AddSingletonAs<AsyncLocalCache>() .As<ILocalCache>(); services.AddSingletonAs<GCHealthCheck>() .As<IHealthCheck>(); services.AddSingletonAs<HttpContextAccessor>() .As<IHttpContextAccessor>(); services.AddSingletonAs<ActionContextAccessor>() .As<IActionContextAccessor>(); services.AddSingletonAs<DefaultUserResolver>() .As<IUserResolver>(); services.AddSingletonAs<DefaultXmlRepository>() .As<IXmlRepository>(); services.AddSingletonAs<AssetUserPictureStore>() .As<IUserPictureStore>(); services.AddTransient(typeof(Lazy<>), typeof(Lazier<>)); } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using NodaTime; using Squidex.Domain.Users; using Squidex.Infrastructure; using Squidex.Infrastructure.Caching; using Squidex.Infrastructure.Diagnostics; using Squidex.Infrastructure.UsageTracking; using Squidex.Shared.Users; #pragma warning disable RECS0092 // Convert field to readonly namespace Squidex.Config.Domain { public static class InfrastructureServices { public static void AddMyInfrastructureServices(this IServiceCollection services) { services.AddSingletonAs(SystemClock.Instance) .As<IClock>(); services.AddSingletonAs<BackgroundUsageTracker>() .AsSelf(); services.AddSingletonAs(c => new CachingUsageTracker(c.GetRequiredService<BackgroundUsageTracker>(), c.GetRequiredService<IMemoryCache>())) .As<IUsageTracker>(); services.AddSingletonAs<AsyncLocalCache>() .As<ILocalCache>(); services.AddSingletonAs<GCHealthCheck>() .As<IHealthCheck>(); services.AddSingletonAs<OrleansHealthCheck>() .As<IHealthCheck>(); services.AddSingletonAs<HttpContextAccessor>() .As<IHttpContextAccessor>(); services.AddSingletonAs<ActionContextAccessor>() .As<IActionContextAccessor>(); services.AddSingletonAs<DefaultUserResolver>() .As<IUserResolver>(); services.AddSingletonAs<DefaultXmlRepository>() .As<IXmlRepository>(); services.AddSingletonAs<AssetUserPictureStore>() .As<IUserPictureStore>(); services.AddTransient(typeof(Lazy<>), typeof(Lazier<>)); } } }
mit
C#
488e703e52390cfef26818c81f30196ee4153318
Fix typo in class name.
symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix
src/SymbooglixLibTests/ConstantFolding/FoldBvnot.cs
src/SymbooglixLibTests/ConstantFolding/FoldBvnot.cs
using NUnit.Framework; using System; using System.Numerics; using Symbooglix; using Microsoft.Boogie; namespace ConstantFoldingTests { [TestFixture()] public class FoldBvnot : TestBase { [Test()] public void Positive() { var arg0 = builder.ConstantBV(7, 4); var neg = builder.BVNOT(arg0); var CFT = new ConstantFoldingTraverser(); var result = CFT.Traverse(neg); Assert.IsInstanceOf<LiteralExpr>(result); Assert.IsTrue(( result as LiteralExpr ).isBvConst); Assert.AreEqual(new BigInteger(8), ( result as LiteralExpr ).asBvConst.Value.ToBigInteger); Assert.IsTrue(builder.ConstantBV(8, 4).Equals(result)); } [Test()] public void Negative() { var arg0 = builder.ConstantBV(-5, 4); var neg = builder.BVNOT(arg0); var CFT = new ConstantFoldingTraverser(); var result = CFT.Traverse(neg); Assert.IsInstanceOf<LiteralExpr>(result); Assert.IsTrue(( result as LiteralExpr ).isBvConst); Assert.AreEqual(new BigInteger(4), ( result as LiteralExpr ).asBvConst.Value.ToBigInteger); Assert.IsTrue(builder.ConstantBV(4, 4).Equals(result)); } [Test()] public void Zero() { var arg0 = builder.ConstantBV(0, 4); var neg = builder.BVNOT(arg0); var CFT = new ConstantFoldingTraverser(); var result = CFT.Traverse(neg); Assert.IsInstanceOf<LiteralExpr>(result); Assert.IsTrue(( result as LiteralExpr ).isBvConst); Assert.AreEqual(new BigInteger(15), ( result as LiteralExpr ).asBvConst.Value.ToBigInteger); Assert.IsTrue(builder.ConstantBV(15, 4).Equals(result)); } } }
using NUnit.Framework; using System; using System.Numerics; using Symbooglix; using Microsoft.Boogie; namespace ConstantFoldingTests { [TestFixture()] public class FoldBnot : TestBase { [Test()] public void Positive() { var arg0 = builder.ConstantBV(7, 4); var neg = builder.BVNOT(arg0); var CFT = new ConstantFoldingTraverser(); var result = CFT.Traverse(neg); Assert.IsInstanceOf<LiteralExpr>(result); Assert.IsTrue(( result as LiteralExpr ).isBvConst); Assert.AreEqual(new BigInteger(8), ( result as LiteralExpr ).asBvConst.Value.ToBigInteger); Assert.IsTrue(builder.ConstantBV(8, 4).Equals(result)); } [Test()] public void Negative() { var arg0 = builder.ConstantBV(-5, 4); var neg = builder.BVNOT(arg0); var CFT = new ConstantFoldingTraverser(); var result = CFT.Traverse(neg); Assert.IsInstanceOf<LiteralExpr>(result); Assert.IsTrue(( result as LiteralExpr ).isBvConst); Assert.AreEqual(new BigInteger(4), ( result as LiteralExpr ).asBvConst.Value.ToBigInteger); Assert.IsTrue(builder.ConstantBV(4, 4).Equals(result)); } [Test()] public void Zero() { var arg0 = builder.ConstantBV(0, 4); var neg = builder.BVNOT(arg0); var CFT = new ConstantFoldingTraverser(); var result = CFT.Traverse(neg); Assert.IsInstanceOf<LiteralExpr>(result); Assert.IsTrue(( result as LiteralExpr ).isBvConst); Assert.AreEqual(new BigInteger(15), ( result as LiteralExpr ).asBvConst.Value.ToBigInteger); Assert.IsTrue(builder.ConstantBV(15, 4).Equals(result)); } } }
bsd-2-clause
C#
43552363f5defe91edab9d87ea95e0e5f1982baf
Add method xml doc
mvelosop/Domion-X.Net
tests/Demo.Budget.Lib.Tests/Helpers/FluentAssertionsExtensions.cs
tests/Demo.Budget.Lib.Tests/Helpers/FluentAssertionsExtensions.cs
using FluentAssertions.Collections; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace Domion.FluentAssertions.Extensions { public static class FluentAssertionsExtensions { /// <summary> /// Asserts that the ValidationError collection contains a message that starts with the constant part of errorMessage, /// i.e. up to the first substitution placeholder ("{.*}"), if any. /// </summary> /// <param name="assertion"></param> /// <param name="errorMessage">Error message text, will be trimmed up to the first substitution placeholder ("{.*}")</param> public static void ContainErrorMessage(this GenericCollectionAssertions<ValidationResult> assertion, string errorMessage) { var errorMessageStart = errorMessage.Split('{')[0]; assertion.Match(c => c.Where(vr => vr.ErrorMessage.StartsWith(errorMessageStart)).Any()); } } }
using FluentAssertions.Collections; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace Domion.FluentAssertions.Extensions { public static class FluentAssertionsExtensions { /// <summary> /// Asserts that the ValidationError collection contains a message that starts with the constant part of errorMessage, /// i.e. up to the first substitution placeholder ("{.*}"), if any. /// </summary> /// <param name="assertion"></param> /// <param name="errorMessage"></param> public static void ContainErrorMessage(this GenericCollectionAssertions<ValidationResult> assertion, string errorMessage) { var errorMessageStart = errorMessage.Split('{')[0]; assertion.Match(c => c.Where(vr => vr.ErrorMessage.StartsWith(errorMessageStart)).Any()); } } }
mit
C#
d4bea792e4bdad27d44c8713bc1604dfc8e553ac
increment minor 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.13.0")] [assembly: AssemblyInformationalVersion("0.13.0")] /* * Version 0.13.0 * * - [FIX] Changes constructor accessiblity of AccessibilityCollectingVisitor * from private to protected. * * - [FIX] AccessibilityCollectingVisitor returns visitor itself instead of * throwing NotSupprotedException, when Visit method is called with * ReflectionElements which does not have any accessiblities. * * - [NEW] Adds RestrictingReferenceAssertion to verify referenced assemblies. * * [Fact] * public void Demo() * { * var assertion = new RestrictingReferenceAssertion(); * assertion.Visit(typeof(IEnumerable<object>).Assembly.ToElement()); * } * * - [FIX] Splits the Jwc.Experiment.Idioms namespace to Jwc.Experiment and * Jwc.Experiment.Idioms. (BREAKING-CHANGE) */
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.12.0")] [assembly: AssemblyInformationalVersion("0.12.0")] /* * Version 0.13.0 * * - [FIX] Changes constructor accessiblity of AccessibilityCollectingVisitor * from private to protected. * * - [FIX] AccessibilityCollectingVisitor returns visitor itself instead of * throwing NotSupprotedException, when Visit method is called with * ReflectionElements which does not have any accessiblities. * * - [NEW] Adds RestrictingReferenceAssertion to verify referenced assemblies. * * [Fact] * public void Demo() * { * var assertion = new RestrictingReferenceAssertion(); * assertion.Visit(typeof(IEnumerable<object>).Assembly.ToElement()); * } * * - [FIX] Splits the Jwc.Experiment.Idioms namespace to Jwc.Experiment and * Jwc.Experiment.Idioms. (BREAKING-CHANGE) */
mit
C#
be32e141bf19573b88b6c6778961d7e1f4070335
add more calls to the methods to check what the generated documentation looks like
jgraber/Blog_Snippets,jgraber/Blog_Snippets,jgraber/Blog_Snippets,jgraber/Blog_Snippets
InheritXMLDocumentation/InheritXMLDocumentation.Tests/UnitTest1.cs
InheritXMLDocumentation/InheritXMLDocumentation.Tests/UnitTest1.cs
using NUnit.Framework; using InheritXMLDocumentation.Persistence; namespace InheritXMLDocumentation.Tests { public class InMemoryUserRepositoryTests { [SetUp] public void Setup() { } [Test] public void AccessThroughInterface() { IUserRepository userRepository = new InMemoryUserRepository(); userRepository.Add(new User()); userRepository.Update(new User()); userRepository.FindById(1); } [Test] public void AccessthroughClass() { var userRepository = new InMemoryUserRepository(); userRepository.Add(new User()); userRepository.Update(new User()); userRepository.FindById(1); } } public class DbUserRepositoryTests { [SetUp] public void Setup() { } [Test] public void AccessThroughInterface() { IUserRepository userRepository = new DbUserRepository(); userRepository.Add(new User()); userRepository.Update(new User()); userRepository.FindById(1); } [Test] public void AccessthroughClass() { var userRepository = new DbUserRepository(); userRepository.Add(new User()); userRepository.Update(new User()); userRepository.FindById(1); } } }
using NUnit.Framework; using InheritXMLDocumentation.Persistence; namespace InheritXMLDocumentation.Tests { public class InMemoryUserRepositoryTests { [SetUp] public void Setup() { } [Test] public void AccessThroughInterface() { IUserRepository userRepository = new InMemoryUserRepository(); userRepository.Add(new User()); } [Test] public void AccessthroughClass() { var userRepository = new InMemoryUserRepository(); userRepository.Add(new User()); } } public class DbUserRepositoryTests { [SetUp] public void Setup() { } [Test] public void AccessThroughInterface() { IUserRepository userRepository = new DbUserRepository(); userRepository.Add(new User()); } [Test] public void AccessthroughClass() { var userRepository = new DbUserRepository(); userRepository.Add(new User()); } } }
apache-2.0
C#
f4dccb6d656e9c876516e94c5990c09a7324712c
Update for end of January Alert changes
amweiss/dark-sky-core
src/DarkSkyCore/Models/Alert.cs
src/DarkSkyCore/Models/Alert.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace DarkSky.Models { public class Alert { [JsonProperty(PropertyName = "description")] public string Description { get; set; } [JsonProperty(PropertyName = "expires")] public long Expires { get; set; } [JsonProperty(PropertyName = "regions")] public List<string> Regions { get; set; } [JsonProperty(PropertyName = "severity")] public string Severity { get; set; } [JsonProperty(PropertyName = "time")] public long Time { get; set; } [JsonProperty(PropertyName = "title")] public string Title { get; set; } [JsonProperty(PropertyName = "uri")] public Uri Uri { get; set; } } }
using Newtonsoft.Json; using System; namespace DarkSky.Models { public class Alert { [JsonProperty(PropertyName = "description")] public string Description { get; set; } [JsonProperty(PropertyName = "expires")] public long Expires { get; set; } [JsonProperty(PropertyName = "time")] public long Time { get; set; } [JsonProperty(PropertyName = "title")] public string Title { get; set; } [JsonProperty(PropertyName = "uri")] public Uri Uri { get; set; } } }
mit
C#
00103e2f65005dfb62c9f08f42495f9fa86fddeb
Put variables in Main first
TeamnetGroup/schema2fm
src/ConsoleApp/Program.cs
src/ConsoleApp/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using static System.Console; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() { // nothing here yet } } }"); } } class Program { private static void Main() { var connectionString = @"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"; var schemaName = "dbo"; var tableName = "Book"; var columnsProvider = new ColumnsProvider(connectionString); var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult(); new Table(tableName, columns).OutputMigrationCode(Out); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using static System.Console; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() { // nothing here yet } } }"); } } class Program { private static void Main() { var columnsProvider = new ColumnsProvider(@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"); var tableName = "Book"; var columns = columnsProvider.GetColumnsAsync("dbo", tableName).GetAwaiter().GetResult(); new Table(tableName, columns).OutputMigrationCode(Out); } } }
mit
C#
b79cb544944fa2c9fe0bdf22e1dcab3494d8cd62
Add standalone ifdef to leap example scene script
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/Examples/Demos/HandTracking/Scripts/LeapMotionOrientationDisplay.cs
Assets/MRTK/Examples/Demos/HandTracking/Scripts/LeapMotionOrientationDisplay.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; using Microsoft.MixedReality.Toolkit.Input; using TMPro; #if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE using Microsoft.MixedReality.Toolkit.LeapMotion.Input; #endif namespace Microsoft.MixedReality.Toolkit.Examples { /// <summary> /// Returns the orientation of Leap Motion Controller /// </summary> public class LeapMotionOrientationDisplay : MonoBehaviour { #if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE [SerializeField] private TextMeshProUGUI orientationText; private LeapMotionDeviceManagerProfile managerProfile; private void Start() { if (GetLeapManager()) { orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString(); } else { orientationText.text = "Orientation: Unavailable"; } } private LeapMotionDeviceManagerProfile GetLeapManager() { if (!MixedRealityToolkit.Instance.ActiveProfile) { return null; } foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations) { if (config.ComponentType == typeof(LeapMotionDeviceManager)) { managerProfile = (LeapMotionDeviceManagerProfile)config.Profile; return managerProfile; } } return null; } #endif } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; using Microsoft.MixedReality.Toolkit.Input; using TMPro; #if LEAPMOTIONCORE_PRESENT using Microsoft.MixedReality.Toolkit.LeapMotion.Input; #endif namespace Microsoft.MixedReality.Toolkit.Examples { /// <summary> /// Returns the orientation of Leap Motion Controller /// </summary> public class LeapMotionOrientationDisplay : MonoBehaviour { #if LEAPMOTIONCORE_PRESENT [SerializeField] private TextMeshProUGUI orientationText; private LeapMotionDeviceManagerProfile managerProfile; private void Start() { if (GetLeapManager()) { orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString(); } else { orientationText.text = "Orientation: Unavailable"; } } private LeapMotionDeviceManagerProfile GetLeapManager() { if (!MixedRealityToolkit.Instance.ActiveProfile) { return null; } foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations) { if (config.ComponentType == typeof(LeapMotionDeviceManager)) { managerProfile = (LeapMotionDeviceManagerProfile)config.Profile; return managerProfile; } } return null; } #endif } }
mit
C#
7a52d1833953db236acd2b94a7429df602123d1c
add include extension method
nirvana-framework/Nirvana,jasoncavaliere/Nirvana,jasoncavaliere/Nirvana,jasoncavaliere/Nirvana,jasoncavaliere/Nirvana
src/Nirvana/Data/IRepository.cs
src/Nirvana/Data/IRepository.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Nirvana.CQRS; using Nirvana.Data.EntityTypes; using Nirvana.Domain; namespace Nirvana.Data { public interface ISqlRepository { IEnumerable<T> Sql<T>(string sql, params object[] parameters); } public interface IRepository<TRoot> where TRoot : ServiceRootType { T Get<T>(Guid id) where T : Entity<Guid>; T Get<T>(long id) where T : Entity<long>; IQueryable<T> GetAll<T>() where T : Entity; IQueryable<T> GetAllAndInclude<T>(IList<Expression<Func<T, object>>> includes) where T : Entity; IQueryable<T> Include<T>(IQueryable<T> queryable, IList<Expression<Func<T, object>>> includes) where T : Entity; IQueryable<T> GetAllAndInclude<T, TProperty>(Expression<Func<T, TProperty>> path) where T : Entity; PagedResult<T> GetPaged<T>(PaginationQuery pageInfo, IList<Expression<Func<T, bool>>> conditions, IList<Expression<Func<T, object>>> orders = null, IList<Expression<Func<T, object>>> includes = null ) where T : Entity; void EnableSoftDeleteLoading(); void BeginTransaction(); void CommitTransaction(); void RollbackTransaction(); void SaveOrUpdate<T>(T entity) where T : Entity; void SaveOrUpdateCollection<T>(IEnumerable<T> entities) where T : Entity; void Delete<T>(T entity) where T : Entity; void DeleteCollection<T>(IEnumerable<T> entities) where T : Entity; T GetAndInclude<T, TProperty>(Guid id, Expression<Func<T, TProperty>> path) where T : Entity<Guid> where TProperty : Entity; int SqlCommand(string sql, params object[] parameters); void ClearContext(); T Refresh<T>(T entity) where T : Entity; IEnumerable<T> Refresh<T>(IEnumerable<T> entities) where T : Entity; IQueryable<T> Include<T>(IQueryable<T> query, params Expression<Func<T, object>>[] includes) where T : class; } public static class RepositoryExtensions { public static IQueryable<T> Include<TRoot,T>(this IQueryable<T> input, IRepository<TRoot> repository, params Expression<Func<T, object>>[] includes) where T : class where TRoot : ServiceRootType { return repository.Include(input, includes); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Nirvana.CQRS; using Nirvana.Data.EntityTypes; using Nirvana.Domain; namespace Nirvana.Data { public interface ISqlRepository { IEnumerable<T> Sql<T>(string sql, params object[] parameters); } public interface IRepository<TRoot> where TRoot : ServiceRootType { T Get<T>(Guid id) where T : Entity<Guid>; T Get<T>(long id) where T : Entity<long>; IQueryable<T> GetAll<T>() where T : Entity; IQueryable<T> GetAllAndInclude<T>(IList<Expression<Func<T, object>>> includes) where T : Entity; IQueryable<T> Include<T>(IQueryable<T> queryable, IList<Expression<Func<T, object>>> includes) where T : Entity; IQueryable<T> GetAllAndInclude<T, TProperty>(Expression<Func<T, TProperty>> path) where T : Entity; PagedResult<T> GetPaged<T>(PaginationQuery pageInfo, IList<Expression<Func<T, bool>>> conditions, IList<Expression<Func<T, object>>> orders = null, IList<Expression<Func<T, object>>> includes = null ) where T : Entity; void EnableSoftDeleteLoading(); void BeginTransaction(); void CommitTransaction(); void RollbackTransaction(); void SaveOrUpdate<T>(T entity) where T : Entity; void SaveOrUpdateCollection<T>(IEnumerable<T> entities) where T : Entity; void Delete<T>(T entity) where T : Entity; void DeleteCollection<T>(IEnumerable<T> entities) where T : Entity; T GetAndInclude<T, TProperty>(Guid id, Expression<Func<T, TProperty>> path) where T : Entity<Guid> where TProperty : Entity; int SqlCommand(string sql, params object[] parameters); void ClearContext(); T Refresh<T>(T entity) where T : Entity; IEnumerable<T> Refresh<T>(IEnumerable<T> entities) where T : Entity; IQueryable<T> Include<T>(IQueryable<T> query, params Expression<Func<T, object>>[] includes) where T : class; } }
apache-2.0
C#
79af64b94c137e394d16483d3aa7cc0d50eebaad
Make sure that classes generated derive from a common type to allow code sharing
AlexGhiondea/SmugMug.NET
src/SmugMugCodeGen/Constants.cs
src/SmugMugCodeGen/Constants.cs
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace SmugMugCodeGen { public static class Constants { public const string PropertyDefinition = @"public {0} {1} {{get; set;}}"; public const string EnumDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace SmugMug.v2.Types {{ public enum {0} {{ {1} }} }} "; public const string ClassDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace SmugMug.v2.Types {{ public partial class {0}Entity : SmugMugEntity {{ {1} }} }} "; } }
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace SmugMugCodeGen { public static class Constants { public const string PropertyDefinition = @"public {0} {1} {{get; set;}}"; public const string EnumDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace SmugMug.v2.Types {{ public enum {0} {{ {1} }} }} "; public const string ClassDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace SmugMug.v2.Types {{ public partial class {0}Entity {{ {1} }} }} "; } }
mit
C#
eaa20886f67cdce02fea82be3e75ea19b20de30c
Set version to 4.2.4
damianh/LibLog
src/SharedAssemblyInfo.cs
src/SharedAssemblyInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SharedAssemblyInfo.cs" company="Damian Hickey"> // Copyright © 2011-2014 Damian Hickey // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Damian Hickey")] [assembly: AssemblyProduct("LibLog")] [assembly: AssemblyCopyright("Damian Hickey 2011-2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("4.2.4.0")] [assembly: AssemblyFileVersion("4.2.4.0")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SharedAssemblyInfo.cs" company="Damian Hickey"> // Copyright © 2011-2014 Damian Hickey // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Damian Hickey")] [assembly: AssemblyProduct("LibLog")] [assembly: AssemblyCopyright("Damian Hickey 2011-2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("4.1.0.0")] [assembly: AssemblyFileVersion("4.1.0.0")]
mit
C#
d634c649fee8ed6ba507a05d93980f485a9fc45d
Support scene primitive rotation
simontaylor81/Syrup,simontaylor81/Syrup
SRPCommon/Scene/Primitive.cs
SRPCommon/Scene/Primitive.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SlimDX; using SRPCommon.Util; using SRPCommon.UserProperties; using System.Reactive.Linq; using System.Reactive; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Diagnostics.CodeAnalysis; namespace SRPCommon.Scene { public enum PrimitiveType { MeshInstance, Sphere, Cube, Plane, } [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public abstract class Primitive { [JsonProperty] [JsonConverter(typeof(StringEnumConverter))] public abstract PrimitiveType Type { get; } [JsonProperty] public Vector3 Position { get; set; } [JsonProperty] public Vector3 Scale { get; set; } [JsonProperty] public Vector3 Rotation { get; set; } public Material Material { get; private set; } [JsonProperty("material")] [SuppressMessage("Language", "CSE0002:Use getter-only auto properties", Justification = "Needed for serialisation")] private string MaterialName { get; set; } protected List<IUserProperty> _userProperties = new List<IUserProperty>(); public IEnumerable<IUserProperty> UserProperties => _userProperties; public virtual bool IsValid => true; // Observable that fires when something important changes in the primitive. public IObservable<Unit> OnChanged { get; } protected Primitive() { Scale = new Vector3(1.0f, 1.0f, 1.0f); _userProperties.Add(new StructUserProperty("Position", () => Position, o => Position = (Vector3)o)); _userProperties.Add(new StructUserProperty("Scale", () => Scale, o => Scale = (Vector3)o)); _userProperties.Add(new StructUserProperty("Rotation", () => Rotation, o => Rotation = (Vector3)o)); // We change whenever our properties change. OnChanged = Observable.Merge(UserProperties); } public Matrix LocalToWorld => Matrix.Scaling(Scale) * Matrix.RotationYawPitchRoll(ToRadians(Rotation.Y), ToRadians(Rotation.X), ToRadians(Rotation.Z)) * Matrix.Translation(Position); private float ToRadians(float degrees) => degrees * ((float)Math.PI / 180.0f); internal virtual void PostLoad(Scene scene) { if (MaterialName != null) { // Look up mesh in the scene's collection. Material mat; if (scene.Materials.TryGetValue(MaterialName, out mat)) { Material = mat; } else { OutputLogger.Instance.LogLine(LogCategory.Log, "Material not found: " + MaterialName); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SlimDX; using SRPCommon.Util; using SRPCommon.UserProperties; using System.Reactive.Linq; using System.Reactive; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Diagnostics.CodeAnalysis; namespace SRPCommon.Scene { public enum PrimitiveType { MeshInstance, Sphere, Cube, Plane, } [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public abstract class Primitive { [JsonProperty] [JsonConverter(typeof(StringEnumConverter))] public abstract PrimitiveType Type { get; } [JsonProperty] public Vector3 Position { get; set; } [JsonProperty] public Vector3 Scale { get; set; } [JsonProperty] public Vector3 Rotation { get; set; } public Material Material { get; private set; } [JsonProperty("material")] [SuppressMessage("Language", "CSE0002:Use getter-only auto properties", Justification = "Needed for serialisation")] private string MaterialName { get; set; } protected List<IUserProperty> _userProperties = new List<IUserProperty>(); public IEnumerable<IUserProperty> UserProperties => _userProperties; public virtual bool IsValid => true; // Observable that fires when something important changes in the primitive. public IObservable<Unit> OnChanged { get; } protected Primitive() { Scale = new Vector3(1.0f, 1.0f, 1.0f); _userProperties.Add(new StructUserProperty("Position", () => Position, o => Position = (Vector3)o)); _userProperties.Add(new StructUserProperty("Scale", () => Scale, o => Scale = (Vector3)o)); _userProperties.Add(new StructUserProperty("Rotation", () => Rotation, o => Rotation = (Vector3)o)); // We change whenever our properties change. OnChanged = Observable.Merge(UserProperties); } public Matrix LocalToWorld // TODO: rotation! => Matrix.Scaling(Scale) * Matrix.Translation(Position); internal virtual void PostLoad(Scene scene) { if (MaterialName != null) { // Look up mesh in the scene's collection. Material mat; if (scene.Materials.TryGetValue(MaterialName, out mat)) { Material = mat; } else { OutputLogger.Instance.LogLine(LogCategory.Log, "Material not found: " + MaterialName); } } } } }
mit
C#
dc8e3c8249ea2e9262d17e8f9ca163d659c46b78
use small classes to improve db communication
pako1337/Content_Man,pako1337/Content_Man
ContentDomain/Repositories/ContentElementRepository.cs
ContentDomain/Repositories/ContentElementRepository.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ContentDomain.Factories; using Simple.Data; namespace ContentDomain.Repositories { public class ContentElementRepository { public IEnumerable<ContentElement> All() { var db = Database.Open(); List<ContentElementDb> e = db.ContentElements.All().WithTextContents(); var elements = new List<ContentElement>(); var factory = new ContentElementFactory(); foreach (var element in e) elements.Add(factory.Create(element)); return elements; } } internal class ContentElementDb { public int ContentElementId { get; set; } public ContentType ContentType { get; set; } public string DefaultLanguage { get; set; } public List<TextContentDb> TextContents { get; set; } } internal class TextContentDb { public int TextContentId { get; set; } public int ContentStatus { get; set; } public string Value { get; set; } public string Language { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ContentDomain.Factories; using Simple.Data; namespace ContentDomain.Repositories { public class ContentElementRepository { public IEnumerable<ContentElement> All() { var db = Database.Open(); dynamic e = db.ContentElements.All().WithTextContents(); var elements = new List<ContentElement>(); var factory = new ContentElementFactory(); foreach (var element in e) { if (element.TextContents == null) element.TextContents = new object[0]; elements.Add(factory.Create(element)); } return elements; } } }
mit
C#
e335e94ad6555ee00b21ad568253b0476d2a6261
Fix projectile spawn issue
jkereako/PillBlasta
Assets/Scripts/Projectile.cs
Assets/Scripts/Projectile.cs
using UnityEngine; using System.Runtime.Remoting.Contexts; public class Projectile: MonoBehaviour { public LayerMask collisionMask; float speed; const float damage = 1.0f; const float lifeTime = 2.0f; const float targetSurfaceThickness = 0.1f; void Start() { Destroy(gameObject, lifeTime); Collider[] collisions = Physics.OverlapSphere(transform.position, 0.1f, collisionMask); if (collisions.Length > 0) { OnObjectHit(collisions[0]); } } void Update() { float distance = Time.deltaTime * speed; CheckCollision(distance); transform.Translate(Vector3.forward * distance); } public void SetSpeed(float newSpeed) { speed = newSpeed; } void CheckCollision(float distance) { Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit, distance + targetSurfaceThickness, collisionMask, QueryTriggerInteraction.Collide)) { OnObjectHit(hit); } } void OnObjectHit(RaycastHit hit) { IDamageable damageable = hit.collider.GetComponent<IDamageable>(); if (damageable != null) { damageable.TakeHit(damage, hit); } Destroy(gameObject); } void OnObjectHit(Collider aCollider) { IDamageable damageable = aCollider.GetComponent<IDamageable>(); if (damageable != null) { damageable.TakeDamage(damage); } Destroy(gameObject); } }
using UnityEngine; public class Projectile: MonoBehaviour { public LayerMask collisionMask; float speed; const float damage = 1.0f; const float lifeTime = 2.0f; void Start() { Destroy(gameObject, lifeTime); } void Update() { float distance = Time.deltaTime * speed; CheckCollision(distance); transform.Translate(Vector3.forward * distance); } public void SetSpeed(float newSpeed) { speed = newSpeed; } void CheckCollision(float distance) { Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit, distance, collisionMask, QueryTriggerInteraction.Collide)) { OnObjectHit(hit); } } void OnObjectHit(RaycastHit hit) { IDamageable damageable = hit.collider.GetComponent<IDamageable>(); if (damageable != null) { damageable.TakeHit(damage, hit); } Destroy(gameObject); } }
mit
C#
0a2a9c21a8d37276d682a1af62614fc44e53b7e5
Add max job count to levels
LeBodro/super-salaryman-2044
Assets/Gameflow/Levels.cs
Assets/Gameflow/Levels.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Levels : MonoBehaviour { /* Cette classe a pour destin d'être sur un prefab. * Ce prefab agira comme une config manuelle de niveaux pour faciliter le level design. * On pourra faire différentes configs si on veut (mettons une par difficulté) et ultimement glisser cette config dans le gamecontroller * pour qu'il s'en serve. * */ [SerializeField] WorkDay[] days; [SerializeField] int maxJobCount; int currentLevel = 0; public void StartNext() { //starts next level } public void EndCurrent() { //ends current level currentLevel++; if (days[currentLevel].AddsJob) { // add a job to pool // if this brings us over maximum, change a job instead } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Levels : MonoBehaviour { /* Cette classe a pour destin d'être sur un prefab. * Ce prefab agira comme une config manuelle de niveaux pour faciliter le level design. * On pourra faire différentes configs si on veut (mettons une par difficulté) et ultimement glisser cette config dans le gamecontroller * pour qu'il s'en serve. * */ [SerializeField] WorkDay[] days; int currentLevel = 0; public void StartNext() { //starts next level } public void EndCurrent() { //ends current level currentLevel++; if (days[currentLevel].AddsJob) { // add a job to pool } } }
mit
C#
6fcebec0bb38e22a381416038cd34541b3cdc47d
Test outline for contentservice.
BrettStory/Macabre2D
Tests/Editor/Framework/Services/ContentServiceTests.cs
Tests/Editor/Framework/Services/ContentServiceTests.cs
namespace Macabresoft.Macabre2D.Tests.Editor.Framework.Services { using System.IO; using FluentAssertions; using FluentAssertions.Execution; using Macabresoft.Core; using Macabresoft.Macabre2D.Editor.Library.Models.Content; using Macabresoft.Macabre2D.Editor.Library.Services; using Macabresoft.Macabre2D.Framework; using NUnit.Framework; [TestFixture] public sealed class ContentServiceTests { private const string BinDirectoryName = "bin"; private const string ContentDirectoryName = "Content"; private const string ContentFileName = "Content.mgcb"; private const string LeagueMonoXnbName = "League Mono.xnb"; private const string PlatformName = "DesktopGL"; private const string SkullXnbName = "skull.xnb"; [Test] [Category("Integration Tests")] public void Build_ShouldRunMGCB() { var service = new ContentService(new Serializer()); var contentDirectory = Path.Combine( TestContext.CurrentContext.TestDirectory, PathHelper.GetPathToAncestorDirectory(3), ContentDirectoryName); var contentFile = Path.Combine(contentDirectory, ContentFileName); var binDirectory = Path.Combine(contentDirectory, BinDirectoryName); var buildContentDirectory = Path.Combine(binDirectory, PlatformName); var skullFilePath = Path.Combine(buildContentDirectory, SkullXnbName); var leagueMonoFilePath = Path.Combine(buildContentDirectory, LeagueMonoXnbName); if (Directory.Exists(binDirectory)) { Directory.Delete(binDirectory, true); } using (new AssertionScope()) { service.Build(new BuildContentArguments(contentFile, PlatformName, false)).Should().Be(0); File.Exists(skullFilePath).Should().BeTrue(); File.Exists(leagueMonoFilePath).Should().BeTrue(); } } [Test] [Category("Integration Tests")] public void Initialize_ShouldBuildContentHierarchy() { } } }
namespace Macabresoft.Macabre2D.Tests.Editor.Framework.Services { using System.IO; using FluentAssertions; using FluentAssertions.Execution; using Macabresoft.Core; using Macabresoft.Macabre2D.Editor.Library.Models.Content; using Macabresoft.Macabre2D.Editor.Library.Services; using Macabresoft.Macabre2D.Framework; using NUnit.Framework; [TestFixture] public sealed class ContentServiceTests { private const string BinDirectoryName = "bin"; private const string ContentDirectoryName = "Content"; private const string ContentFileName = "Content.mgcb"; private const string LeagueMonoXnbName = "League Mono.xnb"; private const string PlatformName = "DesktopGL"; private const string SkullXnbName = "skull.xnb"; [Test] [Category("Integration Tests")] public void Build_ShouldRunMGCB() { var service = new ContentService(new Serializer()); var contentDirectory = Path.Combine( TestContext.CurrentContext.TestDirectory, PathHelper.GetPathToAncestorDirectory(3), ContentDirectoryName); var contentFile = Path.Combine(contentDirectory, ContentFileName); var binDirectory = Path.Combine(contentDirectory, BinDirectoryName); var buildContentDirectory = Path.Combine(binDirectory, PlatformName); var skullFilePath = Path.Combine(buildContentDirectory, SkullXnbName); var leagueMonoFilePath = Path.Combine(buildContentDirectory, LeagueMonoXnbName); if (Directory.Exists(binDirectory)) { Directory.Delete(binDirectory, true); } using (new AssertionScope()) { service.Build(new BuildContentArguments(contentFile, PlatformName, false)).Should().Be(0); File.Exists(skullFilePath).Should().BeTrue(); File.Exists(leagueMonoFilePath).Should().BeTrue(); } } } }
mit
C#
d1dc5b61056769b047ed73d023988139834e0edc
tidy batch test code
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
Test/NakedObjects.Batch.Test/BatchStartPoint.cs
Test/NakedObjects.Batch.Test/BatchStartPoint.cs
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Linq; using System.Threading.Tasks; using AdventureWorksModel; using NakedObjects.Architecture.Component; using NakedObjects.Async; using NakedObjects.Core.Util; using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace NakedObjects.Batch { public class BatchStartPoint : IBatchStartPoint { private readonly string testMessage = Guid.NewGuid().ToString(); public IAsyncService AsyncService { private get; set; } public IDomainObjectContainer Container { private get; set; } #region IBatchStartPoint Members public void Execute() { var ids = Enumerable.Range(63290, 20).ToArray(); var tasks = ids.Select(id => AsyncService.RunAsync(doc => DoWork(doc, id))).ToArray(); Task.WaitAll(tasks); var changed = Container.Instances<SalesOrderHeader>().Where(soh => ids.Contains(soh.SalesOrderID)).ToArray(); changed.ForEach(soh => Assert.AreEqual(testMessage + soh.SalesOrderID, soh.Comment)); } #endregion private void DoWork(IDomainObjectContainer container, int orderId) { var order = container.Instances<SalesOrderHeader>().Single(soh => soh.SalesOrderID == orderId); order.Comment = testMessage + orderId; } } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Linq; using System.Threading.Tasks; using AdventureWorksModel; using NakedObjects.Architecture.Component; using NakedObjects.Async; namespace NakedObjects.Batch { public class BatchStartPoint : IBatchStartPoint { public IAsyncService AsyncService { private get; set; } #region IBatchStartPoint Members public void Execute() { Console.WriteLine("Starting"); var tasks = new Task[4]; tasks[0] = AsyncService.RunAsync((doc) => { DoWork(doc, 63290); }); tasks[1] = AsyncService.RunAsync((doc) => { DoWork(doc, 63291); }); tasks[2] = AsyncService.RunAsync((doc) => { DoWork(doc, 63292); }); tasks[3] = AsyncService.RunAsync((doc) => { DoWork(doc, 63293); }); Console.WriteLine("Waiting"); Task.WaitAll(tasks); Console.WriteLine("All done"); Console.ReadKey(); } #endregion private void DoWork(IDomainObjectContainer container, int orderId) { var order = container.Instances<SalesOrderHeader>().FirstOrDefault(soh => soh.SalesOrderID == orderId); if (order != null) { order.AddComment("Adding comment by Async"); Console.WriteLine("Added comment to Order " + orderId); } } } }
apache-2.0
C#
652a21b3dcac5a2b6c17f14011df8b31b003d8c7
Update r# CLT
ppy/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,ppy/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu,ZLima12/osu,ZLima12/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,johnneijzen/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu
build/build.cake
build/build.cake
#addin "nuget:?package=CodeFileSanity&version=0.0.21" #addin "nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2019.1.1" #tool "nuget:?package=NVika.MSBuild&version=1.0.1" var nVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var configuration = Argument("configuration", "Release"); var rootDirectory = new DirectoryPath(".."); var solution = rootDirectory.CombineWithFilePath("osu.sln"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Compile") .Does(() => { DotNetCoreBuild(solution.FullPath, new DotNetCoreBuildSettings { Configuration = configuration, }); }); Task("Test") .IsDependentOn("Compile") .Does(() => { var testAssemblies = GetFiles(rootDirectory + "/**/*.Tests/bin/**/*.Tests.dll"); DotNetCoreVSTest(testAssemblies, new DotNetCoreVSTestSettings { Logger = AppVeyor.IsRunningOnAppVeyor ? "Appveyor" : $"trx", Parallel = true, ToolTimeout = TimeSpan.FromMinutes(10), }); }); // windows only because both inspectcore and nvika depend on net45 Task("InspectCode") .WithCriteria(IsRunningOnWindows()) .IsDependentOn("Compile") .Does(() => { InspectCode(solution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); int returnCode = StartProcess(nVikaToolPath, $@"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); if (returnCode != 0) throw new Exception($"inspectcode failed with return code {returnCode}"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = rootDirectory.FullPath, IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
#addin "nuget:?package=CodeFileSanity&version=0.0.21" #addin "nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2018.3.4" #tool "nuget:?package=NVika.MSBuild&version=1.0.1" var nVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var configuration = Argument("configuration", "Release"); var rootDirectory = new DirectoryPath(".."); var solution = rootDirectory.CombineWithFilePath("osu.sln"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Compile") .Does(() => { DotNetCoreBuild(solution.FullPath, new DotNetCoreBuildSettings { Configuration = configuration, }); }); Task("Test") .IsDependentOn("Compile") .Does(() => { var testAssemblies = GetFiles(rootDirectory + "/**/*.Tests/bin/**/*.Tests.dll"); DotNetCoreVSTest(testAssemblies, new DotNetCoreVSTestSettings { Logger = AppVeyor.IsRunningOnAppVeyor ? "Appveyor" : $"trx", Parallel = true, ToolTimeout = TimeSpan.FromMinutes(10), }); }); // windows only because both inspectcore and nvika depend on net45 Task("InspectCode") .WithCriteria(IsRunningOnWindows()) .IsDependentOn("Compile") .Does(() => { InspectCode(solution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); int returnCode = StartProcess(nVikaToolPath, $@"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); if (returnCode != 0) throw new Exception($"inspectcode failed with return code {returnCode}"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = rootDirectory.FullPath, IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
mit
C#
14c7cbde38ce4bada24f6a99076833873026b6a1
Fix toggle mute (and volume meter traversal) handling repeat key presses
ppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu
osu.Game/Overlays/Volume/VolumeControlReceptor.cs
osu.Game/Overlays/Volume/VolumeControlReceptor.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using osu.Framework.Graphics.Containers; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Game.Input.Bindings; namespace osu.Game.Overlays.Volume { public class VolumeControlReceptor : Container, IScrollBindingHandler<GlobalAction>, IHandleGlobalKeyboardInput { public Func<GlobalAction, bool> ActionRequested; public Func<GlobalAction, float, bool, bool> ScrollActionRequested; public bool OnPressed(KeyBindingPressEvent<GlobalAction> e) { switch (e.Action) { case GlobalAction.DecreaseVolume: case GlobalAction.IncreaseVolume: ActionRequested?.Invoke(e.Action); return true; case GlobalAction.ToggleMute: case GlobalAction.NextVolumeMeter: case GlobalAction.PreviousVolumeMeter: if (!e.Repeat) ActionRequested?.Invoke(e.Action); return true; } return false; } public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e) { } protected override bool OnScroll(ScrollEvent e) { if (e.ScrollDelta.Y == 0) return false; // forward any unhandled mouse scroll events to the volume control. ScrollActionRequested?.Invoke(GlobalAction.IncreaseVolume, e.ScrollDelta.Y, e.IsPrecise); return true; } public bool OnScroll(KeyBindingScrollEvent<GlobalAction> e) => ScrollActionRequested?.Invoke(e.Action, e.ScrollAmount, e.IsPrecise) ?? false; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using osu.Framework.Graphics.Containers; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Game.Input.Bindings; namespace osu.Game.Overlays.Volume { public class VolumeControlReceptor : Container, IScrollBindingHandler<GlobalAction>, IHandleGlobalKeyboardInput { public Func<GlobalAction, bool> ActionRequested; public Func<GlobalAction, float, bool, bool> ScrollActionRequested; public bool OnPressed(KeyBindingPressEvent<GlobalAction> e) { switch (e.Action) { case GlobalAction.DecreaseVolume: case GlobalAction.IncreaseVolume: case GlobalAction.ToggleMute: case GlobalAction.NextVolumeMeter: case GlobalAction.PreviousVolumeMeter: ActionRequested?.Invoke(e.Action); return true; } return false; } public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e) { } protected override bool OnScroll(ScrollEvent e) { if (e.ScrollDelta.Y == 0) return false; // forward any unhandled mouse scroll events to the volume control. ScrollActionRequested?.Invoke(GlobalAction.IncreaseVolume, e.ScrollDelta.Y, e.IsPrecise); return true; } public bool OnScroll(KeyBindingScrollEvent<GlobalAction> e) => ScrollActionRequested?.Invoke(e.Action, e.ScrollAmount, e.IsPrecise) ?? false; } }
mit
C#
2ffc72b75ffc89de892d92e0e028ccd7e22e866f
Move test into correct namespace.
BluewireTechnologies/cassette,damiensawyer/cassette,damiensawyer/cassette,andrewdavey/cassette,honestegg/cassette,andrewdavey/cassette,damiensawyer/cassette,andrewdavey/cassette,honestegg/cassette,honestegg/cassette,BluewireTechnologies/cassette
src/Cassette.UnitTests/PlaceholderTracker.cs
src/Cassette.UnitTests/PlaceholderTracker.cs
using System; using System.Text.RegularExpressions; using Should; using Xunit; namespace Cassette { public class PlaceholderTracker_Tests { [Fact] public void WhenInsertPlaceholder_ThenPlaceholderIdHtmlReturned() { var tracker = new PlaceholderTracker(); var result = tracker.InsertPlaceholder(() => ("")); var guidRegex = new Regex(@"[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}"); var output = result; guidRegex.IsMatch(output).ShouldBeTrue(); } [Fact] public void GivenInsertPlaceholder_WhenReplacePlaceholders_ThenHtmlInserted() { var tracker = new PlaceholderTracker(); var html = tracker.InsertPlaceholder(() => ("<p>test</p>")); tracker.ReplacePlaceholders(html).ShouldEqual( Environment.NewLine + "<p>test</p>" + Environment.NewLine ); } } }
using System; using System.Text.RegularExpressions; using Should; using Xunit; namespace Cassette.UI { public class PlaceholderTracker_Tests { [Fact] public void WhenInsertPlaceholder_ThenPlaceholderIdHtmlReturned() { var tracker = new PlaceholderTracker(); var result = tracker.InsertPlaceholder(() => ("")); var guidRegex = new Regex(@"[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}"); var output = result; guidRegex.IsMatch(output).ShouldBeTrue(); } [Fact] public void GivenInsertPlaceholder_WhenReplacePlaceholders_ThenHtmlInserted() { var tracker = new PlaceholderTracker(); var html = tracker.InsertPlaceholder(() => ("<p>test</p>")); tracker.ReplacePlaceholders(html).ShouldEqual( Environment.NewLine + "<p>test</p>" + Environment.NewLine ); } } }
mit
C#
27ea2aeba098727a7aa90397250a58c056d9668f
Implement URL opening for android
peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework
osu.Framework.Android/AndroidGameHost.cs
osu.Framework.Android/AndroidGameHost.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using Android.App; using Android.Content; using osu.Framework.Android.Graphics.Textures; using osu.Framework.Android.Input; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.Input.Handlers; using osu.Framework.IO.Stores; using osu.Framework.Platform; using Uri = Android.Net.Uri; namespace osu.Framework.Android { public class AndroidGameHost : GameHost { private readonly AndroidGameView gameView; public AndroidGameHost(AndroidGameView gameView) { this.gameView = gameView; } protected override void SetupForRun() { base.SetupForRun(); AndroidGameWindow.View = gameView; Window = new AndroidGameWindow(); } protected override bool LimitedMemoryEnvironment => true; public override bool CanExit => false; public override bool OnScreenKeyboardOverlapsGameWindow => true; public override ITextInputSource GetTextInput() => new AndroidTextInput(gameView); protected override IEnumerable<InputHandler> CreateAvailableInputHandlers() => new InputHandler[] { new AndroidKeyboardHandler(gameView), new AndroidTouchHandler(gameView) }; protected override Storage GetStorage(string baseName) => new AndroidStorage(baseName, this); public override void OpenFileExternally(string filename) => throw new NotImplementedException(); public override void OpenUrlExternally(string url) { var activity = (Activity)gameView.Context; Uri webpage = Uri.Parse(url); Intent intent = new Intent(Intent.ActionView, webpage); if (intent.ResolveActivity(activity.PackageManager) != null) activity.StartActivity(intent); } public override IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => new AndroidTextureLoaderStore(underlyingStore); protected override void PerformExit(bool immediately) { // Do not exit on Android, Window.Run() does not block } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Android.Graphics.Textures; using osu.Framework.Android.Input; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.Input.Handlers; using osu.Framework.IO.Stores; using osu.Framework.Platform; namespace osu.Framework.Android { public class AndroidGameHost : GameHost { private readonly AndroidGameView gameView; public AndroidGameHost(AndroidGameView gameView) { this.gameView = gameView; } protected override void SetupForRun() { base.SetupForRun(); AndroidGameWindow.View = gameView; Window = new AndroidGameWindow(); } protected override bool LimitedMemoryEnvironment => true; public override bool CanExit => false; public override bool OnScreenKeyboardOverlapsGameWindow => true; public override ITextInputSource GetTextInput() => new AndroidTextInput(gameView); protected override IEnumerable<InputHandler> CreateAvailableInputHandlers() => new InputHandler[] { new AndroidKeyboardHandler(gameView), new AndroidTouchHandler(gameView) }; protected override Storage GetStorage(string baseName) => new AndroidStorage(baseName, this); public override void OpenFileExternally(string filename) => throw new NotImplementedException(); public override void OpenUrlExternally(string url) => throw new NotImplementedException(); public override IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => new AndroidTextureLoaderStore(underlyingStore); protected override void PerformExit(bool immediately) { // Do not exit on Android, Window.Run() does not block } } }
mit
C#
25b14edf2da8b7bbd528736ed0b5affcf0590f43
Fix BindableFloat.IsDefault returning true for non-default values
ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework
osu.Framework/Bindables/BindableFloat.cs
osu.Framework/Bindables/BindableFloat.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Globalization; namespace osu.Framework.Bindables { public class BindableFloat : BindableNumber<float> { // Take 50% of the precision to ensure the value doesn't underflow and return true for non-default values. public override bool IsDefault => Math.Abs(Value - Default) < (Precision / 2); protected override float DefaultMinValue => float.MinValue; protected override float DefaultMaxValue => float.MaxValue; protected override float DefaultPrecision => float.Epsilon; public BindableFloat(float value = 0) : base(value) { } public override string ToString() => Value.ToString("0.0###", NumberFormatInfo.InvariantInfo); } }
// 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.Globalization; namespace osu.Framework.Bindables { public class BindableFloat : BindableNumber<float> { public override bool IsDefault => Math.Abs(Value - Default) < Precision; protected override float DefaultMinValue => float.MinValue; protected override float DefaultMaxValue => float.MaxValue; protected override float DefaultPrecision => float.Epsilon; public BindableFloat(float value = 0) : base(value) { } public override string ToString() => Value.ToString("0.0###", NumberFormatInfo.InvariantInfo); } }
mit
C#
7e2f4af00dd2d47212f1208857bccc936b057e0d
remove whitespaces
EVAST9919/osu,2yangk23/osu,peppy/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,DrabWeb/osu,smoogipoo/osu,ppy/osu,DrabWeb/osu,UselessToucan/osu,naoey/osu,NeoAdonis/osu,EVAST9919/osu,johnneijzen/osu,DrabWeb/osu,NeoAdonis/osu,naoey/osu,ZLima12/osu,UselessToucan/osu,johnneijzen/osu,naoey/osu,smoogipoo/osu,ZLima12/osu,ppy/osu,smoogipooo/osu,ppy/osu
osu.Game.Rulesets.Osu/Mods/OsuModGrow.cs
osu.Game.Rulesets.Osu/Mods/OsuModGrow.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.Graphics; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Mods { internal class OsuModGrow : Mod, IApplicableToDrawableHitObjects { public override string Name => "Grow"; public override string Acronym => "GR"; public override FontAwesome Icon => FontAwesome.fa_arrows_v; public override ModType Type => ModType.Fun; public override string Description => "Hit them at the right size!"; public override double ScoreMultiplier => 1; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var drawable in drawables) { if (drawable is DrawableSpinner spinner) return; drawable.ApplyCustomUpdateState += applyCustomState; } } protected virtual void applyCustomState(DrawableHitObject drawable, ArmedState state) { var hitObject = (OsuHitObject) drawable.HitObject; double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1; double scaleDuration = hitObject.TimePreempt + 1; var originalScale = drawable.Scale; drawable.Scale /= 2; using (drawable.BeginAbsoluteSequence(appearTime, true)) drawable.ScaleTo(originalScale, scaleDuration, Easing.OutSine); if (drawable is DrawableHitCircle circle) using (circle.BeginAbsoluteSequence(hitObject.StartTime - hitObject.TimePreempt)) circle.ApproachCircle.Hide(); } } }
// 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.Graphics; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Mods { internal class OsuModGrow : Mod, IApplicableToDrawableHitObjects { public override string Name => "Grow"; public override string Acronym => "GR"; public override FontAwesome Icon => FontAwesome.fa_arrows_v; public override ModType Type => ModType.Fun; public override string Description => "Hit them at the right size!"; public override double ScoreMultiplier => 1; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var drawable in drawables) { if (drawable is DrawableSpinner spinner) return; drawable.ApplyCustomUpdateState += applyCustomState; } } protected virtual void applyCustomState(DrawableHitObject drawable, ArmedState state) { var hitObject = (OsuHitObject) drawable.HitObject; double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1; double scaleDuration = hitObject.TimePreempt + 1; var originalScale = drawable.Scale; drawable.Scale /= 2; using (drawable.BeginAbsoluteSequence(appearTime, true)) drawable.ScaleTo(originalScale, scaleDuration, Easing.OutSine); if (drawable is DrawableHitCircle circle) using (circle.BeginAbsoluteSequence(hitObject.StartTime - hitObject.TimePreempt)) circle.ApproachCircle.Hide(); } } }
mit
C#
36c7acfb561779da63392d1945b48cb1ecd7fe53
Set version to 3.3.0
EtienneLamoureux/TQVaultAE
src/TQVaultAE.GUI/Properties/AssemblyInfo.cs
src/TQVaultAE.GUI/Properties/AssemblyInfo.cs
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Windows.Media; // 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("TQVaultAE")] [assembly: AssemblyDescription("Extra bank space for Titan Quest Anniversary Edition")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("titanquest.net community")] [assembly: AssemblyProduct("TQVaultAE")] [assembly: AssemblyCopyright("Copyright © 2006-2012 by Brandon Wallace")] [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("40473eaa-06cd-4833-898d-0793c3d1b755")] // CLS compliant attribute //[assembly: CLSCompliant(true)] [assembly: AssemblyVersion("3.3.0")] [assembly: AssemblyFileVersion("3.3.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")] [assembly: DisableDpiAwareness]
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Windows.Media; // 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("TQVaultAE")] [assembly: AssemblyDescription("Extra bank space for Titan Quest Anniversary Edition")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("titanquest.net community")] [assembly: AssemblyProduct("TQVaultAE")] [assembly: AssemblyCopyright("Copyright © 2006-2012 by Brandon Wallace")] [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("40473eaa-06cd-4833-898d-0793c3d1b755")] // CLS compliant attribute //[assembly: CLSCompliant(true)] [assembly: AssemblyVersion("3.2.1")] [assembly: AssemblyFileVersion("3.2.1")] [assembly: NeutralResourcesLanguageAttribute("en-US")] [assembly: DisableDpiAwareness]
mit
C#
3a89cac8695cfff2f685e21f93b395cb4d62b0e2
Fix doc comment
dotnet/roslyn-analyzers,dotnet/roslyn-analyzers
src/Utilities/Compiler/Options/OptionKind.cs
src/Utilities/Compiler/Options/OptionKind.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Analyzer.Utilities { /// <summary> /// Kind of option to fetch from <see cref="ICategorizedAnalyzerConfigOptions"/>. /// </summary> internal enum OptionKind { /// <summary> /// Option prefixed with <c>dotnet_code_quality.</c>. /// <para>Used for custom analyzer config options for analyzers in this repo.</para> /// </summary> DotnetCodeQuality, /// <summary> /// Option prefixed with <c>build_property.</c>. /// <para>Used for options generated for MSBuild properties.</para> /// </summary> BuildProperty, } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Analyzer.Utilities { /// <summary> /// Kind of option to fetch from <see cref="AnalyzerOptionsExtensions"/>. /// </summary> internal enum OptionKind { /// <summary> /// Option prefixed with <c>dotnet_code_quality.</c>. /// <para>Used for custom analyzer config options for analyzers in this repo.</para> /// </summary> DotnetCodeQuality, /// <summary> /// Option prefixed with <c>build_property.</c>. /// <para>Used for options generated for MSBuild properties.</para> /// </summary> BuildProperty, } }
mit
C#
83113cfcf09ad42ecc20217a87c0293790475ea1
allow specifying a connection string in the console
Zocdoc/schemazen,sethreno/schemazen,keith-hall/schemazen,sethreno/schemazen
console/DbCommand.cs
console/DbCommand.cs
using System; using System.Data.SqlClient; using System.Diagnostics; using ManyConsole; using NDesk.Options; using SchemaZen.model; namespace SchemaZen.console { public abstract class DbCommand : ConsoleCommand { protected DbCommand(string command, string oneLineDescription) { IsCommand(command, oneLineDescription); Options = new OptionSet(); SkipsCommandSummaryBeforeRunning(); HasOption("s|server=", "server", o => Server = o); HasOption("b|database=", "database", o => DbName = o); HasOption("c|connectionString=", "connection string", o => ConnectionString = o); HasOption("u|user=", "user", o => User = o); HasOption("p|pass=", "pass", o => Pass = o); HasRequiredOption( "d|scriptDir=", "Path to database script directory.", o => ScriptDir = o); HasOption( "o|overwrite=", "Overwrite existing target without prompt.", o => Overwrite = o != null); HasOption( "v|verbose=", "Enable verbose log messages.", o => Verbose = o != null); } protected string Server { get; set; } protected string DbName { get; set; } protected string ConnectionString { get; set; } protected string User { get; set; } protected string Pass { get; set; } protected string ScriptDir { get; set; } protected bool Overwrite { get; set; } protected bool Verbose { get; set; } protected Database CreateDatabase() { if (!string.IsNullOrEmpty(ConnectionString)) { if (!string.IsNullOrEmpty(Server) || !string.IsNullOrEmpty(DbName) || !string.IsNullOrEmpty(User) || !string.IsNullOrEmpty(Pass)) { throw new ConsoleHelpAsException("You must not provide both a connection string and a server/db/user/password"); } return new Database { Connection = ConnectionString, Dir = ScriptDir }; } if (string.IsNullOrEmpty(Server) || string.IsNullOrEmpty(DbName)) { throw new ConsoleHelpAsException("You must provide a connection string, or a server and database name"); } var builder = new SqlConnectionStringBuilder { DataSource = Server, InitialCatalog = DbName, IntegratedSecurity = string.IsNullOrEmpty(User) }; if (!builder.IntegratedSecurity) { builder.UserID = User; builder.Password = Pass; } return new Database { Connection = builder.ToString(), Dir = ScriptDir }; } protected void Log(TraceLevel level, string message) { var prevColor = Console.ForegroundColor; switch (level) { case TraceLevel.Error: Console.ForegroundColor = ConsoleColor.Red; break; case TraceLevel.Verbose: if (!Verbose) return; break; case TraceLevel.Warning: //Console.ForegroundColor = ConsoleColor.Red; break; } if (message.EndsWith("\r")) Console.Write(message); else Console.WriteLine(message); Console.ForegroundColor = prevColor; } } }
using System; using System.Data.SqlClient; using System.Diagnostics; using ManyConsole; using NDesk.Options; using SchemaZen.model; namespace SchemaZen.console { public abstract class DbCommand : ConsoleCommand { protected DbCommand(string command, string oneLineDescription) { IsCommand(command, oneLineDescription); Options = new OptionSet(); SkipsCommandSummaryBeforeRunning(); HasRequiredOption("s|server=", "server", o => Server = o); HasRequiredOption("b|database=", "database", o => DbName = o); HasOption("u|user=", "user", o => User = o); HasOption("p|pass=", "pass", o => Pass = o); HasRequiredOption( "d|scriptDir=", "Path to database script directory.", o => ScriptDir = o); HasOption( "o|overwrite=", "Overwrite existing target without prompt.", o => Overwrite = o != null); HasOption( "v|verbose=", "Enable verbose log messages.", o => Verbose = o != null); } protected string Server { get; set; } protected string DbName { get; set; } protected string User { get; set; } protected string Pass { get; set; } protected string ScriptDir { get; set; } protected bool Overwrite { get; set; } protected bool Verbose { get; set; } protected Database CreateDatabase() { var builder = new SqlConnectionStringBuilder { DataSource = Server, InitialCatalog = DbName, IntegratedSecurity = string.IsNullOrEmpty(User) }; if (!builder.IntegratedSecurity) { builder.UserID = User; builder.Password = Pass; } return new Database { Connection = builder.ToString(), Dir = ScriptDir }; } protected void Log(TraceLevel level, string message) { var prevColor = Console.ForegroundColor; switch (level) { case TraceLevel.Error: Console.ForegroundColor = ConsoleColor.Red; break; case TraceLevel.Verbose: if (!Verbose) return; break; case TraceLevel.Warning: //Console.ForegroundColor = ConsoleColor.Red; break; } if (message.EndsWith("\r")) Console.Write(message); else Console.WriteLine(message); Console.ForegroundColor = prevColor; } } }
mit
C#
35a966e4f34d9df1d80e5254a5baec7f15532de5
Debug Map
plombeur/alpha,plombeur/alpha
Assets/Scripts/Patches/Map.cs
Assets/Scripts/Patches/Map.cs
using UnityEngine; using System.Collections; public class Map : MonoBehaviour { public int size_x; public int size_y; protected Patch[] patches; public GameObject prefabPatch; // Use this for initialization void Start () { // Create array of patches with script patches = new Patch[size_x*size_y]; for (int i=0; i<size_x; i++) { for (int j=0; j<size_y; j++) { //patches[i*size_x+j] = new Cailloux(); Vector3 pos = new Vector3(i + this.transform.position.x,j + this.transform.position.y, 0); patches[i*size_x+j] = ((GameObject)Instantiate(prefabPatch, pos, Quaternion.identity)).GetComponent<Patch>(); patches[i * size_x + j].gameObject.transform.SetParent(this.transform); } } //Destroy(getPatch(1.0f, 1.0f).gameObject); //Load patches into array /*patches = new Patch[size_x*size_y]; int nChildren = this.gameObject.transform.childCount; Transform currentPatch; for (int i = 0; i < nChildren; i++) { currentPatch = this.gameObject.transform.GetChild(i); patches[Mathf.FloorToInt(currentPatch.transform.position.x) * size_x + Mathf.FloorToInt(currentPatch.transform.position.y)] = currentPatch.GetComponent<Patch>(); } Destroy(getPatch(1.0f, 1.0f).gameObject);*/ } // Update is called once per frame void Update() { } public Patch getPatch(float x,float y){ return patches [Mathf.FloorToInt (x - this.transform.position.x) * this.size_x + Mathf.FloorToInt (y - this.transform.position.y)]; } public float getUpperBorder() { return this.transform.position.y + size_y - 0.5f; } public float getLowerBorder() { return this.transform.position.y - 0.5f; } public float getLeftBorder() { return this.transform.position.x - 0.5f; } public float getRightBorder() { return this.transform.position.x + size_x - 0.5f; } }
using UnityEngine; using System.Collections; public class Map : MonoBehaviour { public int size_x; public int size_y; protected Patch[] patches; public GameObject prefabPatch; // Use this for initialization void Start () { // Create array of patches with script patches = new Patch[size_x*size_y]; for (int i=0; i<size_x; i++) { for (int j=0; j<size_y; j++) { //patches[i*size_x+j] = new Cailloux(); Vector3 pos = new Vector3(i + this.transform.position.x,j + this.transform.position.y,-10); patches[i*size_x+j] = ((GameObject)Instantiate(prefabPatch, pos, Quaternion.identity)).GetComponent<Patch>(); patches[i * size_x + j].gameObject.transform.SetParent(this.transform); } } //Destroy(getPatch(1.0f, 1.0f).gameObject); //Load patches into array /*patches = new Patch[size_x*size_y]; int nChildren = this.gameObject.transform.childCount; Transform currentPatch; for (int i = 0; i < nChildren; i++) { currentPatch = this.gameObject.transform.GetChild(i); patches[Mathf.FloorToInt(currentPatch.transform.position.x) * size_x + Mathf.FloorToInt(currentPatch.transform.position.y)] = currentPatch.GetComponent<Patch>(); } Destroy(getPatch(1.0f, 1.0f).gameObject);*/ } // Update is called once per frame void Update() { } public Patch getPatch(float x,float y){ return patches [Mathf.FloorToInt (x - this.transform.position.x) * this.size_x + Mathf.FloorToInt (y - this.transform.position.y)]; } public float getUpperBorder() { return this.transform.position.y + size_y - 0.5f; } public float getLowerBorder() { return this.transform.position.y - 0.5f; } public float getLeftBorder() { return this.transform.position.x - 0.5f; } public float getRightBorder() { return this.transform.position.x + size_x - 0.5f; } }
apache-2.0
C#
01b27494e355d2fc6d3db6889fe391e10327df94
check that the assembly have the resource or not
TakeAsh/cs-WpfUtility
WpfUtility/ResourceHelper.cs
WpfUtility/ResourceHelper.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Text; using System.Windows.Media.Imaging; namespace WpfUtility { public static class ResourceHelper { public static BitmapImage GetImage(string filename) { if (filename == null) { return null; } var assembly = Assembly.GetCallingAssembly().GetName().Name; return new BitmapImage(new Uri("/" + assembly + ";component/" + filename, UriKind.Relative)); } /// <summary> /// Get text of embedded resource file /// </summary> /// <param name="filename">resource file name</param> /// <param name="encoding">encoding of file content. Default is UTF8.</param> /// <returns>content of resource file</returns> /// <remarks>The resource file must be embedded.</remarks> public static string GetText(string filename, Encoding encoding = null) { if (filename == null) { return null; } encoding = encoding ?? Encoding.UTF8; var assembly = Assembly.GetCallingAssembly(); var directory = Path.GetDirectoryName(filename).Replace('-', '_'); var file = Path.GetFileName(filename); var resourceName = Path.Combine(assembly.GetName().Name, directory, file).Replace('\\', '.').Replace('/', '.'); using (var stream = assembly.GetManifestResourceStream(resourceName)) using (var reader = new StreamReader(stream, encoding)) { return reader.ReadToEnd(); } } public static ResourceManager GetResourceManager(Object obj) { Assembly assembly; if (obj == null || (assembly = obj.GetType().Assembly) == null) { return null; } var resourceName = assembly.GetName().Name + ".Properties.Resources"; if (!assembly.GetManifestResourceNames().Contains(resourceName + ".resources")) { return null; } return new ResourceManager(resourceName, assembly); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Text; using System.Windows.Media.Imaging; namespace WpfUtility { public static class ResourceHelper { public static BitmapImage GetImage(string filename) { if (filename == null) { return null; } var assembly = Assembly.GetCallingAssembly().GetName().Name; return new BitmapImage(new Uri("/" + assembly + ";component/" + filename, UriKind.Relative)); } /// <summary> /// Get text of embedded resource file /// </summary> /// <param name="filename">resource file name</param> /// <param name="encoding">encoding of file content. Default is UTF8.</param> /// <returns>content of resource file</returns> /// <remarks>The resource file must be embedded.</remarks> public static string GetText(string filename, Encoding encoding = null) { if (filename == null) { return null; } encoding = encoding ?? Encoding.UTF8; var assembly = Assembly.GetCallingAssembly(); var directory = Path.GetDirectoryName(filename).Replace('-', '_'); var file = Path.GetFileName(filename); var resourceName = Path.Combine(assembly.GetName().Name, directory, file).Replace('\\', '.').Replace('/', '.'); using (var stream = assembly.GetManifestResourceStream(resourceName)) using (var reader = new StreamReader(stream, encoding)) { return reader.ReadToEnd(); } } public static ResourceManager GetResourceManager(Object obj) { Assembly assembly; ResourceManager resourceManager; if (obj == null || (assembly = obj.GetType().Assembly) == null || (resourceManager = new ResourceManager(assembly.GetName().Name + ".Properties.Resources", assembly)) == null) { return null; } return resourceManager; } } }
mit
C#
86cc010df40d362917c46c3f5551192a06d0041a
Use static HttpClient in SO module
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX
Modix.Services/StackExchange/StackExchangeService.cs
Modix.Services/StackExchange/StackExchangeService.cs
using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Modix.Services.StackExchange { public class StackExchangeService { private static HttpClient HttpClient => new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); private string _ApiReferenceUrl = $"http://api.stackexchange.com/2.2/search/advanced" + "?key={0}" + $"&order=desc" + $"&sort=votes" + $"&filter=default"; public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags) { _ApiReferenceUrl = string.Format(_ApiReferenceUrl, token); phrase = Uri.EscapeDataString(phrase); site = Uri.EscapeDataString(site); tags = Uri.EscapeDataString(tags); var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}"; var response = await HttpClient.GetAsync(query); if (!response.IsSuccessStatusCode) { throw new WebException("Something failed while querying the Stack Exchange API."); } var jsonResponse = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<StackExchangeResponse>(jsonResponse); } } }
using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Modix.Services.StackExchange { public class StackExchangeService { private string _ApiReferenceUrl = $"http://api.stackexchange.com/2.2/search/advanced" + "?key={0}" + $"&order=desc" + $"&sort=votes" + $"&filter=default"; public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags) { _ApiReferenceUrl = string.Format(_ApiReferenceUrl, token); phrase = Uri.EscapeDataString(phrase); site = Uri.EscapeDataString(site); tags = Uri.EscapeDataString(tags); var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}"; var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); var response = await client.GetAsync(query); if (!response.IsSuccessStatusCode) { throw new WebException("Something failed while querying the Stack Exchange API."); } var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<StackExchangeResponse>(json); } } }
mit
C#
8813f95eb411b712905df627d2ebcf110d2d8231
Fix EmployeeFindQuery
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University.Employees/Queries/EmployeeFindQuery.cs
R7.University.Employees/Queries/EmployeeFindQuery.cs
// // EmployeeFindQuery.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016-2018 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Collections.Generic; using System.Linq; using R7.Dnn.Extensions.Models; using R7.University.Models; using R7.University.Queries; namespace R7.University.Employees.Queries { internal class EmployeeFindQuery: QueryBase { public EmployeeFindQuery (IModelContext modelContext): base (modelContext) { } public IEnumerable<EmployeeInfo> FindEmployees (string searchText, bool teachersOnly, int divisionId) { // TODO: Remove @includeSubdivisions parameter from University_FindEmployees sp return ModelContext.Query<EmployeeInfo> ( "EXECUTE {objectQualifier}University_FindEmployees {0}, {1}, 1, {2}", searchText, teachersOnly, divisionId ).ToList ().Distinct (new EntityEqualityComparer<EmployeeInfo> (e => e.EmployeeID)); } } }
// // EmployeeFindQuery.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Collections.Generic; using System.Linq; using R7.Dnn.Extensions.Models; using R7.University.Models; using R7.University.Queries; namespace R7.University.Employees.Queries { internal class EmployeeFindQuery: QueryBase { public EmployeeFindQuery (IModelContext modelContext): base (modelContext) { } public IEnumerable<EmployeeInfo> FindEmployees (string searchText, bool teachersOnly, int divisionId) { // TODO: Remove @includeSubdivisions parameter from University_FindEmployees sp KeyValuePair<string, object> [] parameters = { new KeyValuePair<string, object> ("searchText", searchText), new KeyValuePair<string, object> ("teachersOnly", teachersOnly), new KeyValuePair<string, object> ("includeSubdivisions", true), new KeyValuePair<string, object> ("divisionId", divisionId) }; return ModelContext.Query<EmployeeInfo> ("{objectQualifier}University_FindEmployees", parameters) .Distinct (new EntityEqualityComparer<EmployeeInfo> (e => e.EmployeeID)); } } }
agpl-3.0
C#
be070a17538a0ccbc2d34d3ff45d1817d34d3489
extend stance color converter
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/Converters/WarriorStanceToColorConverter.cs
TCC.Core/Converters/WarriorStanceToColorConverter.cs
using System; using System.Globalization; using System.Windows; using System.Windows.Data; using System.Windows.Media; using TCC.Data; namespace TCC.Converters { public class WarriorStanceToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var col = parameter != null && parameter.ToString().IndexOf("color", StringComparison.Ordinal) != -1; var light = parameter != null && parameter.ToString().IndexOf("light", StringComparison.Ordinal) != -1; var fallback = parameter != null && parameter.ToString().IndexOf("fallback", StringComparison.Ordinal) != -1; var lightFback = Colors.DarkGray; lightFback.A = 170; var color = fallback ? light ? Colors.White : lightFback : Colors.Transparent; if (value != null) { var s = (WarriorStance)value; switch (s) { case WarriorStance.Assault: color = (Color)Application.Current.FindResource($"AssaultStanceColor{(light ? "Light" : "")}"); break; case WarriorStance.Defensive: color = (Color)Application.Current.FindResource($"DefensiveStanceColor{(light ? "Light" : "")}"); break; } } if (col) return color; return new SolidColorBrush(color); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Globalization; using System.Windows; using System.Windows.Data; using System.Windows.Media; using TCC.Data; namespace TCC.Converters { public class WarriorStanceToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { var s = (WarriorStance)value; switch (s) { default: return Application.Current.FindResource("RevampBorderBrush"); case WarriorStance.Assault: return Application.Current.FindResource("AssaultStanceBrush"); case WarriorStance.Defensive: return Application.Current.FindResource("DefensiveStanceBrush"); } } else return Brushes.Transparent; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
mit
C#
182ffc8b8123098425ad7610b7e86bd30bf54ada
Set AssemblyInfo
GlobeBMG/GBMG.Monitoring
source/GBMG.Monitoring/Properties/AssemblyInfo.cs
source/GBMG.Monitoring/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GBMG monitoring and telemetry abstraction")] [assembly: AssemblyDescription("A generic interface for sending custom metrics and telemetry to the configured monitoring provider")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Globe Business Media Group")] [assembly: AssemblyProduct("GBMG.Monitoring")] [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("e0eac5b4-d8e1-4060-9e37-4e1f25ccbd8e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 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("GBMG.Monitoring")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GBMG.Monitoring")] [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("e0eac5b4-d8e1-4060-9e37-4e1f25ccbd8e")] // 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#
1b237dd84b848684f2b050532e0f49029d011407
Fix pitch in CupShuffle
Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,plrusek/NitoriWare
Assets/Resources/Microgames/_Finished/CupShuffle/Scripts/CupShuffleController.cs
Assets/Resources/Microgames/_Finished/CupShuffle/Scripts/CupShuffleController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CupShuffleController : MonoBehaviour { public static CupShuffleController instance; public int cupCount, shuffleCount; public float shuffleTime, shuffleStartDelay; public bool enableBackwardsShuffles; public float fakeOutChance; public GameObject cupPrefab; public AudioClip shuffleClip, correctClip, incorrectClip; private CupShuffleCup[] cups; private AudioSource _audioSource; [SerializeField] private State _state; public State state { get { return _state; } set { _state = value; for (int i = 0; i < cups.Length; cups[i++].state = state);} } public enum State { Idle, Shuffling, Choose, Victory, Loss } void Awake() { instance = this; _audioSource = GetComponent<AudioSource>(); //_audioSource.pitch = Time.timeScale; } void Start() { int correctCup = Random.Range(0, cupCount); cups = new CupShuffleCup[cupCount]; for (int i = 0; i < cupCount; i++) { cups[i] = GameObject.Instantiate(cupPrefab).GetComponent<CupShuffleCup>(); cups[i].position = i; cups[i].isCorrect = i == correctCup; } StartCoroutine(playAnimations()); } private IEnumerator playAnimations() { yield return new WaitForSeconds(shuffleStartDelay); state = State.Shuffling; for (int i = 0; i < shuffleCount; i++) { shuffle(); yield return new WaitForSeconds(shuffleTime); } yield return new WaitForSeconds(shuffleTime / 3f); MicrogameController.instance.displayLocalizedCommand("commandb", "Choose!"); state = State.Choose; } public void victory() { state = State.Victory; MicrogameController.instance.setVictory(true, true); _audioSource.PlayOneShot(correctClip); } public void failure() { state = State.Loss; MicrogameController.instance.setVictory(false, true); _audioSource.PlayOneShot(incorrectClip); } void shuffle() { int indexA = Random.Range(0, cupCount), indexB; do {indexB = Random.Range(0, cupCount);} while (indexA == indexB); bool cupAUp = Random.value < .5f, backwards = enableBackwardsShuffles ? MathHelper.randomBool() : false, fakeout = Random.value < fakeOutChance; CupShuffleCup cupA = cups[indexA], cupB = cups[indexB]; cupA.endAnimation(); cupB.endAnimation(); cupA.startAnimation(cupB.position - cupA.position, shuffleTime, cupAUp, backwards, fakeout); cupB.startAnimation(cupA.position - cupB.position, shuffleTime, !cupAUp, backwards, fakeout); _audioSource.PlayOneShot(shuffleClip); } void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CupShuffleController : MonoBehaviour { public static CupShuffleController instance; public int cupCount, shuffleCount; public float shuffleTime, shuffleStartDelay; public bool enableBackwardsShuffles; public float fakeOutChance; public GameObject cupPrefab; public AudioClip shuffleClip, correctClip, incorrectClip; private CupShuffleCup[] cups; private AudioSource _audioSource; [SerializeField] private State _state; public State state { get { return _state; } set { _state = value; for (int i = 0; i < cups.Length; cups[i++].state = state);} } public enum State { Idle, Shuffling, Choose, Victory, Loss } void Awake() { instance = this; _audioSource = GetComponent<AudioSource>(); _audioSource.pitch = Time.timeScale; } void Start() { int correctCup = Random.Range(0, cupCount); cups = new CupShuffleCup[cupCount]; for (int i = 0; i < cupCount; i++) { cups[i] = GameObject.Instantiate(cupPrefab).GetComponent<CupShuffleCup>(); cups[i].position = i; cups[i].isCorrect = i == correctCup; } StartCoroutine(playAnimations()); } private IEnumerator playAnimations() { yield return new WaitForSeconds(shuffleStartDelay); state = State.Shuffling; for (int i = 0; i < shuffleCount; i++) { shuffle(); yield return new WaitForSeconds(shuffleTime); } yield return new WaitForSeconds(shuffleTime / 3f); MicrogameController.instance.displayLocalizedCommand("commandb", "Choose!"); state = State.Choose; } public void victory() { state = State.Victory; MicrogameController.instance.setVictory(true, true); _audioSource.PlayOneShot(correctClip); } public void failure() { state = State.Loss; MicrogameController.instance.setVictory(false, true); _audioSource.PlayOneShot(incorrectClip); } void shuffle() { int indexA = Random.Range(0, cupCount), indexB; do {indexB = Random.Range(0, cupCount);} while (indexA == indexB); bool cupAUp = Random.value < .5f, backwards = enableBackwardsShuffles ? MathHelper.randomBool() : false, fakeout = Random.value < fakeOutChance; CupShuffleCup cupA = cups[indexA], cupB = cups[indexB]; cupA.endAnimation(); cupB.endAnimation(); cupA.startAnimation(cupB.position - cupA.position, shuffleTime, cupAUp, backwards, fakeout); cupB.startAnimation(cupA.position - cupB.position, shuffleTime, !cupAUp, backwards, fakeout); _audioSource.PlayOneShot(shuffleClip); } void Update () { } }
mit
C#
54127fdea334bdbb8c9fbdda2e1dc1c79c94fca2
Use reference check for null check this is much faster than delegating that to the full op == implementation
EamonNerbonne/ValueUtils,EamonNerbonne/ValueUtils,EamonNerbonne/ValueUtils
ValueUtils/ValueObject.cs
ValueUtils/ValueObject.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ValueUtils { /// <summary> /// Represents a C# object with value semantics. /// ValueObjects implements GetHashCode, Equals, IEquatable<> and operators == and != for you. /// /// A class deriving from ValueObject should pass itself as /// the generic type parameter to ValueObject. ValueObjects must be sealed. /// </summary> /// <typeparam name="T">The sealed subclass of ValueObject.</typeparam> public abstract class ValueObject<T> : IEquatable<T> where T : ValueObject<T> { //CRTP to encourage you to use the value type itself as the type parameter. //However, we cannot prevent the following: ClassA : ValueObject<ClassA> //and ClassB : ValueObject<ClassA> //If you do that, then GetHashCode and Equals will crash with an invalid cast exception. static readonly Func<T, T, bool> equalsFunc = FieldwiseEquality<T>.Instance; static readonly Func<T, int> hashFunc = FieldwiseHasher<T>.Instance; static ValueObject() { if (!typeof(T).IsSealed) throw new NotSupportedException("Value objects must be sealed."); } public sealed override bool Equals(object obj) { return obj is T && equalsFunc((T)this, (T)obj); } public bool Equals(T obj) { return (object)obj != null && equalsFunc((T)this, obj); } //optimization note: (object)obj == null is equivalent to ReferenceEquals(obj, null) but faster. public sealed override int GetHashCode() { return hashFunc((T)this); } public static bool operator !=(ValueObject<T> a, T b) { return (object)a != b && ((object)a == null || (object)b == null || !equalsFunc((T)a, b)); } public static bool operator ==(ValueObject<T> a, T b) { return (object)a == b || (object)a != null && (object)b != null && equalsFunc((T)a, b); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ValueUtils { /// <summary> /// Represents a C# object with value semantics. /// ValueObjects implements GetHashCode, Equals, IEquatable<> and operators == and != for you. /// /// A class deriving from ValueObject should pass itself as /// the generic type parameter to ValueObject. ValueObjects must be sealed. /// </summary> /// <typeparam name="T">The sealed subclass of ValueObject.</typeparam> public abstract class ValueObject<T> : IEquatable<T> where T : ValueObject<T> { //CRTP to encourage you to use the value type itself as the type parameter. //However, we cannot prevent the following: ClassA : ValueObject<ClassA> //and ClassB : ValueObject<ClassA> //If you do that, then GetHashCode and Equals will crash with an invalid cast exception. static readonly Func<T, T, bool> equalsFunc = FieldwiseEquality<T>.Instance; static readonly Func<T, int> hashFunc = FieldwiseHasher<T>.Instance; static ValueObject() { if (!typeof(T).IsSealed) throw new NotSupportedException("Value objects must be sealed."); } public sealed override bool Equals(object obj) { return obj is T && equalsFunc((T)this, (T)obj); } public bool Equals(T obj) { return obj != null && equalsFunc((T)this, obj); } public sealed override int GetHashCode() { return hashFunc((T)this); } public static bool operator !=(ValueObject<T> a, T b) { return (object)a != b && ((object)a == null || (object)b == null || !equalsFunc((T)a, b)); } public static bool operator ==(ValueObject<T> a, T b) { return (object)a == b || (object)a != null && (object)b != null && equalsFunc((T)a, b); } } }
apache-2.0
C#
e80f0e813c1b19f35c89e888a93c5e294d4dc5ee
remove uneeded using
YoloDev/elephanet,YoloDev/elephanet
Elephanet/IDocumentSession.cs
Elephanet/IDocumentSession.cs
using System; using System.Collections.Generic; namespace Elephanet { public interface IDocumentSession : IDisposable { void Delete<T>(Guid id); void Delete<T>(T entity); T GetById<T>(Guid id); IEnumerable<T> GetByIds<T>(IEnumerable<Guid> ids); IEnumerable<T> GetAll<T>(); IJsonbQueryable<T> Query<T>(); void SaveChanges(); void Store<T>(T entity); void DeleteAll<T>(); } }
using System; using System.Collections.Generic; using System.Linq; namespace Elephanet { public interface IDocumentSession : IDisposable { void Delete<T>(Guid id); void Delete<T>(T entity); T GetById<T>(Guid id); IEnumerable<T> GetByIds<T>(IEnumerable<Guid> ids); IEnumerable<T> GetAll<T>(); IJsonbQueryable<T> Query<T>(); void SaveChanges(); void Store<T>(T entity); void DeleteAll<T>(); } }
mit
C#
787086fe18e28494bf74742be02e712d210fd21a
Enable skip if debugger attached.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/AddWallet/Create/ConfirmRecoveryWordsViewModel.cs
WalletWasabi.Fluent/ViewModels/AddWallet/Create/ConfirmRecoveryWordsViewModel.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using DynamicData; using DynamicData.Binding; using NBitcoin; using ReactiveUI; using WalletWasabi.Blockchain.Keys; using WalletWasabi.Fluent.ViewModels.Navigation; using WalletWasabi.Wallets; namespace WalletWasabi.Fluent.ViewModels.AddWallet.Create { public partial class ConfirmRecoveryWordsViewModel : RoutableViewModel { private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords; [AutoNotify] private bool _isSkipEnable; public ConfirmRecoveryWordsViewModel(List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager) { Title = "Confirm recovery words"; var confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>(); _isSkipEnable = walletManager.Network != Network.Main || System.Diagnostics.Debugger.IsAttached; var nextCommandCanExecute = confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .WhenValueChanged(x => x.IsConfirmed) .Select(_ => confirmationWordsSourceList.Items.All(x => x.IsConfirmed)); NextCommand = ReactiveCommand.Create( () => { Navigate().To(new AddedWalletPageViewModel(walletManager, keyManager, WalletType.Normal)); }, nextCommandCanExecute); if (_isSkipEnable) { SkipCommand = ReactiveCommand.Create(() => NextCommand.Execute(null)); } CancelCommand = ReactiveCommand.Create(() => Navigate().Clear()); confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .OnItemAdded(x => x.Reset()) .Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index)) .Bind(out _confirmationWords) .Subscribe(); // Select 4 random words to confirm. confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(_ => new Random().NextDouble()).Take(4)); } public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using DynamicData; using DynamicData.Binding; using NBitcoin; using ReactiveUI; using WalletWasabi.Blockchain.Keys; using WalletWasabi.Fluent.ViewModels.Navigation; using WalletWasabi.Wallets; namespace WalletWasabi.Fluent.ViewModels.AddWallet.Create { public partial class ConfirmRecoveryWordsViewModel : RoutableViewModel { private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords; [AutoNotify] private bool _isSkipEnable; public ConfirmRecoveryWordsViewModel(List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager) { Title = "Confirm recovery words"; var confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>(); _isSkipEnable = walletManager.Network != Network.Main; var nextCommandCanExecute = confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .WhenValueChanged(x => x.IsConfirmed) .Select(_ => confirmationWordsSourceList.Items.All(x => x.IsConfirmed)); NextCommand = ReactiveCommand.Create( () => { Navigate().To(new AddedWalletPageViewModel(walletManager, keyManager, WalletType.Normal)); }, nextCommandCanExecute); if (_isSkipEnable) { SkipCommand = ReactiveCommand.Create(() => NextCommand.Execute(null)); } CancelCommand = ReactiveCommand.Create(() => Navigate().Clear()); confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .OnItemAdded(x => x.Reset()) .Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index)) .Bind(out _confirmationWords) .Subscribe(); // Select 4 random words to confirm. confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(_ => new Random().NextDouble()).Take(4)); } public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords; } }
mit
C#
733eab49d877d4581e6f537a8d597c9422918df8
Update version.
dougludlow/umbraco-navbuilder,dougludlow/umbraco-navbuilder
src/Cob.Umb.NavBuilder/Properties/AssemblyInfo.cs
src/Cob.Umb.NavBuilder/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("Cob.Umb.NavBuilder")] [assembly: AssemblyDescription("NavBuilder for Umbraco 7.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("City of Boise")] [assembly: AssemblyProduct("Cob.Umb.NavBuilder")] [assembly: AssemblyCopyright("Copyright © City of Boise 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a2ec16c7-5dbf-4758-8e15-15b42ec8dc5b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.5.0")] [assembly: AssemblyFileVersion("0.9.5.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("Cob.Umb.NavBuilder")] [assembly: AssemblyDescription("NavBuilder for Umbraco 7.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("City of Boise")] [assembly: AssemblyProduct("Cob.Umb.NavBuilder")] [assembly: AssemblyCopyright("Copyright © City of Boise 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a2ec16c7-5dbf-4758-8e15-15b42ec8dc5b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")]
mit
C#
9120a77fb7806b891172a81f4c84777fdc1a8c11
Test operation for dev
noordwind/Coolector,noordwind/Coolector.Api,noordwind/Collectively.Api,noordwind/Coolector.Api,noordwind/Collectively.Api,noordwind/Coolector
src/Collectively.Api/Modules/DevelopmentModule.cs
src/Collectively.Api/Modules/DevelopmentModule.cs
using System; using Collectively.Api.Commands; using Collectively.Api.Storages; using Collectively.Api.Validation; using Collectively.Services.Storage.Models.Operations; using Nancy; namespace Collectively.Api.Modules { public class DevelopmentModule : ModuleBase { private static int RequestCounter = 0; public DevelopmentModule(ICommandDispatcher commandDispatcher, IValidatorResolver validatorResolver, IOperationStorage operationStorage) : base(commandDispatcher, validatorResolver, modulePath: "development") { Get("operation", args => { RequestCounter++; if(RequestCounter <= 2) { return HttpStatusCode.NotFound; } if(RequestCounter == 3) { return HttpStatusCode.Unauthorized; } if(RequestCounter == 8) { RequestCounter = 0; } return new Operation { Id = Guid.NewGuid(), RequestId = Guid.NewGuid(), CreatedAt = DateTime.UtcNow, State = "completed" }; }); } } }
using System; using Collectively.Api.Commands; using Collectively.Api.Storages; using Collectively.Api.Validation; using Collectively.Services.Storage.Models.Operations; namespace Collectively.Api.Modules { public class DevelopmentModule : ModuleBase { private static int RequestCounter = 0; public DevelopmentModule(ICommandDispatcher commandDispatcher, IValidatorResolver validatorResolver, IOperationStorage operationStorage) : base(commandDispatcher, validatorResolver, modulePath: "development") { Get("operation", args => { var state = "created"; RequestCounter++; if(RequestCounter == 10) { state = "completed"; RequestCounter = 0; } return new Operation { Id = Guid.NewGuid(), RequestId = Guid.NewGuid(), CreatedAt = DateTime.UtcNow, State = state }; }); } } }
mit
C#
e3f9ef08343d44e1f1be47f81cd275091aa5f54b
Set version 0.8.1
morgen2009/DelegateDecompiler,hazzik/DelegateDecompiler,jaenyph/DelegateDecompiler
src/DelegateDecompiler/Properties/AssemblyInfo.cs
src/DelegateDecompiler/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("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012 - 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cec0a257-502b-4718-91c3-9e67555c5e1b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.1.0")] [assembly: AssemblyFileVersion("0.8.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012 - 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cec0a257-502b-4718-91c3-9e67555c5e1b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.0.0")] [assembly: AssemblyFileVersion("0.8.0.0")]
mit
C#
5b5ded0e502e792df4178a49bab162d76071b42c
Allow lower precision in angle tests
feliwir/openSage,feliwir/openSage
src/OpenSage.Game.Tests/Mathematics/AngleTests.cs
src/OpenSage.Game.Tests/Mathematics/AngleTests.cs
using System.Numerics; using OpenSage.Mathematics; using Xunit; namespace OpenSage.Tests.Mathematics { public class AngleTests { private const int Precision = 6; [Fact] public void DegreesToRadiansTest() { Assert.Equal(MathUtility.ToRadians(90.0f), MathUtility.PiOver2, Precision); } [Fact] public void RadiansToDegreesTest() { Assert.Equal(90.0f, MathUtility.ToDegrees(MathUtility.PiOver2), Precision); } [Theory] [InlineData(0.0f, 1.0f, 90.0f)] [InlineData(1.0f, 0.0f, 0.0f)] [InlineData(0.0f, -1.0f, -90.0f)] [InlineData(-1.0f, 0.0f, 180.0f)] public void GetYawFromDirectionTest(float x, float y, float angle) { Assert.Equal(angle, MathUtility.ToDegrees(MathUtility.GetYawFromDirection(new Vector2(x, y))), Precision); } [Theory] [InlineData(0.0f, 0.0f, 1.0f, 0.0f)] [InlineData(0.0f, 1.0f, 0.0f, 90.0f)] [InlineData(0.1f, 0.1f, 0.8f, 10.024973f)] public void GetPitchFromDirectionTest(float x, float y, float z, float angle) { var vec = Vector3.Normalize(new Vector3(x, y, z)); Assert.Equal(angle, MathUtility.ToDegrees(MathUtility.GetPitchFromDirection(vec)), Precision); } [Theory] [InlineData(90.0f, 180.0f, 90.0f)] [InlineData(90.0f, -180.0f, 90.0f)] [InlineData(90.0f, 0.0f, -90.0f)] public void AngleDeltaTest(float alpha, float beta, float delta) { var alphaRad = MathUtility.ToRadians(alpha); var betaRad = MathUtility.ToRadians(beta); var deltaRad = MathUtility.ToRadians(delta); Assert.Equal(deltaRad, MathUtility.CalculateAngleDelta(alphaRad, betaRad), Precision); } } }
using System.Numerics; using OpenSage.Mathematics; using Xunit; namespace OpenSage.Tests.Mathematics { public class AngleTests { [Fact] public void DegreesToRadiansTest() { Assert.Equal(MathUtility.ToRadians(90.0f), MathUtility.PiOver2); } [Fact] public void RadiansToDegreesTest() { Assert.Equal(90.0f, MathUtility.ToDegrees(MathUtility.PiOver2)); } [Theory] [InlineData(0.0f, 1.0f, 90.0f)] [InlineData(1.0f, 0.0f, 0.0f)] [InlineData(0.0f, -1.0f, -90.0f)] [InlineData(-1.0f, 0.0f, 180.0f)] public void GetYawFromDirectionTest(float x, float y, float angle) { Assert.Equal(angle, MathUtility.ToDegrees(MathUtility.GetYawFromDirection(new Vector2(x, y)))); } [Theory] [InlineData(0.0f, 0.0f, 1.0f, 0.0f)] [InlineData(0.0f, 1.0f, 0.0f, 90.0f)] [InlineData(0.1f, 0.1f, 0.8f, 10.024973f)] public void GetPitchFromDirectionTest(float x, float y, float z, float angle) { var vec = Vector3.Normalize(new Vector3(x, y, z)); Assert.Equal(angle, MathUtility.ToDegrees(MathUtility.GetPitchFromDirection(vec))); } [Theory] [InlineData(90.0f, 180.0f, 90.0f)] [InlineData(90.0f, -180.0f, 90.0f)] [InlineData(90.0f, 0.0f, -90.0f)] public void AngleDeltaTest(float alpha, float beta, float delta) { var alphaRad = MathUtility.ToRadians(alpha); var betaRad = MathUtility.ToRadians(beta); var deltaRad = MathUtility.ToRadians(delta); Assert.Equal(deltaRad, MathUtility.CalculateAngleDelta(alphaRad, betaRad), 3); } } }
mit
C#
27fcebb5dc48184bc1ea11ab8928282eadbba0a2
Remove unused using directive
ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework
osu.Framework/Input/Events/JoystickEvent.cs
osu.Framework/Input/Events/JoystickEvent.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 System.Linq; using JetBrains.Annotations; using osu.Framework.Input.States; namespace osu.Framework.Input.Events { public abstract class JoystickEvent : UIEvent { protected JoystickEvent([NotNull] InputState state) : base(state) { } /// <summary> /// List of currently pressed joystick buttons. /// </summary> public IEnumerable<JoystickButton> PressedButtons => CurrentState.Joystick.Buttons; /// <summary> /// List of joystick axes. Axes which have zero value may be omitted. /// </summary> public IEnumerable<JoystickAxis> Axes => CurrentState.Joystick.GetAxes().Where(j => j.Value != 0); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using osu.Framework.Input.States; using osu.Framework.Utils; namespace osu.Framework.Input.Events { public abstract class JoystickEvent : UIEvent { protected JoystickEvent([NotNull] InputState state) : base(state) { } /// <summary> /// List of currently pressed joystick buttons. /// </summary> public IEnumerable<JoystickButton> PressedButtons => CurrentState.Joystick.Buttons; /// <summary> /// List of joystick axes. Axes which have zero value may be omitted. /// </summary> public IEnumerable<JoystickAxis> Axes => CurrentState.Joystick.GetAxes().Where(j => j.Value != 0); } }
mit
C#
ae20a6d59ab07746328245991e61a61905c26a6b
Remove outdated + potentially incorrect comment
smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework/Timing/ThrottledFrameClock.cs
osu.Framework/Timing/ThrottledFrameClock.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using System.Threading; namespace osu.Framework.Timing { /// <summary> /// A FrameClock which will limit the number of frames processed by adding Thread.Sleep calls on each ProcessFrame. /// </summary> public class ThrottledFrameClock : FramedClock { /// <summary> /// The number of updated per second which is permitted. /// </summary> public double MaximumUpdateHz = 1000.0; /// <summary> /// The time spent in a Thread.Sleep state during the last frame. /// </summary> public double TimeSlept { get; private set; } public override void ProcessFrame() { Debug.Assert(MaximumUpdateHz >= 0); base.ProcessFrame(); if (MaximumUpdateHz > 0) { throttle(); } else { // Even when running at unlimited frame-rate, we should call the scheduler // to give lower-priority background processes a chance to do work. TimeSlept = sleepAndUpdateCurrent(0); } Debug.Assert(TimeSlept <= ElapsedFrameTime); } private double accumulatedSleepError; private void throttle() { double excessFrameTime = 1000d / MaximumUpdateHz - ElapsedFrameTime; TimeSlept = sleepAndUpdateCurrent((int)Math.Max(0, excessFrameTime + accumulatedSleepError)); accumulatedSleepError += excessFrameTime - TimeSlept; } private double sleepAndUpdateCurrent(int milliseconds) { double before = CurrentTime; Thread.Sleep(milliseconds); return (CurrentTime = SourceTime) - before; } } }
// 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.Diagnostics; using System.Threading; namespace osu.Framework.Timing { /// <summary> /// A FrameClock which will limit the number of frames processed by adding Thread.Sleep calls on each ProcessFrame. /// </summary> public class ThrottledFrameClock : FramedClock { /// <summary> /// The number of updated per second which is permitted. /// </summary> public double MaximumUpdateHz = 1000.0; /// <summary> /// The time spent in a Thread.Sleep state during the last frame. /// </summary> public double TimeSlept { get; private set; } public override void ProcessFrame() { Debug.Assert(MaximumUpdateHz >= 0); base.ProcessFrame(); if (MaximumUpdateHz > 0) { throttle(); } else { // Even when running at unlimited frame-rate, we should call the scheduler // to give lower-priority background processes a chance to do work. TimeSlept = sleepAndUpdateCurrent(0); } Debug.Assert(TimeSlept <= ElapsedFrameTime); } private double accumulatedSleepError; private void throttle() { double excessFrameTime = 1000d / MaximumUpdateHz - ElapsedFrameTime; TimeSlept = sleepAndUpdateCurrent((int)Math.Max(0, excessFrameTime + accumulatedSleepError)); // Sleep is not guaranteed to be an exact time; it only guaranteed to sleep AT LEAST the specified time. // Accumulated erroris usd accumulatedSleepError += excessFrameTime - TimeSlept; } private double sleepAndUpdateCurrent(int milliseconds) { double before = CurrentTime; Thread.Sleep(milliseconds); return (CurrentTime = SourceTime) - before; } } }
mit
C#
916c5bb3a361cd4dbb74fc8836c304cb49bf194f
Hide constructor
AngleSharp/AngleSharp,FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local,AngleSharp/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,Livven/AngleSharp,AngleSharp/AngleSharp,Livven/AngleSharp,FlorianRappl/AngleSharp,Livven/AngleSharp,AngleSharp/AngleSharp,zedr0n/AngleSharp.Local,FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local
AngleSharp/DOM/Css/Values/CSSValue.cs
AngleSharp/DOM/Css/Values/CSSValue.cs
namespace AngleSharp.DOM.Css { using System; /// <summary> /// Represents a CSS value. /// </summary> sealed class CssValue : ICssValue { #region Fields readonly CssValueType _type; readonly String _text; #endregion #region Special Values /// <summary> /// Gets the instance for an inherited value. /// </summary> public static readonly CssValue Inherit = new CssValue(Keywords.Inherit, CssValueType.Inherit); /// <summary> /// Gets the instance for an initial value. /// </summary> public static readonly CssValue Initial = new CssValue(Keywords.Initial, CssValueType.Initial); /// <summary> /// Gets the instance for a slash delimiter value. /// </summary> internal static readonly CssValue Delimiter = new CssValue("/"); /// <summary> /// Gets the instance for a comma separator value. /// </summary> internal static readonly CssValue Separator = new CssValue(","); #endregion #region ctor /// <summary> /// Creates a new CSS value. /// </summary> /// <param name="text">The text that represents the value.</param> /// <param name="type">The type of of the value.</param> CssValue(String text, CssValueType type) { _text = text; _type = type; } /// <summary> /// Creates a new custom CSS value. /// </summary> /// <param name="text">The text that represents the value.</param> internal CssValue(String text) : this(text, CssValueType.Custom) { } #endregion #region Properties /// <summary> /// Gets a code defining the type of the value as defined above. /// </summary> public CssValueType Type { get { return _type; } } /// <summary> /// Gets or sets a string representation of the current value. /// </summary> public String CssText { get { return _text; } } #endregion } }
namespace AngleSharp.DOM.Css { using System; /// <summary> /// Represents a CSS value. /// </summary> sealed class CssValue : ICssValue { #region Fields readonly CssValueType _type; readonly String _text; #endregion #region Special Values /// <summary> /// Gets the instance for an inherited value. /// </summary> public static readonly CssValue Inherit = new CssValue(Keywords.Inherit, CssValueType.Inherit); /// <summary> /// Gets the instance for an initial value. /// </summary> public static readonly CssValue Initial = new CssValue(Keywords.Initial, CssValueType.Initial); /// <summary> /// Gets the instance for a slash delimiter value. /// </summary> internal static readonly CssValue Delimiter = new CssValue("/"); /// <summary> /// Gets the instance for a comma separator value. /// </summary> internal static readonly CssValue Separator = new CssValue(","); #endregion #region ctor /// <summary> /// Creates a new CSS value. /// </summary> /// <param name="text">The text that represents the value.</param> /// <param name="type">The type of of the value.</param> protected CssValue(String text, CssValueType type) { _text = text; _type = type; } /// <summary> /// Creates a new custom CSS value. /// </summary> /// <param name="text">The text that represents the value.</param> internal CssValue(String text) : this(text, CssValueType.Custom) { } #endregion #region Properties /// <summary> /// Gets a code defining the type of the value as defined above. /// </summary> public CssValueType Type { get { return _type; } } /// <summary> /// Gets or sets a string representation of the current value. /// </summary> public String CssText { get { return _text; } } #endregion } }
mit
C#
d415ef4495984529600dca2621d1ea89be2c2fe9
Remove some old and incorrect FIXMEs
symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix
symbooglix/symbooglix/Core/StateScheduler.cs
symbooglix/symbooglix/Core/StateScheduler.cs
using System; using System.Collections.Generic; using System.Diagnostics; namespace symbooglix { public interface IStateScheduler { ExecutionState getNextState(); bool updateStates(List<ExecutionState> toAdd, List<ExecutionState> toRemove); bool addState(ExecutionState toAdd); bool removeState(ExecutionState toRemove); void removeAll(Predicate<ExecutionState> p); int getNumberOfStates(); } public class DFSStateScheduler : IStateScheduler { private List<ExecutionState> states; public DFSStateScheduler() { states = new List<ExecutionState>(); } public ExecutionState getNextState() { if (states.Count == 0) return null; return states[0]; } public bool updateStates(List<ExecutionState> toAdd, List<ExecutionState> toRemove) { foreach(ExecutionState e in toRemove) { Debug.Assert(states.Contains(e)); states.Remove(e); } // Add to end of List foreach(ExecutionState e in toAdd) { states.Add(e); } return true; // FIXME : Can we fail? } public int getNumberOfStates() { return states.Count;} public bool addState (ExecutionState toAdd) { states.Add(toAdd); return true; } public bool removeState (ExecutionState toRemove) { Debug.Assert(states.Contains(toRemove)); states.Remove(toRemove); return true; } public void removeAll(Predicate<ExecutionState> p) { states.RemoveAll(p); } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace symbooglix { public interface IStateScheduler { ExecutionState getNextState(); // FIXME: Return reference bool updateStates(List<ExecutionState> toAdd, List<ExecutionState> toRemove); //FIXME: pass by ref bool addState(ExecutionState toAdd); bool removeState(ExecutionState toRemove); void removeAll(Predicate<ExecutionState> p); int getNumberOfStates(); } public class DFSStateScheduler : IStateScheduler { private List<ExecutionState> states; public DFSStateScheduler() { states = new List<ExecutionState>(); } public ExecutionState getNextState() { if (states.Count == 0) return null; return states[0]; } public bool updateStates(List<ExecutionState> toAdd, List<ExecutionState> toRemove) { // FIXME: How do we comparisions with refs?? foreach(ExecutionState e in toRemove) { Debug.Assert(states.Contains(e)); states.Remove(e); } // Add to end of List foreach(ExecutionState e in toAdd) { states.Add(e); } return true; // FIXME : Can we fail? } public int getNumberOfStates() { return states.Count;} public bool addState (ExecutionState toAdd) { states.Add(toAdd); return true; } public bool removeState (ExecutionState toRemove) { Debug.Assert(states.Contains(toRemove)); states.Remove(toRemove); return true; } public void removeAll(Predicate<ExecutionState> p) { states.RemoveAll(p); } } }
bsd-2-clause
C#
4f5b1aa19ef7eb783c2fb0c3d6cde0a54ac0d80a
Remove unused constructor
ppy/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,peppy/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework
osu.Framework/Graphics/Textures/TextureWithRefCount.cs
osu.Framework/Graphics/Textures/TextureWithRefCount.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using osu.Framework.Graphics.OpenGL.Textures; namespace osu.Framework.Graphics.Textures { /// <summary> /// A texture which updates the reference count of the underlying <see cref="TextureGL"/> on ctor and disposal. /// </summary> public class TextureWithRefCount : Texture, IDisposable { public TextureWithRefCount(TextureGL textureGl) : base(textureGl) { TextureGL.Reference(); } #region Disposal public bool IsDisposed { get; private set; } ~TextureWithRefCount() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { if (IsDisposed) return; IsDisposed = true; TextureGL?.Dereference(); } #endregion } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using osu.Framework.Graphics.OpenGL.Textures; using OpenTK.Graphics.ES30; namespace osu.Framework.Graphics.Textures { /// <summary> /// A texture which updates the reference count of the underlying <see cref="TextureGL"/> on ctor and disposal. /// </summary> public class TextureWithRefCount : Texture, IDisposable { public TextureWithRefCount(TextureGL textureGl) : base(textureGl) { TextureGL.Reference(); } public TextureWithRefCount(int width, int height, bool manualMipmaps = false, All filteringMode = All.Linear) : base(width, height, manualMipmaps, filteringMode) { TextureGL.Reference(); } #region Disposal public bool IsDisposed { get; private set; } ~TextureWithRefCount() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { if (IsDisposed) return; IsDisposed = true; TextureGL?.Dereference(); } #endregion } }
mit
C#
0c4f24825969c64775705b8feb9297af2f4fc9ac
Fix CI issues
NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu-new,smoogipooo/osu,johnneijzen/osu,peppy/osu,ppy/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,johnneijzen/osu,peppy/osu,peppy/osu,smoogipoo/osu,EVAST9919/osu
osu.Game/Overlays/BeatmapSet/BeatmapRulesetSelector.cs
osu.Game/Overlays/BeatmapSet/BeatmapRulesetSelector.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.UserInterface; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osuTK; using System.Linq; namespace osu.Game.Overlays.BeatmapSet { public class BeatmapRulesetSelector : RulesetSelector { private BeatmapSetInfo beatmapSet; public BeatmapSetInfo BeatmapSet { get => beatmapSet; set { if (value == beatmapSet) return; beatmapSet = value; foreach (var tab in TabContainer.TabItems.OfType<BeatmapRulesetTabItem>()) tab.SetBeatmaps(beatmapSet?.Beatmaps.FindAll(b => b.Ruleset.Equals(tab.Value))); var firstRuleset = beatmapSet?.Beatmaps.OrderBy(b => b.Ruleset.ID).FirstOrDefault()?.Ruleset; SelectTab(TabContainer.TabItems.FirstOrDefault(t => t.Value.Equals(firstRuleset))); } } public BeatmapRulesetSelector() { AutoSizeAxes = Axes.Both; TabContainer.Spacing = new Vector2(10, 0); } protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new BeatmapRulesetTabItem(value); protected override TabFillFlowContainer CreateTabFlow() => new TabFillFlowContainer { Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, }; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.UserInterface; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osuTK; using System.Linq; namespace osu.Game.Overlays.BeatmapSet { public class BeatmapRulesetSelector : RulesetSelector { private BeatmapSetInfo beatmapSet; public BeatmapSetInfo BeatmapSet { get => beatmapSet; set { if (value == beatmapSet) return; beatmapSet = value; foreach (BeatmapRulesetTabItem tab in TabContainer.TabItems) tab.SetBeatmaps(beatmapSet?.Beatmaps.FindAll(b => b.Ruleset.Equals(tab.Value))); var firstRuleset = beatmapSet?.Beatmaps.OrderBy(b => b.Ruleset.ID).FirstOrDefault()?.Ruleset; SelectTab(TabContainer.TabItems.FirstOrDefault(t => t.Value.Equals(firstRuleset))); } } public BeatmapRulesetSelector() { AutoSizeAxes = Axes.Both; TabContainer.Spacing = new Vector2(10, 0); } protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new BeatmapRulesetTabItem(value); protected override TabFillFlowContainer CreateTabFlow() => new TabFillFlowContainer { Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, }; } }
mit
C#
6828f82decc7f55f53e7c2e76bff706cca229638
change copyright date
waltdestler/SharpDX,sharpdx/SharpDX,waltdestler/SharpDX,mrvux/SharpDX,andrewst/SharpDX,waltdestler/SharpDX,mrvux/SharpDX,dazerdude/SharpDX,dazerdude/SharpDX,sharpdx/SharpDX,waltdestler/SharpDX,andrewst/SharpDX,dazerdude/SharpDX,andrewst/SharpDX,mrvux/SharpDX,dazerdude/SharpDX,sharpdx/SharpDX
Source/SharedAssemblyInfo.cs
Source/SharedAssemblyInfo.cs
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly:AssemblyCompany("Alexandre Mutel")] [assembly:AssemblyCopyright("Copyright © 2010-2016 Alexandre Mutel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly:AssemblyVersion("3.0.2")] [assembly:AssemblyFileVersion("3.0.2")] [assembly: NeutralResourcesLanguage("en-us")] #if DEBUG [assembly:AssemblyConfiguration("Debug")] #else [assembly:AssemblyConfiguration("Release")] #endif [assembly:ComVisible(false)] #if STORE_APP [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when public and interface: renaming", Exclude = false, ApplyToMembers = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when struct: renaming", Exclude = false, ApplyToMembers = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.*: INotifyPropertyChanged heuristics", Exclude = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: forced rename", Exclude = false)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: enum values pruning", Exclude = false)] [assembly: Obfuscation(Feature = "legacy xml serialization heuristics", Exclude = true)] [assembly: Obfuscation(Feature = "ignore InternalsVisibleToAttribute", Exclude = false)] #endif
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly:AssemblyCompany("Alexandre Mutel")] [assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly:AssemblyVersion("3.0.2")] [assembly:AssemblyFileVersion("3.0.2")] [assembly: NeutralResourcesLanguage("en-us")] #if DEBUG [assembly:AssemblyConfiguration("Debug")] #else [assembly:AssemblyConfiguration("Release")] #endif [assembly:ComVisible(false)] #if STORE_APP [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when public and interface: renaming", Exclude = false, ApplyToMembers = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when struct: renaming", Exclude = false, ApplyToMembers = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.*: INotifyPropertyChanged heuristics", Exclude = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: forced rename", Exclude = false)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: enum values pruning", Exclude = false)] [assembly: Obfuscation(Feature = "legacy xml serialization heuristics", Exclude = true)] [assembly: Obfuscation(Feature = "ignore InternalsVisibleToAttribute", Exclude = false)] #endif
mit
C#
50c796c7b12084cb5a0df974495154bba5184291
Send no body
1and1/TypedRest-DotNet,TypedRest/TypedRest-DotNet,TypedRest/TypedRest-DotNet,1and1/TypedRest-DotNet
TypedRest/TriggerEndpoint.cs
TypedRest/TriggerEndpoint.cs
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace TypedRest { /// <summary> /// REST endpoint that represents a single triggerable action. /// </summary> public class TriggerEndpoint : EndpointBase, ITriggerEndpoint { /// <summary> /// Creates a new trigger endpoint. /// </summary> /// <param name="parent">The parent endpoint containing this one.</param> /// <param name="relativeUri">The URI of this endpoint relative to the <paramref name="parent"/>'s.</param> public TriggerEndpoint(IEndpoint parent, Uri relativeUri) : base(parent, relativeUri) { } /// <summary> /// Creates a new trigger endpoint. /// </summary> /// <param name="parent">The parent endpoint containing this one.</param> /// <param name="relativeUri">The URI of this endpoint relative to the <paramref name="parent"/>'s.</param> public TriggerEndpoint(IEndpoint parent, string relativeUri) : base(parent, relativeUri) { } public Task ProbeAsync(CancellationToken cancellationToken = new CancellationToken()) { return HandleResponseAsync(HttpClient.OptionsAsync(Uri, cancellationToken)); } public bool? TriggerAllowed => IsVerbAllowed(HttpMethod.Post.Method); public Task TriggerAsync(CancellationToken cancellationToken = new CancellationToken()) { return HandleResponseAsync(HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, Uri), cancellationToken)); } } }
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace TypedRest { /// <summary> /// REST endpoint that represents a single triggerable action. /// </summary> public class TriggerEndpoint : EndpointBase, ITriggerEndpoint { /// <summary> /// Creates a new trigger endpoint. /// </summary> /// <param name="parent">The parent endpoint containing this one.</param> /// <param name="relativeUri">The URI of this endpoint relative to the <paramref name="parent"/>'s.</param> public TriggerEndpoint(IEndpoint parent, Uri relativeUri) : base(parent, relativeUri) { } /// <summary> /// Creates a new trigger endpoint. /// </summary> /// <param name="parent">The parent endpoint containing this one.</param> /// <param name="relativeUri">The URI of this endpoint relative to the <paramref name="parent"/>'s.</param> public TriggerEndpoint(IEndpoint parent, string relativeUri) : base(parent, relativeUri) { } public Task ProbeAsync(CancellationToken cancellationToken = new CancellationToken()) { return HandleResponseAsync(HttpClient.OptionsAsync(Uri, cancellationToken)); } public bool? TriggerAllowed => IsVerbAllowed(HttpMethod.Post.Method); public Task TriggerAsync(CancellationToken cancellationToken = new CancellationToken()) { return HandleResponseAsync(HttpClient.PostAsJsonAsync(Uri, new {}, cancellationToken)); } } }
mit
C#
1a1efe8c0a0545b52b6524d5a23b416e185f1faa
Fix bug.
crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin
SignInCheckIn/MinistryPlatform.Translation/Repositories/ChildCheckinRepository.cs
SignInCheckIn/MinistryPlatform.Translation/Repositories/ChildCheckinRepository.cs
using System.Collections.Generic; using MinistryPlatform.Translation.Models.DTO; using MinistryPlatform.Translation.Repositories.Interfaces; namespace MinistryPlatform.Translation.Repositories { public class ChildCheckinRepository : IChildCheckinRepository { private readonly IApiUserRepository _apiUserRepository; private readonly IMinistryPlatformRestRepository _ministryPlatformRestRepository; public ChildCheckinRepository(IApiUserRepository apiUserRepository, IMinistryPlatformRestRepository ministryPlatformRestRepository) { _apiUserRepository = apiUserRepository; _ministryPlatformRestRepository = ministryPlatformRestRepository; } public List<MpParticipantDto> GetChildrenByEventAndRoom(int eventId, int roomId) { var apiUserToken = _apiUserRepository.GetToken(); var columnList = new List<string> { "Event_ID_Table.Event_ID", "Room_ID_Table.Room_ID", "Event_Participants.Event_Participant_ID", "Participant_ID_Table.Participant_ID", "Participant_ID_Table_Contact_ID_Table.Contact_ID", "Participant_ID_Table_Contact_ID_Table.First_Name", "Participant_ID_Table_Contact_ID_Table.Last_Name", "Participation_Status_ID_Table.Participation_Status_ID" }; return _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken). SearchTable<MpParticipantDto>("Event_Participants", $"Event_ID_Table.[Event_ID] = {eventId} AND Room_ID_Table.[Room_ID] = {roomId}", columnList); } public void CheckinChildrenForCurrentEventAndRoom(int checkinStatusId, int eventParticipantId) { var apiUserToken = _apiUserRepository.GetToken(); var updateObject = new Dictionary<string, object> { { "Event_Participant_ID", eventParticipantId }, { "Participation_Status_ID_Table.Participation_Status_ID", checkinStatusId } }; _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken).UpdateRecord("Event_Participants", eventParticipantId, updateObject); } } }
using System.Collections.Generic; using MinistryPlatform.Translation.Models.DTO; using MinistryPlatform.Translation.Repositories.Interfaces; namespace MinistryPlatform.Translation.Repositories { public class ChildCheckinRepository : IChildCheckinRepository { private readonly IApiUserRepository _apiUserRepository; private readonly IMinistryPlatformRestRepository _ministryPlatformRestRepository; public ChildCheckinRepository(IApiUserRepository apiUserRepository, IMinistryPlatformRestRepository ministryPlatformRestRepository) { _apiUserRepository = apiUserRepository; _ministryPlatformRestRepository = ministryPlatformRestRepository; } public List<MpParticipantDto> GetChildrenByEventAndRoom(int eventId, int roomId) { var apiUserToken = _apiUserRepository.GetToken(); var columnList = new List<string> { "Event_ID_Table.Event_ID", "Room_ID_Table.Room_ID", "Event_Participants.Event_Participant_ID", "Participant_ID_Table.Participant_ID", "Participant_ID_Table_Contact_ID_Table.Contact_ID", "Participant_ID_Table_Contact_ID_Table.First_Name", "Participant_ID_Table_Contact_ID_Table.Last_Name", "Participation_Status_ID_Table.Participation_Status_ID" }; return _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken). SearchTable<MpParticipantDto>("Event_Participants", $"Event_ID_Table.[Event_ID] = {eventId} AND Room_ID_Table.[Room_ID] = {roomId}", columnList); } public void CheckinChildrenForCurrentEventAndRoom(int checkinStatusId, int eventParticipantId) { var apiUserToken = _apiUserRepository.GetToken(); var updateObject = new Dictionary<string, object> { { "Participation_Status_ID_Table.Participation_Status_ID", checkinStatusId } }; _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken).UpdateRecord("Event_Participants", eventParticipantId, updateObject); } } }
bsd-2-clause
C#
b9cdf3a3a5b82406f0f9a829b2dbd4f80dba1850
Add GrammarType (Combined, Separated, Lexer)
KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE,KvanTTT/DAGE
AntlrGrammarEditor/Grammar.cs
AntlrGrammarEditor/Grammar.cs
using System.Collections.Generic; namespace AntlrGrammarEditor { public enum CaseInsensitiveType { None, lower, UPPER } public enum GrammarType { Combined, Separated, Lexer } public class Grammar { public const string AntlrDotExt = ".g4"; public const string LexerPostfix = "Lexer"; public const string ParserPostfix = "Parser"; public string Name { get; set; } public string LexerSuperClass { get; set; } public string ParserSuperClass { get; set; } public string FileExtension { get; set; } = "txt"; public GrammarType Type { get; set; } public CaseInsensitiveType CaseInsensitiveType { get; set; } public List<string> Files { get; set; } = new List<string>(); public List<string> TextFiles { get; set; } = new List<string>(); public string Directory { get; set; } = ""; } }
using System.Collections.Generic; namespace AntlrGrammarEditor { public enum CaseInsensitiveType { None, lower, UPPER } public class Grammar { public const string AntlrDotExt = ".g4"; public const string LexerPostfix = "Lexer"; public const string ParserPostfix = "Parser"; public string Name { get; set; } public string LexerSuperClass { get; set; } public string ParserSuperClass { get; set; } public string FileExtension { get; set; } = "txt"; public bool SeparatedLexerAndParser { get; set; } public CaseInsensitiveType CaseInsensitiveType { get; set; } public List<string> Files { get; set; } = new List<string>(); public List<string> TextFiles { get; set; } = new List<string>(); public string Directory { get; set; } = ""; } }
apache-2.0
C#
18d95b5a4e485a36fd5e709ce002fd5ca9ba16cf
Update Ship.cs
dnmitev/Team-Joseph-Heller
TeamJosephHeller/Game/Ship.cs
TeamJosephHeller/Game/Ship.cs
namespace NinjaWars { using System; using NinjaWars.Interfaces; public abstract class Ship : MovingObject { public new const string CollisionGroupString = "ship"; protected const int InitialHealth = 5; protected const int BulletSpeed = 1; public Ship(MatrixCoord topLeft, char[,] body, MatrixCoord speed) : base(topLeft, body, speed) { this.Health = InitialHealth; InfoBox.GameInfo(this.Health); } public virtual uint Health { get; protected set; } public virtual void TakeDamage(uint damage) { this.Health -= damage; InfoBox.GameInfo(this.Health); if (this.Health <= 0) { this.IsDestroyed = true; End.Title(); Environment.Exit(1); } } public override string GetCollisionGroupString() { return CollisionGroupString; } public abstract MovingObject Fire(); public override void RespondToCollision(ICollidable collideWith) { switch (collideWith.GetCollisionGroupString()) { case "ship": this.IsDestroyed = true; break; case "bullet": this.TakeDamage((collideWith as Bullet).Damage); break; case "meteor": this.TakeDamage((collideWith as Meteors).Damage); break; case "life": this.Health = +1; break; default: break; } } } }
namespace NinjaWars { using System; using NinjaWars.Interfaces; public abstract class Ship : MovingObject { public new const string CollisionGroupString = "ship"; protected const int InitialHealth = 5; protected const int BulletSpeed = 1; public Ship(MatrixCoord topLeft, char[,] body, MatrixCoord speed) : base(topLeft, body, speed) { this.Health = InitialHealth; } public virtual uint Health { get; protected set; } public virtual void TakeDamage(uint damage) { this.Health -= damage; if (this.Health == 0) this.IsDestroyed = true; } public override string GetCollisionGroupString() { return CollisionGroupString; } public abstract MovingObject Fire(); public override void RespondToCollision(ICollidable collideWith) { switch (collideWith.GetCollisionGroupString()) { case "ship": this.IsDestroyed = true; break; case "bullet": this.TakeDamage((collideWith as Bullet).Damage); break; case "meteor": this.TakeDamage((collideWith as Meteors).Damage); break; case "life": this.Health = +1; break; default: break; } } } }
mit
C#
7e4bec16a7dd1a9067ed78bb7b1dbaa3307a2c9f
Add a test initializing method 'CompileOutputTest#ClassInitialize'
lury-lang/compiler-base
UnitTest/CompileOutputTest.cs
UnitTest/CompileOutputTest.cs
using System; using System.Linq; using Lury.Compiling.Logger; using Lury.Compiling.Utils; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest { [TestClass] public class CompileOutputTest { private const int number = 0; private const string code = "code"; private const string sourceCode = "source code"; private static readonly CharPosition pos = new CharPosition(1, 8); private const string appendix = "appendix"; private static OutputLogger logger = new OutputLogger(); [ClassInitialize] public static void ClassInitialize(TestContext context) { logger.ReportInfo(number, code, sourceCode, pos, appendix); logger.ReportWarn(1, code, sourceCode, pos, appendix); logger.ReportError(2, code, sourceCode, pos, appendix); logger.ReportInfo(3, code, sourceCode, pos, appendix); logger.ReportWarn(4, code, sourceCode, pos, appendix); logger.ReportError(5, code, sourceCode, pos, appendix); CompileOutput.MessageProviders.Add(new MessageProviderInfo()); CompileOutput.MessageProviders.Add(new MessageProviderWarn()); CompileOutput.MessageProviders.Add(new MessageProviderError()); } [TestMethod] public void ConstructorTest() { CompileOutput output = logger.Outputs.First(); Assert.AreEqual(OutputCategory.Info, output.Category); Assert.AreEqual(number, output.OutputNumber); Assert.AreEqual(code, output.Code); Assert.AreEqual(sourceCode, output.SourceCode); Assert.AreEqual(pos, output.Position); Assert.AreEqual(appendix, output.Appendix); } } }
using System; using System.Linq; using Lury.Compiling.Logger; using Lury.Compiling.Utils; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest { [TestClass] public class CompileOutputTest { private const int number = 0; private const string code = "code"; private const string sourceCode = "source code"; private static readonly CharPosition pos = new CharPosition(1, 8); private const string appendix = "appendix"; [TestMethod] public void ConstructorTest() { OutputLogger logger = new OutputLogger(); logger.ReportInfo(number, code, sourceCode, pos, appendix); CompileOutput output = logger.Outputs.First(); Assert.AreEqual(OutputCategory.Info, output.Category); Assert.AreEqual(number, output.OutputNumber); Assert.AreEqual(code, output.Code); Assert.AreEqual(sourceCode, output.SourceCode); Assert.AreEqual(pos, output.Position); Assert.AreEqual(appendix, output.Appendix); } } }
mit
C#
e8c9883bcdde599e64fdb3dd68401069e87a97b6
Add newline
EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework
osu.Framework/Graphics/UserInterface/BasicTextBox.cs
osu.Framework/Graphics/UserInterface/BasicTextBox.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Graphics.UserInterface { public class BasicTextBox : TextBox { protected override float CaretWidth => 2; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Graphics.UserInterface { public class BasicTextBox : TextBox { protected override float CaretWidth => 2; } }
mit
C#
a23da033eba7a3ca22b26a925fed630e0ae97caf
Update Program.cs
NMSLanX/Natasha
samples/Core21/Program.cs
samples/Core21/Program.cs
using Natasha; using Natasha.CSharp; using System; using System.Collections.Generic; namespace Core21 { class Program { static void Main(string[] args) { DomainManagement.RegisterDefault<AssemblyDomain>(); var @operator = FastMethodOperator.DefaultDomain(); var actionDelegate = @operator .Param(typeof(string), "parameter") .Body("Console.WriteLine(parameter);") .Compile(); actionDelegate.DynamicInvoke("HelloWorld!"); var action = (Action<string>)actionDelegate; action("HelloWorld!"); actionDelegate.DisposeDomain(); //Console.WriteLine(typeof(List<int>[]).GetRuntimeName()); //Console.WriteLine(typeof(List<int>[,]).GetRuntimeName()); //Console.WriteLine(typeof(int[,]).GetRuntimeName()); //Console.WriteLine(typeof(int[][]).GetRuntimeName()); //Console.WriteLine(typeof(int[][,,,]).GetRuntimeName()); Console.ReadKey(); } } }
using Natasha; using System; using System.Collections.Generic; namespace Core21 { class Program { static void Main(string[] args) { /* * 在此之前,你需要右键,选择工程文件,在你的.csproj里面 * * 写上这样一句浪漫的话: * * <PreserveCompilationContext>true</PreserveCompilationContext> */ Console.WriteLine(typeof(List<int>[]).GetRuntimeName()); Console.WriteLine(typeof(List<int>[,]).GetRuntimeName()); Console.WriteLine(typeof(int[,]).GetRuntimeName()); Console.WriteLine(typeof(int[][]).GetRuntimeName()); Console.WriteLine(typeof(int[][,,,]).GetRuntimeName()); Console.ReadKey(); } } }
mpl-2.0
C#
2c0e71ba325eaf3fdf3aa857bfa888497e8e780b
change route config back.
mikechung11/nasw17,mikechung11/nasw17
Web/App_Start/RouteConfig.cs
Web/App_Start/RouteConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace nasw17.Web { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace nasw17.Web { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("Home"); routes.IgnoreRoute("Home/Index"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
mit
C#
c9b18d707fbf523a3e8576e021abb67d996769a2
change type in GameManager to 0
LNWPOR/HamsterRushVR-Client
Assets/Scripts/GameManager.cs
Assets/Scripts/GameManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public string URL = "http://localhost:8000"; public PlayerData playerData; public GameObject trinusLeapSetupIsSet; public GameObject gamePage; public int characterType; private static GameManager _instance; public static GameManager Instance { get { if (_instance == null) { _instance = new GameObject("GameManager").AddComponent<GameManager>(); } return _instance; } } void Awake() { playerData = new PlayerData("58b46ac0dafcde22a4bce7bd", "LNWPOR", 0, 0); characterType = 0; DontDestroyOnLoad(gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public string URL = "http://localhost:8000"; public PlayerData playerData; public GameObject trinusLeapSetupIsSet; public GameObject gamePage; public int characterType; private static GameManager _instance; public static GameManager Instance { get { if (_instance == null) { _instance = new GameObject("GameManager").AddComponent<GameManager>(); } return _instance; } } void Awake() { playerData = new PlayerData("58b46ac0dafcde22a4bce7bd", "LNWPOR", 0, 0); characterType = 2; DontDestroyOnLoad(gameObject); } }
mit
C#
093c8de0139e6e834f6eb2ee29bf0d7ead9801ac
Fix assembly and file versions
jakesee/ganttchart
GanttChart/Properties/AssemblyInfo.cs
GanttChart/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(".NET Winforms Gantt Chart Control")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Braincase Solutions")] [assembly: AssemblyProduct("GanttChartControl")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e316b126-c783-4060-95b9-aa8ee2e676d7")] // 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.1")] [assembly: AssemblyFileVersion("1.0.0.4")]
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(".NET Winforms Gantt Chart Control")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Braincase Solutions")] [assembly: AssemblyProduct("GanttChartControl")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e316b126-c783-4060-95b9-aa8ee2e676d7")] // 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.3")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
380a9738a5c51d51c702fffed7028cf35cfa85ea
remove comment
chsword/ctrc
src/CTRC/Cache/ExecutingAssemblyCache.cs
src/CTRC/Cache/ExecutingAssemblyCache.cs
using System; using System.Reflection; namespace CTRC.Cache { internal class ExecutingAssemblyCache { private static Version _version; public static Version Version => _version ?? (_version = _version = typeof(ExecutingAssemblyCache).GetTypeInfo() .Assembly.GetName().Version ); } }
using System; using System.Reflection; namespace CTRC.Cache { internal class ExecutingAssemblyCache { private static Version _version; //public static Version Version //{ // get { return _version ?? (_version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version); } //} public static Version Version => _version ?? (_version = _version = typeof(ExecutingAssemblyCache).GetTypeInfo() .Assembly.GetName().Version ); } }
mit
C#
9dc5e8a84244de88320852efef6a16fd435a2f2c
Add naming convention for retry-queue
pardahlman/RawRabbit,northspb/RawRabbit
src/RawRabbit/Common/NamingConvetions.cs
src/RawRabbit/Common/NamingConvetions.cs
using System; namespace RawRabbit.Common { public interface INamingConvetions { Func<Type, string> ExchangeNamingConvention { get; set; } Func<Type, string> QueueNamingConvention { get; set; } Func<Type, Type, string> RpcExchangeNamingConvention { get; set; } Func<string> ErrorExchangeNamingConvention { get; set; } Func<string> ErrorQueueNamingConvention { get; set; } Func<string> DeadLetterExchangeNamingConvention { get; set; } Func<string> RetryQueueNamingConvention { get; set; } } public class NamingConvetions : INamingConvetions { public virtual Func<Type, string> ExchangeNamingConvention { get; set; } public virtual Func<Type, string> QueueNamingConvention { get; set; } public virtual Func<Type, Type, string> RpcExchangeNamingConvention { get; set; } public virtual Func<string> ErrorExchangeNamingConvention { get; set; } public virtual Func<string> ErrorQueueNamingConvention { get; set; } public virtual Func<string> DeadLetterExchangeNamingConvention { get; set; } public virtual Func<string> RetryQueueNamingConvention { get; set; } public NamingConvetions() { ExchangeNamingConvention = type => type?.Namespace?.ToLower() ?? string.Empty; RpcExchangeNamingConvention = (request, response) => request?.Namespace?.ToLower() ?? "default_rpc_exchange"; QueueNamingConvention = type => CreateShortAfqn(type); ErrorQueueNamingConvention = () => "default_error_queue"; ErrorExchangeNamingConvention = () => "default_error_exchange"; DeadLetterExchangeNamingConvention = () => "default_dead_letter_exchange"; RetryQueueNamingConvention = () => $"retry_{Guid.NewGuid()}"; } private static string CreateShortAfqn(Type type, string path = "", string delimeter = ".") { var t = $"{path}{(string.IsNullOrEmpty(path) ? string.Empty : delimeter)}{GetNonGenericTypeName(type)}"; if (type.IsGenericType) { t += "["; foreach (var argument in type.GenericTypeArguments) { t = CreateShortAfqn(argument, t, t.EndsWith("[") ? string.Empty : ","); } t += "]"; } return (t.Length > 254 ? string.Concat("...", t.Substring(t.Length - 250)) : t).ToLowerInvariant(); } public static string GetNonGenericTypeName(Type type) { var name = !type.IsGenericType ? new[] { type.Name } : type.Name.Split('`'); return name[0]; } } }
using System; namespace RawRabbit.Common { public interface INamingConvetions { Func<Type, string> ExchangeNamingConvention { get; set; } Func<Type, string> QueueNamingConvention { get; set; } Func<Type, Type, string> RpcExchangeNamingConvention { get; set; } Func<string> ErrorExchangeNamingConvention { get; set; } Func<string> ErrorQueueNamingConvention { get; set; } Func<string> DeadLetterExchangeNamingConvention { get; set; } } public class NamingConvetions : INamingConvetions { public virtual Func<Type, string> ExchangeNamingConvention { get; set; } public virtual Func<Type, string> QueueNamingConvention { get; set; } public virtual Func<Type, Type, string> RpcExchangeNamingConvention { get; set; } public virtual Func<string> ErrorExchangeNamingConvention { get; set; } public virtual Func<string> ErrorQueueNamingConvention { get; set; } public virtual Func<string> DeadLetterExchangeNamingConvention { get; set; } public NamingConvetions() { ExchangeNamingConvention = type => type?.Namespace?.ToLower() ?? string.Empty; RpcExchangeNamingConvention = (request, response) => request?.Namespace?.ToLower() ?? "default_rpc_exchange"; QueueNamingConvention = type => CreateShortAfqn(type); ErrorQueueNamingConvention = () => "default_error_queue"; ErrorExchangeNamingConvention = () => "default_error_exchange"; DeadLetterExchangeNamingConvention = () => "default_dead_letter_exchange"; } private static string CreateShortAfqn(Type type, string path = "", string delimeter = ".") { var t = $"{path}{(string.IsNullOrEmpty(path) ? string.Empty : delimeter)}{GetNonGenericTypeName(type)}"; if (type.IsGenericType) { t += "["; foreach (var argument in type.GenericTypeArguments) { t = CreateShortAfqn(argument, t, t.EndsWith("[") ? string.Empty : ","); } t += "]"; } return (t.Length > 254 ? string.Concat("...", t.Substring(t.Length - 250)) : t).ToLowerInvariant(); } public static string GetNonGenericTypeName(Type type) { var name = !type.IsGenericType ? new[] { type.Name } : type.Name.Split('`'); return name[0]; } } }
mit
C#
e4582b073b4254263bd6911f8e12d32c6bc16cc1
Update the factory as well.
tmat/roslyn,tvand7093/roslyn,diryboy/roslyn,nguerrera/roslyn,jeffanders/roslyn,VSadov/roslyn,reaction1989/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,amcasey/roslyn,jmarolf/roslyn,drognanar/roslyn,swaroop-sridhar/roslyn,yeaicc/roslyn,mgoertz-msft/roslyn,mattscheffer/roslyn,cston/roslyn,jamesqo/roslyn,genlu/roslyn,paulvanbrenk/roslyn,swaroop-sridhar/roslyn,sharwell/roslyn,Giftednewt/roslyn,MichalStrehovsky/roslyn,agocke/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,xasx/roslyn,xasx/roslyn,AnthonyDGreen/roslyn,stephentoub/roslyn,jkotas/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,jmarolf/roslyn,abock/roslyn,khyperia/roslyn,wvdd007/roslyn,agocke/roslyn,pdelvo/roslyn,lorcanmooney/roslyn,mmitche/roslyn,drognanar/roslyn,orthoxerox/roslyn,akrisiun/roslyn,TyOverby/roslyn,drognanar/roslyn,tannergooding/roslyn,cston/roslyn,weltkante/roslyn,jamesqo/roslyn,akrisiun/roslyn,AnthonyDGreen/roslyn,lorcanmooney/roslyn,Giftednewt/roslyn,robinsedlaczek/roslyn,gafter/roslyn,MichalStrehovsky/roslyn,eriawan/roslyn,mavasani/roslyn,lorcanmooney/roslyn,amcasey/roslyn,mattwar/roslyn,robinsedlaczek/roslyn,Hosch250/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,panopticoncentral/roslyn,bkoelman/roslyn,weltkante/roslyn,jcouv/roslyn,OmarTawfik/roslyn,yeaicc/roslyn,weltkante/roslyn,bartdesmet/roslyn,kelltrick/roslyn,aelij/roslyn,AlekseyTs/roslyn,sharwell/roslyn,physhi/roslyn,zooba/roslyn,jasonmalinowski/roslyn,MattWindsor91/roslyn,jcouv/roslyn,kelltrick/roslyn,AnthonyDGreen/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,mattwar/roslyn,CaptainHayashi/roslyn,KevinRansom/roslyn,genlu/roslyn,cston/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,jmarolf/roslyn,reaction1989/roslyn,mattwar/roslyn,dpoeschl/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,OmarTawfik/roslyn,DustinCampbell/roslyn,heejaechang/roslyn,jeffanders/roslyn,gafter/roslyn,davkean/roslyn,jasonmalinowski/roslyn,yeaicc/roslyn,zooba/roslyn,jcouv/roslyn,srivatsn/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,jkotas/roslyn,heejaechang/roslyn,pdelvo/roslyn,xasx/roslyn,orthoxerox/roslyn,tmat/roslyn,abock/roslyn,ErikSchierboom/roslyn,diryboy/roslyn,mattscheffer/roslyn,mavasani/roslyn,physhi/roslyn,srivatsn/roslyn,MichalStrehovsky/roslyn,brettfo/roslyn,amcasey/roslyn,wvdd007/roslyn,tmeschter/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,Hosch250/roslyn,CaptainHayashi/roslyn,brettfo/roslyn,dpoeschl/roslyn,tmeschter/roslyn,akrisiun/roslyn,MattWindsor91/roslyn,jkotas/roslyn,OmarTawfik/roslyn,DustinCampbell/roslyn,dotnet/roslyn,abock/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,jamesqo/roslyn,stephentoub/roslyn,eriawan/roslyn,nguerrera/roslyn,srivatsn/roslyn,reaction1989/roslyn,paulvanbrenk/roslyn,ErikSchierboom/roslyn,bkoelman/roslyn,shyamnamboodiripad/roslyn,mattscheffer/roslyn,physhi/roslyn,MattWindsor91/roslyn,zooba/roslyn,khyperia/roslyn,heejaechang/roslyn,davkean/roslyn,genlu/roslyn,DustinCampbell/roslyn,KirillOsenkov/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,KevinRansom/roslyn,orthoxerox/roslyn,mmitche/roslyn,TyOverby/roslyn,brettfo/roslyn,VSadov/roslyn,jeffanders/roslyn,aelij/roslyn,tvand7093/roslyn,CyrusNajmabadi/roslyn,mmitche/roslyn,pdelvo/roslyn,MattWindsor91/roslyn,tmat/roslyn,Giftednewt/roslyn,kelltrick/roslyn,khyperia/roslyn,aelij/roslyn,dpoeschl/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,sharwell/roslyn,stephentoub/roslyn,eriawan/roslyn,Hosch250/roslyn,dotnet/roslyn,bkoelman/roslyn,paulvanbrenk/roslyn,TyOverby/roslyn,CaptainHayashi/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,AmadeusW/roslyn,tvand7093/roslyn,diryboy/roslyn,AmadeusW/roslyn,tmeschter/roslyn,gafter/roslyn,robinsedlaczek/roslyn,agocke/roslyn
src/Workspaces/Core/Desktop/Workspace/Storage/PersistenceStorageServiceFactory.cs
src/Workspaces/Core/Desktop/Workspace/Storage/PersistenceStorageServiceFactory.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.Esent; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionSize; namespace Microsoft.CodeAnalysis.Storage { [ExportWorkspaceServiceFactory(typeof(IPersistentStorageService), ServiceLayer.Desktop), Shared] internal class PersistenceStorageServiceFactory : IWorkspaceServiceFactory { private readonly object _gate = new object(); private readonly SolutionSizeTracker _solutionSizeTracker; private IPersistentStorageService _singleton; [ImportingConstructor] public PersistenceStorageServiceFactory(SolutionSizeTracker solutionSizeTracker) { _solutionSizeTracker = solutionSizeTracker; } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { lock (_gate) { if (_singleton == null) { _singleton = GetPersistentStorageService(workspaceServices); } return _singleton; } } private IPersistentStorageService GetPersistentStorageService(HostWorkspaceServices workspaceServices) { var optionService = workspaceServices.GetService<IOptionService>(); var database = optionService.GetOption(StorageOptions.Database); switch (database) { case StorageDatabase.Esent: return new EsentPersistentStorageService(optionService, _solutionSizeTracker); case StorageDatabase.None: default: return NoOpPersistentStorageService.Instance; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.Esent; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionSize; using Microsoft.CodeAnalysis.SQLite; namespace Microsoft.CodeAnalysis.Storage { [ExportWorkspaceServiceFactory(typeof(IPersistentStorageService), ServiceLayer.Desktop), Shared] internal class PersistenceStorageServiceFactory : IWorkspaceServiceFactory { private readonly object _gate = new object(); private readonly SolutionSizeTracker _solutionSizeTracker; private IPersistentStorageService _singleton; [ImportingConstructor] public PersistenceStorageServiceFactory(SolutionSizeTracker solutionSizeTracker) { _solutionSizeTracker = solutionSizeTracker; } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { lock (_gate) { if (_singleton == null) { _singleton = GetPersistentStorageService(workspaceServices); } return _singleton; } } private IPersistentStorageService GetPersistentStorageService(HostWorkspaceServices workspaceServices) { var optionService = workspaceServices.GetService<IOptionService>(); var database = optionService.GetOption(StorageOptions.Database); switch (database) { case StorageDatabase.SQLite: return new SQLitePersistentStorageService(optionService, _solutionSizeTracker); case StorageDatabase.Esent: return new EsentPersistentStorageService(optionService, _solutionSizeTracker); default: return NoOpPersistentStorageService.Instance; } } } }
mit
C#
a96739e92d4df0306f815a01d74419c8565da165
Make flat GaussNewtonIkSolver adjust root translation
virtuallynaked/virtually-naked,virtuallynaked/virtually-naked
Demos/src/FlatIk/GaussNewtonIkSolver.cs
Demos/src/FlatIk/GaussNewtonIkSolver.cs
using System.Collections.Generic; using SharpDX; using MathNet.Numerics.LinearAlgebra; using System.Linq; namespace FlatIk { public class GaussNewtonIkSolver : IIkSolver { private const float RootTranslationWeight = 1f; private static IEnumerable<Bone> GetBoneChain(Bone sourceBone) { for (var bone = sourceBone; bone != null; bone = bone.Parent) { yield return bone; } } public void DoIteration(SkeletonInputs inputs, Bone sourceBone, Vector2 unposedSource, Vector2 target) { Vector2 source = Matrix3x2.TransformPoint(sourceBone.GetChainedTransform(inputs), sourceBone.End); Vector<float> residuals = Vector<float>.Build.Dense(2); residuals[0] = target.X - source.X; residuals[1] = target.Y - source.Y; List<Bone> bones = GetBoneChain(sourceBone).ToList(); int boneCount = bones.Count; Matrix<float> jacobian = Matrix<float>.Build.Dense(2, boneCount + 2); for (int boneIdx = 0; boneIdx < boneCount; ++boneIdx) { Vector2 boneGradient = bones[boneIdx].GetGradientOfTransformedPointWithRespectToRotation(inputs, source); jacobian[0, boneIdx] = boneGradient.X; jacobian[1, boneIdx] = boneGradient.Y; } jacobian[0, boneCount + 0] = RootTranslationWeight; jacobian[1, boneCount + 1] = RootTranslationWeight; Vector<float> step = jacobian.PseudoInverse().Multiply(residuals); for (int boneIdx = 0; boneIdx < boneCount; ++boneIdx) { var bone = bones[boneIdx]; bone.IncrementRotation(inputs, step[boneIdx]); } Vector2 rootTranslationStep = new Vector2( step[boneCount + 0], step[boneCount + 1]); inputs.Translation += rootTranslationStep * RootTranslationWeight; } } }
using System.Collections.Generic; using SharpDX; using MathNet.Numerics.LinearAlgebra; using System.Linq; namespace FlatIk { public class GaussNewtonIkSolver : IIkSolver { private static IEnumerable<Bone> GetBoneChain(Bone sourceBone) { for (var bone = sourceBone; bone != null; bone = bone.Parent) { yield return bone; } } public void DoIteration(SkeletonInputs inputs, Bone sourceBone, Vector2 unposedSource, Vector2 target) { Vector2 source = Matrix3x2.TransformPoint(sourceBone.GetChainedTransform(inputs), sourceBone.End); Vector<float> residuals = Vector<float>.Build.Dense(2); residuals[0] = target.X - source.X; residuals[1] = target.Y - source.Y; List<Bone> bones = GetBoneChain(sourceBone).ToList(); Matrix<float> jacobian = Matrix<float>.Build.Dense(2, bones.Count); for (int boneIdx = 0; boneIdx < bones.Count; ++boneIdx) { Vector2 boneGradient = bones[boneIdx].GetGradientOfTransformedPointWithRespectToRotation(inputs, source); jacobian[0, boneIdx] = boneGradient.X; jacobian[1, boneIdx] = boneGradient.Y; } Vector<float> step = jacobian.PseudoInverse().Multiply(residuals); for (int boneIdx = 0; boneIdx < bones.Count; ++boneIdx) { var bone = bones[boneIdx]; bone.IncrementRotation(inputs, step[boneIdx]); } } } }
mit
C#
8c44fb4c199d00021e8c7665b1b1b75d259972ac
add ctos for sudoku9
Mooophy/158212
sudoku/Library/Sudoku9.cs
sudoku/Library/Sudoku9.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Library { public class Sudoku9 : Matrix { public Sudoku9() : base(9, new RangSet9(), new RangSet9()) { } public Sudoku9(int[,] data) : base(9, new RangSet9(), new RangSet9(), data) { } public class RangSet9 : HashSet<Matrix.Range> { public RangSet9() { foreach (var num in Enumerable.Range(0, 3).Select(i => 3 * i)) this.Add(new Matrix.Range(num, 3)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Library { public class Sudoku9 { public class RangSet9 : HashSet<Matrix.Range> { public RangSet9() { foreach (var num in Enumerable.Range(0, 3).Select(i => 3 * i)) this.Add(new Matrix.Range(num, 3)); } } } }
mit
C#
4ef0b7cfcc264503e86a1e25d960c7ae73970a96
Add extention methods for DisplayViewModel<T>.
Grabacr07/MetroTrilithon
source/MetroTrilithon.Desktop/Mvvm/DisplayViewModel.cs
source/MetroTrilithon.Desktop/Mvvm/DisplayViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Livet; using MetroTrilithon.Serialization; namespace MetroTrilithon.Mvvm { public static class DisplayViewModel { public static DisplayViewModel<T> Create<T>(T value, string display) { return new DisplayViewModel<T> { Value = value, Display = display, }; } public static DisplayViewModel<T> ToDefaultDisplay<T>(this SerializableProperty<T> property, string display) { return new DisplayViewModel<T> { Value = property.Default, Display = display, }; } public static IEnumerable<DisplayViewModel<TResult>> ToDisplay<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> valueSelector, Func<TSource, string> displaySelector) { return source.Select(x => new DisplayViewModel<TResult> { Value = valueSelector(x), Display = displaySelector(x), }); } } public class DisplayViewModel<T> : ViewModel { #region Value 変更通知プロパティ private T _Value; public T Value { get { return this._Value; } set { if (!Equals(this._Value, value)) { this._Value = value; this.RaisePropertyChanged(); } } } #endregion #region Display 変更通知プロパティ private string _Display; public string Display { get { return this._Display; } set { if (this._Display != value) { this._Display = value; this.RaisePropertyChanged(); } } } #endregion public static implicit operator T(DisplayViewModel<T> dvm) { return dvm.Value; } public override string ToString() { return this.Display; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Livet; namespace MetroTrilithon.Mvvm { public static class DisplayViewModel { public static DisplayViewModel<T> Create<T>(T value, string display) { return new DisplayViewModel<T> { Value = value, Display = display, }; } } public class DisplayViewModel<T> : ViewModel { #region Value 変更通知プロパティ private T _Value; public T Value { get { return this._Value; } set { if (!Equals(this._Value, value)) { this._Value = value; this.RaisePropertyChanged(); } } } #endregion #region Display 変更通知プロパティ private string _Display; public string Display { get { return this._Display; } set { if (this._Display != value) { this._Display = value; this.RaisePropertyChanged(); } } } #endregion public static implicit operator T(DisplayViewModel<T> dvm) { return dvm.Value; } public override string ToString() { return this.Display; } } }
mit
C#
6b297b921f9aafe2f1b5583f483fbd51c720883a
add some pre-validation to property setter
gstreamer-sharp/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,GStreamer/gstreamer-sharp,GStreamer/gstreamer-sharp,GStreamer/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,gstreamer-sharp/gstreamer-sharp
sources/custom/Object.cs
sources/custom/Object.cs
// Copyright (C) 2013 Stephan Sundermann <stephansundermann@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Gst { public class PropertyNotFoundException : Exception {} partial class Object { private Dictionary <string, bool> PropertyNameCache = new Dictionary<string, bool> (); [DllImport ("libgobject-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr g_object_class_find_property (IntPtr klass, IntPtr name); bool PropertyExists (string name) { if (PropertyNameCache.ContainsKey (name)) return PropertyNameCache [name]; var ptr = g_object_class_find_property (Marshal.ReadIntPtr (Handle), GLib.Marshaller.StringToPtrGStrdup (name)); var result = ptr != IntPtr.Zero; // just cache the positive results because there might // actually be new properties getting installed if (result) PropertyNameCache [name] = result; return result; } public object this[string property] { get { if (PropertyExists (property)) { using (GLib.Value v = GetProperty (property)) { return v.Val; } } else throw new PropertyNotFoundException (); } set { if (PropertyExists (property)) { if (value == null) { throw new ArgumentNullException (); } var type = value.GetType (); var gtype = (GLib.GType)type; if (gtype == null) { throw new Exception ("Could not find a GType for type " + type.FullName); } using (GLib.Value v = new GLib.Value ((GLib.GType)value.GetType ())) { v.Val = value; SetProperty (property, v); } } else throw new PropertyNotFoundException (); } } public void Connect (string signal, SignalHandler handler) { DynamicSignal.Connect (this, signal, handler); } public void Disconnect (string signal, SignalHandler handler) { DynamicSignal.Disconnect (this, signal, handler); } public void Connect (string signal, Delegate handler) { DynamicSignal.Connect (this, signal, handler); } public void Disconnect (string signal, Delegate handler) { DynamicSignal.Disconnect (this, signal, handler); } public object Emit (string signal, params object[] parameters) { return DynamicSignal.Emit (this, signal, parameters); } } }
// Copyright (C) 2013 Stephan Sundermann <stephansundermann@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Gst { public class PropertyNotFoundException : Exception {} partial class Object { private Dictionary <string, bool> PropertyNameCache = new Dictionary<string, bool> (); [DllImport ("libgobject-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr g_object_class_find_property (IntPtr klass, IntPtr name); bool PropertyExists (string name) { if (PropertyNameCache.ContainsKey (name)) return PropertyNameCache [name]; var ptr = g_object_class_find_property (Marshal.ReadIntPtr (Handle), GLib.Marshaller.StringToPtrGStrdup (name)); var result = ptr != IntPtr.Zero; // just cache the positive results because there might // actually be new properties getting installed if (result) PropertyNameCache [name] = result; return result; } public object this[string property] { get { if (PropertyExists (property)) { using (GLib.Value v = GetProperty (property)) { return v.Val; } } else throw new PropertyNotFoundException (); } set { if (PropertyExists (property)) { using (GLib.Value v = new GLib.Value ((GLib.GType)value.GetType ())) { v.Val = value; SetProperty (property, v); } } else throw new PropertyNotFoundException (); } } public void Connect (string signal, SignalHandler handler) { DynamicSignal.Connect (this, signal, handler); } public void Disconnect (string signal, SignalHandler handler) { DynamicSignal.Disconnect (this, signal, handler); } public void Connect (string signal, Delegate handler) { DynamicSignal.Connect (this, signal, handler); } public void Disconnect (string signal, Delegate handler) { DynamicSignal.Disconnect (this, signal, handler); } public object Emit (string signal, params object[] parameters) { return DynamicSignal.Emit (this, signal, parameters); } } }
lgpl-2.1
C#
5d6fe4579b3c852499467eb044406d75339fd9b1
Mark Test project can visible for console extension project
BigEggTools/JsonComparer
BigEgg.ConsoleExtension/Properties/AssemblyInfo.cs
BigEgg.ConsoleExtension/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("BigEgg.ConsoleExtension")] [assembly: AssemblyDescription("Some extensions for Console project")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("BigEgg")] [assembly: AssemblyProduct("BigEgg.Tools")] [assembly: AssemblyCopyright("Copyright © BigEgg 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("664ce9b8-05cd-4117-993b-d918c056f630")] // 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: InternalsVisibleTo("BigEgg.ConsoleExtension.Tests")]
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("BigEgg.ConsoleExtension")] [assembly: AssemblyDescription("Some extensions for Console project")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("BigEgg")] [assembly: AssemblyProduct("BigEgg.Tools")] [assembly: AssemblyCopyright("Copyright © BigEgg 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("664ce9b8-05cd-4117-993b-d918c056f630")] // 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#
442b3f0cea7fc5f38ffd58bd9aae71893b95b0ac
Reduce testing of coordinate nodes call
PlayFab/consuldotnet
Consul.Test/CoordinateTest.cs
Consul.Test/CoordinateTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Consul.Test { [TestClass] public class CoordinateTest { [TestMethod] public void Coordinate_Datacenters() { var client = new Client(); var info = client.Agent.Self(); if (!info.Response.ContainsKey("Coord")) { Assert.Inconclusive("This version of Consul does not support the coordinate API"); } var datacenters = client.Coordinate.Datacenters(); Assert.IsNotNull(datacenters.Response); Assert.IsTrue(datacenters.Response.Length > 0); } [TestMethod] public void Coordinate_Nodes() { var client = new Client(); var info = client.Agent.Self(); if (!info.Response.ContainsKey("Coord")) { Assert.Inconclusive("This version of Consul does not support the coordinate API"); } var nodes = client.Coordinate.Nodes(); // There's not a good way to populate coordinates without // waiting for them to calculate and update, so the best // we can do is call the endpoint and make sure we don't // get an error. - from offical API. Assert.IsNotNull(nodes); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Consul.Test { [TestClass] public class CoordinateTest { [TestMethod] public void TestCoordinate_Datacenters() { var client = new Client(); var info = client.Agent.Self(); if (!info.Response.ContainsKey("Coord")) { Assert.Inconclusive("This version of Consul does not support the coordinate API"); } var datacenters = client.Coordinate.Datacenters(); Assert.IsNotNull(datacenters.Response); Assert.IsTrue(datacenters.Response.Length > 0); } [TestMethod] public void TestCoordinate_Nodes() { var client = new Client(); var info = client.Agent.Self(); if (!info.Response.ContainsKey("Coord")) { Assert.Inconclusive("This version of Consul does not support the coordinate API"); } var nodes = client.Coordinate.Nodes(); Assert.IsNotNull(nodes.Response); Assert.IsTrue(nodes.Response.Length > 0); } } }
apache-2.0
C#
ebdb2fe89e0023acf6c8e396509fe4908d581548
Fix - Use EntityId instead of mail ID for EntityId column in recorder
EminentTechnology/Mailer
src/recorders/Mailer.Recorders.Sql/MailMessage.cs
src/recorders/Mailer.Recorders.Sql/MailMessage.cs
using Mailer.Abstractions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mailer.Recorders.Sql { public class MailMessage { public string MailMessageID { get; set; } public string MailSubject { get; set; } public string MailBody { get; set; } public string Priority { get; set; } public bool IsBodyHtml { get; set; } public bool IsSent { get; set; } public DateTimeOffset? MailSentDate { get; set; } public string Template { get; set; } public string EntityType { get; set; } public string EntityID { get; set; } public string ErrorMessage { get; set; } public DateTimeOffset CreatedOn { get; set; } public string CreatedBy { get; set; } public DateTimeOffset ModifiedOn { get; set; } public string ModifiedBy { get; set; } public List<MailMessageAddress> Addresses { get; set; } public List<MailMessageAttachment> Attachments { get; set; } internal static MailMessage Populate(MailMessage message, EmailMessage email) { message.MailMessageID = email.Id; message.MailSubject = email.Subject; message.MailBody = email.Body; message.Priority = email.Priority.ToString(); message.IsBodyHtml = email.IsBodyHtml; message.Template = email.Template; message.EntityType = email.EntityType; message.EntityID = email.EntityId; message.CreatedOn = email.CreatedOn; message.CreatedBy = email.From.DisplayName; message.ModifiedOn = email.CreatedOn; message.ModifiedBy = email.From.DisplayName; return message; } } }
using Mailer.Abstractions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mailer.Recorders.Sql { public class MailMessage { public string MailMessageID { get; set; } public string MailSubject { get; set; } public string MailBody { get; set; } public string Priority { get; set; } public bool IsBodyHtml { get; set; } public bool IsSent { get; set; } public DateTimeOffset? MailSentDate { get; set; } public string Template { get; set; } public string EntityType { get; set; } public string EntityID { get; set; } public string ErrorMessage { get; set; } public DateTimeOffset CreatedOn { get; set; } public string CreatedBy { get; set; } public DateTimeOffset ModifiedOn { get; set; } public string ModifiedBy { get; set; } public List<MailMessageAddress> Addresses { get; set; } public List<MailMessageAttachment> Attachments { get; set; } internal static MailMessage Populate(MailMessage message, EmailMessage email) { message.MailMessageID = email.Id; message.MailSubject = email.Subject; message.MailBody = email.Body; message.Priority = email.Priority.ToString(); message.IsBodyHtml = email.IsBodyHtml; message.Template = email.Template; message.EntityType = email.EntityType; message.EntityID = email.Id; message.CreatedOn = email.CreatedOn; message.CreatedBy = email.From.DisplayName; message.ModifiedOn = email.CreatedOn; message.ModifiedBy = email.From.DisplayName; return message; } } }
mit
C#
380f557ad0c565ae22a0638378053e4eaf9541ec
Make use of Header endianness field
arfbtwn/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp,arfbtwn/dbus-sharp,mono/dbus-sharp
src/Message.cs
src/Message.cs
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using System.IO; namespace NDesk.DBus { class Message { public Message () { Header.Endianness = Connection.NativeEndianness; Header.MessageType = MessageType.MethodCall; Header.Flags = HeaderFlag.NoReplyExpected; //TODO: is this the right place to do this? Header.MajorVersion = Protocol.Version; Header.Fields = new Dictionary<FieldCode,object> (); } public Header Header; public Connection Connection; public Signature Signature { get { object o; if (Header.Fields.TryGetValue (FieldCode.Signature, out o)) return (Signature)o; else return Signature.Empty; } set { if (value == Signature.Empty) Header.Fields.Remove (FieldCode.Signature); else Header.Fields[FieldCode.Signature] = value; } } public bool ReplyExpected { get { return (Header.Flags & HeaderFlag.NoReplyExpected) == HeaderFlag.None; } set { if (value) Header.Flags &= ~HeaderFlag.NoReplyExpected; //flag off else Header.Flags |= HeaderFlag.NoReplyExpected; //flag on } } //public HeaderField[] HeaderFields; //public Dictionary<FieldCode,object>; public byte[] Body; //TODO: make use of Locked /* protected bool locked = false; public bool Locked { get { return locked; } } */ public void SetHeaderData (byte[] data) { EndianFlag endianness = (EndianFlag)data[0]; MessageReader reader = new MessageReader (endianness, data); Header = (Header)reader.ReadStruct (typeof (Header)); } public byte[] GetHeaderData () { if (Body != null) Header.Length = (uint)Body.Length; MessageWriter writer = new MessageWriter (Header.Endianness); writer.WriteValueType (Header, typeof (Header)); writer.CloseWrite (); return writer.ToArray (); } } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using System.IO; namespace NDesk.DBus { class Message { public Message () { Header.Endianness = Connection.NativeEndianness; Header.MessageType = MessageType.MethodCall; Header.Flags = HeaderFlag.NoReplyExpected; //TODO: is this the right place to do this? Header.MajorVersion = Protocol.Version; Header.Fields = new Dictionary<FieldCode,object> (); } public Header Header; public Connection Connection; public Signature Signature { get { object o; if (Header.Fields.TryGetValue (FieldCode.Signature, out o)) return (Signature)o; else return Signature.Empty; } set { if (value == Signature.Empty) Header.Fields.Remove (FieldCode.Signature); else Header.Fields[FieldCode.Signature] = value; } } public bool ReplyExpected { get { return (Header.Flags & HeaderFlag.NoReplyExpected) == HeaderFlag.None; } set { if (value) Header.Flags &= ~HeaderFlag.NoReplyExpected; //flag off else Header.Flags |= HeaderFlag.NoReplyExpected; //flag on } } //public HeaderField[] HeaderFields; //public Dictionary<FieldCode,object>; public byte[] Body; //TODO: make use of Locked /* protected bool locked = false; public bool Locked { get { return locked; } } */ public void SetHeaderData (byte[] data) { EndianFlag endianness = (EndianFlag)data[0]; MessageReader reader = new MessageReader (endianness, data); Header = (Header)reader.ReadStruct (typeof (Header)); } public byte[] GetHeaderData () { if (Body != null) Header.Length = (uint)Body.Length; MessageWriter writer = new MessageWriter (Connection.NativeEndianness); writer.WriteValueType (Header, typeof (Header)); writer.CloseWrite (); return writer.ToArray (); } } }
mit
C#
a95d9ce98cc31f9dc888fdeb191f015b2703cf65
Add TODO item.
tiesmaster/DCC,tiesmaster/DCC
Dcc/Program.cs
Dcc/Program.cs
using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; namespace Tiesmaster.Dcc { public static class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables(prefix: "DCC_") .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); // TODO: fix libuv missing host.Run(); } } }
using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; namespace Tiesmaster.Dcc { public static class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables(prefix: "DCC_") .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
mit
C#
82e2feeec8cfe4aa2b1585b0384a483566977e10
Add varying sent data sizes
brian-dot-net/writeasync,brian-dot-net/writeasync,brian-dot-net/writeasync
projects/CommSample/source/CommSample.App/Program.cs
projects/CommSample/source/CommSample.App/Program.cs
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace CommSample { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; internal sealed class Program { private static void Main(string[] args) { Logger logger = new Logger(); TimeSpan duration = TimeSpan.FromSeconds(5.0d); int senderCount = 2; logger.WriteLine("Receive loop with {0} senders, {1:0.0} sec...", senderCount, duration.TotalSeconds); Receive_loop_with_N_senders(logger, senderCount, duration); logger.WriteLine("Done."); } private static void Receive_loop_with_N_senders(Logger logger, int senderCount, TimeSpan duration) { MemoryChannel channel = new MemoryChannel(); Receiver receiver = new Receiver(channel, logger, 16); int[] sentDataSizes = new int[] { 11, 19, 29, 41, 53, 71 }; using (CancellationTokenSource cts = new CancellationTokenSource()) { Task receiverTask = receiver.RunAsync(); Task[] senderTasks = new Task[senderCount]; for (int i = 0; i < senderTasks.Length; ++i) { Sender sender = new Sender(channel, logger, sentDataSizes[i % sentDataSizes.Length], (byte)(i + 1), new Delay(2, 1)); senderTasks[i] = sender.RunAsync(cts.Token); } Thread.Sleep(duration); cts.Cancel(); Task.WaitAll(senderTasks); channel.Dispose(); receiverTask.Wait(); } } } }
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace CommSample { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; internal sealed class Program { private static void Main(string[] args) { Logger logger = new Logger(); TimeSpan duration = TimeSpan.FromSeconds(5.0d); int senderCount = 2; logger.WriteLine("Receive loop with {0} senders, {1:0.0} sec...", senderCount, duration.TotalSeconds); Receive_loop_with_N_senders(logger, senderCount, duration); logger.WriteLine("Done."); } private static void Receive_loop_with_N_senders(Logger logger, int senderCount, TimeSpan duration) { MemoryChannel channel = new MemoryChannel(); Receiver receiver = new Receiver(channel, logger, 16); using (CancellationTokenSource cts = new CancellationTokenSource()) { Task receiverTask = receiver.RunAsync(); Task[] senderTasks = new Task[senderCount]; for (int i = 0; i < senderTasks.Length; ++i) { Sender sender = new Sender(channel, logger, 16, (byte)(i + 1), new Delay(2, 1)); senderTasks[i] = sender.RunAsync(cts.Token); } Thread.Sleep(duration); cts.Cancel(); Task.WaitAll(senderTasks); channel.Dispose(); receiverTask.Wait(); } } } }
unlicense
C#
ca989f309e393e5449e88fc051d119fa90fe7530
fix update sdk version number
NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity
ncmb_unity/Assets/NCMB/CommonConstant.cs
ncmb_unity/Assets/NCMB/CommonConstant.cs
/******* Copyright 2017 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********/ using System.Collections; namespace NCMB.Internal { //通信種別 internal enum ConnectType { //GET通信 GET, //POST通信 POST, //PUT通信 PUT, //DELETE通信 DELETE } /// <summary> /// 定数を定義する共通用のクラスです /// </summary> internal static class CommonConstant { //service public static readonly string DOMAIN = "mb.api.cloud.nifty.com";//ドメイン public static readonly string DOMAIN_URL = "https://mb.api.cloud.nifty.com";//ドメインのURL public static readonly string API_VERSION = "2013-09-01";//APIバージョン public static readonly string SDK_VERSION = "3.0.1"; //SDKバージョン //DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください } }
/******* Copyright 2017 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********/ using System.Collections; namespace NCMB.Internal { //通信種別 internal enum ConnectType { //GET通信 GET, //POST通信 POST, //PUT通信 PUT, //DELETE通信 DELETE } /// <summary> /// 定数を定義する共通用のクラスです /// </summary> internal static class CommonConstant { //service public static readonly string DOMAIN = "mb.api.cloud.nifty.com";//ドメイン public static readonly string DOMAIN_URL = "https://mb.api.cloud.nifty.com";//ドメインのURL public static readonly string API_VERSION = "2013-09-01";//APIバージョン public static readonly string SDK_VERSION = "3.0.0"; //SDKバージョン //DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください } }
apache-2.0
C#
f2a87e80ea7beb809b2942854b5a727520aadb7e
Update DirectInputPadPlugin.Build.cs
katze7514/UEDirectInputPadPlugin,katze7514/UEDirectInputPadPlugin
Source/DirectInputPadPlugin/DirectInputPadPlugin.Build.cs
Source/DirectInputPadPlugin/DirectInputPadPlugin.Build.cs
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. namespace UnrealBuildTool.Rules { public class DirectInputPadPlugin : ModuleRules { public DirectInputPadPlugin(ReadOnlyTargetRules Target):base(Target) { PrivatePCHHeaderFile = "Private/DirectInputPadPluginPrivatePCH.h"; PublicIncludePaths.AddRange( new string[] { // "DirectInputPadPlugin/Public", // ... add public include paths required here ... } ); PrivateIncludePaths.AddRange( new string[] { // "DirectInputPadPlugin/Private", // ... add other private include paths required here ... } ); PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "ApplicationCore", "Engine", "InputDevice", // ... add other public dependencies that you statically link with here ... } ); PrivateDependencyModuleNames.AddRange( new string[] { "Slate", "SlateCore", "InputCore", // ... add private dependencies that you statically link with here ... } ); if (Target.bBuildEditor) { PrivateDependencyModuleNames.AddRange(new string[]{ "MainFrame", }); } DynamicallyLoadedModuleNames.AddRange( new string[] { // ... add any modules that your module loads dynamically here ... } ); } } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. namespace UnrealBuildTool.Rules { public class DirectInputPadPlugin : ModuleRules { public DirectInputPadPlugin(ReadOnlyTargetRules Target):base(Target) { PublicIncludePaths.AddRange( new string[] { // "DirectInputPadPlugin/Public", // ... add public include paths required here ... } ); PrivateIncludePaths.AddRange( new string[] { // "DirectInputPadPlugin/Private", // ... add other private include paths required here ... } ); PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "ApplicationCore", "Engine", "InputDevice", // ... add other public dependencies that you statically link with here ... } ); PrivateDependencyModuleNames.AddRange( new string[] { "Slate", "SlateCore", "InputCore", // ... add private dependencies that you statically link with here ... } ); if (Target.bBuildEditor) { PrivateDependencyModuleNames.AddRange(new string[]{ "MainFrame", }); } DynamicallyLoadedModuleNames.AddRange( new string[] { // ... add any modules that your module loads dynamically here ... } ); } } }
mit
C#
c49753d19d645b900d0f2f317ea68c7e263bb79a
Add ResolveByName attribute to TargetTextBlock property
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactions/Custom/ShowPointerPositionBehavior.cs
src/Avalonia.Xaml.Interactions/Custom/ShowPointerPositionBehavior.cs
using Avalonia.Controls; using Avalonia.Input; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom; /// <summary> /// A behavior that displays cursor position on <see cref="InputElement.PointerMoved"/> event for the <see cref="Behavior{T}.AssociatedObject"/> using <see cref="TextBlock.Text"/> property. /// </summary> public class ShowPointerPositionBehavior : Behavior<Control> { /// <summary> /// Identifies the <seealso cref="TargetTextBlockProperty"/> avalonia property. /// </summary> public static readonly StyledProperty<TextBlock?> TargetTextBlockProperty = AvaloniaProperty.Register<ShowPointerPositionBehavior, TextBlock?>(nameof(TargetTextBlock)); /// <summary> /// Gets or sets the target TextBlock object in which this behavior displays cursor position on PointerMoved event. /// </summary> [ResolveByName] public TextBlock? TargetTextBlock { get => GetValue(TargetTextBlockProperty); set => SetValue(TargetTextBlockProperty, value); } /// <inheritdoc /> protected override void OnAttachedToVisualTree() { if (AssociatedObject is { }) { AssociatedObject.PointerMoved += AssociatedObject_PointerMoved; } } /// <inheritdoc /> protected override void OnDetachedFromVisualTree() { if (AssociatedObject is { }) { AssociatedObject.PointerMoved -= AssociatedObject_PointerMoved; } } private void AssociatedObject_PointerMoved(object? sender, PointerEventArgs e) { if (TargetTextBlock is { }) { TargetTextBlock.Text = e.GetPosition(AssociatedObject).ToString(); } } }
using Avalonia.Controls; using Avalonia.Input; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom; /// <summary> /// A behavior that displays cursor position on <see cref="InputElement.PointerMoved"/> event for the <see cref="Behavior{T}.AssociatedObject"/> using <see cref="TextBlock.Text"/> property. /// </summary> public class ShowPointerPositionBehavior : Behavior<Control> { /// <summary> /// Identifies the <seealso cref="TargetTextBlockProperty"/> avalonia property. /// </summary> public static readonly StyledProperty<TextBlock?> TargetTextBlockProperty = AvaloniaProperty.Register<ShowPointerPositionBehavior, TextBlock?>(nameof(TargetTextBlock)); /// <summary> /// Gets or sets the target TextBlock object in which this behavior displays cursor position on PointerMoved event. /// </summary> public TextBlock? TargetTextBlock { get => GetValue(TargetTextBlockProperty); set => SetValue(TargetTextBlockProperty, value); } /// <inheritdoc /> protected override void OnAttachedToVisualTree() { if (AssociatedObject is { }) { AssociatedObject.PointerMoved += AssociatedObject_PointerMoved; } } /// <inheritdoc /> protected override void OnDetachedFromVisualTree() { if (AssociatedObject is { }) { AssociatedObject.PointerMoved -= AssociatedObject_PointerMoved; } } private void AssociatedObject_PointerMoved(object? sender, PointerEventArgs e) { if (TargetTextBlock is { }) { TargetTextBlock.Text = e.GetPosition(AssociatedObject).ToString(); } } }
mit
C#
a73c9c0f791bf30a70527e23d440f8561ea42148
Add reference to the drawable handling a touch event per-manager
smoogipooo/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework
osu.Framework/Input/TouchEventManager.cs
osu.Framework/Input/TouchEventManager.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 System.Diagnostics; using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Framework.Input.States; using osuTK; namespace osu.Framework.Input { /// <summary> /// A manager that manages states and events for a single touch. /// </summary> public class TouchEventManager : ButtonEventManager<TouchSource> { protected Vector2? TouchDownPosition; /// <summary> /// The drawable from the input queue that handled a <see cref="TouchEvent"/> corresponding to this touch source. /// Null when no drawable has handled a touch event or the touch is not yet active / has been deactivated. /// </summary> public Drawable HeldDrawable { get; protected set; } public TouchEventManager(TouchSource source) : base(source) { } public void HandlePositionChange(InputState state, Vector2 lastPosition) { handleTouchMove(state, state.Touch.TouchPositions[(int)Button], lastPosition); } private void handleTouchMove(InputState state, Vector2 position, Vector2 lastPosition) { PropagateButtonEvent(ButtonDownInputQueue, new TouchMoveEvent(state, new Touch(Button, position), TouchDownPosition, lastPosition)); } protected override Drawable HandleButtonDown(InputState state, List<Drawable> targets) { TouchDownPosition = state.Touch.GetTouchPosition(Button); Debug.Assert(TouchDownPosition != null); var handled = PropagateButtonEvent(targets, new TouchDownEvent(state, new Touch(Button, (Vector2)TouchDownPosition))); HeldDrawable = handled; return handled; } protected override void HandleButtonUp(InputState state, List<Drawable> targets) { var currentPosition = state.Touch.TouchPositions[(int)Button]; PropagateButtonEvent(targets, new TouchUpEvent(state, new Touch(Button, currentPosition), TouchDownPosition)); HeldDrawable = null; TouchDownPosition = null; } } }
// 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 System.Diagnostics; using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Framework.Input.States; using osuTK; namespace osu.Framework.Input { /// <summary> /// A manager that manages states and events for a single touch. /// </summary> public class TouchEventManager : ButtonEventManager<TouchSource> { protected Vector2? TouchDownPosition; public TouchEventManager(TouchSource source) : base(source) { } public void HandlePositionChange(InputState state, Vector2 lastPosition) { handleTouchMove(state, state.Touch.TouchPositions[(int)Button], lastPosition); } private void handleTouchMove(InputState state, Vector2 position, Vector2 lastPosition) { PropagateButtonEvent(ButtonDownInputQueue, new TouchMoveEvent(state, new Touch(Button, position), TouchDownPosition, lastPosition)); } protected override Drawable HandleButtonDown(InputState state, List<Drawable> targets) { TouchDownPosition = state.Touch.GetTouchPosition(Button); Debug.Assert(TouchDownPosition != null); return PropagateButtonEvent(targets, new TouchDownEvent(state, new Touch(Button, (Vector2)TouchDownPosition))); } protected override void HandleButtonUp(InputState state, List<Drawable> targets) { var currentPosition = state.Touch.TouchPositions[(int)Button]; PropagateButtonEvent(targets, new TouchUpEvent(state, new Touch(Button, currentPosition), TouchDownPosition)); TouchDownPosition = null; } } }
mit
C#
985633b7b21d5b1e22af8845879cbcbddb03d7e5
Update ContentItemDisplay mapper to set IsContainer and IsChildOfListView correctly
OPTEN/Opten.Umbraco.ListView,OPTEN/Opten.Umbraco.ListView,OPTEN/Opten.Umbraco.ListView
src/Opten.Umbraco.ListView/Events/TreeEventHandler.cs
src/Opten.Umbraco.ListView/Events/TreeEventHandler.cs
using AutoMapper; using Opten.Umbraco.ListView.Extensions; using System.Linq; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Trees; namespace ClassLibrary1 { public class TreeEventHandler : ApplicationEventHandler { protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { ContentTreeController.TreeNodesRendering += ContentTreeController_TreeNodesRendering; var typeMaps = Mapper.GetAllTypeMaps(); var contentMapper = typeMaps.First(map => map.DestinationType.Equals(typeof(ContentItemDisplay)) && map.SourceType.Equals(typeof(IContent))); contentMapper.AddAfterMapAction((src, dest) => { var srcTyped = src as IContent; var destTyped = dest as ContentItemDisplay; destTyped.IsChildOfListView = destTyped.IsChildOfListView || srcTyped.Parent().IsInListView(srcTyped.ContentType.Alias); destTyped.IsContainer = destTyped.IsContainer || srcTyped.FindGridListViewContentTypeAliases().Any(); }); } private void ContentTreeController_TreeNodesRendering(TreeControllerBase sender, TreeNodesRenderingEventArgs e) { if (e.QueryStrings["application"].Equals("content") && e.QueryStrings["isDialog"].Equals("false") && string.IsNullOrWhiteSpace(e.QueryStrings["id"]) == false) { var content = sender.Services.ContentService.GetById(int.Parse(e.QueryStrings["id"])); e.Nodes.RemoveAll(treeNode => treeNode.AdditionalData.ContainsKey("contentType") && content.IsInListView(treeNode.AdditionalData["contentType"].ToString())); } } } }
using Opten.Umbraco.ListView.Extensions; using System; using System.Linq; using Umbraco.Core; using Umbraco.Web.Trees; namespace ClassLibrary1 { public class TreeEventHandler : ApplicationEventHandler { protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { ContentTreeController.TreeNodesRendering += ContentTreeController_TreeNodesRendering; } private void ContentTreeController_TreeNodesRendering(TreeControllerBase sender, TreeNodesRenderingEventArgs e) { if (e.QueryStrings["application"].Equals("content") && e.QueryStrings["isDialog"].Equals("false") && string.IsNullOrWhiteSpace(e.QueryStrings["id"]) == false) { var content = sender.Services.ContentService.GetById(int.Parse(e.QueryStrings["id"])); e.Nodes.RemoveAll(treeNode => treeNode.AdditionalData.ContainsKey("contentType") && content.IsInListView(treeNode.AdditionalData["contentType"].ToString())); } } } }
mit
C#
2da9f7ca82a3ecd3faa9ed8ef32c4660eba99f72
Fix GitHubAccessToken never being used
tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Host/Core/GitHubClientFactory.cs
src/Tgstation.Server.Host/Core/GitHubClientFactory.cs
using System; using Microsoft.Extensions.Options; using Octokit; using Tgstation.Server.Host.Configuration; using Tgstation.Server.Host.System; namespace Tgstation.Server.Host.Core { /// <inheritdoc /> sealed class GitHubClientFactory : IGitHubClientFactory { /// <summary> /// The <see cref="IAssemblyInformationProvider"/> for the <see cref="GitHubClientFactory"/> /// </summary> readonly IAssemblyInformationProvider assemblyInformationProvider; /// <summary> /// The <see cref="GeneralConfiguration"/> for the <see cref="GitHubClientFactory"/>. /// </summary> readonly GeneralConfiguration generalConfiguration; /// <summary> /// Construct a <see cref="GitHubClientFactory"/> /// </summary> /// <param name="assemblyInformationProvider">The value of <see cref="assemblyInformationProvider"/>.</param> /// public GitHubClientFactory(IAssemblyInformationProvider assemblyInformationProvider, IOptions<GeneralConfiguration> generalConfigurationOptions) { this.assemblyInformationProvider = assemblyInformationProvider ?? throw new ArgumentNullException(nameof(assemblyInformationProvider)); generalConfiguration = generalConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(generalConfigurationOptions)); } /// <summary> /// Create a <see cref="GitHubClient"/>. /// </summary> /// <param name="accessToken">Optional access token to use as credentials.</param> /// <returns>A new <see cref="GitHubClient"/></returns> GitHubClient CreateClientImpl(string accessToken) { var client = new GitHubClient( new ProductHeaderValue( assemblyInformationProvider.ProductInfoHeaderValue.Product.Name, assemblyInformationProvider.ProductInfoHeaderValue.Product.Version)); if (accessToken != null) client.Credentials = new Credentials(accessToken); return client; } /// <inheritdoc /> public IGitHubClient CreateClient() => CreateClientImpl(generalConfiguration.GitHubAccessToken); /// <inheritdoc /> public IGitHubClient CreateClient(string accessToken) => CreateClientImpl(accessToken ?? throw new ArgumentNullException(nameof(accessToken))); } }
using System; using Octokit; using Tgstation.Server.Host.System; namespace Tgstation.Server.Host.Core { /// <inheritdoc /> sealed class GitHubClientFactory : IGitHubClientFactory { /// <summary> /// The <see cref="IAssemblyInformationProvider"/> for the <see cref="GitHubClientFactory"/> /// </summary> readonly IAssemblyInformationProvider assemblyInformationProvider; /// <summary> /// Construct a <see cref="GitHubClientFactory"/> /// </summary> /// <param name="assemblyInformationProvider">The value of <see cref="assemblyInformationProvider"/></param> public GitHubClientFactory(IAssemblyInformationProvider assemblyInformationProvider) { this.assemblyInformationProvider = assemblyInformationProvider ?? throw new ArgumentNullException(nameof(assemblyInformationProvider)); } /// <summary> /// Create a <see cref="GitHubClient"/> /// </summary> /// <returns>A new <see cref="GitHubClient"/></returns> GitHubClient CreateBaseClient() => new GitHubClient( new ProductHeaderValue( assemblyInformationProvider.ProductInfoHeaderValue.Product.Name, assemblyInformationProvider.ProductInfoHeaderValue.Product.Version)); /// <inheritdoc /> public IGitHubClient CreateClient() => CreateBaseClient(); /// <inheritdoc /> public IGitHubClient CreateClient(string accessToken) { if (accessToken == null) throw new ArgumentNullException(nameof(accessToken)); var result = CreateBaseClient(); result.Credentials = new Credentials(accessToken); return result; } } }
agpl-3.0
C#