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
1fedf442f35898546b4b7eca8c2633475f6de85a
add code snippet for cookie policy
Franklin89/Blog,Franklin89/Blog
MLSoftware.Blog/Startup.cs
MLSoftware.Blog/Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace MLSoftware.Blog { public class Startup { public void ConfigureServices(IServiceCollection services) { // services.Configure<CookiePolicyOptions>(options => // { // // This lambda determines whether user consent for non-essential cookies is needed for a given request. // options.CheckConsentNeeded = context => true; // options.MinimumSameSitePolicy = SameSiteMode.None; // }); services.AddOrchardCms(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); // app.UseCookiePolicy(); app.UseOrchardCore(); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace MLSoftware.Blog { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddOrchardCms(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseOrchardCore(); } } }
mit
C#
432567a501c117e1dc966d075d8d6e7068afc3eb
Handle new frame for navigation service. #277 #307
Caliburn-Micro/Caliburn.Micro,TriadTom/Caliburn.Micro,bitbonk/Caliburn.Micro,serenabenny/Caliburn.Micro,TriadTom/Caliburn.Micro
samples/Caliburn.Micro.HelloUWP/Caliburn.Micro.HelloUWP/ViewModels/ShellViewModel.cs
samples/Caliburn.Micro.HelloUWP/Caliburn.Micro.HelloUWP/ViewModels/ShellViewModel.cs
using System; using Windows.UI.Xaml.Controls; using Caliburn.Micro.HelloUWP.Messages; namespace Caliburn.Micro.HelloUWP.ViewModels { public class ShellViewModel : Screen, IHandle<ResumeStateMessage>, IHandle<SuspendStateMessage> { private readonly WinRTContainer _container; private readonly IEventAggregator _eventAggregator; private INavigationService _navigationService; private bool _resume; public ShellViewModel(WinRTContainer container, IEventAggregator eventAggregator) { _container = container; _eventAggregator = eventAggregator; } protected override void OnActivate() { _eventAggregator.Subscribe(this); } protected override void OnDeactivate(bool close) { _eventAggregator.Unsubscribe(this); } public void SetupNavigationService(Frame frame) { if (_container.HasHandler(typeof(INavigationService), null)) _container.UnregisterHandler(typeof(INavigationService), null); _navigationService = _container.RegisterNavigationService(frame); if (_resume) _navigationService.ResumeState(); } public void ShowDevices() { _navigationService.For<DeviceViewModel>().Navigate(); } public void Handle(SuspendStateMessage message) { _navigationService.SuspendState(); } public void Handle(ResumeStateMessage message) { _resume = true; } } }
using System; using Windows.UI.Xaml.Controls; using Caliburn.Micro.HelloUWP.Messages; namespace Caliburn.Micro.HelloUWP.ViewModels { public class ShellViewModel : Screen, IHandle<ResumeStateMessage>, IHandle<SuspendStateMessage> { private readonly WinRTContainer _container; private readonly IEventAggregator _eventAggregator; private INavigationService _navigationService; private bool _resume; public ShellViewModel(WinRTContainer container, IEventAggregator eventAggregator) { _container = container; _eventAggregator = eventAggregator; } protected override void OnActivate() { _eventAggregator.Subscribe(this); } protected override void OnDeactivate(bool close) { _eventAggregator.Unsubscribe(this); } public void SetupNavigationService(Frame frame) { _navigationService = _container.RegisterNavigationService(frame); if (_resume) _navigationService.ResumeState(); } public void ShowDevices() { _navigationService.For<DeviceViewModel>().Navigate(); } public void Handle(SuspendStateMessage message) { _navigationService.SuspendState(); } public void Handle(ResumeStateMessage message) { _resume = true; } } }
mit
C#
6b45708de087e6fed54ecbf7ac72a9a3b60e2ac4
Fix Sandbox occurs compile error under 5.3
ataihei/UniRx,cruwel/UniRx,ufcpp/UniRx,saruiwa/UniRx,cruwel/UniRx,OC-Leon/UniRx,neuecc/UniRx,kimsama/UniRx,endo0407/UniRx,m-ishikawa/UniRx,TORISOUP/UniRx,ppcuni/UniRx,cruwel/UniRx,OrangeCube/UniRx
Assets/ObjectTest/Sandbox2.cs
Assets/ObjectTest/Sandbox2.cs
using UnityEngine; using UniRx; using UniRx.Triggers; using System.Collections; using System.Linq; using System; using System.Collections.Generic; using UnityEngine.UI; // using UnityEngine.SceneManagement; public class MyEventClass { public event Action<int> Hoge; public void Push(int x) { Hoge(x); } } public class MoGe { public void Huga() { } } // for Scenes/NextSandBox public class Sandbox2 : MonoBehaviour { public Button button; void Awake() { MainThreadDispatcher.Initialize(); } void Aaa(Action action) { } int clickCount = 0; AsyncOperation ao = null; int hogehoge; void Start() { button.OnClickAsObservable().Subscribe(_ => { //if (clickCount++ == 0) //{ // ao = SceneManager.LoadSceneAsync("TestSandbox"); // // Debug.Log(ao.allowSceneActivation); // ao.allowSceneActivation = false; // ao.AsAsyncOperationObservable(new Progress<float>(x => // { // Debug.Log(x); // })).Subscribe(); //} //else //{ // ao.allowSceneActivation = true; //} }); } }
using UnityEngine; using UniRx; using UniRx.Triggers; using System.Collections; using System.Linq; using System; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.SceneManagement; public class MyEventClass { public event Action<int> Hoge; public void Push(int x) { Hoge(x); } } public class MoGe { public void Huga() { } } // for Scenes/NextSandBox public class Sandbox2 : MonoBehaviour { public Button button; void Awake() { MainThreadDispatcher.Initialize(); } void Aaa(Action action) { } int clickCount = 0; AsyncOperation ao = null; int hogehoge; void Start() { button.OnClickAsObservable().Subscribe(_ => { if (clickCount++ == 0) { ao = SceneManager.LoadSceneAsync("TestSandbox"); // Debug.Log(ao.allowSceneActivation); ao.allowSceneActivation = false; ao.AsAsyncOperationObservable(new Progress<float>(x => { Debug.Log(x); })).Subscribe(); } else { ao.allowSceneActivation = true; } }); } }
mit
C#
e61a728681028c767bd8050ff0159a591de7c579
Allow setting the local packages feed from env
mrahhal/Migrator.EF6
deploy_local.csx
deploy_local.csx
using System; using System.IO; using System.Text.RegularExpressions; using System.Diagnostics; using System.Linq; var cd = Environment.CurrentDirectory; var projectName = "Migrator.EF6.Tools"; var userName = Environment.UserName; var userProfileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var deploymentFolder = Environment.GetEnvironmentVariable("MIGRATOR_EF6_LOCAL_PACKAGES_FEED_PATH") ?? $@"C:\D\dev\src\Local Packages"; Directory.CreateDirectory(deploymentFolder); var nugetDirectory = Path.Combine(userProfileDirectory, ".nuget/packages"); var nugetToolsDirectory = Path.Combine(nugetDirectory, ".tools"); var nugetProjectDirectory = Path.Combine(nugetDirectory, projectName); var nugetToolsProjectDirectory = Path.Combine(nugetToolsDirectory, projectName); var regexFolder = new Regex(@"(.\..\..)-(.+)"); var regexFile = new Regex($@"{projectName}\.(.\..\..)-(.+).nupkg"); if (!Pack()) { Console.WriteLine("A problem occurred while packing."); return; } RemoveDevPackageFilesIn(deploymentFolder); RemoveDevPackagesIn(nugetProjectDirectory); RemoveDevPackagesIn(nugetToolsProjectDirectory); var package = GetPackagePath(); if (package == null) { Console.WriteLine("Package file not found. A problem might have occurred with the build script."); return; } var packageFileName = Path.GetFileName(package); var deployedPackagePath = Path.Combine(deploymentFolder, packageFileName); File.Copy(package, deployedPackagePath); Console.WriteLine($"{packageFileName} -> {deployedPackagePath}"); //------------------------------------------------------------------------------ void RemoveDevPackagesIn(string directory) { var folders = Directory.EnumerateDirectories(directory); foreach (var folder in folders) { var name = Path.GetFileName(folder); if (regexFolder.IsMatch(name)) { Directory.Delete(folder, true); } } } void RemoveDevPackageFilesIn(string directory) { var files = Directory.EnumerateFiles(directory); foreach (var file in files) { var name = Path.GetFileName(file); if (regexFile.IsMatch(name)) { File.Delete(file); } } } bool Pack() { var process = Process.Start("powershell", "build.ps1"); process.WaitForExit(); var exitCode = process.ExitCode; return exitCode == 0; } string GetPackagePath() { var packagesDirectory = Path.Combine(cd, "artifacts/packages"); if (!Directory.Exists(packagesDirectory)) { return null; } var files = Directory.EnumerateFiles(packagesDirectory); return files.OrderBy(f => f.Length).FirstOrDefault(); }
using System; using System.IO; using System.Text.RegularExpressions; using System.Diagnostics; using System.Linq; var cd = Environment.CurrentDirectory; var projectName = "Migrator.EF6.Tools"; var userName = Environment.UserName; var userProfileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var deploymentFolder = $@"C:\D\dev\src\Local Packages"; Directory.CreateDirectory(deploymentFolder); var nugetDirectory = Path.Combine(userProfileDirectory, ".nuget/packages"); var nugetToolsDirectory = Path.Combine(nugetDirectory, ".tools"); var nugetProjectDirectory = Path.Combine(nugetDirectory, projectName); var nugetToolsProjectDirectory = Path.Combine(nugetToolsDirectory, projectName); var regexFolder = new Regex(@"(.\..\..)-(.+)"); var regexFile = new Regex($@"{projectName}\.(.\..\..)-(.+).nupkg"); if (!Pack()) { Console.WriteLine("A problem occurred while packing."); return; } RemoveDevPackageFilesIn(deploymentFolder); RemoveDevPackagesIn(nugetProjectDirectory); RemoveDevPackagesIn(nugetToolsProjectDirectory); var package = GetPackagePath(); if (package == null) { Console.WriteLine("Package file not found. A problem might have occurred with the build script."); return; } var packageFileName = Path.GetFileName(package); var deployedPackagePath = Path.Combine(deploymentFolder, packageFileName); File.Copy(package, deployedPackagePath); Console.WriteLine($"{packageFileName} -> {deployedPackagePath}"); //------------------------------------------------------------------------------ void RemoveDevPackagesIn(string directory) { var folders = Directory.EnumerateDirectories(directory); foreach (var folder in folders) { var name = Path.GetFileName(folder); if (regexFolder.IsMatch(name)) { Directory.Delete(folder, true); } } } void RemoveDevPackageFilesIn(string directory) { var files = Directory.EnumerateFiles(directory); foreach (var file in files) { var name = Path.GetFileName(file); if (regexFile.IsMatch(name)) { File.Delete(file); } } } bool Pack() { var process = Process.Start("powershell", "build.ps1"); process.WaitForExit(); var exitCode = process.ExitCode; return exitCode == 0; } string GetPackagePath() { var packagesDirectory = Path.Combine(cd, "artifacts/packages"); if (!Directory.Exists(packagesDirectory)) { return null; } var files = Directory.EnumerateFiles(packagesDirectory); return files.OrderBy(f => f.Length).FirstOrDefault(); }
mit
C#
6ea0198c193db900bbb142f758ccf4daf91e853d
Add transaction to SaveOrUpdate
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/RepositorySaveOrUpdate.cs
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/RepositorySaveOrUpdate.cs
using System.Threading.Tasks; using Dapper.FastCrud; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; using Smooth.IoC.Dapper.Repository.UnitOfWork.Entities; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public abstract partial class Repository<TSession, TEntity, TPk> where TEntity : class, IEntity<TPk> where TSession : class, ISession { public TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow) { return SaveOrUpdateAsync(entity, uow).Result; } public async Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow) { if (entity.Id.Equals(default(TPk))) { return await Task.Run(() => { uow.Insert(entity, statement=>statement.AttachToTransaction(uow)); return entity.Id; }); } var result = await uow.UpdateAsync(entity, statement => statement.AttachToTransaction(uow)); return result ? entity.Id : default(TPk); } } }
using System.Threading.Tasks; using Dapper.FastCrud; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; using Smooth.IoC.Dapper.Repository.UnitOfWork.Entities; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public abstract partial class Repository<TSession, TEntity, TPk> where TEntity : class, IEntity<TPk> where TSession : class, ISession { public TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow) { return SaveOrUpdateAsync(entity, uow).Result; } public async Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow) { if (entity.Id.Equals(default(TPk))) { return await Task.Run(() => { uow.Insert(entity); return entity.Id; }); } var result = await uow.UpdateAsync(entity); return result ? entity.Id : default(TPk); } } }
mit
C#
c888ed06bd35a6ed03ec641a480a0b2123a3515c
change FindByExternalLoginInfo to FindByUserLoginInfo
tc-dev/tc-dev.Core
src/tc-dev.Core/Identity/IAppUserManager.cs
src/tc-dev.Core/Identity/IAppUserManager.cs
using System; using System.Security.Claims; using System.Threading.Tasks; using tc_dev.Core.Identity.Models; namespace tc_dev.Core.Identity { public interface IAppUserManager : IDisposable { string AppCookie { get; } string ExternalBearer { get; } string ExternalCookie { get; } string TwoFactorCookie { get; } string TwoFactorRememberBrowserCookie { get; } AppIdentityResult AddLogin(int userId, AppUserLoginInfo loginInfo); Task<AppIdentityResult> AddLoginAsync(int userId, AppUserLoginInfo loginInfo); AppIdentityResult AddPassword(int userId, string password); Task<AppIdentityResult> AddPasswordAsync(int userId, string password); AppIdentityResult ChangePassword(int userId, string oldPassword, string newPassword); Task<AppIdentityResult> ChangePasswordAsync(int userId, string oldPassword, string newPassword); AppIdentityResult Create(AppUser user); Task<AppIdentityResult> CreateAsync(AppUser user); AppIdentityResult Create(AppUser user, string password); Task<AppIdentityResult> CreateAsync(AppUser user, string password); ClaimsIdentity CreateIdentity(AppUser user, string authenticationType); Task<ClaimsIdentity> CreateIdentityAsyc(AppUser user, string authenticationType); AppUser FindByEmail(string email); Task<AppUser> FindByEmailAsync(string email); AppUser FindByUserLoginInfo(AppUserLoginInfo loginInfo); Task<AppUser> FindByUserLoginInfoAsync(AppUserLoginInfo loginInfo); AppUser FindById(int userId); Task<AppUser> FindByIdAsync(int userId); AppUser FindByUserName(string userName); Task<AppUser> FindByUserNameAsync(string userName); AppIdentityResult RemoveLogin(int userId, AppUserLoginInfo loginInfo); Task<AppIdentityResult> RemoveLoginAsync(int userId, AppUserLoginInfo loginInfo); } }
using System; using System.Security.Claims; using System.Threading.Tasks; using tc_dev.Core.Identity.Models; namespace tc_dev.Core.Identity { public interface IAppUserManager : IDisposable { string AppCookie { get; } string ExternalBearer { get; } string ExternalCookie { get; } string TwoFactorCookie { get; } string TwoFactorRememberBrowserCookie { get; } AppIdentityResult AddLogin(int userId, AppUserLoginInfo loginInfo); Task<AppIdentityResult> AddLoginAsync(int userId, AppUserLoginInfo loginInfo); AppIdentityResult AddPassword(int userId, string password); Task<AppIdentityResult> AddPasswordAsync(int userId, string password); AppIdentityResult ChangePassword(int userId, string oldPassword, string newPassword); Task<AppIdentityResult> ChangePasswordAsync(int userId, string oldPassword, string newPassword); AppIdentityResult Create(AppUser user); Task<AppIdentityResult> CreateAsync(AppUser user); AppIdentityResult Create(AppUser user, string password); Task<AppIdentityResult> CreateAsync(AppUser user, string password); ClaimsIdentity CreateIdentity(AppUser user, string authenticationType); Task<ClaimsIdentity> CreateIdentityAsyc(AppUser user, string authenticationType); AppUser FindByEmail(string email); Task<AppUser> FindByEmailAsync(string email); AppUser FindByExternalLoginInfo(AppExternalLoginInfo loginInfo); Task<AppUser> FindByExternalLoginInfoAsync(AppExternalLoginInfo loginInfo); AppUser FindById(int userId); Task<AppUser> FindByIdAsync(int userId); AppUser FindByUserName(string userName); Task<AppUser> FindByUserNameAsync(string userName); AppIdentityResult RemoveLogin(int userId, AppUserLoginInfo loginInfo); Task<AppIdentityResult> RemoveLoginAsync(int userId, AppUserLoginInfo loginInfo); } }
mit
C#
1b6a51d14ad74ea70c3a72e585aff9b685d3d749
Bump version
transistor1/SQLFormatterPlugin
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SQLFormatterPlugin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SQLFormatterPlugin")] [assembly: AssemblyCopyright("Copyright © 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("22247641-9910-4c24-9a9d-dd295a749d41")] // 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.9997.0")] [assembly: AssemblyFileVersion("1.0.9997.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("SQLFormatterPlugin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SQLFormatterPlugin")] [assembly: AssemblyCopyright("Copyright © 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("22247641-9910-4c24-9a9d-dd295a749d41")] // 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.9996.0")] [assembly: AssemblyFileVersion("1.0.9996.0")]
bsd-3-clause
C#
6e0db31a528fae2fbbf953a6dab7f7e1bd766428
Put loop test's variables in a local scope
TheBerkin/Rant
Rant.Tests/Expressions/Loops.cs
Rant.Tests/Expressions/Loops.cs
using NUnit.Framework; namespace Rant.Tests.Expressions { [TestFixture] public class Loops { private readonly RantEngine rant = new RantEngine(); [Test] public void StringBuildingWhileLoop() { var output = rant.Do(@" [@ (function() { var parts = (""this"", ""is"", ""a"", ""test""); var i = 0; var buffer = """"; while(i < parts.length) { if (i > 0) buffer ~= "" ""; buffer ~= parts[i]; i++; } return buffer; })(); ]"); Assert.AreEqual("this is a test", output.Main); } } }
using NUnit.Framework; namespace Rant.Tests.Expressions { [TestFixture] public class Loops { private readonly RantEngine rant = new RantEngine(); [Test] public void StringBuildingWhileLoop() { var output = rant.Do(@" [@ var parts = (""this"", ""is"", ""a"", ""test""); var i = 0; var buffer = """"; while(i < parts.length) { if (i > 0) buffer ~= "" ""; buffer ~= parts[i]; i++; } return buffer; ]"); Assert.AreEqual("this is a test", output.Main); } } }
mit
C#
9609520a53b3f91d722b68bbe189cc419f2491b9
Remove "Get" statement from example docs
Confruggy/Discord.Net,RogueException/Discord.Net,AntiTcb/Discord.Net,LassieME/Discord.Net
docs/guides/samples/dependency_module.cs
docs/guides/samples/dependency_module.cs
using Discord; using Discord.Commands; using Discord.WebSocket; public class ModuleA : ModuleBase { private readonly DatabaseService _database; // Dependencies can be injected via the constructor public ModuleA(DatabaseService database) { _database = database; } public async Task ReadFromDb() { var x = _database.getX(); await ReplyAsync(x); } } public class ModuleB { // Public settable properties will be injected public AnnounceService { get; set; } // Public properties without setters will not public CommandService Commands { get; } // Public properties annotated with [DontInject] will not [DontInject] public NotificationService { get; set; } public ModuleB(CommandService commands) { Commands = commands; } }
using Discord; using Discord.Commands; using Discord.WebSocket; public class ModuleA : ModuleBase { private readonly DatabaseService _database; // Dependencies can be injected via the constructor public ModuleA(DatabaseService database) { _database = database; } public async Task ReadFromDb() { var x = _database.getX(); await ReplyAsync(x); } } public class ModuleB { // Public settable properties will be injected public AnnounceService { get; set; } // Public properties without setters will not public CommandService Commands { get; } // Public properties annotated with [DontInject] will not [DontInject] public NotificationService { get; set; } public ModuleB(CommandService commands, IDependencyMap map) { Commands = commands; _notification = map.Get<NotificationService>(); } }
mit
C#
f2f2829e97711e251e16732a587e4167f263dc43
Fix build
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
NakedLegacy/NakedLegacy.Reflector/Facet/ActionChoicesViaAboutMethodFacet.cs
NakedLegacy/NakedLegacy.Reflector/Facet/ActionChoicesViaAboutMethodFacet.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.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; using NakedFramework.Architecture.Adapter; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.Framework; using NakedFramework.Architecture.Spec; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Core.Util; namespace NakedLegacy.Reflector.Facet; [Serializable] public sealed class ActionChoicesViaAboutMethodFacet : AbstractViaAboutMethodFacet, IActionChoicesFacet, IImperativeFacet { private readonly int index; private readonly ILogger<ActionChoicesViaAboutMethodFacet> logger; public ActionChoicesViaAboutMethodFacet(MethodInfo aboutmethod, ISpecification holder, int index, ILogger<ActionChoicesViaAboutMethodFacet> logger) : base(typeof(IActionChoicesFacet), holder, aboutmethod, AboutHelpers.AboutType.Action) { this.index = index; this.logger = logger; } public (string, IObjectSpecImmutable)[] ParameterNamesAndTypes => Array.Empty<(string, IObjectSpecImmutable)>(); public bool IsMultiple => false; public bool IsEnabled(INakedObjectAdapter nakedObjectAdapter) => GetChoices(nakedObjectAdapter).Any(); public object[] GetChoices(INakedObjectAdapter nakedObjectAdapter, IDictionary<string, INakedObjectAdapter> parameterNameValues, INakedFramework framework) => GetChoices(nakedObjectAdapter); private object[] GetChoices(INakedObjectAdapter nakedObjectAdapter) { if (GetAbout(nakedObjectAdapter) is ActionAbout actionAbout) { var parameterOptions = actionAbout.ParamOptions?.Any() == true ? actionAbout.ParamOptions[index] : Array.Empty<object>(); if (parameterOptions.Any()) { return parameterOptions; } } return Array.Empty<object>(); } public IAbout GetAbout(INakedObjectAdapter nakedObjectAdapter) => InvokeAboutMethod(nakedObjectAdapter.GetDomainObject(), AboutTypeCodes.Parameters, false, true); } // Copyright (c) Naked Objects Group Ltd.
// 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.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; using NakedFramework.Architecture.Adapter; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.Framework; using NakedFramework.Architecture.Spec; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Core.Util; namespace NakedLegacy.Reflector.Facet; [Serializable] public sealed class ActionChoicesViaAboutMethodFacet : AbstractViaAboutMethodFacet, IActionChoicesFacet, IImperativeFacet { private readonly int index; private readonly ILogger<ActionChoicesViaAboutMethodFacet> logger; public ActionChoicesViaAboutMethodFacet(MethodInfo aboutmethod, ISpecification holder, int index, ILogger<ActionChoicesViaAboutMethodFacet> logger) : base(typeof(IActionChoicesFacet), holder, aboutmethod, AboutHelpers.AboutType.Action) { this.index = index; this.logger = logger; } public (string, IObjectSpecImmutable)[] ParameterNamesAndTypes => Array.Empty<(string, IObjectSpecImmutable)>(); public bool IsMultiple => false; public bool IsEnabled(INakedObjectAdapter nakedObjectAdapter) => GetChoices(nakedObjectAdapter).Any(); public object[] GetChoices(INakedObjectAdapter nakedObjectAdapter, IDictionary<string, INakedObjectAdapter> parameterNameValues, INakedFramework framework) => GetChoices(nakedObjectAdapter); private object[] GetChoices(INakedObjectAdapter nakedObjectAdapter) { if (GetAbout(nakedObjectAdapter) is ActionAbout actionAbout) { var parameterOptions = actionAbout.ParamOptions?[index] ?? Array.Empty<object>(); if (parameterOptions.Any()) { return parameterOptions; } } return Array.Empty<object>(); } public IAbout GetAbout(INakedObjectAdapter nakedObjectAdapter) => InvokeAboutMethod(nakedObjectAdapter.GetDomainObject(), AboutTypeCodes.Parameters, false, true); } // Copyright (c) Naked Objects Group Ltd.
apache-2.0
C#
6ca01f1b470b3dd80ec236baa9e41b420d66ca51
use string builder
splitice/SystemInteract.Net,splitice/SystemInteract.Net
SystemInteract/ProcessHelper.cs
SystemInteract/ProcessHelper.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace SystemInteract { public class ProcessHelper { private const int DefaultTimeout = 120; public static void ReadToEnd(ISystemProcess process, out String output, out String error, int timeout = DefaultTimeout) { StringBuilder toutput = new StringBuilder(); StringBuilder terror = new StringBuilder(); DataReceivedEventHandler errorEvent = null, outEvent = null; if (process.StartInfo.RedirectStandardError) { errorEvent = (a, b) => terror.AppendLine(b.Data); process.ErrorDataReceived += errorEvent; process.BeginErrorReadLine(); } if (process.StartInfo.RedirectStandardOutput) { outEvent = (a, b) => toutput.AppendLine(b.Data); process.OutputDataReceived += outEvent; process.BeginOutputReadLine(); } if (!process.WaitForExit(timeout * 1000)) { throw new TimeoutException(String.Format("Timeout. Process did not complete executing within {0} seconds", timeout)); } output = toutput.ToString(); error = terror.ToString(); if (errorEvent != null) { process.ErrorDataReceived -= errorEvent; } if (outEvent != null) { process.OutputDataReceived -= outEvent; } } public static void WaitForExit(ISystemProcess process) { String temp; ReadToEnd(process, out temp, out temp); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace SystemInteract { public class ProcessHelper { private const int DefaultTimeout = 120; public static void ReadToEnd(ISystemProcess process, out String output, out String error, int timeout = DefaultTimeout) { String toutput = ""; String terror = ""; DataReceivedEventHandler errorEvent = null, outEvent = null; if (process.StartInfo.RedirectStandardError) { errorEvent = (a, b) => terror += b.Data + "\n"; process.ErrorDataReceived += errorEvent; process.BeginErrorReadLine(); } if (process.StartInfo.RedirectStandardOutput) { outEvent = (a, b) => toutput += b.Data + "\n"; process.OutputDataReceived += outEvent; process.BeginOutputReadLine(); } if (!process.WaitForExit(timeout * 1000)) { throw new TimeoutException(String.Format("Timeout. Process did not complete executing within {0} seconds", timeout)); } output = toutput; error = terror; if (errorEvent != null) { process.ErrorDataReceived -= errorEvent; } if (outEvent != null) { process.OutputDataReceived -= outEvent; } } public static void WaitForExit(ISystemProcess process) { String temp; ReadToEnd(process, out temp, out temp); } } }
apache-2.0
C#
bc0872c3585f2e2cb11ad9f32e33a0acee5c9105
Improve cfx default settings (removing hack switch)
David-Desmaisons/Neutronium,David-Desmaisons/Neutronium,NeutroniumCore/Neutronium,NeutroniumCore/Neutronium,NeutroniumCore/Neutronium,David-Desmaisons/Neutronium
WebBrowserEngine/ChromiumFX/HTMEngine.ChromiumFX/ChromiumFxWebBrowserApp.cs
WebBrowserEngine/ChromiumFX/HTMEngine.ChromiumFX/ChromiumFxWebBrowserApp.cs
using Chromium; using Chromium.Event; using Neutronium.Core; using Neutronium.WPF; namespace Neutronium.WebBrowserEngine.ChromiumFx { public abstract class ChromiumFxWebBrowserApp : HTMLApp { protected virtual bool DisableWebSecurity => false; protected override IWPFWebWindowFactory GetWindowFactory(IWebSessionLogger logger) => new ChromiumFXWPFWebWindowFactory(logger, UpdateChromiumSettings, PrivateUpdateLineCommandArg); protected virtual void UpdateChromiumSettings(CfxSettings settings) { } private void PrivateUpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand) { var commandLine = beforeLineCommand.CommandLine; commandLine.AppendSwitch("disable-gpu"); if (DisableWebSecurity) commandLine.AppendSwitch("disable-web-security"); UpdateLineCommandArg(beforeLineCommand); } protected virtual void UpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand) { } } }
using Chromium; using Chromium.Event; using Neutronium.Core; using Neutronium.WPF; namespace Neutronium.WebBrowserEngine.ChromiumFx { public abstract class ChromiumFxWebBrowserApp : HTMLApp { protected virtual bool DisableWebSecurity => true; protected override IWPFWebWindowFactory GetWindowFactory(IWebSessionLogger logger) => new ChromiumFXWPFWebWindowFactory(logger, UpdateChromiumSettings, PrivateUpdateLineCommandArg); protected virtual void UpdateChromiumSettings(CfxSettings settings) { } private void PrivateUpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand) { var commandLine = beforeLineCommand.CommandLine; commandLine.AppendSwitch("disable-gpu"); // Needed to avoid crash when using devtools application tab with custom schema commandLine.AppendSwitch("disable-kill-after-bad-ipc"); if (DisableWebSecurity) commandLine.AppendSwitch("disable-web-security"); UpdateLineCommandArg(beforeLineCommand); } protected virtual void UpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand) { } } }
mit
C#
d56c33cd2a73df2b5e992d8faad77cf7ee919510
Add test for #164
SharpMap/SharpMap,SharpMap/SharpMap
UnitTests/Issues/GitHub.cs
UnitTests/Issues/GitHub.cs
using System.Net; using NUnit.Framework; namespace UnitTests.Issues { public class GitHub { #if !LINUX [TestCase] [Description("Raster Layer removed when apply rotation on map")] public void TestIssue116() { string rasterFile = TestUtility.GetPathToTestFile("world.topo.bathy.200412.3x21600x10800.jpg"); if (!System.IO.File.Exists(rasterFile)) Assert.Ignore("Test file {0} not present.", rasterFile); using (var map = new SharpMap.Map()) { var rasterLyr = new SharpMap.Layers.GdalRasterLayer("Raster", rasterFile); map.Layers.Add(rasterLyr); var linePoints = new[] { new GeoAPI.Geometries.Coordinate(0, 0), new GeoAPI.Geometries.Coordinate(10, 10) }; var line = NetTopologySuite.NtsGeometryServices.Instance.CreateGeometryFactory(4326).CreateLineString(linePoints); var linealDs = new SharpMap.Data.Providers.GeometryProvider(line); var linealLyr = new SharpMap.Layers.VectorLayer("Lineal", linealDs) { SRID = 4326 }; linealLyr.Style.Line = new System.Drawing.Pen(System.Drawing.Color.Red, 2f) { EndCap = System.Drawing.Drawing2D.LineCap.Round }; map.Layers.Add(linealLyr); map.ZoomToExtents(); var centerMap = new System.Drawing.PointF(map.Size.Width / 2f, map.Size.Height / 2f); for (float f = -180; f <= 180; f += 5) { var mapTransform = new System.Drawing.Drawing2D.Matrix(); mapTransform.RotateAt(f, centerMap); map.MapTransform = mapTransform; using (var img = map.GetMap()) img.Save(System.IO.Path.Combine(UnitTestsFixture.GetImageDirectory(this), $"TestIssue116.{f}deg.png")); } } } #endif [TestCase("https://www.wms.nrw.de/geobasis/wms_nw_dop", SecurityProtocolType.Ssl3, SecurityProtocolType.Tls12)] [Description("https request with unmatching security protocol type")] [Category("RequiresWindows")] public void TestIssue156(string url, SecurityProtocolType sptFail, SecurityProtocolType sptSucceed) { var spDefault = ServicePointManager.SecurityProtocol; SharpMap.Layers.WmsLayer wmsLayer = null; ServicePointManager.SecurityProtocol = sptFail; Assert.That(() => wmsLayer = new SharpMap.Layers.WmsLayer("WMSFAIL", url), Throws.InstanceOf<System.ApplicationException>() ); ServicePointManager.SecurityProtocol = sptSucceed; Assert.That(() => wmsLayer = new SharpMap.Layers.WmsLayer("WMSSUCCED", url), Throws.Nothing); Assert.That(wmsLayer, Is.Not.Null, "wmsLayer null"); ServicePointManager.SecurityProtocol = spDefault; } } }
using System; using System.Net; using GeoAPI.Geometries; using NUnit.Framework; namespace UnitTests.Issues { public class GitHub { [TestCase("https://www.wms.nrw.de/geobasis/wms_nw_dop", SecurityProtocolType.Ssl3, SecurityProtocolType.Tls12)] [Description("https request with unmatching security protocol type")] [Category("RequiresWindows")] public void TestIssue156(string url, SecurityProtocolType sptFail, SecurityProtocolType sptSucceed) { var spDefault = ServicePointManager.SecurityProtocol; SharpMap.Layers.WmsLayer wmsLayer = null; ServicePointManager.SecurityProtocol = sptFail; Assert.That(() => wmsLayer = new SharpMap.Layers.WmsLayer("WMSFAIL", url), Throws.InstanceOf<ApplicationException>() ); ServicePointManager.SecurityProtocol = sptSucceed; Assert.That(() => wmsLayer = new SharpMap.Layers.WmsLayer("WMSSUCCED", url), Throws.Nothing); Assert.That(wmsLayer, Is.Not.Null, "wmsLayer null"); ServicePointManager.SecurityProtocol = spDefault; } } }
lgpl-2.1
C#
a287fd73bbc81ca412d7b67fb33783483ed5b964
Write MaxCombo attribute for mania
peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu
osu.Game.Rulesets.Mania/Difficulty/ManiaDifficultyAttributes.cs
osu.Game.Rulesets.Mania/Difficulty/ManiaDifficultyAttributes.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 Newtonsoft.Json; using osu.Game.Rulesets.Difficulty; namespace osu.Game.Rulesets.Mania.Difficulty { public class ManiaDifficultyAttributes : DifficultyAttributes { /// <summary> /// The hit window for a GREAT hit inclusive of rate-adjusting mods (DT/HT/etc). /// </summary> /// <remarks> /// Rate-adjusting mods do not affect the hit window at all in osu-stable. /// </remarks> [JsonProperty("great_hit_window")] public double GreatHitWindow { get; set; } /// <summary> /// The score multiplier applied via score-reducing mods. /// </summary> [JsonProperty("score_multiplier")] public double ScoreMultiplier { get; set; } public override IEnumerable<(int attributeId, object value)> ToDatabaseAttributes() { foreach (var v in base.ToDatabaseAttributes()) yield return v; yield return (ATTRIB_ID_MAX_COMBO, MaxCombo); yield return (ATTRIB_ID_DIFFICULTY, StarRating); yield return (ATTRIB_ID_GREAT_HIT_WINDOW, GreatHitWindow); yield return (ATTRIB_ID_SCORE_MULTIPLIER, ScoreMultiplier); } public override void FromDatabaseAttributes(IReadOnlyDictionary<int, double> values) { base.FromDatabaseAttributes(values); MaxCombo = (int)values[ATTRIB_ID_MAX_COMBO]; StarRating = values[ATTRIB_ID_DIFFICULTY]; GreatHitWindow = values[ATTRIB_ID_GREAT_HIT_WINDOW]; ScoreMultiplier = values[ATTRIB_ID_SCORE_MULTIPLIER]; } } }
// 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 Newtonsoft.Json; using osu.Game.Rulesets.Difficulty; namespace osu.Game.Rulesets.Mania.Difficulty { public class ManiaDifficultyAttributes : DifficultyAttributes { /// <summary> /// The hit window for a GREAT hit inclusive of rate-adjusting mods (DT/HT/etc). /// </summary> /// <remarks> /// Rate-adjusting mods do not affect the hit window at all in osu-stable. /// </remarks> [JsonProperty("great_hit_window")] public double GreatHitWindow { get; set; } /// <summary> /// The score multiplier applied via score-reducing mods. /// </summary> [JsonProperty("score_multiplier")] public double ScoreMultiplier { get; set; } public override IEnumerable<(int attributeId, object value)> ToDatabaseAttributes() { foreach (var v in base.ToDatabaseAttributes()) yield return v; // Todo: osu!mania doesn't output MaxCombo attribute for some reason. yield return (ATTRIB_ID_DIFFICULTY, StarRating); yield return (ATTRIB_ID_GREAT_HIT_WINDOW, GreatHitWindow); yield return (ATTRIB_ID_SCORE_MULTIPLIER, ScoreMultiplier); } public override void FromDatabaseAttributes(IReadOnlyDictionary<int, double> values) { base.FromDatabaseAttributes(values); StarRating = values[ATTRIB_ID_DIFFICULTY]; GreatHitWindow = values[ATTRIB_ID_GREAT_HIT_WINDOW]; ScoreMultiplier = values[ATTRIB_ID_SCORE_MULTIPLIER]; } } }
mit
C#
f9d26334b350748fa6278b34ef8732905763ea6a
fix logic, S_SPAWN_PROJECTILE
neowutran/OpcodeSearcher
DamageMeter.Core/Heuristic/S_SPAWN_PROJECTILE.cs
DamageMeter.Core/Heuristic/S_SPAWN_PROJECTILE.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tera.Game.Messages; namespace DamageMeter.Heuristic { public class S_SPAWN_PROJECTILE : AbstractPacketHeuristic { public static S_SPAWN_PROJECTILE Instance => _instance ?? (_instance = new S_SPAWN_PROJECTILE()); private static S_SPAWN_PROJECTILE _instance; public bool Initialized = false; private S_SPAWN_PROJECTILE() : base(OpcodeEnum.S_SPAWN_PROJECTILE) { } public new void Process(ParsedMessage message) { base.Process(message); if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) { return; } // 65 - current packet size from NA (EU should be too), 67 will be in future (maybe?) //TODO: ADD check with projectilOwnerId from sEachSkillResult if (message.Payload.Count != 65 || message.Payload.Count != 67) { return; } var id = Reader.ReadUInt64(); var unk1 = Reader.ReadInt32(); var skill = Reader.ReadInt32(); var startPosition = Reader.ReadVector3f(); var endPosition = Reader.ReadVector3f(); var unk2 = Reader.ReadByte(); var speed = Reader.ReadSingle(); var source = Reader.ReadUInt64(); var model = Reader.ReadUInt32(); var unk4 = Reader.ReadInt32(); var unk5 = Reader.ReadInt32(); if (!OpcodeFinder.Instance.KnowledgeDatabase.TryGetValue(OpcodeFinder.KnowledgeDatabaseItem.LoggedCharacter, out Tuple<Type, object> currChar)) { throw new Exception("Logger character should be know at this point."); } var ch = (LoggedCharacter)currChar.Item2; if (ch.Cid != source) { return; } if (ch.Model != model) { return; } OpcodeFinder.Instance.SetOpcode(message.OpCode, OPCODE); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tera.Game.Messages; namespace DamageMeter.Heuristic { public class S_SPAWN_PROJECTILE : AbstractPacketHeuristic { public static S_SPAWN_PROJECTILE Instance => _instance ?? (_instance = new S_SPAWN_PROJECTILE()); private static S_SPAWN_PROJECTILE _instance; public bool Initialized = false; private S_SPAWN_PROJECTILE() : base(OpcodeEnum.S_SPAWN_PROJECTILE) { } public new void Process(ParsedMessage message) { base.Process(message); if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) { return; } // 65 - current packet size from NA (EU should be too), 67 will be in future (maybe?) //TODO: ADD check with projectilOwnerId from sEachSkillResult if (message.Payload.Count == 65 || message.Payload.Count == 67) { return; } var id = Reader.ReadUInt64(); var unk1 = Reader.ReadInt32(); var skill = Reader.ReadInt32(); var startPosition = Reader.ReadVector3f(); var endPosition = Reader.ReadVector3f(); var unk2 = Reader.ReadByte(); var speed = Reader.ReadSingle(); var source = Reader.ReadUInt64(); var model = Reader.ReadUInt32(); var unk4 = Reader.ReadInt32(); var unk5 = Reader.ReadInt32(); if (!OpcodeFinder.Instance.KnowledgeDatabase.TryGetValue(OpcodeFinder.KnowledgeDatabaseItem.LoggedCharacter, out Tuple<Type, object> currChar)) { throw new Exception("Logger character should be know at this point."); } var ch = (LoggedCharacter)currChar.Item2; if (ch.Cid != source) { return; } if (ch.Model != model) { return; } OpcodeFinder.Instance.SetOpcode(message.OpCode, OPCODE); } } }
mit
C#
ff9da9d7e1c74a26dc8d98b235aec27c191f1ce7
Add null check to VocabUtils.AssociatesWith
TheBerkin/Rant
Rant/Vocabulary/VocabUtils.cs
Rant/Vocabulary/VocabUtils.cs
using System; using System.Collections.Generic; using System.Linq; namespace Rant.Vocabulary { internal static class VocabUtils { private static readonly Dictionary<string, string> StringCache = new Dictionary<string, string>(); public static string GetString(string str) { string cstr; if (!StringCache.TryGetValue(str, out cstr)) cstr = StringCache[str] = str; return cstr; } public static bool AssociatesWith(this RantDictionaryEntry a, RantDictionaryEntry b) { if (a == null || b == null) return false; bool aNoneRequired = !a.GetRequiredClasses().Any(); bool bNoneRequired = !b.GetRequiredClasses().Any(); if (aNoneRequired && bNoneRequired) return true; // If both have no required classes, pass. // One or both have required classes. // Remove B optionals from A required. var aRequired = a.GetRequiredClasses().Except(b.GetOptionalClasses()); // Remove A optionals from B required. var bRequired = b.GetRequiredClasses().Except(a.GetOptionalClasses()); // Both should be either empty, or have exactly the same classes. return !aRequired.Except(bRequired).Any() && aRequired.Any() == bRequired.Any(); } public static int RhymeIndex(RantDictionaryTerm baseValue, RantDictionaryTerm testValue) { if (baseValue == null || testValue == null) return 0; var baseParts = baseValue.PronunciationParts; var testParts = testValue.PronunciationParts; int index = 0; int len = Math.Min(baseParts.Length, testParts.Length); for (int i = 0; i < len; i++) { if (baseParts[baseParts.Length - (i + 1)] == testParts[testParts.Length - (i + 1)]) { index++; } else { return index; } } return index; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Rant.Vocabulary { internal static class VocabUtils { private static readonly Dictionary<string, string> StringCache = new Dictionary<string, string>(); public static string GetString(string str) { string cstr; if (!StringCache.TryGetValue(str, out cstr)) cstr = StringCache[str] = str; return cstr; } public static bool AssociatesWith(this RantDictionaryEntry a, RantDictionaryEntry b) { bool aNoneRequired = !a.GetRequiredClasses().Any(); bool bNoneRequired = !b.GetRequiredClasses().Any(); if (aNoneRequired && bNoneRequired) return true; // If both have no required classes, pass. // One or both have required classes. // Remove B optionals from A required. var aRequired = a.GetRequiredClasses().Except(b.GetOptionalClasses()); // Remove A optionals from B required. var bRequired = b.GetRequiredClasses().Except(a.GetOptionalClasses()); // Both should be either empty, or have exactly the same classes. return !aRequired.Except(bRequired).Any() && aRequired.Any() == bRequired.Any(); } public static int RhymeIndex(RantDictionaryTerm baseValue, RantDictionaryTerm testValue) { if (baseValue == null || testValue == null) return 0; var baseParts = baseValue.PronunciationParts; var testParts = testValue.PronunciationParts; int index = 0; int len = Math.Min(baseParts.Length, testParts.Length); for (int i = 0; i < len; i++) { if (baseParts[baseParts.Length - (i + 1)] == testParts[testParts.Length - (i + 1)]) { index++; } else { return index; } } return index; } } }
mit
C#
9b37228d172e09204b261280cb03865639212612
Add unit tests.
jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr
test/app.tests/WebApi/ActionFactoryTest.cs
test/app.tests/WebApi/ActionFactoryTest.cs
using Xunit; using Moq; using FluentAssertions; using HelloWorldApp.WebApi.Actions; using HelloWorldApp.WebApi; namespace HelloWorldApp.Test.WebApi { public class ActionFactoryTest { [Fact] public void CreateSayHelloWorldActionTest() { var action = Mock.Of<ISayHelloWorldAction>(); var resourceProvider = Mock.Of<IResourceProvider>(r => r.CreateResource<ISayHelloWorldAction>() == action); var sut = new ActionFactory(resourceProvider); var result = sut.CreateSayHelloWorldAction(); result.Should().NotBeNull(); } [Fact] public void CreateGetLastTenGreetingsActionTest() { var action = Mock.Of<IGetLastTenGreetingsAction>(); var resourceProvider = Mock.Of<IResourceProvider>(r => r.CreateResource<IGetLastTenGreetingsAction>() == action); var sut = new ActionFactory(resourceProvider); var result = sut.CreateGetLastTenGreetingsAction(); result.Should().NotBeNull(); } [Fact] public void CreateGetTotalNumberOfGreetingsActionTest() { var action = Mock.Of<IGetTotalNumberOfGreetingsAction>(); var resourceProvider = Mock.Of<IResourceProvider>(r => r.CreateResource<GetTotalNumberOfGreetingsAction>() == action); var sut = new ActionFactory(resourceProvider); var result = sut.CreateGetTotalNumberOfGreetingsAction(); result.Should().NotBeNull(); } } }
using Xunit; using Moq; using FluentAssertions; using HelloWorldApp.WebApi.Actions; using HelloWorldApp.WebApi; namespace HelloWorldApp.Test.WebApi { public class ActionFactoryTest { [Fact] public void CreateSayHelloWorldActionTest() { var sayHelloWorldAction = Mock.Of<ISayHelloWorldAction>(); var resourceProvider = Mock.Of<IResourceProvider>(r => r.CreateResource<ISayHelloWorldAction>() == sayHelloWorldAction); var sut = new ActionFactory(resourceProvider); var action = sut.CreateSayHelloWorldAction(); action.Should().NotBeNull(); } [Fact] public void CreateGetLastTenGreetingsActionTest() { var getLastTenGreetingsAction = Mock.Of<IGetLastTenGreetingsAction>(); var resourceProvider = Mock.Of<IResourceProvider>(r => r.CreateResource<IGetLastTenGreetingsAction>() == getLastTenGreetingsAction); var sut = new ActionFactory(resourceProvider); var action = sut.CreateGetLastTenGreetingsAction(); action.Should().NotBeNull(); } } }
mit
C#
1dcce093df91e992c8ecc63306511333d0d2bd2e
Make Configuration public
OatmealDome/SplatoonUtilities
MusicRandomizer/MusicRandomizer/Configuration.cs
MusicRandomizer/MusicRandomizer/Configuration.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace MusicRandomizer { [Serializable] public class Configuration { public String currentVersion; public SplatoonRegion region; private static XmlSerializer serializer = new XmlSerializer(typeof(Configuration)); public static Configuration currentConfig; public static void Load() { if (!File.Exists("Configuration.xml")) { VersionRequestForm requestForm = new VersionRequestForm(); requestForm.ShowDialog(); currentConfig = new Configuration(); currentConfig.currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); currentConfig.region = requestForm.chosenRegion; Save(); } else { using (FileStream stream = File.OpenRead("Configuration.xml")) { currentConfig = (Configuration)serializer.Deserialize(stream); } } } public static void Save() { File.Delete("Configuration.xml"); using (FileStream writer = File.OpenWrite("Configuration.xml")) { serializer.Serialize(writer, currentConfig); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace MusicRandomizer { [Serializable] class Configuration { public String currentVersion; public SplatoonRegion region; private static XmlSerializer serializer = new XmlSerializer(typeof(Configuration)); public static Configuration currentConfig; public static void Load() { if (!File.Exists("Configuration.xml")) { VersionRequestForm requestForm = new VersionRequestForm(); requestForm.ShowDialog(); currentConfig = new Configuration(); currentConfig.currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); currentConfig.region = requestForm.chosenRegion; Save(); } else { using (FileStream stream = File.OpenRead("Configuration.xml")) { currentConfig = (Configuration)serializer.Deserialize(stream); } } } public static void Save() { File.Delete("Configuration.xml"); using (FileStream writer = File.OpenWrite("Configuration.xml")) { serializer.Serialize(writer, currentConfig); } } } }
mit
C#
e0d3ed65f1069666279e1a60ea1150a3dc74dee1
Update CharacterSpawn.cs
lockzag/PolarisServer,PolarisTeam/PolarisServer,Dreadlow/PolarisServer,MrSwiss/PolarisServer,cyberkitsune/PolarisServer
PolarisServer/Packets/Handlers/CharacterSpawn.cs
PolarisServer/Packets/Handlers/CharacterSpawn.cs
using System; using System.IO; using System.Linq; using Newtonsoft.Json; using PolarisServer.Models; using PolarisServer.Packets.PSOPackets; using PolarisServer.Object; using PolarisServer.Database; using PolarisServer.Zone; namespace PolarisServer.Packets.Handlers { [PacketHandlerAttr(0x11, 0x3E)] public class CharacterSpawn : PacketHandler { #region implemented abstract members of PacketHandler public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size) { if (context.User == null || context.Character == null) return; // Looks/Jobs if (size > 0) { var reader = new PacketReader(data); reader.BaseStream.Seek(0x38, SeekOrigin.Begin); context.Character.Looks = reader.ReadStruct<Character.LooksParam>(); context.Character.Jobs = reader.ReadStruct<Character.JobParam>(); using(var db = new PolarisEf()) db.ChangeTracker.DetectChanges(); } Map lobbyMap = ZoneManager.Instance.MapFromInstance("lobby", "lobby"); lobbyMap.SpawnClient(context, lobbyMap.GetDefaultLoaction()); // Unlock Controls context.SendPacket(new NoPayloadPacket(0x03, 0x2B)); // memset packet - Enables menus // Also holds event items and likely other stuff too var memSetPacket = File.ReadAllBytes("Resources/setMemoryPacket.bin"); context.SendPacket(0x23, 0x07, 0, memSetPacket); //context.SendPacket(File.ReadAllBytes("testbed/237.23-7.210.189.208.30.bin")); // Give a blank palette context.SendPacket(new PalettePacket()); } #endregion } }
using System; using System.IO; using System.Linq; using Newtonsoft.Json; using PolarisServer.Models; using PolarisServer.Packets.PSOPackets; using PolarisServer.Object; using PolarisServer.Database; using PolarisServer.Zone; namespace PolarisServer.Packets.Handlers { [PacketHandlerAttr(0x11, 0x3E)] public class CharacterSpawn : PacketHandler { #region implemented abstract members of PacketHandler public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size) { if (context.User == null || context.Character == null) return; // Looks/Jobs if (size > 0) { var reader = new PacketReader(data); reader.BaseStream.Seek(0x38, SeekOrigin.Begin); context.Character.Looks = reader.ReadStruct<Character.LooksParam>(); context.Character.Jobs = reader.ReadStruct<Character.JobParam>(); using(var db = new PolarisEf()) db.ChangeTracker.DetectChanges(); } Map lobbyMap = ZoneManager.Instance.MapFromInstance("lobby", "lobby"); lobbyMap.SpawnClient(context, lobbyMap.GetDefaultLoaction()); // Unlock Controls context.SendPacket(new NoPayloadPacket(0x03, 0x2B)); // memset packet - Enables menus // Also holds event items and likely other stuff too var memSetPacket = File.ReadAllBytes("Resources/setMemoryPacket.bin"); context.SendPacket(0x23, 0x07, 0, memSetPacket); context.SendPacket(File.ReadAllBytes("testbed/237.23-7.210.189.208.30.bin")); // Give a blank palette context.SendPacket(new PalettePacket()); } #endregion } }
agpl-3.0
C#
64f242d39ff564dd1b424a6966d5df61fee3aea0
add Validation Rules
hemincong/PostageStampTransactionHelper
PostageStampTransactionHelper/ValidationRules.cs
PostageStampTransactionHelper/ValidationRules.cs
using System.Globalization; using System.Windows.Controls; namespace PostageStampTransactionHelper { public class StringToIntValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { uint i; return uint.TryParse(value?.ToString(), out i) ? new ValidationResult(true, null) : new ValidationResult(false, "Please enter a valid unsigned int value."); } } public class StringToFloatValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { float f; return float.TryParse(value?.ToString(), out f) ? new ValidationResult(true, null) : new ValidationResult(false, "Please enter a valid float value."); } } public class EndsWithValidationRule : ValidationRule { public string MustEndWith { get; set; } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { var str = value as string; if (str == null) return new ValidationResult(false, "Please enter some text"); return !str.EndsWith(MustEndWith) ? new ValidationResult(false, $"Text must end with '{MustEndWith}'") : new ValidationResult(true, null); } } }
using System.Globalization; using System.Windows.Controls; namespace PostageStampTransactionHelper { public class StringToIntValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { int i; return int.TryParse(value?.ToString(), out i) ? new ValidationResult(true, null) : new ValidationResult(false, "Please enter a valid float value."); } } public class StringToFloatValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { float f; return float.TryParse(value?.ToString(), out f) ? new ValidationResult(true, null) : new ValidationResult(false, "Please enter a valid float value."); } } public class EndsWithValidationRule : ValidationRule { public string MustEndWith { get; set; } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { var str = value as string; if (str == null) return new ValidationResult(false, "Please enter some text"); return !str.EndsWith(MustEndWith) ? new ValidationResult(false, $"Text must end with '{MustEndWith}'") : new ValidationResult(true, null); } } }
apache-2.0
C#
7810e33bb8c177175e19c476cb9013e9e901ea5a
Add missing fault handling of AkkaAskRequestWaiter.
SaladLab/Akka.Interfaced,SaladbowlCreative/Akka.Interfaced,SaladbowlCreative/Akka.Interfaced,SaladLab/Akka.Interfaced
core/Akka.Interfaced/AkkaAskRequestWaiter.cs
core/Akka.Interfaced/AkkaAskRequestWaiter.cs
using System; using System.Threading.Tasks; using Akka.Actor; namespace Akka.Interfaced { internal class AkkaAskRequestWaiter : IRequestWaiter { void IRequestWaiter.SendRequest(IActorRef target, RequestMessage requestMessage) { target.Tell(requestMessage); } Task IRequestWaiter.SendRequestAndWait(IActorRef target, RequestMessage requestMessage, TimeSpan? timeout) { requestMessage.RequestId = -1; return target.Ask<ResponseMessage>(requestMessage, timeout).ContinueWith(t => { if (t.IsCanceled) throw new TaskCanceledException(); if (t.IsFaulted) throw t.Exception; var response = t.Result; if (response.Exception != null) { throw response.Exception; } }); } Task<TReturn> IRequestWaiter.SendRequestAndReceive<TReturn>( IActorRef target, RequestMessage requestMessage, TimeSpan? timeout) { requestMessage.RequestId = -1; return target.Ask<ResponseMessage>(requestMessage, timeout).ContinueWith(t => { if (t.IsCanceled) throw new TaskCanceledException(); if (t.IsFaulted) throw t.Exception; var response = t.Result; if (response.Exception != null) { throw response.Exception; } else { var getable = response.ReturnPayload; return (TReturn)getable?.Value; } }); } public static IRequestWaiter Instance = new AkkaAskRequestWaiter(); } }
using System; using System.Threading.Tasks; using Akka.Actor; namespace Akka.Interfaced { internal class AkkaAskRequestWaiter : IRequestWaiter { void IRequestWaiter.SendRequest(IActorRef target, RequestMessage requestMessage) { target.Tell(requestMessage); } Task IRequestWaiter.SendRequestAndWait(IActorRef target, RequestMessage requestMessage, TimeSpan? timeout) { requestMessage.RequestId = -1; return target.Ask<ResponseMessage>(requestMessage, timeout).ContinueWith(t => { var response = t.Result; if (response.Exception != null) { throw response.Exception; } }); } Task<TReturn> IRequestWaiter.SendRequestAndReceive<TReturn>( IActorRef target, RequestMessage requestMessage, TimeSpan? timeout) { requestMessage.RequestId = -1; return target.Ask<ResponseMessage>(requestMessage, timeout).ContinueWith(t => { var response = t.Result; if (response.Exception != null) { throw response.Exception; } else { var getable = response.ReturnPayload; return (TReturn)getable?.Value; } }); } public static IRequestWaiter Instance = new AkkaAskRequestWaiter(); } }
mit
C#
60f1bd51a6c995f902419c9f1acaeb6313b3e92d
Fix for audio URIs to prevent onerror javascript being introduced via percent encoding.
lukehoban/JabbR,lukehoban/JabbR,ajayanandgit/JabbR,e10/JabbR,borisyankov/JabbR,timgranstrom/JabbR,CrankyTRex/JabbRMirror,yadyn/JabbR,yadyn/JabbR,M-Zuber/JabbR,huanglitest/JabbRTest2,18098924759/JabbR,AAPT/jean0226case1322,fuzeman/vox,borisyankov/JabbR,18098924759/JabbR,huanglitest/JabbRTest2,huanglitest/JabbRTest2,JabbR/JabbR,meebey/JabbR,SonOfSam/JabbR,e10/JabbR,fuzeman/vox,yadyn/JabbR,meebey/JabbR,AAPT/jean0226case1322,LookLikeAPro/JabbR,CrankyTRex/JabbRMirror,LookLikeAPro/JabbR,SonOfSam/JabbR,lukehoban/JabbR,timgranstrom/JabbR,mzdv/JabbR,meebey/JabbR,LookLikeAPro/JabbR,M-Zuber/JabbR,JabbR/JabbR,mzdv/JabbR,ajayanandgit/JabbR,borisyankov/JabbR,fuzeman/vox,CrankyTRex/JabbRMirror
JabbR/ContentProviders/AudioContentProvider.cs
JabbR/ContentProviders/AudioContentProvider.cs
using System; using System.Threading.Tasks; using JabbR.ContentProviders.Core; using Microsoft.Security.Application; namespace JabbR.ContentProviders { public class AudioContentProvider : IContentProvider { public bool IsValidContent(Uri uri) { return uri.AbsolutePath.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase) || uri.AbsolutePath.EndsWith(".wav", StringComparison.OrdinalIgnoreCase) || uri.AbsolutePath.EndsWith(".ogg", StringComparison.OrdinalIgnoreCase); } public Task<ContentProviderResult> GetContent(ContentProviderHttpRequest request) { string url = request.RequestUri.ToString(); return TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(@"<audio controls=""controls"" src=""{0}"">Your browser does not support the audio tag.</audio>", Encoder.HtmlAttributeEncode(url)), Title = request.RequestUri.AbsoluteUri }); } } }
using System; using System.Threading.Tasks; using JabbR.ContentProviders.Core; namespace JabbR.ContentProviders { public class AudioContentProvider : IContentProvider { public bool IsValidContent(Uri uri) { return uri.AbsolutePath.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase) || uri.AbsolutePath.EndsWith(".wav", StringComparison.OrdinalIgnoreCase) || uri.AbsolutePath.EndsWith(".ogg", StringComparison.OrdinalIgnoreCase); } public Task<ContentProviderResult> GetContent(ContentProviderHttpRequest request) { return TaskAsyncHelper.FromResult(new ContentProviderResult() { Content = String.Format(@"<audio controls=""controls"" src=""{0}"">Your browser does not support the audio tag.</audio>", request.RequestUri), Title = request.RequestUri.AbsoluteUri.ToString() }); } } }
mit
C#
add99f2234f0babfa790187ee813d1718f763f9e
Remove User ID from device credential creation payload
jerriep/auth0.net,auth0/auth0.net,auth0/auth0.net,jerriep/auth0.net,jerriep/auth0.net
src/Auth0.ManagementApi/Models/DeviceCredentialCreateRequest.cs
src/Auth0.ManagementApi/Models/DeviceCredentialCreateRequest.cs
using System; using Auth0.Core; using Newtonsoft.Json; namespace Auth0.ManagementApi.Models { /// <summary> /// /// </summary> public class DeviceCredentialCreateRequest : DeviceCredentialBase { /// <summary> /// Gets or sets the ID of the client for which the credential will be created. /// </summary> [JsonProperty("client_id")] public string ClientId { get; set; } /// <summary> /// Gets or sets the ID of the user using the device for which the credential will be created. /// </summary> [Obsolete("This property has been removed from the Auth0 API and sending it has no effect")] [JsonIgnore] [JsonProperty("user_id")] public string UserId { get; set; } /// <summary> /// Gets or sets the value of the credentia /// </summary> [JsonProperty("value")] public string Value { get; set; } } }
using Auth0.Core; using Newtonsoft.Json; namespace Auth0.ManagementApi.Models { /// <summary> /// /// </summary> public class DeviceCredentialCreateRequest : DeviceCredentialBase { /// <summary> /// Gets or sets the ID of the client for which the credential will be created. /// </summary> [JsonProperty("client_id")] public string ClientId { get; set; } /// <summary> /// Gets or sets the ID of the user using the device for which the credential will be created. /// </summary> [JsonProperty("user_id")] public string UserId { get; set; } /// <summary> /// Gets or sets the value of the credentia /// </summary> [JsonProperty("value")] public string Value { get; set; } } }
mit
C#
5138679dba78ce2807d606fd3ab1babea904785b
Fix WinRT build breaks (#4398)
gregkalapos/corert,shrah/corert,shrah/corert,shrah/corert,shrah/corert,gregkalapos/corert,gregkalapos/corert,gregkalapos/corert
src/System.Private.CoreLib/shared/System/IO/FileStream.WinRT.cs
src/System.Private.CoreLib/shared/System/IO/FileStream.WinRT.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; namespace System.IO { public partial class FileStream : Stream { private unsafe SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share); int access = ((_access & FileAccess.Read) == FileAccess.Read ? GENERIC_READ : 0) | ((_access & FileAccess.Write) == FileAccess.Write ? GENERIC_WRITE : 0); // Our Inheritable bit was stolen from Windows, but should be set in // the security attributes class. Don't leave this bit set. share &= ~FileShare.Inheritable; // Must use a valid Win32 constant here... if (mode == FileMode.Append) mode = FileMode.OpenOrCreate; Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS parameters = new Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS(); parameters.dwSize = (uint)sizeof(Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS); parameters.dwFileFlags = (uint)options; parameters.lpSecurityAttributes = &secAttrs; using (DisableMediaInsertionPrompt.Create()) { return ValidateFileHandle(Interop.Kernel32.CreateFile2( lpFileName: _path, dwDesiredAccess: access, dwShareMode: share, dwCreationDisposition: mode, pCreateExParams: ref parameters)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; namespace System.IO { public partial class FileStream : Stream { #if !CORECLR private unsafe SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options) { return CreateFile2OpenHandle(mode, share, options); } #endif private unsafe SafeFileHandle CreateFile2OpenHandle(FileMode mode, FileShare share, FileOptions options) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share); int access = ((_access & FileAccess.Read) == FileAccess.Read ? GENERIC_READ : 0) | ((_access & FileAccess.Write) == FileAccess.Write ? GENERIC_WRITE : 0); // Our Inheritable bit was stolen from Windows, but should be set in // the security attributes class. Don't leave this bit set. share &= ~FileShare.Inheritable; // Must use a valid Win32 constant here... if (mode == FileMode.Append) mode = FileMode.OpenOrCreate; Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS parameters = new Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS(); parameters.dwSize = (uint)sizeof(Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS); parameters.dwFileFlags = (uint)options; parameters.lpSecurityAttributes = &secAttrs; using (DisableMediaInsertionPrompt.Create()) { return ValidateFileHandle(Interop.FileApiInterop.CreateFile2( lpFileName: _path, dwDesiredAccess: access, dwShareMode: share, dwCreationDisposition: mode, pCreateExParams: ref parameters)); } } } }
mit
C#
0afa356f504489717d061941f8b9b43e6f121d67
Update tile template.
betrakiss/Tramline-5,betrakiss/Tramline-5
src/TramlineFive/BackgroundTasks/FavouriteStopBackgroundTask.cs
src/TramlineFive/BackgroundTasks/FavouriteStopBackgroundTask.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TramlineFive.Common; using TramlineFive.Common.Converters; using TramlineFive.Common.Models; using Windows.ApplicationModel.Background; using Windows.Data.Xml.Dom; using Windows.UI.Notifications; namespace BackgroundTasks { public sealed class FavouriteStopBackgroundTask : IBackgroundTask { public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); List<Arrival> arrivals = await SumcManager.GetByStopAsync("2193", null); UpdateTile(arrivals); deferral.Complete(); } private void UpdateTile(List<Arrival> arrivals) { var updater = TileUpdateManager.CreateTileUpdaterForApplication(); updater.EnableNotificationQueue(true); updater.Clear(); XmlDocument xml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image); ((XmlElement)xml.GetElementsByTagName("image")[0]).SetAttribute("src", "ms-appx:///Assets/Store/Wide310x150Logo.scale-400.png"); int itemCount = 1; foreach (Arrival arrival in arrivals) { XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text03); string title = arrivals.First().StopTitle; tileXml.GetElementsByTagName("text")[0].InnerText = SumcParser.ParseStopTitle(title) + "\n" + String.Join(", ", arrival.Timings); //tileXml.GetElementsByTagName("text")[1].InnerText = String.Join(", ", arrival.Timings); TileNotification timings = new TileNotification(tileXml); timings.ExpirationTime = DateTime.Now.AddHours(1); updater.Update(timings); if (itemCount++ > 5) break; } TileNotification defaultTile = new TileNotification(xml); defaultTile.ExpirationTime = DateTime.Now.AddHours(1); updater.Update(defaultTile); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TramlineFive.Common; using TramlineFive.Common.Converters; using TramlineFive.Common.Models; using Windows.ApplicationModel.Background; using Windows.Data.Xml.Dom; using Windows.UI.Notifications; namespace BackgroundTasks { public sealed class FavouriteStopBackgroundTask : IBackgroundTask { public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); List<Arrival> arrivals = await SumcManager.GetByStopAsync("2193", null); UpdateTile(arrivals); deferral.Complete(); } private void UpdateTile(List<Arrival> arrivals) { var updater = TileUpdateManager.CreateTileUpdaterForApplication(); updater.EnableNotificationQueue(true); updater.Clear(); XmlDocument xml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image); ((XmlElement)xml.GetElementsByTagName("image")[0]).SetAttribute("src", "ms-appx:///Assets/Store/Wide310x150Logo.scale-400.png"); int itemCount = 1; foreach (Arrival arrival in arrivals) { XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text01); string title = arrivals.First().StopTitle; tileXml.GetElementsByTagName("text")[0].InnerText = SumcParser.ParseStopTitle(title); tileXml.GetElementsByTagName("text")[1].InnerText = String.Join(", ", arrival.Timings); TileNotification timings = new TileNotification(tileXml); timings.ExpirationTime = DateTime.Now.AddHours(1); updater.Update(timings); if (itemCount++ > 5) break; } TileNotification defaultTile = new TileNotification(xml); defaultTile.ExpirationTime = DateTime.Now.AddHours(1); updater.Update(defaultTile); } } }
apache-2.0
C#
48aeda49bc1808813f5d5c3d0a6212c46207eed9
order history item partial view updated
mpenchev86/ASP.NET-MVC-FinalProject,mpenchev86/ASP.NET-MVC-FinalProject,mpenchev86/JustOrderIt,mpenchev86/ASP.NET-MVC-FinalProject,mpenchev86/JustOrderIt,mpenchev86/JustOrderIt
Source/Web/JustOrderIt.Web/Areas/Public/Views/Orders/DisplayTemplates/OrderItems.cshtml
Source/Web/JustOrderIt.Web/Areas/Public/Views/Orders/DisplayTemplates/OrderItems.cshtml
@using Microsoft.AspNet.Identity @using JustOrderIt.Web.Areas.Public.ViewModels.Orders @using JustOrderIt.Web.Areas.Public.ViewModels.Votes @model List<OrderItemForUserProfile> <div class="row cart-labels"> <div class="col-md-7"><label><span>Product</span></label></div> <div class="col-md-2"><label><span>Unit Price</span></label></div> <div class="col-md-1"><label><span>Quantity</span></label></div> <div class="col-md-2"><label><span>Rate this item</span></label></div> </div> @for (int i = 0; i < Model.Count; i++) { <div class="row order-item"> <div class="col-md-2"> <div class="row"> <img id="order-product-image" src="@Url.ProductPicture(Model[i].Product.ImageUrlPath, Model[i].Product.ImageFileExtension, ImageSizes.Small)" /> </div> @Html.ActionLink(" ", "Index", "Products", new { id = Model[i].Product.EncodedId }, new { @class = "order-product-link" }) </div> <div class="col-md-5 orderitem-product"> @Html.ActionLink(Model[i].Product.Title, "Index", "Products", new { id = Model[i].Product.EncodedId }, null) </div> <div class="col-md-2 orderitem-unitprice"> @Html.DisplayFor(m => Model[i].Product.UnitPrice) </div> <div class="col-md-1 orderitem-quantity"> @Html.DisplayFor(m => Model[i].ProductQuantity) </div> <div class="col-md-2 orderitem-vote"> @Html.Partial( "VoteForOrderItem", new VoteEditorModel { Id = i, ProductId = Model[i].ProductId, UserId = this.User.Identity.GetUserId(), VoteValue = Model[i].Product.Rating }) </div> </div> <br /> }
@using Microsoft.AspNet.Identity @using JustOrderIt.Web.Areas.Public.ViewModels.Orders @using JustOrderIt.Web.Areas.Public.ViewModels.Votes @model List<OrderItemForUserProfile> <div class="row cart-labels"> <div class="col-md-8"><label><span>Product</span></label></div> <div class="col-md-2"><label><span>Unit Price</span></label></div> <div class="col-md-1"><label><span>Quantity</span></label></div> </div> @for (int i = 0; i < Model.Count; i++) { <div class="row order-item"> <div class="col-md-2"> <div class="row"> <img id="order-product-image" src="@Url.ProductPicture(Model[i].Product.ImageUrlPath, Model[i].Product.ImageFileExtension, ImageSizes.Small)" /> </div> @Html.ActionLink(" ", "Index", "Products", new { id = Model[i].Product.EncodedId }, new { @class = "order-product-link" }) </div> <div class="col-md-6 orderitem-product"> @Html.ActionLink(Model[i].Product.Title, "Index", "Products", new { id = Model[i].Product.EncodedId }, null) </div> <div class="col-md-2 orderitem-unitprice"> @Html.DisplayFor(m => Model[i].Product.UnitPrice) </div> <div class="col-md-1 orderitem-quantity"> @Html.DisplayFor(m => Model[i].ProductQuantity) </div> <div class="col-md-1 orderitem-vote"> @Html.Partial( "VoteForOrderItem", new VoteEditorModel { Id = i, ProductId = Model[i].ProductId, UserId = this.User.Identity.GetUserId(), VoteValue = Model[i].Product.Rating }) </div> </div> <br /> }
mit
C#
e385dedd5f75e1b0d91753ff580b1964f4ffad14
Remove try-catch blocks and handle the null case.
PackSciences/LiveSplit,Glurmo/LiveSplit,kugelrund/LiveSplit,stoye/LiveSplit,zoton2/LiveSplit,zoton2/LiveSplit,ROMaster2/LiveSplit,Dalet/LiveSplit,Fluzzarn/LiveSplit,Jiiks/LiveSplit,stoye/LiveSplit,Fluzzarn/LiveSplit,LiveSplit/LiveSplit,PackSciences/LiveSplit,Fluzzarn/LiveSplit,chloe747/LiveSplit,kugelrund/LiveSplit,chloe747/LiveSplit,Jiiks/LiveSplit,zoton2/LiveSplit,PackSciences/LiveSplit,stoye/LiveSplit,kugelrund/LiveSplit,Dalet/LiveSplit,Jiiks/LiveSplit,chloe747/LiveSplit,Dalet/LiveSplit,ROMaster2/LiveSplit,ROMaster2/LiveSplit,Glurmo/LiveSplit,Glurmo/LiveSplit
LiveSplit/LiveSplit.Core/Web/DynamicXMLNode.cs
LiveSplit/LiveSplit.Core/Web/DynamicXMLNode.cs
using System.Dynamic; using System.Xml; namespace LiveSplit.Web { public static class XMLExtensions { public static dynamic ToDynamic(this XmlElement element) { return new DynamicXMLElement(element); } } internal class DynamicXMLAttributesCollection : DynamicObject { private XmlAttributeCollection Attributes { get; set; } public DynamicXMLAttributesCollection(XmlAttributeCollection attributes) { Attributes = attributes; } public override string ToString() { return Attributes.ToString(); } public override bool TryGetMember(GetMemberBinder binder, out object result) { var attribute = Attributes[binder.Name]; // Attribute is not present. if (attribute == null) { result = null; return false; } result = attribute; return true; } } internal class DynamicXMLElement : DynamicObject { private XmlElement Element { get; set; } public DynamicXMLElement(XmlElement element) { Element = element; } public override string ToString() { return Element.ToString(); } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (binder.Name == "Attributes") { result = new DynamicXMLAttributesCollection(Element.Attributes); return true; } var memberElement = Element[binder.Name]; // Child element is not present if (memberElement == null) { result = null; return false; } if (memberElement.HasChildNodes) result = new DynamicXMLElement(memberElement); else result = memberElement.InnerText; return true; } } }
using System.Dynamic; using System.Xml; namespace LiveSplit.Web { public static class XMLExtensions { public static dynamic ToDynamic(this XmlElement element) { return new DynamicXMLElement(element); } } internal class DynamicXMLAttributesCollection : DynamicObject { private XmlAttributeCollection Attributes { get; set; } public DynamicXMLAttributesCollection(XmlAttributeCollection attributes) { Attributes = attributes; } public override string ToString() { return Attributes.ToString(); } public override bool TryGetMember(GetMemberBinder binder, out object result) { try { result = Attributes[binder.Name]; return true; } catch { } result = null; return false; } } internal class DynamicXMLElement : DynamicObject { private XmlElement Element { get; set; } public DynamicXMLElement(XmlElement element) { Element = element; } public override string ToString() { return Element.ToString(); } public override bool TryGetMember(GetMemberBinder binder, out object result) { try { if (binder.Name == "Attributes") { result = new DynamicXMLAttributesCollection(Element.Attributes); return true; } var memberElement = Element[binder.Name]; if (memberElement.HasChildNodes) { result = new DynamicXMLElement(memberElement); return true; } else { result = memberElement.InnerText; return true; } } catch { } result = null; return false; } } }
mit
C#
ebb7bba4fe1d5570b659c89cbadee10922a2f736
Fix naming
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer
LmpClient/Harmony/VesselLabels_ProcessLabel.cs
LmpClient/Harmony/VesselLabels_ProcessLabel.cs
using Harmony; using LmpClient.Events; // ReSharper disable All namespace LmpClient.Harmony { /// <summary> /// This harmony patch is intended to trigger an event when drawing a label /// </summary> [HarmonyPatch(typeof(VesselLabels))] [HarmonyPatch("ProcessLabel")] public class VesselLabels_ProcessLabel { [HarmonyPostfix] private static void PostfixProcessLabel(BaseLabel label) { if (label.gameObject.activeSelf) { LabelEvent.onLabelProcessed.Fire(label); } } } }
using Harmony; using LmpClient.Events; // ReSharper disable All namespace LmpClient.Harmony { /// <summary> /// This harmony patch is intended to trigger an event when drawing a label /// </summary> [HarmonyPatch(typeof(VesselLabels))] [HarmonyPatch("ProcessLabel")] public class VesselLabels_ProcessLabel { [HarmonyPostfix] private static void PostProcessLabel(BaseLabel label) { if (label.gameObject.activeSelf) { LabelEvent.onLabelProcessed.Fire(label); } } } }
mit
C#
d0e577cd8f1cb3fecd883c892e5d318c8593a92f
Increase version number
xpressive-websolutions/Xpressive.Home.ProofOfConcept,xpressive-websolutions/Xpressive.Home.ProofOfConcept,xpressive-websolutions/Xpressive.Home,xpressive-websolutions/Xpressive.Home,xpressive-websolutions/Xpressive.Home,xpressive-websolutions/Xpressive.Home.ProofOfConcept
Xpressive.Home/Properties/AssemblyInfo.shared.cs
Xpressive.Home/Properties/AssemblyInfo.shared.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Cake. // </auto-generated> //------------------------------------------------------------------------------ using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Xpressive Websolutions")] [assembly: AssemblyProduct("Xpressive.Home")] [assembly: AssemblyVersion("1.0.0.19318")] [assembly: AssemblyFileVersion("1.0.0.19318")] [assembly: AssemblyInformationalVersion("1.0.0-beta.8")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyConfiguration("")] [assembly: ComVisible(false)]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Cake. // </auto-generated> //------------------------------------------------------------------------------ using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Xpressive Websolutions")] [assembly: AssemblyProduct("Xpressive.Home")] [assembly: AssemblyVersion("1.0.0.19152")] [assembly: AssemblyFileVersion("1.0.0.19152")] [assembly: AssemblyInformationalVersion("1.0.0-beta.8")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyConfiguration("")] [assembly: ComVisible(false)]
mit
C#
3c8c21e6279afa6608a0199513c1cabf93da4f69
Make the custom ActionFilter internal
serilog-web/classic-webapi
src/SerilogWeb.Classic.WebApi/Classic/WebApi/StoreWebApInfoInHttpContextActionFilter.cs
src/SerilogWeb.Classic.WebApi/Classic/WebApi/StoreWebApInfoInHttpContextActionFilter.cs
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace SerilogWeb.Classic.WebApi { internal class StoreWebApInfoInHttpContextActionFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { StoreWebApInfoInHttpContext(actionContext); base.OnActionExecuting(actionContext); } public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { StoreWebApInfoInHttpContext(actionContext); return base.OnActionExecutingAsync(actionContext, cancellationToken); } private static void StoreWebApInfoInHttpContext(HttpActionContext actionContext) { var actionDescriptor = actionContext.ActionDescriptor; var routeData = actionContext.RequestContext.RouteData; var actionName = actionDescriptor.ActionName; var controllerName = actionDescriptor.ControllerDescriptor.ControllerName; var routeTemplate = routeData.Route.RouteTemplate; var routeDataDictionary = new Dictionary<string, object>( routeData.Values); var contextualInfo = new Dictionary<WebApiRequestInfoKey, object> { [WebApiRequestInfoKey.RouteUrlTemplate] = routeTemplate, [WebApiRequestInfoKey.RouteData] = routeDataDictionary, [WebApiRequestInfoKey.ActionName] = actionName, [WebApiRequestInfoKey.ControllerName] = controllerName }; var currentHttpContext = HttpContext.Current; if (currentHttpContext != null) { currentHttpContext.Items[Constants.WebApiContextInfoKey] = contextualInfo; } } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace SerilogWeb.Classic.WebApi { public class StoreWebApInfoInHttpContextActionFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { StoreWebApInfoInHttpContext(actionContext); base.OnActionExecuting(actionContext); } public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { StoreWebApInfoInHttpContext(actionContext); return base.OnActionExecutingAsync(actionContext, cancellationToken); } private static void StoreWebApInfoInHttpContext(HttpActionContext actionContext) { var actionDescriptor = actionContext.ActionDescriptor; var routeData = actionContext.RequestContext.RouteData; var actionName = actionDescriptor.ActionName; var controllerName = actionDescriptor.ControllerDescriptor.ControllerName; var routeTemplate = routeData.Route.RouteTemplate; var routeDataDictionary = new Dictionary<string, object>( routeData.Values); var contextualInfo = new Dictionary<WebApiRequestInfoKey, object> { [WebApiRequestInfoKey.RouteUrlTemplate] = routeTemplate, [WebApiRequestInfoKey.RouteData] = routeDataDictionary, [WebApiRequestInfoKey.ActionName] = actionName, [WebApiRequestInfoKey.ControllerName] = controllerName }; var currentHttpContext = HttpContext.Current; if (currentHttpContext != null) { currentHttpContext.Items[Constants.WebApiContextInfoKey] = contextualInfo; } } } }
apache-2.0
C#
a7f0ea9033e720c29718efc2531f9a270ab39d82
Fix error
12joan/hangman
row.cs
row.cs
using System; using System.Collections.Generic; namespace Hangman { public class Row { public Cell[] Cells; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; return String.Join("\n", Lines()); } private string[] Lines() { var lines = new List<string>(); for (var i = 0; i < MaxCellDepth(); i++) { var line = LineAtIndex(i); lines.Add(String.Join("", line)); } return lines.ToArray(); } private string LineAtIndex(int index) { var line = new List<string>(); int usedSpace = 0; foreach (var cell in Cells) { var part = cell.LineAtIndex(index); line.Add(part); usedSpace += part.Length; } return line; } private int MaxCellDepth() { int max = 0; foreach (var cell in Cells) { max = Math.Max(max, cell.Depth()); } return max; } } }
using System; using System.Collections.Generic; namespace Hangman { public class Row { public Cell[] Cells; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; return String.Join("\n", Lines()); } private string[] Lines() { var lines = new List<string>(); for (var i = 0; i < MaxCellDepth(); i++) { var line = LineAtIndex(i); lines.Add(String.Join("", line)); } return lines.ToArray(); } private string LineAtIndex(int index) { var line = new List<string>(); foreach (var cell in Cells) { var part = cell.LineAtIndex(index); line.Add(part); } } private int MaxCellDepth() { int max = 0; foreach (var cell in Cells) { max = Math.Max(max, cell.Depth()); } return max; } } }
unlicense
C#
26ae97a7f418306e6dbf8c698e245bd8861de70a
test to claims
ramzzzay/PhoneBook,ramzzzay/PhoneBook
PhoneBook.Core/Controllers/ValuesController.cs
PhoneBook.Core/Controllers/ValuesController.cs
using System.Collections.Generic; using System.Web.Http; namespace PhoneBook.Core.Controllers { public class ValuesController : ApiController { // GET api/values [Authorize(Roles = "user")] public IEnumerable<string> Get() { return new[] {"value1", "value2"}; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody] string value) { } // PUT api/values/5 public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace PhoneBook.Core.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } } }
apache-2.0
C#
1e5b400499177cbf5025b9e3006549b4ed172829
Add option to control whether player can use twisting
NamefulTeam/PortoGameJam2016
PortoGameJam2016/Assets/Scripts/GameManager.cs
PortoGameJam2016/Assets/Scripts/GameManager.cs
using UnityEngine; using System.Collections; public class GameManager : MonoBehaviour { public static GameManager Instance; public Mode CurrentMode = Mode.TopDown; public bool AllowTwisting = true; CameraController cameraController; void Awake() { if (Instance == null) { Instance = this; } else if (Instance != this) { Destroy(Instance.gameObject); Instance = this; } cameraController = GetComponent<CameraController>(); if (CurrentMode == Mode.TopDown) { cameraController.SwitchToTopDown(); } else { cameraController.SwitchToSideScroller(); } } void Update() { if (Input.GetButtonDown("Twist") && AllowTwisting) { if (CurrentMode == Mode.TopDown) { cameraController.RotateToSideScroller(); GetComponent<TransitionManager>().Twist(Mode.SideScroller); } else if(CurrentMode == Mode.SideScroller) { GetComponent<TransitionManager>().Twist(Mode.TopDown); cameraController.RotateToTopDown(); } } } } public enum Mode { SideScroller, TopDown, TransitioningToSideScroller, TransitioningToTopDown }
using UnityEngine; using System.Collections; public class GameManager : MonoBehaviour { public static GameManager Instance; public Mode CurrentMode = Mode.TopDown; CameraController cameraController; void Awake() { if (Instance == null) { Instance = this; } else if (Instance != this) { Destroy(Instance.gameObject); Instance = this; } cameraController = GetComponent<CameraController>(); if (CurrentMode == Mode.TopDown) { cameraController.SwitchToTopDown(); } else { cameraController.SwitchToSideScroller(); } } void Update() { if (Input.GetButtonDown("Twist")) { if (CurrentMode == Mode.TopDown) { cameraController.RotateToSideScroller(); GetComponent<TransitionManager>().Twist(Mode.SideScroller); } else if(CurrentMode == Mode.SideScroller) { GetComponent<TransitionManager>().Twist(Mode.TopDown); cameraController.RotateToTopDown(); } } } } public enum Mode { SideScroller, TopDown, TransitioningToSideScroller, TransitioningToTopDown }
mit
C#
cae6e02ceb8b427e03e268e17195ac2f9d441fc4
Fix migration to handle identical aliases for different group names and write error to log
arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS
src/Umbraco.Core/Migrations/Upgrade/V_8_16_0/AddPropertyTypeGroupColumns.cs
src/Umbraco.Core/Migrations/Upgrade/V_8_16_0/AddPropertyTypeGroupColumns.cs
using System.Linq; using Umbraco.Core.Logging; using Umbraco.Core.Persistence.Dtos; namespace Umbraco.Core.Migrations.Upgrade.V_8_16_0 { public class AddPropertyTypeGroupColumns : MigrationBase { public AddPropertyTypeGroupColumns(IMigrationContext context) : base(context) { } public override void Migrate() { AddColumn<PropertyTypeGroupDto>("type"); AddColumn<PropertyTypeGroupDto>("alias", out var sqls); var dtos = Database.Fetch<PropertyTypeGroupDto>(); foreach (var dtosPerAlias in dtos.GroupBy(x => x.Text.ToSafeAlias(true))) { var dtosPerAliasAndText = dtosPerAlias.GroupBy(x => x.Text); var numberSuffix = 1; foreach (var dtosPerText in dtosPerAliasAndText) { foreach (var dto in dtosPerText) { dto.Alias = dtosPerAlias.Key; if (numberSuffix > 1) { // More than 1 name found for the alias, so add a suffix dto.Alias += numberSuffix; } Database.Update(dto, x => new { x.Alias }); } numberSuffix++; } if (numberSuffix > 2) { Logger.Error<AddPropertyTypeGroupColumns>("Detected the same alias {Alias} for different property group names {Names}, the migration added suffixes, but this might break backwards compatibility.", dtosPerAlias.Key, dtosPerAliasAndText.Select(x => x.Key)); } } foreach (var sql in sqls) Database.Execute(sql); } } }
using System.Linq; using Umbraco.Core.Persistence.Dtos; namespace Umbraco.Core.Migrations.Upgrade.V_8_16_0 { public class AddPropertyTypeGroupColumns : MigrationBase { public AddPropertyTypeGroupColumns(IMigrationContext context) : base(context) { } public override void Migrate() { AddColumn<PropertyTypeGroupDto>("type"); AddColumn<PropertyTypeGroupDto>("alias", out var sqls); var dtos = Database.Fetch<PropertyTypeGroupDto>(); foreach (var dto in dtos) { // Generate alias from current name dto.Alias = dto.Text.ToSafeAlias(true); Database.Update(dto, x => new { x.Alias }); } foreach (var sql in sqls) Database.Execute(sql); } } }
mit
C#
bc3979fc91ee37f563337e478d74bed34a3bebd4
Change page size in TagController-list
SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery
AstroPhotoGallery/AstroPhotoGallery/Controllers/TagController.cs
AstroPhotoGallery/AstroPhotoGallery/Controllers/TagController.cs
using AstroPhotoGallery.Extensions; using AstroPhotoGallery.Models; using PagedList; using System.Data.Entity; using System.Linq; using System.Web.Mvc; namespace AstroPhotoGallery.Controllers { public class TagController : Controller { // // GET: Tag/List/id public ActionResult List(int? id ,int? page) { if (id == null) { this.AddNotification("No tag ID provided.", NotificationType.ERROR); return RedirectToAction("Index", "Home"); } using (var db = new GalleryDbContext()) { //Get pictures from db var pictures = db.Tags .Include(t => t.Pictures.Select(p => p.Tags)) .Include(t => t.Pictures.Select(p => p.PicUploader)) .FirstOrDefault(t => t.Id == id) .Pictures .ToList(); //Return the view int pageSize = 4; int pageNumber = (page ?? 1); return View(pictures.ToPagedList(pageNumber, pageSize)); } } } }
using AstroPhotoGallery.Extensions; using AstroPhotoGallery.Models; using PagedList; using System.Data.Entity; using System.Linq; using System.Web.Mvc; namespace AstroPhotoGallery.Controllers { public class TagController : Controller { // // GET: Tag/List/id public ActionResult List(int? id ,int? page) { if (id == null) { this.AddNotification("No tag ID provided.", NotificationType.ERROR); return RedirectToAction("Index", "Home"); } using (var db = new GalleryDbContext()) { //Get pictures from db var pictures = db.Tags .Include(t => t.Pictures.Select(p => p.Tags)) .Include(t => t.Pictures.Select(p => p.PicUploader)) .FirstOrDefault(t => t.Id == id) .Pictures .ToList(); //Return the view int pageSize = 3; int pageNumber = (page ?? 1); return View(pictures.ToPagedList(pageNumber, pageSize)); } } } }
mit
C#
664c3c1d549e5e3b606b8f318f29e3425ab28ce3
remove unused stuff in brawlerbar
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/Controls/ClassBars/BrawlerBar.xaml.cs
TCC.Core/Controls/ClassBars/BrawlerBar.xaml.cs
using System; using System.ComponentModel; using System.Windows; using System.Windows.Media.Animation; using TCC.ViewModels; namespace TCC.Controls.ClassBars { /// <summary> /// Logica di interazione per BrawlerBar.xaml /// </summary> public partial class BrawlerBar { public BrawlerBar() { InitializeComponent(); } private BrawlerBarManager _dc; private DoubleAnimation _an; private void BrawlerBar_OnLoaded(object sender, RoutedEventArgs e) { _dc = (BrawlerBarManager)DataContext; _an = new DoubleAnimation(_dc.StaminaTracker.Factor * 359.99 + 40, TimeSpan.FromMilliseconds(150)); _dc.StaminaTracker.PropertyChanged += ST_PropertyChanged; } private void ST_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName != nameof(_dc.StaminaTracker.Factor)) return; _an.To = _dc.StaminaTracker.Factor*(359.99 - 80) + 40; MainReArc.BeginAnimation(Arc.EndAngleProperty,_an); } } }
using System; using System.ComponentModel; using System.Windows; using System.Windows.Media.Animation; using TCC.Data; using TCC.ViewModels; namespace TCC.Controls.ClassBars { /// <summary> /// Logica di interazione per BrawlerBar.xaml /// </summary> public partial class BrawlerBar { public BrawlerBar() { InitializeComponent(); } private BrawlerBarManager _dc; private DoubleAnimation _an; private DoubleAnimation _counter; private bool _counterAnimating; private void BrawlerBar_OnLoaded(object sender, RoutedEventArgs e) { _dc = (BrawlerBarManager)DataContext; _an = new DoubleAnimation(_dc.StaminaTracker.Factor * 359.99 + 40, TimeSpan.FromMilliseconds(150)); _dc.StaminaTracker.PropertyChanged += ST_PropertyChanged; _dc.Counter.PropertyChanged += AnimateCounter; _counter = new DoubleAnimation(1, TimeSpan.FromMilliseconds(200)) { EasingFunction = new QuadraticEase() }; _counter.Completed += (_, __) => _counterAnimating = false; } private void ST_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName != nameof(_dc.StaminaTracker.Factor)) return; _an.To = _dc.StaminaTracker.Factor*(359.99 - 80) + 40; MainReArc.BeginAnimation(Arc.EndAngleProperty,_an); //if (_dc.StaminaTracker.Factor == 1) //{ // MainReArc.Stroke = Brushes.Orange; // ((DropShadowEffect)MainReArcGrid.Effect).Opacity = 1; // ((DropShadowEffect)BgImage.Effect).Opacity = 1; //} //else //{ // MainReArc.Stroke = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0x99, 0x33)); // ((DropShadowEffect)MainReArcGrid.Effect).Opacity = 0; // ((DropShadowEffect)BgImage.Effect).Opacity = 0; //} } private void AnimateCounter(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(StatTracker.Factor)) { //_counter.To = _dc.Counter.Factor * 359.9; _counterAnimating = true; //CounterArc.BeginAnimation(Arc.EndAngleProperty, _counter); } } } }
mit
C#
b2931f22c3004df536c4d4738d2452e5b3a78a38
Remove Drawn callback and preserve selected color
Gankov/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,sillsdev/gtk-sharp,antoniusriha/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,antoniusriha/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp
sample/GtkDemo/DemoColorSelection.cs
sample/GtkDemo/DemoColorSelection.cs
/* Color Selector * * GtkColorSelection lets the user choose a color. GtkColorSelectionDialog is * a prebuilt dialog containing a GtkColorSelection. * */ using System; using Gdk; using Gtk; namespace GtkDemo { [Demo ("Color Selection", "DemoColorSelection.cs")] public class DemoColorSelection : Gtk.Window { private Gdk.RGBA color; private Gtk.DrawingArea drawingArea; public DemoColorSelection () : base ("Color Selection") { BorderWidth = 8; VBox vbox = new VBox (false,8); vbox.BorderWidth = 8; Add (vbox); // Create the color swatch area Frame frame = new Frame (); frame.ShadowType = ShadowType.In; vbox.PackStart (frame, true, true, 0); drawingArea = new DrawingArea (); // set a minimum size drawingArea.SetSizeRequest (200,200); // set the color color.Red = 0; color.Green = 0; color.Blue = 1; color.Alpha = 1; drawingArea.OverrideBackgroundColor (StateFlags.Normal, color); frame.Add (drawingArea); Alignment alignment = new Alignment (1.0f, 0.5f, 0.0f, 0.0f); Button button = new Button ("_Change the above color"); button.Clicked += new EventHandler (ChangeColorCallback); alignment.Add (button); vbox.PackStart (alignment, false, false, 0); ShowAll (); } protected override bool OnDeleteEvent (Gdk.Event evt) { Destroy (); return true; } private void ChangeColorCallback (object o, EventArgs args) { using (ColorSelectionDialog colorSelectionDialog = new ColorSelectionDialog ("Changing color")) { colorSelectionDialog.TransientFor = this; colorSelectionDialog.ColorSelection.SetPreviousRgba (color); colorSelectionDialog.ColorSelection.CurrentRgba = color; colorSelectionDialog.ColorSelection.HasPalette = true; if (colorSelectionDialog.Run () == (int) ResponseType.Ok) { color = colorSelectionDialog.ColorSelection.CurrentRgba; drawingArea.OverrideBackgroundColor (StateFlags.Normal, color); } colorSelectionDialog.Hide (); } } } }
/* Color Selector * * GtkColorSelection lets the user choose a color. GtkColorSelectionDialog is * a prebuilt dialog containing a GtkColorSelection. * */ using System; using Gdk; using Gtk; namespace GtkDemo { [Demo ("Color Selection", "DemoColorSelection.cs")] public class DemoColorSelection : Gtk.Window { private Gdk.RGBA color; private Gtk.DrawingArea drawingArea; public DemoColorSelection () : base ("Color Selection") { BorderWidth = 8; VBox vbox = new VBox (false,8); vbox.BorderWidth = 8; Add (vbox); // Create the color swatch area Frame frame = new Frame (); frame.ShadowType = ShadowType.In; vbox.PackStart (frame, true, true, 0); drawingArea = new DrawingArea (); drawingArea.Drawn += new DrawnHandler (DrawnCallback); // set a minimum size drawingArea.SetSizeRequest (200,200); // set the color color.Red = 0; color.Green = 0; color.Blue = 1; color.Alpha = 1; drawingArea.OverrideBackgroundColor (StateFlags.Normal, color); frame.Add (drawingArea); Alignment alignment = new Alignment (1.0f, 0.5f, 0.0f, 0.0f); Button button = new Button ("_Change the above color"); button.Clicked += new EventHandler (ChangeColorCallback); alignment.Add (button); vbox.PackStart (alignment, false, false, 0); ShowAll (); } protected override bool OnDeleteEvent (Gdk.Event evt) { Destroy (); return true; } // Drawn callback for the drawing area private void DrawnCallback (object o, DrawnArgs args) { Cairo.Context cr = args.Cr; Gdk.RGBA rgba = StyleContext.GetBackgroundColor (StateFlags.Normal); cr.SetSourceRGBA (rgba.Red, rgba.Green, rgba.Blue, rgba.Alpha); cr.Paint (); args.RetVal = true; } private void ChangeColorCallback (object o, EventArgs args) { using (ColorSelectionDialog colorSelectionDialog = new ColorSelectionDialog ("Changing color")) { colorSelectionDialog.TransientFor = this; colorSelectionDialog.ColorSelection.SetPreviousRgba (color); colorSelectionDialog.ColorSelection.CurrentRgba = color; colorSelectionDialog.ColorSelection.HasPalette = true; if (colorSelectionDialog.Run () == (int) ResponseType.Ok) { Gdk.RGBA selected = colorSelectionDialog.ColorSelection.CurrentRgba; drawingArea.OverrideBackgroundColor (StateFlags.Normal, selected); } colorSelectionDialog.Hide (); } } } }
lgpl-2.1
C#
88acd4b4e27addd3e2290c1097ab9ea2e7a81767
Fix build with XamMac older than 3.4
TheBrainTech/xwt,mono/xwt,hwthomas/xwt,antmicro/xwt,cra0zy/xwt,hamekoz/xwt,lytico/xwt
Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs
Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs
// // NSApplicationInitializer.cs // // Author: // Lluis Sanchez Gual <lluis@xamarin.com> // // Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using AppKit; namespace Xwt.Mac { static class NSApplicationInitializer { public static void Initialize () { var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized"); if (System.Threading.Thread.GetData (ds) == null) { System.Threading.Thread.SetData (ds, true); // IgnoreMissingAssembliesDuringRegistration is only avalilable in Xamarin.Mac 3.4+ // Use reflection to not break builds with older Xamarin.Mac var ignoreMissingAssemblies = typeof (NSApplication).GetField ("IgnoreMissingAssembliesDuringRegistration", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); ignoreMissingAssemblies?.SetValue (null, true); NSApplication.Init (); } } } }
// // NSApplicationInitializer.cs // // Author: // Lluis Sanchez Gual <lluis@xamarin.com> // // Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using AppKit; namespace Xwt.Mac { static class NSApplicationInitializer { public static void Initialize () { var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized"); if (System.Threading.Thread.GetData (ds) == null) { System.Threading.Thread.SetData (ds, true); NSApplication.IgnoreMissingAssembliesDuringRegistration = true; NSApplication.Init (); } } } }
mit
C#
754a013d622483070d3a61bbd4a49e43efcf5b5e
change namespace of ActionDelegate.cs
fmarrabal/Caliburn.Micro,dvdvorle/Caliburn.Micro,mwpowellhtx/Caliburn.Micro,vgrigoriu/Caliburn.Micro,bitbonk/Caliburn.Micro,dvdvorle/Caliburn.Micro,ryanJohn33/CMicro,thewindev/Caliburn.Micro,huoxudong125/Caliburn.Micro,ehigh2014/Caliburn.Micro,Caliburn-Micro/Caliburn.Micro,suvjunmd/Caliburn.Micro,BrunoJuchli/Caliburn.Micro,taori/Caliburn.Micro,Billpzoom/Caliburn.Micro,ckjohn88/CaliburnMicroCopy,TriadTom/Caliburn.Micro,bendetat/Caliburn.Micro,serenabenny/Caliburn.Micro,Bobdina/Caliburn.Micro,TriadTom/Caliburn.Micro,mbruckner/Caliburn.Micro,chrisrpatterson/Caliburn.Micro,ryanJohn33/CMicro
src/Caliburn.Micro.WP71/ActionDelegate.cs
src/Caliburn.Micro.WP71/ActionDelegate.cs
namespace Caliburn.Micro { /// <summary> /// Encapsulates a method that has five type parameters and does not return a value. /// </summary> /// <typeparam name="T1">The first type parameter.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The thrid type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> public delegate void Action<T1, T2, T3, T4, T5, T6>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6); /// <summary> /// Encapsulates a method that has five type parameters and returns a value. /// </summary> /// <typeparam name="T1">The first type parameter.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The thrid type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="TResult">The return type.</typeparam> public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5); }
namespace System { /// <summary> /// Encapsulates a method that has five type parameters and does not return a value. /// </summary> /// <typeparam name="T1">The first type parameter.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The thrid type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="T6">The sixth type parameter.</typeparam> public delegate void Action<T1, T2, T3, T4, T5, T6>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6); /// <summary> /// Encapsulates a method that has five type parameters and returns a value. /// </summary> /// <typeparam name="T1">The first type parameter.</typeparam> /// <typeparam name="T2">The second type parameter.</typeparam> /// <typeparam name="T3">The thrid type parameter.</typeparam> /// <typeparam name="T4">The fourth type parameter.</typeparam> /// <typeparam name="T5">The fifth type parameter.</typeparam> /// <typeparam name="TResult">The return type.</typeparam> public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5); }
mit
C#
56e4c6ac5c08d17664b099b90b030f5355220131
Test clicking CheckBox.
toroso/ruibarbo
tungsten.sampletest/CheckBoxTest.cs
tungsten.sampletest/CheckBoxTest.cs
using NUnit.Framework; using tungsten.core.Elements; using tungsten.core.Search; using tungsten.nunit; namespace tungsten.sampletest { public class CheckBoxTest : TestBase { [Test] public void Hupp() { var window = Desktop.FindFirstElement<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstElement<WpfCheckBox>(By.Name("ShowStuff")); checkBox.AssertThat(x => x.IsChecked, Is.True); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked, Is.False); } } }
using NUnit.Framework; using tungsten.core.Elements; using tungsten.core.Search; using tungsten.nunit; namespace tungsten.sampletest { public class CheckBoxTest : TestBase { [Test] public void Hupp() { var window = Desktop.FindFirstElement<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstElement<WpfCheckBox>(By.Name("ShowStuff")); checkBox.AssertThat(x => x.IsChecked, Is.True); } } }
apache-2.0
C#
0d1a2a869b8d00e9ddb1eb8f7ce98e261dc1becd
Add a new route to sample app that display OS and .NET versions (#41901)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Http/samples/MinimalSample/Program.cs
src/Http/samples/MinimalSample/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Mvc; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } string Plaintext() => "Hello, World!"; app.MapGet("/plaintext", Plaintext); var message = $""" Operating System: {Environment.OSVersion} .NET version: {Environment.Version} """; app.MapGet("/", () => message); var nestedGroup = app.MapGroup("/group/{groupName}") .MapGroup("/nested/{nestedName}") .WithMetadata(new TagsAttribute("nested")); nestedGroup .MapGet("/", (string groupName, string nestedName) => { return $"Hello from {groupName}:{nestedName}!"; }); object Json() => new { message = "Hello, World!" }; app.MapGet("/json", Json).WithTags("json"); string SayHello(string name) => $"Hello, {name}!"; app.MapGet("/hello/{name}", SayHello); app.MapGet("/null-result", IResult () => null); app.MapGet("/todo/{id}", Results<Ok<Todo>, NotFound, BadRequest> (int id) => id switch { <= 0 => TypedResults.BadRequest(), >= 1 and <= 10 => TypedResults.Ok(new Todo(id, "Walk the dog")), _ => TypedResults.NotFound() }); var extensions = new Dictionary<string, object>() { { "traceId", "traceId123" } }; app.MapGet("/problem", () => Results.Problem(statusCode: 500, extensions: extensions)); app.MapGet("/problem-object", () => Results.Problem(new ProblemDetails() { Status = 500, Extensions = { { "traceId", "traceId123" } } })); var errors = new Dictionary<string, string[]>() { { "Title", new[] { "The Title field is required." } } }; app.MapGet("/validation-problem", () => Results.ValidationProblem(errors, statusCode: 400, extensions: extensions)); app.MapGet("/validation-problem-object", () => Results.Problem(new HttpValidationProblemDetails(errors) { Status = 400, Extensions = { { "traceId", "traceId123" } } })); app.MapGet("/validation-problem-typed", () => TypedResults.ValidationProblem(errors, extensions: extensions)); app.Run(); internal record Todo(int Id, string Title);
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Mvc; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } string Plaintext() => "Hello, World!"; app.MapGet("/plaintext", Plaintext); var nestedGroup = app.MapGroup("/group/{groupName}") .MapGroup("/nested/{nestedName}") .WithMetadata(new TagsAttribute("nested")); nestedGroup .MapGet("/", (string groupName, string nestedName) => { return $"Hello from {groupName}:{nestedName}!"; }); object Json() => new { message = "Hello, World!" }; app.MapGet("/json", Json).WithTags("json"); string SayHello(string name) => $"Hello, {name}!"; app.MapGet("/hello/{name}", SayHello); app.MapGet("/null-result", IResult () => null); app.MapGet("/todo/{id}", Results<Ok<Todo>, NotFound, BadRequest> (int id) => id switch { <= 0 => TypedResults.BadRequest(), >= 1 and <= 10 => TypedResults.Ok(new Todo(id, "Walk the dog")), _ => TypedResults.NotFound() }); var extensions = new Dictionary<string, object>() { { "traceId", "traceId123" } }; app.MapGet("/problem", () => Results.Problem(statusCode: 500, extensions: extensions)); app.MapGet("/problem-object", () => Results.Problem(new ProblemDetails() { Status = 500, Extensions = { { "traceId", "traceId123" } } })); var errors = new Dictionary<string, string[]>() { { "Title", new[] { "The Title field is required." } } }; app.MapGet("/validation-problem", () => Results.ValidationProblem(errors, statusCode: 400, extensions: extensions)); app.MapGet("/validation-problem-object", () => Results.Problem(new HttpValidationProblemDetails(errors) { Status = 400, Extensions = { { "traceId", "traceId123" } } })); app.MapGet("/validation-problem-typed", () => TypedResults.ValidationProblem(errors, extensions: extensions)); app.Run(); internal record Todo(int Id, string Title);
apache-2.0
C#
9b7897785d500af6ad0489531318ecb40a65e3a3
fix parallelCoinView
Neurosploit/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Derrick-/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,DogaOztuzun/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode
Stratis.Bitcoin.FullNode/Consensus/CoinViews/ParallelCoinView.cs
Stratis.Bitcoin.FullNode/Consensus/CoinViews/ParallelCoinView.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NBitcoin; namespace Stratis.Bitcoin.FullNode.Consensus { public class ParallelCoinView : CoinView, IBackedCoinView { CoinView _Inner; public ParallelCoinView(TaskScheduler taskScheduler, CoinView inner) { if(inner == null) throw new ArgumentNullException("inner"); TaskScheduler = taskScheduler; _Inner = inner; BatchMaxSize = 100; } public ParallelCoinView(CoinView inner) : this(null, inner) { } public CoinView Inner { get { return _Inner; } } public override ChainedBlock Tip { get { return _Inner.Tip; } } TaskScheduler _TaskScheduler; public TaskScheduler TaskScheduler { get { return _TaskScheduler ?? TaskScheduler.Default; } set { _TaskScheduler = value; } } public int BatchMaxSize { get; set; } public override UnspentOutputs[] FetchCoins(uint256[] txIds) { int remain; int batchCount = Math.DivRem(txIds.Length, BatchMaxSize, out remain); if(batchCount == 0) return _Inner.FetchCoins(txIds); if(remain > 0) batchCount++; UnspentOutputs[] utxos = new UnspentOutputs[txIds.Length]; Task[] subfetch = new Task[batchCount]; int total = txIds.Length; int offset = 0; for(int i = 0; i < batchCount; i++) { int localOffset = offset; int size = Math.Min(BatchMaxSize, total); uint256[] txIdsPart = new uint256[size]; Array.Copy(txIds, offset, txIdsPart, 0, size); total -= size; offset += size; subfetch[i] = new Task(() => { Array.Copy(_Inner.FetchCoins(txIdsPart), 0, utxos, localOffset, txIdsPart.Length); }); subfetch[i].Start(TaskScheduler); } Task.WhenAll(subfetch).GetAwaiter().GetResult(); return utxos; } public override void SaveChanges(ChainedBlock newTip, IEnumerable<UnspentOutputs> unspentOutputs) { _Inner.SaveChanges(newTip, unspentOutputs); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NBitcoin; namespace Stratis.Bitcoin.FullNode.Consensus { public class ParallelCoinView : CoinView, IBackedCoinView { CoinView _Inner; public ParallelCoinView(TaskScheduler taskScheduler, CoinView inner) { if(inner == null) throw new ArgumentNullException("inner"); TaskScheduler = taskScheduler; _Inner = inner; BatchMaxSize = 100; } public ParallelCoinView(CoinView inner) : this(null, inner) { } public CoinView Inner { get { return _Inner; } } public override ChainedBlock Tip { get { return _Inner.Tip; } } TaskScheduler _TaskScheduler; public TaskScheduler TaskScheduler { get { return _TaskScheduler ?? TaskScheduler.Default; } set { _TaskScheduler = value; } } public int BatchMaxSize { get; set; } public override UnspentOutputs[] FetchCoins(uint256[] txIds) { int remain; int batchCount = Math.DivRem(txIds.Length, BatchMaxSize, out remain); if(batchCount == 0) return _Inner.FetchCoins(txIds); if(remain > 0) batchCount++; UnspentOutputs[] utxos = new UnspentOutputs[txIds.Length]; Task[] subfetch = new Task[batchCount]; int total = txIds.Length; int offset = 0; for(int i = 0; i < batchCount; i++) { int localOffset = offset; int size = Math.Min(100, total); uint256[] txIdsPart = new uint256[size]; Array.Copy(txIds, offset, txIdsPart, 0, size); total -= size; offset += size; subfetch[i] = new Task(() => { Array.Copy(_Inner.FetchCoins(txIdsPart), 0, utxos, localOffset, txIdsPart.Length); }); subfetch[i].Start(TaskScheduler); } Task.WhenAll(subfetch).GetAwaiter().GetResult(); return utxos; } public override void SaveChanges(ChainedBlock newTip, IEnumerable<UnspentOutputs> unspentOutputs) { _Inner.SaveChanges(newTip, unspentOutputs); } } }
mit
C#
ad344a2e7b0a29522db462e299985aa9e6ca67e3
add method to service
Iwuh/Wycademy
WycademyV2/src/WycademyV2/Commands/Services/WeaponInfoService.cs
WycademyV2/src/WycademyV2/Commands/Services/WeaponInfoService.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using WycademyV2.Commands.Entities; namespace WycademyV2.Commands.Services { public class WeaponInfoService { private readonly string[] FILENAMES = new string[] { "bow", "chargeblade", "dualblades", "greatsword", "gunlance", "hammer", "heavybowgun", "huntinghorn", "insectglaive", "lance", "lightbowgun", "longsword", "switchaxe", "swordshield" }; private List<WeaponInfo> _weapons; private List<string> _pages; private StringBuilder _currentPage; public WeaponInfoService() { var deserialized = new List<List<WeaponInfo>>(); foreach (var name in FILENAMES) { deserialized.Add(JsonConvert.DeserializeObject<List<WeaponInfo>>(File.ReadAllText($"{WycademyConst.DATA_LOCATION}\\weapon\\{name}.json"))); } // Flatten the list of lists into a single list. _weapons = deserialized.SelectMany(x => x).ToList(); _pages = new List<string>(); _currentPage = new StringBuilder(); } /// <summary> /// Find 0 or more WeaponInfo objects using part or all of the weapon's name. /// </summary> /// <param name="searchTerm">The string to search names for.</param> /// <returns>0 or more search results.</returns> public IEnumerable<WeaponInfo> SearchWeaponInfo(string searchTerm) { return _weapons.Where(w => w.Name.Contains(searchTerm)); } /// <summary> /// Gets a WeaponInfo by its ID. /// </summary> /// <param name="id">The weapon's ID.</param> /// <returns>The WeaponInfo with the requested ID, or null if not found.</returns> public WeaponInfo GetWeaponInfoById(int? id) { return _weapons.FirstOrDefault(w => w.ID == id); } public List<string> BuildWeaponInfoPages(WeaponInfo info) { return new WeaponInfoBuilder().Build(info, GetWeaponInfoById(info.UpgradesFrom)); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using WycademyV2.Commands.Entities; namespace WycademyV2.Commands.Services { public class WeaponInfoService { private readonly string[] FILENAMES = new string[] { "bow", "chargeblade", "dualblades", "greatsword", "gunlance", "hammer", "heavybowgun", "huntinghorn", "insectglaive", "lance", "lightbowgun", "longsword", "switchaxe", "swordshield" }; private List<WeaponInfo> _weapons; private List<string> _pages; private StringBuilder _currentPage; public WeaponInfoService() { var deserialized = new List<List<WeaponInfo>>(); foreach (var name in FILENAMES) { deserialized.Add(JsonConvert.DeserializeObject<List<WeaponInfo>>(File.ReadAllText($"{WycademyConst.DATA_LOCATION}\\weapon\\{name}.json"))); } // Flatten the list of lists into a single list. _weapons = deserialized.SelectMany(x => x).ToList(); _pages = new List<string>(); _currentPage = new StringBuilder(); } /// <summary> /// Find 0 or more WeaponInfo objects using part or all of the weapon's name. /// </summary> /// <param name="searchTerm">The string to search names for.</param> /// <returns>0 or more search results.</returns> public IEnumerable<WeaponInfo> SearchWeaponInfo(string searchTerm) { return _weapons.Where(w => w.Name.Contains(searchTerm)); } /// <summary> /// Gets a WeaponInfo by its ID. /// </summary> /// <param name="id">The weapon's ID.</param> /// <returns>The WeaponInfo with the requested ID, or null if not found.</returns> /// <exception cref="KeyNotFoundException">Thrown if no WeaponInfo matching the id is found.</exception> public WeaponInfo GetWeaponInfoById(int id) { var weapon = _weapons.FirstOrDefault(w => w.ID == id); if (weapon == null) { throw new KeyNotFoundException($"No WeaponInfo matching the id {id} was found."); } return weapon; } } }
mit
C#
ad6b637aca2fe6ad9758f943ea450f4970a777c8
Use await instead of hand-written continuation.
mysql-net/MySqlConnector,mysql-net/MySqlConnector
src/MySqlConnector/ValueTaskExtensions.cs
src/MySqlConnector/ValueTaskExtensions.cs
using System; using System.Threading.Tasks; namespace MySql.Data { internal static class ValueTaskExtensions { public static async ValueTask<TResult> ContinueWith<T, TResult>(this ValueTask<T> valueTask, Func<T, ValueTask<TResult>> continuation) => await continuation(await valueTask); public static ValueTask<T> FromException<T>(Exception exception) => new ValueTask<T>(Utility.TaskFromException<T>(exception)); } }
using System; using System.Threading.Tasks; namespace MySql.Data { internal static class ValueTaskExtensions { public static ValueTask<TResult> ContinueWith<T, TResult>(this ValueTask<T> valueTask, Func<T, ValueTask<TResult>> continuation) { return valueTask.IsCompleted ? continuation(valueTask.Result) : new ValueTask<TResult>(valueTask.AsTask().ContinueWith(task => continuation(task.GetAwaiter().GetResult()).AsTask()).Unwrap()); } public static ValueTask<T> FromException<T>(Exception exception) => new ValueTask<T>(Utility.TaskFromException<T>(exception)); } }
mit
C#
39b04a27072ffb458f5e9df9c6381fe4ea5535b9
Write some tests for GenerateFromFile
rzhw/Squirrel.Windows,rzhw/Squirrel.Windows
src/NSync.Tests/Core/ReleaseEntryTests.cs
src/NSync.Tests/Core/ReleaseEntryTests.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using NSync.Core; using NSync.Tests.TestHelpers; using Xunit; using Xunit.Extensions; namespace NSync.Tests.Core { public class ReleaseEntryTests { [Theory] [InlineData("94689fede03fed7ab59c24337673a27837f0c3ec MyCoolApp-1.0.nupkg 1004502", "MyCoolApp-1.0.nupkg", 1004502)] [InlineData("3a2eadd15dd984e4559f2b4d790ec8badaeb6a39 MyCoolApp-1.1.nupkg 1040561", "MyCoolApp-1.1.nupkg", 1040561)] [InlineData("14db31d2647c6d2284882a2e101924a9c409ee67 MyCoolApp-1.1.nupkg.delta 80396", "MyCoolApp-1.1.nupkg.delta", 80396)] public void ParseValidReleaseEntryLines(string releaseEntry, string fileName, long fileSize) { var fixture = ReleaseEntry.ParseReleaseEntry(releaseEntry); Assert.Equal(fixture.Filename, fileName); Assert.Equal(fixture.Filesize, fileSize); } [Theory] [InlineData("NSync.Core.1.0.0.0.nupkg", 4457, "75255cfd229a1ed1447abe1104f5635e69975d30")] [InlineData("NSync.Core.1.1.0.0.nupkg", 15830, "9baf1dbacb09940086c8c62d9a9dbe69fe1f7593")] public void GenerateFromFileTest(string name, long size, string sha1) { var path = IntegrationTestHelper.GetPath("fixtures", name); using (var f = File.OpenRead(path)) { var fixture = ReleaseEntry.GenerateFromFile(f, "dontcare"); Assert.Equal(size, fixture.Filesize); Assert.Equal(sha1, fixture.SHA1.ToLowerInvariant()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NSync.Core; using Xunit; using Xunit.Extensions; namespace NSync.Tests.Core { public class ReleaseEntryTests { [Theory] [InlineData("94689fede03fed7ab59c24337673a27837f0c3ec MyCoolApp-1.0.nupkg 1004502", "MyCoolApp-1.0.nupkg", 1004502)] [InlineData("3a2eadd15dd984e4559f2b4d790ec8badaeb6a39 MyCoolApp-1.1.nupkg 1040561", "MyCoolApp-1.1.nupkg", 1040561)] [InlineData("14db31d2647c6d2284882a2e101924a9c409ee67 MyCoolApp-1.1.nupkg.delta 80396", "MyCoolApp-1.1.nupkg.delta", 80396)] public void ParseValidReleaseEntryLines(string releaseEntry, string fileName, long fileSize) { var fixture = ReleaseEntry.ParseReleaseEntry(releaseEntry); Assert.Equal(fixture.Filename, fileName); Assert.Equal(fixture.Filesize, fileSize); } } }
mit
C#
b3eccba6225ff54eaa58c19245d4f38595dc9c56
Update GoogleAnalyticsPlatform.cs
KSemenenko/Google-Analytics-for-Xamarin-Forms,KSemenenko/GoogleAnalyticsForXamarinForms
Plugin.GoogleAnalytics/Plugin.GoogleAnalytics.UWP/GoogleAnalyticsPlatform.cs
Plugin.GoogleAnalytics/Plugin.GoogleAnalytics.UWP/GoogleAnalyticsPlatform.cs
using System.Threading.Tasks; using Windows.UI.Xaml; namespace Plugin.GoogleAnalytics { public partial class GoogleAnalytics { static GoogleAnalytics() { Application.Current.UnhandledException += CurrentDomain_UnhandledException; } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (!Current.Config.ReportUncaughtExceptions) return; Current.Tracker.SendException(e.Exception, true); Task.Delay(1000).Wait(); //delay } } }
using System.Threading.Tasks; using Windows.UI.Xaml; namespace Plugin.GoogleAnalytics { public partial class GoogleAnalytics { static GoogleAnalytics() { Application.Current.UnhandledException += CurrentDomain_UnhandledException; } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Current.Tracker.SendException(e.Exception, true); Task.Delay(1000).Wait(); //delay } } }
mit
C#
951ea89ddbe0d9ff04ca4a8dd09c40a838156b2d
Make MSBuild happy by adding attributes back to AssemblyInfo.cs.
Thealexbarney/LibDspAdpcm,Thealexbarney/VGAudio,Thealexbarney/LibDspAdpcm,Thealexbarney/VGAudio
DspAdpcm/DspAdpcm/Properties/AssemblyInfo.cs
DspAdpcm/DspAdpcm/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; [assembly: AssemblyTitle("DspAdpcm")] [assembly: AssemblyDescription("A library for encoding, decoding, and manipulating audio files using Nintendo's DSP-ADPCM format.")] [assembly: AssemblyCopyright("Copyright © 2016 Alex Barney")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyProduct("DspAdpcm")] [assembly: NeutralResourcesLanguage("en-US")]
using System.Reflection; using System.Resources; [assembly: AssemblyProduct("DspAdpcm")] [assembly: NeutralResourcesLanguage("en-US")]
mit
C#
06bbaad5a6c249d827f5047d80b136d3a330e0e5
Bump version for release
evem8/clilauncher,Icy0ne/clilauncher
EVEm8.CliLauncher/Properties/AssemblyInfo.cs
EVEm8.CliLauncher/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("EVEm8 CLI Launcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("EVEm8")] [assembly: AssemblyProduct("EVEm8.CliLauncher")] [assembly: AssemblyCopyright("Copyright © 2015 Kali Izia")] [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("c63c9d01-00ae-43ca-a079-bd286299c7ff")] // 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.3.1.0")] [assembly: AssemblyFileVersion("0.3.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("EVEm8 CLI Launcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("EVEm8")] [assembly: AssemblyProduct("EVEm8.CliLauncher")] [assembly: AssemblyCopyright("Copyright © 2015 Kali Izia")] [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("c63c9d01-00ae-43ca-a079-bd286299c7ff")] // 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.3.0.0")] [assembly: AssemblyFileVersion("0.3.0.0")]
mit
C#
c6275650696dd6c6da1e756d3599dd6f8c1d021f
Fix missing plot in claims
leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net
Joinrpg/Views/Plot/ShowElementPartial.cshtml
Joinrpg/Views/Plot/ShowElementPartial.cshtml
@using JoinRpg.Web.App_Code @using JoinRpg.Web.Models.Plot @model PlotElementViewModel @if (!Model.Visible) { return; } @{ var hideClass = Model.Status == PlotStatus.InWork ? "world-object-hidden" : ""; } @if (Model.HasEditAccess) { <div> @Html.DisplayFor(model => model.Status) @Html.ActionLink("Изменить", "Edit", "Plot", new { Model.PlotFolderId, Model.ProjectId }, null) @if (Model.CharacterId != null) { @Html.MoveControl(model => Model, "MoveElementForCharacter", "Plot", Model.CharacterId) } </div> } @if (Model.HasMasterAccess || Model.PublishMode) { <br/> <b>Для</b> if (Model.TargetsForDisplay.Any()) { foreach (var target in Model.TargetsForDisplay) { @Html.DisplayFor(model => target) } } else { <span>Не установлено</span> } } @if (!string.IsNullOrWhiteSpace(Model.TodoField) && Model.HasMasterAccess) { <p><b>Доделать</b>: @Model.TodoField</p> } <div class="@hideClass"> @Model.Content </div>
@using JoinRpg.Web.App_Code @using JoinRpg.Web.Models.Plot @model PlotElementViewModel @if (!Model.Visible) { return; } @{ var hideClass = Model.Status == PlotStatus.InWork ? "world-object-hidden" : ""; } @if (Model.HasEditAccess) { <div> @Html.DisplayFor(model => model.Status) @Html.ActionLink("Изменить", "Edit", "Plot", new { Model.PlotFolderId, Model.ProjectId }, null) @if (Model.CharacterId != null) { @Html.MoveControl(model => Model, "MoveElementForCharacter", "Plot", Model.CharacterId) } </div> } @if (Model.HasMasterAccess || Model.PublishMode) { <br/> <b>Для</b> if (Model.TargetsForDisplay.Any()) { foreach (var target in Model.TargetsForDisplay) { @Html.DisplayFor(model => target) } } else { <span>Не установлено</span> } } @if (!string.IsNullOrWhiteSpace(Model.TodoField) && Model.HasMasterAccess) { <p><b>Доделать</b>: @Model.TodoField</p> } <div class="@hideClass"> @Html.DisplayFor(model => Model.Content) </div>
mit
C#
16cadc6f30a27418d32537d26e86df47ee506991
fix force start
gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
LmpClient/Extensions/OrbitDriverExtension.cs
LmpClient/Extensions/OrbitDriverExtension.cs
using Harmony; using System.Reflection; namespace LmpClient.Extensions { public static class OrbitDriverExtension { private static readonly FieldInfo OrbitDriverReady = typeof(OrbitDriver).GetField("ready", AccessTools.all); private static readonly MethodInfo OrbitDriverStart = typeof(OrbitDriver).GetMethod("Start", AccessTools.all); public static bool Ready(this OrbitDriver driver) { return (bool)OrbitDriverReady.GetValue(driver); } public static void ForceStart(this OrbitDriver driver) { if(!driver.Ready()) OrbitDriverStart.Invoke(driver, null); } } }
using Harmony; using System.Reflection; namespace LmpClient.Extensions { public static class OrbitDriverExtension { private static readonly FieldInfo OrbitDriverReady = typeof(OrbitDriver).GetField("ready", AccessTools.all); private static readonly MethodInfo OrbitDriverStart = typeof(OrbitDriver).GetMethod("Start", AccessTools.all); public static bool Ready(this OrbitDriver driver) { return (bool)OrbitDriverReady.GetValue(driver); } public static void ForceStart(this OrbitDriver driver) { OrbitDriverStart.Invoke(driver, null); } } }
mit
C#
d593aa2a96c90940d2b6a23d1dff737d02841306
Add message
DimitarSD/Teamwork-Elderberry,DimitarSD/ElderberryTeam
LevelMoney/LevelMoneyUI/GUI/MoneyManager/MoneyManagerForms/ClassLibrary/GlobalMessages.cs
LevelMoney/LevelMoneyUI/GUI/MoneyManager/MoneyManagerForms/ClassLibrary/GlobalMessages.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TeamElderberryProject { public static class GlobalMessages { public const string NonNegativeInput = "Amount cannot be negative number!"; public const string ObjectCannotBeNull = "Please provide valid name!"; public const string InvalidStringLength = "ID should be exact {0} symbols!"; public const string IncomeAdded = "An income has been added"; public const string ExpenseAdded = "An expense has been added"; public const string LoanAdded = "A loan has been added"; public const string IncomeTitle = "Incomes"; public const string ExpenseTitle = "Expenses"; public const string LoanTitle = "Loans"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TeamElderberryProject { public class GlobalMessages { public const string NonNegativeInput = "Amount cannot be negative number!"; public const string ObjectCannotBeNull = "Please provide valid name!"; public const string InvalidStringLength = "ID should be exact {0} symbols!"; public const string IncomeAdded = "An income has been added"; public const string ExpenseAdded = "An expense has been added"; public const string LoanAdded = "A loan has been added"; public const string IncomeTitle = "Incomes"; public const string ExpenseTitle = "Expenses"; public const string LoanTitle = "Loans"; } }
mit
C#
82c64ac1da58b61279f1455ca56331499eac6c03
fix download
mohamed-abdo/reactive-export-large-data-as-stream,mohamed-abdo/reactive-export-large-data-as-stream
reactive-download/Views/Home/Index.cshtml
reactive-download/Views/Home/Index.cshtml
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <p>Download large file contents (hundrads of thousands of records)....</p> <br /> <form role="form" id="frm-merchantId" method="get" action="@Url.Action("DownloadReportData","Download")"> <div class="form-group"> <label>report Name</label> <input type="text" id="reportName" name="reportName" value="reportName" required placeholder="Enter reportName" class="form-control"> </div> <div class="form-group"> <label>records To Download</label> <input type="number" id="recordsToDownload" value="10000" name="recordsToDownload" required placeholder="recordsToDownload" class="form-control"> </div> <div class="form-group"> <label>file Name</label> <input type="text" id="fileName" name="fileName" value="downloadFile.txt" required placeholder="Enter fileName" class="form-control"> </div> <div class="form-group"> <label>target</label> <input type="text" id="target" name="target" value="txt" required placeholder="Enter target (pdf | xlsx | Text)" class="form-control"> </div> <div> <button class="btn btn-sm btn-primary pull-right m-t-n-xs" type="submit"><strong>Download</strong></button> </div> </form> </div>
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <p>Download large file contents (hundrads of thousands of records)....</p> <br /> <form role="form" id="frm-merchantId" method="get" action="@Url.Action("ReactiveDownloadReport","Download")"> <div class="form-group"> <label>reportName</label> <input type="text" id="reportName" name="reportName" value="reportName" required placeholder="Enter reportName" class="form-control"> </div> <div class="form-group"> <label>recordsToDownload (in progress feature)</label> <input type="number" id="recordsToDownload" disabled value="10000" name="recordsToDownload" required placeholder="recordsToDownload" class="form-control"> </div> <div class="form-group"> <label>fileName</label> <input type="text" id="fileName" name="fileName" value="downloadFile.txt" required placeholder="Enter fileName" class="form-control"> </div> <div class="form-group"> <label>target</label> <input type="text" id="target" name="target" value="txt" required placeholder="Enter target (pdf | xlsx | Text)" class="form-control"> </div> <div> <button class="btn btn-sm btn-primary pull-right m-t-n-xs" type="submit"><strong>Download</strong></button> </div> </form> </div>
apache-2.0
C#
fe63abfceca28f739e39dba66ecc46324f319c96
remove unused class
bordoley/SQLitePCL.pretty,matrostik/SQLitePCL.pretty
SQLitePCL.pretty/DatabaseConnection.Index.cs
SQLitePCL.pretty/DatabaseConnection.Index.cs
using System; using System.Collections.Generic; namespace SQLitePCL.pretty { public static partial class DatabaseConnection { /// <summary> /// Rebuilds all indexes in all attached databases. /// </summary> /// <param name="This">The database connection.</param> /// <seealso href="https://www.sqlite.org/lang_reindex.html"/> public static void ReIndex(this IDatabaseConnection This) { This.Execute(SQLBuilder.ReIndex); } /// <summary> /// Delete and recreate indexes from scratch. Useful when the definition of a collation sequence has changed. /// </summary> /// <param name="This">The database connection.</param> /// <param name="name"> /// Either a collation sequence name, or a table or index name optionally prefixed by a database name. /// </param> /// <seealso href="https://www.sqlite.org/lang_reindex.html"/> public static void ReIndex(this IDatabaseConnection This, string name) { This.Execute(SQLBuilder.ReIndexWithName(name)); } } }
using System; using System.Collections.Generic; namespace SQLitePCL.pretty { public sealed class IndexedColumn { public enum SortOrder { Ascending, Descending } private readonly string name; private readonly string collation; private readonly SortOrder? sortOrder; public } public static partial class DatabaseConnection { /// <summary> /// Rebuilds all indexes in all attached databases. /// </summary> /// <param name="This">The database connection.</param> /// <seealso href="https://www.sqlite.org/lang_reindex.html"/> public static void ReIndex(this IDatabaseConnection This) { This.Execute(SQLBuilder.ReIndex); } /// <summary> /// Delete and recreate indexes from scratch. Useful when the definition of a collation sequence has changed. /// </summary> /// <param name="This">The database connection.</param> /// <param name="name"> /// Either a collation sequence name, or a table or index name optionally prefixed by a database name. /// </param> /// <seealso href="https://www.sqlite.org/lang_reindex.html"/> public static void ReIndex(this IDatabaseConnection This, string name) { This.Execute(SQLBuilder.ReIndexWithName(name)); } } }
apache-2.0
C#
bb645d3456f1b1cab84116e481b78364c7790aa5
Update AssemblyInfo.cs
MisinformedDNA/SmartyStreets.Net
SmartyStreets.Net/Properties/AssemblyInfo.cs
SmartyStreets.Net/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SmartyStreets.Net Client Library")] [assembly: AssemblyDescription("The simplest and most flexible client library for using SmartyStreets.Net.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dan Friedman, Dragon Door Publications")] [assembly: AssemblyProduct("SmartyStreets.Net")] [assembly: AssemblyCopyright("Copyright © 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("abea6a18-cc56-4304-9914-8849b38b2074")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SmartyStreets.Net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SmartyStreets.Net")] [assembly: AssemblyCopyright("Copyright © 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("abea6a18-cc56-4304-9914-8849b38b2074")] // 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#
91946b1e45dbf44f2b6d74cfdbfd21bdb0350314
Change loglevel to debug
nopara73/DotNetTor
src/DotNetTor.Tests/SharedFixture.cs
src/DotNetTor.Tests/SharedFixture.cs
using DotNetEssentials.Logging; using DotNetTor.Exceptions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Text; using System.Threading.Tasks; namespace DotNetTor.Tests { public class SharedFixture : IDisposable { public string HostAddress { get; set; } public int SocksPort { get; set; } public int ControlPort { get; set; } public string ControlPortPassword { get; set; } public IPEndPoint TorSock5EndPoint => new IPEndPoint(IPAddress.Parse(HostAddress), SocksPort); private Process TorProcess { get; set; } public SharedFixture() { // Initialize tests... Logger.SetMinimumLevel(LogLevel.Debug); Logger.SetModes(LogMode.Debug, LogMode.File); Logger.SetFilePath("TestLogs.txt"); HostAddress = "127.0.0.1"; SocksPort = 9050; ControlPort = 9051; ControlPortPassword = "ILoveBitcoin21"; TorProcess = null; var torControl = new TorControlClient(HostAddress, ControlPort, ControlPortPassword); try { torControl.IsCircuitEstablishedAsync().GetAwaiter().GetResult(); } catch { var torProcessStartInfo = new ProcessStartInfo("tor") { Arguments = $"SOCKSPort {SocksPort} ControlPort {ControlPort} HashedControlPassword 16:0978DBAF70EEB5C46063F3F6FD8CBC7A86DF70D2206916C1E2AE29EAF6", UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true }; TorProcess = Process.Start(torProcessStartInfo); Task.Delay(3000).GetAwaiter().GetResult(); var established = false; var count = 0; while (!established) { if (count >= 21) throw new TorException("Couldn't establish circuit in time."); established = torControl.IsCircuitEstablishedAsync().GetAwaiter().GetResult(); Task.Delay(1000).GetAwaiter().GetResult(); count++; } } } public void Dispose() { // Cleanup tests... TorProcess?.Kill(); } } }
using DotNetEssentials.Logging; using DotNetTor.Exceptions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Text; using System.Threading.Tasks; namespace DotNetTor.Tests { public class SharedFixture : IDisposable { public string HostAddress { get; set; } public int SocksPort { get; set; } public int ControlPort { get; set; } public string ControlPortPassword { get; set; } public IPEndPoint TorSock5EndPoint => new IPEndPoint(IPAddress.Parse(HostAddress), SocksPort); private Process TorProcess { get; set; } public SharedFixture() { // Initialize tests... Logger.SetMinimumLevel(LogLevel.Trace); Logger.SetModes(LogMode.Debug, LogMode.File); Logger.SetFilePath("TestLogs.txt"); HostAddress = "127.0.0.1"; SocksPort = 9050; ControlPort = 9051; ControlPortPassword = "ILoveBitcoin21"; TorProcess = null; var torControl = new TorControlClient(HostAddress, ControlPort, ControlPortPassword); try { torControl.IsCircuitEstablishedAsync().GetAwaiter().GetResult(); } catch { var torProcessStartInfo = new ProcessStartInfo("tor") { Arguments = $"SOCKSPort {SocksPort} ControlPort {ControlPort} HashedControlPassword 16:0978DBAF70EEB5C46063F3F6FD8CBC7A86DF70D2206916C1E2AE29EAF6", UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true }; TorProcess = Process.Start(torProcessStartInfo); Task.Delay(3000).GetAwaiter().GetResult(); var established = false; var count = 0; while (!established) { if (count >= 21) throw new TorException("Couldn't establish circuit in time."); established = torControl.IsCircuitEstablishedAsync().GetAwaiter().GetResult(); Task.Delay(1000).GetAwaiter().GetResult(); count++; } } } public void Dispose() { // Cleanup tests... TorProcess?.Kill(); } } }
mit
C#
0e11c6d1241db1dd679a4ee643f919780f93c006
upgrade enode version
tangxuehua/enode,Aaron-Liu/enode
src/ENode/Properties/AssemblyInfo.cs
src/ENode/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("ENode")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdf470ac-90a3-47cf-9032-a3f7a298a688")] // 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.2.4")] [assembly: AssemblyFileVersion("1.2.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("ENode")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdf470ac-90a3-47cf-9032-a3f7a298a688")] // 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.2.3")] [assembly: AssemblyFileVersion("1.2.3")]
mit
C#
1a3f34de9bf089c1ad55c118a9774da96874e174
Set version to 0.1.
joeyespo/google-apps-client
GoogleAppsClient/Properties/AssemblyInfo.cs
GoogleAppsClient/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GoogleAppsClient")] [assembly: AssemblyDescription("Access Google Apps and get notifications on your desktop.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GoogleAppsClient")] [assembly: AssemblyCopyright("Copyright © Joe Esposito 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)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.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("GoogleAppsClient")] [assembly: AssemblyDescription("Access Google Apps and get notifications on your desktop.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GoogleAppsClient")] [assembly: AssemblyCopyright("Copyright © Joe Esposito 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)] // 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#
ff0577df5fe7d47e57df06ce63f5225ad2cf0392
Update "Book"
DRFP/Personal-Library
_Build/PersonalLibrary/Library/Model/Book.cs
_Build/PersonalLibrary/Library/Model/Book.cs
using SQLite; using System; namespace Library.Model { [Table("Books")] public class Book { [PrimaryKey, AutoIncrement] public int booID { get; set; } public int slfID { get; set; } public string booTitle { get; set; } public string booDescription { get; set; } public string booAuthor { get; set; } public string booPublisher { get; set; } public string booPublishedDate { get; set; } public int booPageCount { get; set; } public double booRating { get; set; } public int booRatingsCount { get; set; } public string booInformationURL { get; set; } public string booPreviewURL { get; set; } public string booThumbnail { get; set; } } }
using SQLite; using System; namespace Library.Model { [Table("Books")] public class Book { [PrimaryKey, AutoIncrement] public int booID { get; set; } public int slfID { get; set; } public string booTitle { get; set; } public string booDescription { get; set; } public string booAuthor { get; set; } public string booPublisher { get; set; } public DateTime booPublishedDate { get; set; } public int booPageCount { get; set; } public double booRating { get; set; } public int booRatingsCount { get; set; } public string booInformationURL { get; set; } public string booPreviewURL { get; set; } } }
mit
C#
f2fb1cb948d0f7e139d25cc43e8d1ce42ee5514c
Extend StdIOService to take a working directory.
DartVS/DartVS,modulexcite/DartVS,DartVS/DartVS,DartVS/DartVS,modulexcite/DartVS,modulexcite/DartVS
DartVS.Common/StdIOService.cs
DartVS.Common/StdIOService.cs
using System; using System.Diagnostics; using System.Text; namespace DartVS { /// <summary> /// Wraps a process for two-way communication over STDIN/STDOUT. /// </summary> public class StdIOService : IDisposable { readonly Process process; /// <summary> /// Launches the provided process with the provided arguments and calls <paramref name="outputHandler"/> and /// <paramref name="errorHandler"/> as data is received on STDOUT and STDERR. /// </summary> /// <param name="file">The executable file to start.</param> /// <param name="args">The arguments to pass to the executable file.</param> /// <param name="outputHandler">A handler to be called for data recieved from STDOUT.</param> /// <param name="errorHandler">A handler to be called for data recieved from STDERR.</param> [Obsolete("Use the overload that takes a workingDir instead.")] public StdIOService(string file, string args, Action<string> outputHandler, Action<string> errorHandler) : this(Environment.CurrentDirectory, file, args, outputHandler, errorHandler) { } /// <summary> /// Launches the provided process with the provided arguments and calls <paramref name="outputHandler"/> and /// <paramref name="errorHandler"/> as data is received on STDOUT and STDERR. /// </summary> /// <param name="workingDir">The directory to start the process in.</param> /// <param name="file">The executable file to start.</param> /// <param name="args">The arguments to pass to the executable file.</param> /// <param name="outputHandler">A handler to be called for data recieved from STDOUT.</param> /// <param name="errorHandler">A handler to be called for data recieved from STDERR.</param> public StdIOService(string workingDir, string file, string args, Action<string> outputHandler, Action<string> errorHandler) { var info = new ProcessStartInfo { WorkingDirectory = workingDir, FileName = file, Arguments = args, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, StandardOutputEncoding = Encoding.UTF8, }; process = Process.Start(info); process.OutputDataReceived += (sender, e) => outputHandler(e.Data); process.ErrorDataReceived += (sender, e) => errorHandler(e.Data); process.BeginOutputReadLine(); process.BeginErrorReadLine(); } /// <summary> /// Writes a line to STDIN of the wrapped process. /// </summary> /// <param name="value">The data to send to STDIN (newline is automatically appended).</param> public void WriteLine(string value) { if (process.HasExited) throw new Exception("Process has exited!"); lock (process.StandardInput) // Can't find any info on whether WriteLine below is threadsafe, so letassume the worst process.StandardInput.WriteLine(value); } public void WaitForExit(int milliseconds = 0) { if (milliseconds == 0) process.WaitForExit(); else process.WaitForExit(milliseconds); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { try { process.Kill(); } catch { } try { process.Close(); } catch { } } } } }
using System; using System.Diagnostics; using System.Text; namespace DartVS { /// <summary> /// Wraps a process for two-way communication over STDIN/STDOUT. /// </summary> public class StdIOService : IDisposable { readonly Process process; /// <summary> /// Launches the provided process with the provided arguments and calls <paramref name="outputHandler"/> and /// <paramref name="errorHandler"/> as data is received on STDOUT and STDERR. /// </summary> /// <param name="file">The executable file to start.</param> /// <param name="arguments">The arguments to pass to the executable file.</param> /// <param name="outputHandler">A handler to be called for data recieved from STDOUT.</param> /// <param name="errorHandler">A handler to be called for data recieved from STDERR.</param> public StdIOService(string file, string arguments, Action<string> outputHandler, Action<string> errorHandler) { var info = new ProcessStartInfo { FileName = file, Arguments = arguments, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, StandardOutputEncoding = Encoding.UTF8, }; process = Process.Start(info); process.OutputDataReceived += (sender, e) => outputHandler(e.Data); process.ErrorDataReceived += (sender, e) => errorHandler(e.Data); process.BeginOutputReadLine(); process.BeginErrorReadLine(); } /// <summary> /// Writes a line to STDIN of the wrapped process. /// </summary> /// <param name="value">The data to send to STDIN (newline is automatically appended).</param> public void WriteLine(string value) { if (process.HasExited) throw new Exception("Process has exited!"); lock (process.StandardInput) // Can't find any info on whether WriteLine below is threadsafe, so letassume the worst process.StandardInput.WriteLine(value); } public void WaitForExit(int milliseconds = 0) { if (milliseconds == 0) process.WaitForExit(); else process.WaitForExit(milliseconds); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { try { process.Kill(); } catch { } try { process.Close(); } catch { } } } } }
mit
C#
271b9c8f61f2fe92a7dcd4614d7d4f569ae53e81
bump version
raml-org/raml-dotnet-parser-2,raml-org/raml-dotnet-parser-2
source/Raml.Parser/Properties/AssemblyInfo.cs
source/Raml.Parser/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RAML.Parser")] [assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mulesoft Inc")] [assembly: AssemblyProduct("Raml.Parser")] [assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d5f8e5f6-634a-4487-be70-591c4d8546f2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.4")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RAML.Parser")] [assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mulesoft Inc")] [assembly: AssemblyProduct("Raml.Parser")] [assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d5f8e5f6-634a-4487-be70-591c4d8546f2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.3")]
apache-2.0
C#
39f0d146568da708c6ef47f050fbe5166452d7db
fix version
raml-org/raml-dotnet-parser-2,raml-org/raml-dotnet-parser-2
source/Raml.Parser/Properties/AssemblyInfo.cs
source/Raml.Parser/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RAML.Parser")] [assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mulesoft Inc")] [assembly: AssemblyProduct("Raml.Parser")] [assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d5f8e5f6-634a-4487-be70-591c4d8546f2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.5")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RAML.Parser")] [assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mulesoft Inc")] [assembly: AssemblyProduct("Raml.Parser")] [assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d5f8e5f6-634a-4487-be70-591c4d8546f2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.6")]
apache-2.0
C#
8cadf035c9bdd46e925fd886e00d6604a6135f98
Fix custom color chooser requiring "#" prefix
danielchalmers/SteamAccountSwitcher
SteamAccountSwitcher/HexColorChooser.xaml.cs
SteamAccountSwitcher/HexColorChooser.xaml.cs
#region using System.ComponentModel; using System.Windows; using System.Windows.Media; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for HexColorChooser.xaml /// </summary> public partial class HexColorChooser : Window { public Brush Color; public HexColorChooser(Brush oldBrush) { InitializeComponent(); txtColor.Text = oldBrush?.ToString(); txtColor.Focus(); } private void btnOK_Click(object sender, RoutedEventArgs e) { DialogResult = true; } private void Window_Closing(object sender, CancelEventArgs e) { try { Color = (Brush)new BrushConverter().ConvertFromString(txtColor.Text.StartsWith("#") == false ? "#" + txtColor.Text : txtColor.Text); } catch { // ignored } } } }
#region using System.ComponentModel; using System.Windows; using System.Windows.Media; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for HexColorChooser.xaml /// </summary> public partial class HexColorChooser : Window { public Brush Color; public HexColorChooser(Brush oldBrush) { InitializeComponent(); txtColor.Text = oldBrush?.ToString(); txtColor.Focus(); } private void btnOK_Click(object sender, RoutedEventArgs e) { DialogResult = true; } private void Window_Closing(object sender, CancelEventArgs e) { try { Color = (Brush)new BrushConverter().ConvertFromString(txtColor.Text); } catch { // ignored } } } }
mit
C#
8f86ed2a982b77a0bc2f63de4976e5afa9723ce8
Update JsonDeserializer.cs
tiksn/TIKSN-Framework
TIKSN.Core/Serialization/JsonDeserializer.cs
TIKSN.Core/Serialization/JsonDeserializer.cs
using Newtonsoft.Json; namespace TIKSN.Serialization { public class JsonDeserializer : DeserializerBase<string> { protected override T DeserializeInternal<T>(string serial) { return JsonConvert.DeserializeObject<T>(serial); } } }
using Newtonsoft.Json; using TIKSN.Analytics.Telemetry; namespace TIKSN.Serialization { public class JsonDeserializer : DeserializerBase<string> { public JsonDeserializer(IExceptionTelemeter exceptionTelemeter) : base(exceptionTelemeter) { } protected override T DeserializeInternal<T>(string serial) { return JsonConvert.DeserializeObject<T>(serial); } } }
mit
C#
69f17921bd0ef0e1549469173ab5e3d3631f138d
add assert helper for job project
mzrimsek/resume-site-api
Test.Integration/TestHelpers/AssertHelper.cs
Test.Integration/TestHelpers/AssertHelper.cs
using Web.Models.JobModels; using Web.Models.JobProjectModels; using Web.Models.SchoolModels; namespace Test.Integration.TestHelpers { public static class AssertHelper { public static bool AreJobViewModelsEqual(AddUpdateJobViewModel expected, JobViewModel actual) { return expected.Name == actual.Name && expected.City == actual.City && expected.State == actual.State && expected.Title == actual.Title && expected.StartDate == actual.StartDate && expected.EndDate == actual.EndDate; } public static bool AreSchoolViewModelsEqual(AddUpdateSchoolViewModel expected, SchoolViewModel actual) { return expected.Name == actual.Name && expected.City == actual.City && expected.State == actual.State && expected.Major == actual.Major && expected.Degree == actual.Degree && expected.StartDate == actual.StartDate && expected.EndDate == actual.EndDate; } public static bool AreJobProjectViewModelsEqual(AddUpdateJobProjectViewModel expected, JobProjectViewModel actual) { return expected.JobId == actual.JobId && expected.Name == actual.Name && expected.Description == actual.Description; } } }
using Web.Models.JobModels; using Web.Models.SchoolModels; namespace Test.Integration.TestHelpers { public static class AssertHelper { public static bool AreJobViewModelsEqual(AddUpdateJobViewModel expected, JobViewModel actual) { return expected.Name == actual.Name && expected.City == actual.City && expected.State == actual.State && expected.Title == actual.Title && expected.StartDate == actual.StartDate && expected.EndDate == actual.EndDate; } public static bool AreSchoolViewModelsEqual(AddUpdateSchoolViewModel expected, SchoolViewModel actual) { return expected.Name == actual.Name && expected.City == actual.City && expected.State == actual.State && expected.Major == actual.Major && expected.Degree == actual.Degree && expected.StartDate == actual.StartDate && expected.EndDate == actual.EndDate; } } }
mit
C#
c7116ab69ebf41e20a11fe8ea9f124dbbfa3a52b
fix xunit
Fody/Scalpel
Fody/Removers/XUnitRemover.cs
Fody/Removers/XUnitRemover.cs
using System.Collections.Generic; using System.Linq; using Mono.Cecil; class XUnitRemover : IRemover { public IEnumerable<string> GetReferenceNames() { yield return "xunit"; yield return "xunit.core"; yield return "xunit2"; } public IEnumerable<string> GetModuleAttributeNames() { yield break; } public IEnumerable<string> GetAssemblyAttributeNames() { yield return "Xunit.CollectionBehaviorAttribute"; } public bool ShouldRemoveType(TypeDefinition typeDefinition) { return HasXunitAttribute(typeDefinition.CustomAttributes) || typeDefinition.Methods.Any(HasXUnitAttributes); } static bool HasXunitAttribute(IEnumerable<CustomAttribute> customAttributes) { return customAttributes.Any(IsXUnitAttribute); } static bool IsXUnitAttribute(CustomAttribute y) { var scope = y.AttributeType.Scope.Name; return scope == "xunit" || scope == "xunit.core" || scope == "xunit2"; } static bool HasXUnitAttributes(MethodDefinition x) { return HasXunitAttribute(x.CustomAttributes); } }
using System.Collections.Generic; using System.Linq; using Mono.Cecil; class XUnitRemover : IRemover { public IEnumerable<string> GetReferenceNames() { yield return "xunit"; yield return "xunit2"; } public IEnumerable<string> GetModuleAttributeNames() { yield break; } public IEnumerable<string> GetAssemblyAttributeNames() { yield return "Xunit.CollectionBehaviorAttribute"; } public bool ShouldRemoveType(TypeDefinition typeDefinition) { return HasXunitAttribute(typeDefinition.CustomAttributes) || typeDefinition.Methods.Any(HasXUnitAttributes); } static bool HasXunitAttribute(IEnumerable<CustomAttribute> customAttributes) { return customAttributes.Any(IsXUnitAttribute); } static bool IsXUnitAttribute(CustomAttribute y) { var scope = y.AttributeType.Scope.Name; return scope == "Xunit" || scope == "Xunit2"; } static bool HasXUnitAttributes(MethodDefinition x) { return HasXunitAttribute(x.CustomAttributes); } }
mit
C#
9d49ef1d979fdff0ed7876b1562ea14f4a7e338c
Implement AccessTokenConfiguration#SetAccessToken
appharbor/appharbor-cli
src/AppHarbor/AccessTokenConfiguration.cs
src/AppHarbor/AccessTokenConfiguration.cs
using System; namespace AppHarbor { public class AccessTokenConfiguration : IAccessTokenConfiguration { private const string TokenEnvironmentVariable = "AppHarborToken"; private const EnvironmentVariableTarget TokenEnvironmentVariableTarget = EnvironmentVariableTarget.User; public virtual void DeleteAccessToken() { Environment.SetEnvironmentVariable(TokenEnvironmentVariable, null, TokenEnvironmentVariableTarget); } public virtual string GetAccessToken() { return Environment.GetEnvironmentVariable(TokenEnvironmentVariable, TokenEnvironmentVariableTarget); } public virtual void SetAccessToken(string accessToken) { Environment.SetEnvironmentVariable(TokenEnvironmentVariable, accessToken, TokenEnvironmentVariableTarget); } } }
using System; namespace AppHarbor { public class AccessTokenConfiguration : IAccessTokenConfiguration { private const string TokenEnvironmentVariable = "AppHarborToken"; private const EnvironmentVariableTarget TokenEnvironmentVariableTarget = EnvironmentVariableTarget.User; public virtual void DeleteAccessToken() { Environment.SetEnvironmentVariable(TokenEnvironmentVariable, null, TokenEnvironmentVariableTarget); } public virtual string GetAccessToken() { return Environment.GetEnvironmentVariable(TokenEnvironmentVariable, TokenEnvironmentVariableTarget); } public virtual void SetAccessToken(string username, string password) { throw new NotImplementedException(); //Environment.SetEnvironmentVariable(TokenEnvironmentVariable, "foo", TokenEnvironmentVariableTarget); } } }
mit
C#
13cbb8ce30187de2b41661889ab529acb3f283f5
work in progress
ghuntley/starter-mobile,ghuntley/starter-mobile,ghuntley/starter-mobile
src/StarterMobile.Core/AppMetrics.cs
src/StarterMobile.Core/AppMetrics.cs
using System; namespace StarterMobile.Core { /// <summary> /// All metrics are prefixed with a namespace which is used to denote which /// platform the application the application is running on: /// /// <platform>.<applicationname> /// /// Nouns are used to define the target and past tense verbs to define the action /// which is a very useful convention when you need to nest metrics: /// /// <namespace>.<instrumented section>.<target (noun)>.<action (past tense verb)> /// /// (time) akavache.query_time /// (counter) akavache.query.<appCacheKey> /// (time) bootstrapper.akavache.registration_time /// (time) bootstrapper.services.registration_time /// (time) bootstrapper.viewmodel.registration_time /// (counter) viewmodel.<viewmodelname>.[navigated|activated] /// /// (counter) fetchavatar.gravatar.attempted /// (counter) fetchavatar.gravatar.succeeded /// (counter) fetchavatar.gravatar.query.<emailaddress> /// (timer) fetchavatar.gravatar.query_time /// (counter) fetchavatar.gravatar.failure.account_not_found /// (counter) fetchavatar.gravatar.failure.authentication_failed /// (counter) fetchavatar.gravatar.failure.query_failed /// </summary> public static class AppMetrics { private static string StandardPrefix() { return String.Format("{0}.", AppInfo.ApplicationName).ToLowerInvariant(); } public static string AppBootstrapRegistrationTime(string service) { return StandardPrefix() + service.ToLowerInvariant() + ".registration_time"; } } }
using System; namespace StarterMobile.Core { /// <summary> /// All metrics are prefixed with a namespace which is used to denote which /// platform the application the application is running on: /// /// <platform>.<applicationname> /// /// Nouns are used to define the target and past tense verbs to define the action /// which is a very useful convention when you need to nest metrics: /// /// <namespace>.<instrumented section>.<target (noun)>.<action (past tense verb)> /// /// akavache.query_time /// akavache.query.<appCacheKey> /// bootstrapper.akavache.registration_time /// bootstrapper.services.registration_time /// bootstrapper.viewmodel.registration_time /// viewmodel.<viewmodelname>.?? /// </summary> public static class AppMetrics { private static string StandardPrefix() { return String.Format("{0}.", AppInfo.ApplicationName).ToLowerInvariant(); } public static string AppBootstrapRegistrationTime(string service) { return StandardPrefix() + service.ToLowerInvariant() + ".registration_time"; } // bootstrapper.*.registration_time; // akavache.registration_time; // akavache. // (counter) fetchavatar.gravatar.attempted // (counter) fetchavatar.gravatar.succeeded // (counter) fetchavatar.gravatar.query.<emailaddress> // (timer) fetchavatar.gravatar.query_time // (counter) fetchavatar.gravatar.failure.account_not_found // (counter) fetchavatar.gravatar.failure.authentication_failed // (counter) fetchavatar.gravatar.failure.query_failed } }
mit
C#
0c61b9ede2121461fc34fbaa451568f3da92e185
update version number
mono/tao,OpenRA/tao,mono/tao,OpenRA/tao
src/Tao.OpenGl/Properties/AssemblyInfo.cs
src/Tao.OpenGl/Properties/AssemblyInfo.cs
#region License /* MIT License Copyright 2003-2006 Tao Framework Team http://www.taoframework.com All rights reserved. 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. */ #endregion License using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyCompany("Tao Framework -- http://www.taoframework.com")] [assembly: AssemblyConfiguration("Retail")] [assembly: AssemblyCopyright("Copyright 2003-2007 Tao Framework Team. All rights reserved.")] [assembly: AssemblyCulture("")] [assembly: AssemblyDefaultAlias("Tao.OpenGl")] [assembly: AssemblyDelaySign(false)] [assembly: AssemblyDescription("Tao Framework OpenGL Binding For .NET")] [assembly: AssemblyFileVersion("2.1.0.3")] [assembly: AssemblyInformationalVersion("2.1.0.3")] [assembly: AssemblyKeyName("")] [assembly: AssemblyProduct("Tao.OpenGl.dll")] [assembly: AssemblyTitle("Tao Framework OpenGL Binding For .NET")] [assembly: AssemblyTrademark("Tao Framework -- http://www.taoframework.com")] [assembly: AssemblyVersion("2.1.0.3")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.SkipVerification)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]
#region License /* MIT License Copyright 2003-2006 Tao Framework Team http://www.taoframework.com All rights reserved. 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. */ #endregion License using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyCompany("Tao Framework -- http://www.taoframework.com")] [assembly: AssemblyConfiguration("Retail")] [assembly: AssemblyCopyright("Copyright 2003-2007 Tao Framework Team. All rights reserved.")] [assembly: AssemblyCulture("")] [assembly: AssemblyDefaultAlias("Tao.OpenGl")] [assembly: AssemblyDelaySign(false)] [assembly: AssemblyDescription("Tao Framework OpenGL Binding For .NET")] [assembly: AssemblyFileVersion("2.1.0.3")] [assembly: AssemblyInformationalVersion("2.1.0.2")] [assembly: AssemblyKeyName("")] [assembly: AssemblyProduct("Tao.OpenGl.dll")] [assembly: AssemblyTitle("Tao Framework OpenGL Binding For .NET")] [assembly: AssemblyTrademark("Tao Framework -- http://www.taoframework.com")] [assembly: AssemblyVersion("2.1.0.3")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.SkipVerification)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]
mit
C#
7428c8018984f67ad64f8050ec65ee7767ecb846
Use generic overload for Enum.GetValues
json-api-dotnet/JsonApiDotNetCore,Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core
src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs
src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using JsonApiDotNetCore.QueryStrings; namespace JsonApiDotNetCore.Controllers.Annotations { /// <summary> /// Used on an ASP.NET Core controller class to indicate which query string parameters are blocked. /// </summary> /// <example><![CDATA[ /// [DisableQueryString(JsonApiQueryStringParameters.Sort | JsonApiQueryStringParameters.Page)] /// public class CustomersController : JsonApiController<Customer> { } /// ]]></example> /// <example><![CDATA[ /// [DisableQueryString("skipCache")] /// public class CustomersController : JsonApiController<Customer> { } /// ]]></example> [PublicAPI] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class DisableQueryStringAttribute : Attribute { public static readonly DisableQueryStringAttribute Empty = new(JsonApiQueryStringParameters.None); public IReadOnlySet<string> ParameterNames { get; } /// <summary> /// Disables one or more of the builtin query parameters for a controller. /// </summary> public DisableQueryStringAttribute(JsonApiQueryStringParameters parameters) { var parameterNames = new HashSet<string>(); foreach (JsonApiQueryStringParameters value in Enum.GetValues<JsonApiQueryStringParameters>()) { if (value != JsonApiQueryStringParameters.None && value != JsonApiQueryStringParameters.All && parameters.HasFlag(value)) { parameterNames.Add(value.ToString()); } } ParameterNames = parameterNames; } /// <summary> /// It is allowed to use a comma-separated list of strings to indicate which query parameters should be disabled, because the user may have defined /// custom query parameters that are not included in the <see cref="JsonApiQueryStringParameters" /> enum. /// </summary> public DisableQueryStringAttribute(string parameterNames) { ArgumentGuard.NotNullNorEmpty(parameterNames, nameof(parameterNames)); ParameterNames = parameterNames.Split(",").ToHashSet(); } public bool ContainsParameter(JsonApiQueryStringParameters parameter) { string name = parameter.ToString(); return ParameterNames.Contains(name); } } }
using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using JsonApiDotNetCore.QueryStrings; namespace JsonApiDotNetCore.Controllers.Annotations { /// <summary> /// Used on an ASP.NET Core controller class to indicate which query string parameters are blocked. /// </summary> /// <example><![CDATA[ /// [DisableQueryString(JsonApiQueryStringParameters.Sort | JsonApiQueryStringParameters.Page)] /// public class CustomersController : JsonApiController<Customer> { } /// ]]></example> /// <example><![CDATA[ /// [DisableQueryString("skipCache")] /// public class CustomersController : JsonApiController<Customer> { } /// ]]></example> [PublicAPI] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class DisableQueryStringAttribute : Attribute { public static readonly DisableQueryStringAttribute Empty = new(JsonApiQueryStringParameters.None); public IReadOnlySet<string> ParameterNames { get; } /// <summary> /// Disables one or more of the builtin query parameters for a controller. /// </summary> public DisableQueryStringAttribute(JsonApiQueryStringParameters parameters) { var parameterNames = new HashSet<string>(); foreach (JsonApiQueryStringParameters value in Enum.GetValues(typeof(JsonApiQueryStringParameters))) { if (value != JsonApiQueryStringParameters.None && value != JsonApiQueryStringParameters.All && parameters.HasFlag(value)) { parameterNames.Add(value.ToString()); } } ParameterNames = parameterNames; } /// <summary> /// It is allowed to use a comma-separated list of strings to indicate which query parameters should be disabled, because the user may have defined /// custom query parameters that are not included in the <see cref="JsonApiQueryStringParameters" /> enum. /// </summary> public DisableQueryStringAttribute(string parameterNames) { ArgumentGuard.NotNullNorEmpty(parameterNames, nameof(parameterNames)); ParameterNames = parameterNames.Split(",").ToHashSet(); } public bool ContainsParameter(JsonApiQueryStringParameters parameter) { string name = parameter.ToString(); return ParameterNames.Contains(name); } } }
mit
C#
9c83e3cd3abae45a0f7e6ce3dfaf5107fe2f4a37
Update FaceToCamera.cs
insthync/unity-utilities
UnityUtilities/Scripts/Misc/FaceToCamera.cs
UnityUtilities/Scripts/Misc/FaceToCamera.cs
using UnityEngine; public class FaceToCamera : MonoBehaviour { public Camera targetCamera; void FixedUpdate() { Camera camera = targetCamera; if (camera == null) camera = Camera.main; transform.forward = camera.transform.forward; } }
using UnityEngine; public class FaceToCamera : MonoBehaviour { void FixedUpdate() { transform.forward = Camera.main.transform.forward; } }
mit
C#
b79fc0e0267022fc1b70973e3a0473f3044ee61a
Reformat the file to match C# code style.
versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla
VersionOne.ServerConnector/EntityFactory.cs
VersionOne.ServerConnector/EntityFactory.cs
using System; using System.Collections.Generic; using System.Linq; using VersionOne.SDK.APIClient; namespace VersionOne.ServerConnector { // TODO extract interface and inject into VersionOneProcessor internal class EntityFactory { private readonly IServices services; private readonly IEnumerable<AttributeInfo> attributesToQuery; internal EntityFactory(IServices services, IEnumerable<AttributeInfo> attributesToQuery) { this.services = services; this.attributesToQuery = attributesToQuery; } internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) { var assetType = services.Meta.GetAssetType(assetTypeName); var asset = services.New(assetType, Oid.Null); foreach (var attributeValue in attributeValues) { if (attributeValue is SingleAttributeValue) { asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value); } else if (attributeValue is MultipleAttributeValue) { var values = ((MultipleAttributeValue)attributeValue).Values; var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name); foreach (var value in values) { asset.AddAttributeValue(attributeDefinition, value); } } else { throw new NotSupportedException("Unknown Attribute Value type."); } } foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) { asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr)); } services.Save(asset); return asset; } } }
using System; using System.Collections.Generic; using System.Linq; using VersionOne.SDK.APIClient; namespace VersionOne.ServerConnector { // TODO extract interface and inject into VersionOneProcessor internal class EntityFactory { private readonly IServices services; private readonly IEnumerable<AttributeInfo> attributesToQuery; internal EntityFactory(IServices services, IEnumerable<AttributeInfo> attributesToQuery) { this.services = services; this.attributesToQuery = attributesToQuery; } internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) { var assetType = services.Meta.GetAssetType(assetTypeName); var asset = services.New(assetType, Oid.Null); foreach (var attributeValue in attributeValues) { if(attributeValue is SingleAttributeValue) { asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value); } else if(attributeValue is MultipleAttributeValue) { var values = ((MultipleAttributeValue) attributeValue).Values; var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name); foreach (var value in values) { asset.AddAttributeValue(attributeDefinition, value); } } else { throw new NotSupportedException("Unknown Attribute Value type."); } } foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) { asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr)); } services.Save(asset); return asset; } } }
bsd-3-clause
C#
3065761ae341ad9e89123e0da833272d4ef4dd42
reorder members in android sample
builttoroam/BuildIt,builttoroam/BuildIt
src/BuildIt.ML/Samples/BuildIt.ML.Sample.Android/MainActivity.cs
src/BuildIt.ML/Samples/BuildIt.ML.Sample.Android/MainActivity.cs
using Android.App; using Android.Content.PM; using Android.OS; using BuildIt.ML.Sample.UI; using Plugin.CurrentActivity; using Plugin.Permissions; namespace BuildIt.ML.Sample.Droid { [Activity(Label = "BuildIt.ML.Sample", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity { public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); } protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; CrossCurrentActivity.Current.Init(this, bundle); base.OnCreate(bundle); Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
using Android.App; using Android.Content.PM; using Android.OS; using BuildIt.ML.Sample.UI; using Plugin.CurrentActivity; using Plugin.Permissions; namespace BuildIt.ML.Sample.Droid { [Activity(Label = "BuildIt.ML.Sample", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; CrossCurrentActivity.Current.Init(this, bundle); base.OnCreate(bundle); Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
mit
C#
3e26473ca0683e8d94457b0bbc004fe4eddc9fdc
Define some array helpers
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
stdlib/corlib/Array.cs
stdlib/corlib/Array.cs
#importMacros(LeMP.CSharp6); namespace System { // TODO: tweak the compiler to make all arrays implement 'System.Array'. public abstract class Array : Object { public static void Clear(byte[] array, int index, int length) { Clear<byte>(array, index, length); } public static void Clear<T>(T[] array, int index, int length) { EnsureValidRange( nameof(index), nameof(array), index, length, array.Length); for (int i = 0; i < length; i++) { array[index + i] = default(T); } } public static unsafe void Copy<T>( T[] source, int sourceIndex, T[] destination, int destinationIndex, int length) { EnsureValidRange( nameof(sourceIndex), nameof(source), sourceIndex, length, source.Length); EnsureValidRange( nameof(destinationIndex), nameof(destination), destinationIndex, length, destination.Length); Buffer.MemoryCopy( &source[sourceIndex], &destination[destinationIndex], (destination.Length - destinationIndex) * sizeof(T), (length - sourceIndex) * sizeof(T)); } internal static bool IsValidRange(int rangeStart, int rangeLength, int dataLength) { return rangeStart + rangeLength <= dataLength; } internal static void EnsureValidRange( string argName, string arrayName, int rangeStart, int rangeLength, int arrayLength) { EnsureInArray(argName, arrayName, rangeStart, arrayLength); if (!IsValidRange(rangeStart, rangeLength, arrayLength)) { throw new ArgumentOutOfRangeException( argName, rangeStart, arrayName + " array range [" + rangeStart + ", " + rangeStart + rangeLength + ") is out of bounds."); } } internal static void EnsureInArray( string argName, string arrayName, int argValue, int arrayLength) { if (argValue >= arrayLength) { throw new ArgumentOutOfRangeException( nameof(argName), argValue, argName + " is greater than the length of the " + arrayName + " array."); } } } }
namespace System { // TODO: tweak the compiler to make all arrays implement 'System.Array'. public abstract class Array : Object { public static void Clear(byte[] array, int index, int length) { for (int i = 0; i < length; i++) { array[index + i] = 0; } } } }
mit
C#
0b53249d5742404e7511d129ae55503ce8673c85
Make ImageSharpConfigurationOptions public
abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS
src/Umbraco.Web.Common/DependencyInjection/ImageSharpConfigurationOptions.cs
src/Umbraco.Web.Common/DependencyInjection/ImageSharpConfigurationOptions.cs
using Microsoft.Extensions.Options; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Web.Middleware; namespace Umbraco.Cms.Web.Common.DependencyInjection { /// <summary> /// Configures the ImageSharp middleware options to use the registered configuration. /// </summary> /// <seealso cref="Microsoft.Extensions.Options.IConfigureOptions&lt;SixLabors.ImageSharp.Web.Middleware.ImageSharpMiddlewareOptions&gt;" /> public sealed class ImageSharpConfigurationOptions : IConfigureOptions<ImageSharpMiddlewareOptions> { /// <summary> /// The ImageSharp configuration. /// </summary> private readonly Configuration _configuration; /// <summary> /// Initializes a new instance of the <see cref="ImageSharpConfigurationOptions" /> class. /// </summary> /// <param name="configuration">The ImageSharp configuration.</param> public ImageSharpConfigurationOptions(Configuration configuration) => _configuration = configuration; /// <summary> /// Invoked to configure a <typeparamref name="TOptions" /> instance. /// </summary> /// <param name="options">The options instance to configure.</param> public void Configure(ImageSharpMiddlewareOptions options) => options.Configuration = _configuration; } }
using Microsoft.Extensions.Options; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Web.Middleware; namespace Umbraco.Cms.Web.Common.DependencyInjection { /// <summary> /// Configures the ImageSharp middleware options to use the registered configuration. /// </summary> /// <seealso cref="Microsoft.Extensions.Options.IConfigureOptions&lt;SixLabors.ImageSharp.Web.Middleware.ImageSharpMiddlewareOptions&gt;" /> internal class ImageSharpConfigurationOptions : IConfigureOptions<ImageSharpMiddlewareOptions> { /// <summary> /// The ImageSharp configuration. /// </summary> private readonly Configuration _configuration; /// <summary> /// Initializes a new instance of the <see cref="ImageSharpConfigurationOptions" /> class. /// </summary> /// <param name="configuration">The ImageSharp configuration.</param> public ImageSharpConfigurationOptions(Configuration configuration) => _configuration = configuration; /// <summary> /// Invoked to configure a <typeparamref name="TOptions" /> instance. /// </summary> /// <param name="options">The options instance to configure.</param> public void Configure(ImageSharpMiddlewareOptions options) => options.Configuration = _configuration; } }
mit
C#
0b2eb48fb742da154f211bb407a7dcbc8ff70114
Remove Tuple<T1, T2> base class from Response
smarkets/IronSmarkets
IronSmarkets/Clients/Response.cs
IronSmarkets/Clients/Response.cs
// Copyright (c) 2011-2012 Smarkets Limited // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; namespace IronSmarkets.Clients { public interface IResponse<T> { ulong Sequence { get; } T Data { get; } } internal sealed class Response<T> : IResponse<T> { private readonly ulong _sequence; private readonly T _data; public ulong Sequence { get { return _sequence; } } public T Data { get { return _data; } } internal Response(ulong sequence, T data) { _sequence = sequence; _data = data; } } }
// Copyright (c) 2011-2012 Smarkets Limited // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; namespace IronSmarkets.Clients { public interface IResponse<T> { ulong Sequence { get; } T Data { get; } } internal sealed class Response<T> : Tuple<ulong, T>, IResponse<T> { public ulong Sequence { get { return Item1; } } public T Data { get { return Item2; } } internal Response(ulong sequence, T data) : base(sequence, data) { } } }
mit
C#
27d358c88400fcc7e1f75e483da729a2d35d8fc1
add EOLs in the end of files
livarcocc/cli-1,johnbeisner/cli,blackdwarf/cli,harshjain2/cli,blackdwarf/cli,ravimeda/cli,blackdwarf/cli,EdwardBlair/cli,livarcocc/cli-1,EdwardBlair/cli,harshjain2/cli,svick/cli,svick/cli,Faizan2304/cli,Faizan2304/cli,johnbeisner/cli,Faizan2304/cli,johnbeisner/cli,dasMulli/cli,livarcocc/cli-1,ravimeda/cli,EdwardBlair/cli,dasMulli/cli,blackdwarf/cli,ravimeda/cli,harshjain2/cli,svick/cli,dasMulli/cli
test/Microsoft.DotNet.Tools.Tests.Utilities/NonWindowsOnlyTheoryAttribute.cs
test/Microsoft.DotNet.Tools.Tests.Utilities/NonWindowsOnlyTheoryAttribute.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.DotNet.PlatformAbstractions; using Xunit; namespace Microsoft.DotNet.Tools.Test.Utilities { public class NonWindowsOnlyTheoryAttribute : TheoryAttribute { public NonWindowsOnlyTheoryAttribute() { if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows) { this.Skip = "This test requires non-Windows to run"; } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.DotNet.PlatformAbstractions; using Xunit; namespace Microsoft.DotNet.Tools.Test.Utilities { public class NonWindowsOnlyTheoryAttribute : TheoryAttribute { public NonWindowsOnlyTheoryAttribute() { if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows) { this.Skip = "This test requires non-Windows to run"; } } } }
mit
C#
e039925416d8301537d1b1f424e5df0bac3ab124
Refactor `AtataContextTimeZoneTests`
atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata
test/Atata.Tests/AtataContextTimeZoneTests.cs
test/Atata.Tests/AtataContextTimeZoneTests.cs
using System; using System.Linq; using NUnit.Framework; namespace Atata.Tests { public class AtataContextTimeZoneTests : UITestFixtureBase { private readonly TimeZoneInfo _timeZone = TimeZoneInfo.FindSystemTimeZoneById("UTC-02"); private DateTime _nowInSetTimeZone; [SetUp] public void SetUpTest() { ConfigureBaseAtataContext() .UseTimeZone(_timeZone) .UseDriverInitializationStage(AtataContextDriverInitializationStage.None) .Build(); _nowInSetTimeZone = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, _timeZone); } [Test] public void AtataContext_StartedAt() { AssertDateTimeIsCloseToExpected(AtataContext.Current.StartedAt, _nowInSetTimeZone); } [Test] public void AtataContext_BuildStartInTimeZone() { AssertDateTimeIsCloseToExpected(AtataContext.Current.BuildStartInTimeZone, _nowInSetTimeZone); } [Test] public void LogEventInfo_Timestamp() { AssertDateTimeIsCloseToExpected(LogEntries.Last().Timestamp, _nowInSetTimeZone); } [Test] public void LogEventInfo_TestStart() { AssertDateTimeIsCloseToExpected(LogEntries.Last().TestStart, _nowInSetTimeZone); } [Test] public void LogEventInfo_BuildStart() { AssertDateTimeIsCloseToExpected(LogEntries.Last().BuildStart, _nowInSetTimeZone); } private static void AssertDateTimeIsCloseToExpected(DateTime actual, DateTime expected) { Assert.That(actual, Is.EqualTo(expected).Within(1).Minutes); } } }
using System; using System.Linq; using NUnit.Framework; namespace Atata.Tests { public class AtataContextTimeZoneTests : UITestFixtureBase { private readonly TimeZoneInfo _timeZone = TimeZoneInfo.FindSystemTimeZoneById("UTC-02"); private DateTime _nowInSetTimeZone; [SetUp] public void SetUpTest() { ConfigureBaseAtataContext() .UseTimeZone(_timeZone) .Build(); _nowInSetTimeZone = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, _timeZone); } [Test] public void AtataContext_StartedAt() { AssertDateTimeIsCloseToExpected(AtataContext.Current.StartedAt, _nowInSetTimeZone); } [Test] public void AtataContext_BuildStartInTimeZone() { AssertDateTimeIsCloseToExpected(AtataContext.Current.BuildStartInTimeZone, _nowInSetTimeZone); } [Test] public void LogEventInfo_Timestamp() { AssertDateTimeIsCloseToExpected(LogEntries.Last().Timestamp, _nowInSetTimeZone); } [Test] public void LogEventInfo_TestStart() { AssertDateTimeIsCloseToExpected(LogEntries.Last().TestStart, _nowInSetTimeZone); } [Test] public void LogEventInfo_BuildStart() { AssertDateTimeIsCloseToExpected(LogEntries.Last().BuildStart, _nowInSetTimeZone); } private static void AssertDateTimeIsCloseToExpected(DateTime actual, DateTime expected) { Assert.That(actual, Is.EqualTo(expected).Within(2).Minutes); } } }
apache-2.0
C#
0c464bec4677fdba76f6091455dcf1c92df5e14e
Tweak caret diagnostics example
jonathanvdc/Pixie,jonathanvdc/Pixie
Examples/CaretDiagnostics/Program.cs
Examples/CaretDiagnostics/Program.cs
using System; using System.Linq; using Pixie; using Pixie.Terminal; using Pixie.Markup; using Pixie.Code; using Pixie.Terminal.Render; namespace CaretDiagnostics { public static class Program { public static void Main(string[] args) { // First, acquire a terminal log. You should acquire // a log once and then re-use it in your application. // // In this case, we'll also overwrite the default // caret diagnostics renderer with a variation that // colors its output red and tries to print five lines // of context. var log = TerminalLog .Acquire() .WithRenderers(new NodeRenderer[] { new HighlightedSourceRenderer(Colors.Red, 5) }); var doc = new StringDocument("code.cs", SourceCode); var ctorStartOffset = SourceCode.IndexOf("public Program()"); var ctorNameOffset = SourceCode.IndexOf("Program()"); var highlightRegion = new SourceRegion( new SourceSpan(doc, ctorStartOffset, "public Program()".Length)) .ExcludeCharacters(char.IsWhiteSpace); var focusRegion = new SourceRegion( new SourceSpan(doc, ctorNameOffset, "Program".Length)); // Write an entry to the log that contains the things // we would like to print. log.Log( new LogEntry( Severity.Info, new MarkupNode[] { new Title(new ColorSpan(new Text("Hello world"), Colors.Green)), new HighlightedSource(highlightRegion, focusRegion) })); } private const string SourceCode = @"public static class Program { public Program() { } }"; } }
using System; using System.Linq; using Pixie; using Pixie.Terminal; using Pixie.Markup; using Pixie.Code; namespace CaretDiagnostics { public static class Program { public static void Main(string[] args) { // First, acquire a terminal log. You should acquire // a log once and then re-use it in your application. var log = TerminalLog.Acquire(); var doc = new StringDocument("code.cs", SourceCode); var ctorStartOffset = SourceCode.IndexOf("public Program()"); var ctorNameOffset = SourceCode.IndexOf("Program()"); var highlightRegion = new SourceRegion( new SourceSpan(doc, ctorStartOffset, "public Program()".Length)) .ExcludeCharacters(char.IsWhiteSpace); var focusRegion = new SourceRegion( new SourceSpan(doc, ctorNameOffset, "Program".Length)); // Write an entry to the log that contains the things // we would like to print. log.Log( new LogEntry( Severity.Info, new MarkupNode[] { new Title(new ColorSpan(new Text("Hello world"), Colors.Green)), new HighlightedSource(highlightRegion, focusRegion) })); } private const string SourceCode = @"public static class Program { public Program() { } }"; } }
mit
C#
2e2a8591462b3e8634e34203ad30211701d503e3
Fix invalid logic when start server
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/LiteNetLibGameManager.cs
Scripts/LiteNetLibGameManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace LiteNetLibHighLevel { [RequireComponent(typeof(LiteNetLibAssets))] public class LiteNetLibGameManager : LiteNetLibManager { private LiteNetLibAssets assets; public LiteNetLibAssets Assets { get { if (assets == null) assets = GetComponent<LiteNetLibAssets>(); return assets; } } protected override void Awake() { base.Awake(); Assets.ClearRegisterPrefabs(); Assets.RegisterPrefabs(); } public override bool StartServer() { if (base.StartServer()) { Assets.RegisterSceneObjects(); return true; } return false; } public override LiteNetLibClient StartClient() { var client = base.StartClient(); if (client != null) Assets.RegisterSceneObjects(); return client; } protected override void RegisterServerMessages() { base.RegisterServerMessages(); } protected override void RegisterClientMessages() { base.RegisterClientMessages(); } #region Relates components functions public LiteNetLibIdentity NetworkSpawn(GameObject gameObject) { return Assets.NetworkSpawn(gameObject); } public bool NetworkDestroy(GameObject gameObject) { return Assets.NetworkDestroy(gameObject); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace LiteNetLibHighLevel { [RequireComponent(typeof(LiteNetLibAssets))] public class LiteNetLibGameManager : LiteNetLibManager { private LiteNetLibAssets assets; public LiteNetLibAssets Assets { get { if (assets == null) assets = GetComponent<LiteNetLibAssets>(); return assets; } } protected override void Awake() { base.Awake(); Assets.ClearRegisterPrefabs(); Assets.RegisterPrefabs(); } public override bool StartServer() { if (base.StartServer()) Assets.RegisterSceneObjects(); return false; } public override LiteNetLibClient StartClient() { var client = base.StartClient(); if (client != null) Assets.RegisterSceneObjects(); return client; } protected override void RegisterServerMessages() { base.RegisterServerMessages(); } protected override void RegisterClientMessages() { base.RegisterClientMessages(); } #region Relates components functions public LiteNetLibIdentity NetworkSpawn(GameObject gameObject) { return Assets.NetworkSpawn(gameObject); } public bool NetworkDestroy(GameObject gameObject) { return Assets.NetworkDestroy(gameObject); } #endregion } }
mit
C#
e9695af94f163243435335dd514f3bd50be37092
fix bug
OpenTl/OpenTl.Schema
src/OpenTl.Schema/SchemaInfo.cs
src/OpenTl.Schema/SchemaInfo.cs
namespace OpenTl.Schema { public static class SchemaInfo { public static int SchemaVersion { get; } = 76; } }
namespace OpenTl.Schema { public static class SchemaInfo { public static int SchemaVersion { get; } = 73; } }
mit
C#
5ae623fe77f7d1e3cc4e3de00bcef6834ac5c6f8
Update SessionLeaveAction.cs
StevenThuriot/Nova,StevenThuriot/Nova
Nova.Shell/Actions/Session/SessionLeaveAction.cs
Nova.Shell/Actions/Session/SessionLeaveAction.cs
#region License // // Copyright 2013 Steven Thuriot // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using Nova.Library.Actions; namespace Nova.Shell.Actions.Session { /// <summary> /// The session leave action /// </summary> public class SessionLeaveAction : LeaveAction<SessionView, SessionViewModel> { public override bool Leave() { var canLeave = true; if (ViewModel.IsChanged) { //Todo: Save Cancel //var result = ShowDialog(Buttons.SaveCancel, "changes have been made", "Save?"); //if (result == Save) { //var changesSaved = ViewModel.SaveChanges() && ViewModel.IsSessionValid(); //if (!changesSaved) { //ShowDialog(Buttons.OK, "Changes could not be saved..."); //canLeave = false; } } //else { //canLeave = false; } } return canLeave; } } }
#region License // // Copyright 2013 Steven Thuriot // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using Nova.Library.Actions; namespace Nova.Shell.Actions.Session { /// <summary> /// The session leave action /// </summary> public class SessionLeaveAction : LeaveAction<SessionView, SessionViewModel> { public override bool Leave() { if (!ViewModel.IsSessionValid()) { //Todo: Handle error state. } //if (!ViewModel.IsDirty) //{ // //Todo: Handle dirty state. //} return base.Leave(); } } }
mit
C#
7ccd3d5b5075ee08b5af727247ac25184f69ee9c
Make username password fields fit on Mac Chrome
yadyn/JabbR,borisyankov/JabbR,fuzeman/vox,LookLikeAPro/JabbR,fuzeman/vox,borisyankov/JabbR,LookLikeAPro/JabbR,18098924759/JabbR,CrankyTRex/JabbRMirror,lukehoban/JabbR,18098924759/JabbR,CrankyTRex/JabbRMirror,SonOfSam/JabbR,lukehoban/JabbR,timgranstrom/JabbR,ajayanandgit/JabbR,M-Zuber/JabbR,mzdv/JabbR,JabbR/JabbR,e10/JabbR,JabbR/JabbR,M-Zuber/JabbR,ajayanandgit/JabbR,timgranstrom/JabbR,lukehoban/JabbR,mzdv/JabbR,borisyankov/JabbR,CrankyTRex/JabbRMirror,yadyn/JabbR,e10/JabbR,LookLikeAPro/JabbR,SonOfSam/JabbR,fuzeman/vox,yadyn/JabbR
JabbR/Views/Account/_username.cshtml
JabbR/Views/Account/_username.cshtml
@using JabbR; <form class="form-horizontal" action="@Url.Content("~/account/login")" method="post"> @Html.ValidationSummary() <div class="control-group"> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-user"></i></span> @Html.TextBox("username", "span10", "Username") </div> </div> </div> <div class="control-group"> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-lock"></i></span> @Html.Password("password", "span10", "Password") </div> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn">Sign in</button> </div> </div> @if (Model) { <div class="control-group"> <div class="controls"> <a href="@Url.Content("~/account/register")">Register</a> if you don't have an account. </div> </div> } @Html.AntiForgeryToken() </form>
@using JabbR; <form class="form-horizontal" action="@Url.Content("~/account/login")" method="post"> @Html.ValidationSummary() <div class="control-group"> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-user"></i></span> @Html.TextBox("username", "input-block-level", "Username") </div> </div> </div> <div class="control-group"> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-lock"></i></span> @Html.Password("password", "input-block-level", "Password") </div> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn">Sign in</button> </div> </div> @if (Model) { <div class="control-group"> <div class="controls"> <a href="@Url.Content("~/account/register")">Register</a> if you don't have an account. </div> </div> } @Html.AntiForgeryToken() </form>
mit
C#
67626b723932f12b0031f236fa1e72280a57bbe4
Remove obsolete field.
Zoxive/libgit2sharp,PKRoma/libgit2sharp,red-gate/libgit2sharp,Zoxive/libgit2sharp,libgit2/libgit2sharp,red-gate/libgit2sharp
LibGit2Sharp/Core/GitCloneOptions.cs
LibGit2Sharp/Core/GitCloneOptions.cs
using System; using System.Runtime.InteropServices; namespace LibGit2Sharp.Core { internal enum GitCloneLocal { CloneLocalAuto, CloneLocal, CloneNoLocal, CloneLocalNoLinks } [StructLayout(LayoutKind.Sequential)] internal struct GitCloneOptions { public uint Version; public GitCheckoutOpts CheckoutOpts; public GitFetchOptions FetchOpts; public int Bare; public GitCloneLocal Local; public IntPtr CheckoutBranch; public IntPtr RepositoryCb; public IntPtr RepositoryCbPayload; public IntPtr RemoteCb; public IntPtr RemoteCbPayload; } }
using System; using System.Runtime.InteropServices; namespace LibGit2Sharp.Core { internal enum GitCloneLocal { CloneLocalAuto, CloneLocal, CloneNoLocal, CloneLocalNoLinks } [StructLayout(LayoutKind.Sequential)] internal struct GitCloneOptions { public uint Version; public GitCheckoutOpts CheckoutOpts; public GitFetchOptions FetchOpts; public int Bare; public GitCloneLocal Local; public IntPtr CheckoutBranch; public IntPtr signature; // Really a SignatureSafeHandle public IntPtr RepositoryCb; public IntPtr RepositoryCbPayload; public IntPtr RemoteCb; public IntPtr RemoteCbPayload; } }
mit
C#
013b9079f356856c1f60d28525e716da5005d302
Update DictionaryExtensions.cs
REALTOBIZ/LiteDB,prepare/LiteDB,prepare/LiteDB,masterdidoo/LiteDB,Skysper/LiteDB,89sos98/LiteDB,89sos98/LiteDB,prepare/LiteDB,falahati/LiteDB,prepare/LiteDB,mbdavid/LiteDB,masterdidoo/LiteDB,guslubudus/LiteDB,kbdavis07/LiteDB,Xicy/LiteDB,RytisLT/LiteDB,falahati/LiteDB,tbdbj/LiteDB,RytisLT/LiteDB,icelty/LiteDB
LiteDB/Utils/DictionaryExtensions.cs
LiteDB/Utils/DictionaryExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; namespace LiteDB { internal static class DictionaryExtensions { public static ushort NextIndex<T>(this Dictionary<ushort, T> dict) { ushort next = 0; while (dict.ContainsKey(next)) { next++; } return next; } public static object Get(this Dictionary<string, object> dict, string name) { object res; if (dict.TryGetValue(name, out res)) return res; return null; } public static BsonValue Get(this Dictionary<string, BsonValue> dict, string name) { BsonValue res; if (dict.TryGetValue(name, out res)) return res; return BsonValue.Null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; namespace LiteDB { internal static class DictionaryExtensions { public static ushort NextIndex<T>(this Dictionary<ushort, T> dict) { ushort next = 0; while (dict.ContainsKey(next)) { next++; } return next; } public static object Get(this Dictionary<string, object> dict, string name) { return dict.ContainsKey(name) ? dict[name] : null; } public static BsonValue Get(this Dictionary<string, BsonValue> dict, string name) { return dict.ContainsKey(name) ? dict[name] : BsonValue.Null; } } }
mit
C#
653726a40ae4ed0b54c32262dbc7bb86fd22c6ad
fix the SDK build for real this time. the missing macros weren't declared in the proper order last time.
ND-3500/platform_manifest,knone1/platform_manifest,xorware/android_build,xorware/android_build,xorware/android_build,RR-msm7x30/platform_manifest,hagar006/platform_manifest,pranav01/platform_manifest,xorware/android_build,see4ri/lolili,xorware/android_build,fallouttester/platform_manifest,Hybrid-Power/startsync
tools/droiddoc/templates/customization.cs
tools/droiddoc/templates/customization.cs
<?cs # This default template file is meant to be replaced. ?> <?cs # Use the -templatedir arg to javadoc to set your own directory with a ?> <?cs # replacement for this file in it. ?> <?cs def:default_search_box() ?><?cs /def ?> <?cs def:default_left_nav() ?><?cs /def ?> <?cs # appears at the top of every page ?><?cs def:custom_masthead() ?> <div id="header"> <div id="headerLeft"> <a href="<?cs var:toroot ?>index.html" tabindex="-1"><?cs var:page.title ?></a> </div> <div id="headerRight"> <?cs if:!online-pdk ?> <?cs call:default_search_box() ?> <?cs /if ?> </div><!-- headerRight --> </div><!-- header --><?cs /def ?> <?cs # appear at the bottom of every page ?> <?cs def:custom_copyright() ?><?cs /def ?> <?cs def:custom_cc_copyright() ?><?cs /def ?> <?cs def:custom_footerlinks() ?><?cs /def ?> <?cs def:custom_buildinfo() ?>Build <?cs var:page.build ?> - <?cs var:page.now ?><?cs /def ?> <?cs # appears on the side of the page ?> <?cs def:custom_left_nav() ?><?cs call:default_left_nav() ?><?cs /def ?>
<?cs # This default template file is meant to be replaced. ?> <?cs # Use the -templatedir arg to javadoc to set your own directory with a ?> <?cs # replacement for this file in it. ?> <?cs # appears at the top of every page ?><?cs def:custom_masthead() ?> <div id="header"> <div id="headerLeft"> <a href="<?cs var:toroot ?>index.html" tabindex="-1"><?cs var:page.title ?></a> </div> <div id="headerRight"> <?cs if:!online-pdk ?> <?cs call:default_search_box() ?> <?cs /if ?> </div><!-- headerRight --> </div><!-- header --><?cs /def ?> <?cs # appear at the bottom of every page ?> <?cs def:custom_copyright() ?><?cs /def ?> <?cs def:custom_cc_copyright() ?><?cs /def ?> <?cs def:custom_footerlinks() ?><?cs /def ?> <?cs def:custom_buildinfo() ?>Build <?cs var:page.build ?> - <?cs var:page.now ?><?cs /def ?> <?cs # appears on the side of the page ?> <?cs def:custom_left_nav() ?><?cs call:default_left_nav() ?><?cs /def ?> <?cs def:default_search_box() ?><?cs /def ?> <?cs def:default_left_nav() ?><?cs /def ?>
mit
C#
5d2fe8733997295bbbecee0cdbc947440e305d06
Use empty hit windows for spinner ticks
NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new
osu.Game.Rulesets.Osu/Objects/SpinnerTick.cs
osu.Game.Rulesets.Osu/Objects/SpinnerTick.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Audio; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { public class SpinnerTick : OsuHitObject { public SpinnerTick() { Samples.Add(new HitSampleInfo { Name = "spinnerbonus" }); } public override Judgement CreateJudgement() => new OsuSpinnerTickJudgement(); protected override HitWindows CreateHitWindows() => HitWindows.Empty; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Audio; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { public class SpinnerTick : OsuHitObject { public SpinnerTick() { Samples.Add(new HitSampleInfo { Name = "spinnerbonus" }); } public override Judgement CreateJudgement() => new OsuSpinnerTickJudgement(); protected override HitWindows CreateHitWindows() => null; } }
mit
C#
e7d04564545cb4fe87d04add0792d6d14c1284c6
Add SpinnerNoBlink to LegacySettings
peppy/osu,UselessToucan/osu,peppy/osu,peppy/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu
osu.Game/Skinning/LegacySkinConfiguration.cs
osu.Game/Skinning/LegacySkinConfiguration.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.Game.Skinning { public class LegacySkinConfiguration : SkinConfiguration { public const decimal LATEST_VERSION = 2.7m; /// <summary> /// Legacy version of this skin. /// </summary> public decimal? LegacyVersion { get; internal set; } public enum LegacySetting { Version, ComboPrefix, ComboOverlap, AnimationFramerate, LayeredHitSounds, SpinnerNoBlink } } }
// 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.Game.Skinning { public class LegacySkinConfiguration : SkinConfiguration { public const decimal LATEST_VERSION = 2.7m; /// <summary> /// Legacy version of this skin. /// </summary> public decimal? LegacyVersion { get; internal set; } public enum LegacySetting { Version, ComboPrefix, ComboOverlap, AnimationFramerate, LayeredHitSounds, } } }
mit
C#
c0c8448f385483479f7e75a52255c10c7b7b9951
Fix TestGetPlaylistFormats after adding more extensions to the PlaylistReaderFactory
Zeugma440/atldotnet
ATL.test/FactoryTest.cs
ATL.test/FactoryTest.cs
using System; using ATL.AudioReaders; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text; namespace ATL.test { [TestClass] public class FactoryTest { [TestMethod] public void TestGetPlaylistFormats() { StringBuilder filter = new StringBuilder(""); foreach (Format f in ATL.PlaylistReaders.PlaylistReaderFactory.GetInstance().getFormats()) { if (f.Readable) { foreach (String extension in f) { filter.Append(extension).Append(";"); } } } // Removes the last separator filter.Remove(filter.Length - 1, 1); Assert.AreEqual(".PLS;.M3U;.M3U8;.FPL;.XSPF;.SMIL;.SMI;.ZPL;.WPL;.ASX;.WAX;.WVX;.B4S", filter.ToString()); } } }
using System; using ATL.AudioReaders; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text; namespace ATL.test { [TestClass] public class FactoryTest { [TestMethod] public void TestGetPlaylistFormats() { StringBuilder filter = new StringBuilder(""); foreach (Format f in ATL.PlaylistReaders.PlaylistReaderFactory.GetInstance().getFormats()) { if (f.Readable) { foreach (String extension in f) { filter.Append(extension).Append(";"); } } } // Removes the last separator filter.Remove(filter.Length - 1, 1); Assert.AreEqual(".PLS;.M3U;.M3U8;.FPL;.XSPF;.SMIL;.SMI;.ASX;.WAX;.WVX;.B4S", filter.ToString()); } } }
mit
C#
62ba0fea885b1480c4640cae99313b42d1646ca3
Add comment
60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope
QueueDataGraphic/QueueDataGraphic/CSharpFiles/QueueDataGraphic.cs
QueueDataGraphic/QueueDataGraphic/CSharpFiles/QueueDataGraphic.cs
/******************************************************************** * Develop by Jimmy Hu * * This program is licensed under the Apache License 2.0. * * QueueDataGraphic.cs * * 本檔案用於佇列資料繪圖功能 * ******************************************************************** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QueueDataGraphic.CSharpFiles { // namespace start, 進入命名空間 class QueueDataGraphic // QueueDataGraphic class, QueueDataGraphic類別 { // QueueDataGraphic class start, 進入QueueDataGraphic類別 List<DataQueue> DataQueueList; // DataQueueList object, DataQueueList物件 } // QueueDataGraphic class end, 結束QueueDataGraphic類別 } // namespace end, 結束命名空間
/******************************************************************** * Develop by Jimmy Hu * * This program is licensed under the Apache License 2.0. * * QueueDataGraphic.cs * * 本檔案用於佇列資料繪圖功能 * ******************************************************************** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QueueDataGraphic.CSharpFiles { // namespace start, 進入命名空間 class QueueDataGraphic // QueueDataGraphic class, QueueDataGraphic類別 { // QueueDataGraphic class start, 進入QueueDataGraphic類別 List<DataQueue> DataQueueList; // } // QueueDataGraphic class end, 結束QueueDataGraphic類別 } // namespace end, 結束命名空間
apache-2.0
C#
c9ace219da5b0bcff7af2be2acbebd2ab936ab0c
Update AutofacCompositionRootSetupBase.cs
tiksn/TIKSN-Framework
TIKSN.Core/DependencyInjection/AutofacCompositionRootSetupBase.cs
TIKSN.Core/DependencyInjection/AutofacCompositionRootSetupBase.cs
using System; using System.Collections.Generic; using Autofac; using Autofac.Core; using Autofac.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using TIKSN.PowerShell; namespace TIKSN.DependencyInjection { public abstract class AutofacCompositionRootSetupBase : CompositionRootSetupBase { protected AutofacCompositionRootSetupBase(IConfigurationRoot configurationRoot) : base(configurationRoot) { } public IContainer CreateContainer() { var container = this.CreateContainerInternal(); var serviceProvider = new AutofacServiceProvider(container); ValidateOptions(this._services.Value, serviceProvider); return container; } protected abstract void ConfigureContainerBuilder(ContainerBuilder builder); protected IContainer CreateContainerInternal() { var builder = new ContainerBuilder(); builder.Populate(this._services.Value); foreach (var module in this.GetAutofacModules()) { _ = builder.RegisterModule(module); } this.ConfigureContainerBuilder(builder); return builder.Build(); } protected override IServiceProvider CreateServiceProviderInternal() => new AutofacServiceProvider(this.CreateContainerInternal()); protected virtual IEnumerable<IModule> GetAutofacModules() { yield return new CoreModule(); yield return new PowerShellModule(); } } }
using System; using System.Collections.Generic; using Autofac; using Autofac.Core; using Autofac.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using TIKSN.PowerShell; namespace TIKSN.DependencyInjection { public abstract class AutofacCompositionRootSetupBase : CompositionRootSetupBase { protected AutofacCompositionRootSetupBase(IConfigurationRoot configurationRoot) : base(configurationRoot) { } public IContainer CreateContainer() { var container = this.CreateContainerInternal(); var serviceProvider = new AutofacServiceProvider(container); this.ValidateOptions(this._services.Value, serviceProvider); return container; } protected abstract void ConfigureContainerBuilder(ContainerBuilder builder); protected IContainer CreateContainerInternal() { var builder = new ContainerBuilder(); builder.Populate(this._services.Value); foreach (var module in this.GetAutofacModules()) { builder.RegisterModule(module); } this.ConfigureContainerBuilder(builder); return builder.Build(); } protected override IServiceProvider CreateServiceProviderInternal() => new AutofacServiceProvider(this.CreateContainerInternal()); protected virtual IEnumerable<IModule> GetAutofacModules() { yield return new CoreModule(); yield return new PowerShellModule(); } } }
mit
C#
6a0628b2c05e54da39e0a4cbe961fa9b7d0bc3fe
fix distributos view
jmirancid/TropicalNet.Topppro,jmirancid/TropicalNet.Topppro,jmirancid/TropicalNet.Topppro
Topppro.WebSite/Views/Distributor/DisplayTemplates/Country.cshtml
Topppro.WebSite/Views/Distributor/DisplayTemplates/Country.cshtml
@using Topppro.WebSite.Extensions @model Topppro.Entities.Country <div class="country-group"> <h2>@Model.Name</h2> <hr class="bg-green" /> <br /> @Html.DisplayFor(m => m.Distributors) <br /> </div>
@using Topppro.WebSite.Extensions @model Topppro.Entities.Country <div class="country-group"> <h2>@Model.Name</h2> <hr class="bg-green" /> <br /> @Html.DisplayFor(m => m.Distributor) <br /> </div>
mit
C#
98c7f6fb896089f2a59370bd7cf80e93b50dc04f
fix in Enemy Pathfinding
daltonbr/TopDownShooter
Assets/Scripts/Enemy.cs
Assets/Scripts/Enemy.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; [RequireComponent (typeof(NavMeshAgent))] public class Enemy : MonoBehaviour { NavMeshAgent pathfinder; Transform target; void Start () { pathfinder = GetComponent<NavMeshAgent>(); target = GameObject.FindGameObjectWithTag("Player").transform; StartCoroutine(UpdatePath ()); } IEnumerator UpdatePath() { float refreshRate = 0.25f; while (target != null) { Vector3 targetPosition = new Vector3(target.position.x, 0, target.position.z); pathfinder.SetDestination (targetPosition); yield return new WaitForSeconds(refreshRate); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; [RequireComponent (typeof(NavMeshAgent))] public class Enemy : MonoBehaviour { NavMeshAgent pathfinder; Transform target; void Start () { pathfinder = GetComponent<NavMeshAgent>(); target = GameObject.FindGameObjectWithTag("Player").transform; StartCoroutine(UpdatePath ()); } IEnumerator UpdatePath() { float refreshRate = 0.25f; while (target != null) { Vector3 targePosition = new Vector3(target.position.x, 0, target.position.z); pathfinder.SetDestination (target.position); yield return new WaitForSeconds(refreshRate); } } }
mit
C#
084bb9086c42e4ca6472768e2170d15ce1751a38
add ini tests
Pavuucek/ArachNGIN,Pavuucek/ArachNGIN
Tests/Files/Settings/IniTests.cs
Tests/Files/Settings/IniTests.cs
using ArachNGIN.Files.Settings; using Microsoft.VisualStudio.TestTools.UnitTesting; using Shouldly; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace ArachNGIN.Tests.Files.Settings { [TestClass] public class IniTests { private Ini ini = new Ini("inifile.ini"); [TestMethod] public void WriteAndReadString() { ini.WriteString("section 1", "string 1", "value 1"); ini.ReadString("section 1", "string 1", "This is incorrect default value").ShouldBe("value 1"); ini.ReadString("section 1", "string 1").ShouldBe("value 1"); } [TestMethod] public void WriteAndReadBool() { ini.WriteBool("section 2", "bool 1", false); ini.WriteBool("section 2", "bool 2", true); ini.ReadBool("section 2", "bool 2").ShouldBeTrue(); ini.ReadBool("section 2", "bool 1", true).ShouldBeFalse(); } [TestMethod] public void WriteAndReadInteger() { for (int i = 0; i < 20; i++) { ini.WriteInteger("section 3", "integer " + i, i); } for (int i = 20 - 1; i >= 0; i--) { ini.ReadInteger("section 3", "integer " + i).ShouldBe(i); } } [TestMethod] public void WriteAndReadColor() { var i = 1; foreach (KnownColor knownColor in Enum.GetValues(typeof(KnownColor))) { ini.WriteColor("section 4", "color " + i, Color.FromKnownColor(knownColor)); ini.ReadColor("section 4", "color " + i).ShouldBe(Color.FromKnownColor(knownColor)); i++; } var c = Color.FromArgb(250, 252, 253, 255); ini.WriteColor("section 4", "color 0", c); Console.WriteLine(ColorTranslator.ToHtml(c)); ini.ReadColor("section 4", "color 0", Color.Black).ShouldBe(c); } [TestMethod] public void ReadSection() { ini.WriteString("section 5", "string 1", "valueeeee"); ini.ReadSection("section 5").ShouldNotBeNullOrWhiteSpace(); var s = ini.ReadSectionToArray("section 5"); s.ShouldNotBeNull(); s.ShouldNotBeEmpty(); } [TestMethod] public void SectionNamesShouldContainASectionName() { ini.WriteString("section 6", "string 1", "valueeeee"); ini.SectionNames().Contains("section 6").ShouldBeTrue(); ini.SectionNames().Contains("section 6 a").ShouldBeFalse(); } [TestMethod] public void DeleteSectionShouldWork() { ini.WriteString("section 7", "string 1", "valueeeee"); ini.SectionNames().Contains("section 7").ShouldBeTrue(); ini.DeleteSection("section 7"); ini.SectionNames().Contains("section 7").ShouldBeFalse(); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ArachNGIN.Tests.Files.Settings { [TestClass] public class IniTests { [TestMethod] public void WriteAndReadString() { } } }
mit
C#
6cefa61db2649152eca3a42704a57dbd130d1101
Add 'AssemblyVersion' property
whampson/bft-spec,whampson/cascara
Cascara/AssemblyInfo.cs
Cascara/AssemblyInfo.cs
#region License /* Copyright (c) 2017 Wes Hampson * * 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. */ #endregion using System; using System.Reflection; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Cascara.Tests")] namespace WHampson.Cascara { internal static class AssemblyInfo { internal static Version AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version; } } } }
#region License /* Copyright (c) 2017 Wes Hampson * * 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. */ #endregion using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Cascara.Tests")]
mit
C#
7ee0eaaa29fd5f090f9d2a479f465c7ac644996e
update year
RapidScada/scada,RapidScada/scada,RapidScada/scada,RapidScada/scada
ScadaAdmin/ScadaAdmin/Properties/AssemblyInfo.cs
ScadaAdmin/ScadaAdmin/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SCADA-Administrator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Rapid SCADA")] [assembly: AssemblyCopyright("Copyright © 2010-2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0d7b887e-d812-41ff-a679-6b7c28da739f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.0.0.0")] [assembly: AssemblyFileVersion("5.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SCADA-Administrator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Rapid SCADA")] [assembly: AssemblyCopyright("Copyright © 2010-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("0d7b887e-d812-41ff-a679-6b7c28da739f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.0.0.0")] [assembly: AssemblyFileVersion("5.0.0.0")]
apache-2.0
C#
af30275d6e61dfff6c3579d63218955f8104f760
Fix iOS cache folder path
CIR2000/Amica.vNext.SimpleCache
SimpleCache.iOS/SqliteObjectCache.cs
SimpleCache.iOS/SqliteObjectCache.cs
using System; using System.IO; using Amica.vNext; [assembly: Xamarin.Forms.Dependency(typeof(SqliteObjectCache))] namespace Amica.vNext { public class SqliteObjectCache : SqliteObjectCacheBase { protected override string GetDatabasePath() { const string sqliteFilename = "cache.db3"; var cacheFolder = Path.Combine(ApplicationName, "SimpleCache"); var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var cachePath = Path.Combine(documentsPath, cacheFolder); Directory.CreateDirectory(cachePath); return Path.Combine(cachePath, sqliteFilename); } } }
using System; using System.IO; namespace Amica.vNext { public class SqliteObjectCache : SqliteObjectCacheBase { protected override string GetDatabasePath() { const string sqliteFilename = "cache.db3"; var cacheFolder = Path.Combine(ApplicationName, "SimpleCache"); var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var cachePath = Path.Combine(documentsPath, "..", "Library", cacheFolder); Directory.CreateDirectory(cachePath); return Path.Combine(cachePath, sqliteFilename); } } }
bsd-3-clause
C#
566c1bad51fcbdb81b6bf6bec578cf36f74e9ae3
Increase version number
majorsilence/AddCsClass
src/AddCsClass/Properties/AssemblyInfo.cs
src/AddCsClass/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("AddCsClass")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AddCsClass")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7a42dac4-7656-4ee2-84bd-2ab1307bcd52")] // 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.1")]
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("AddCsClass")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AddCsClass")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7a42dac4-7656-4ee2-84bd-2ab1307bcd52")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
c1902565ea2a99abd9905834053e32828e761252
modify the route to display username and date
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Http/samples/MinimalSample/Program.cs
src/Http/samples/MinimalSample/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Mvc; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } string Plaintext() => "Hello, World!"; app.MapGet("/plaintext", Plaintext); app.MapGet("/", () => $""" Operating System: {Environment.OSVersion} .NET version: {Environment.Version} Username: {Environment.UserName} Date and Time: {DateTime.Now} """); var nestedGroup = app.MapGroup("/group/{groupName}") .MapGroup("/nested/{nestedName}") .WithTags("nested"); nestedGroup .MapGet("/", (string groupName, string nestedName) => { return $"Hello from {groupName}:{nestedName}!"; }); object Json() => new { message = "Hello, World!" }; app.MapGet("/json", Json).WithTags("json"); string SayHello(string name) => $"Hello, {name}!"; app.MapGet("/hello/{name}", SayHello); app.MapGet("/null-result", IResult () => null); app.MapGet("/todo/{id}", Results<Ok<Todo>, NotFound, BadRequest> (int id) => id switch { <= 0 => TypedResults.BadRequest(), >= 1 and <= 10 => TypedResults.Ok(new Todo(id, "Walk the dog")), _ => TypedResults.NotFound() }); var extensions = new Dictionary<string, object>() { { "traceId", "traceId123" } }; var errors = new Dictionary<string, string[]>() { { "Title", new[] { "The Title field is required." } } }; app.MapGet("/problem/{problemType}", (string problemType) => problemType switch { "plain" => Results.Problem(statusCode: 500, extensions: extensions), "object" => Results.Problem(new ProblemDetails() { Status = 500, Extensions = { { "traceId", "traceId123" } } }), "validation" => Results.ValidationProblem(errors, statusCode: 400, extensions: extensions), "objectValidation" => Results.Problem(new HttpValidationProblemDetails(errors) { Status = 400, Extensions = { { "traceId", "traceId123" } } }), "validationTyped" => TypedResults.ValidationProblem(errors, extensions: extensions), _ => TypedResults.NotFound() }); app.Run(); internal record Todo(int Id, string Title);
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Mvc; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } string Plaintext() => "Hello, World!"; app.MapGet("/plaintext", Plaintext); var message = $""" Operating System: {Environment.OSVersion} .NET version: {Environment.Version} """; app.MapGet("/", () => message); var nestedGroup = app.MapGroup("/group/{groupName}") .MapGroup("/nested/{nestedName}") .WithTags("nested"); nestedGroup .MapGet("/", (string groupName, string nestedName) => { return $"Hello from {groupName}:{nestedName}!"; }); object Json() => new { message = "Hello, World!" }; app.MapGet("/json", Json).WithTags("json"); string SayHello(string name) => $"Hello, {name}!"; app.MapGet("/hello/{name}", SayHello); app.MapGet("/null-result", IResult () => null); app.MapGet("/todo/{id}", Results<Ok<Todo>, NotFound, BadRequest> (int id) => id switch { <= 0 => TypedResults.BadRequest(), >= 1 and <= 10 => TypedResults.Ok(new Todo(id, "Walk the dog")), _ => TypedResults.NotFound() }); var extensions = new Dictionary<string, object>() { { "traceId", "traceId123" } }; var errors = new Dictionary<string, string[]>() { { "Title", new[] { "The Title field is required." } } }; app.MapGet("/problem/{problemType}", (string problemType) => problemType switch { "plain" => Results.Problem(statusCode: 500, extensions: extensions), "object" => Results.Problem(new ProblemDetails() { Status = 500, Extensions = { { "traceId", "traceId123" } } }), "validation" => Results.ValidationProblem(errors, statusCode: 400, extensions: extensions), "objectValidation" => Results.Problem(new HttpValidationProblemDetails(errors) { Status = 400, Extensions = { { "traceId", "traceId123" } } }), "validationTyped" => TypedResults.ValidationProblem(errors, extensions: extensions), _ => TypedResults.NotFound() }); app.Run(); internal record Todo(int Id, string Title);
apache-2.0
C#
fbaff9c2a12aeff3c3ff0f15b812ee2aa5a4b038
Add .NET Standard 2.0 assembly to ReferenceFinder (#22)
Fody/Janitor
Fody/ReferenceFinder.cs
Fody/ReferenceFinder.cs
using System.Collections.Generic; using System.Linq; using Mono.Cecil; public partial class ModuleWeaver { public void FindCoreReferences() { List<TypeDefinition> types = new List<TypeDefinition>(); AddAssemblyIfExists("mscorlib", types); AddAssemblyIfExists("System.Runtime", types); AddAssemblyIfExists("System.Threading", types); AddAssemblyIfExists("netstandard", types); ObjectFinalizeReference = ModuleDefinition.ImportReference(ModuleDefinition.TypeSystem.Object.Resolve().Find("Finalize")); var gcTypeDefinition = types.First(x => x.Name == "GC"); SuppressFinalizeMethodReference = ModuleDefinition.ImportReference(gcTypeDefinition.Find("SuppressFinalize", "Object")); var iDisposableTypeDefinition = types.First(x => x.Name == "IDisposable"); DisposeMethodReference = ModuleDefinition.ImportReference(iDisposableTypeDefinition.Find("Dispose")); var interlockedTypeDefinition = types.First(x => x.Name == "Interlocked"); ExchangeIntMethodReference = ModuleDefinition.ImportReference(interlockedTypeDefinition.Find("Exchange", "Int32&", "Int32")); ExchangeTMethodReference = ModuleDefinition.ImportReference(interlockedTypeDefinition.Find("Exchange", "T&", "T")); var exceptionTypeDefinition = types.First(x => x.Name == "ObjectDisposedException"); ExceptionConstructorReference = ModuleDefinition.ImportReference(exceptionTypeDefinition.Find(".ctor", "String")); } void AddAssemblyIfExists(string name, List<TypeDefinition> types) { var msCoreLibDefinition = ModuleDefinition.AssemblyResolver.Resolve(new AssemblyNameReference(name, null)); if (msCoreLibDefinition != null) { types.AddRange(msCoreLibDefinition.MainModule.Types); } } public MethodReference ExchangeIntMethodReference; public MethodReference ExchangeTMethodReference; public MethodReference SuppressFinalizeMethodReference; public MethodReference ObjectFinalizeReference; public MethodReference DisposeMethodReference; public MethodReference ExceptionConstructorReference; }
using System.Collections.Generic; using System.Linq; using Mono.Cecil; public partial class ModuleWeaver { public void FindCoreReferences() { List<TypeDefinition> types = new List<TypeDefinition>(); AddAssemblyIfExists("mscorlib", types); AddAssemblyIfExists("System.Runtime", types); AddAssemblyIfExists("System.Threading", types); ObjectFinalizeReference = ModuleDefinition.ImportReference(ModuleDefinition.TypeSystem.Object.Resolve().Find("Finalize")); var gcTypeDefinition = types.First(x => x.Name == "GC"); SuppressFinalizeMethodReference = ModuleDefinition.ImportReference(gcTypeDefinition.Find("SuppressFinalize", "Object")); var iDisposableTypeDefinition = types.First(x => x.Name == "IDisposable"); DisposeMethodReference = ModuleDefinition.ImportReference(iDisposableTypeDefinition.Find("Dispose")); var interlockedTypeDefinition = types.First(x => x.Name == "Interlocked"); ExchangeIntMethodReference = ModuleDefinition.ImportReference(interlockedTypeDefinition.Find("Exchange", "Int32&", "Int32")); ExchangeTMethodReference = ModuleDefinition.ImportReference(interlockedTypeDefinition.Find("Exchange", "T&", "T")); var exceptionTypeDefinition = types.First(x => x.Name == "ObjectDisposedException"); ExceptionConstructorReference = ModuleDefinition.ImportReference(exceptionTypeDefinition.Find(".ctor", "String")); } void AddAssemblyIfExists(string name, List<TypeDefinition> types) { var msCoreLibDefinition = ModuleDefinition.AssemblyResolver.Resolve(new AssemblyNameReference(name, null)); if (msCoreLibDefinition != null) { types.AddRange(msCoreLibDefinition.MainModule.Types); } } public MethodReference ExchangeIntMethodReference; public MethodReference ExchangeTMethodReference; public MethodReference SuppressFinalizeMethodReference; public MethodReference ObjectFinalizeReference; public MethodReference DisposeMethodReference; public MethodReference ExceptionConstructorReference; }
mit
C#
9c7f2f0a8dcb0bad68c33ddb1348b064743618bf
Add API comments for Git Testing ;)
thedersen/UnityAutoMoq,thedersen/UnityAutoMoq,Henadz/UnityAutoMoq,Henadz/UnityAutoMoq,thedersen/UnityAutoMoq,azarkevich/UnityAutoMoq,azarkevich/UnityAutoMoq,azarkevich/UnityAutoMoq,Henadz/UnityAutoMoq
src/UnityAutoMoq/UnityAutoMoqExtension.cs
src/UnityAutoMoq/UnityAutoMoqExtension.cs
using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.ObjectBuilder; namespace UnityAutoMoq { /// <summary> /// Provide extensions for Unity Auto Moq /// </summary> public class UnityAutoMoqExtension : UnityContainerExtension { private readonly UnityAutoMoqContainer autoMoqContainer; public UnityAutoMoqExtension(UnityAutoMoqContainer autoMoqContainer) { this.autoMoqContainer = autoMoqContainer; } protected override void Initialize() { Context.Strategies.Add(new UnityAutoMoqBuilderStrategy(autoMoqContainer), UnityBuildStage.PreCreation); } } }
using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.ObjectBuilder; namespace UnityAutoMoq { public class UnityAutoMoqExtension : UnityContainerExtension { private readonly UnityAutoMoqContainer autoMoqContainer; public UnityAutoMoqExtension(UnityAutoMoqContainer autoMoqContainer) { this.autoMoqContainer = autoMoqContainer; } protected override void Initialize() { Context.Strategies.Add(new UnityAutoMoqBuilderStrategy(autoMoqContainer), UnityBuildStage.PreCreation); } } }
mit
C#