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
81e120eb8d423b684e53e73e3f241365c0c4cddd
remove PreSaving in LockeableEntity
AlejandroCano/framework,signumsoftware/framework,avifatal/framework,avifatal/framework,signumsoftware/framework,AlejandroCano/framework
Signum.Entities/Patterns/LockeableEntity.cs
Signum.Entities/Patterns/LockeableEntity.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Entities.Properties; using System.Linq.Expressions; using System.ComponentModel; using Signum.Utilities; namespace Signum.Entities.Patterns { [Serializable] public abstract class LockableEntity : Entity { bool locked; public bool Locked { get { return locked; } set { if (UnsafeSet(ref locked, value, () => Locked)) ItemLockedChanged(Locked); } } protected bool UnsafeSet<T>(ref T field, T value, Expression<Func<T>> property) { return base.Set<T>(ref field, value, property); } protected virtual void ItemLockedChanged(bool locked) { } protected override bool Set<T>(ref T field, T value, Expression<Func<T>> property) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; if (this.locked) throw new ApplicationException(Resources.AttemptToModifyLockedEntity0.Formato(this.ToString())); return base.Set<T>(ref field, value, property); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Entities.Properties; using System.Linq.Expressions; using System.ComponentModel; using Signum.Utilities; namespace Signum.Entities.Patterns { [Serializable] public abstract class LockableEntity : Entity { bool locked; public bool Locked { get { return locked; } set { if (UnsafeSet(ref locked, value, () => Locked)) ItemLockedChanged(Locked); } } protected bool UnsafeSet<T>(ref T field, T value, Expression<Func<T>> property) { return base.Set<T>(ref field, value, property); } protected virtual void ItemLockedChanged(bool locked) { } protected override bool Set<T>(ref T field, T value, Expression<Func<T>> property) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; if (this.locked) throw new ApplicationException( Resources.AttemptToModifyLockedEntity0.Formato(this.ToString())); return base.Set<T>(ref field, value, property); } protected internal override void PreSaving(ref bool graphModified) { UnsafeSet(ref toStr, ToString(), () => ToStr); } } }
mit
C#
794104c272c0a0a096f38f4acc0fd96fe6699869
Update Customer.cs
EzyWebwerkstaden/openpay-dotnet,open-pay/openpay-dotnet
Openpay/Entities/Customer.cs
Openpay/Entities/Customer.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Openpay.Entities { public class Customer : OpenpayResourceObject { [JsonProperty(PropertyName = "name")] public String Name { get; set; } [JsonProperty(PropertyName = "email")] public String Email { get; set; } [JsonProperty(PropertyName = "last_name")] public String LastName { get; set; } [JsonProperty(PropertyName = "phone_number")] public String PhoneNumber { get; set; } [JsonProperty(PropertyName = "address")] public Address Address { get; set; } [JsonProperty(PropertyName = "status")] public String Status { get; set; } [JsonProperty(PropertyName = "clabe")] public String CLABE { get; set; } [JsonProperty(PropertyName = "balance")] public Decimal Balance { get; set; } [JsonProperty(PropertyName = "creation_date")] public DateTime? CreationDate { get; set; } [JsonProperty(PropertyName = "requires_account")] public Boolean RequiresAccount { get; set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Openpay.Entities { public class Customer : OpenpayResourceObject { [JsonProperty(PropertyName = "name")] public String Name { get; set; } [JsonProperty(PropertyName = "email")] public String Email { get; set; } [JsonProperty(PropertyName = "last_name")] public String LastName { get; set; } [JsonProperty(PropertyName = "phone_number")] public String PhoneNumber { get; set; } [JsonProperty(PropertyName = "address")] public Address Address { get; set; } [JsonProperty(PropertyName = "status")] public String Status { get; set; } [JsonProperty(PropertyName = "clabe")] public String CLABE { get; set; } [JsonProperty(PropertyName = "balance")] public Decimal Balance { get; set; } [JsonProperty(PropertyName = "creation_date")] public DateTime? CreationDate { get; set; } } }
apache-2.0
C#
041cd2565e751c5680bd748c8d1c1d3e66aa77fe
Use Migrate instead of EnsureCreated for the sample app (these are mutually exclusive)
mrahhal/MR.AspNetCore.Jobs,mrahhal/MR.AspNetCore.Jobs
samples/Basic/Startup.cs
samples/Basic/Startup.cs
using Basic.Jobs; using Basic.Models; using Basic.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using MR.AspNetCore.Jobs; namespace Basic { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:Default"])); services.AddMvc(); services.AddJobs(options => { // Use the sql server adapter options.UseSqlServer(opts => { opts.ConnectionString = Configuration["ConnectionStrings:Default"]; // This is the default schema used. //opts.Schema = "Jobs"; }); // Use the cron jobs registry options.UseCronJobRegistry<BasicCronJobRegistry>(); // Configure the polling delay used when polling the storage (in seconds) options.PollingDelay = 10; }); // Add jobs to DI services.AddTransient<LogBlogCountJob>(); services.AddTransient<RetryableJob>(); // Services services.AddScoped<FooService>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); // Make sure the database is created first using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) { var provider = scope.ServiceProvider; provider.GetRequiredService<AppDbContext>().Database.Migrate(); } // Starts the processing server app.UseJobs(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using Basic.Jobs; using Basic.Models; using Basic.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using MR.AspNetCore.Jobs; namespace Basic { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:Default"])); services.AddMvc(); services.AddJobs(options => { // Use the sql server adapter options.UseSqlServer(opts => { opts.ConnectionString = Configuration["ConnectionStrings:Default"]; // This is the default schema used. //opts.Schema = "Jobs"; }); // Use the cron jobs registry options.UseCronJobRegistry<BasicCronJobRegistry>(); // Configure the polling delay used when polling the storage (in seconds) options.PollingDelay = 10; }); // Add jobs to DI services.AddTransient<LogBlogCountJob>(); services.AddTransient<RetryableJob>(); // Services services.AddScoped<FooService>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); // Make sure the database is created first using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) { var provider = scope.ServiceProvider; provider.GetRequiredService<AppDbContext>().Database.EnsureCreated(); } // Starts the processing server app.UseJobs(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
mit
C#
871b9c2f09582b211b56cce9c08d50c958660353
Remove dead code
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Microservices/ProcessBridge.cs
WalletWasabi/Microservices/ProcessBridge.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.Microservices { public class ProcessBridge : IProcessBridge { public ProcessBridge(string processPath) { ProcessPath = Guard.NotNullOrEmptyOrWhitespace(nameof(processPath), processPath); if (!File.Exists(ProcessPath)) { var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(ProcessPath); throw new FileNotFoundException($"{fileNameWithoutExtension} is not found.", ProcessPath); } } public string ProcessPath { get; } public Process Start(string arguments, bool openConsole) { var finalArguments = arguments; var redirectStandardOutput = !openConsole; var useShellExecute = openConsole; var createNoWindow = !openConsole; var windowStyle = openConsole ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden; if (openConsole && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new PlatformNotSupportedException($"{RuntimeInformation.OSDescription} is not supported."); } ProcessStartInfo startInfo = new ProcessStartInfo { FileName = ProcessPath, Arguments = finalArguments, RedirectStandardOutput = redirectStandardOutput, UseShellExecute = useShellExecute, CreateNoWindow = createNoWindow, WindowStyle = windowStyle }; try { return Process.Start(startInfo); } catch { Logger.LogInfo($"{nameof(startInfo.FileName)}: {startInfo.FileName}"); Logger.LogInfo($"{nameof(startInfo.Arguments)}: {startInfo.Arguments}"); Logger.LogInfo($"{nameof(startInfo.RedirectStandardOutput)}: {startInfo.RedirectStandardOutput}"); Logger.LogInfo($"{nameof(startInfo.UseShellExecute)}: {startInfo.UseShellExecute}"); Logger.LogInfo($"{nameof(startInfo.CreateNoWindow)}: {startInfo.CreateNoWindow}"); Logger.LogInfo($"{nameof(startInfo.WindowStyle)}: {startInfo.WindowStyle}"); throw; } } public async Task<(string response, int exitCode)> SendCommandAsync(string arguments, bool openConsole, CancellationToken cancel) { int exitCode; using var process = Start(arguments, openConsole); await process.WaitForExitAsync(cancel).ConfigureAwait(false); exitCode = process.ExitCode; string responseString = openConsole ? string.Empty : await process.StandardOutput.ReadToEndAsync().ConfigureAwait(false); return (responseString, exitCode); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.Microservices { public class ProcessBridge : IProcessBridge { public ProcessBridge(string processPath) { ProcessPath = Guard.NotNullOrEmptyOrWhitespace(nameof(processPath), processPath); if (!File.Exists(ProcessPath)) { var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(ProcessPath); throw new FileNotFoundException($"{fileNameWithoutExtension} is not found.", ProcessPath); } } public string ProcessPath { get; } public Process Start(string arguments, bool openConsole) { var finalArguments = arguments; var redirectStandardOutput = !openConsole; var useShellExecute = openConsole; var createNoWindow = !openConsole; var windowStyle = openConsole ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden; if (openConsole && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new PlatformNotSupportedException($"{RuntimeInformation.OSDescription} is not supported."); //var escapedArguments = (hwiPath + " " + arguments).Replace("\"", "\\\""); //useShellExecute = false; //if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) //{ // fileName = "xterm"; // finalArguments = $"-e \"{escapedArguments}\""; //} //else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) //{ // fileName = "osascript"; // finalArguments = $"-e 'tell application \"Terminal\" to do script \"{escapedArguments}\"'"; //} } ProcessStartInfo startInfo = new ProcessStartInfo { FileName = ProcessPath, Arguments = finalArguments, RedirectStandardOutput = redirectStandardOutput, UseShellExecute = useShellExecute, CreateNoWindow = createNoWindow, WindowStyle = windowStyle }; try { return Process.Start(startInfo); } catch { Logger.LogInfo($"{nameof(startInfo.FileName)}: {startInfo.FileName}"); Logger.LogInfo($"{nameof(startInfo.Arguments)}: {startInfo.Arguments}"); Logger.LogInfo($"{nameof(startInfo.RedirectStandardOutput)}: {startInfo.RedirectStandardOutput}"); Logger.LogInfo($"{nameof(startInfo.UseShellExecute)}: {startInfo.UseShellExecute}"); Logger.LogInfo($"{nameof(startInfo.CreateNoWindow)}: {startInfo.CreateNoWindow}"); Logger.LogInfo($"{nameof(startInfo.WindowStyle)}: {startInfo.WindowStyle}"); throw; } } public async Task<(string response, int exitCode)> SendCommandAsync(string arguments, bool openConsole, CancellationToken cancel) { int exitCode; using var process = Start(arguments, openConsole); await process.WaitForExitAsync(cancel).ConfigureAwait(false); exitCode = process.ExitCode; string responseString = openConsole ? string.Empty : await process.StandardOutput.ReadToEndAsync().ConfigureAwait(false); return (responseString, exitCode); } } }
mit
C#
6410f01351a5921eec3c12790aef8c0ba865786b
Fix Consul tests (#7722)
dotnet/orleans,ibondy/orleans,ElanHasson/orleans,hoopsomuah/orleans,hoopsomuah/orleans,ibondy/orleans,ElanHasson/orleans,dotnet/orleans,galvesribeiro/orleans,waynemunro/orleans,waynemunro/orleans,galvesribeiro/orleans
test/Extensions/Consul.Tests/ConsulTestUtils.cs
test/Extensions/Consul.Tests/ConsulTestUtils.cs
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using TestExtensions; using Xunit; namespace Consul.Tests { public static class ConsulTestUtils { public static readonly string ConsulConnectionString = TestDefaultConfiguration.ConsulConnectionString; private static readonly Lazy<bool> EnsureConsulLazy = new Lazy<bool>(() => EnsureConsulAsync().Result); public static void EnsureConsul() { if (!EnsureConsulLazy.Value) throw new SkipException("Consul cluster isn't running"); } public static async Task<bool> EnsureConsulAsync() { if (string.IsNullOrWhiteSpace(ConsulConnectionString)) { return false; } try { var client = new HttpClient(); client.Timeout = TimeSpan.FromSeconds(15); var response = await client.GetAsync($"{ConsulConnectionString}/v1/health/service/consul?pretty"); return response.StatusCode == HttpStatusCode.OK; } catch (HttpRequestException) { return false; } catch (OperationCanceledException) { return false; } } } }
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using TestExtensions; using Xunit; namespace Consul.Tests { public static class ConsulTestUtils { public static string ConsulConnectionString = TestDefaultConfiguration.ConsulConnectionString; private static readonly Lazy<bool> EnsureConsulLazy = new Lazy<bool>(() => EnsureConsulAsync().Result); public static void EnsureConsul() { if (!EnsureConsulLazy.Value) throw new SkipException("Consul cluster isn't running"); } public static async Task<bool> EnsureConsulAsync() { try { var client = new HttpClient(); client.Timeout = TimeSpan.FromSeconds(15); var response = await client.GetAsync($"{ConsulConnectionString}/v1/health/service/consul?pretty"); return response.StatusCode == HttpStatusCode.OK; } catch (HttpRequestException) { return false; } catch (OperationCanceledException) { return false; } } } }
mit
C#
541004d0950b4f48fb4a88b0f33e7e3cd79ca555
Update GlobalVariables.cs
UnityCommunity/UnityLibrary
Assets/Scripts/Utilities/GlobalVariables.cs
Assets/Scripts/Utilities/GlobalVariables.cs
using System.Collections.Generic; /// <summary> /// A simple static class to get and set globally accessible variables through a key-value approach. /// </summary> /// <remarks> /// <para>Uses a key-value approach (dictionary) for storing and modifying variables.</para> /// <para>It also uses a lock to ensure consistency between the threads.</para> /// </remarks> public static class GlobalVariables { private static readonly object lockObject = new object(); private static Dictionary<string, object> variablesDictionary = new Dictionary<string, object>(); /// <summary> /// The underlying key-value storage (dictionary). /// </summary> /// <value>Gets the underlying variables dictionary</value> public static Dictionary<string, object> VariablesDictionary => variablesDictionary; /// <summary> /// Retrieves all global variables. /// </summary> /// <returns>The global variables dictionary object.</returns> public static Dictionary<string, object> GetAll() { return variablesDictionary; } /// <summary> /// Gets a variable and casts it to the provided type argument. /// </summary> /// <typeparam name="T">The type of the variable</typeparam> /// <param name="key">The variable key</param> /// <returns>The casted variable value</returns> public static T Get<T>(string key) { if (variablesDictionary == null || !variablesDictionary.ContainsKey(key)) { return default(T); } return (T)variablesDictionary[key]; } /// <summary> /// Sets the variable, the existing value gets overridden. /// </summary> /// <remarks>It uses a lock under the hood to ensure consistensy between threads</remarks> /// <param name="key">The variable name/key</param> /// <param name="value">The variable value</param> public static void Set(string key, object value) { lock (lockObject) { if (variablesDictionary == null) { variablesDictionary = new Dictionary<string, object>(); } variablesDictionary[key] = value; } } }
using System.Collections.Generic; /// <summary> /// A simple static class to get and set globally accessible variables through a key-value approach. /// </summary> /// <remarks> /// <para>Uses a key-value approach (dictionary) for storing and modifying variables.</para> /// <para>It also uses a lock to ensure consistency between the threads.</para> /// </remarks> public static class GlobalVariables { private static readonly object lockObject = new object(); private static Dictionary<string, object> variablesDictionary = new Dictionary<string, object>(); /// <summary> /// The underlying key-value storage (dictionary). /// </summary> /// <value>Gets the underlying variables dictionary</value> public static Dictionary<string, object> VariablesDictionary => variablesDictionary; /// <summary> /// Retrieves all global variables. /// </summary> /// <returns>The global variables dictionary object.</returns> public static Dictionary<string, object> GetAll() { return variablesDictionary; } /// <summary> /// Gets a variable and casts it to the provided type argument. /// </summary> /// <typeparam name="T">The type of the variable</typeparam> /// <param name="key">The variable key</param> /// <returns>The casted variable value</returns> public static T Get<T>(string key) { if (variablesDictionary == null || !variablesDictionary.ContainsKey(key)) { return default(T); } return (T)variablesDictionary[key]; } /// <summary> /// Sets the variable, the existing value gets overridden. /// </summary> /// <remarks>It uses a lock under the hood to ensure consistensy between threads</remarks> /// <param name="key">The variable name/key</param> /// <param name="value">The variable value</param> public static void Set(string key, string value) { lock (lockObject) { if (variablesDictionary == null) { variablesDictionary = new Dictionary<string, object>(); } variablesDictionary[key] = value; } } }
mit
C#
08902fe2351767ab659f8afd2538bdaf367a63f4
remove typo
jcolebrand/hnb,jcolebrand/hnb
hnb/Views/Foster/Index.cshtml
hnb/Views/Foster/Index.cshtml
@section Title { <h2 class="title">Become part of our family!</h2> } <h3>Become a Hearts & Bones Foster!</h3> <p>Fosters are the lifeblood of rescue. Without fosters, dogs end up dying in shelters. Very literally, one additional foster is one additional life that we can save. If you have always wanted to foster but were not sure that you could commit to a dog long term, fostering is the best way to enjoy a shorter-term commitment. As we are an all-breed dog rescue, we have dogs of all ages, shapes, and sizes that are available. We value our foster homes very highly and appreciate you for considering fostering with us! </p> <p>Hearts & Bones Rescue is a low-stress, no-drama rescue. We value your time just like we value ours. If there is a problem, let us know right away so we can help you and your foster dog. We want you and your foster dog to be successful! Fosters are the biggest, most important part of rescue, and we have the utmost respect for people like you who are willing to open your hearts and home to animals in need. </p> <p>Interested in Fostering? <a href="mailto:info@heartsandbonesrescue.com">Email us to</a> get started! </p> <h4>Fostering 101:</h4> <ol> <li>Upon approval to foster, Hearts fosters join a closed group dedicated to our foster program. </li> <li>Dogs that are available to be fostered are posted in the group. Prior to committing to a dog, we provide as much information to you about the dogs that need fosters. Often times, information can be limited as we do not have much history on the dog. </li> <li>Hearts & Bones Rescue pays for ALL medical expenses for the dog.</li> </ol>
@section Title { <h2 class="title">Become part of our family!</h2> } <h3>Become a Hearts & Bones Foster!</h3> <p>Fosters are the lifeblood of rescue. Without fosters, dogs end up dying in shelters. Very literally, one additional foster is one additional life that we can save. If you have always wanted to foster but were not sure that you could commit to a dog long term, fostering is the best way to enjoy a shorter-term commitment. As we are an all-breed dog rescue, we have dogs of all ages, shapes, and sizes that are available. We value our foster homes very highly and appreciate you for considering fostering with us! </p> <p>Hearts & Bones Rescue is a low-stress, no-drama rescue. We value your time just like we value ours. If there is a problem, let us know right away so we can help you and your foster dog. We want you and your foster dog to be successful! Fosters are the biggest, most important part of rescue, and we have the utmost respect for people like you who are willing to open your hearts and home to animals in need. </p> <p>Interested in Fostering? <a href="mailto:info@heartsandbonesrescue.com">Email us to</a> get started! </p> <h4>Fostering 101:</h4> <ol> <li>Upon approval to foster, Hearts fosters join a closed group dedicated to our foster program. </li> <li>Dogs that are available to be fostered are posted in the group. Prior to committing to a dog, we provide as much information to you about the dogs that need fosters. Often times, information can be limited as we do not have much history on the dog. </li> <li>We will</li> <li>Hearts & Bones Rescue pays for ALL medical expenses for the dog.</li> </ol>
unlicense
C#
8b83d5238a167627237868d1e6f9a34942608e87
Update validation.cake
xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents
.ci/validation.cake
.ci/validation.cake
#addin nuget:?package=Xamarin.Nuget.Validator&version=1.1.1 using Xamarin.Nuget.Validator; // SECTION: Arguments and Settings var ROOT_DIR = (DirectoryPath)Argument ("root", "."); var ROOT_OUTPUT_DIR = ROOT_DIR.Combine ("output"); var PACKAGE_NAMESPACES = Argument ("n", Argument ("namespaces", "")) .Split (new [] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries) .ToList (); PACKAGE_NAMESPACES.AddRange (new [] { "Xamarin", }); // SECTION: Main Script Information (""); Information ("Script Arguments:"); Information (" Root directory: {0}", MakeAbsolute (ROOT_DIR)); Information (" Root output directory: {0}", ROOT_OUTPUT_DIR); Information (" Valid package namespaces: {0}", string.Join (", ", PACKAGE_NAMESPACES)); Information (""); // SECTION: Validate Output var options = new NugetValidatorOptions { Copyright = "© Microsoft Corporation. All rights reserved.", Author = "Microsoft", // Owner = "Microsoft", - No longer supported in nuspec: https://docs.microsoft.com/en-us/nuget/reference/msbuild-targets#pack-target NeedsProjectUrl = true, NeedsLicenseUrl = true, ValidateRequireLicenseAcceptance = true, ValidPackageNamespace = PACKAGE_NAMESPACES.ToArray (), }; var nupkgFiles = GetFiles (ROOT_OUTPUT_DIR + "/**/*.nupkg"); Information ("Found {0} NuGet packages to validate.", nupkgFiles.Count); var hasErrors = false; foreach (var nupkgFile in nupkgFiles) { Information ("Verifying NuGet metadata of {0}...", nupkgFile); var result = NugetValidator.Validate (nupkgFile.FullPath, options); if (result.Success) { Information ("NuGet metadata validation passed."); } else { Error ($"NuGet metadata validation failed for {nupkgFile}:"); Error (string.Join (Environment.NewLine + " ", result.ErrorMessages)); hasErrors = true; // Update DevOps Warning ($"##vso[task.logissue type=warning]NuGet metadata validation failed for {nupkgFile}."); } } if (hasErrors) throw new Exception ($"Invalid NuGet metadata found.");
#addin nuget:?package=Xamarin.Nuget.Validator&version=1.1.1 using Xamarin.Nuget.Validator; // SECTION: Arguments and Settings var ROOT_DIR = (DirectoryPath)Argument ("root", "."); var ROOT_OUTPUT_DIR = ROOT_DIR.Combine ("output"); var PACKAGE_NAMESPACES = Argument ("n", Argument ("namespaces", "")) .Split (new [] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries) .ToList (); PACKAGE_NAMESPACES.AddRange (new [] { "Xamarin", }); // SECTION: Main Script Information (""); Information ("Script Arguments:"); Information (" Root directory: {0}", MakeAbsolute (ROOT_DIR)); Information (" Root output directory: {0}", ROOT_OUTPUT_DIR); Information (" Valid package namespaces: {0}", string.Join (", ", PACKAGE_NAMESPACES)); Information (""); // SECTION: Validate Output var options = new NugetValidatorOptions { Copyright = "© Microsoft Corporation. All rights reserved.", Author = "Microsoft", Owner = "Microsoft", NeedsProjectUrl = true, NeedsLicenseUrl = true, ValidateRequireLicenseAcceptance = true, ValidPackageNamespace = PACKAGE_NAMESPACES.ToArray (), }; var nupkgFiles = GetFiles (ROOT_OUTPUT_DIR + "/**/*.nupkg"); Information ("Found {0} NuGet packages to validate.", nupkgFiles.Count); var hasErrors = false; foreach (var nupkgFile in nupkgFiles) { Information ("Verifying NuGet metadata of {0}...", nupkgFile); var result = NugetValidator.Validate (nupkgFile.FullPath, options); if (result.Success) { Information ("NuGet metadata validation passed."); } else { Error ($"NuGet metadata validation failed for {nupkgFile}:"); Error (string.Join (Environment.NewLine + " ", result.ErrorMessages)); hasErrors = true; // Update DevOps Warning ($"##vso[task.logissue type=warning]NuGet metadata validation failed for {nupkgFile}."); } } if (hasErrors) throw new Exception ($"Invalid NuGet metadata found.");
mit
C#
ce372f1615ea3f6f488bbab6a12fea1930159fc4
Increment minor -> 0.3.0
awseward/restivus
AssemblyInfo.sln.cs
AssemblyInfo.sln.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.3.0.0")] [assembly: AssemblyFileVersion("0.3.0.0")] [assembly: AssemblyInformationalVersion("0.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")] [assembly: AssemblyInformationalVersion("0.2.0")]
mit
C#
f4be1f589f67e67c43b09ce989187a172a86927a
Fix bulk alias unit tests
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/Indices/AliasManagement/Alias/Actions/IAliasAction.cs
src/Nest/Indices/AliasManagement/Alias/Actions/IAliasAction.cs
using Utf8Json; using Utf8Json.Internal; namespace Nest { /// <summary> /// Marker interface for alias operation /// </summary> [JsonFormatter(typeof(AliasActionFormatter))] public interface IAliasAction { } public class AliasActionFormatter : IJsonFormatter<IAliasAction> { private static readonly AutomataDictionary Actions = new AutomataDictionary { { "add", 0 }, { "remove", 1 }, { "remove_index", 2 }, }; public IAliasAction Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) { var token = reader.GetCurrentJsonToken(); if (token == JsonToken.Null) return null; var segment = reader.ReadNextBlockSegment(); var segmentReader = new JsonReader(segment.Array, segment.Offset); segmentReader.ReadIsBeginObjectWithVerify(); var action = segmentReader.ReadPropertyNameSegmentRaw(); IAliasAction aliasAction = null; segmentReader = new JsonReader(segment.Array, segment.Offset); if (Actions.TryGetValue(action, out var value)) { switch (value) { case 0: aliasAction = Deserialize<AliasAddAction>(ref segmentReader, formatterResolver); break; case 1: aliasAction = Deserialize<AliasRemoveAction>(ref segmentReader, formatterResolver); break; case 2: aliasAction = Deserialize<AliasRemoveIndexAction>(ref segmentReader, formatterResolver); break; } } return aliasAction; } public void Serialize(ref JsonWriter writer, IAliasAction value, IJsonFormatterResolver formatterResolver) { if (value == null) { writer.WriteNull(); return; } switch (value) { case IAliasAddAction addAction: Serialize(ref writer, addAction, formatterResolver); break; case IAliasRemoveAction removeAction: Serialize(ref writer, removeAction, formatterResolver); break; case IAliasRemoveIndexAction removeIndexAction: Serialize(ref writer, removeIndexAction, formatterResolver); break; default: // TODO: Should we handle some other way? writer.WriteNull(); break; } } private static void Serialize<TAliasAction>(ref JsonWriter writer, TAliasAction action, IJsonFormatterResolver formatterResolver ) where TAliasAction : IAliasAction { var formatter = formatterResolver.GetFormatter<TAliasAction>(); formatter.Serialize(ref writer, action, formatterResolver); } private static TAliasAction Deserialize<TAliasAction>(ref JsonReader reader, IJsonFormatterResolver formatterResolver) where TAliasAction : IAliasAction { var formatter = formatterResolver.GetFormatter<TAliasAction>(); return formatter.Deserialize(ref reader, formatterResolver); } } }
namespace Nest { /// <summary> /// Marker interface for alias operation /// </summary> public interface IAliasAction { } }
apache-2.0
C#
bd364684d091232c70166dc5bd4b69b6ca75a550
Update SolutionAssemblyInfo.cs
DimensionDataCBUSydney/Compute.Api.Client
ComputeClient/SolutionAssemblyInfo.cs
ComputeClient/SolutionAssemblyInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SolutionAssemblyInfo.cs" company=""> // // </copyright> // <summary> // SolutionAssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyCompany("Dimension Data")] [assembly: AssemblyProduct("Compute as a Service (CaaS) API client.")] [assembly: AssemblyCopyright("Copyright © Dimension Data 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.7.21")] [assembly: AssemblyFileVersion("3.7.21")] [assembly: AssemblyInformationalVersion("3.7.21")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SolutionAssemblyInfo.cs" company=""> // // </copyright> // <summary> // SolutionAssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyCompany("Dimension Data")] [assembly: AssemblyProduct("Compute as a Service (CaaS) API client.")] [assembly: AssemblyCopyright("Copyright © Dimension Data 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.7.21")] [assembly: AssemblyFileVersion("3.7.21")] [assembly: AssemblyInformationalVersion("3.7.21-dev")]
mit
C#
fbd2564fe509f1029845f54ff275f18b77937df2
Bump version to 3.2.1
jcheng31/DarkSkyApi,jcheng31/ForecastPCL
DarkSkyApi/Properties/AssemblyInfo.cs
DarkSkyApi/Properties/AssemblyInfo.cs
using System.Resources; 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("DarkSkyApi")] [assembly: AssemblyDescription("An unofficial PCL for the Dark Sky weather API.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jerome Cheng")] [assembly: AssemblyProduct("DarkSkyApi")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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("3.2.1.0")] [assembly: AssemblyFileVersion("3.2.1.0")]
using System.Resources; 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("DarkSkyApi")] [assembly: AssemblyDescription("An unofficial PCL for the Dark Sky weather API.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jerome Cheng")] [assembly: AssemblyProduct("DarkSkyApi")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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("3.2.0.0")] [assembly: AssemblyFileVersion("3.2.0.0")]
mit
C#
6ec48042bd189cf8ee42f084726197ceb538c8d0
Fix Remove
larsbrubaker/agg-sharp,MatterHackers/agg-sharp,jlewin/agg-sharp
DataConverters3D/Object3D/SafeList.cs
DataConverters3D/Object3D/SafeList.cs
/* Copyright (c) 2017, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Collections; using System.Collections.Generic; namespace MatterHackers.DataConverters3D { public class SafeList<T> : IEnumerable<T> { public event EventHandler ItemsModified; private List<T> items; public SafeList() { items = new List<T>(); } public SafeList(IEnumerable<T> sourceItems) { items = new List<T>(sourceItems); } public void Add(T item) => this.Modify(list => list.Add(item)); public void Remove(T item) => this.Modify(list => list.Remove(item)); public int Count => items.Count; public bool Contains(T item) => items.Contains(item); /// <summary> /// Provides a safe context to manipulate items. Copies items into a new list, invokes the 'modifier' /// Action passing in the copied list and finally swaps the modified list into place after the invoked Action completes /// </summary> /// <param name="modifier">The Action to invoke</param> public void Modify(Action<List<T>> modifier) { // Copy the child items to a new list var safeClone = new List<T>(items); // Pass the new list to the Action for manipulation modifier(safeClone); // Swap the modified list into place items = safeClone; this.ItemsModified?.Invoke(this, null); } public IEnumerator<T> GetEnumerator() => items.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => items.GetEnumerator(); } }
/* Copyright (c) 2017, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Collections; using System.Collections.Generic; namespace MatterHackers.DataConverters3D { public class SafeList<T> : IEnumerable<T> { public event EventHandler ItemsModified; private List<T> items; public SafeList() { items = new List<T>(); } public SafeList(IEnumerable<T> sourceItems) { items = new List<T>(sourceItems); } public void Add(T item) => this.Modify(list => list.Add(item)); public void Remove(T item) => this.Modify(list => list.Add(item)); public int Count => items.Count; public bool Contains(T item) => items.Contains(item); /// <summary> /// Provides a safe context to manipulate items. Copies items into a new list, invokes the 'modifier' /// Action passing in the copied list and finally swaps the modified list into place after the invoked Action completes /// </summary> /// <param name="modifier">The Action to invoke</param> public void Modify(Action<List<T>> modifier) { // Copy the child items to a new list var safeClone = new List<T>(items); // Pass the new list to the Action for manipulation modifier(safeClone); // Swap the modified list into place items = safeClone; this.ItemsModified?.Invoke(this, null); } public IEnumerator<T> GetEnumerator() => items.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => items.GetEnumerator(); } }
bsd-2-clause
C#
47c403700f7b51ab1198be970093a0fda4a61fe3
Update ComboTests.cs
willrawls/xlg,willrawls/xlg
MetX/MetX.Console.Tests/Fiver/ComboTests.cs
MetX/MetX.Console.Tests/Fiver/ComboTests.cs
using System; using System.Collections.Generic; using MetX.Five.Setup; using MetX.Standard.Primary.Scripts; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MetX.Console.Tests.Fiver; [TestClass] public class ComboTests { [TestMethod] public void TestScript_Simple() { var validCombo = new ValidCombo<TestActor>(ArgumentVerb.Test, ArgumentNoun.Script); var testActor = validCombo.Factory(); testActor.FakeReadyToActResult = true; var quickScriptTemplate = new XlgQuickScriptTemplate(@"TestTemplates\TestExe"); quickScriptTemplate.Name = "George"; XlgQuickScript quickScript = new XlgQuickScript("Freddy", "a = b;"); testActor.ResultFromAct = new ProcessorResult { ActualizationResult = new ActualizationResult(new ActualizationSettings(quickScriptTemplate, true, quickScript, false, null)), }; var settings = new ArgumentSettings { Verb = ArgumentVerb.Test, Noun = ArgumentNoun.Script, Name = "Fred", AdditionalArguments = new List<string> { "George" } }; Assert.IsTrue(testActor.ReadyToAct(settings, out var reason)); Assert.IsNull(reason); var actual = testActor.Run(settings); Assert.IsNotNull(actual); Assert.IsNotNull(actual.ActualizationResult); } } public class TestActor : FiverActorBase { public bool FakeReadyToActResult { get; set; } public bool ReadyToActWasCalled { get; set; } public string FakeReason { get; set; } public ProcessorResult ResultFromAct { get; set; } = new(); public bool ActWasCalled { get; set; } public override bool ReadyToAct(ArgumentSettings settings, out string reason) { reason = FakeReason; ReadyToActWasCalled = true; return FakeReadyToActResult; } public override ProcessorResult Run(ArgumentSettings settings) { ActWasCalled = true; return ResultFromAct; } }
using System.Collections.Generic; using MetX.Five.Setup; using MetX.Standard.Primary.Scripts; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MetX.Console.Tests.Fiver; [TestClass] public class ComboTests { [TestMethod] public void TestScript_Simple() { var validCombo = new ValidCombo<TestActor>(ArgumentVerb.Test, ArgumentNoun.Script); var testActor = validCombo.Factory(); testActor.FakeReadyToActResult = true; var quickScriptTemplate = new XlgQuickScriptTemplate(@"TestTemplates\TestExe"); quickScriptTemplate.Name = "George"; XlgQuickScript quickScript = new XlgQuickScript("Freddy", "a = b;"); testActor.ResultFromAct = new ProcessorResult { ActualizationResult = new ActualizationResult(new ActualizationSettings(quickScriptTemplate, true, quickScript, false, null)), }; var settings = new ArgumentSettings { Verb = ArgumentVerb.Test, Noun = ArgumentNoun.Script, Name = "Fred", AdditionalArguments = new List<string> { "George" } }; Assert.IsTrue(testActor.ReadyToAct(settings, out var reason)); Assert.IsNull(reason); var actual = testActor.Run(settings); Assert.IsNotNull(actual); Assert.IsNotNull(actual.ActualizationResult); } } public class TestActor : FiverActorBase { public bool FakeReadyToActResult { get; set; } public bool ReadyToActWasCalled { get; set; } public string FakeReason { get; set; } public ProcessorResult ResultFromAct { get; set; } = new(); public bool ActWasCalled { get; set; } public override bool ReadyToAct(ArgumentSettings settings, out string reason) { reason = FakeReason; ReadyToActWasCalled = true; return FakeReadyToActResult; } public override ProcessorResult Run(ArgumentSettings settings) { ActWasCalled = true; return ResultFromAct; } }
mit
C#
64a849d1e8ef2e0fa381e185ce3975d9625e0eec
Bump version to 2.4.0.0
InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform
Files/Packaging/GlobalAssemblyInfo.cs
Files/Packaging/GlobalAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Infinnity Solutions")] [assembly: AssemblyProduct("InfinniPlatform")] [assembly: AssemblyCopyright("Copyright © Infinnity Solutions 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyConfiguration("")] // TeamCity File Content Replacer: Add build number // Look in: */Packaging/GlobalAssemblyInfo.cs // Find what: ((AssemblyVersion|AssemblyFileVersion)\s*\(\s*@?\")(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<patch>[0-9]+)\.(?<build>[0-9]+)(\"\s*\)) // Replace with: $1$3.$4.$5.\%build.number%$7 [assembly: AssemblyVersion("2.4.0.0")] [assembly: AssemblyFileVersion("2.4.0.0")] // TeamCity File Content Replacer: Add VCS hash // Look in: */Packaging/GlobalAssemblyInfo.cs // Find what: (AssemblyInformationalVersion\s*\(\s*@?\").*?(\"\s*\)) // Replace with: $1\%build.vcs.number%$2 [assembly: AssemblyInformationalVersion("")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Infinnity Solutions")] [assembly: AssemblyProduct("InfinniPlatform")] [assembly: AssemblyCopyright("Copyright © Infinnity Solutions 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyConfiguration("")] // TeamCity File Content Replacer: Add build number // Look in: */Packaging/GlobalAssemblyInfo.cs // Find what: ((AssemblyVersion|AssemblyFileVersion)\s*\(\s*@?\")(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<patch>[0-9]+)\.(?<build>[0-9]+)(\"\s*\)) // Replace with: $1$3.$4.$5.\%build.number%$7 [assembly: AssemblyVersion("2.3.8.0")] [assembly: AssemblyFileVersion("2.3.8.0")] // TeamCity File Content Replacer: Add VCS hash // Look in: */Packaging/GlobalAssemblyInfo.cs // Find what: (AssemblyInformationalVersion\s*\(\s*@?\").*?(\"\s*\)) // Replace with: $1\%build.vcs.number%$2 [assembly: AssemblyInformationalVersion("")]
agpl-3.0
C#
ff56d33f624bee91354ebe09ab83bbc79b587536
Fix test case comment to reflect the actual test (#19531)
cshung/coreclr,cshung/coreclr,wtgodbe/coreclr,krk/coreclr,krk/coreclr,cshung/coreclr,mmitche/coreclr,poizan42/coreclr,cshung/coreclr,mmitche/coreclr,krk/coreclr,poizan42/coreclr,cshung/coreclr,mmitche/coreclr,krk/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,mmitche/coreclr,mmitche/coreclr,mmitche/coreclr,wtgodbe/coreclr,krk/coreclr,poizan42/coreclr,krk/coreclr,poizan42/coreclr,wtgodbe/coreclr,poizan42/coreclr,cshung/coreclr,poizan42/coreclr,wtgodbe/coreclr
tests/src/JIT/Regression/JitBlue/GitHub_19454/Github_19454.cs
tests/src/JIT/Regression/JitBlue/GitHub_19454/Github_19454.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. // // GitHub19454: a zero length span was tripping up the jit when trying // to analyze a bounds check. using System; public struct MyStruct { public Span<byte> Span1 { get { return Span<byte>.Empty; } } } public struct MyReader { public void ReadBytesInner(int batch) { MyStruct value = new MyStruct(); for (int i = 0; i < batch; i++) { value.Span1[i] = 0; } } } class GitHub_19454 { static int Main() { MyReader r = new MyReader(); r.ReadBytesInner(0); return 100; } }
// 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. // // This test was extracted from the corefx System.Numerics.Vectors tests, // and was failing with minOpts because a SIMD12 was being spilled using // a 16-byte load, but only a 12-byte location had been allocated. using System; public struct MyStruct { public Span<byte> Span1 { get { return Span<byte>.Empty; } } } public struct MyReader { public void ReadBytesInner(int batch) { MyStruct value = new MyStruct(); for (int i = 0; i < batch; i++) { value.Span1[i] = 0; } } } class GitHub_19454 { static int Main() { MyReader r = new MyReader(); r.ReadBytesInner(0); return 100; } }
mit
C#
c4b8620633076d0a10effdba113b6597e0953b07
修正 StyleSetting 测试文件路径错误
yonglehou/Jumony,wukaixian/Jumony,wukaixian/Jumony,yonglehou/Jumony,zpzgone/Jumony,zpzgone/Jumony
SelectorTest/CssStyleTest.cs
SelectorTest/CssStyleTest.cs
using System; using System.IO; using Ivony.Html; using Ivony.Html.Parser; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SelectorTest { [TestClass] public class CssStyleTest { [TestMethod] public void StyleSettingParseTest() { var document = new JumonyParser().LoadDocument( Path.Combine( Environment.CurrentDirectory, "CssStyleSettingTest1.html" ) ); Assert.AreEqual( document.FindSingle( "div" ).Style().GetValue( "display" ), "none", "无法正确解析丢失分号的属性值" ); } } }
using System; using System.IO; using Ivony.Html; using Ivony.Html.Parser; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SelectorTest { [TestClass] public class CssStyleTest { [TestMethod] public void StyleSettingParseTest() { var document = new JumonyParser().LoadDocument( Path.Combine( Environment.CurrentDirectory, "SelectorTest1.html" ) ); Assert.AreEqual( document.FindSingle( "div" ).Style().GetValue( "display" ), "none", "无法正确解析丢失分号的属性值" ); } } }
apache-2.0
C#
db24dc5f7f0471ff921972b60c6dd5218461dad2
update version to 1.5.0.4
evitself/HTML-Renderer,windygu/HTML-Renderer,drickert5/HTML-Renderer,drickert5/HTML-Renderer,todor-dk/HTML-Renderer,Perspex/HTML-Renderer,todor-dk/HTML-Renderer,verdesgrobert/HTML-Renderer,Perspex/HTML-Renderer,tinygg/graphic-HTML-Renderer,todor-dk/HTML-Renderer,tinygg/graphic-HTML-Renderer,ArthurHub/HTML-Renderer,windygu/HTML-Renderer,slagou/HTML-Renderer,verdesgrobert/HTML-Renderer,evitself/HTML-Renderer,slagou/HTML-Renderer,tinygg/graphic-HTML-Renderer,ArthurHub/HTML-Renderer
Source/SharedAssemblyInfo.cs
Source/SharedAssemblyInfo.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("HTML Renderer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Open source hosted on CodePlex")] [assembly: AssemblyProduct("HTML Renderer")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("ec8a9e7e-9a9d-43c3-aa97-f6f505b1d3ed")] // Version information for an assembly consists of the following four values: [assembly: AssemblyVersion("1.5.0.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("HTML Renderer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Open source hosted on CodePlex")] [assembly: AssemblyProduct("HTML Renderer")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("ec8a9e7e-9a9d-43c3-aa97-f6f505b1d3ed")] // Version information for an assembly consists of the following four values: [assembly: AssemblyVersion("1.5.0.3")]
bsd-3-clause
C#
8519222cb78a7b497b19cd24e4347b3e4fd87bfc
comment fix
bokobza/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode
Stratis.Bitcoin/Utilities/LinqExtensions.cs
Stratis.Bitcoin/Utilities/LinqExtensions.cs
using System; using System.Collections.Generic; using System.Linq; namespace Stratis.Bitcoin.Utilities { /// <summary> /// Extension methods for IEnumerable interface. /// </summary> public static class LinqExtensions { /// <summary> /// Calculates a median value of a collection of integers. /// </summary> /// <param name="source">Collection of numbers to count median of.</param> /// <returns>Median value, or 0 if the collection is empty.</returns> public static long Median(this IEnumerable<long> source) { long count = source.LongCount(); if (count == 0) return 0; int midpoint = source.Count() / 2; IOrderedEnumerable<long> ordered = source.OrderBy(n => n); if ((count % 2) == 0) return (long)Math.Round(ordered.Skip(midpoint-1).Take(2).Average()); else return ordered.ElementAt(midpoint); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Stratis.Bitcoin.Utilities { /// <summary> /// Extension methods for collections. /// </summary> /// <remarks>TODO: Why is this called LinqExtensions? Wouldn't CollectionsExtensions be better?</remarks> public static class LinqExtensions { /// <summary> /// Calculates a median value of a collection of integers. /// </summary> /// <param name="source">Collection of numbers to count median of.</param> /// <returns>Median value, or 0 if the collection is empty.</returns> public static long Median(this IEnumerable<long> source) { long count = source.LongCount(); if (count == 0) return 0; int midpoint = source.Count() / 2; IOrderedEnumerable<long> ordered = source.OrderBy(n => n); if ((count % 2) == 0) return (long)Math.Round(ordered.Skip(midpoint-1).Take(2).Average()); else return ordered.ElementAt(midpoint); } } }
mit
C#
9ebcba9f70e66e2b0e884343a2ad94e603b21462
Change assert
bjornharrtell/saule,joukevandermaas/saule
Tests/Http/AttributeTests.cs
Tests/Http/AttributeTests.cs
using System; using System.Collections.Generic; using Saule.Http; using Tests.Models; using Xunit; using System.Threading.Tasks; using Tests.Helpers; using Xunit.Abstractions; using System.Linq; namespace Tests.Http { public class AttributeTests { [Theory(DisplayName = "PaginatedAttribute does not allow PerPage < 1")] [InlineData(0)] [InlineData(int.MinValue)] [InlineData(-1)] [InlineData(-10)] [InlineData(-512)] public void PerPageLargerThanOne(int count) { Assert.Throws<ArgumentOutOfRangeException>(() => new PaginatedAttribute { PerPage = count }); } [Theory(DisplayName = "ReturnsResourceAttribute only allows types that extend ApiResource")] [InlineData(typeof(string))] [InlineData(typeof(IDictionary<,>))] [InlineData(typeof(int))] [InlineData(typeof(LocationType))] [InlineData(typeof(List<>))] public void OnlyAllowApiResource(Type type) { Assert.Throws<ArgumentException>(() => new ReturnsResourceAttribute(type)); } [Fact(DisplayName = "JsonApiAttribute responds to HttpGets with Json Api even when accept header is not 'application/vnd.api+json'")] public async Task JsonApiAttributeRespondsWithJsonApi() { using (var server = new NewSetupJsonApiServer()) { var client = server.GetClient(addDefaultHeaders: false); var result = await client.GetJsonResponseAsync("api/people/123/usingJsonApiAttributeFilter"); Assert.NotEmpty(result["data"]["attributes"].Children()); } } } }
using System; using System.Collections.Generic; using Saule.Http; using Tests.Models; using Xunit; using System.Threading.Tasks; using Tests.Helpers; namespace Tests.Http { public class AttributeTests { [Theory(DisplayName = "PaginatedAttribute does not allow PerPage < 1")] [InlineData(0)] [InlineData(int.MinValue)] [InlineData(-1)] [InlineData(-10)] [InlineData(-512)] public void PerPageLargerThanOne(int count) { Assert.Throws<ArgumentOutOfRangeException>(() => new PaginatedAttribute { PerPage = count }); } [Theory(DisplayName = "ReturnsResourceAttribute only allows types that extend ApiResource")] [InlineData(typeof(string))] [InlineData(typeof(IDictionary<,>))] [InlineData(typeof(int))] [InlineData(typeof(LocationType))] [InlineData(typeof(List<>))] public void OnlyAllowApiResource(Type type) { Assert.Throws<ArgumentException>(() => new ReturnsResourceAttribute(type)); } [Fact(DisplayName = "JsonApiAttribute responds to HttpGets with Json Api even when accept header is not 'application/vnd.api+json'")] public async Task JsonApiAttributeRespondsWithJsonApi() { using (var server = new NewSetupJsonApiServer()) { var client = server.GetClient(addDefaultHeaders: false); var result = await client.GetJsonResponseAsync("api/people/123/usingJsonApiAttributeFilter"); Assert.NotNull(result["data"]["attributes"]["first-name"]); } } } }
mit
C#
db09374bd28e9fa172bf18ad08ef0abbbd44fbda
Improve test method name for clarity.
fixie/fixie
src/Fixie.Tests/Execution/RunnerAppDomainCommunicationTests.cs
src/Fixie.Tests/Execution/RunnerAppDomainCommunicationTests.cs
using Fixie.Execution; using Fixie.Internal; namespace Fixie.Tests.Execution { public class RunnerAppDomainCommunicationTests { public void ShouldAllowRunnersInOtherAppDomainsToProvideTheirOwnListeners() { typeof(Listener).ShouldBeSafeAppDomainCommunicationInterface(); } public void ShouldAllowRunnersInOtherAppDomainsToPerformTestDiscoveryAndExecutionThroughExecutionProxy() { typeof(ExecutionProxy).ShouldBeSafeAppDomainCommunicationInterface(); } } }
using Fixie.Execution; using Fixie.Internal; namespace Fixie.Tests.Execution { public class RunnerAppDomainCommunicationTests { public void ShouldAllowRunnersInOtherAppDomainsToProvideTheirOwnListeners() { typeof(Listener).ShouldBeSafeAppDomainCommunicationInterface(); } public void ShouldAllowRunnersToPerformTestDiscoveryAndExecutionThroughExecutionProxy() { typeof(ExecutionProxy).ShouldBeSafeAppDomainCommunicationInterface(); } } }
mit
C#
d2804123d18e0aa38234c7d76896b93e45621b22
Update anti forgery helper as extension methods
geeklearningio/Testavior
src/GeekLearning.Test.Integration/Helpers/AntiForgeryHelper.cs
src/GeekLearning.Test.Integration/Helpers/AntiForgeryHelper.cs
namespace GeekLearning.Test.Integration.Helpers { using System; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; // http://www.stefanhendriks.com/2016/05/11/integration-testing-your-asp-net-core-app-dealing-with-anti-request-forgery-csrf-formdata-and-cookies/ public static class AntiForgeryHelper { public static string ExtractAntiForgeryToken(string htmlResponseText) { if (htmlResponseText == null) throw new ArgumentNullException("htmlResponseText"); System.Text.RegularExpressions.Match match = Regex.Match(htmlResponseText, @"\<input name=""__RequestVerificationToken"" type=""hidden"" value=""([^""]+)"" \/\>"); return match.Success ? match.Groups[1].Captures[0].Value : null; } public static async Task<string> ExtractAntiForgeryTokenAsync(this HttpResponseMessage response) { string responseAsString = await response.Content.ReadAsStringAsync(); return await Task.FromResult(ExtractAntiForgeryToken(responseAsString)); } } }
namespace GeekLearning.Test.Integration.Helpers { using System; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; // http://www.stefanhendriks.com/2016/05/11/integration-testing-your-asp-net-core-app-dealing-with-anti-request-forgery-csrf-formdata-and-cookies/ public class AntiForgeryHelper { public static string ExtractAntiForgeryToken(string htmlResponseText) { if (htmlResponseText == null) throw new ArgumentNullException("htmlResponseText"); System.Text.RegularExpressions.Match match = Regex.Match(htmlResponseText, @"\<input name=""__RequestVerificationToken"" type=""hidden"" value=""([^""]+)"" \/\>"); return match.Success ? match.Groups[1].Captures[0].Value : null; } public static async Task<string> ExtractAntiForgeryToken(HttpResponseMessage response) { string responseAsString = await response.Content.ReadAsStringAsync(); return await Task.FromResult(ExtractAntiForgeryToken(responseAsString)); } } }
mit
C#
41ba0bf07f9186d1beb817a2319bb9b23ca9816d
Add export for InlineCommentMarginEnabled
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.InlineReviews/Margins/InlineCommentMarginEnabled.cs
src/GitHub.InlineReviews/Margins/InlineCommentMarginEnabled.cs
using System; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Utilities; using Microsoft.VisualStudio.Text.Editor; namespace GitHub.InlineReviews.Margins { [Export(typeof(InlineCommentMarginEnabled))] [Export(typeof(EditorOptionDefinition)), Name(OptionName)] public class InlineCommentMarginEnabled : ViewOptionDefinition<bool> { const string OptionName = "TextViewHost/InlineCommentMarginEnabled"; public override bool Default => false; public override EditorOptionKey<bool> Key => new EditorOptionKey<bool>(OptionName); } }
using System; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Utilities; using Microsoft.VisualStudio.Text.Editor; namespace GitHub.InlineReviews.Margins { [Export(typeof(EditorOptionDefinition))] [Name(OptionName)] public class InlineCommentMarginEnabled : ViewOptionDefinition<bool> { const string OptionName = "TextViewHost/InlineCommentMarginEnabled"; public override bool Default => false; public override EditorOptionKey<bool> Key => new EditorOptionKey<bool>(OptionName); } }
mit
C#
e69c7ae3b4a9d426d7ca6b9bfffbba14d2ca519a
Improve messaging from SDL2 GL context failures
ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework
osu.Framework/Platform/SDL2/SDL2GraphicsBackend.cs
osu.Framework/Platform/SDL2/SDL2GraphicsBackend.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using SDL2; namespace osu.Framework.Platform.SDL2 { /// <summary> /// Implementation of <see cref="PassthroughGraphicsBackend"/> that uses SDL's OpenGL bindings. /// </summary> public class SDL2GraphicsBackend : PassthroughGraphicsBackend { private IntPtr sdlWindowHandle; public override bool VerticalSync { get => SDL.SDL_GL_GetSwapInterval() != 0; set => SDL.SDL_GL_SetSwapInterval(value ? 1 : 0); } protected override IntPtr CreateContext() { SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_PROFILE_MASK, SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); IntPtr context = SDL.SDL_GL_CreateContext(sdlWindowHandle); if (context == IntPtr.Zero) throw new InvalidOperationException($"Failed to create an SDL2 GL context ({SDL.SDL_GetError()})"); return context; } protected override void MakeCurrent(IntPtr context) => SDL.SDL_GL_MakeCurrent(sdlWindowHandle, context); public override void SwapBuffers() => SDL.SDL_GL_SwapWindow(sdlWindowHandle); protected override IntPtr GetProcAddress(string symbol) => SDL.SDL_GL_GetProcAddress(symbol); public override void Initialise(IWindow window) { if (!(window is SDL2DesktopWindow sdlWindow)) throw new ArgumentException("Unsupported window backend.", nameof(window)); sdlWindowHandle = sdlWindow.SDLWindowHandle; base.Initialise(window); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using SDL2; namespace osu.Framework.Platform.SDL2 { /// <summary> /// Implementation of <see cref="PassthroughGraphicsBackend"/> that uses SDL's OpenGL bindings. /// </summary> public class SDL2GraphicsBackend : PassthroughGraphicsBackend { private IntPtr sdlWindowHandle; public override bool VerticalSync { get => SDL.SDL_GL_GetSwapInterval() != 0; set => SDL.SDL_GL_SetSwapInterval(value ? 1 : 0); } protected override IntPtr CreateContext() { SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_PROFILE_MASK, SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); return SDL.SDL_GL_CreateContext(sdlWindowHandle); } protected override void MakeCurrent(IntPtr context) => SDL.SDL_GL_MakeCurrent(sdlWindowHandle, context); public override void SwapBuffers() => SDL.SDL_GL_SwapWindow(sdlWindowHandle); protected override IntPtr GetProcAddress(string symbol) => SDL.SDL_GL_GetProcAddress(symbol); public override void Initialise(IWindow window) { if (!(window is SDL2DesktopWindow sdlWindow)) throw new ArgumentException("Unsupported window backend.", nameof(window)); sdlWindowHandle = sdlWindow.SDLWindowHandle; base.Initialise(window); } } }
mit
C#
0e38ff07c74de55cfc640361f51b8ea5658171d9
Check if relax is one of the mods, if so hide.
ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu
osu.Game.Rulesets.Catch/UI/DrawableCatchRuleset.cs
osu.Game.Rulesets.Catch/UI/DrawableCatchRuleset.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Input; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Input.Handlers; using osu.Game.Replays; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.Replays; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.UI.Scrolling; using osu.Game.Scoring; namespace osu.Game.Rulesets.Catch.UI { public class DrawableCatchRuleset : DrawableScrollingRuleset<CatchHitObject> { protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Constant; protected override bool UserScrollSpeedAdjustment => false; private bool showMobileMapper = true; public DrawableCatchRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null) : base(ruleset, beatmap, mods) { // Check if mods have RelaxMod instance if (mods.OfType<ModRelax>().Any()) showMobileMapper = false; Direction.Value = ScrollingDirection.Down; TimeRange.Value = IBeatmapDifficultyInfo.DifficultyRange(beatmap.Difficulty.ApproachRate, 1800, 1200, 450); } [BackgroundDependencyLoader] private void load() { if (showMobileMapper) KeyBindingInputManager.Add(new CatchTouchInputMapper()); } protected override ReplayInputHandler CreateReplayInputHandler(Replay replay) => new CatchFramedReplayInputHandler(replay); protected override ReplayRecorder CreateReplayRecorder(Score score) => new CatchReplayRecorder(score, (CatchPlayfield)Playfield); protected override Playfield CreatePlayfield() => new CatchPlayfield(Beatmap.Difficulty); public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new CatchPlayfieldAdjustmentContainer(); protected override PassThroughInputManager CreateInputManager() => new CatchInputManager(Ruleset.RulesetInfo); public override DrawableHitObject<CatchHitObject> CreateDrawableRepresentation(CatchHitObject h) => null; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Input; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Input.Handlers; using osu.Game.Replays; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.Replays; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.UI.Scrolling; using osu.Game.Scoring; namespace osu.Game.Rulesets.Catch.UI { public class DrawableCatchRuleset : DrawableScrollingRuleset<CatchHitObject> { protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Constant; protected override bool UserScrollSpeedAdjustment => false; public DrawableCatchRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null) : base(ruleset, beatmap, mods) { Direction.Value = ScrollingDirection.Down; TimeRange.Value = IBeatmapDifficultyInfo.DifficultyRange(beatmap.Difficulty.ApproachRate, 1800, 1200, 450); } [BackgroundDependencyLoader] private void load() { KeyBindingInputManager.Add(new CatchTouchInputMapper()); } protected override ReplayInputHandler CreateReplayInputHandler(Replay replay) => new CatchFramedReplayInputHandler(replay); protected override ReplayRecorder CreateReplayRecorder(Score score) => new CatchReplayRecorder(score, (CatchPlayfield)Playfield); protected override Playfield CreatePlayfield() => new CatchPlayfield(Beatmap.Difficulty); public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new CatchPlayfieldAdjustmentContainer(); protected override PassThroughInputManager CreateInputManager() => new CatchInputManager(Ruleset.RulesetInfo); public override DrawableHitObject<CatchHitObject> CreateDrawableRepresentation(CatchHitObject h) => null; } }
mit
C#
0a157a3b60a9309bdaef841639d56fc604a6180f
update version
dreign/ComBoost,dreign/ComBoost
Wodsoft.ComBoost/Properties/AssemblyInfo.cs
Wodsoft.ComBoost/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ComBoost")] [assembly: AssemblyDescription("ComBoost Framework")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Wodsoft")] [assembly: AssemblyProduct("ComBoost Framework")] [assembly: AssemblyCopyright("Copyright © Wodsoft 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("f1c82024-352b-4a0e-81a9-20e10f771bb0")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3.0")] [assembly: AssemblyFileVersion("1.0.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ComBoost")] [assembly: AssemblyDescription("ComBoost Framework")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Wodsoft")] [assembly: AssemblyProduct("ComBoost Framework")] [assembly: AssemblyCopyright("Copyright © Wodsoft 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("f1c82024-352b-4a0e-81a9-20e10f771bb0")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
mit
C#
9320eff8177d51850e7a49bcfd9840a96a455e48
Add ResolveByName attribute to TargetControl property
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactions/Custom/HideOnLostFocusBehavior.cs
src/Avalonia.Xaml.Interactions/Custom/HideOnLostFocusBehavior.cs
using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom; /// <summary> /// A behavior that allows to hide control on lost focus event. /// </summary> public class HideOnLostFocusBehavior : Behavior<Control> { /// <summary> /// Identifies the <seealso cref="TargetControl"/> avalonia property. /// </summary> public static readonly StyledProperty<Control?> TargetControlProperty = AvaloniaProperty.Register<HideOnLostFocusBehavior, Control?>(nameof(TargetControl)); /// <summary> /// Gets or sets the target control. This is a avalonia property. /// </summary> [ResolveByName] public Control? TargetControl { get => GetValue(TargetControlProperty); set => SetValue(TargetControlProperty, value); } /// <inheritdoc /> protected override void OnAttachedToVisualTree() { AssociatedObject?.AddHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus, RoutingStrategies.Tunnel | RoutingStrategies.Bubble); } /// <inheritdoc /> protected override void OnDetachedFromVisualTree() { AssociatedObject?.RemoveHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus); } private void AssociatedObject_LostFocus(object? sender, RoutedEventArgs e) { if (TargetControl is { }) { TargetControl.IsVisible = false; } } }
using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom; /// <summary> /// A behavior that allows to hide control on lost focus event. /// </summary> public class HideOnLostFocusBehavior : Behavior<Control> { /// <summary> /// Identifies the <seealso cref="TargetControl"/> avalonia property. /// </summary> public static readonly StyledProperty<Control?> TargetControlProperty = AvaloniaProperty.Register<HideOnLostFocusBehavior, Control?>(nameof(TargetControl)); /// <summary> /// Gets or sets the target control. This is a avalonia property. /// </summary> public Control? TargetControl { get => GetValue(TargetControlProperty); set => SetValue(TargetControlProperty, value); } /// <inheritdoc /> protected override void OnAttachedToVisualTree() { AssociatedObject?.AddHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus, RoutingStrategies.Tunnel | RoutingStrategies.Bubble); } /// <inheritdoc /> protected override void OnDetachedFromVisualTree() { AssociatedObject?.RemoveHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus); } private void AssociatedObject_LostFocus(object? sender, RoutedEventArgs e) { if (TargetControl is { }) { TargetControl.IsVisible = false; } } }
mit
C#
f3edbf1a2365635d5ebb50ac5ceebf5e333338af
Add debug msg to tell block (#1649)
ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,LtRipley36706/ACE,ACEmulator/ACE
Source/ACE.Server/Network/GameAction/Actions/GameActionTell.cs
Source/ACE.Server/Network/GameAction/Actions/GameActionTell.cs
using ACE.Common.Extensions; using ACE.Entity.Enum; using ACE.Server.Managers; using ACE.Server.Network.GameEvent.Events; using ACE.Server.Network.GameMessages.Messages; using log4net; namespace ACE.Server.Network.GameAction.Actions { public static class GameActionTell { private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); [GameAction(GameActionType.Tell)] public static void Handle(ClientMessage clientMessage, Session session) { var message = clientMessage.Payload.ReadString16L(); // The client seems to do the trimming for us var target = clientMessage.Payload.ReadString16L(); // Needs to be trimmed because it may contain white spaces after the name and before the , target = target.Trim(); var targetPlayer = PlayerManager.GetOnlinePlayer(target); if (targetPlayer == null) { var statusMessage = new GameEventWeenieError(session, WeenieError.CharacterNotAvailable); session.Network.EnqueueSend(statusMessage); return; } if (session.Player != targetPlayer) session.Network.EnqueueSend(new GameMessageSystemChat($"You tell {targetPlayer.Name}, \"{message}\"", ChatMessageType.OutgoingTell)); if (targetPlayer.Squelches.Contains(session.Player)) { //todo: remove debug msg. session.Network.EnqueueSend(new GameEventWeenieErrorWithString(session, WeenieErrorWithString.MessageBlocked_,$"{target} has you squelched."), new GameMessageSystemChat($"DEBUG: This message was blocked. Report seeing this block to devs in discord, please.", ChatMessageType.AdminTell)); log.Warn($"Tell from {session.Player.Name} (0x{session.Player.Guid.ToString()}) to {targetPlayer.Name} (0x{targetPlayer.Guid.ToString()}) blocked due to squelch"); return; } var tell = new GameEventTell(targetPlayer.Session, message, session.Player.Name, session.Player.Guid.Full, targetPlayer.Guid.Full, ChatMessageType.Tell); targetPlayer.Session.Network.EnqueueSend(tell); } } }
using ACE.Common.Extensions; using ACE.Entity.Enum; using ACE.Server.Managers; using ACE.Server.Network.GameEvent.Events; using ACE.Server.Network.GameMessages.Messages; namespace ACE.Server.Network.GameAction.Actions { public static class GameActionTell { [GameAction(GameActionType.Tell)] public static void Handle(ClientMessage clientMessage, Session session) { var message = clientMessage.Payload.ReadString16L(); // The client seems to do the trimming for us var target = clientMessage.Payload.ReadString16L(); // Needs to be trimmed because it may contain white spaces after the name and before the , target = target.Trim(); var targetPlayer = PlayerManager.GetOnlinePlayer(target); if (targetPlayer == null) { var statusMessage = new GameEventWeenieError(session, WeenieError.CharacterNotAvailable); session.Network.EnqueueSend(statusMessage); return; } if (session.Player != targetPlayer) session.Network.EnqueueSend(new GameMessageSystemChat($"You tell {targetPlayer.Name}, \"{message}\"", ChatMessageType.OutgoingTell)); if (targetPlayer.Squelches.Contains(session.Player)) return; var tell = new GameEventTell(targetPlayer.Session, message, session.Player.Name, session.Player.Guid.Full, targetPlayer.Guid.Full, ChatMessageType.Tell); targetPlayer.Session.Network.EnqueueSend(tell); } } }
agpl-3.0
C#
2ae20975187a9b1dc821cac31fbfd2706840e7f7
add blank line
saturn72/saturn72
src/NetCore/Saturn72.Core.Services/Caching/MemoryCacheManager.cs
src/NetCore/Saturn72.Core.Services/Caching/MemoryCacheManager.cs
#region using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Primitives; using Saturn72.Core.Caching; #endregion namespace Saturn72.Core.Services.Caching { public class MemoryCacheManager : ICacheManager { #region Fields private readonly IMemoryCache _memoryCache; private CancellationTokenSource _resetCacheToken; protected static readonly HashSet<string> CacheKeys = new HashSet<string>(); #endregion #region ctor public MemoryCacheManager(IMemoryCache memoryCache) { _memoryCache = memoryCache; _resetCacheToken = new CancellationTokenSource(); } #endregion public void Clear() { if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && _resetCacheToken.Token.CanBeCanceled) { _resetCacheToken.Cancel(); _resetCacheToken.Dispose(); } _resetCacheToken = new CancellationTokenSource(); CacheKeys.Clear(); } public TCachedObject Get<TCachedObject>(string key) { return _memoryCache.TryGetValue(key, out TCachedObject value) ? value : default(TCachedObject); } public void RemoveByPattern(string pattern) { var keysToRemove = CacheKeys .Where(k => Regex.IsMatch(k, pattern, RegexOptions.IgnoreCase)) .ToArray(); foreach (var ktr in keysToRemove) Remove(ktr); } public void Remove(string key) { _memoryCache.Remove(key); CacheKeys.Remove(key); } public void Set<TCachedObject>(string key, TCachedObject value, int cacheTime) { var options = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheTime)); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); _memoryCache.Set(key, value, options); CacheKeys.Add(key); } } }
#region using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Primitives; using Saturn72.Core.Caching; #endregion namespace Saturn72.Core.Services.Caching { public class MemoryCacheManager : ICacheManager { #region Fields private readonly IMemoryCache _memoryCache; private CancellationTokenSource _resetCacheToken; protected static readonly HashSet<string> CacheKeys = new HashSet<string>(); #endregion #region ctor public MemoryCacheManager(IMemoryCache memoryCache) { _memoryCache = memoryCache; _resetCacheToken = new CancellationTokenSource(); } #endregion public void Clear() { if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && _resetCacheToken.Token.CanBeCanceled) { _resetCacheToken.Cancel(); _resetCacheToken.Dispose(); } _resetCacheToken = new CancellationTokenSource(); CacheKeys.Clear(); } public TCachedObject Get<TCachedObject>(string key) { return _memoryCache.TryGetValue(key, out TCachedObject value) ? value : default(TCachedObject); } public void RemoveByPattern(string pattern) { var keysToRemove = CacheKeys .Where(k => Regex.IsMatch(k, pattern, RegexOptions.IgnoreCase)) .ToArray(); foreach (var ktr in keysToRemove) Remove(ktr); } public void Remove(string key) { _memoryCache.Remove(key); CacheKeys.Remove(key); } public void Set<TCachedObject>(string key, TCachedObject value, int cacheTime) { var options = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheTime)); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); _memoryCache.Set(key, value, options); CacheKeys.Add(key); } } }
mit
C#
7f6222aa60315ecae649238ac3574ad72482b8a1
Update Applicant.cs
datanets/kask-kiosk,datanets/kask-kiosk
Models/Applicant.cs
Models/Applicant.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Empty.Models { public class Applicant { public int Applicant_ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int SSN { get; set; } public char gender { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Empty.Models { public class Applicant { public int Pk { get; set; } public string firstName { get; set; } public string lastName { get; set; } public int SSN { get; set; } public char gender { get; set; } } }
mit
C#
af37c9760ce50febc20b524a7be2c336041df5d5
Update Palindrome.cs
michaeljwebb/Algorithm-Practice
Other/Palindrome.cs
Other/Palindrome.cs
//Check to see if given string is a palindrome. Return true or false. Ignore letter casing. using System; using System.Collections.Generic; public class Palindrome { public static bool Palindrome(string word) { string result = ""; bool flag = false; string lowerWord = word.ToLower(); for(int i = lowerWord.Length - 1; i >= 0; i--) { result += lowerWord[i]; } if(result == lowerWord) { flag = true; } else { flag = false; } return flag; } public static void Main() { Console.WriteLine(Palindrome("interview")); Console.WriteLine(Palindrome("racecar")); Console.WriteLine(Palindrome("Racecar")); } }
//Check to see if given string is a palindrome. Return true or false. using System; using System.Collections.Generic; public class Palindrome { public static void Main() { string testString = "racecar"; CheckPalindrome(testString); } public static void CheckPalindrome(string s){ string result = ""; char[] cArray = s.ToCharArray(); for(int i = cArray.Length - 1; i >= 0; i--){ result += cArray[i]; } if(result == s){ Console.WriteLine(result + " true"); } else if(result != s){ Console.WriteLine(result + " false"); } } }
mit
C#
1f0b8c027a10f19b842b0a8bc2302981c3090214
Make registrations similar to SQLite.
martijn00/Akavache,shana/Akavache,Loke155/Akavache,gimsum/Akavache,jcomtois/Akavache,mms-/Akavache,kmjonmastro/Akavache,PureWeen/Akavache,christer155/Akavache,MathieuDSTP/MyAkavache,akavache/Akavache,ghuntley/AkavacheSandpit,shana/Akavache,MarcMagnin/Akavache,bbqchickenrobot/Akavache
Akavache.Deprecated/Registrations.cs
Akavache.Deprecated/Registrations.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using Splat; #if UIKIT using MonoTouch.Foundation; #endif #if APPKIT using MonoMac.Foundation; #endif #if ANDROID using Android.App; #endif namespace Akavache.Deprecated { public class Registrations : IWantsToRegisterStuff { public void Register(IMutableDependencyResolver resolver) { if (ModeDetector.InUnitTestRunner()) return; // NB: We want the most recently registered fs, since there really // only should be one var fs = Locator.Current.GetService<IFilesystemProvider>(); if (fs == null) { throw new Exception("Failed to initialize Akavache properly. Do you have a reference to Akavache.dll?"); } var localCache = new Lazy<IBlobCache>(() => { fs.CreateRecursive(fs.GetDefaultLocalMachineCacheDirectory()).Wait(); return new PersistentBlobCache(fs.GetDefaultLocalMachineCacheDirectory(), fs, BlobCache.TaskpoolScheduler); }); resolver.Register(() => localCache.Value, typeof(IBlobCache), "LocalMachine"); var userAccount = new Lazy<IBlobCache>(() => { fs.CreateRecursive(fs.GetDefaultRoamingCacheDirectory()).Wait(); return new PersistentBlobCache(fs.GetDefaultRoamingCacheDirectory(), fs, BlobCache.TaskpoolScheduler); }); resolver.Register(() => userAccount.Value, typeof(IBlobCache), "UserAccount"); var secure = new Lazy<ISecureBlobCache>(() => { fs.CreateRecursive(fs.GetDefaultSecretCacheDirectory()).Wait(); return new EncryptedBlobCache(fs.GetDefaultRoamingCacheDirectory(), resolver.GetService<IEncryptionProvider>(), fs, BlobCache.TaskpoolScheduler); }); resolver.Register(() => secure.Value, typeof(ISecureBlobCache), null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Splat; #if UIKIT using MonoTouch.Foundation; #endif #if APPKIT using MonoMac.Foundation; #endif #if ANDROID using Android.App; #endif namespace Akavache.Deprecated { public class Registrations : IWantsToRegisterStuff { public void Register(IMutableDependencyResolver resolver) { if (ModeDetector.InUnitTestRunner()) return; var localCache = default(Lazy<IBlobCache>); var userAccount = default(Lazy<IBlobCache>); var secure = default(Lazy<ISecureBlobCache>); localCache = new Lazy<IBlobCache>(() => { var fs = resolver.GetService<IFilesystemProvider>(); return new CPersistentBlobCache(fs.GetDefaultLocalMachineCacheDirectory(), fs); }); userAccount = new Lazy<IBlobCache>(() => { var fs = resolver.GetService<IFilesystemProvider>(); return new CPersistentBlobCache(fs.GetDefaultRoamingCacheDirectory(), fs); }); secure = new Lazy<ISecureBlobCache>(() => { var fs = resolver.GetService<IFilesystemProvider>(); return new CEncryptedBlobCache(fs.GetDefaultRoamingCacheDirectory(), resolver.GetService<IEncryptionProvider>(), fs); }); resolver.Register(() => localCache.Value, typeof(IBlobCache), "LocalMachine"); resolver.Register(() => userAccount.Value, typeof(IBlobCache), "UserAccount"); resolver.Register(() => secure.Value, typeof(ISecureBlobCache), null); } } }
mit
C#
d6e7e06ff3ab3a57043bdb6a0b1e3a8782f8ab72
Update ZoomHelper.cs
wieslawsoltes/MatrixPanAndZoomDemo,wieslawsoltes/PanAndZoom,PanAndZoom/PanAndZoom,PanAndZoom/PanAndZoom,wieslawsoltes/PanAndZoom
src/Avalonia.Controls.PanAndZoom/ZoomHelper.cs
src/Avalonia.Controls.PanAndZoom/ZoomHelper.cs
using System; using static System.Math; namespace Avalonia.Controls.PanAndZoom { /// <summary> /// Zoom helper methods. /// </summary> public static class ZoomHelper { /// <summary> /// Calculate scrollable properties. /// </summary> /// <param name="bounds">The view bounds.</param> /// <param name="matrix">The transform matrix.</param> /// <param name="extent">The extent of the scrollable content.</param> /// <param name="viewport">The size of the viewport.</param> /// <param name="offset">The current scroll offset.</param> public static void CalculateScrollable(Rect bounds, Matrix matrix, out Size extent, out Size viewport, out Vector offset) { var transformed = bounds.TransformToAABB(matrix); var width = transformed.Size.Width; var height = transformed.Size.Height; var ex = matrix.M31; var ey = matrix.M32; extent = new Size( width + Math.Abs(ex), height + Math.Abs(ey)); viewport = bounds.Size; var ox = matrix.M31 * matrix.M11; var oy = matrix.M32 * matrix.M22; var offsetX = ox < 0 ? Abs(ox) : 0; var offsetY = oy < 0 ? Abs(oy) : 0; offset = new Vector(offsetX, offsetY); } } }
using System; using static System.Math; namespace Avalonia.Controls.PanAndZoom { /// <summary> /// Zoom helper methods. /// </summary> public static class ZoomHelper { /// <summary> /// Calculate scrollable properties. /// </summary> /// <param name="bounds">The view bounds.</param> /// <param name="matrix">The transform matrix.</param> /// <param name="extent">The extent of the scrollable content.</param> /// <param name="viewport">The size of the viewport.</param> /// <param name="offset">The current scroll offset.</param> public static void CalculateScrollable(Rect bounds, Matrix matrix, out Size extent, out Size viewport, out Vector offset) { var transformed = bounds.TransformToAABB(matrix); var width = transformed.Size.Width; var height = transformed.Size.Height; var x = matrix.M31; var y = matrix.M32; extent = new Size( width + Math.Abs(x), height + Math.Abs(y)); viewport = bounds.Size; var offsetX = x < 0 ? Abs(x) : 0; var offsetY = y < 0 ? Abs(y) : 0; offset = new Vector(offsetX, offsetY); } } }
mit
C#
0ef544267b750fd2b9928e7c2014d9957e1e002a
Change EnumExtensions to public
kiyoaki/bitflyer-api-dotnet-client
src/BitFlyer.Apis/Extensions/EnumExtensions.cs
src/BitFlyer.Apis/Extensions/EnumExtensions.cs
using System; using System.Collections.Concurrent; using System.Linq; using System.Runtime.Serialization; #if NET_CORE using System.Reflection; #endif namespace BitFlyer.Apis { public static class EnumExtensions { private static readonly ConcurrentDictionary<Enum, string> EnumMemberCache = new ConcurrentDictionary<Enum, string>(); public static string GetEnumMemberValue(this Enum value) { string returnValue; if (EnumMemberCache.TryGetValue(value, out returnValue)) { return returnValue; } #if NET_CORE var attributes = value.GetType().GetTypeInfo().GetField(value.ToString()).GetCustomAttributes<EnumMemberAttribute>(false); #else var attributes = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(EnumMemberAttribute), false) as EnumMemberAttribute[]; #endif returnValue = attributes?.FirstOrDefault()?.Value; if (returnValue != null) { EnumMemberCache.TryAdd(value, returnValue); } return returnValue; } } }
using System; using System.Collections.Concurrent; using System.Linq; using System.Runtime.Serialization; #if NET_CORE using System.Reflection; #endif namespace BitFlyer.Apis { internal static class EnumExtensions { private static readonly ConcurrentDictionary<Enum, string> EnumMemberCache = new ConcurrentDictionary<Enum, string>(); internal static string GetEnumMemberValue(this Enum value) { string returnValue; if (EnumMemberCache.TryGetValue(value, out returnValue)) { return returnValue; } #if NET_CORE var attributes = value.GetType().GetTypeInfo().GetField(value.ToString()).GetCustomAttributes<EnumMemberAttribute>(false); #else var attributes = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(EnumMemberAttribute), false) as EnumMemberAttribute[]; #endif returnValue = attributes?.FirstOrDefault()?.Value; if (returnValue != null) { EnumMemberCache.TryAdd(value, returnValue); } return returnValue; } } }
mit
C#
37eafc6ac5f9bc2623be872d166a7e6164b06070
Allow easier subclassing of metadata dialog
ermshiperete/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso
SIL.Windows.Forms/ClearShare/WinFormsUI/MetadataEditorDialog.cs
SIL.Windows.Forms/ClearShare/WinFormsUI/MetadataEditorDialog.cs
using System; using System.Windows.Forms; using L10NSharp; namespace SIL.Windows.Forms.ClearShare.WinFormsUI { public partial class MetadataEditorDialog : SIL.Windows.Forms.Miscellaneous.FormForUsingPortableClipboard { private readonly Metadata _originalMetaData; private Metadata _returnMetaData; public MetadataEditorDialog(Metadata originalMetaData) { _originalMetaData = originalMetaData; InitializeComponent(); _metadataEditorControl.Metadata = _returnMetaData = originalMetaData.DeepCopy(); ShowCreator = true; } /// <summary> /// Set this to false if you don't want to collect info on who created it (e.g. you're just getting copyright/license) /// </summary> public bool ShowCreator { get { return _metadataEditorControl.ShowCreator; } set { _metadataEditorControl.ShowCreator = value; Text = value ? LocalizationManager.GetString("MetadataEditor.TitleWithCredit", "Credit, Copyright, and License") : LocalizationManager.GetString("MetadataEditor.TitleNoCredit", "Copyright and License"); } } public Metadata Metadata { get { return _returnMetaData; } } private void _cancelButton_Click(object sender, EventArgs e) { _returnMetaData = _originalMetaData; DialogResult = DialogResult.Cancel; Close(); } private void _okButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; //we can't have a custom license without some description of it var customLicense = _returnMetaData.License as CustomLicense; if(customLicense!=null && string.IsNullOrEmpty(customLicense.RightsStatement)) _returnMetaData.License = new NullLicense(); Close(); } // allow subclass to access these methods/properties. protected virtual void _minimallyCompleteCheckTimer_Tick(object sender, EventArgs e) { _okButton.Enabled = _metadataEditorControl.Metadata.IsMinimallyComplete; } protected MetadataEditorControl MetadataControl { get { return _metadataEditorControl; } } protected Button OkButton { get { return _okButton; } } } }
using System; using System.Windows.Forms; using L10NSharp; namespace SIL.Windows.Forms.ClearShare.WinFormsUI { public partial class MetadataEditorDialog : SIL.Windows.Forms.Miscellaneous.FormForUsingPortableClipboard { private readonly Metadata _originalMetaData; private Metadata _returnMetaData; public MetadataEditorDialog(Metadata originalMetaData) { _originalMetaData = originalMetaData; InitializeComponent(); _metadataEditorControl.Metadata = _returnMetaData = originalMetaData.DeepCopy(); ShowCreator = true; } /// <summary> /// Set this to false if you don't want to collect info on who created it (e.g. you're just getting copyright/license) /// </summary> public bool ShowCreator { get { return _metadataEditorControl.ShowCreator; } set { _metadataEditorControl.ShowCreator = value; Text = value ? LocalizationManager.GetString("MetadataEditor.TitleWithCredit", "Credit, Copyright, and License") : LocalizationManager.GetString("MetadataEditor.TitleNoCredit", "Copyright and License"); } } public Metadata Metadata { get { return _returnMetaData; } } private void _cancelButton_Click(object sender, EventArgs e) { _returnMetaData = _originalMetaData; DialogResult = DialogResult.Cancel; Close(); } private void _okButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; //we can't have a custom license without some description of it var customLicense = _returnMetaData.License as CustomLicense; if(customLicense!=null && string.IsNullOrEmpty(customLicense.RightsStatement)) _returnMetaData.License = new NullLicense(); Close(); } private void _minimallyCompleteCheckTimer_Tick(object sender, EventArgs e) { _okButton.Enabled = _metadataEditorControl.Metadata.IsMinimallyComplete; } } }
mit
C#
c2eb0e7f1f0669393317eb918ae4fba475f76329
add version attributes
coolkev/LewisTech.Utils
src/LewisTech.Utils/Properties/AssemblyInfo.cs
src/LewisTech.Utils/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("LewisTech.Utils")] [assembly: AssemblyDescription("Common utility classes and extension methods")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lewis Technology, Inc.")] [assembly: AssemblyProduct("LewisTech.Utils")] [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("4ffe8326-4355-4b1d-a8ef-d66ca6b8786a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0")] [assembly: AssemblyFileVersion("2.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("LewisTech.Utils")] [assembly: AssemblyDescription("Common utility classes and extension methods")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lewis Technology, Inc.")] [assembly: AssemblyProduct("LewisTech.Utils")] [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("4ffe8326-4355-4b1d-a8ef-d66ca6b8786a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] //[assembly: AssemblyVersion("2.0.1")] //[assembly: AssemblyFileVersion("2.0.1")]
mit
C#
cdcbcece579ced70659561f0bab81a7211a8bfea
Replace state file instead of overwriting it
zr40/steamgames
SteamGames/State.cs
SteamGames/State.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using ProtoBuf; namespace SteamGames { [ProtoContract] internal sealed class State { internal static readonly string BasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SteamGames"); private static readonly string statePath = Path.Combine(BasePath, "state.dat"); private static readonly string savePath = Path.Combine(BasePath, "state new.dat"); [ProtoMember(1)] internal string WebApiKey; [ProtoMember(2)] internal ulong SteamId; [ProtoMember(3)] internal readonly Dictionary<string, List<int>> Tags = new Dictionary<string, List<int>>(); [ProtoMember(4)] internal Dictionary<string, CheckState> TagState = new Dictionary<string, CheckState>(); [ProtoMember(5)] internal readonly Dictionary<string, Filter> Filters; [ProtoMember(6)] internal string SelectedFilter = "All games"; private State() { Filters = new Dictionary<string, Filter>(); } internal static State Load() { if (!Directory.Exists(BasePath)) { Directory.CreateDirectory(BasePath); } if (!Directory.Exists(ImageCache.cachePath)) { Directory.CreateDirectory(ImageCache.cachePath); } if (File.Exists(statePath)) { using (FileStream s = File.OpenRead(statePath)) { return Serializer.Deserialize<State>(s); } } return new State(); } internal void Save() { foreach (string key in Tags.Keys.ToList()) { if (Tags[key].Count == 0) { Tags.Remove(key); } } foreach (string key in TagState.Keys.ToList()) { if (!Tags.ContainsKey(key)) { TagState.Remove(key); } } if (File.Exists(savePath)) File.Delete(savePath); using (FileStream s = File.Open(savePath, FileMode.CreateNew, FileAccess.Write)) { Serializer.Serialize(s, this); } if (File.Exists(statePath)) File.Delete(statePath); File.Move(savePath, statePath); } [ProtoAfterDeserialization] private void AfterDeserialization() { CreatePredicates(); CreateAllGamesIfNoFilterExists(); } private void CreatePredicates() { foreach (var filter in Filters) { filter.Value.CreatePredicate(this); } } private void CreateAllGamesIfNoFilterExists() { if (Filters.Count == 0) Filters.Add("All games", new Filter("All games", "true", this)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using ProtoBuf; namespace SteamGames { [ProtoContract] internal sealed class State { internal static readonly string BasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SteamGames"); private static readonly string savePath = Path.Combine(BasePath, "state.dat"); [ProtoMember(1)] internal string WebApiKey; [ProtoMember(2)] internal ulong SteamId; [ProtoMember(3)] internal readonly Dictionary<string, List<int>> Tags = new Dictionary<string, List<int>>(); [ProtoMember(4)] internal Dictionary<string, CheckState> TagState = new Dictionary<string, CheckState>(); [ProtoMember(5)] internal readonly Dictionary<string, Filter> Filters; [ProtoMember(6)] internal string SelectedFilter = "All games"; private State() { Filters = new Dictionary<string, Filter>(); } internal static State Load() { if (!Directory.Exists(BasePath)) { Directory.CreateDirectory(BasePath); } if (!Directory.Exists(ImageCache.cachePath)) { Directory.CreateDirectory(ImageCache.cachePath); } if (File.Exists(savePath)) { using (FileStream s = File.OpenRead(savePath)) { return Serializer.Deserialize<State>(s); } } return new State(); } internal void Save() { foreach (string key in Tags.Keys.ToList()) { if (Tags[key].Count == 0) { Tags.Remove(key); } } foreach (string key in TagState.Keys.ToList()) { if (!Tags.ContainsKey(key)) { TagState.Remove(key); } } using (FileStream s = File.Open(savePath, FileMode.Truncate, FileAccess.Write)) { Serializer.Serialize(s, this); } } [ProtoAfterDeserialization] private void AfterDeserialization() { CreatePredicates(); CreateAllGamesIfNoFilterExists(); } private void CreatePredicates() { foreach (var filter in Filters) { filter.Value.CreatePredicate(this); } } private void CreateAllGamesIfNoFilterExists() { if (Filters.Count == 0) Filters.Add("All games", new Filter("All games", "true", this)); } } }
mit
C#
aa9a5f08c24036f65e1fe289307c1906af99f8bd
Set new assembly version for release 1.1.0.0
seiggy/AsterNET.ARI,skrusty/AsterNET.ARI,skrusty/AsterNET.ARI,skrusty/AsterNET.ARI,seiggy/AsterNET.ARI,seiggy/AsterNET.ARI
AsterNET.ARI/Properties/AssemblyInfo.cs
AsterNET.ARI/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("AsterNET.ARI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AsterNET.ARI")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0d0c4e4f-1ff2-427b-9027-d010b0edd456")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.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("AsterNET.ARI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AsterNET.ARI")] [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("0d0c4e4f-1ff2-427b-9027-d010b0edd456")] // 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#
53b58c39c35d1a97c8ab9d8204acb87fd7f6337c
Enable cors request from everywhere.
dimitardanailov/cloud_conf_varna_microservices_rest_api,dimitardanailov/cloud_conf_varna_microservices_rest_api,dimitardanailov/cloud_conf_varna_microservices_rest_api
CloudConfVarnaEdition4.0-RestAPI/Controllers/MatchesController.cs
CloudConfVarnaEdition4.0-RestAPI/Controllers/MatchesController.cs
using CloudConfVarnaEdition4._0.Entities; using CloudConfVarnaEdition4._0.Repositories; using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CloudConfVarnaEdition4._0_RestAPI.Controllers { // Allow CORS for all origins. (Caution!) [EnableCors(origins: "*", headers: "*", methods: "*")] public class MatchesController : ApiController { private static readonly MongoDbMatchRepository _repository = new MongoDbMatchRepository(); // GET api/matches public IEnumerable<Match> Get() { // Add Dummy records to database _repository.AddDummyMatches(); return _repository.GetAllEntities(); } } }
using CloudConfVarnaEdition4._0.Entities; using CloudConfVarnaEdition4._0.Repositories; using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CloudConfVarnaEdition4._0_RestAPI.Controllers { [EnableCors(origins: "http://cloudconfvarnamicroservices.azurewebsites.net", headers: "*", methods: "*")] public class MatchesController : ApiController { private static readonly MongoDbMatchRepository _repository = new MongoDbMatchRepository(); // GET api/matches public IEnumerable<Match> Get() { // Add Dummy records to database _repository.AddDummyMatches(); return _repository.GetAllEntities(); } } }
mit
C#
1939f7030f75150ee04030215fe5157759b6842c
Use the new valid rename field tag id in integration tests
aelij/roslyn,AmadeusW/roslyn,gafter/roslyn,Giftednewt/roslyn,heejaechang/roslyn,jamesqo/roslyn,panopticoncentral/roslyn,robinsedlaczek/roslyn,tvand7093/roslyn,agocke/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,OmarTawfik/roslyn,mavasani/roslyn,agocke/roslyn,khyperia/roslyn,abock/roslyn,dotnet/roslyn,diryboy/roslyn,AlekseyTs/roslyn,OmarTawfik/roslyn,shyamnamboodiripad/roslyn,jkotas/roslyn,davkean/roslyn,mmitche/roslyn,reaction1989/roslyn,swaroop-sridhar/roslyn,stephentoub/roslyn,MichalStrehovsky/roslyn,tannergooding/roslyn,genlu/roslyn,ErikSchierboom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,dpoeschl/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,jkotas/roslyn,panopticoncentral/roslyn,aelij/roslyn,eriawan/roslyn,mmitche/roslyn,srivatsn/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,paulvanbrenk/roslyn,bartdesmet/roslyn,physhi/roslyn,AmadeusW/roslyn,aelij/roslyn,DustinCampbell/roslyn,nguerrera/roslyn,cston/roslyn,AlekseyTs/roslyn,AnthonyDGreen/roslyn,eriawan/roslyn,orthoxerox/roslyn,brettfo/roslyn,mattscheffer/roslyn,sharwell/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mavasani/roslyn,reaction1989/roslyn,physhi/roslyn,tvand7093/roslyn,dotnet/roslyn,TyOverby/roslyn,mattscheffer/roslyn,heejaechang/roslyn,TyOverby/roslyn,tmeschter/roslyn,abock/roslyn,tmat/roslyn,orthoxerox/roslyn,xasx/roslyn,abock/roslyn,jcouv/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,genlu/roslyn,kelltrick/roslyn,dpoeschl/roslyn,cston/roslyn,MattWindsor91/roslyn,VSadov/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,pdelvo/roslyn,pdelvo/roslyn,khyperia/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,VSadov/roslyn,nguerrera/roslyn,bkoelman/roslyn,Giftednewt/roslyn,davkean/roslyn,cston/roslyn,AlekseyTs/roslyn,VSadov/roslyn,jmarolf/roslyn,srivatsn/roslyn,robinsedlaczek/roslyn,swaroop-sridhar/roslyn,jasonmalinowski/roslyn,tmeschter/roslyn,jamesqo/roslyn,wvdd007/roslyn,stephentoub/roslyn,AmadeusW/roslyn,jamesqo/roslyn,Hosch250/roslyn,jcouv/roslyn,genlu/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,weltkante/roslyn,MattWindsor91/roslyn,tannergooding/roslyn,bkoelman/roslyn,AnthonyDGreen/roslyn,mavasani/roslyn,Giftednewt/roslyn,sharwell/roslyn,physhi/roslyn,CaptainHayashi/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,mattscheffer/roslyn,KevinRansom/roslyn,lorcanmooney/roslyn,tannergooding/roslyn,gafter/roslyn,dotnet/roslyn,paulvanbrenk/roslyn,tmat/roslyn,davkean/roslyn,KirillOsenkov/roslyn,DustinCampbell/roslyn,srivatsn/roslyn,xasx/roslyn,jcouv/roslyn,tmeschter/roslyn,shyamnamboodiripad/roslyn,Hosch250/roslyn,Hosch250/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,MattWindsor91/roslyn,kelltrick/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,xasx/roslyn,paulvanbrenk/roslyn,DustinCampbell/roslyn,KevinRansom/roslyn,pdelvo/roslyn,orthoxerox/roslyn,mgoertz-msft/roslyn,mmitche/roslyn,heejaechang/roslyn,CaptainHayashi/roslyn,robinsedlaczek/roslyn,eriawan/roslyn,dpoeschl/roslyn,lorcanmooney/roslyn,TyOverby/roslyn,lorcanmooney/roslyn,diryboy/roslyn,swaroop-sridhar/roslyn,gafter/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,kelltrick/roslyn,MichalStrehovsky/roslyn,stephentoub/roslyn,tvand7093/roslyn,AnthonyDGreen/roslyn,bkoelman/roslyn,weltkante/roslyn,jkotas/roslyn,MattWindsor91/roslyn,weltkante/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,khyperia/roslyn,reaction1989/roslyn,diryboy/roslyn,CaptainHayashi/roslyn,agocke/roslyn
src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/InlineRenameDialog_OutOfProc.cs
src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/InlineRenameDialog_OutOfProc.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class InlineRenameDialog_OutOfProc : OutOfProcComponent { private const string ChangeSignatureDialogAutomationId = "InlineRenameDialog"; public string ValidRenameTag => RenameFieldBackgroundAndBorderTag.TagId; public InlineRenameDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void Invoke() { VisualStudioInstance.ExecuteCommand("Refactor.Rename"); VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename); } public void ToggleIncludeComments() { VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.C, ShiftState.Alt)); VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename); } public void ToggleIncludeStrings() { VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.S, ShiftState.Alt)); VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename); } public void ToggleIncludeOverloads() { VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.O, ShiftState.Alt)); VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class InlineRenameDialog_OutOfProc : OutOfProcComponent { private const string ChangeSignatureDialogAutomationId = "InlineRenameDialog"; public string ValidRenameTag => "RoslynRenameValidTag"; public InlineRenameDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void Invoke() { VisualStudioInstance.ExecuteCommand("Refactor.Rename"); VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename); } public void ToggleIncludeComments() { VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.C, ShiftState.Alt)); VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename); } public void ToggleIncludeStrings() { VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.S, ShiftState.Alt)); VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename); } public void ToggleIncludeOverloads() { VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.O, ShiftState.Alt)); VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename); } } }
mit
C#
b35aebe48da63881900bb7593707c59ff2e3f30c
add twitter login actions
tblocksharer/tblocksharer,tblocksharer/tblocksharer
src/TBlockSharer/Controllers/HomeController.cs
src/TBlockSharer/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TBlockSharer.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public async Task<ActionResult> Login() { var auth = new MvcSignInAuthorizer { CredentialStore = new SessionStateCredentialStore { ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"] } }; string callbackUrl = Request.Url.ToString().Replace("Login", "LoginComplete"); return await auth.BeginAuthorizationAsync(new Uri(callbackUrl)); } public async Task<ActionResult> LoginComplete() { var auth = new MvcAuthorizer { CredentialStore = new SessionStateCredentialStore() }; await auth.CompleteAuthorizeAsync(Request.Url); //return View("Index", new Models.Index() { BlockedUsers = new string[] { "hello" } }); return RedirectToAction("Index"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TBlockSharer.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
agpl-3.0
C#
08477cf27ec639a8228fd1690434f9a58de1b8c2
update to show send local
amri/RebusExample
Program.cs
Program.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; using Rebus.Activation; using Rebus.Config; using Rebus.Handlers; namespace RebusExample { class Program { private static void Main(string[] args) { using (var activator = new BuiltinHandlerActivator()) { activator.Register(() => new PrintDateTime()); var connectionString = ConfigurationManager.AppSettings["serviceBus"]; Configure.With(activator) .Transport(t => t.UseAzureServiceBus(connectionString, "rebusQueue")).Start(); var timer = new Timer(); timer.Elapsed += delegate { activator.Bus.SendLocal(DateTime.Now).Wait(); }; timer.Interval = 1000; timer.Start(); Console.ReadLine(); } } } internal class PrintDateTime : IHandleMessages<DateTime> { public async Task Handle(DateTime message) { Console.WriteLine("The time is {0}",message); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using Rebus.Activation; using Rebus.Config; namespace RebusExample { class Program { private static void Main(string[] args) { using (var activator = new BuiltinHandlerActivator()) { var connectionString = ConfigurationManager.AppSettings["serviceBus"]; Configure.With(activator) .Transport(t => t.UseAzureServiceBus(connectionString, "rebusQueue")).Start(); } Console.WriteLine("q"); Console.ReadLine(); } } }
mit
C#
df9a0990f11d22cc8d0fcba81bd10c4da50d686d
Add readonly to Label members
0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced
src/csharp/Intel/Iced/Intel/Assembler/Label.cs
src/csharp/Intel/Iced/Intel/Assembler/Label.cs
/* Copyright (C) 2018-2019 de4dot@gmail.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. */ #if ENCODER && BLOCK_ENCODER using System; namespace Iced.Intel { /// <summary> /// A label that can be created by <see cref="Assembler.CreateLabel"/>. /// </summary> public struct Label : IEquatable<Label> { internal Label(string? name, ulong id) { Name = name ?? "___label"; Id = id; InstructionIndex = -1; } /// <summary> /// Name of this label. /// </summary> public readonly string Name; /// <summary> /// Id of this label. /// </summary> public readonly ulong Id; /// <summary> /// Gets the instruction index associated with this label. This is setup after calling <see cref="Assembler.Label"/>. /// </summary> public int InstructionIndex { readonly get; internal set; } /// <summary> /// <c>true</c> if this label is empty and was not created by <see cref="Assembler.CreateLabel"/>. /// </summary> public readonly bool IsEmpty => Id == 0; /// <inheritdoc /> public override readonly string ToString() => $"{Name}@{Id}"; /// <inheritdoc /> public readonly bool Equals(Label other) => Name == other.Name && Id == other.Id; /// <inheritdoc /> public override readonly bool Equals(object? obj) => obj is Label other && Equals(other); /// <inheritdoc /> public override readonly int GetHashCode() { unchecked { return (Name.GetHashCode() * 397) ^ Id.GetHashCode(); } } /// <summary> /// Equality operator for <see cref="Label"/> /// </summary> /// <param name="left">Label</param> /// <param name="right">Label</param> /// <returns></returns> public static bool operator ==(Label left, Label right) => left.Equals(right); /// <summary> /// Inequality operator for <see cref="Label"/> /// </summary> /// <param name="left">Label</param> /// <param name="right">Label</param> /// <returns></returns> public static bool operator !=(Label left, Label right) => !left.Equals(right); } } #endif
/* Copyright (C) 2018-2019 de4dot@gmail.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. */ #if ENCODER && BLOCK_ENCODER using System; namespace Iced.Intel { /// <summary> /// A label that can be created by <see cref="Assembler.CreateLabel"/>. /// </summary> public struct Label : IEquatable<Label> { internal Label(string? name, ulong id) { Name = name ?? "___label"; Id = id; InstructionIndex = -1; } /// <summary> /// Name of this label. /// </summary> public readonly string Name; /// <summary> /// Id of this label. /// </summary> public readonly ulong Id; /// <summary> /// Gets the instruction index associated with this label. This is setup after calling <see cref="Assembler.Label"/>. /// </summary> public int InstructionIndex { get; internal set; } /// <summary> /// <c>true</c> if this label is empty and was not created by <see cref="Assembler.CreateLabel"/>. /// </summary> public bool IsEmpty => Id == 0; /// <inheritdoc /> public override string ToString() => $"{Name}@{Id}"; /// <inheritdoc /> public bool Equals(Label other) => Name == other.Name && Id == other.Id; /// <inheritdoc /> public override bool Equals(object? obj) => obj is Label other && Equals(other); /// <inheritdoc /> public override int GetHashCode() { unchecked { return (Name.GetHashCode() * 397) ^ Id.GetHashCode(); } } /// <summary> /// Equality operator for <see cref="Label"/> /// </summary> /// <param name="left">Label</param> /// <param name="right">Label</param> /// <returns></returns> public static bool operator ==(Label left, Label right) => left.Equals(right); /// <summary> /// Inequality operator for <see cref="Label"/> /// </summary> /// <param name="left">Label</param> /// <param name="right">Label</param> /// <returns></returns> public static bool operator !=(Label left, Label right) => !left.Equals(right); } } #endif
mit
C#
d18769b6a85c4cdcba3197b6f5ac703b403a2c52
Remove unnecessary focus overriding.
Nabile-Rahmani/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,default0/osu-framework,RedNesto/osu-framework,paparony03/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,default0/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,Tom94/osu-framework,RedNesto/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,naoey/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework
osu.Framework/Graphics/UserInterface/Tab/TabDropDownMenu.cs
osu.Framework/Graphics/UserInterface/Tab/TabDropDownMenu.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE // TODO: Hide header when no items in dropdown namespace osu.Framework.Graphics.UserInterface.Tab { public abstract class TabDropDownMenu<T> : DropDownMenu<T> { protected TabDropDownMenu() { RelativeSizeAxes = Axes.X; Header.Anchor = Anchor.TopRight; Header.Origin = Anchor.TopRight; ContentContainer.Anchor = Anchor.TopRight; ContentContainer.Origin = Anchor.TopRight; } internal float HeaderHeight { get { return Header.DrawHeight; } set { Header.Height = value; } } internal float HeaderWidth { get { return Header.DrawWidth; } set { Header.Width = value; } } internal void HideItem(T val) { int index; if (ItemDictionary.TryGetValue(val, out index)) ItemList[index]?.Hide(); } internal void ShowItem(T val) { int index; if (ItemDictionary.TryGetValue(val, out index)) ItemList[index]?.Show(); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Input; // TODO: Hide header when no items in dropdown namespace osu.Framework.Graphics.UserInterface.Tab { public abstract class TabDropDownMenu<T> : DropDownMenu<T> { protected TabDropDownMenu() { RelativeSizeAxes = Axes.X; Header.Anchor = Anchor.TopRight; Header.Origin = Anchor.TopRight; ContentContainer.Anchor = Anchor.TopRight; ContentContainer.Origin = Anchor.TopRight; } internal float HeaderHeight { get { return Header.DrawHeight; } set { Header.Height = value; } } internal float HeaderWidth { get { return Header.DrawWidth; } set { Header.Width = value; } } internal void HideItem(T val) { int index; if (ItemDictionary.TryGetValue(val, out index)) ItemList[index]?.Hide(); } internal void ShowItem(T val) { int index; if (ItemDictionary.TryGetValue(val, out index)) ItemList[index]?.Show(); } // Don't give focus or it will cover tabs protected override bool OnFocus(InputState state) => false; } }
mit
C#
52e9fb4a7ee954d93e02860bd5adebdaad254e6d
Implement Main logic
dirkrombauts/fizz-buzz
ConsoleApp/Program.cs
ConsoleApp/Program.cs
using System; namespace FizzBuzz.ConsoleApp { class Program { static void Main() { var fizzBuzzer = new FizzBuzzer(); for (int i = 1; i <= 100; i++) { Console.WriteLine(fizzBuzzer.Print(i)); } } } }
using System; namespace FizzBuzz.ConsoleApp { class Program { static void Main() { } } }
mit
C#
7c116ff09cafbc7f4cc7e801d4eb477b2ee79b03
Update assembly version to 1.1.1.0
lench4991/EasyScaleMod
EasyScale/Properties/AssemblyInfo.cs
EasyScale/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("EasyScale")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lench")] [assembly: AssemblyProduct("EasyScale")] [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("6a16f1f7-31c2-4cae-9fd3-0c56bbd29757")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.1.0")] [assembly: AssemblyFileVersion("1.1.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("EasyScale")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lench")] [assembly: AssemblyProduct("EasyScale")] [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("6a16f1f7-31c2-4cae-9fd3-0c56bbd29757")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
mit
C#
5cb9dbdf4af177cbcbc8915c2cba780c0d15a285
Make sure there is an error code available
ArachisH/Eavesdrop
Eavesdrop/Internals/NativeMethods.cs
Eavesdrop/Internals/NativeMethods.cs
using System; using System.Runtime.InteropServices; namespace Eavesdrop { internal static class NativeMethods { [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength); } }
using System; using System.Runtime.InteropServices; namespace Eavesdrop { internal static class NativeMethods { [DllImport("wininet.dll")] public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength); } }
mit
C#
f0cf524cc4a5ffc982e9628a05af47a0c0b0623c
Set default back to Chrome driver.
dwhelan/atdd_training,dwhelan/atdd_training
cs/WebSpecs/Support/Hooks.cs
cs/WebSpecs/Support/Hooks.cs
using System.Collections.Generic; using BoDi; using Coypu; using Coypu.Drivers; using TechTalk.SpecFlow; namespace WebSpecs.Support { [Binding] public class Hooks { private readonly IObjectContainer objectContainer; private BrowserSession browser; private readonly List<Page> pages = new List<Page>(); public Hooks(IObjectContainer objectContainer) { this.objectContainer = objectContainer; } [BeforeScenario] public void Before() { var configuration = new SessionConfiguration { // Uncomment the Browser you want Browser = Browser.Firefox, //Browser = Browser.Chrome, //Browser = Browser.InternetExplorer, //Browser = Browser.PhantomJS, }; browser = new PageBrowserSession(configuration); objectContainer.RegisterInstanceAs(browser); objectContainer.RegisterInstanceAs(pages); } [AfterScenario] public void DisposeSites() { browser.Dispose(); } } }
using System.Collections.Generic; using BoDi; using Coypu; using Coypu.Drivers; using TechTalk.SpecFlow; namespace WebSpecs.Support { [Binding] public class Hooks { private readonly IObjectContainer objectContainer; private BrowserSession browser; private readonly List<Page> pages = new List<Page>(); public Hooks(IObjectContainer objectContainer) { this.objectContainer = objectContainer; } [BeforeScenario] public void Before() { var configuration = new SessionConfiguration { // Uncomment the Browser you want //Browser = Browser.Firefox, //Browser = Browser.Chrome, //Browser = Browser.InternetExplorer, Browser = Browser.PhantomJS, }; browser = new PageBrowserSession(configuration); objectContainer.RegisterInstanceAs(browser); objectContainer.RegisterInstanceAs(pages); } [AfterScenario] public void DisposeSites() { browser.Dispose(); } } }
mit
C#
b54f60d9cb4385f3c42dffe6548a563fc261bc00
Add functionality to ExpenditureDate class to compare dates and format year correctly
xyon1/Expenditure-App
GeneralUseClasses/ExpenditureDate.cs
GeneralUseClasses/ExpenditureDate.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GeneralUseClasses.Exceptions; namespace GeneralUseClasses { public class ExpenditureDate { public int day; public int month; public int year; public ExpenditureDate() { day = new int(); month = new int(); year = new int(); } public ExpenditureDate(int day, int month, int year) { this.day = day; this.month = month; FormatYear(year); } private void FormatYear(int year) { if (year.ToString().Length == 4) { this.year = year; ; } else if (year.ToString().Length == 2 || year.ToString().Length == 1) { this.year = year + 2000; } else { throw new ExceptionForUser("Year is in unusable format"); } } public bool IsNotEarlierThan(ExpenditureDate date) { bool isLaterThan = true; if (!(this.year >= date.year)) { isLaterThan = false; } else if (!(this.month >= date.month) && this.year == date.year) { isLaterThan = false; } else if (!(this.day >= date.day) && this.month == date.month && this.year == date.year) { isLaterThan = false; } return isLaterThan; } public bool IsNotLaterThan(ExpenditureDate date) { bool isEarlierThan = true; if (!(this.year <= date.year)) { isEarlierThan = false; } else if (!(this.month <= date.month) && this.year == date.year) { isEarlierThan = false; } else if (!(this.day <= date.day) && this.month == date.month && this.year == date.year) { isEarlierThan = false; } return isEarlierThan; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(this.day.ToString("D2")); sb.Append("/"); sb.Append(this.month.ToString("D2")); sb.Append("/"); sb.Append(this.year); return sb.ToString(); } public bool IsTheSameDateAs(ExpenditureDate date) { bool sameDate = false; sameDate = date.day == this.day ? true : false; sameDate = (date.month == this.month) && sameDate ? true : false; sameDate = (date.year == this.year) && sameDate ? true : false; return sameDate; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GeneralUseClasses { public class ExpenditureDate { public int day { get; set; } public int month { get; set; } public int year { get; set; } public ExpenditureDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } } }
apache-2.0
C#
d8ba089c3ce98081afa002ea0b7a234598b89adf
Revert "Quarantine all ProjectTemplate tests until dotnet new lock issue is resolved." (#21831)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/ProjectTemplates/test/AssemblyInfo.AssemblyFixtures.cs
src/ProjectTemplates/test/AssemblyInfo.AssemblyFixtures.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.E2ETesting; using Microsoft.AspNetCore.Testing; using Templates.Test.Helpers; using Xunit; [assembly: TestFramework("Microsoft.AspNetCore.E2ETesting.XunitTestFrameworkWithAssemblyFixture", "ProjectTemplates.Tests")] [assembly: Microsoft.AspNetCore.E2ETesting.AssemblyFixture(typeof(ProjectFactoryFixture))] [assembly: Microsoft.AspNetCore.E2ETesting.AssemblyFixture(typeof(SeleniumStandaloneServer))]
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.E2ETesting; using Microsoft.AspNetCore.Testing; using Templates.Test.Helpers; using Xunit; [assembly: TestFramework("Microsoft.AspNetCore.E2ETesting.XunitTestFrameworkWithAssemblyFixture", "ProjectTemplates.Tests")] [assembly: Microsoft.AspNetCore.E2ETesting.AssemblyFixture(typeof(ProjectFactoryFixture))] [assembly: Microsoft.AspNetCore.E2ETesting.AssemblyFixture(typeof(SeleniumStandaloneServer))] [assembly: QuarantinedTest("Investigation pending in https://github.com/dotnet/aspnetcore/issues/21748")]
apache-2.0
C#
938f9c508031bb28a39b690d9ae6f342f5fba2ff
Adjust scene menu position and rotation
miccl/VisualiseR,miccl/VisualiseR
Assets/VisualiseR/Code/Scripts/VisualiseR/Showroom/Controller/ShowShowroomSceneMenuCommand.cs
Assets/VisualiseR/Code/Scripts/VisualiseR/Showroom/Controller/ShowShowroomSceneMenuCommand.cs
using strange.extensions.command.impl; using strange.extensions.context.api; using UnityEngine; namespace VisualiseR.Showroom { /// <summary> /// Command to show the scene menu. /// </summary> public class ShowShowroomSceneMenuCommand : Command { private static readonly JCsLogger Logger = new JCsLogger(typeof(ShowShowroomSceneMenuCommand)); [Inject] public bool _isShown { get; set; } [Inject(ContextKeys.CONTEXT_VIEW)] public GameObject _contextView { get; set; } [Inject] public ShowroomSceneMenuIsShownSignal ShowroomSceneMenuIsShownSignal { get; set; } public override void Execute() { Logger.InfoFormat("Showing scene menu"); ShowSceneMenu(); ShowObjects(); ShowroomSceneMenuIsShownSignal.Dispatch(_isShown); } private void ShowObjects() { var objects = _contextView.transform.Find("Objects").gameObject; objects.SetActive(!_isShown); } private void ShowSceneMenu() { var sceneMenu = GameObject.Find("Menus").transform.Find("ShowroomSceneMenuCanvas").gameObject; sceneMenu.SetActive(_isShown); if (_isShown) { AdjustPositionAndRotation(sceneMenu); } } private static void AdjustPositionAndRotation(GameObject sceneMenu) { Vector3 shift = Camera.main.transform.forward.normalized * 4; Vector3 pos = Camera.main.transform.position + shift; sceneMenu.transform.position = pos; if (sceneMenu.transform.localPosition.y < 0) { sceneMenu.transform.localPosition = new Vector3(sceneMenu.transform.localPosition.x, 0, sceneMenu.transform.localPosition.z); } Vector3 relativePos = Camera.main.transform.position - pos; sceneMenu.transform.rotation = Quaternion.LookRotation(relativePos); sceneMenu.transform.Rotate(0, 180, 0); var rot = sceneMenu.transform.eulerAngles; rot.x = 0; sceneMenu.transform.eulerAngles = rot; } } }
using strange.extensions.command.impl; using strange.extensions.context.api; using UnityEngine; namespace VisualiseR.Showroom { /// <summary> /// Command to show the scene menu. /// </summary> public class ShowShowroomSceneMenuCommand : Command { private static readonly JCsLogger Logger = new JCsLogger(typeof(ShowShowroomSceneMenuCommand)); [Inject] public bool _isShown { get; set; } [Inject(ContextKeys.CONTEXT_VIEW)] public GameObject _contextView { get; set; } [Inject] public ShowroomSceneMenuIsShownSignal ShowroomSceneMenuIsShownSignal { get; set; } public override void Execute() { Logger.InfoFormat("Showing scene menu"); ShowSceneMenu(); ShowObjects(); ShowroomSceneMenuIsShownSignal.Dispatch(_isShown); } private void ShowObjects() { var objects = _contextView.transform.Find("Objects").gameObject; objects.SetActive(!_isShown); } private void ShowSceneMenu() { var sceneMenu = GameObject.Find("Menus").transform.Find("ShowroomSceneMenuCanvas").gameObject; sceneMenu.SetActive(_isShown); if (_isShown) { AdjustPositionAndRotation(sceneMenu); } } private static void AdjustPositionAndRotation(GameObject sceneMenu) { Vector3 shift = Camera.main.transform.forward.normalized * 4; Vector3 pos = Camera.main.transform.position + shift; sceneMenu.transform.position = pos; if (sceneMenu.transform.position.y < 0) { sceneMenu.transform.position = new Vector3(pos.x, 0, pos.z); } Vector3 relativePos = Camera.main.transform.position - pos; sceneMenu.transform.rotation = Quaternion.LookRotation(relativePos); sceneMenu.transform.Rotate(0, 180, 0); } } }
apache-2.0
C#
3c7e820773879fbb0e96934e57ab5158ad393d0c
remove the directory check
bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,base33/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,lars-erik/Umbraco-CMS,arknu/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,aadfPT/Umbraco-CMS,base33/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tompipe/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,lars-erik/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,tompipe/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,WebCentrum/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,aadfPT/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,NikRimington/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,arknu/Umbraco-CMS,aaronpowell/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,WebCentrum/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,NikRimington/Umbraco-CMS,WebCentrum/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,aaronpowell/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,aadfPT/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,aaronpowell/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,lars-erik/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,base33/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,tompipe/Umbraco-CMS
src/umbraco.cms/businesslogic/utilities/Zip.cs
src/umbraco.cms/businesslogic/utilities/Zip.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using System.Web; using umbraco; namespace umbraco.cms.businesslogic.utilities { public class Zip { public static void UnPack(string ZipFilePath, string UnPackDirectory, bool DeleteZipFile) { ZipFile.ExtractToDirectory(ZipFilePath, UnPackDirectory); if (DeleteZipFile) File.Delete(ZipFilePath); } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using System.Web; using umbraco; namespace umbraco.cms.businesslogic.utilities { public class Zip { public static void UnPack(string ZipFilePath, string UnPackDirectory, bool DeleteZipFile) { if (Directory.Exists(UnPackDirectory) != true) { Directory.CreateDirectory(UnPackDirectory); } ZipFile.ExtractToDirectory(ZipFilePath, UnPackDirectory); if (DeleteZipFile) File.Delete(ZipFilePath); } } }
mit
C#
74bc2db8c9675a0e8367c1420b2d4c246f03b16a
Set sink version to match Serilog version.
tugberkugurlu/serilog-sinks-mongodb,serilog/serilog-sinks-mongodb
assets/CommonAssemblyInfo.cs
assets/CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.4.204.0")] [assembly: AssemblyInformationalVersion("1.0.0")]
using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.1.1.1")] [assembly: AssemblyInformationalVersion("1.0.0")]
apache-2.0
C#
13612695778ac6b2c6e42302442564efbccfc873
Correct negative values under arm64
jherby2k/AudioWorks
AudioWorks/src/AudioWorks.Extensibility/Int24.cs
AudioWorks/src/AudioWorks.Extensibility/Int24.cs
/* Copyright © 2018 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ using System.Runtime.InteropServices; namespace AudioWorks.Extensibility { [StructLayout(LayoutKind.Sequential)] readonly struct Int24 { readonly byte _byte1; readonly byte _byte2; readonly byte _byte3; internal Int24(float value) { _byte1 = (byte) value; _byte2 = (byte) (((int) value >> 8) & 0xFF); _byte3 = (byte) (((int) value >> 16) & 0xFF); } public static implicit operator int(Int24 value) => value._byte1 | value._byte2 << 8 | ((sbyte) value._byte3 << 16); } }
/* Copyright © 2018 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ using System.Runtime.InteropServices; namespace AudioWorks.Extensibility { [StructLayout(LayoutKind.Sequential)] readonly struct Int24 { readonly byte _byte1; readonly byte _byte2; readonly byte _byte3; internal Int24(float value) { _byte1 = (byte) value; _byte2 = (byte) (((uint) value >> 8) & 0xFF); _byte3 = (byte) (((uint) value >> 16) & 0xFF); } public static implicit operator int(Int24 value) => value._byte1 | value._byte2 << 8 | ((sbyte) value._byte3 << 16); } }
agpl-3.0
C#
7a502daa265a989bdec1da9b065c6d2ef002ec50
Update Cake.Issues.Recipe to 0.4.1
cake-contrib/Cake.Recipe,cake-contrib/Cake.Recipe
Cake.Recipe/Content/addins.cake
Cake.Recipe/Content/addins.cake
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.9.1 #addin nuget:?package=Cake.Coveralls&version=0.10.2 #addin nuget:?package=Cake.Coverlet&version=2.5.1 #addin nuget:?package=Portable.BouncyCastle&version=1.8.5 #addin nuget:?package=MimeKit&version=2.9.1 #addin nuget:?package=MailKit&version=2.8.0 #addin nuget:?package=MimeTypesMap&version=1.0.8 #addin nuget:?package=Cake.Email.Common&version=0.4.2 #addin nuget:?package=Cake.Email&version=0.10.0 #addin nuget:?package=Cake.Figlet&version=1.3.1 #addin nuget:?package=Cake.Gitter&version=0.11.1 #addin nuget:?package=Cake.Incubator&version=5.1.0 #addin nuget:?package=Cake.Kudu&version=0.11.0 #addin nuget:?package=Cake.MicrosoftTeams&version=0.9.0 #addin nuget:?package=Cake.Slack&version=0.13.0 #addin nuget:?package=Cake.Transifex&version=0.9.1 #addin nuget:?package=Cake.Twitter&version=0.10.1 #addin nuget:?package=Cake.Wyam&version=2.2.9 #load nuget:?package=Cake.Issues.Recipe&version=0.4.1 Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if (BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if (BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.9.1 #addin nuget:?package=Cake.Coveralls&version=0.10.2 #addin nuget:?package=Cake.Coverlet&version=2.5.1 #addin nuget:?package=Portable.BouncyCastle&version=1.8.5 #addin nuget:?package=MimeKit&version=2.9.1 #addin nuget:?package=MailKit&version=2.8.0 #addin nuget:?package=MimeTypesMap&version=1.0.8 #addin nuget:?package=Cake.Email.Common&version=0.4.2 #addin nuget:?package=Cake.Email&version=0.10.0 #addin nuget:?package=Cake.Figlet&version=1.3.1 #addin nuget:?package=Cake.Gitter&version=0.11.1 #addin nuget:?package=Cake.Incubator&version=5.1.0 #addin nuget:?package=Cake.Kudu&version=0.11.0 #addin nuget:?package=Cake.MicrosoftTeams&version=0.9.0 #addin nuget:?package=Cake.Slack&version=0.13.0 #addin nuget:?package=Cake.Transifex&version=0.9.1 #addin nuget:?package=Cake.Twitter&version=0.10.1 #addin nuget:?package=Cake.Wyam&version=2.2.9 #load nuget:?package=Cake.Issues.Recipe&version=0.4.0 Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if (BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if (BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
mit
C#
767a6e1ecb25ea85940140df30279e2aff506371
Bump Version
Bottswana/ShadowUtility
ShadowForm/Properties/AssemblyInfo.cs
ShadowForm/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("Shadow Utility")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Shadow Utility")] [assembly: AssemblyCopyright("Copyright © James Botting 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("0d478b38-d0d9-407e-a6cc-395bf8d924da")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Shadow Utility")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Shadow Utility")] [assembly: AssemblyCopyright("Copyright © James Botting 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("0d478b38-d0d9-407e-a6cc-395bf8d924da")] // 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#
b65e9df8416af287ea477988586098238ac7259f
Format docs
bartlomiejwolk/TPPCamera
Enums/Mode.cs
Enums/Mode.cs
public enum Mode { /// <summary> /// Camera moves with the target transform instantly. /// </summary> Instantenous, /// <summary> /// If target transform moves withing defined dead zone, camera /// will not follow. /// </summary> DeadZone }
public enum Mode { /// <summary> /// Camera moves with the target transform instantly. /// </summary> Instantenous, /// <summary> /// If target transform moves withing defined dead zone, camera /// will not follow. /// </summary> DeadZone }
mit
C#
ca5d0d00ee6fa02d7bfe9d8a64b541c72142e4cc
Read from log stream and use a simple filter
Ailuridaes/solid-doodle,djmlee013/solid-doodle,Ailuridaes/solid-doodle,onema/solid-doodle,onema/solid-doodle,djmlee013/solid-doodle
LogParser/Function.cs
LogParser/Function.cs
using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Text.RegularExpressions; using Amazon.CloudWatchLogs; using Amazon.Lambda.Core; using LogParser.Model; using Newtonsoft.Json; namespace LogParser { public class Function { //--- Fields --- private readonly IAmazonCloudWatchLogs _cloudWatchClient; private const string FILTER = @"^(\[[A-Z ]+\])"; private static readonly Regex filter = new Regex(FILTER, RegexOptions.Compiled | RegexOptions.CultureInvariant); //--- Constructors --- public Function() { _cloudWatchClient = new AmazonCloudWatchLogsClient(); } //--- Methods --- [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public void Handler(CloudWatchLogsEvent cloudWatchLogsEvent, ILambdaContext context) { // Level One Console.WriteLine($"THIS IS THE DATA: {cloudWatchLogsEvent.AwsLogs.Data}"); var data = DecompressLogData(cloudWatchLogsEvent.AwsLogs.Data); Console.WriteLine($"THIS IS THE DECODED, UNCOMPRESSED DATA: {data}"); var events = JsonConvert.DeserializeObject<DecompressedEvents>(data).LogEvents; var filteredEvents = events.Where(x => filter.IsMatch(x.Message)).ToList(); filteredEvents.ForEach(x => Console.WriteLine(x.Message)); } public static string DecompressLogData(string value) { var gzip = Convert.FromBase64String(value); using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress)) return new StreamReader(stream).ReadToEnd(); } } }
using System; using Amazon.CloudWatchLogs; using Amazon.Lambda.Core; namespace LogParser { //--- Classes --- public class CloudWatchLogsEvent { //--- Properties --- public Awslogs awslogs { get; set; } } public class Awslogs { //--- Properties --- public string data { get; set; } } public class Function { //--- Fields --- private readonly IAmazonCloudWatchLogs _cloudWatchClient; //--- Methods --- public Function() { _cloudWatchClient = new AmazonCloudWatchLogsClient(); } [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public void Handler(CloudWatchLogsEvent cloudWatchLogsEvent, ILambdaContext context) { Console.WriteLine(cloudWatchLogsEvent.awslogs.data); } } }
mit
C#
78633a5950ad25b286fc282f93434e0753578fba
Stop logging to console all text from text editor.
mrward/typescript-addin,mrward/typescript-addin,chrisber/typescript-addin,chrisber/typescript-addin
src/TypeScriptBinding/Hosting/TypeScriptContext.cs
src/TypeScriptBinding/Hosting/TypeScriptContext.cs
// // TypeScriptContext.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (C) 2013 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using ICSharpCode.Core; using ICSharpCode.SharpDevelop.Project; using Noesis.Javascript; using TypeScriptHosting; namespace ICSharpCode.TypeScriptBinding.Hosting { public class TypeScriptContext : IDisposable { JavascriptContext context = new JavascriptContext(); LanguageServiceShimHost host = new LanguageServiceShimHost(); ScriptLoader scriptLoader = new ScriptLoader(); public TypeScriptContext() { context.SetParameter("host", host); context.Run(scriptLoader.GetTypeScriptServicesScript()); } public void Dispose() { context.Dispose(); } public void AddFile(FileName fileName, string text) { host.AddFile(fileName.ToString(), text); if (host.getScriptCount() == 1) { context.Run(scriptLoader.GetMainScript()); } } public void UpdateFile(FileName fileName, string text) { if (host.getScriptCount() == 0) { AddFile(fileName, text); } else { host.UpdateFile(fileName.ToString(), text); } } public CompletionInfo GetCompletionItems(FileName fileName, int offset, string text, bool memberCompletion) { host.position = offset; host.fileName = fileName.ToString(); host.isMemberCompletion = memberCompletion; context.Run(scriptLoader.GetMemberCompletionScript()); return host.CompletionResult.result; } } }
// // TypeScriptContext.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (C) 2013 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using ICSharpCode.Core; using ICSharpCode.SharpDevelop.Project; using Noesis.Javascript; using TypeScriptHosting; namespace ICSharpCode.TypeScriptBinding.Hosting { public class TypeScriptContext : IDisposable { JavascriptContext context = new JavascriptContext(); LanguageServiceShimHost host = new LanguageServiceShimHost(); ScriptLoader scriptLoader = new ScriptLoader(); public TypeScriptContext() { context.SetParameter("host", host); context.Run(scriptLoader.GetTypeScriptServicesScript()); } public void Dispose() { context.Dispose(); } public void AddFile(FileName fileName, string text) { host.AddFile(fileName.ToString(), text); if (host.getScriptCount() == 1) { context.Run(scriptLoader.GetMainScript()); } } public void UpdateFile(FileName fileName, string text) { if (host.getScriptCount() == 0) { AddFile(fileName, text); } else { host.UpdateFile(fileName.ToString(), text); } } public CompletionInfo GetCompletionItems(FileName fileName, int offset, string text, bool memberCompletion) { host.position = offset; host.fileName = fileName.ToString(); host.isMemberCompletion = memberCompletion; context.Run(scriptLoader.GetMemberCompletionScript()); Console.WriteLine("text=" + text); return host.CompletionResult.result; } } }
mit
C#
9cb00ebd972203787b31ca1e7f9fd48c85d9713b
Check lengths.
Peter-Juhasz/HX-Main
HX-Main/2D.cs
HX-Main/2D.cs
namespace System.Linq { using System; using System.Collections.Generic; /// <summary> /// Provides extensions methods to 2-dimensional arrays. /// </summary> public static partial class ExtensionsTo2DArrays { /// <summary> /// Determines whether two arrays are equal by comparing their elements using an equality comparer. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="second">The array to compare.</param> /// <param name="comparer">An equality comparer to use to compare elements.</param> /// <returns></returns> public static bool ArrayEqual<T>(this T[,] source, T[,] second, IEqualityComparer<T> comparer) { if (source == null) throw new ArgumentNullException("source"); if (second == null) throw new ArgumentNullException("second"); if (comparer == null) throw new ArgumentNullException("comparer"); int width = source.GetLength(0), height = source.GetLength(1); if (width != second.GetLength(0)) throw new ArgumentException("second", "The width of the second array must match the width of the source array."); if (height != second.GetLength(1)) throw new ArgumentException("second", "The height of the second array must match the height of the source array."); for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) if (!comparer.Equals(source[x, y], second[x, y])) return false; return true; } /// <summary> /// Determines whether two arrays are equal by comparing their elements using the default equality comparer. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="second">The array to compare.</param> /// <returns></returns> public static bool ArrayEqual<T>(this T[,] source, T[,] second) where T : IEquatable<T> { return source.ArrayEqual(second, EqualityComparer<T>.Default); } } }
namespace System.Linq { using System; using System.Collections.Generic; /// <summary> /// Provides extensions methods to 2-dimensional arrays. /// </summary> public static partial class ExtensionsTo2DArrays { /// <summary> /// Determines whether two arrays are equal by comparing their elements using an equality comparer. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="second">The array to compare.</param> /// <param name="comparer">An equality comparer to use to compare elements.</param> /// <returns></returns> public static bool ArrayEqual<T>(this T[,] source, T[,] second, IEqualityComparer<T> comparer) { if (source == null) throw new ArgumentNullException("source"); if (second == null) throw new ArgumentNullException("second"); if (comparer == null) throw new ArgumentNullException("comparer"); int width = source.GetLength(0), height = source.GetLength(1); for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) if (!comparer.Equals(source[x, y], second[x, y])) return false; return true; } /// <summary> /// Determines whether two arrays are equal by comparing their elements using the default equality comparer. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="second">The array to compare.</param> /// <returns></returns> public static bool ArrayEqual<T>(this T[,] source, T[,] second) where T : IEquatable<T> { return source.ArrayEqual(second, EqualityComparer<T>.Default); } } }
mit
C#
6bc31f6f2ed63f179fd7269210cd5c497816a031
Update DockerContainerIdComponent.cs
MatthewKing/DeviceId
src/DeviceId.Linux/Components/DockerContainerIdComponent.cs
src/DeviceId.Linux/Components/DockerContainerIdComponent.cs
using System.IO; using System.Text.RegularExpressions; namespace DeviceId.Linux.Components; /// <summary> /// An implementation of <see cref="IDeviceIdComponent"/> that uses the cgroup to read the docker container id. /// </summary> public class DockerContainerIdComponent : IDeviceIdComponent { private readonly string _cGroupFile; /// <summary> /// Initializes a new instance of the <see cref="DockerContainerIdComponent"/> class. /// </summary> public DockerContainerIdComponent() :this("/proc/1/cgroup") { } internal DockerContainerIdComponent(string cGroupFile) { _cGroupFile = cGroupFile; } /// <summary> /// Gets the component value. /// </summary> /// <returns>The component value.</returns> public string GetValue() { if (string.IsNullOrWhiteSpace(_cGroupFile) || !File.Exists(_cGroupFile)) { return null; } using (var file = File.OpenText(_cGroupFile)) { if (TryGetContainerId(file, out string containerId)) { return containerId; } } return null; } private static bool TryGetContainerId(StreamReader reader, out string containerId) { Regex regex = new("(\\d)+\\:(.)+?\\:(/.+?)??(/docker[-/])([0-9a-f]+)"); string line; while ((line = reader?.ReadLine()) != null) { Match match = regex.Match(line); if (match.Success) { containerId = match.Groups[5].Value; return true; } } containerId = default; return false; } }
using System.IO; using System.Text.RegularExpressions; namespace DeviceId.Linux.Components; /// <summary> /// An implementation of <see cref="IDeviceIdComponent"/> that uses the cgroup to read the docker container id. /// </summary> public class DockerContainerIdComponent : IDeviceIdComponent { private readonly string _cGroupFile; /// <summary> /// Initializes a new instance of the <see cref="DockerContainerIdComponent"/> class. /// </summary> public DockerContainerIdComponent() :this("/proc/1/cgroup") { } internal DockerContainerIdComponent(string cGroupFile) { _cGroupFile = cGroupFile; } /// <summary> /// Gets the component value. /// </summary> /// <returns>The component value.</returns> public string GetValue() { if (string.IsNullOrWhiteSpace(_cGroupFile) || !File.Exists(_cGroupFile)) { return null; } using (var file = File.OpenText(_cGroupFile)) { if (TryGetContainerId(file, out string containerId)) { return containerId; } } return null; } private bool TryGetContainerId(StreamReader reader, out string containerId) { Regex regex = new("(\\d)+\\:(.)+?\\:(/.+?)??(/docker[-/])([0-9a-f]+)"); string line; while ((line = reader?.ReadLine()) != null) { Match match = regex.Match(line); if (match.Success) { containerId = match.Groups[5].Value; return true; } } containerId = default; return false; } }
mit
C#
9bf56c8ddd1acb65887f99eb7e142caaed13efdd
Remove extra whitespace
KirillOsenkov/roslyn,abock/roslyn,aelij/roslyn,weltkante/roslyn,genlu/roslyn,tannergooding/roslyn,AmadeusW/roslyn,diryboy/roslyn,agocke/roslyn,mavasani/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,xasx/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,xasx/roslyn,KevinRansom/roslyn,davkean/roslyn,tmat/roslyn,agocke/roslyn,sharwell/roslyn,nguerrera/roslyn,gafter/roslyn,jmarolf/roslyn,jcouv/roslyn,mavasani/roslyn,AlekseyTs/roslyn,brettfo/roslyn,diryboy/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,wvdd007/roslyn,DustinCampbell/roslyn,abock/roslyn,bartdesmet/roslyn,genlu/roslyn,sharwell/roslyn,jmarolf/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,tmat/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,aelij/roslyn,sharwell/roslyn,davkean/roslyn,MichalStrehovsky/roslyn,VSadov/roslyn,xasx/roslyn,stephentoub/roslyn,gafter/roslyn,MichalStrehovsky/roslyn,tmat/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,DustinCampbell/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,genlu/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,aelij/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,weltkante/roslyn,gafter/roslyn,reaction1989/roslyn,abock/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,swaroop-sridhar/roslyn,stephentoub/roslyn,MichalStrehovsky/roslyn,reaction1989/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,swaroop-sridhar/roslyn,physhi/roslyn,weltkante/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,VSadov/roslyn,jcouv/roslyn,davkean/roslyn,heejaechang/roslyn,DustinCampbell/roslyn,dotnet/roslyn,stephentoub/roslyn,tannergooding/roslyn,nguerrera/roslyn,brettfo/roslyn,diryboy/roslyn,agocke/roslyn,panopticoncentral/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,brettfo/roslyn,dotnet/roslyn,VSadov/roslyn,reaction1989/roslyn
src/EditorFeatures/TestUtilities/TestObscuringTipManager.cs
src/EditorFeatures/TestUtilities/TestObscuringTipManager.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests { // In 15.6 the editor (QuickInfo in particular) took a dependency on // IObscuringTipManager, which is only exported in VS editor layer. // This is tracked by the editor bug https://devdiv.visualstudio.com/DevDiv/_workitems?id=544569. // Meantime a workaround is to export dummy IObscuringTipManager. [Export(typeof(IObscuringTipManager))] internal class TestObscuringTipManager : IObscuringTipManager { public void PushTip(ITextView view, IObscuringTip tip) { } public void RemoveTip(ITextView view, IObscuringTip tip) { } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests { // In 15.6 the editor (QuickInfo in particular) took a dependency on // IObscuringTipManager, which is only exported in VS editor layer. // This is tracked by the editor bug https://devdiv.visualstudio.com/DevDiv/_workitems?id=544569. // Meantime a workaround is to export dummy IObscuringTipManager. [Export(typeof(IObscuringTipManager))] internal class TestObscuringTipManager : IObscuringTipManager { public void PushTip(ITextView view, IObscuringTip tip) { } public void RemoveTip(ITextView view, IObscuringTip tip) { } } }
mit
C#
25e063359d3902ddc0efe29f7fb560375b11daf6
Optimize SerializableJsonProperty delegates
QuickenLoans/XSerializer,rlyczynski/XSerializer
XSerializer/SerializableJsonProperty.cs
XSerializer/SerializableJsonProperty.cs
using System; using System.Linq.Expressions; using System.Reflection; namespace XSerializer { internal class SerializableJsonProperty { private readonly string _name; private readonly Lazy<IJsonSerializerInternal> _serializer; private readonly Func<object, object> _getValue; private readonly Action<object, object> _setValue; public SerializableJsonProperty(PropertyInfo propertyInfo, bool encrypt) { if (propertyInfo.DeclaringType == null) { throw new ArgumentException("The DeclaringType of the PropertyInfo must not be null.", "propertyInfo"); } _name = propertyInfo.Name; _serializer = new Lazy<IJsonSerializerInternal>(() => JsonSerializerFactory.GetSerializer(propertyInfo.PropertyType, encrypt)); _getValue = GetGetValueFunc(propertyInfo, propertyInfo.DeclaringType); if (propertyInfo.CanWrite) { _setValue = GetSetValueAction(propertyInfo, propertyInfo.DeclaringType); } } public string Name { get { return _name; } } public void WriteValue(JsonWriter writer, object instance, IJsonSerializeOperationInfo info) { var value = _getValue(instance); writer.WriteValue(Name); writer.WriteNameValueSeparator(); _serializer.Value.SerializeObject(writer, value, info); } public object ReadValue(JsonReader reader, IJsonSerializeOperationInfo info) { return _serializer.Value.DeserializeObject(reader, info); } public void SetValue(object instance, JsonReader reader, IJsonSerializeOperationInfo info) { var value = ReadValue(reader, info); _setValue(instance, value); } private static Func<object, object> GetGetValueFunc(PropertyInfo propertyInfo, Type declaringType) { var instanceParameter = Expression.Parameter(typeof(object), "instance"); Expression property = Expression.Property(Expression.Convert(instanceParameter, declaringType), propertyInfo); if (propertyInfo.PropertyType.IsValueType) // Needs boxing. { property = Expression.Convert(property, typeof(object)); } var lambda = Expression.Lambda<Func<object, object>>(property, new[] { instanceParameter }); return lambda.Compile(); } private static Action<object, object> GetSetValueAction(PropertyInfo propertyInfo, Type declaringType) { var instanceParameter = Expression.Parameter(typeof(object), "instance"); var valueParameter = Expression.Parameter(typeof(object), "value"); Expression property = Expression.Property(Expression.Convert(instanceParameter, declaringType), propertyInfo); var assign = Expression.Assign(property, Expression.Convert(valueParameter, propertyInfo.PropertyType)); var lambda = Expression.Lambda<Action<object, object>>(assign, new[] { instanceParameter, valueParameter }); return lambda.Compile(); } } }
using System; using System.Reflection; namespace XSerializer { internal class SerializableJsonProperty { private readonly string _name; private readonly Lazy<IJsonSerializerInternal> _serializer; private readonly Func<object, object> _getValue; private readonly Action<object, object> _setValue; public SerializableJsonProperty(PropertyInfo propertyInfo, bool encrypt) { _name = propertyInfo.Name; _serializer = new Lazy<IJsonSerializerInternal>(() => JsonSerializerFactory.GetSerializer(propertyInfo.PropertyType, encrypt)); // TODO: Optimize these delegates. _getValue = instance => propertyInfo.GetValue(instance, null); _setValue = (instance, value) => propertyInfo.SetValue(instance, value, null); } public string Name { get { return _name; } } public void WriteValue(JsonWriter writer, object instance, IJsonSerializeOperationInfo info) { var value = _getValue(instance); writer.WriteValue(Name); writer.WriteNameValueSeparator(); _serializer.Value.SerializeObject(writer, value, info); } public object ReadValue(JsonReader reader, IJsonSerializeOperationInfo info) { return _serializer.Value.DeserializeObject(reader, info); } public void SetValue(object instance, JsonReader reader, IJsonSerializeOperationInfo info) { var value = ReadValue(reader, info); _setValue(instance, value); } } }
mit
C#
7f585445ef3d0c937799231cc2c01fe8e36460b6
Fix repository method call
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University.Launchpad/Tables/PositionsTable.cs
R7.University.Launchpad/Tables/PositionsTable.cs
// // PositionsTable.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2014-2015 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Collections; using System.Data; using System.Linq; using DotNetNuke.Entities.Modules; using R7.University.Components; using R7.University.Data; using System.Collections.Generic; namespace R7.University.Launchpad { public class PositionsTable: LaunchpadTableBase { public PositionsTable () : base ("Positions") { } public override DataTable GetDataTable (PortalModuleBase module, string search) { IList<PositionInfo> positions; using (var db = UniversityDbContextFactory.Instance.Create ()) { using (var repo = new UniversityRepository<PositionInfo> (db)) { // REVIEW: Cannot set comparison options positions = repo.Where (p => p.Title.Contains (search) || p.ShortTitle.Contains (search)) .ToList (); if (!positions.Any ()) { positions = db.Set<PositionInfo> ().ToList (); } } } return DataTableConstructor.FromIEnumerable (positions); } } }
// // PositionsTable.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2014-2015 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Collections; using System.Data; using System.Linq; using DotNetNuke.Entities.Modules; using R7.University.Components; using R7.University.Data; using System.Collections.Generic; namespace R7.University.Launchpad { public class PositionsTable: LaunchpadTableBase { public PositionsTable () : base ("Positions") { } public override DataTable GetDataTable (PortalModuleBase module, string search) { IList<PositionInfo> positions; using (var db = UniversityDbContextFactory.Instance.Create ()) { using (var repo = new UniversityRepository<PositionInfo> (db)) { // REVIEW: Cannot set comparison options positions = repo.GetObjects (p => p.Title.Contains (search) || p.ShortTitle.Contains (search)) .ToList (); if (!positions.Any ()) { positions = db.Positions.ToList (); } } } return DataTableConstructor.FromIEnumerable (positions); } } }
agpl-3.0
C#
9efedbe6ec38ae611e5120a3efee25576ac64927
Disable GroupTopoSort test
rsdn/CodeJam,NN---/CodeJam
Experimental/tests/Collections/GroupTopoSortTest.cs
Experimental/tests/Collections/GroupTopoSortTest.cs
using System.Collections.Generic; using System.Linq; using CodeJam.Strings; using NUnit.Framework; namespace CodeJam.Collections { [TestFixture] [Ignore("TDB")] public class GroupTopoSortTest { [TestCase(arg: new[] { "a:b", "b:c", "c" }, TestName = "Simple", ExpectedResult = "c, b, a")] [TestCase(arg: new[] { "a:c", "b:c", "c" }, ExpectedResult = "c, a, b")] [TestCase(arg: new[] { "a", "b", "c: a, b" }, ExpectedResult = "a, b, c")] [TestCase(arg: new[] { "a:c", "b:c", "c", "d:a, b" }, TestName = "Diamond", ExpectedResult = "c, a, b, d")] [TestCase(arg: new[] { "a", "b:a", "c" }, ExpectedResult = "a, c, b")] // TODO: add more cases public string GroupTopoSort(string[] source) { // Prepare dependency structure Dictionary<string, string[]> deps; var items = GetDepStructure(source, out deps); // Perform sort return items.GroupTopoSort(i => deps[i]).Select(l => l.Join(", ")).Join(" : "); } private static IEnumerable<string> GetDepStructure(IEnumerable<string> source, out Dictionary<string, string[]> deps) { var items = new HashSet<string>(); deps = new Dictionary<string, string[]>(); foreach (var itemStr in source) { var itemParts = itemStr.Split(':'); var item = itemParts[0].Trim(); items.Add(item); deps.Add( item, itemParts.Length > 1 ? itemParts[1].Split(',').Select(s => s.Trim()).ToArray() : Array<string>.Empty); } return items; } private static IEnumerable<Holder> GetDepStructure(IEnumerable<string> source, out Dictionary<Holder, Holder[]> deps) { Dictionary<string, string[]> innerDeps; var items = GetDepStructure(source, out innerDeps); deps = innerDeps.ToDictionary( kv => new Holder(kv.Key), kv => kv.Value.Select(v => new Holder(v)).ToArray(), new KeyEqualityComparer<Holder, string>(v => v.Value)); return items.Select(v => new Holder(v)); } private class Holder { public string Value { get; } public Holder(string value) { Value = value; } public override string ToString() => Value; } } }
using System.Collections.Generic; using System.Linq; using CodeJam.Strings; using NUnit.Framework; namespace CodeJam.Collections { [TestFixture] public class GroupTopoSortTest { [TestCase(arg: new[] { "a:b", "b:c", "c" }, ExpectedResult = "c, b, a")] [TestCase(arg: new[] { "a:c", "b:c", "c" }, ExpectedResult = "c, a, b")] [TestCase(arg: new[] { "a", "b", "c: a, b" }, ExpectedResult = "a, b, c")] [TestCase(arg: new[] { "a:c", "b:c", "c", "d:a, b" }, TestName = "Diamond", ExpectedResult = "c, a, b, d")] [TestCase(arg: new[] { "a", "b:a", "c" }, ExpectedResult = "a, c, b")] // TODO: add more cases public string GroupTopoSort(string[] source) { // Prepare dependency structure Dictionary<string, string[]> deps; var items = GetDepStructure(source, out deps); // Perform sort return items.GroupTopoSort(i => deps[i]).Select(l => l.Join(", ")).Join(" : "); } private static IEnumerable<string> GetDepStructure(IEnumerable<string> source, out Dictionary<string, string[]> deps) { var items = new HashSet<string>(); deps = new Dictionary<string, string[]>(); foreach (var itemStr in source) { var itemParts = itemStr.Split(':'); var item = itemParts[0].Trim(); items.Add(item); deps.Add( item, itemParts.Length > 1 ? itemParts[1].Split(',').Select(s => s.Trim()).ToArray() : Array<string>.Empty); } return items; } private static IEnumerable<Holder> GetDepStructure(IEnumerable<string> source, out Dictionary<Holder, Holder[]> deps) { Dictionary<string, string[]> innerDeps; var items = GetDepStructure(source, out innerDeps); deps = innerDeps.ToDictionary( kv => new Holder(kv.Key), kv => kv.Value.Select(v => new Holder(v)).ToArray(), new KeyEqualityComparer<Holder, string>(v => v.Value)); return items.Select(v => new Holder(v)); } private class Holder { public string Value { get; } public Holder(string value) { Value = value; } public override string ToString() => Value; } } }
mit
C#
9c962a4eb8b3c22e688b89f0ffc0edeca385f0a5
fix tests
SixLabors/Fonts
tests/SixLabors.Fonts.Tests/FontLoaderTests.cs
tests/SixLabors.Fonts.Tests/FontLoaderTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SixLabors.Fonts.Tests { using Xunit; public class FontLoaderTests { [Fact] public void LoadFontMetadata() { FontDescription description = FontDescription.LoadDescription(TestFonts.SimpleFontFileData()); Assert.Equal("SixLaborsSampleAB regular", description.FontName); Assert.Equal("Regular", description.FontSubFamilyName); } [Fact] public void LoadFont() { Font font = Font.LoadFont(TestFonts.SimpleFontFileData()); Assert.Equal("SixLaborsSampleAB regular", font.FontName); Assert.Equal("Regular", font.FontSubFamilyName); var glyph = font.GetGlyph('a'); var r = new GlyphRenderer(); glyph.RenderTo(r, 12, 72); // the test font only has characters .notdef, 'a' & 'b' defined Assert.Equal(7, r.ControlPoints.Count); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SixLabors.Fonts.Tests { using Xunit; public class FontLoaderTests { [Fact] public void LoadFontMetadata() { FontDescription description = FontDescription.LoadDescription(TestFonts.SimpleFontFileData()); Assert.Equal("SixLaborsSampleAB regular", description.FontName); Assert.Equal("Regular", description.FontSubFamilyName); } [Fact] public void LoadFont() { Font font = Font.LoadFont(TestFonts.SimpleFontFileData()); Assert.Equal("SixLaborsSampleAB regular", font.FontName); Assert.Equal("Regular", font.FontSubFamilyName); var glyph = font.GetGlyph('a'); var r = new GlyphRenderer(); glyph.RenderTo(r, 12, 72); // the test font only has characters .notdef, 'a' & 'b' defined Assert.Equal(4, r.ControlPoints.Count); } } }
apache-2.0
C#
274958669c826236e48f681b8edb3c00ea8bf2b7
Add early assert as sanity check
UselessToucan/osu,ppy/osu,smoogipooo/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,johnneijzen/osu,2yangk23/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,EVAST9919/osu,NeoAdonis/osu
osu.Game.Tests/Visual/Gameplay/TestScenePauseWhenInactive.cs
osu.Game.Tests/Visual/Gameplay/TestScenePauseWhenInactive.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual.Gameplay { [HeadlessTest] // we alter unsafe properties on the game host to test inactive window state. public class TestScenePauseWhenInactive : PlayerTestScene { protected new TestPlayer Player => (TestPlayer)base.Player; protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) { var beatmap = (Beatmap)base.CreateBeatmap(ruleset); beatmap.HitObjects.RemoveAll(h => h.StartTime < 30000); return beatmap; } [Resolved] private GameHost host { get; set; } public TestScenePauseWhenInactive() : base(new OsuRuleset()) { } [Test] public void TestDoesntPauseDuringIntro() { AddStep("set inactive", () => ((Bindable<bool>)host.IsActive).Value = false); AddStep("resume player", () => Player.GameplayClockContainer.Start()); AddAssert("ensure not paused", () => !Player.GameplayClockContainer.IsPaused.Value); AddUntilStep("wait for pause", () => Player.GameplayClockContainer.IsPaused.Value); AddAssert("time of pause is after gameplay start time", () => Player.GameplayClockContainer.GameplayClock.CurrentTime >= Player.DrawableRuleset.GameplayStartTime); } protected override Player CreatePlayer(Ruleset ruleset) => new TestPlayer(true, true, true); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual.Gameplay { [HeadlessTest] // we alter unsafe properties on the game host to test inactive window state. public class TestScenePauseWhenInactive : PlayerTestScene { protected new TestPlayer Player => (TestPlayer)base.Player; protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) { var beatmap = (Beatmap)base.CreateBeatmap(ruleset); beatmap.HitObjects.RemoveAll(h => h.StartTime < 30000); return beatmap; } [Resolved] private GameHost host { get; set; } public TestScenePauseWhenInactive() : base(new OsuRuleset()) { } [Test] public void TestDoesntPauseDuringIntro() { AddStep("set inactive", () => ((Bindable<bool>)host.IsActive).Value = false); AddStep("resume player", () => Player.GameplayClockContainer.Start()); AddUntilStep("wait for pause", () => Player.GameplayClockContainer.IsPaused.Value); AddAssert("time of pause is after gameplay start time", () => Player.GameplayClockContainer.GameplayClock.CurrentTime >= Player.DrawableRuleset.GameplayStartTime); } protected override Player CreatePlayer(Ruleset ruleset) => new TestPlayer(true, true, true); } }
mit
C#
6b43c5aa3b32a8f62a52bfdbc405a602aa1327a0
Fix For Broken Tests For CustomType List
NServiceKit/NServiceKit.Redis,nataren/NServiceKit.Redis,MindTouch/NServiceKit.Redis
tests/ServiceStack.Redis.Tests/Support/CustomTypeFactory.cs
tests/ServiceStack.Redis.Tests/Support/CustomTypeFactory.cs
using NUnit.Framework; using ServiceStack.Common.Tests.Models; namespace ServiceStack.Redis.Tests.Support { public class CustomTypeFactory : ModelFactoryBase<CustomType> { public CustomTypeFactory() { ModelConfig<CustomType>.Id(x => x.CustomId); } public override void AssertIsEqual(CustomType actual, CustomType expected) { Assert.AreEqual(actual.CustomId, expected.CustomId); Assert.AreEqual(actual.CustomName, expected.CustomName); } public override CustomType CreateInstance(int i) { return new CustomType { CustomId = i, CustomName = "Name" + i }; } } }
using NUnit.Framework; using ServiceStack.Common.Tests.Models; namespace ServiceStack.Redis.Tests.Support { public class CustomTypeFactory : ModelFactoryBase<CustomType> { public CustomTypeFactory() { ModelConfig<CustomType>.Id(x => x.CustomId); } public override void AssertIsEqual(CustomType actual, CustomType expected) { Assert.AreEqual(actual.CustomId, Is.EqualTo(expected.CustomId)); Assert.AreEqual(actual.CustomName, Is.EqualTo(expected.CustomName)); } public override CustomType CreateInstance(int i) { return new CustomType { CustomId = i, CustomName = "Name" + i }; } } }
bsd-3-clause
C#
67a4459203665ff8bfe534dd7dcbec48197cf6db
Add correct table mapping
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/CommitmentsV2/SFA.DAS.CommitmentsV2/Data/Configuration/ApprenticeshipUpdateConfiguration.cs
src/CommitmentsV2/SFA.DAS.CommitmentsV2/Data/Configuration/ApprenticeshipUpdateConfiguration.cs
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using SFA.DAS.CommitmentsV2.Models; namespace SFA.DAS.CommitmentsV2.Data.Configuration { public class ApprenticeshipUpdateConfiguration : IEntityTypeConfiguration<ApprenticeshipUpdate> { public void Configure(EntityTypeBuilder<ApprenticeshipUpdate> builder) { builder.ToTable("ApprenticeshipUpdate").HasKey(e => e.Id); builder.Property(e => e.Cost).HasColumnType("decimal(18, 0)"); builder.Property(e => e.CreatedOn).HasColumnType("datetime"); builder.Property(e => e.DateOfBirth).HasColumnType("datetime"); builder.Property(e => e.EffectiveFromDate).HasColumnType("datetime"); builder.Property(e => e.EffectiveToDate).HasColumnType("datetime"); builder.Property(e => e.EndDate).HasColumnType("datetime"); builder.Property(e => e.FirstName).HasMaxLength(100); builder.Property(e => e.LastName).HasMaxLength(100); builder.Property(e => e.StartDate).HasColumnType("datetime"); builder.Property(e => e.TrainingCode).HasMaxLength(20); builder.Property(e => e.TrainingName).HasMaxLength(126); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using SFA.DAS.CommitmentsV2.Models; namespace SFA.DAS.CommitmentsV2.Data.Configuration { public class ApprenticeshipUpdateConfiguration : IEntityTypeConfiguration<ApprenticeshipUpdate> { public void Configure(EntityTypeBuilder<ApprenticeshipUpdate> builder) { builder.Property(e => e.Cost).HasColumnType("decimal(18, 0)"); builder.Property(e => e.CreatedOn).HasColumnType("datetime"); builder.Property(e => e.DateOfBirth).HasColumnType("datetime"); builder.Property(e => e.EffectiveFromDate).HasColumnType("datetime"); builder.Property(e => e.EffectiveToDate).HasColumnType("datetime"); builder.Property(e => e.EndDate).HasColumnType("datetime"); builder.Property(e => e.FirstName).HasMaxLength(100); builder.Property(e => e.LastName).HasMaxLength(100); builder.Property(e => e.StartDate).HasColumnType("datetime"); builder.Property(e => e.TrainingCode).HasMaxLength(20); builder.Property(e => e.TrainingName).HasMaxLength(126); } } }
mit
C#
424cc0c4743891f54b9e5ae96938a11dba152bc4
use methodName convention
Pondidum/Conifer,Pondidum/Conifer
Test.WebApi/App_Start/WebApiConfig.cs
Test.WebApi/App_Start/WebApiConfig.cs
using System.Web.Http; using RestRouter; using RestRouter.Conventions; using StructureMap; using StructureMap.Graph; using Test.WebApi.Controllers; namespace Test.WebApi { public static class WebApiConfig { public static void Register(HttpConfiguration config) { var router = Router.Create(config, r => { //setup the default conventions, these 3 will generate routes like: // /Person/View/1234 r.DefaultConventionsAre(new IRouteConvention[] { new ControllerNameRouteConvention(), new MethodNameRouteConvention(), new ParameterNameRouteConvention(), new ActionEndsWithRawRouteConvention() }); r.Add<HomeController>(null); //no conventions applied to this route r.Add<PersonController>(); }); //configure your container of choice config.DependencyResolver = new StructureMapDependencyResolver(new Container(c => { c.Scan(a => { a.TheCallingAssembly(); a.WithDefaultConventions(); }); //just make sure RouteBuilder is the same instance each time: c.For<RouteBuilder>().Use(router); })); } } }
using System.Web.Http; using RestRouter; using RestRouter.Conventions; using StructureMap; using StructureMap.Graph; using Test.WebApi.Controllers; namespace Test.WebApi { public static class WebApiConfig { public static void Register(HttpConfiguration config) { var router = Router.Create(config, r => { //setup the default conventions, these 3 will generate routes like: // /Person/View/1234 r.DefaultConventionsAre(new IRouteConvention[] { new ControllerNameRouteConvention(), new ParameterNameRouteConvention(), new ActionEndsWithRawRouteConvention() }); r.Add<HomeController>(null); //no conventions applied to this route r.Add<PersonController>(); }); //configure your container of choice config.DependencyResolver = new StructureMapDependencyResolver(new Container(c => { c.Scan(a => { a.TheCallingAssembly(); a.WithDefaultConventions(); }); //just make sure RouteBuilder is the same instance each time: c.For<RouteBuilder>().Use(router); })); } } }
lgpl-2.1
C#
e268937217160734f0b3862773000afd7f4668e3
Increment version
Benrnz/BudgetAnalyser
BudgetAnalyser.Engine/Properties/AssemblyInfo.cs
BudgetAnalyser.Engine/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("BudgetAnalyser.Engine")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rees.biz")] [assembly: AssemblyProduct("BudgetAnalyser.Engine")] [assembly: AssemblyCopyright("Rees.biz 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("f599a2c9-9506-4ca8-bf33-7e2b34cca63d")] // 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.3.1.0")] [assembly: AssemblyFileVersion("1.3.1.0")] [assembly: InternalsVisibleTo("BudgetAnalyser.UnitTest")]
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("BudgetAnalyser.Engine")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rees.biz")] [assembly: AssemblyProduct("BudgetAnalyser.Engine")] [assembly: AssemblyCopyright("Rees.biz 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("f599a2c9-9506-4ca8-bf33-7e2b34cca63d")] // 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.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: InternalsVisibleTo("BudgetAnalyser.UnitTest")]
mit
C#
d49190077a00f9d96d17375282d64ab42061bfea
Clean up namespaces
corsairmarks/csharp-dataaccess-test
src/DataAccessTest/DataAccessTest.Web/DependencyResolution/Registry/DatabaseMigrationRegistry.cs
src/DataAccessTest/DataAccessTest.Web/DependencyResolution/Registry/DatabaseMigrationRegistry.cs
namespace DataAccessTest.Web.DependencyResolution.Registry { using System.Diagnostics; using System.Reflection; using DataAccessTest.DatabaseMigrations.Migrations; using FluentMigrator; using FluentMigrator.Runner; using FluentMigrator.Runner.Announcers; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.Processors.SqlServer; using StructureMap.Configuration.DSL; /// <summary> /// Configures dependency resolution for database migrations. /// </summary> public class DatabaseMigrationRegistry : Registry { /// <summary> /// Initializes a new instance of the <see cref="DatabaseMigrationRegistry"/> class. /// </summary> public DatabaseMigrationRegistry() { ForSingletonOf<IMigrationProcessorOptions>().Use<ProcessorOptions>() .Setter<bool>(po => po.PreviewOnly).Is(false) .Setter<int>(po => po.Timeout).Is(60); // StructureMap does not properly find the Action<string> controller when // attempting injection, so I resorted to specifying a concrete object for the Singleton ForSingletonOf<IAnnouncer>().Use(new TextWriterAnnouncer(s => Debug.Write(s))); var migrationsAssembly = Assembly.GetAssembly(typeof(InitialCreate)); ForSingletonOf<IRunnerContext>() .Use<RunnerContext>() .Setter<string>(rc => rc.Namespace) .Is(typeof(InitialCreate).Namespace); ForSingletonOf<IMigrationProcessorFactory>().Use<SqlServer2014ProcessorFactory>(); ForSingletonOf<IMigrationProcessor>() .Use(c => c.GetInstance<IMigrationProcessorFactory>().Create( c.GetInstance<string>("DefaultConnectionString"), c.GetInstance<IAnnouncer>(), c.GetInstance<IMigrationProcessorOptions>())); ForSingletonOf<IMigrationRunner>() .Use<MigrationRunner>() .SelectConstructor(() => new MigrationRunner(null as Assembly, null, null)) .Ctor<Assembly>() .Is(migrationsAssembly); } } }
namespace DataAccessTest.Web.DependencyResolution.Registry { using System.Diagnostics; using System.Linq; using System.Reflection; using DataAccessTest.DatabaseMigrations.Migrations; using FluentMigrator; using FluentMigrator.Infrastructure; using FluentMigrator.Runner; using FluentMigrator.Runner.Announcers; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.Processors.SqlServer; using StructureMap.Configuration.DSL; /// <summary> /// Configures dependency resolution for database migrations. /// </summary> public class DatabaseMigrationRegistry : Registry { /// <summary> /// Initializes a new instance of the <see cref="DatabaseMigrationRegistry"/> class. /// </summary> public DatabaseMigrationRegistry() { ForSingletonOf<IMigrationProcessorOptions>().Use<ProcessorOptions>() .Setter<bool>(po => po.PreviewOnly).Is(false) .Setter<int>(po => po.Timeout).Is(60); // StructureMap does not properly find the Action<string> controller when // attempting injection, so I resorted to specifying a concrete object for the Singleton ForSingletonOf<IAnnouncer>().Use(new TextWriterAnnouncer(s => Debug.Write(s))); var migrationsAssembly = Assembly.GetAssembly(typeof(InitialCreate)); ForSingletonOf<IRunnerContext>() .Use<RunnerContext>() .Setter<string>(rc => rc.Namespace) .Is(typeof(InitialCreate).Namespace); ForSingletonOf<IMigrationProcessorFactory>().Use<SqlServer2014ProcessorFactory>(); ForSingletonOf<IMigrationProcessor>() .Use(c => c.GetInstance<IMigrationProcessorFactory>().Create( c.GetInstance<string>("DefaultConnectionString"), c.GetInstance<IAnnouncer>(), c.GetInstance<IMigrationProcessorOptions>())); ForSingletonOf<IMigrationRunner>() .Use<MigrationRunner>() .SelectConstructor(() => new MigrationRunner(null as Assembly, null, null)) .Ctor<Assembly>() .Is(migrationsAssembly); } } }
mit
C#
0d5a573dae6972216091a3f8dfe5905896a5d589
Update TintedImageRenderer.cs
shrutinambiar/xamarin-forms-tinted-image
src/Plugin.CrossPlatformTintedImage.iOS/TintedImageRenderer.cs
src/Plugin.CrossPlatformTintedImage.iOS/TintedImageRenderer.cs
using Plugin.CrossPlatformTintedImage.iOS; using Plugin.CrossPlatformTintedImage.Abstractions; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))] namespace Plugin.CrossPlatformTintedImage.iOS { public class TintedImageRenderer : ImageRenderer { public static void Init() { } protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); SetTint(); } protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == TintedImage.TintColorProperty.PropertyName || e.PropertyName == TintedImage.SourceProperty.PropertyName) SetTint(); } void SetTint() { if (Control?.Image == null || Element == null) return; if (((TintedImage)Element).TintColor == Color.Transparent) { //Turn off tinting Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.Automatic); Control.TintColor = null; } else { //Apply tint color Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.AlwaysTemplate); Control.TintColor = ((TintedImage)Element).TintColor.ToUIColor(); } } } }
using Plugin.CrossPlatformTintedImage.iOS; using Plugin.CrossPlatformTintedImage.Abstractions; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))] namespace Plugin.CrossPlatformTintedImage.iOS { public class TintedImageRenderer : ImageRenderer { public static void Init() { } protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); SetTint(); } protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == TintedImage.TintColorProperty.PropertyName) SetTint(); } void SetTint() { if (Control?.Image == null || Element == null) return; if (((TintedImage)Element).TintColor == Color.Transparent) { //Turn off tinting Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.Automatic); Control.TintColor = null; } else { //Apply tint color Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.AlwaysTemplate); Control.TintColor = ((TintedImage)Element).TintColor.ToUIColor(); } } } }
mit
C#
33f558d0b9f490fdf5604e1acda233da4de75d29
Revert "Changed NetworkLevelLoader to be in line with new loading method."
hpoggie/Backstab-Networking
Framework/NetworkLevelLoader.cs
Framework/NetworkLevelLoader.cs
using UnityEngine; using UnityEngine.Networking; public class NetworkLevelLoader : NetScript { static int lastLevel = -108; bool[] status; bool hasServerLoaded = false; public void Start () { DontDestroyOnLoad(this); } public void AllLoadLevel (int level) { if (!backstab.IsServer) { Debug.LogError("Can't issue LoadLevel messages if not the server."); return; } status = new bool[backstab.NumConnections]; Rpc("LoadLevel", level); LoadLevel(level); } [RpcClients(qosType = QosType.ReliableSequenced)] private void LoadLevel (int level) { Application.LoadLevel(level); } void OnLevelWasLoaded (int level) { if (backstab.IsClient) { Rpc("OnClientFinishedLoading"); } else { hasServerLoaded = true; if (HasEveryoneLoaded()) { Rpc("OnLoadingFinished", lastLevel); OnLoadingFinished(lastLevel); } } lastLevel = level; } [RpcServer(qosType = QosType.ReliableSequenced)] private void OnClientFinishedLoading () { int recClientIndex = backstab.GetRecClientIndex(); if (recClientIndex == -1) { Debug.LogError("Recieved message from a non-connected client."); } else { status[recClientIndex]= true; } if (HasEveryoneLoaded()) { Rpc("OnLoadingFinished", lastLevel); } } public bool HasEveryoneLoaded () { if (!hasServerLoaded) return false; if (status == null || status.Length == 0) return true; foreach (bool b in status) { if (!b) return false; } return true; } //NOTE: Use OnNetworkLoadedLevel only if you're sure you need it. //If you spawn a NetScript that spawns more of itself, this loop will never terminate. [RpcClients(qosType = QosType.ReliableSequenced)] private void OnLoadingFinished (int level) { for (int i = 0; i < NetScript.Instances.Count; i++) { if (NetScript.Find(i) != null) { NetScript.Find(i).OnNetworkLoadedLevel(level); } } } }
using UnityEngine; using UnityEngine.Networking; using UnityEngine.SceneManagement; public class NetworkLevelLoader : NetScript { static int lastLevel = -108; bool[] status; bool hasServerLoaded = false; public void Start () { DontDestroyOnLoad(this); } public void AllLoadLevel (int level) { if (!backstab.IsServer) { Debug.LogError("Can't issue LoadLevel messages if not the server."); return; } status = new bool[backstab.NumConnections]; Rpc("LoadLevel", level); LoadLevel(level); } [RpcClients(qosType = QosType.ReliableSequenced)] private void LoadLevel (int level) { SceneManager.LoadScene(level); } void OnLevelWasLoaded (int level) { if (backstab.IsClient) { Rpc("OnClientFinishedLoading"); } else { hasServerLoaded = true; if (HasEveryoneLoaded()) { Rpc("OnLoadingFinished", lastLevel); OnLoadingFinished(lastLevel); } } lastLevel = level; } [RpcServer(qosType = QosType.ReliableSequenced)] private void OnClientFinishedLoading () { int recClientIndex = backstab.GetRecClientIndex(); if (recClientIndex == -1) { Debug.LogError("Recieved message from a non-connected client."); } else { status[recClientIndex]= true; } if (HasEveryoneLoaded()) { Rpc("OnLoadingFinished", lastLevel); } } public bool HasEveryoneLoaded () { if (!hasServerLoaded) return false; if (status == null || status.Length == 0) return true; foreach (bool b in status) { if (!b) return false; } return true; } //NOTE: Use OnNetworkLoadedLevel only if you're sure you need it. //If you spawn a NetScript that spawns more of itself, this loop will never terminate. [RpcClients(qosType = QosType.ReliableSequenced)] private void OnLoadingFinished (int level) { for (int i = 0; i < NetScript.Instances.Count; i++) { if (NetScript.Find(i) != null) { NetScript.Find(i).OnNetworkLoadedLevel(level); } } } }
mit
C#
8dc3a511a3e9e529874db1f93f166b719482d96a
update versioning info
0xFireball/FireCryptEx
FireCrypt/FireCryptEx/Properties/AssemblyInfo.cs
FireCrypt/FireCryptEx/Properties/AssemblyInfo.cs
/* * THIS PROGRAM AND ITS SOURCE CODE ARE PROVIDED TO YOU FREE OF CHARGE. * YOU ARE PROHIBITED FROM REMOVING THIS NOTICE FROM THIS SOURCE DOCUMENT * OR OTHERWISE MODIFYING IT. * * FireCryptEx is a free (and by now, open-source) program that allows * the user to create encrypted volumes to store files. * * FireCryptEx was and continues to be developed by 0xFireball, and is * the successor to another free program, FireCrypt. * * About the Author: * Pseudonym: 0xFireball, ExaPhaser * Websites: * http://acetylene.x10.bz * http://omnibean.x10.bz * http://exaphaser.x10.bz * * Contact: * 0xFireball on GitHub * 0xFireball on GitLab * exaphaser on GitLab * * omnibean@outlook.com * * * You are hereby allowed to make changes to the below source code and * improve this program. In doing so, you are bound by the terms and * conditions of the AGPLv3 License. * */ #region Using directives using System; using System.Reflection; using System.Runtime.InteropServices; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle ("FireCryptEx")] [assembly: AssemblyDescription ("FireCryptEx - Encryption software to create secure encrypted volumes.")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("0xFireball, AluminumDev")] [assembly: AssemblyProduct ("FireCryptEx")] [assembly: AssemblyCopyright ("Copyright 2015-2016, 0xFireball. All Rights Reserved.")] [assembly: AssemblyTrademark ("FireCryptEx")] [assembly: AssemblyCulture ("")] // This sets the default COM visibility of types in the assembly to invisible. // If you need to expose a type to COM, use [ComVisible(true)] on that type. [assembly: ComVisible (false)] // The assembly version has following format : // // Major.Minor.Build.Revision // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: [assembly: AssemblyVersion ("3.0.*")] [assembly: AssemblyFileVersion ("3.0.*")] [assembly: Guid ("a4067db9-0cc6-4a55-b87a-04b56a603f49")]
/* * THIS PROGRAM AND ITS SOURCE CODE ARE PROVIDED TO YOU FREE OF CHARGE. * YOU ARE PROHIBITED FROM REMOVING THIS NOTICE FROM THIS SOURCE DOCUMENT * OR OTHERWISE MODIFYING IT. * * FireCryptEx is a free (and by now, open-source) program that allows * the user to create encrypted volumes to store files. * * FireCryptEx was and continues to be developed by 0xFireball, and is * the successor to another free program, FireCrypt. * * About the Author: * Pseudonym: 0xFireball, ExaPhaser * Websites: * http://acetylene.x10.bz * http://omnibean.x10.bz * http://exaphaser.x10.bz * * Contact: * 0xFireball on GitHub * 0xFireball on GitLab * exaphaser on GitLab * * omnibean@outlook.com * * * You are hereby allowed to make changes to the below source code and * improve this program. In doing so, you are bound by the terms and * conditions of the AGPLv3 License. * */ #region Using directives using System; using System.Reflection; using System.Runtime.InteropServices; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle ("FireCryptEx")] [assembly: AssemblyDescription ("FireCryptEx - Encryption software to create secure encrypted volumes.")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("0xFireball, AluminumDev")] [assembly: AssemblyProduct ("FireCryptEx")] [assembly: AssemblyCopyright ("Copyright 2015-2016, 0xFireball. All Rights Reserved.")] [assembly: AssemblyTrademark ("FireCryptEx")] [assembly: AssemblyCulture ("")] // This sets the default COM visibility of types in the assembly to invisible. // If you need to expose a type to COM, use [ComVisible(true)] on that type. [assembly: ComVisible (false)] // The assembly version has following format : // // Major.Minor.Build.Revision // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: [assembly: AssemblyVersion ("2.2.3.*")] [assembly: AssemblyFileVersion ("2.2.3.*")] [assembly: Guid ("a4067db9-0cc6-4a55-b87a-04b56a603f49")]
agpl-3.0
C#
066b953896626fb5a29da2a37ac17413c9d70326
remove DeviceTimestamp from SensorValues model
MCeddy/IoT-core
IoT-Core/Models/SensorValues.cs
IoT-Core/Models/SensorValues.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace IoT_Core.Models { public class SensorValues { public int Id { get; set; } public DateTime Date { get; set; } //public int? DeviceTimestamp { get; set; } [Required] public float Temperature { get; set; } [Required] public float Humidity { get; set; } [Required] public int SoilMoisture { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace IoT_Core.Models { public class SensorValues { public int Id { get; set; } public DateTime Date { get; set; } public int? DeviceTimestamp { get; set; } [Required] public float Temperature { get; set; } [Required] public float Humidity { get; set; } [Required] public int SoilMoisture { get; set; } } }
mit
C#
17c02ae43dade5cd7a881703111b2f90f2279d72
Bump commit
xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents
XPlat/ExposureNotification/build.cake
XPlat/ExposureNotification/build.cake
var TARGET = Argument("t", Argument("target", "ci")); var SRC_COMMIT = "150b9a89553ddef9ef146d5cf51efff31af35404"; var SRC_URL = $"https://github.com/xamarin/xamarin.exposurenotification/archive/{SRC_COMMIT}.zip"; var OUTPUT_PATH = (DirectoryPath)"./output/"; var NUGET_VERSION = "0.1.0-beta1"; Task("externals") .Does(() => { DownloadFile(SRC_URL, "./src.zip"); Unzip("./src.zip", "./"); MoveDirectory($"./xamarin.exposurenotification-{SRC_COMMIT}", "./src"); }); Task("libs") .IsDependentOn("externals") .Does(() => { EnsureDirectoryExists(OUTPUT_PATH); MSBuild($"./src/Xamarin.ExposureNotification/Xamarin.ExposureNotification.csproj", c => c .SetConfiguration("Release") .WithRestore() .WithTarget("Build") .WithTarget("Pack") .WithProperty("PackageVersion", NUGET_VERSION) .WithProperty("PackageOutputPath", MakeAbsolute(OUTPUT_PATH).FullPath)); }); Task("nuget") .IsDependentOn("libs"); Task("samples") .IsDependentOn("nuget"); Task("clean") .Does(() => { CleanDirectories("./externals/"); }); Task("ci") .IsDependentOn("nuget"); RunTarget(TARGET);
var TARGET = Argument("t", Argument("target", "ci")); var SRC_COMMIT = "b3ce14af8949829463f07c667125fca024661f36"; var SRC_URL = $"https://github.com/xamarin/xamarin.exposurenotification/archive/{SRC_COMMIT}.zip"; var OUTPUT_PATH = (DirectoryPath)"./output/"; var NUGET_VERSION = "0.1.0-beta1"; Task("externals") .Does(() => { DownloadFile(SRC_URL, "./src.zip"); Unzip("./src.zip", "./"); MoveDirectory($"./xamarin.exposurenotification-{SRC_COMMIT}", "./src"); }); Task("libs") .IsDependentOn("externals") .Does(() => { EnsureDirectoryExists(OUTPUT_PATH); MSBuild($"./src/Xamarin.ExposureNotification/Xamarin.ExposureNotification.csproj", c => c .SetConfiguration("Release") .WithRestore() .WithTarget("Build") .WithTarget("Pack") .WithProperty("PackageVersion", NUGET_VERSION) .WithProperty("PackageOutputPath", MakeAbsolute(OUTPUT_PATH).FullPath)); }); Task("nuget") .IsDependentOn("libs"); Task("samples") .IsDependentOn("nuget"); Task("clean") .Does(() => { CleanDirectories("./externals/"); }); Task("ci") .IsDependentOn("nuget"); RunTarget(TARGET);
mit
C#
bebe658fab7a1c32b640c65416087c0fa9daae40
set parent window in AlertDialogBackend
TheBrainTech/xwt,antmicro/xwt,iainx/xwt,residuum/xwt,directhex/xwt,steffenWi/xwt,hamekoz/xwt,akrisiun/xwt,mminns/xwt,hwthomas/xwt,cra0zy/xwt,mminns/xwt,lytico/xwt,mono/xwt
Xwt.Mac/Xwt.Mac/AlertDialogBackend.cs
Xwt.Mac/Xwt.Mac/AlertDialogBackend.cs
// // AlertDialogBackend.cs // // Author: // Thomas Ziegler <ziegler.thomas@web.de> // // Copyright (c) 2012 Thomas Ziegler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using MonoMac.AppKit; using MonoMac.Foundation; using Xwt.Backends; using Xwt.Drawing; namespace Xwt.Mac { public class AlertDialogBackend : NSAlert, IAlertDialogBackend { ApplicationContext Context; public AlertDialogBackend () { } public AlertDialogBackend (System.IntPtr intptr) { } public void Initialize (ApplicationContext actx) { Context = actx; } #region IAlertDialogBackend implementation public Command Run (WindowFrame transientFor, MessageDescription message) { this.MessageText = (message.Text != null) ? message.Text : String.Empty; this.InformativeText = (message.SecondaryText != null) ? message.SecondaryText : String.Empty; if (message.Icon != null) Icon = message.Icon.ToImageDescription (Context).ToNSImage (); var sortedButtons = new Command [message.Buttons.Count]; var j = 0; if (message.DefaultButton >= 0) { sortedButtons [0] = message.Buttons [message.DefaultButton]; this.AddButton (message.Buttons [message.DefaultButton].Label); j = 1; } for (var i = 0; i < message.Buttons.Count; i++) { if (i == message.DefaultButton) continue; sortedButtons [j++] = message.Buttons [i]; this.AddButton (message.Buttons [i].Label); } var win = (WindowBackend)Toolkit.GetBackend (transientFor); if (win != null) return sortedButtons [this.RunSheetModal (win) - 1000]; return sortedButtons [this.RunModal () - 1000]; } public bool ApplyToAll { get; set; } #endregion } }
// // AlertDialogBackend.cs // // Author: // Thomas Ziegler <ziegler.thomas@web.de> // // Copyright (c) 2012 Thomas Ziegler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using MonoMac.AppKit; using MonoMac.Foundation; using Xwt.Backends; using Xwt.Drawing; namespace Xwt.Mac { public class AlertDialogBackend : NSAlert, IAlertDialogBackend { ApplicationContext Context; public AlertDialogBackend () { } public AlertDialogBackend (System.IntPtr intptr) { } public void Initialize (ApplicationContext actx) { Context = actx; } #region IAlertDialogBackend implementation public Command Run (WindowFrame transientFor, MessageDescription message) { this.MessageText = (message.Text != null) ? message.Text : String.Empty; this.InformativeText = (message.SecondaryText != null) ? message.SecondaryText : String.Empty; if (message.Icon != null) Icon = message.Icon.ToImageDescription (Context).ToNSImage (); var sortedButtons = new Command [message.Buttons.Count]; var j = 0; if (message.DefaultButton >= 0) { sortedButtons [0] = message.Buttons [message.DefaultButton]; this.AddButton (message.Buttons [message.DefaultButton].Label); j = 1; } for (var i = 0; i < message.Buttons.Count; i++) { if (i == message.DefaultButton) continue; sortedButtons [j++] = message.Buttons [i]; this.AddButton (message.Buttons [i].Label); } return sortedButtons [this.RunModal () - 1000]; } public bool ApplyToAll { get; set; } #endregion } }
mit
C#
b90aae9847d992523bb6970c7e122b08cdb4c0fc
Add property InvertRepeatAsFloat
mcneel/RhinoCycles
CyclesTextureImage.cs
CyclesTextureImage.cs
/** Copyright 2014-2016 Robert McNeel and Associates 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 Rhino.Render; namespace RhinoCyclesCore { public class CyclesTextureImage { public bool HasTextureImage => TexByte != null || TexFloat != null; public bool HasFloatImage => TexFloat != null; public bool HasByteImage => TexByte != null; public byte[] TexByte { get; set; } public float[] TexFloat { get; set; } public int TexWidth; public int TexHeight; public string Name; public bool UseAlpha; public float UseAlphaAsFloat => UseAlpha ? 1.0f : 0.0f; public float Amount { get; set; } public bool IsLinear { get; set; } /// <summary> /// transformations on texture space. Vectors used are: /// Transform.x = translate /// Transform.y = scale /// Transform.z = rotate /// </summary> public ccl.Transform Transform { get; set; } public float BumpDistance { get { if (Transform == null) return 0.0f; var td = Transform.x.x; if (td > 0.2f) return 0.05f; if (td < 0.06) return 2.0f; return td > 0.14 ? 0.1f : 0.75f; } } public TextureProjectionMode ProjectionMode { get; set; } public TextureEnvironmentMappingMode EnvProjectionMode { get; set; } public bool Repeat { get; set; } public float InvertRepeatAsFloat => Repeat ? 0.0f : 1.0f; public float RepeatAsFloat => Repeat ? 1.0f : 0.0f; public CyclesTextureImage() { Clear(); } public void Clear() { Transform = ccl.Transform.Identity(); TexByte = null; TexFloat = null; TexWidth = 0; TexHeight = 0; Name = ""; UseAlpha = false; Amount = 0.0f; } } }
/** Copyright 2014-2016 Robert McNeel and Associates 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 Rhino.Render; namespace RhinoCyclesCore { public class CyclesTextureImage { public bool HasTextureImage => TexByte != null || TexFloat != null; public bool HasFloatImage => TexFloat != null; public bool HasByteImage => TexByte != null; public byte[] TexByte { get; set; } public float[] TexFloat { get; set; } public int TexWidth; public int TexHeight; public string Name; public bool UseAlpha; public float UseAlphaAsFloat => UseAlpha ? 1.0f : 0.0f; public float Amount { get; set; } public bool IsLinear { get; set; } /// <summary> /// transformations on texture space. Vectors used are: /// Transform.x = translate /// Transform.y = scale /// Transform.z = rotate /// </summary> public ccl.Transform Transform { get; set; } public float BumpDistance { get { if (Transform == null) return 0.0f; var td = Transform.x.x; if (td > 0.2f) return 0.05f; if (td < 0.06) return 2.0f; return td > 0.14 ? 0.1f : 0.75f; } } public TextureProjectionMode ProjectionMode { get; set; } public TextureEnvironmentMappingMode EnvProjectionMode { get; set; } public bool Repeat { get; set; } public float RepeatAsFloat => Repeat ? 1.0f : 0.0f; public CyclesTextureImage() { Clear(); } public void Clear() { Transform = ccl.Transform.Identity(); TexByte = null; TexFloat = null; TexWidth = 0; TexHeight = 0; Name = ""; UseAlpha = false; Amount = 0.0f; } } }
apache-2.0
C#
9aa73df4a646347ec6ffd147280c10ab6500f1f3
Add comments
tomgrv/PA.Utilities
PA.Utilities.InnoSetupTask/PreprocessFileList.cs
PA.Utilities.InnoSetupTask/PreprocessFileList.cs
using System; using System.ComponentModel; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using PA.Utilities.InnoSetupTask; namespace PA.Utilities.InnoSetupTask { public class PreprocessFileList : Task { TaskLogger logger; public PreprocessFileList() { logger = new TaskLogger(this); GitVersion.Logger.SetLoggers(this.LogInfo, this.LogWarning, s => this.LogError(s)); } [Required] public string IntermediateOutputPath { get; set; } public override bool Execute() { try { InnerExecute(); return true; } catch (WarningException errorException) { logger.LogWarning(errorException.Message); return true; } catch (Exception exception) { logger.LogError("Error occurred: " + exception +" at line " + exception.Source ); return false; } finally { GitVersion.Logger.Reset(); } } void InnerExecute() { logger.LogInfo("Project is " + ProjectFile); foreach (var script in this.Scripts.Select(e => e.ItemSpec)) { } }
using System; using System.ComponentModel; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using PA.Utilities.InnoSetupTask; namespace PA.Utilities.InnoSetupTask { public class PreprocessFileList : Task { TaskLogger logger; public PreprocessFileList() { logger = new TaskLogger(this); GitVersion.Logger.SetLoggers(this.LogInfo, this.LogWarning, s => this.LogError(s)); } [Required] public string IntermediateOutputPath { get; set; } public override bool Execute() { try { InnerExecute(); return true; } catch (WarningException errorException) { logger.LogWarning(errorException.Message); return true; } catch (Exception exception) { logger.LogError("Error occurred: " + exception); return false; } finally { GitVersion.Logger.Reset(); } } void InnerExecute() { logger.LogInfo("Project is " + ProjectFile); foreach (var script in this.Scripts.Select(e => e.ItemSpec)) { } }
mit
C#
3c74cf4131c47e11c14f98c3b34300caadba5829
fix comment
skrusty/AsterNET,AsterNET/AsterNET
Asterisk.2013/Asterisk.NET/Manager/Event/MusicOnHoldEvent.cs
Asterisk.2013/Asterisk.NET/Manager/Event/MusicOnHoldEvent.cs
namespace AsterNET.Manager.Event { /// <summary> /// The MusicOnHoldEvent event triggers when the music starts or ends playing the hold music.<br /> /// See <see target="_blank" href="LINK">LINK</see> /// </summary> public class MusicOnHoldEvent : ManagerEvent { /// <summary> /// Creates a new empty <see cref="MusicOnHoldEvent"/> using the given <see cref="ManagerConnection"/>. /// </summary> public MusicOnHoldEvent(ManagerConnection source) : base(source) { } /// <summary> /// States /// </summary> public enum MusicOnHoldStates { /// <summary> /// Unknown /// </summary> Unknown, /// <summary> /// Music on hold is started. /// </summary> Start, /// <summary> /// Music on hold is stopped. /// </summary> Stop } /// <summary> /// Get or set state /// </summary> public MusicOnHoldStates State { get; set; } } }
namespace AsterNET.Manager.Event { /// <summary> /// The MusicOnHoldEvent event triggers when the music starts or ends playing the hold music.<br /> /// See <see target="_blank" href="LINK">LINK</see> /// </summary> public class MusicOnHoldEvent : ManagerEvent { /// <summary> /// Creates a new empty <see cref="MusicOnHoldEvent"/> using the given <see cref="ManagerConnection"/>. /// </summary> public MusicOnHoldEvent(ManagerConnection source) : base(source) { } /// <summary> /// States /// </summary> public enum MusicOnHoldStates { /// <summary> /// Unknown /// </summary> Unknown, /// <summary> /// Music on hold is started. /// </summary> Start, /// <summary> /// Music on hold is stopped. /// </summary> Stop } /// <summary> /// Get or set state /// </summary> public MusicOnHoldStates State { get; set; } } }
mit
C#
e81f550150438741a9da4ee7e26a7899b9d9b673
Fix hit explosions not being cleaned up correctly when rewinding
peppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu
osu.Game.Rulesets.Mania/UI/PoolableHitExplosion.cs
osu.Game.Rulesets.Mania/UI/PoolableHitExplosion.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Game.Rulesets.Judgements; using osu.Game.Skinning; namespace osu.Game.Rulesets.Mania.UI { public class PoolableHitExplosion : PoolableDrawable { public const double DURATION = 200; public JudgementResult Result { get; private set; } private SkinnableDrawable skinnableExplosion; public PoolableHitExplosion() { RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { InternalChild = skinnableExplosion = new SkinnableDrawable(new ManiaSkinComponent(ManiaSkinComponents.HitExplosion), _ => new DefaultHitExplosion()) { RelativeSizeAxes = Axes.Both }; } public void Apply(JudgementResult result) { Result = result; } protected override void PrepareForUse() { base.PrepareForUse(); LifetimeStart = Time.Current; (skinnableExplosion?.Drawable as IHitExplosion)?.Animate(Result); this.Delay(DURATION).Then().Expire(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Game.Rulesets.Judgements; using osu.Game.Skinning; namespace osu.Game.Rulesets.Mania.UI { public class PoolableHitExplosion : PoolableDrawable { public const double DURATION = 200; public JudgementResult Result { get; private set; } private SkinnableDrawable skinnableExplosion; public PoolableHitExplosion() { RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { InternalChild = skinnableExplosion = new SkinnableDrawable(new ManiaSkinComponent(ManiaSkinComponents.HitExplosion), _ => new DefaultHitExplosion()) { RelativeSizeAxes = Axes.Both }; } public void Apply(JudgementResult result) { Result = result; } protected override void PrepareForUse() { base.PrepareForUse(); (skinnableExplosion?.Drawable as IHitExplosion)?.Animate(Result); this.Delay(DURATION).Then().Expire(); } } }
mit
C#
a25ee632dd47aa6e3a6aac8e2bc41fff53ce33d5
Write full type namespace
peppy/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,default0/osu-framework,default0/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework
osu.Framework/Allocation/RecursiveLoadException.cs
osu.Framework/Allocation/RecursiveLoadException.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Linq; using System.Reflection; using System.Text; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics.Containers; namespace osu.Framework.Allocation { /// <summary> /// The exception that is re-thrown by <see cref="DependencyContainer"/> when a loader invocation fails. /// This exception type builds a readablestacktrace message since loader invocations tend to be long recursive reflection calls. /// </summary> public class RecursiveLoadException : Exception { /// <summary> /// Types that are ignored for the custom stack traces. The initializers for these typically invoke /// initializers in user code where the problem actually lies. /// </summary> private static readonly Type[] blacklist = { typeof(Container), typeof(Container<>), typeof(CompositeDrawable) }; private readonly StringBuilder traceBuilder; public RecursiveLoadException(Exception inner, MethodInfo loaderMethod) : base(string.Empty, (inner as RecursiveLoadException)?.InnerException ?? inner) { traceBuilder = inner is RecursiveLoadException recursiveException ? recursiveException.traceBuilder : new StringBuilder(); if (!blacklist.Contains(loaderMethod.DeclaringType)) traceBuilder.AppendLine($" at {loaderMethod.DeclaringType}.{loaderMethod.Name} ()"); } public override string ToString() { var builder = new StringBuilder(); builder.Append(InnerException?.ToString() ?? string.Empty); builder.AppendLine(traceBuilder.ToString()); return builder.ToString(); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Linq; using System.Reflection; using System.Text; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics.Containers; namespace osu.Framework.Allocation { /// <summary> /// The exception that is re-thrown by <see cref="DependencyContainer"/> when a loader invocation fails. /// This exception type builds a readablestacktrace message since loader invocations tend to be long recursive reflection calls. /// </summary> public class RecursiveLoadException : Exception { /// <summary> /// Types that are ignored for the custom stack traces. The initializers for these typically invoke /// initializers in user code where the problem actually lies. /// </summary> private static readonly Type[] blacklist = { typeof(Container), typeof(Container<>), typeof(CompositeDrawable) }; private readonly StringBuilder traceBuilder; public RecursiveLoadException(Exception inner, MethodInfo loaderMethod) : base(string.Empty, (inner as RecursiveLoadException)?.InnerException ?? inner) { traceBuilder = inner is RecursiveLoadException recursiveException ? recursiveException.traceBuilder : new StringBuilder(); if (!blacklist.Contains(loaderMethod.DeclaringType)) traceBuilder.AppendLine($" at {loaderMethod.DeclaringType?.ReadableName() ?? string.Empty}.{loaderMethod.Name} ()"); } public override string ToString() { var builder = new StringBuilder(); builder.Append(InnerException?.ToString() ?? string.Empty); builder.AppendLine(traceBuilder.ToString()); return builder.ToString(); } } }
mit
C#
3d99b89633b622b93a59423f72660d2af57eec01
Add back actually needed change
peppy/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu
osu.Game/Tests/Visual/LegacySkinPlayerTestScene.cs
osu.Game/Tests/Visual/LegacySkinPlayerTestScene.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.IO.Stores; using osu.Game.Rulesets; using osu.Game.Skinning; namespace osu.Game.Tests.Visual { [TestFixture] public abstract class LegacySkinPlayerTestScene : PlayerTestScene { protected LegacySkin LegacySkin { get; private set; } private ISkinSource legacySkinSource; protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource); [BackgroundDependencyLoader] private void load(OsuGameBase game, SkinManager skins) { LegacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins); legacySkinSource = new SkinProvidingContainer(LegacySkin); } public class SkinProvidingPlayer : TestPlayer { [Cached(typeof(ISkinSource))] private readonly ISkinSource skinSource; public SkinProvidingPlayer(ISkinSource skinSource) { this.skinSource = skinSource; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.IO.Stores; using osu.Game.Rulesets; using osu.Game.Skinning; namespace osu.Game.Tests.Visual { [TestFixture] public abstract class LegacySkinPlayerTestScene : PlayerTestScene { private ISkinSource legacySkinSource; protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource); [BackgroundDependencyLoader] private void load(OsuGameBase game, SkinManager skins) { var legacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins); legacySkinSource = new SkinProvidingContainer(legacySkin); } public class SkinProvidingPlayer : TestPlayer { [Cached(typeof(ISkinSource))] private readonly ISkinSource skinSource; public SkinProvidingPlayer(ISkinSource skinSource) { this.skinSource = skinSource; } } } }
mit
C#
7d15acd87af20549052c166e9431c1243a21cfaa
remove whitespace
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerFinance/Infrastructure/OuterApiRequests/GetAccountProjectionSummaryRequest.cs
src/SFA.DAS.EmployerFinance/Infrastructure/OuterApiRequests/GetAccountProjectionSummaryRequest.cs
using SFA.DAS.EmployerFinance.Interfaces.OuterApi; namespace SFA.DAS.EmployerFinance.Infrastructure.OuterApiRequests { public class GetAccountProjectionSummaryRequest : IGetApiRequest { private readonly long _accountId; public string GetUrl => $"Projections/{_accountId}"; public GetAccountProjectionSummaryRequest(long accountId) { _accountId = accountId; } } }
using SFA.DAS.EmployerFinance.Interfaces.OuterApi; namespace SFA.DAS.EmployerFinance.Infrastructure.OuterApiRequests { public class GetAccountProjectionSummaryRequest : IGetApiRequest { private readonly long _accountId; public string GetUrl => $"Projections/{_accountId}"; public GetAccountProjectionSummaryRequest(long accountId) { _accountId = accountId; } } }
mit
C#
e6be58aa56d0c7e7409d8c048955d00ba9b0ac3e
Refactor to the http in GithubClient
skolima/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper
NuKeeper/Github/GithubClient.cs
NuKeeper/Github/GithubClient.cs
using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace NuKeeper.Github { public class GithubClient : IGithub { private readonly Settings _settings; private readonly GithubRequestBuilder _requestBuilder; private static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings { ContractResolver = new LowercaseContractResolver() }; public GithubClient(Settings settings) { _settings = settings; _requestBuilder = new GithubRequestBuilder(settings.GithubToken); } private async Task<HttpResponseMessage> PostAsync<T>(Uri uri, T content) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } var requestUri = _requestBuilder.AddSecretToken(uri); var request = _requestBuilder.ConstructRequestMessage(requestUri, HttpMethod.Post); request.Content = ToJsonContent(content); var client = new HttpClient(); return await client.SendAsync(request); } private HttpContent ToJsonContent<T>(T content) { var requestBody = JsonConvert.SerializeObject(content, JsonSettings); const string gitHubApiJsonType = "application/vnd.github.v3.text+json"; return new StringContent(requestBody, Encoding.UTF8, gitHubApiJsonType); } public async Task<OpenPullRequestResult> OpenPullRequest(OpenPullRequestRequest request) { var uri = new Uri(_settings.GithubBaseUri, $"/repos/{request.RepositoryOwner}/{request.RepositoryName}/pulls"); var response = await PostAsync(uri, request.Data); if (!response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); throw new Exception($"Post failed: {response.StatusCode} {content}"); } return new OpenPullRequestResult(response); } } }
using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using NuGet.Protocol; namespace NuKeeper.Github { public class GithubClient : IGithub { private readonly Settings _settings; private readonly GithubRequestBuilder _requestBuilder; private static JsonSerializerSettings jsonSettings = new JsonSerializerSettings { ContractResolver = new LowercaseContractResolver() }; public GithubClient(Settings settings) { _settings = settings; _requestBuilder = new GithubRequestBuilder(settings.GithubToken); } private async Task<HttpResponseMessage> PostAsync<T>(Uri uri, T content) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } var requestUri = _requestBuilder.AddSecretToken(uri); var requestBody = JsonConvert.SerializeObject(content, jsonSettings); var request = _requestBuilder.ConstructRequestMessage(requestUri, HttpMethod.Post); request.Content = new StringContent(requestBody, Encoding.UTF8, "application/vnd.github.v3.text+json"); var client = new HttpClient(); return await client.SendAsync(request); } public async Task<OpenPullRequestResult> OpenPullRequest(OpenPullRequestRequest request) { var uri = new Uri(_settings.GithubBaseUri, $"/repos/{request.RepositoryOwner}/{request.RepositoryName}/pulls"); var response = await PostAsync(uri, request.Data); if (!response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); throw new Exception($"Post failed: {response.StatusCode} {content}"); } return new OpenPullRequestResult(response); } } }
apache-2.0
C#
edcc74be3d91f05f8a92cd88d3b8b33c341116d9
Remove test parallelization (#712)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/IISIntegration.FunctionalTests/Properties/AssemblyInfo.cs
test/IISIntegration.FunctionalTests/Properties/AssemblyInfo.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // All functional tests in this project require a version of IIS express with an updated schema using Xunit; [assembly: Microsoft.AspNetCore.Server.IISIntegration.FunctionalTests.IISExpressSupportsInProcessHosting] [assembly: CollectionBehavior(DisableTestParallelization = true)]
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // All functional tests in this project require a version of IIS express with an updated schema [assembly: Microsoft.AspNetCore.Server.IISIntegration.FunctionalTests.IISExpressSupportsInProcessHosting]
apache-2.0
C#
316d76d8602a62454c4eb7ad5716e8b49883efcb
Use new new syntax for initialized fields
rubberduck203/GitNStats,rubberduck203/GitNStats
src/gitnstats.core/CommitVisitor.cs
src/gitnstats.core/CommitVisitor.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using LibGit2Sharp; using static GitNStats.Core.Tooling; namespace GitNStats.Core { /// <summary> /// Walks the commit graph back to the beginning of time. /// Guaranteed to only visit a commit once. /// </summary> public class CommitVisitor : Visitor { /// <summary> /// Walk the graph from this commit back. /// </summary> /// <param name="commit">The commit to start at.</param> public override void Walk(Commit commit) { Walk(commit, new HashSet<string>()); //WithStopWatch(() => Walk(commit, new HashSet<string>()), "Total Time Walking Graph: {0}"); } private Object padlock = new(); private void Walk(Commit commit, ISet<string> visitedCommits) { // It's not safe to concurrently write to the Set. // If two threads hit this at the same time we could visit the same commit twice. lock(padlock) { // If we weren't successful in adding the commit, we've already been here. if(!visitedCommits.Add(commit.Sha)) return; } OnVisited(this, commit); Parallel.ForEach(commit.Parents, parent => { Walk(parent, visitedCommits); }); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using LibGit2Sharp; using static GitNStats.Core.Tooling; namespace GitNStats.Core { /// <summary> /// Walks the commit graph back to the beginning of time. /// Guaranteed to only visit a commit once. /// </summary> public class CommitVisitor : Visitor { /// <summary> /// Walk the graph from this commit back. /// </summary> /// <param name="commit">The commit to start at.</param> public override void Walk(Commit commit) { Walk(commit, new HashSet<string>()); //WithStopWatch(() => Walk(commit, new HashSet<string>()), "Total Time Walking Graph: {0}"); } private Object padlock = new Object(); private void Walk(Commit commit, ISet<string> visitedCommits) { // It's not safe to concurrently write to the Set. // If two threads hit this at the same time we could visit the same commit twice. lock(padlock) { // If we weren't successful in adding the commit, we've already been here. if(!visitedCommits.Add(commit.Sha)) return; } OnVisited(this, commit); Parallel.ForEach(commit.Parents, parent => { Walk(parent, visitedCommits); }); } } }
mit
C#
c061edb52f361ac8320ce339c41ca5abac7adf92
Use pattern matching
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
src/LondonTravel.Site/Identity/UserClaimsPrincipalFactory.cs
src/LondonTravel.Site/Identity/UserClaimsPrincipalFactory.cs
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Identity { using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; /// <summary> /// A custom implementation of <see cref="UserClaimsPrincipalFactory{LondonTravelUser, LondonTravelRole}"/> /// that adds additional claims to the principal when it is created by the application. /// </summary> public class UserClaimsPrincipalFactory : UserClaimsPrincipalFactory<LondonTravelUser, LondonTravelRole> { /// <summary> /// Initializes a new instance of the <see cref="UserClaimsPrincipalFactory"/> class. /// </summary> /// <param name="userManager">The <see cref="UserManager{LondonTravelUser}"/> to use.</param> /// <param name="roleManager">The <see cref="RoleManager{LondonTravelRole}"/> to use.</param> /// <param name="optionsAccessor">The <see cref="IOptions{IdentityOptions}"/> to use.</param> public UserClaimsPrincipalFactory(UserManager<LondonTravelUser> userManager, RoleManager<LondonTravelRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor) { } /// <inheritdoc /> public async override Task<ClaimsPrincipal> CreateAsync(LondonTravelUser user) { var principal = await base.CreateAsync(user); if (principal.Identity is ClaimsIdentity identity) { foreach (LondonTravelRole role in user?.RoleClaims) { identity.AddClaim(role.ToClaim()); } } return principal; } } }
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Identity { using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; /// <summary> /// A custom implementation of <see cref="UserClaimsPrincipalFactory{LondonTravelUser, LondonTravelRole}"/> /// that adds additional claims to the principal when it is created by the application. /// </summary> public class UserClaimsPrincipalFactory : UserClaimsPrincipalFactory<LondonTravelUser, LondonTravelRole> { /// <summary> /// Initializes a new instance of the <see cref="UserClaimsPrincipalFactory"/> class. /// </summary> /// <param name="userManager">The <see cref="UserManager{LondonTravelUser}"/> to use.</param> /// <param name="roleManager">The <see cref="RoleManager{LondonTravelRole}"/> to use.</param> /// <param name="optionsAccessor">The <see cref="IOptions{IdentityOptions}"/> to use.</param> public UserClaimsPrincipalFactory(UserManager<LondonTravelUser> userManager, RoleManager<LondonTravelRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor) { } /// <inheritdoc /> public async override Task<ClaimsPrincipal> CreateAsync(LondonTravelUser user) { var principal = await base.CreateAsync(user); var identity = principal.Identity as ClaimsIdentity; if (identity != null) { foreach (LondonTravelRole role in user?.RoleClaims) { identity.AddClaim(role.ToClaim()); } } return principal; } } }
apache-2.0
C#
efc2ee3a56b04c314fce9ba99817704b446bbedd
make sure you only build .net core on non Windows
MienDev/IdentityServer4,siyo-wang/IdentityServer4,jbijlsma/IdentityServer4,IdentityServer/IdentityServer4,chrisowhite/IdentityServer4,MienDev/IdentityServer4,chrisowhite/IdentityServer4,chrisowhite/IdentityServer4,siyo-wang/IdentityServer4,jbijlsma/IdentityServer4,jbijlsma/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,siyo-wang/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,IdentityServer/IdentityServer4
build.cake
build.cake
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor; var packPath = Directory("./src/IdentityServer4"); var sourcePath = Directory("./src"); var testsPath = Directory("test"); var buildArtifacts = Directory("./artifacts/packages"); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreBuildSettings { Configuration = configuration }; if (!IsRunningOnWindows()) { Information("Not running on Windows - skipping build for full .NET Framework"); settings.Framework = "netcoreapp1.0"; } DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); Task("RunTests") .IsDependentOn("Restore") .IsDependentOn("Clean") .Does(() => { var projects = GetFiles("./test/**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreTestSettings { Configuration = configuration }; if (!IsRunningOnWindows()) { Information("Not running on Windows - skipping tests for full .NET Framework"); settings.Framework = "netcoreapp1.0"; } DotNetCoreTest(project.GetDirectory().FullPath, settings); } }); Task("Pack") .IsDependentOn("Restore") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = buildArtifacts, }; // add build suffix for CI builds if(!isLocalBuild) { settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0'); } DotNetCorePack(packPath, settings); }); Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts }); }); Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new [] { "https://api.nuget.org/v3/index.json" } }; DotNetCoreRestore(sourcePath, settings); DotNetCoreRestore(testsPath, settings); }); Task("Default") .IsDependentOn("Build") .IsDependentOn("RunTests") .IsDependentOn("Pack"); RunTarget(target);
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor; var packPath = Directory("./src/IdentityServer4"); var sourcePath = Directory("./src"); var testsPath = Directory("test"); var buildArtifacts = Directory("./artifacts/packages"); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreBuildSettings { Configuration = configuration // Runtime = IsRunningOnWindows() ? null : "unix-x64" }; DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); Task("RunTests") .IsDependentOn("Restore") .IsDependentOn("Clean") .Does(() => { var projects = GetFiles("./test/**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreTestSettings { Configuration = configuration }; if (!IsRunningOnWindows()) { Information("Not running on Windows - skipping tests for full .NET Framework"); settings.Framework = "netcoreapp1.0"; } DotNetCoreTest(project.GetDirectory().FullPath, settings); } }); Task("Pack") .IsDependentOn("Restore") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = buildArtifacts, }; // add build suffix for CI builds if(!isLocalBuild) { settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0'); } DotNetCorePack(packPath, settings); }); Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts }); }); Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new [] { "https://api.nuget.org/v3/index.json" } }; DotNetCoreRestore(sourcePath, settings); DotNetCoreRestore(testsPath, settings); }); Task("Default") .IsDependentOn("Build") .IsDependentOn("RunTests") .IsDependentOn("Pack"); RunTarget(target);
apache-2.0
C#
e4a65a459e1ce1c811c6704c83da7a77daa15dc4
Use persistentDataPath.
Silphid/Silphid.Unity,Silphid/Silphid.Unity
Sources/Silphid.Injexit/Sources/Installers/RootInstaller.cs
Sources/Silphid.Injexit/Sources/Installers/RootInstaller.cs
using System.IO; using System.Xml; using log4net; using UnityEngine; using log4net.Config; namespace Silphid.Injexit { public abstract class RootInstaller : Installer { public string LogResourceFile = "Log4net"; private static string DataPath => Application.isEditor ? Path.Combine(Application.dataPath, "../AppData") : Application.persistentDataPath; protected override IContainer CreateContainer() => new Container(new Reflector(), ShouldInject); protected virtual bool ShouldInject(object obj) { var ns = obj.GetType().Namespace; return ns == null || !ns.StartsWith("Unity") && !ns.StartsWith("TMPro"); } public override void Start() { Debug.Log("Configuring logging..."); ConfigureLogging(); base.Start(); } protected virtual void ConfigureLogging() { var textAsset = Resources.Load<TextAsset>(LogResourceFile); var text = textAsset.text.Replace("${DataPath}", DataPath); var xmldoc = new XmlDocument(); xmldoc.LoadXml (text); var repository = LogManager.GetRepository(GetType().Assembly); XmlConfigurator.Configure(repository, xmldoc.DocumentElement); } } }
using System.IO; using System.Xml; using log4net; using UnityEngine; using log4net.Config; namespace Silphid.Injexit { public abstract class RootInstaller : Installer { public string LogResourceFile = "Log4net"; private static string DataPath => Application.isEditor ? Path.Combine(Application.dataPath, "../AppData") : Application.dataPath; protected override IContainer CreateContainer() => new Container(new Reflector(), ShouldInject); protected virtual bool ShouldInject(object obj) { var ns = obj.GetType().Namespace; return ns == null || !ns.StartsWith("Unity") && !ns.StartsWith("TMPro"); } public override void Start() { Debug.Log("Configuring logging..."); ConfigureLogging(); base.Start(); } protected virtual void ConfigureLogging() { var textAsset = Resources.Load<TextAsset>(LogResourceFile); var text = textAsset.text.Replace("${DataPath}", DataPath); var xmldoc = new XmlDocument(); xmldoc.LoadXml (text); var repository = LogManager.GetRepository(GetType().Assembly); XmlConfigurator.Configure(repository, xmldoc.DocumentElement); } } }
mit
C#
ce65f876761d43ad36c1bd3080dd7ccffd702a5b
Add indexer, IEnumerable, and Add for easier creation of HasArbitraryKey objects
Valetude/Valetude.Rollbar
Rollbar.Net/HasArbitraryKeys.cs
Rollbar.Net/HasArbitraryKeys.cs
using System.Collections; using System.Collections.Generic; namespace Rollbar { public abstract class HasArbitraryKeys : IEnumerable<KeyValuePair<string, object>> { protected HasArbitraryKeys(Dictionary<string, object> additionalKeys) { AdditionalKeys = additionalKeys ?? new Dictionary<string, object>(); } public abstract void Normalize(); public abstract Dictionary<string, object> Denormalize(); public Dictionary<string, object> AdditionalKeys { get; private set; } public void Add(string key, object value) { AdditionalKeys.Add(key, value); Normalize(); } public object this[string key] { get { return Denormalize()[key]; } set { Add(key, value); } } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return Denormalize().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static class HasArbitraryKeysExtension { public static T WithKeys<T>(this T has, Dictionary<string, object> otherKeys) where T : HasArbitraryKeys { foreach (var kvp in otherKeys) { has.AdditionalKeys.Add(kvp.Key, kvp.Value); } return has; } } }
using System.Collections.Generic; namespace Rollbar { public abstract class HasArbitraryKeys { protected HasArbitraryKeys(Dictionary<string, object> additionalKeys) { AdditionalKeys = additionalKeys ?? new Dictionary<string, object>(); } public abstract void Normalize(); public abstract Dictionary<string, object> Denormalize(); public Dictionary<string, object> AdditionalKeys { get; private set; } } public static class HasArbitraryKeysExtension { public static T WithKeys<T>(this T has, Dictionary<string, object> otherKeys) where T : HasArbitraryKeys { foreach (var kvp in otherKeys) { has.AdditionalKeys.Add(kvp.Key, kvp.Value); } return has; } } }
mit
C#
5f94faf1df7f33ce979fd91a4c511a118a44a2f1
Save ip after recording, check ip on index, version 1.0
erooijak/athousandcounts,erooijak/athousandcounts,erooijak/athousandcounts
AThousandCounts/Views/Count/_Count.cshtml
AThousandCounts/Views/Count/_Count.cshtml
<div class="span7"> <div id="button" class="tile quadro triple-vertical bg-lightPink bg-active-lightBlue" style="padding:10px; text-align: center;"> Your number is... <br /><br /> <span class="COUNT">@(Model)!!!</span><br /><br /> Click this pink square to record a three second video of you saying <strong>@Model</strong> in your language of choice.<br /><br /> If you don't like your number refresh the page to see what other counts are left.<br /><br /> Make yourself comfortable and get ready to join A Thousand Counts.<br /><br /> 3, 2, 1, COUNT! </div> </div>
<div class="span7"> <div id="button" class="tile quadro triple-vertical bg-lightPink bg-active-lightBlue" style="padding:10px; text-align: center;"> Your number is... <br /><br /> <span class="COUNT">@(Model)!!!</span><br /><br /> Click this pink square to record a three second video of you saying <strong>@Model</strong> in your language of choice.<br /><br /> If you don't like your number please hit refresh.<br /><br /> Make yourself comfortable and get ready to join A Thousand Counts.<br /><br /> 3, 2, 1, COUNT! </div> </div>
mit
C#
5cc46cae8cb6b94b6bd2cddbdc587ff395275011
Add missing attribute to mouse wave effect
WolfspiritM/Colore,CoraleStudios/Colore
Corale.Colore/Razer/Mouse/Effects/Wave.cs
Corale.Colore/Razer/Mouse/Effects/Wave.cs
// --------------------------------------------------------------------------------------- // <copyright file="Wave.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any // of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott // do not take responsibility for any harm caused, direct or indirect, to any // Razer peripherals via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore.Razer.Mouse.Effects { using Corale.Colore.Annotations; /// <summary> /// Wave effect. /// </summary> public struct Wave { /// <summary> /// The direction of the wave effect. /// </summary> [UsedImplicitly] public Direction Direction; /// <summary> /// Initializes a new instance of the <see cref="Wave" /> struct. /// </summary> /// <param name="direction">The direction of the effect.</param> public Wave(Direction direction) { Direction = direction; } } }
// --------------------------------------------------------------------------------------- // <copyright file="Wave.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any // of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott // do not take responsibility for any harm caused, direct or indirect, to any // Razer peripherals via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore.Razer.Mouse.Effects { /// <summary> /// Wave effect. /// </summary> public struct Wave { /// <summary> /// The direction of the wave effect. /// </summary> public Direction Direction; /// <summary> /// Initializes a new instance of the <see cref="Wave" /> struct. /// </summary> /// <param name="direction">The direction of the effect.</param> public Wave(Direction direction) { Direction = direction; } } }
mit
C#
2c1e5417a0e305e77af44428caf57aa31410ab82
Update AssemblyInfo.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D
Test/Properties/AssemblyInfo.cs
Test/Properties/AssemblyInfo.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.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("Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Test")] [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("59d0368f-4817-4623-a9ee-33045c50227c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
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("Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Test")] [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("59d0368f-4817-4623-a9ee-33045c50227c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
e679b44245aa569d579241d7b89ff01944848d69
Update ValidationResult
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Models/ValidationResult.cs
src/WeihanLi.Common/Models/ValidationResult.cs
// Copyright (c) Weihan Li. All rights reserved. // Licensed under the Apache license. namespace WeihanLi.Common.Models; public interface IValidationResult { /// <summary> /// Valid /// </summary> bool Valid { get; } /// <summary> /// ErrorMessages /// Key: memberName /// Value: errorMessages /// </summary> Dictionary<string, string[]> Errors { get; } } public sealed class ValidationResult: IValidationResult { private Dictionary<string, string[]> _errors = new(); /// <inheritdoc cref="IValidationResult"/> public bool Valid { get; set; } /// <inheritdoc cref="IValidationResult"/> public Dictionary<string, string[]> Errors { get => _errors; set => _errors = Guard.NotNull(value); } public static ValidationResult Failed(params string[] errors) { var result = new ValidationResult { Errors = { [string.Empty] = errors } }; return result; } public static ValidationResult Failed(Dictionary<string, string[]> errors) { var result = new ValidationResult { Errors = errors }; return result; } }
// Copyright (c) Weihan Li. All rights reserved. // Licensed under the Apache license. namespace WeihanLi.Common.Models; public class ValidationResult { /// <summary> /// Valid /// </summary> public bool Valid { get; set; } /// <summary> /// ErrorMessages /// Key: memberName /// Value: errorMessages /// </summary> public Dictionary<string, string[]>? Errors { get; set; } }
mit
C#
8080f833e7c46b543ed835c03a1f13804da9ac60
Remove method override
astorch/motoi
src/plug-ins/motoi.workbench/runtime/AbstractEditor.cs
src/plug-ins/motoi.workbench/runtime/AbstractEditor.cs
using motoi.platform.resources.model.editors; using motoi.workbench.model; using Xcite.Csharp.lang; namespace motoi.workbench.runtime { /// <summary> /// Provides an abstract implementation of <see cref="IEditor"/> that is based on <see cref="AbstractSaveableWorkbenchPart"/>. /// </summary> public abstract class AbstractEditor : AbstractSaveableWorkbenchPart, IEditor { private string iEditorTabText; /// <inheritdoc /> public virtual string EditorTabText { get { return iEditorTabText; } protected set { if (iEditorTabText == value) return; iEditorTabText = value; DispatchPropertyChanged(Name.Of(() => EditorTabText)); } } /// <inheritdoc /> public abstract void SetEditorInput(IEditorInput editorInput); } }
using motoi.platform.resources.model.editors; using motoi.platform.ui.toolbars; using motoi.workbench.model; using Xcite.Csharp.lang; namespace motoi.workbench.runtime { /// <summary> /// Provides an abstract implementation of <see cref="IEditor"/> that is based on <see cref="AbstractSaveableWorkbenchPart"/>. /// </summary> public abstract class AbstractEditor : AbstractSaveableWorkbenchPart, IEditor { private string iEditorTabText; /// <summary> /// Returns name of the current editor tab text. /// </summary> public virtual string EditorTabText { get { return iEditorTabText; } protected set { if (iEditorTabText == value) return; iEditorTabText = value; DispatchPropertyChanged(Name.Of(() => EditorTabText)); } } /// <summary> /// Tells the editor to add additional tool bar controls if desired. /// </summary> /// <param name="toolBar">Tool bar to configure</param> public abstract void ConfigureToolBar(IToolBar toolBar); /// <summary> /// Tells the editor to use the given <paramref name="editorInput"/>. /// </summary> /// <param name="editorInput">Editor input</param> public abstract void SetEditorInput(IEditorInput editorInput); } }
mit
C#
623099de9cdfa1c4005d43447121dde233e7d313
Fix Clear-Bitmap disposing cleared bitmap too early.
Prof9/PixelPet
PixelPet/Workbench.cs
PixelPet/Workbench.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; namespace PixelPet { /// <summary> /// PixelPet workbench instance. /// </summary> public class Workbench { public IList<Color> Palette { get; } public Bitmap Bitmap { get; private set; } public Graphics Graphics { get; private set; } public MemoryStream Stream { get; private set; } public Workbench() { this.Palette = new List<Color>(); ClearBitmap(8, 8); this.Stream = new MemoryStream(); } public void ClearBitmap(int width, int height) { Bitmap bmp = null; try { bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); SetBitmap(bmp); } finally { if (bmp != null) { bmp.Dispose(); } } this.Graphics.Clear(Color.Transparent); this.Graphics.Flush(); } public void SetBitmap(Bitmap bmp) { if (this.Graphics != null) { this.Graphics.Dispose(); } if (this.Bitmap != null) { this.Bitmap.Dispose(); } this.Bitmap = bmp; this.Graphics = Graphics.FromImage(this.Bitmap); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; namespace PixelPet { /// <summary> /// PixelPet workbench instance. /// </summary> public class Workbench { public IList<Color> Palette { get; } public Bitmap Bitmap { get; private set; } public Graphics Graphics { get; private set; } public MemoryStream Stream { get; private set; } public Workbench() { this.Palette = new List<Color>(); ClearBitmap(8, 8); this.Stream = new MemoryStream(); } public void ClearBitmap(int width, int height) { Bitmap bmp = null; try { bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); } finally { if (bmp != null) { bmp.Dispose(); } } SetBitmap(bmp); this.Graphics.Clear(Color.Transparent); this.Graphics.Flush(); } public void SetBitmap(Bitmap bmp) { if (this.Graphics != null) { this.Graphics.Dispose(); } if (this.Bitmap != null) { this.Bitmap.Dispose(); } this.Bitmap = bmp; this.Graphics = Graphics.FromImage(this.Bitmap); } } }
mit
C#
73d99ea7dd3ba484a57870b9ba4ecc29c49a3acd
Add ResolveByName attribute to TargetControl property
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactions/Custom/HideOnKeyPressedBehavior.cs
src/Avalonia.Xaml.Interactions/Custom/HideOnKeyPressedBehavior.cs
using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom; /// <summary> /// A behavior that allows to hide control on key down event. /// </summary> public class HideOnKeyPressedBehavior : Behavior<Control> { /// <summary> /// Identifies the <seealso cref="TargetControl"/> avalonia property. /// </summary> public static readonly StyledProperty<Control?> TargetControlProperty = AvaloniaProperty.Register<HideOnKeyPressedBehavior, Control?>(nameof(TargetControl)); /// <summary> /// Identifies the <seealso cref="Key"/> avalonia property. /// </summary> public static readonly StyledProperty<Key> KeyProperty = AvaloniaProperty.Register<HideOnKeyPressedBehavior, Key>(nameof(Key), Key.Escape); /// <summary> /// Gets or sets the target control. This is a avalonia property. /// </summary> [ResolveByName] public Control? TargetControl { get => GetValue(TargetControlProperty); set => SetValue(TargetControlProperty, value); } /// <summary> /// Gets or sets the key. This is a avalonia property. /// </summary> public Key Key { get => GetValue(KeyProperty); set => SetValue(KeyProperty, value); } /// <inheritdoc /> protected override void OnAttachedToVisualTree() { AssociatedObject?.AddHandler(InputElement.KeyDownEvent, AssociatedObject_KeyDown, RoutingStrategies.Tunnel | RoutingStrategies.Bubble); } /// <inheritdoc /> protected override void OnDetachedFromVisualTree() { AssociatedObject?.RemoveHandler(InputElement.KeyDownEvent, AssociatedObject_KeyDown); } private void AssociatedObject_KeyDown(object? sender, KeyEventArgs e) { if (e.Key == Key && TargetControl is { }) { TargetControl.IsVisible = false; } } }
using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom; /// <summary> /// A behavior that allows to hide control on key down event. /// </summary> public class HideOnKeyPressedBehavior : Behavior<Control> { /// <summary> /// Identifies the <seealso cref="TargetControl"/> avalonia property. /// </summary> public static readonly StyledProperty<Control?> TargetControlProperty = AvaloniaProperty.Register<HideOnKeyPressedBehavior, Control?>(nameof(TargetControl)); /// <summary> /// Identifies the <seealso cref="Key"/> avalonia property. /// </summary> public static readonly StyledProperty<Key> KeyProperty = AvaloniaProperty.Register<HideOnKeyPressedBehavior, Key>(nameof(Key), Key.Escape); /// <summary> /// Gets or sets the target control. This is a avalonia property. /// </summary> public Control? TargetControl { get => GetValue(TargetControlProperty); set => SetValue(TargetControlProperty, value); } /// <summary> /// Gets or sets the key. This is a avalonia property. /// </summary> public Key Key { get => GetValue(KeyProperty); set => SetValue(KeyProperty, value); } /// <inheritdoc /> protected override void OnAttachedToVisualTree() { AssociatedObject?.AddHandler(InputElement.KeyDownEvent, AssociatedObject_KeyDown, RoutingStrategies.Tunnel | RoutingStrategies.Bubble); } /// <inheritdoc /> protected override void OnDetachedFromVisualTree() { AssociatedObject?.RemoveHandler(InputElement.KeyDownEvent, AssociatedObject_KeyDown); } private void AssociatedObject_KeyDown(object? sender, KeyEventArgs e) { if (e.Key == Key && TargetControl is { }) { TargetControl.IsVisible = false; } } }
mit
C#
1a2208c6623f1cf00615c637f6d8c2b3740165ab
support zip for standalone
tsubaki/UnityZip,tsubaki/UnityZip,tsubaki/UnityZip
Assets/Plugins/Zip.cs
Assets/Plugins/Zip.cs
using UnityEngine; using System.Collections; using System; using System.Runtime.InteropServices; using Ionic.Zip; using System.Text; using System.IO; public class ZipUtil { #if UNITY_IPHONE [DllImport("__Internal")] private static extern void unzip (string zipFilePath, string location); [DllImport("__Internal")] private static extern void zip (string zipFilePath); [DllImport("__Internal")] private static extern void addZipFile (string addFile); #endif public static void Unzip (string zipFilePath, string location) { #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX Directory.CreateDirectory (location); using (ZipFile zip = ZipFile.Read (zipFilePath)) { zip.ExtractAll (location, ExtractExistingFileAction.OverwriteSilently); } #elif UNITY_ANDROID using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) { zipper.CallStatic ("unzip", zipFilePath, location); } #elif UNITY_IPHONE unzip (zipFilePath, location); #endif } public static void Zip (string zipFileName, params string[] files) { #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX string path = Path.GetDirectoryName(zipFileName); Directory.CreateDirectory (path); using (ZipFile zip = new ZipFile()) { foreach (string file in files) { zip.AddFile(file, ""); } zip.Save (zipFileName); } #elif UNITY_ANDROID using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) { { zipper.CallStatic ("zip", zipFileName, files); } } #elif UNITY_IPHONE foreach (string file in files) { addZipFile (file); } zip (zipFileName); #endif } }
using UnityEngine; using System.Collections; using System; using System.Runtime.InteropServices; using Ionic.Zip; using System.Text; using System.IO; public class ZipUtil { #if UNITY_IPHONE [DllImport("__Internal")] private static extern void unzip (string zipFilePath, string location); [DllImport("__Internal")] private static extern void zip (string zipFilePath); [DllImport("__Internal")] private static extern void addZipFile (string addFile); #endif public static void Unzip (string zipFilePath, string location) { #if UNITY_EDITOR Directory.CreateDirectory (location); using (ZipFile zip = ZipFile.Read (zipFilePath)) { zip.ExtractAll (location, ExtractExistingFileAction.OverwriteSilently); } #elif UNITY_ANDROID using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) { zipper.CallStatic ("unzip", zipFilePath, location); } #elif UNITY_IPHONE unzip (zipFilePath, location); #endif } public static void Zip (string zipFileName, params string[] files) { #if UNITY_EDITOR using (ZipFile zip = new ZipFile()) { foreach (string file in files) { zip.AddFile (file); } zip.Save (zipFileName); } #elif UNITY_ANDROID using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) { { zipper.CallStatic ("zip", zipFileName, files); } } #elif UNITY_IPHONE foreach (string file in files) { addZipFile (file); } zip (zipFileName); #endif } }
mit
C#