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 |
|---|---|---|---|---|---|---|---|---|
98603d570eda9dd80dbb2fa0d862fb4203df2fc4 | Update version | regisbsb/FluentValidation,olcayseker/FluentValidation,glorylee/FluentValidation,IRlyDontKnow/FluentValidation,robv8r/FluentValidation,GDoronin/FluentValidation,mgmoody42/FluentValidation,ruisebastiao/FluentValidation,deluxetiky/FluentValidation,cecilphillip/FluentValidation | src/CommonAssemblyInfo.cs | src/CommonAssemblyInfo.cs | using System.Reflection;
[assembly : AssemblyVersion("5.6.2.0")]
[assembly : AssemblyFileVersion("5.6.2.0")] | using System.Reflection;
[assembly : AssemblyVersion("5.6.1.0")]
[assembly : AssemblyFileVersion("5.6.1.0")] | apache-2.0 | C# |
6b1117caa908a5cef1e5b13b0ec7860b27617851 | Make this type internal | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Razor.Language/Legacy/SpanKindInternal.cs | src/Microsoft.AspNetCore.Razor.Language/Legacy/SpanKindInternal.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.
namespace Microsoft.AspNetCore.Razor.Language.Legacy
{
internal enum SpanKindInternal
{
Transition,
MetaCode,
Comment,
Code,
Markup
}
}
| // 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.
namespace Microsoft.AspNetCore.Razor.Language.Legacy
{
public enum SpanKindInternal
{
Transition,
MetaCode,
Comment,
Code,
Markup
}
}
| apache-2.0 | C# |
1c4908421f010d47c8621d5b83397fe61f756231 | Make this static | jorik041/maccore,cwensley/maccore,mono/maccore | src/CoreImage/CIFilter.cs | src/CoreImage/CIFilter.cs | //
// CIFilter.cs: Extensions
//
// Copyright 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace MonoTouch.CoreImage {
public partial class CIFilter {
public static string [] FilterNamesInCategories (params string [] categories)
{
return _FilterNamesInCategories (categories);
}
}
} | //
// CIFilter.cs: Extensions
//
// Copyright 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace MonoTouch.CoreImage {
public partial class CIFilter {
public string [] FilterNamesInCategories (params string [] categories)
{
return _FilterNamesInCategories (categories);
}
}
} | apache-2.0 | C# |
d75a6b43f4bafb7c249a0ea5fc7e41a0659d0442 | Add TzInfo | SteveLasker/polyglot-api-dotnet,SteveLasker/polyglot-api-dotnet | api-dotnet/Controllers/HelloController.cs | api-dotnet/Controllers/HelloController.cs | using Microsoft.AspNetCore.Mvc;
using System;
using System.Runtime.InteropServices;
namespace ApiDotNet.Controllers
{
[Route("/api/hello")]
public class HelloController
{
[HttpGet]
public string Get()
{
var osDescription = RuntimeInformation.OSDescription;
var machineName = Environment.MachineName;
// TimeZoneInfo has unique Ids per OS
// Querying the wrong string will throw
TimeZoneInfo tzInfo = null;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
tzInfo = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
tzInfo = TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles");
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
tzInfo = TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles");
else
tzInfo = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id);
var message = string.Format("Hello from api-dotnet. running on: {0} {1}",
osDescription,
tzInfo.ToString());
return message;
}
}
}
| using Microsoft.AspNetCore.Mvc;
using System;
namespace ApiDotNet.Controllers
{
[Route("/api/hello")]
public class HelloController
{
[HttpGet]
public string Get()
{
return $"Hello from api-dotnet at: {DateTimeOffset.UtcNow.ToString("u")}";
}
}
}
| mit | C# |
9130ea1aaf313c7267808cbafcc61971478ee141 | Remove unwanted memberList parameters. | aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template | aspnet-core/src/AbpCompanyName.AbpProjectName.Application/Users/Dto/UserMapProfile.cs | aspnet-core/src/AbpCompanyName.AbpProjectName.Application/Users/Dto/UserMapProfile.cs | using AutoMapper;
using AbpCompanyName.AbpProjectName.Authorization.Users;
namespace AbpCompanyName.AbpProjectName.Users.Dto
{
public class UserMapProfile : Profile
{
public UserMapProfile()
{
CreateMap<UserDto, User>();
CreateMap<UserDto, User>()
.ForMember(x => x.Roles, opt => opt.Ignore())
.ForMember(x => x.CreationTime, opt => opt.Ignore())
.ForMember(x => x.LastLoginTime, opt => opt.Ignore());
CreateMap<CreateUserDto, User>();
CreateMap<CreateUserDto, User>().ForMember(x => x.Roles, opt => opt.Ignore());
}
}
}
| using AutoMapper;
using AbpCompanyName.AbpProjectName.Authorization.Users;
namespace AbpCompanyName.AbpProjectName.Users.Dto
{
public class UserMapProfile : Profile
{
public UserMapProfile()
{
CreateMap<UserDto, User>();
CreateMap<UserDto, User>(MemberList.Source)
.ForMember(x => x.Roles, opt => opt.Ignore())
.ForMember(x => x.CreationTime, opt => opt.Ignore())
.ForMember(x => x.LastLoginTime, opt => opt.Ignore());
CreateMap<CreateUserDto, User>();
CreateMap<CreateUserDto, User>().ForMember(x => x.Roles, opt => opt.Ignore());
}
}
}
| mit | C# |
dc4e41cb58715c21bfce660ce32f3e13075e2b4d | Update add-phone-number.5.x.cs | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | proxy/quickstart/add-phone-number/add-phone-number.5.x.cs | proxy/quickstart/add-phone-number/add-phone-number.5.x.cs | // Get the C# helper library from https://twilio.com/docs/libraries/csharp
using System;
using Twilio;
using Twilio.Rest.Preview.Proxy.Service;
class Example
{
static void Main(string[] args)
{
// Get your Account SID and Auth Token from https://twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
const string proxyServiceSid = "KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string twilioPhoneNumberSid = "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var proxyNumber = PhoneNumberResource.Create(proxyServiceSid, twilioPhoneNumberSid);
Console.WriteLine(proxyNumber.Sid);
}
}
| // Get the Node helper library from https://twilio.com/docs/libraries/csharp
using System;
using Twilio;
using Twilio.Rest.Preview.Proxy.Service;
class Example
{
static void Main(string[] args)
{
// Get your Account SID and Auth Token from https://twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
const string proxyServiceSid = "KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string twilioPhoneNumberSid = "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var proxyNumber = PhoneNumberResource.Create(proxyServiceSid, twilioPhoneNumberSid);
Console.WriteLine(proxyNumber.Sid);
}
}
| mit | C# |
d071230bcfa9d18fe24be6137f3afc0a50485040 | Make the next release version 0.1.1 (bug fixes) | SQLStreamStore/SQLStreamStore,damianh/SqlStreamStore,damianh/Cedar.EventStore,danbarua/Cedar.EventStore,SQLStreamStore/SQLStreamStore | src/SharedAssemblyInfo.cs | src/SharedAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyProduct("SqlStreamStore")]
[assembly: AssemblyCopyright("Copyright Damian Hickey & Contributors 2015 - 2016")]
[assembly: AssemblyVersion("0.1.1.0")]
[assembly: AssemblyFileVersion("0.1.1.0")]
| using System.Reflection;
[assembly: AssemblyProduct("SqlStreamStore")]
[assembly: AssemblyCopyright("Copyright Damian Hickey & Contributors 2015 - 2016")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
| mit | C# |
1736ad2a6bc0cfcf72d5c66a8df3addb3de32b7b | add doc for Org API client | TattsGroup/octokit.net,rlugojr/octokit.net,adamralph/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,gabrielweyer/octokit.net,Sarmad93/octokit.net,kdolan/octokit.net,editor-tools/octokit.net,ChrisMissal/octokit.net,forki/octokit.net,shiftkey/octokit.net,magoswiat/octokit.net,bslliw/octokit.net,hahmed/octokit.net,octokit/octokit.net,khellang/octokit.net,SmithAndr/octokit.net,hahmed/octokit.net,brramos/octokit.net,kolbasov/octokit.net,M-Zuber/octokit.net,alfhenrik/octokit.net,gdziadkiewicz/octokit.net,shiftkey-tester/octokit.net,darrelmiller/octokit.net,yonglehou/octokit.net,alfhenrik/octokit.net,Red-Folder/octokit.net,naveensrinivasan/octokit.net,nsnnnnrn/octokit.net,chunkychode/octokit.net,yonglehou/octokit.net,hitesh97/octokit.net,rlugojr/octokit.net,SmithAndr/octokit.net,editor-tools/octokit.net,eriawan/octokit.net,gabrielweyer/octokit.net,octokit-net-test/octokit.net,ivandrofly/octokit.net,shana/octokit.net,octokit/octokit.net,devkhan/octokit.net,mminns/octokit.net,shiftkey/octokit.net,thedillonb/octokit.net,dampir/octokit.net,fffej/octokit.net,Sarmad93/octokit.net,daukantas/octokit.net,eriawan/octokit.net,geek0r/octokit.net,khellang/octokit.net,devkhan/octokit.net,nsrnnnnn/octokit.net,octokit-net-test-org/octokit.net,dlsteuer/octokit.net,ivandrofly/octokit.net,TattsGroup/octokit.net,SamTheDev/octokit.net,gdziadkiewicz/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,michaKFromParis/octokit.net,M-Zuber/octokit.net,SamTheDev/octokit.net,mminns/octokit.net,takumikub/octokit.net,octokit-net-test-org/octokit.net,cH40z-Lord/octokit.net,thedillonb/octokit.net,shiftkey-tester/octokit.net,chunkychode/octokit.net,dampir/octokit.net,SLdragon1989/octokit.net,shana/octokit.net,fake-organization/octokit.net | Octokit/Clients/OrganizationsClient.cs | Octokit/Clients/OrganizationsClient.cs | using System;
#if NET_45
using System.Collections.Generic;
#endif
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// A client for GitHub's Orgs API.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/orgs/">Orgs API documentation</a> for more information.
/// </remarks>
public class OrganizationsClient : ApiClient, IOrganizationsClient
{
/// <summary>
/// Initializes a new GitHub Orgs API client.
/// </summary>
/// <param name="connection">An API connection.</param>
public OrganizationsClient(IApiConnection connection) : base(connection)
{
}
/// <summary>
/// Returns the specified <see cref="Organization"/>.
/// </summary>
/// <param name="org">login of the organization to get.</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>The specified <see cref="Organization"/>.</returns>
public async Task<Organization> Get(string org)
{
Ensure.ArgumentNotNullOrEmptyString(org, "org");
var endpoint = "/orgs/{0}".FormatUri(org);
return await Client.Get<Organization>(endpoint);
}
/// <summary>
/// Returns all <see cref="Organization" />s for the current user.
/// </summary>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A list of the current user's <see cref="Organization"/>s.</returns>
public async Task<IReadOnlyList<Organization>> GetAllForCurrent()
{
var endpoint = new Uri("/user/orgs", UriKind.Relative);
return await Client.GetAll<Organization>(endpoint);
}
/// <summary>
/// Returns all <see cref="Organization" />s for the specified user.
/// </summary>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A list of the specified user's <see cref="Organization"/>s.</returns>
public async Task<IReadOnlyList<Organization>> GetAll(string user)
{
Ensure.ArgumentNotNullOrEmptyString(user, "user");
var endpoint = "/users/{0}/orgs".FormatUri(user);
return await Client.GetAll<Organization>(endpoint);
}
}
}
| using System;
#if NET_45
using System.Collections.Generic;
#endif
using System.Threading.Tasks;
namespace Octokit
{
public class OrganizationsClient : ApiClient, IOrganizationsClient
{
public OrganizationsClient(IApiConnection client) : base(client)
{
}
public async Task<Organization> Get(string org)
{
Ensure.ArgumentNotNullOrEmptyString(org, "org");
var endpoint = "/orgs/{0}".FormatUri(org);
return await Client.Get<Organization>(endpoint);
}
public async Task<IReadOnlyList<Organization>> GetAllForCurrent()
{
var endpoint = new Uri("/user/orgs", UriKind.Relative);
return await Client.GetAll<Organization>(endpoint);
}
public async Task<IReadOnlyList<Organization>> GetAll(string user)
{
Ensure.ArgumentNotNullOrEmptyString(user, "user");
var endpoint = "/users/{0}/orgs".FormatUri(user);
return await Client.GetAll<Organization>(endpoint);
}
}
}
| mit | C# |
1deb2bfb9e4d2b1431e23fafe429358631be388d | Fix always match issue | Workshop2/noobot,noobot/noobot | src/Noobot.Core/MessagingPipeline/Middleware/ValidHandles/AlwaysMatchHandle.cs | src/Noobot.Core/MessagingPipeline/Middleware/ValidHandles/AlwaysMatchHandle.cs | namespace Noobot.Core.MessagingPipeline.Middleware.ValidHandles
{
public class AlwaysMatchHandle : IValidHandle
{
public bool IsMatch(string message)
{
return true;
}
public string HandleHelpText => string.Empty;
}
} | namespace Noobot.Core.MessagingPipeline.Middleware.ValidHandles
{
public class AlwaysMatchHandle : IValidHandle
{
public bool IsMatch(string message)
{
return true;
}
public string HandleHelpText => "<anything>";
}
} | mit | C# |
8c4840702defbfc083003a8184b61d0f75df8a23 | Fix LabelledValue<T>.Equals | cH40z-Lord/Stylet,canton7/Stylet,cH40z-Lord/Stylet,canton7/Stylet | Stylet/LabelledValue.cs | Stylet/LabelledValue.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stylet
{
public class LabelledValue<T> : IEquatable<LabelledValue<T>>
{
public string Label { get; set; }
public T Value { get; set; }
public LabelledValue(string label, T value)
{
this.Label = label;
this.Value = value;
}
public bool Equals(LabelledValue<T> other)
{
return other == null ? false : this.Label == other.Label && EqualityComparer<T>.Default.Equals(this.Value, other.Value);
}
public override bool Equals(object obj)
{
return this.Equals(obj as LabelledValue<T>);
}
public override int GetHashCode()
{
return this.Label.GetHashCode() ^ this.Value.GetHashCode();
}
public override string ToString()
{
return this.Label;
}
}
public static class LabelledValue
{
public static LabelledValue<T> Create<T>(string label, T value)
{
return new LabelledValue<T>(label, value);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stylet
{
public class LabelledValue<T> : IEquatable<LabelledValue<T>>
{
public string Label { get; set; }
public T Value { get; set; }
public LabelledValue(string label, T value)
{
this.Label = label;
this.Value = value;
}
public bool Equals(LabelledValue<T> other)
{
return this.Label == other.Label && EqualityComparer<T>.Default.Equals(this.Value, other.Value);
}
public override bool Equals(object obj)
{
return (obj is LabelledValue<T>) ? this.Equals((LabelledValue<T>)obj) : false;
}
public override int GetHashCode()
{
return this.Label.GetHashCode() ^ this.Value.GetHashCode();
}
public override string ToString()
{
return this.Label;
}
}
public static class LabelledValue
{
public static LabelledValue<T> Create<T>(string label, T value)
{
return new LabelledValue<T>(label, value);
}
}
}
| mit | C# |
4816eb6e1489bca8861c8fb6db221b96b1f97fa5 | fix vari | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.Models/Classi/ServiziEsterni/AFM/ErroreRichiestaSoccorsoAereo.cs | src/backend/SO115App.Models/Classi/ServiziEsterni/AFM/ErroreRichiestaSoccorsoAereo.cs | using System.Collections.Generic;
namespace SO115App.Models.Classi.ServiziEsterni.AFM
{
public class ErroreRichiestaSoccorsoAereo
{
public List<Errore> errors { get; set; }
public bool IsError() => errors != null && errors.Count > 0;
}
public class Errore
{
public string code { get; set; }
public string detail { get; set; }
}
}
| using System.Collections.Generic;
namespace SO115App.Models.Classi.ServiziEsterni.AFM
{
public class ErroreRichiestaSoccorsoAereo
{
public List<Errore> errors { get; set; }
public bool IsError() => errors != null || errors.Count > 0;
}
public class Errore
{
public string code { get; set; }
public string detail { get; set; }
}
}
| agpl-3.0 | C# |
f3d68c0ea9173c43514e072d4df0680a7d76da7e | Move Seq 'Compact' flag, default | mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection | Program.cs | Program.cs | namespace Cash_Flow_Projection
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
public class Program
{
public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging((context, builder) =>
{
Log.Logger =
new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
.Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
.WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), controlLevelSwitch: LogLevel)
.MinimumLevel.ControlledBy(LogLevel)
.CreateLogger();
builder.AddSerilog();
});
}
}
| namespace Cash_Flow_Projection
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
public class Program
{
public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging((context, builder) =>
{
Log.Logger =
new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
.Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
.WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), compact: true, controlLevelSwitch: LogLevel)
.MinimumLevel.ControlledBy(LogLevel)
.CreateLogger();
builder.AddSerilog();
});
}
}
| mit | C# |
a0cdd62579f89432e3e36e55b8e9b3aa19399044 | Add mx handling and not implemented if non supported type request | fiinix00/DNSRootServerResolver | Program.cs | Program.cs | using ARSoft.Tools.Net.Dns;
using System;
using System.Net;
using System.Net.Sockets;
namespace DNSRootServerResolver
{
public class Program
{
public static void Main(string[] args)
{
using (var server = new DnsServer(IPAddress.Any, 25, 25, DnsServerHandler))
{
server.Start();
string command;
while ((command = Console.ReadLine()) != "exit")
{
if (command == "clear")
{
DNS.GlobalCache.Clear();
}
}
}
}
public static DnsMessageBase DnsServerHandler(DnsMessageBase dnsMessageBase, IPAddress clientAddress, ProtocolType protocolType)
{
DnsMessage query = dnsMessageBase as DnsMessage;
foreach (var question in query.Questions)
{
Console.WriteLine(question);
switch (question.RecordType)
{
case RecordType.A:
case RecordType.Mx:
query.AnswerRecords.AddRange(DNS.Resolve(question.Name, question.RecordType, question.RecordClass)); break;
case RecordType.Ptr:
{
if (question.Name == "1.0.0.127.in-addr.arpa")
{
query.AnswerRecords.Add(new PtrRecord("127.0.0.1", 172800 /*2 days*/, "localhost"));
}
}; break;
default:
{
query.ReturnCode = ReturnCode.NotImplemented;
Console.WriteLine("Unknown record type: " + question.RecordType + " (class: " + question.RecordClass + ", " + question.Name + ")");
} break;
}
}
return query;
}
}
}
| using ARSoft.Tools.Net.Dns;
using System;
using System.Net;
using System.Net.Sockets;
namespace DNSRootServerResolver
{
public class Program
{
public static void Main(string[] args)
{
using (var server = new DnsServer(IPAddress.Any, 25, 25, DnsServerHandler))
{
server.Start();
string command;
while ((command = Console.ReadLine()) != "exit")
{
if (command == "clear")
{
DNS.GlobalCache.Clear();
}
}
}
}
public static DnsMessageBase DnsServerHandler(DnsMessageBase dnsMessageBase, IPAddress clientAddress, ProtocolType protocolType)
{
DnsMessage query = dnsMessageBase as DnsMessage;
foreach (var question in query.Questions)
{
switch (question.RecordType)
{
case RecordType.A:
query.AnswerRecords.AddRange(DNS.Resolve(question.Name)); break;
case RecordType.Ptr:
{
if (question.Name == "1.0.0.127.in-addr.arpa")
{
query.AnswerRecords.Add(new PtrRecord("127.0.0.1", 172800 /*2 days*/, "localhost"));
}
}; break;
}
}
return query;
}
}
}
| mit | C# |
d29310ed5eb27b2f69d712a86a015d33b7747fee | Update client logging function | godarklight/DarkMultiPlayer,Dan-Shields/DarkMultiPlayer,81ninja/DarkMultiPlayer,Sanmilie/DarkMultiPlayer,81ninja/DarkMultiPlayer,godarklight/DarkMultiPlayer | Client/Log.cs | Client/Log.cs | using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
namespace DarkMultiPlayer
{
public class DarkLog
{
public static Queue<string> messageQueue = new Queue<string>();
private static object externalLogLock = new object();
public static void Debug(string message)
{
//Use messageQueue if looking for messages that don't normally show up in the log.
messageQueue.Enqueue(string.Format("DarkMultiPlayer: {0}", message));
}
public static void Update()
{
while (messageQueue.Count > 0)
{
string message = messageQueue.Dequeue();
UnityEngine.Debug.Log(string.Format("[{0}] {1}", Time.realtimeSinceStartup, message));
}
}
public static void ExternalLog(string debugText)
{
lock (externalLogLock)
{
using (StreamWriter sw = new StreamWriter(Path.Combine(KSPUtil.ApplicationRootPath, "DMP.log"), true))
{
sw.WriteLine(debugText);
}
}
}
}
}
| using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
namespace DarkMultiPlayer
{
public class DarkLog
{
public static Queue<string> messageQueue = new Queue<string>();
private static object externalLogLock = new object();
public static void Debug(string message)
{
//Use messageQueue if looking for messages that don't normally show up in the log.
messageQueue.Enqueue("[" + UnityEngine.Time.realtimeSinceStartup + "] DarkMultiPlayer: " + message);
//UnityEngine.Debug.Log("[" + UnityEngine.Time.realtimeSinceStartup + "] DarkMultiPlayer: " + message);
}
public static void Update()
{
while (messageQueue.Count > 0)
{
string message = messageQueue.Dequeue();
UnityEngine.Debug.Log(message);
/*
using (StreamWriter sw = new StreamWriter("DarkLog.txt", true, System.Text.Encoding.UTF8)) {
sw.WriteLine(message);
}
*/
}
}
public static void ExternalLog(string debugText)
{
lock (externalLogLock)
{
using (StreamWriter sw = new StreamWriter(Path.Combine(KSPUtil.ApplicationRootPath, "DMP.log"), true))
{
sw.WriteLine(debugText);
}
}
}
}
}
| mit | C# |
9283b58fd1548941d2816a18e0137de32489913b | Implement SA1124 | DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers/ReadabilityRules/SA1124DoNotUseRegions.cs | StyleCop.Analyzers/StyleCop.Analyzers/ReadabilityRules/SA1124DoNotUseRegions.cs | namespace StyleCop.Analyzers.ReadabilityRules
{
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
/// <summary>
/// The C# code contains a region.
/// </summary>
/// <remarks>
/// <para>A violation of this rule occurs whenever a region is placed anywhere within the code. In many editors,
/// including Visual Studio, the region will appear collapsed by default, hiding the code within the region. It is
/// generally a bad practice to hide code, as this can lead to bad decisions as the code is maintained over
/// time.</para>
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SA1124DoNotUseRegions : DiagnosticAnalyzer
{
/// <summary>
/// The ID for diagnostics produced by the <see cref="SA1124DoNotUseRegions"/> analyzer.
/// </summary>
public const string DiagnosticId = "SA1124";
private const string Title = "Do not use regions";
private const string MessageFormat = "Do not use regions";
private const string Category = "StyleCop.CSharp.ReadabilityRules";
private const string Description = "The C# code contains a region.";
private const string HelpLink = "http://www.stylecop.com/docs/SA1124.html";
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, AnalyzerConstants.DisabledNoTests, Description, HelpLink);
private static readonly ImmutableArray<DiagnosticDescriptor> SupportedDiagnosticsValue =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return SupportedDiagnosticsValue;
}
}
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(this.HandleRegionDirectiveTrivia, SyntaxKind.RegionDirectiveTrivia);
}
private void HandleRegionDirectiveTrivia(SyntaxNodeAnalysisContext context)
{
RegionDirectiveTriviaSyntax regionSyntax = context.Node as RegionDirectiveTriviaSyntax;
// regions that are completely inside a body are handled by SA1123.
if (regionSyntax != null && !SA1123DoNotPlaceRegionsWithinElements.IsCompletelyContainedInBody(regionSyntax))
{
// Regions must not be used.
context.ReportDiagnostic(Diagnostic.Create(Descriptor, regionSyntax.GetLocation()));
}
}
}
}
| namespace StyleCop.Analyzers.ReadabilityRules
{
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
/// <summary>
/// The C# code contains a region.
/// </summary>
/// <remarks>
/// <para>A violation of this rule occurs whenever a region is placed anywhere within the code. In many editors,
/// including Visual Studio, the region will appear collapsed by default, hiding the code within the region. It is
/// generally a bad practice to hide code, as this can lead to bad decisions as the code is maintained over
/// time.</para>
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SA1124DoNotUseRegions : DiagnosticAnalyzer
{
/// <summary>
/// The ID for diagnostics produced by the <see cref="SA1124DoNotUseRegions"/> analyzer.
/// </summary>
public const string DiagnosticId = "SA1124";
private const string Title = "Do not use regions";
private const string MessageFormat = "TODO: Message format";
private const string Category = "StyleCop.CSharp.ReadabilityRules";
private const string Description = "The C# code contains a region.";
private const string HelpLink = "http://www.stylecop.com/docs/SA1124.html";
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, AnalyzerConstants.DisabledNoTests, Description, HelpLink);
private static readonly ImmutableArray<DiagnosticDescriptor> SupportedDiagnosticsValue =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return SupportedDiagnosticsValue;
}
}
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
// TODO: Implement analysis
}
}
}
| mit | C# |
14b4f528d1f5792f8efb8647a2f2ddd420bcaa80 | Make CommitExtensions public so that it can be used by classes extending standard SqlPersistenceEngine | NEventStore/NEventStore,marcoaoteixeira/NEventStore,D3-LucaPiombino/NEventStore,jamiegaines/NEventStore,AGiorgetti/NEventStore,paritoshmmmec/NEventStore,deltatre-webplu/NEventStore,chris-evans/NEventStore,nerdamigo/NEventStore,gael-ltd/NEventStore,adamfur/NEventStore | src/proj/EventStore.Persistence.SqlPersistence/CommitExtensions.cs | src/proj/EventStore.Persistence.SqlPersistence/CommitExtensions.cs | namespace EventStore.Persistence.SqlPersistence
{
using System;
using System.Collections.Generic;
using System.Data;
using Serialization;
public static class CommitExtensions
{
private const int StreamIdIndex = 0;
private const int StreamRevisionIndex = 1;
private const int CommitIdIndex = 2;
private const int CommitSequenceIndex = 3;
private const int CommitStampIndex = 4;
private const int HeadersIndex = 5;
private const int PayloadIndex = 6;
public static Commit GetCommit(this IDataRecord record, ISerialize serializer)
{
var headers = serializer.Deserialize<Dictionary<string, object>>(record, HeadersIndex);
var events = serializer.Deserialize<List<EventMessage>>(record, PayloadIndex);
return new Commit(
record[StreamIdIndex].ToGuid(),
record[StreamRevisionIndex].ToInt(),
record[CommitIdIndex].ToGuid(),
record[CommitSequenceIndex].ToInt(),
record[CommitStampIndex].ToDateTime(),
headers,
events);
}
public static T Deserialize<T>(this ISerialize serializer, IDataRecord record, int index)
{
if (index >= record.FieldCount)
return default(T);
var value = record[index];
if (value == null || value == DBNull.Value)
return default(T);
var bytes = (byte[])value;
return bytes.Length == 0 ? default(T) : serializer.Deserialize<T>(bytes);
}
}
} | namespace EventStore.Persistence.SqlPersistence
{
using System;
using System.Collections.Generic;
using System.Data;
using Serialization;
internal static class CommitExtensions
{
private const int StreamIdIndex = 0;
private const int StreamRevisionIndex = 1;
private const int CommitIdIndex = 2;
private const int CommitSequenceIndex = 3;
private const int CommitStampIndex = 4;
private const int HeadersIndex = 5;
private const int PayloadIndex = 6;
public static Commit GetCommit(this IDataRecord record, ISerialize serializer)
{
var headers = serializer.Deserialize<Dictionary<string, object>>(record, HeadersIndex);
var events = serializer.Deserialize<List<EventMessage>>(record, PayloadIndex);
return new Commit(
record[StreamIdIndex].ToGuid(),
record[StreamRevisionIndex].ToInt(),
record[CommitIdIndex].ToGuid(),
record[CommitSequenceIndex].ToInt(),
record[CommitStampIndex].ToDateTime(),
headers,
events);
}
public static T Deserialize<T>(this ISerialize serializer, IDataRecord record, int index)
{
if (index >= record.FieldCount)
return default(T);
var value = record[index];
if (value == null || value == DBNull.Value)
return default(T);
var bytes = (byte[])value;
return bytes.Length == 0 ? default(T) : serializer.Deserialize<T>(bytes);
}
}
} | mit | C# |
f77b143d2486b481b9a432fe1dc4c708ad55c91a | Change Entity.AddComponent to infer type instead of being generic. | ZachMassia/XNA_Project | ECS/Entity.cs | ECS/Entity.cs | using System;
using System.Collections.Generic;
namespace ECS
{
public sealed class Entity
{
// A unique ID representing the Entity. Will not be reused if
// the entity is deleted.
public long UniqueID { get; internal set; }
// The entity's components mapped to their type.
private Dictionary<Type, IComponent> components;
internal Entity(long id)
{
UniqueID = id;
}
// Attempt to retrieve a component of type T.
public T GetComponent<T>() where T:IComponent
{
IComponent c;
if (components.TryGetValue(typeof(T), out c))
{
return (T)c;
}
throw new ArgumentException(String.Format("Entity {0} does not contain component {1}", UniqueID, typeof(T)));
}
// Add a component of type T if it does not already exist.
public void AddComponent(IComponent component)
{
var T = component.GetType();
if (!components.ContainsKey(T))
{
components[T] = component;
}
}
// Remove component of type T.
public void RemoveComponent<T>()
{
components.Remove(typeof(T));
}
// Check if Entity has component of type T.
public bool HasComponent<T>()
{
return HasComponent(typeof(T));
}
public bool HasComponent(Type t)
{
return components.ContainsKey(t);
}
}
}
| using System;
using System.Collections.Generic;
namespace ECS
{
public sealed class Entity
{
// A unique ID representing the Entity. Will not be reused if
// the entity is deleted.
public long UniqueID { get; internal set; }
// The entity's components mapped to their type.
private Dictionary<Type, IComponent> components;
internal Entity(long id)
{
UniqueID = id;
}
// Attempt to retrieve a component of type T.
public T GetComponent<T>() where T:IComponent
{
IComponent c;
if (components.TryGetValue(typeof(T), out c))
{
return (T)c;
}
throw new ArgumentException(String.Format("Entity {0} does not contain component {1}", UniqueID, typeof(T)));
}
// Add a component of type T if it does not already exist.
public void AddComponent<T>(T component) where T:IComponent
{
if (!components.ContainsKey(typeof(T)))
{
components[typeof(T)] = component;
}
}
// Remove component of type T.
public void RemoveComponent<T>()
{
components.Remove(typeof(T));
}
// Check if Entity has component of type T.
public bool HasComponent<T>()
{
return HasComponent(typeof(T));
}
public bool HasComponent(Type t)
{
return components.ContainsKey(t);
}
}
}
| mit | C# |
dfa49aea79036e551e8393f4be8cdc22b73671e4 | Add unity config | laedit/Borderlands2-Golden-Keys,laedit/Borderlands2-Golden-Keys | Borderlands2GoldendKeys/Borderlands2GoldendKeys/Global.asax.cs | Borderlands2GoldendKeys/Borderlands2GoldendKeys/Global.asax.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Borderlands2GoldendKeys
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
UnityConfig.RegisterComponents();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Borderlands2GoldendKeys
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| apache-2.0 | C# |
1dd0ffbd5dffc3ef72f38a1c9f4f2c76e1ac74cf | Add tests | skonves/Konves.KScript | tests/Konves.KScript.UnitTests/InExpressionTestFixture.cs | tests/Konves.KScript.UnitTests/InExpressionTestFixture.cs | using System;
using Konves.KScript.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
namespace Konves.KScript.UnitTests
{
[TestClass]
public class InExpressionTestFixture
{
[TestCategory(nameof(InExpression))]
[TestMethod]
public void TestEvaluate()
{
string stringValue = "string value";
decimal decimalValue = 5m;
DateTime dateValue = DateTime.Parse("2015-1-1");
bool boolValue = true;
IReadOnlyCollection<object> list = new List<object> { stringValue, decimalValue, dateValue, boolValue };
DoTestEvaluate(null, list, false);
DoTestEvaluate(stringValue, list, true);
DoTestEvaluate(decimalValue, list, true);
DoTestEvaluate(dateValue, list, true);
DoTestEvaluate(boolValue, list, true);
DoTestEvaluate("not found", list, false);
DoTestEvaluate(1234m, list, false);
DoTestEvaluate(DateTime.Parse("2000-1-1"), list, false);
DoTestEvaluate(!boolValue, list, false);
}
private void DoTestEvaluate(object value, IReadOnlyCollection<object> list, bool expected)
{
// Arrange
Literal literal = new Literal(value, LiteralType.Value);
IReadOnlyCollection<Literal> literals = list.Select(item => new Literal(item, LiteralType.Value)).ToList();
IExpression expression = new InExpression(literal, literals);
// Act
bool result = expression.Evaluate(null);
// Assert
Assert.AreEqual(expected, result);
}
}
}
| using System;
using Konves.KScript.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace Konves.KScript.UnitTests
{
[TestClass]
public class InExpressionTestFixture
{
[TestCategory(nameof(InExpression))]
[TestMethod]
public void TestEvaluate()
{
}
private void DoTestEvaluate(bool expected)
{
// Arrange
//IExpression expression = new InExpression()
// Act
// Assert
}
}
}
| apache-2.0 | C# |
46ef17354ee1922f30ef2e64d38ee321455e0f2b | Simplify path construction | ppy/osu,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,naoey/osu,ZLima12/osu,NeoAdonis/osu,ZLima12/osu,Nabile-Rahmani/osu,Frontear/osuKyzer,ppy/osu,peppy/osu,DrabWeb/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,johnneijzen/osu,peppy/osu-new,naoey/osu,smoogipoo/osu,UselessToucan/osu,naoey/osu,EVAST9919/osu,EVAST9919/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,DrabWeb/osu,UselessToucan/osu,DrabWeb/osu,2yangk23/osu | osu.Game/Audio/SampleInfo.cs | osu.Game/Audio/SampleInfo.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.IO;
using osu.Framework.Audio.Sample;
namespace osu.Game.Audio
{
[Serializable]
public class SampleInfo
{
public const string HIT_WHISTLE = @"hitwhistle";
public const string HIT_FINISH = @"hitfinish";
public const string HIT_NORMAL = @"hitnormal";
public const string HIT_CLAP = @"hitclap";
public SampleChannel GetChannel(SampleManager manager, string resourceNamespace = null)
{
SampleChannel channel = manager.Get(Path.Combine("Gameplay", resourceNamespace ?? string.Empty, $"{Bank}-{Name}"));
channel.Volume.Value = Volume / 100.0;
return channel;
}
/// <summary>
/// The bank to load the sample from.
/// </summary>
public string Bank;
/// <summary>
/// The name of the sample to load.
/// </summary>
public string Name;
/// <summary>
/// The sample volume.
/// </summary>
public int Volume;
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Audio.Sample;
namespace osu.Game.Audio
{
[Serializable]
public class SampleInfo
{
public const string HIT_WHISTLE = @"hitwhistle";
public const string HIT_FINISH = @"hitfinish";
public const string HIT_NORMAL = @"hitnormal";
public const string HIT_CLAP = @"hitclap";
public SampleChannel GetChannel(SampleManager manager, string resourceNamespace = null)
{
SampleChannel channel = null;
if (!string.IsNullOrEmpty(resourceNamespace))
channel = manager.Get($"Gameplay/{resourceNamespace}/{Bank}-{Name}");
if (channel == null)
channel = manager.Get($"Gameplay/{Bank}-{Name}");
channel.Volume.Value = Volume / 100.0;
return channel;
}
/// <summary>
/// The bank to load the sample from.
/// </summary>
public string Bank;
/// <summary>
/// The name of the sample to load.
/// </summary>
public string Name;
/// <summary>
/// The sample volume.
/// </summary>
public int Volume;
}
}
| mit | C# |
3430f6f1faae0844e3024ce9ed13609fb5af9f97 | Refactor GeneralSettingsTests.GeneralAndNUnit test | atata-framework/atata-configuration-json | src/Atata.Configuration.Json.Tests/GeneralSettingsTests.cs | src/Atata.Configuration.Json.Tests/GeneralSettingsTests.cs | using System;
using FluentAssertions;
using FluentAssertions.Execution;
using NUnit.Framework;
namespace Atata.Configuration.Json.Tests
{
[TestFixture]
public class GeneralSettingsTests : TestFixture
{
[Test]
public void GeneralAndNUnit()
{
AtataContextBuilder builder = AtataContext.Configure().
ApplyJsonConfig("Configs/Chrome+NUnit.json");
var context = builder.BuildingContext;
using (new AssertionScope())
{
context.BaseUrl.Should().Be("https://demo.atata.io/");
context.Culture.Name.Should().Be("en-US");
context.CleanUpActions.Should().HaveCount(3);
context.AssertionExceptionType.Should().Be(typeof(NUnit.Framework.AssertionException));
context.BaseRetryTimeout.Should().Be(TimeSpan.FromSeconds(7));
context.BaseRetryInterval.Should().Be(TimeSpan.FromSeconds(0.7));
context.ElementFindTimeout.Should().Be(TimeSpan.FromSeconds(8));
context.ElementFindRetryInterval.Should().Be(TimeSpan.FromSeconds(0.8));
context.WaitingTimeout.Should().Be(TimeSpan.FromSeconds(9));
context.WaitingRetryInterval.Should().Be(TimeSpan.FromSeconds(0.9));
context.VerificationTimeout.Should().Be(TimeSpan.FromSeconds(10));
context.VerificationRetryInterval.Should().Be(TimeSpan.FromSeconds(1));
context.TestNameFactory().Should().Be(nameof(GeneralAndNUnit));
context.DefaultAssemblyNamePatternToFindTypes.Should().Be("def");
context.AssemblyNamePatternToFindComponentTypes.Should().Be("comp");
context.AssemblyNamePatternToFindAttributeTypes.Should().Be("attr");
}
}
}
}
| using System;
using FluentAssertions;
using FluentAssertions.Execution;
using NUnit.Framework;
namespace Atata.Configuration.Json.Tests
{
[TestFixture]
public class GeneralSettingsTests : TestFixture
{
[Test]
public void GeneralAndNUnit()
{
AtataContextBuilder builder = AtataContext.Configure().
ApplyJsonConfig("Configs/Chrome+NUnit.json");
var context = builder.BuildingContext;
using (new AssertionScope())
{
context.BaseUrl.Should().Be("https://demo.atata.io/");
context.Culture.Name.Should().Be("en-US");
context.CleanUpActions.Should().HaveCount(3);
context.AssertionExceptionType.Should().Be(typeof(NUnit.Framework.AssertionException));
context.BaseRetryTimeout.Should().Be(TimeSpan.FromSeconds(7));
context.BaseRetryInterval.Should().Be(TimeSpan.FromSeconds(0.7));
context.ElementFindTimeout.Should().Be(TimeSpan.FromSeconds(8));
context.ElementFindRetryInterval.Should().Be(TimeSpan.FromSeconds(0.8));
context.WaitingTimeout.Should().Be(TimeSpan.FromSeconds(9));
context.WaitingRetryInterval.Should().Be(TimeSpan.FromSeconds(0.9));
context.VerificationTimeout.Should().Be(TimeSpan.FromSeconds(10));
context.VerificationRetryInterval.Should().Be(TimeSpan.FromSeconds(1));
context.TestNameFactory().Should().Be(nameof(GeneralAndNUnit));
context.DefaultAssemblyNamePatternToFindTypes.Should().Be("def");
context.AssemblyNamePatternToFindComponentTypes.Should().Be("comp");
context.AssemblyNamePatternToFindAttributeTypes.Should().Be("attr");
}
builder.Build();
}
}
}
| apache-2.0 | C# |
1681988c53a60b5e1a01a5da2f00b924844cf64a | remove navigation reset on close | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/AddWallet/Common/EnterPasswordViewModel.cs | WalletWasabi.Fluent/AddWallet/Common/EnterPasswordViewModel.cs | using ReactiveUI;
using System;
using System.Reactive.Linq;
using System.Windows.Input;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Fluent.AddWallet.CreateWallet;
using WalletWasabi.Fluent.ViewModels;
using WalletWasabi.Fluent.ViewModels.Dialogs;
using WalletWasabi.Gui;
using WalletWasabi.Gui.Validation;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Models;
using WalletWasabi.Userfacing;
namespace WalletWasabi.Fluent.AddWallet.Common
{
public class EnterPasswordViewModel : DialogViewModelBase<string>
{
private IScreen _screen;
private string _password;
private string _confirmPassword;
public EnterPasswordViewModel(IScreen screen, Global global, string walletName)
{
_screen = screen;
this.ValidateProperty(x => x.Password, ValidatePassword);
this.ValidateProperty(x => x.ConfirmPassword, ValidateConfirmPassword);
var continueCommandCanExecute = this.WhenAnyValue(
x => x.Password,
x => x.ConfirmPassword,
(password, confirmPassword) =>
{
// This will fire validations before return canExecute value.
this.RaisePropertyChanged(nameof(Password));
this.RaisePropertyChanged(nameof(ConfirmPassword));
return (string.IsNullOrEmpty(password) && string.IsNullOrEmpty(confirmPassword)) || (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(confirmPassword) && !Validations.Any);
})
.ObserveOn(RxApp.MainThreadScheduler);
ContinueCommand = ReactiveCommand.Create(() => Close(Password), continueCommandCanExecute);
CancelCommand = ReactiveCommand.Create(() => Close(null!));
}
public string Password
{
get => _password;
set => this.RaiseAndSetIfChanged(ref _password, value);
}
public string ConfirmPassword
{
get => _confirmPassword;
set => this.RaiseAndSetIfChanged(ref _confirmPassword, value);
}
public ICommand ContinueCommand { get; }
public ICommand CancelCommand { get; }
protected override void OnDialogClosed()
{
}
private void ValidateConfirmPassword(IValidationErrors errors)
{
if (!string.IsNullOrEmpty(ConfirmPassword) && Password != ConfirmPassword)
{
errors.Add(ErrorSeverity.Error, PasswordHelper.MatchingMessage);
}
}
private void ValidatePassword(IValidationErrors errors)
{
if (PasswordHelper.IsTrimable(Password, out _))
{
errors.Add(ErrorSeverity.Error, PasswordHelper.WhitespaceMessage);
}
if (PasswordHelper.IsTooLong(Password, out _))
{
errors.Add(ErrorSeverity.Error, PasswordHelper.PasswordTooLongMessage);
}
}
}
} | using ReactiveUI;
using System;
using System.Reactive.Linq;
using System.Windows.Input;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Fluent.AddWallet.CreateWallet;
using WalletWasabi.Fluent.ViewModels;
using WalletWasabi.Fluent.ViewModels.Dialogs;
using WalletWasabi.Gui;
using WalletWasabi.Gui.Validation;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Models;
using WalletWasabi.Userfacing;
namespace WalletWasabi.Fluent.AddWallet.Common
{
public class EnterPasswordViewModel : DialogViewModelBase<string>
{
private IScreen _screen;
private string _password;
private string _confirmPassword;
public EnterPasswordViewModel(IScreen screen, Global global, string walletName)
{
_screen = screen;
this.ValidateProperty(x => x.Password, ValidatePassword);
this.ValidateProperty(x => x.ConfirmPassword, ValidateConfirmPassword);
var continueCommandCanExecute = this.WhenAnyValue(
x => x.Password,
x => x.ConfirmPassword,
(password, confirmPassword) =>
{
// This will fire validations before return canExecute value.
this.RaisePropertyChanged(nameof(Password));
this.RaisePropertyChanged(nameof(ConfirmPassword));
return (string.IsNullOrEmpty(password) && string.IsNullOrEmpty(confirmPassword)) || (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(confirmPassword) && !Validations.Any);
})
.ObserveOn(RxApp.MainThreadScheduler);
ContinueCommand = ReactiveCommand.Create(() => Close(Password), continueCommandCanExecute);
CancelCommand = ReactiveCommand.Create(() => Close(null!));
}
public string Password
{
get => _password;
set => this.RaiseAndSetIfChanged(ref _password, value);
}
public string ConfirmPassword
{
get => _confirmPassword;
set => this.RaiseAndSetIfChanged(ref _confirmPassword, value);
}
public ICommand ContinueCommand { get; }
public ICommand CancelCommand { get; }
protected override void OnDialogClosed()
{
_screen.Router.NavigateAndReset.Execute(new AddWalletPageViewModel(_screen));
}
private void ValidateConfirmPassword(IValidationErrors errors)
{
if (!string.IsNullOrEmpty(ConfirmPassword) && Password != ConfirmPassword)
{
errors.Add(ErrorSeverity.Error, PasswordHelper.MatchingMessage);
}
}
private void ValidatePassword(IValidationErrors errors)
{
if (PasswordHelper.IsTrimable(Password, out _))
{
errors.Add(ErrorSeverity.Error, PasswordHelper.WhitespaceMessage);
}
if (PasswordHelper.IsTooLong(Password, out _))
{
errors.Add(ErrorSeverity.Error, PasswordHelper.PasswordTooLongMessage);
}
}
}
} | mit | C# |
4b9d2413ded4f44e625c04d91c4a047eb8ce36e2 | add overload to AutomaticPackageMigrationPlan | arknu/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS | src/Umbraco.Infrastructure/Packaging/AutomaticPackageMigrationPlan.cs | src/Umbraco.Infrastructure/Packaging/AutomaticPackageMigrationPlan.cs | using System;
using System.Xml.Linq;
using Umbraco.Cms.Core.Packaging;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Infrastructure.Migrations;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Packaging
{
/// <summary>
/// Used to automatically indicate that a package has an embedded package data manifest that needs to be installed
/// </summary>
public abstract class AutomaticPackageMigrationPlan : PackageMigrationPlan
{
private XDocument _xdoc;
protected AutomaticPackageMigrationPlan(string name)
: base(name)
{
}
protected AutomaticPackageMigrationPlan(string packageName, string planName) : base(packageName, planName)
{
}
protected sealed override void DefinePlan()
{
// calculate the final state based on the hash value of the embedded resource
var finalId = PackageDataManifest.ToString(SaveOptions.DisableFormatting).ToGuid();
To<MigrateToPackageData>(finalId);
}
/// <summary>
/// Get the extracted package data xml manifest
/// </summary>
private XDocument PackageDataManifest
{
get
{
if (_xdoc != null)
{
return _xdoc;
}
Type planType = GetType();
_xdoc = PackageMigrationResource.GetEmbeddedPackageDataManifest(planType);
return _xdoc;
}
}
private class MigrateToPackageData : PackageMigrationBase
{
public MigrateToPackageData(IPackagingService packagingService, IMigrationContext context)
: base(packagingService, context)
{
}
public override void Migrate()
{
var plan = (AutomaticPackageMigrationPlan)Context.Plan;
XDocument xml = plan.PackageDataManifest;
ImportPackage.FromXmlDataManifest(xml).Do();
}
}
}
}
| using System;
using System.Xml.Linq;
using Umbraco.Cms.Core.Packaging;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Infrastructure.Migrations;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Packaging
{
/// <summary>
/// Used to automatically indicate that a package has an embedded package data manifest that needs to be installed
/// </summary>
public abstract class AutomaticPackageMigrationPlan : PackageMigrationPlan
{
private XDocument _xdoc;
protected AutomaticPackageMigrationPlan(string name)
: base(name)
{
}
protected sealed override void DefinePlan()
{
// calculate the final state based on the hash value of the embedded resource
var finalId = PackageDataManifest.ToString(SaveOptions.DisableFormatting).ToGuid();
To<MigrateToPackageData>(finalId);
}
/// <summary>
/// Get the extracted package data xml manifest
/// </summary>
private XDocument PackageDataManifest
{
get
{
if (_xdoc != null)
{
return _xdoc;
}
Type planType = GetType();
_xdoc = PackageMigrationResource.GetEmbeddedPackageDataManifest(planType);
return _xdoc;
}
}
private class MigrateToPackageData : PackageMigrationBase
{
public MigrateToPackageData(IPackagingService packagingService, IMigrationContext context)
: base(packagingService, context)
{
}
public override void Migrate()
{
var plan = (AutomaticPackageMigrationPlan)Context.Plan;
XDocument xml = plan.PackageDataManifest;
ImportPackage.FromXmlDataManifest(xml).Do();
}
}
}
}
| mit | C# |
c912a3c06b3f77589ce34cefe29dc4bc709f3453 | fix ladder time ui refresh on load race state | tawnkramer/sdsandbox,tawnkramer/sdsandbox | sdsim/Assets/Scripts/Race/RacePairUI.cs | sdsim/Assets/Scripts/Race/RacePairUI.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RacePairUI : MonoBehaviour
{
public Text racer1;
public Text racer2;
public Text place1;
public Text place2;
public Text racer1time;
public Text racer2time;
public Color win_color;
public Color loss_color;
public void Awake()
{
racer1time.text = "";
racer2time.text = "";
}
public void SetRacers(string r1, string r2, int p1, int p2)
{
racer1.text = r1;
if (r2 == "solo")
racer2.gameObject.SetActive(false);
else
racer2.text = r2;
place1.text = System.String.Format("{0}.", p1);
if (p2 > 0)
place2.text = System.String.Format("{0}.", p2);
else
place2.gameObject.SetActive(false);
}
public void SetTimes(float t1, float t2)
{
racer1time.text = System.String.Format("{0:F2}", t1);
if(t2 != RaceManager.dq_time)
racer2time.text = System.String.Format("{0:F2}", t2);
}
public void SetWinner(bool firstWon)
{
racer1.color = firstWon ? win_color : loss_color;
racer1time.color = firstWon ? win_color : loss_color;
racer2.color = !firstWon ? win_color : loss_color;
racer2time.color = !firstWon ? win_color : loss_color;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RacePairUI : MonoBehaviour
{
public Text racer1;
public Text racer2;
public Text place1;
public Text place2;
public Text racer1time;
public Text racer2time;
public Color win_color;
public Color loss_color;
public void Start()
{
racer1time.text = "";
racer2time.text = "";
}
public void SetRacers(string r1, string r2, int p1, int p2)
{
racer1.text = r1;
if (r2 == "solo")
racer2.gameObject.SetActive(false);
else
racer2.text = r2;
place1.text = System.String.Format("{0}.", p1);
if (p2 > 0)
place2.text = System.String.Format("{0}.", p2);
else
place2.gameObject.SetActive(false);
}
public void SetTimes(float t1, float t2)
{
racer1time.text = System.String.Format("{0:F2}", t1);
if(t2 != RaceManager.dq_time)
racer2time.text = System.String.Format("{0:F2}", t2);
}
public void SetWinner(bool firstWon)
{
racer1.color = firstWon ? win_color : loss_color;
racer1time.color = firstWon ? win_color : loss_color;
racer2.color = !firstWon ? win_color : loss_color;
racer2time.color = !firstWon ? win_color : loss_color;
}
}
| bsd-3-clause | C# |
fe2c639cf9666145d1d69f8c35014da7c520b73c | Set lang dir only if RTL | petedavis/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard,petedavis/Orchard2,stevetayloruk/Orchard2 | src/OrchardCore.Modules/OrchardCore.Html/Views/HtmlBodyPart-Trumbowyg.Edit.cshtml | src/OrchardCore.Modules/OrchardCore.Html/Views/HtmlBodyPart-Trumbowyg.Edit.cshtml | @model HtmlBodyPartViewModel
@using OrchardCore.Html.ViewModels;
@using OrchardCore.Html.Settings;
@using OrchardCore.ContentLocalization
@using OrchardCore.ContentManagement.Metadata.Models
@using OrchardCore.Localization
@using System.Globalization
@{
var settings = Model.TypePartDefinition.GetSettings<HtmlBodyPartSettings>();
var trumbowygSettings = Model.TypePartDefinition.GetSettings<HtmlBodyPartTrumbowygEditorSettings>();
var culture = await Orchard.GetContentCultureAsync(Model.ContentItem) ?? CultureInfo.CurrentUICulture;
}
<script asp-name="trumbowyg-plugins" depends-on="admin" version="2" at="Foot"></script>
<style asp-name="trumbowyg-plugins" version="2"></style>
@if (trumbowygSettings.InsertMediaWithUrl)
{
<script asp-src="~/OrchardCore.Html/Scripts/trumbowyg.media.url.min.js" debug-src="~/OrchardCore.Html/Scripts/trumbowyg.media.url.js" depends-on="trumbowyg" at="Foot"></script>
}
else
{
<script asp-src="~/OrchardCore.Html/Scripts/trumbowyg.media.tag.min.js" debug-src="~/OrchardCore.Html/Scripts/trumbowyg.media.tag.js" depends-on="trumbowyg" at="Foot"></script>
}
<div class="form-group">
<label asp-for="Html">@Model.TypePartDefinition.DisplayName()</label>
@if (culture.IsRightToLeft())
{
<div style="text-align:right">
<textarea asp-for="Html" rows="5" class="form-control"></textarea>
</div>
}
else
{
<textarea asp-for="Html" rows="5" class="form-control"></textarea>
}
<span class="hint">@T["The body of the content item."]</span>
</div>
<script at="Foot">
$(function () {
@{
if (culture.GetLanguageDirection() == LanguageDirection.RTL)
{
<text>
jQuery.trumbowyg.langs.@culture.TwoLetterISOLanguageName = {
_dir: '@culture.GetLanguageDirection()'
};
</text>
}
}
var settings = @Html.Raw(trumbowygSettings.Options);
settings['lang'] = '@culture.TwoLetterISOLanguageName';
$('#@Html.IdFor(m => m.Html)').trumbowyg(settings).on('tbwchange', function () {
$(document).trigger('contentpreview:render');
});
});
$.trumbowyg.svgPath = '/OrchardCore.Resources/Styles/ui/icons.svg';
</script> | @model HtmlBodyPartViewModel
@using OrchardCore.Html.ViewModels;
@using OrchardCore.Html.Settings;
@using OrchardCore.ContentLocalization
@using OrchardCore.ContentManagement.Metadata.Models
@using OrchardCore.Localization
@using System.Globalization
@{
var settings = Model.TypePartDefinition.GetSettings<HtmlBodyPartSettings>();
var trumbowygSettings = Model.TypePartDefinition.GetSettings<HtmlBodyPartTrumbowygEditorSettings>();
var culture = await Orchard.GetContentCultureAsync(Model.ContentItem) ?? CultureInfo.CurrentUICulture;
}
<script asp-name="trumbowyg-plugins" depends-on="admin" version="2" at="Foot"></script>
<style asp-name="trumbowyg-plugins" version="2"></style>
@if (trumbowygSettings.InsertMediaWithUrl)
{
<script asp-src="~/OrchardCore.Html/Scripts/trumbowyg.media.url.min.js" debug-src="~/OrchardCore.Html/Scripts/trumbowyg.media.url.js" depends-on="trumbowyg" at="Foot"></script>
}
else
{
<script asp-src="~/OrchardCore.Html/Scripts/trumbowyg.media.tag.min.js" debug-src="~/OrchardCore.Html/Scripts/trumbowyg.media.tag.js" depends-on="trumbowyg" at="Foot"></script>
}
<div class="form-group">
<label asp-for="Html">@Model.TypePartDefinition.DisplayName()</label>
@if (culture.IsRightToLeft())
{
<div style="text-align:right">
<textarea asp-for="Html" rows="5" class="form-control"></textarea>
</div>
}
else
{
<textarea asp-for="Html" rows="5" class="form-control"></textarea>
}
<span class="hint">@T["The body of the content item."]</span>
</div>
<script at="Foot">
$(function () {
jQuery.trumbowyg.langs.@culture.TwoLetterISOLanguageName = {
_dir: '@culture.GetLanguageDirection()',
};
var settings = @Html.Raw(trumbowygSettings.Options);
settings['lang'] = '@culture.TwoLetterISOLanguageName';
$('#@Html.IdFor(m => m.Html)').trumbowyg(settings).on('tbwchange', function () {
$(document).trigger('contentpreview:render');
});
});
$.trumbowyg.svgPath = '/OrchardCore.Resources/Styles/ui/icons.svg';
</script> | bsd-3-clause | C# |
64f0d9bc40df1c1a195808bed75a95c5a521f16b | Fix logging | laurentkempe/HipChatConnect,laurentkempe/HipChatConnect | src/HipChatConnect/Controllers/Listeners/TeamCity/TeamCityListenerController.cs | src/HipChatConnect/Controllers/Listeners/TeamCity/TeamCityListenerController.cs | using System.Net;
using System.Threading.Tasks;
using HipChatConnect.Controllers.Listeners.TeamCity.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace HipChatConnect.Controllers.Listeners.TeamCity
{
[Route("/teamcity/listener")]
public class TeamCityListenerController : Controller
{
private readonly IMediator _mediator;
private readonly ILogger<TeamCityListenerController> _logger;
public TeamCityListenerController(IMediator mediator, ILogger<TeamCityListenerController> logger)
{
_mediator = mediator;
_logger = logger;
}
[HttpPost]
public async Task<HttpStatusCode> Build([FromBody]TeamCityModel teamCityModel)
{
_logger.LogInformation($"Received status for [{teamCityModel.build.buildName}] from [{teamCityModel.build.rootUrl}] with result [{teamCityModel.build.buildResult}]");
await _mediator.Publish(new TeamcityBuildNotification(teamCityModel));
return HttpStatusCode.OK;
}
}
}
| using System.Net;
using System.Threading.Tasks;
using HipChatConnect.Controllers.Listeners.TeamCity.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace HipChatConnect.Controllers.Listeners.TeamCity
{
[Route("/teamcity/listener")]
public class TeamCityListenerController : Controller
{
private readonly IMediator _mediator;
private readonly ILogger<TeamCityListenerController> _logger;
public TeamCityListenerController(IMediator mediator, ILogger<TeamCityListenerController> logger)
{
_mediator = mediator;
_logger = logger;
}
[HttpPost]
public async Task<HttpStatusCode> Build([FromBody]TeamCityModel teamCityModel)
{
_logger.LogInformation($"Received status for {teamCityModel.build.buildName} from ${teamCityModel.build.rootUrl} with status ${teamCityModel.build.buildStatus}");
await _mediator.Publish(new TeamcityBuildNotification(teamCityModel));
return HttpStatusCode.OK;
}
}
}
| mit | C# |
a4e607dee1d3f288306a3af3daa88233ff8acfb6 | Add peter to contact | jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox | ZirMed.TrainingSandbox/Views/Home/Contact.cshtml | ZirMed.TrainingSandbox/Views/Home/Contact.cshtml | @{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a>
<strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Nicolas:</strong> <a href="mailto:nick.wolf@zirmed.com">nick.wolf@zirmed.com</a>
<strong>Dustin2:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Travis:</strong> <a href="mailto:travis.elkins@zirmed.com">travis.elkins@zirmed.com</a>
<strong>Travis2:</strong> <a href="mailto:travis.elkins@zirmed.com">travis.elkins@zirmed.com</a>
<strong>Stephanie:</strong> <a href="mailto:stephanie.craig@zirmed.com">stephanie.craig@zirmed.com</a>
<strong>Clark Kent:</strong> <a href="mailto:superman.com">superman.com</a>
<strong>Peter Parker:</strong> <a href="mailto:spider-man.com">spider-man.com</a>
</address> | @{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a>
<strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Nicolas:</strong> <a href="mailto:nick.wolf@zirmed.com">nick.wolf@zirmed.com</a>
<strong>Dustin2:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Travis:</strong> <a href="mailto:travis.elkins@zirmed.com">travis.elkins@zirmed.com</a>
<strong>Travis2:</strong> <a href="mailto:travis.elkins@zirmed.com">travis.elkins@zirmed.com</a>
<strong>Stephanie:</strong> <a href="mailto:stephanie.craig@zirmed.com">stephanie.craig@zirmed.com</a>
<strong>Clark Kent:</strong> <a href="mailto:superman.com">superman.com</a>
</address> | mit | C# |
2e698024abc3f185ea7ba0a43e12d91584209308 | Remove premature extension addition | agc93/DocCreator,agc93/DocCreator | src/MarkdownGenerator/Extensions.cs | src/MarkdownGenerator/Extensions.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MarkdownGenerator
{
public static class Extensions
{
public static void CopyDirectory(this DirectoryInfo source, DirectoryInfo target)
{
Copy(source.FullName, target.FullName);
}
private static void Copy(string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
CopyAll(diSource, diTarget);
}
private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MarkdownGenerator
{
public static class Extensions
{
public static void CopyDirectory(this DirectoryInfo source, DirectoryInfo target)
{
Copy(source.FullName, target.FullName);
}
private static void Copy(string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
CopyAll(diSource, diTarget);
}
private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
public static void CreateIfNotExists(this DirectoryBase directory, string path)
{
if (directory.Exists(path)) return;
directory.CreateDirectory(path);
}
}
}
| mit | C# |
51031ba053456f219285a75988924c0f08dc2dcf | Remove unused constructor | OpenStreamDeck/StreamDeckSharp | src/StreamDeckSharp/RepaintQueue.cs | src/StreamDeckSharp/RepaintQueue.cs | using System;
using System.Collections.Generic;
using System.Threading;
namespace StreamDeckSharp
{
internal sealed class KeyRepaintQueue
{
private class KeyBitmapHolder
{
public byte[] bitmapData;
}
private readonly Queue<int> keyQueue = new Queue<int>();
private readonly KeyBitmapHolder[] keyIndex = new KeyBitmapHolder[StreamDeckHID.numOfKeys];
private readonly object listLock = new object();
private readonly SemaphoreSlim waiter = new SemaphoreSlim(0);
public void Enqueue(int keyId, byte[] data)
{
lock (listLock)
{
if (keyIndex[keyId] == null)
{
//enque
keyQueue.Enqueue(keyId);
keyIndex[keyId] = new KeyBitmapHolder();
waiter.Release();
}
//update
keyIndex[keyId].bitmapData = data;
}
}
public bool Dequeue(out Tuple<int, byte[]> info, CancellationToken token)
{
byte[] outdata;
int keyId;
try { waiter.Wait(token); }
catch (OperationCanceledException) { }
lock (listLock)
{
if (keyQueue.Count < 1)
{
info = null;
return false;
}
keyId = keyQueue.Dequeue();
outdata = keyIndex[keyId].bitmapData;
keyIndex[keyId] = null;
}
info = new Tuple<int, byte[]>(keyId, outdata);
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading;
namespace StreamDeckSharp
{
internal sealed class KeyRepaintQueue
{
private class KeyBitmapHolder
{
public byte[] bitmapData;
}
private readonly Queue<int> keyQueue = new Queue<int>();
private readonly KeyBitmapHolder[] keyIndex = new KeyBitmapHolder[StreamDeckHID.numOfKeys];
private readonly object listLock = new object();
private readonly SemaphoreSlim waiter = new SemaphoreSlim(0);
public void Enqueue(int keyId, byte[] data)
{
lock (listLock)
{
if (keyIndex[keyId] == null)
{
//enque
keyQueue.Enqueue(keyId);
keyIndex[keyId] = new KeyBitmapHolder();
waiter.Release();
}
//update
keyIndex[keyId].bitmapData = data;
}
}
public bool Dequeue(out Tuple<int, byte[]> info, CancellationToken token)
{
byte[] outdata;
int keyId;
try { waiter.Wait(token); }
catch (OperationCanceledException) { }
lock (listLock)
{
if (keyQueue.Count < 1)
{
info = null;
return false;
}
keyId = keyQueue.Dequeue();
outdata = keyIndex[keyId].bitmapData;
keyIndex[keyId] = null;
}
info = new Tuple<int, byte[]>(keyId, outdata);
return true;
}
public KeyRepaintQueue()
{
}
}
}
| mit | C# |
0f8368184e37cabe1a9e9412d2a735c23d7312f4 | Bump version | lars-erik/Our.Umbraco.Fluent.ContentTypes | Our.Umbraco.Fluent.ContentTypes/Properties/AssemblyInfo.cs | Our.Umbraco.Fluent.ContentTypes/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("Our.Umbraco.Fluent.ContentTypes")]
[assembly: AssemblyDescription("Fluent configuration of Umbraco metadata")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Our.Umbraco.Fluent.ContentTypes")]
[assembly: AssemblyCopyright("Copyright © 2017 Lars-Erik Aabech")]
[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("ecef6538-5e34-4d3a-88b2-0ec3173240cb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.*")]
[assembly: AssemblyInformationalVersion("0.1.0-alpha4")]
| 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("Our.Umbraco.Fluent.ContentTypes")]
[assembly: AssemblyDescription("Fluent configuration of Umbraco metadata")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Our.Umbraco.Fluent.ContentTypes")]
[assembly: AssemblyCopyright("Copyright © 2017 Lars-Erik Aabech")]
[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("ecef6538-5e34-4d3a-88b2-0ec3173240cb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.*")]
[assembly: AssemblyInformationalVersion("0.1.0-alpha3")]
| mit | C# |
2602dcbe6836d8874e81f4efd2893304dc0bf888 | Update StartupInterface.cs | WojcikMike/docs.particular.net | Snippets/Snippets_6/UpgradeGuides/5to6/StartupInterface.cs | Snippets/Snippets_6/UpgradeGuides/5to6/StartupInterface.cs | namespace Snippets6.Handlers
{
using System.Threading.Tasks;
using NServiceBus;
#region 5to6-IWantToRunWhenBusStartsAndStops
public class Bootstrapper : IWantToRunWhenBusStartsAndStops
{
public Task Start(IBusSession session)
{
// Do your startup action here.
// Either mark your Start method as async or do the following
return Task.FromResult(0);
}
public Task Stop(IBusSession session)
{
// Do your cleanup action here.
// Either mark your Stop method as async or do the following
return Task.FromResult(0);
}
}
#endregion
}
| namespace Snippets6.Handlers
{
using System.Threading.Tasks;
using NServiceBus;
#region 5to6-IWantToRunWhenBusStartsAndStops
public class Bootstrapper : IWantToRunWhenBusStartsAndStops
{
public Task Start(IBusSession session)
{
// Do your startup action here.
// Either mark your Start method as async or do the following
return Task.FromResult(0);
}
public Task Stop(IBusSession session)
{
// Do your cleanup action here.
// Either mark your Stop method as async or do the following
return Task.FromResult(0);
}
}
#endregion
}
| apache-2.0 | C# |
08fc056a318c50a23baaa8379aaa1db6d2a6e0b6 | make code optional on service error api event | devdigital/AutoResponse | Source/AutoResponse.Core/ApiEvents/ServiceErrorApiEvent.cs | Source/AutoResponse.Core/ApiEvents/ServiceErrorApiEvent.cs | namespace AutoResponse.Core.ApiEvents
{
using System;
public class ServiceErrorApiEvent : IAutoResponseApiEvent
{
public ServiceErrorApiEvent(string code, string message)
{
if (string.IsNullOrWhiteSpace(nameof(message)))
{
throw new ArgumentNullException(nameof(message));
}
this.Code = code;
this.Message = message;
}
public ServiceErrorApiEvent(string code, Exception exception)
{
if (exception == null)
{
throw new ArgumentNullException(nameof(exception));
}
this.Code = code;
this.Exception = exception;
}
public ServiceErrorApiEvent(string message) : this("AR500", message)
{
}
public ServiceErrorApiEvent(Exception exception) : this("AR500", exception)
{
}
public string Code { get; }
public string Message { get; }
public Exception Exception { get; }
}
} | namespace AutoResponse.Core.ApiEvents
{
using System;
public class ServiceErrorApiEvent : IAutoResponseApiEvent
{
public ServiceErrorApiEvent(string code, string message)
{
if (string.IsNullOrWhiteSpace(nameof(message)))
{
throw new ArgumentNullException(nameof(message));
}
this.Code = code;
this.Message = message;
}
public ServiceErrorApiEvent(string code, Exception exception)
{
if (string.IsNullOrWhiteSpace(code))
{
throw new ArgumentNullException(nameof(code));
}
if (exception == null)
{
throw new ArgumentNullException(nameof(exception));
}
this.Code = code;
this.Exception = exception;
}
public ServiceErrorApiEvent(string message) : this("AR500", message)
{
}
public ServiceErrorApiEvent(Exception exception) : this("AR500", exception)
{
}
public string Code { get; }
public string Message { get; }
public Exception Exception { get; }
}
} | mit | C# |
7e127cec131d418f54827ea5cd666131abb5503a | Support encrypted RSA 4096 keys (#1236) | bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core | src/Core/Models/Api/CipherFieldModel.cs | src/Core/Models/Api/CipherFieldModel.cs | using System.ComponentModel.DataAnnotations;
using Bit.Core.Enums;
using Bit.Core.Models.Data;
using Bit.Core.Utilities;
namespace Bit.Core.Models.Api
{
public class CipherFieldModel
{
public CipherFieldModel() { }
public CipherFieldModel(CipherFieldData data)
{
Type = data.Type;
Name = data.Name;
Value = data.Value;
}
public FieldType Type { get; set; }
[EncryptedStringLength(1000)]
public string Name { get; set; }
[EncryptedStringLength(5000)]
public string Value { get; set; }
}
}
| using System.ComponentModel.DataAnnotations;
using Bit.Core.Enums;
using Bit.Core.Models.Data;
using Bit.Core.Utilities;
namespace Bit.Core.Models.Api
{
public class CipherFieldModel
{
public CipherFieldModel() { }
public CipherFieldModel(CipherFieldData data)
{
Type = data.Type;
Name = data.Name;
Value = data.Value;
}
public FieldType Type { get; set; }
[EncryptedStringLength(1000)]
public string Name { get; set; }
[EncryptedStringLength(1000)]
public string Value { get; set; }
}
}
| agpl-3.0 | C# |
8b0ed3d2bda88c6ce0f3c7b7e6e560861b1f4ea7 | optimize codacy | minhhungit/DatabaseMigrateExt | Src/DatabaseMigrateExt/Attributes/ExtMigrationAttribute.cs | Src/DatabaseMigrateExt/Attributes/ExtMigrationAttribute.cs | using FluentMigrator;
namespace DatabaseMigrateExt.Attributes
{
public class ExtMigrationAttribute : MigrationAttribute
{
public ExtMigrationAttribute(DatabaseScriptType scriptType, int year, int month, int day, int hour, int minute, int second)
: base(CalculateValue(scriptType, year, month, day, hour, minute, second))
{
ScriptType = scriptType;
}
public ExtMigrationAttribute(DatabaseScriptType scriptType, int year, int month, int day, int hour, int minute, int second, bool useTransaction)
: base(CalculateValue(scriptType, year, month, day, hour, minute, second))
{
ScriptType = scriptType;
UseTransaction = useTransaction;
}
public ExtMigrationAttribute(DatabaseScriptType scriptType, int year, int month, int day, int hour, int minute, int second, string author)
: base(CalculateValue(scriptType, year, month, day, hour, minute, second))
{
ScriptType = scriptType;
Author = author;
}
public ExtMigrationAttribute(DatabaseScriptType scriptType, int year, int month, int day, int hour, int minute, int second, string author, bool useTransaction)
: base(CalculateValue(scriptType, year, month, day, hour, minute, second))
{
ScriptType = scriptType;
UseTransaction = useTransaction;
Author = author;
}
public string Author { get; set; }
public DatabaseScriptType ScriptType { get; set; }
public bool UseTransaction { get; set; } = true;
private static long CalculateValue(DatabaseScriptType scriptType, int year, int month, int day, int hour, int minute, int second)
{
var branchNumber = (int)scriptType;
return (branchNumber * 100000000000000L) +
(year * 10000000000L) +
(month * 100000000L) +
(day * 1000000L) +
(hour * 10000L) +
(minute * 100L) +
second;
}
}
}
| using FluentMigrator;
namespace DatabaseMigrateExt.Attributes
{
public class ExtMigrationAttribute : MigrationAttribute
{
public ExtMigrationAttribute(DatabaseScriptType scriptType, int year, int month, int day, int hour, int minute, int second, bool useTransaction = true)
: base(CalculateValue(scriptType, year, month, day, hour, minute, second))
{
ScriptType = scriptType;
UseTransaction = useTransaction;
}
public ExtMigrationAttribute(DatabaseScriptType scriptType, int year, int month, int day, int hour, int minute, int second, string author, bool useTransaction = true)
: base(CalculateValue(scriptType, year, month, day, hour, minute, second))
{
ScriptType = scriptType;
UseTransaction = useTransaction;
Author = author;
}
public string Author { get; set; }
public DatabaseScriptType ScriptType { get; set; }
public bool UseTransaction { get; set; }
private static long CalculateValue(DatabaseScriptType scriptType, int year, int month, int day, int hour, int minute, int second)
{
var branchNumber = (int)scriptType;
return (branchNumber * 100000000000000L) +
(year * 10000000000L) +
(month * 100000000L) +
(day * 1000000L) +
(hour * 10000L) +
(minute * 100L) +
second;
}
}
}
| mit | C# |
28f5d9c4d62eefb8f0302dcf40055710816c5f9c | fix to loading of SqlMembershipProvider | martijnboland/RavenDBMembership,martijnboland/RavenDBMembership | src/RavenDBMembership.IntegrationTests/ProviderFixtures/FixtureForSqlMembershipProvider.cs | src/RavenDBMembership.IntegrationTests/ProviderFixtures/FixtureForSqlMembershipProvider.cs | using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Configuration;
using System.Web.Security;
using NUnit.Framework;
namespace RavenDBMembership.IntegrationTests.ProviderFixtures
{
public class FixtureForSqlMembershipProvider : MembershipProviderFixture
{
public const string DatabaseName = "RavenDBMembershipTestSqlDatabase";
public override MembershipProvider GetProvider()
{
string tempPath = Properties.Settings.Default.AccessibleTempPath;
string databaseMdfPath = Path.Combine(tempPath, @"RavenDBMembershipTestSqlDatabase\DatabaseFile.mdf");
if (!Directory.Exists(tempPath))
Directory.CreateDirectory(tempPath);
DatabaseInitialization.DetachDatabase(DatabaseName);
DatabaseInitialization.RecreateDatabase(DatabaseName, databaseMdfPath);
var result = new SqlMembershipProvider();
// Try to load the configuration values in the config file for this
// membership provider
NameValueCollection nameValueCollection = null;
MembershipSection membership = ConfigurationManager.GetSection("system.web/membership") as MembershipSection;
foreach (ProviderSettings settings in membership.Providers)
{
if (settings.Name == "RavenDBMembership")
{
nameValueCollection = new NameValueCollection(settings.Parameters);
break;
}
}
if (nameValueCollection == null)
{
throw new Exception("Configuration not found for membership provider RavenDBMembership.");
}
nameValueCollection["connectionStringName"] = "StubConnectionString";
result.Initialize(null, nameValueCollection);
var connectionStringProperty = typeof (SqlMembershipProvider).GetField("_sqlConnectionString",
BindingFlags.NonPublic |
BindingFlags.Instance);
Assert.That(connectionStringProperty, Is.Not.Null);
connectionStringProperty.SetValue(result, DatabaseInitialization.GetConnectionStringFor(DatabaseName));
return result;
}
}
} | using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Security;
using NUnit.Framework;
namespace RavenDBMembership.IntegrationTests.ProviderFixtures
{
public class FixtureForSqlMembershipProvider : MembershipProviderFixture
{
public const string DatabaseName = "RavenDBMembershipTestSqlDatabase";
public override MembershipProvider GetProvider()
{
string tempPath = Properties.Settings.Default.AccessibleTempPath;
string databaseMdfPath = Path.Combine(tempPath, @"RavenDBMembershipTestSqlDatabase\DatabaseFile.mdf");
if (!Directory.Exists(tempPath))
Directory.CreateDirectory(tempPath);
DatabaseInitialization.DetachDatabase(DatabaseName);
DatabaseInitialization.RecreateDatabase(DatabaseName, databaseMdfPath);
var result = new SqlMembershipProvider();
// Try to load the configuration values in the config file for this
// membership provider
NameValueCollection nameValueCollection = new NameValueCollection(
Membership.Providers.AsQueryable().OfType<ProviderSettings>().Where(p => p.Name == "RavenDBMembership").
Single().Parameters);
nameValueCollection["connectionStringName"] = "StubConnectionString";
result.Initialize(null, nameValueCollection);
var connectionStringProperty = typeof (SqlMembershipProvider).GetField("_sqlConnectionString",
BindingFlags.NonPublic |
BindingFlags.Instance);
Assert.That(connectionStringProperty, Is.Not.Null);
connectionStringProperty.SetValue(result, DatabaseInitialization.GetConnectionStringFor(DatabaseName));
return result;
}
}
} | mit | C# |
ed8827a6f2636df01143cdf9b399d97ebbc8cf6c | Remove some CAS cruft (dotnet/coreclr#22576) | shimingsg/corefx,shimingsg/corefx,BrennanConroy/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,ericstj/corefx,ViktorHofer/corefx,ptoonen/corefx,wtgodbe/corefx,wtgodbe/corefx,ericstj/corefx,wtgodbe/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ericstj/corefx,ptoonen/corefx,ericstj/corefx,ViktorHofer/corefx,wtgodbe/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,wtgodbe/corefx,ptoonen/corefx,ptoonen/corefx,ericstj/corefx,ptoonen/corefx,wtgodbe/corefx,ptoonen/corefx,ViktorHofer/corefx,ptoonen/corefx,ViktorHofer/corefx,BrennanConroy/corefx,BrennanConroy/corefx,shimingsg/corefx,ViktorHofer/corefx,shimingsg/corefx | src/Common/src/CoreLib/System/Security/SuppressUnmanagedCodeSecurityAttribute.cs | src/Common/src/CoreLib/System/Security/SuppressUnmanagedCodeSecurityAttribute.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.
namespace System.Security
{
// SuppressUnmanagedCodeSecurityAttribute:
// This attribute has no functional impact in CoreCLR.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false)]
public sealed class SuppressUnmanagedCodeSecurityAttribute : Attribute
{
public SuppressUnmanagedCodeSecurityAttribute() { }
}
}
| // 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.
namespace System.Security
{
// SuppressUnmanagedCodeSecurityAttribute:
// Indicates that the target P/Invoke method(s) should skip the per-call
// security checked for unmanaged code permission.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false)]
public sealed class SuppressUnmanagedCodeSecurityAttribute : Attribute
{
public SuppressUnmanagedCodeSecurityAttribute() { }
}
}
| mit | C# |
7ccd04fd03349e01dae9a79385e3903e29ec9ab9 | Change the Script Task use Monaco Editor (#10715) | stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2 | src/OrchardCore.Modules/OrchardCore.Workflows/Views/Items/ScriptTask.Fields.Edit.cshtml | src/OrchardCore.Modules/OrchardCore.Workflows/Views/Items/ScriptTask.Fields.Edit.cshtml | @using OrchardCore.Workflows.ViewModels;
@model ScriptTaskViewModel
<div class="form-group" asp-validation-class-for="AvailableOutcomes">
<label asp-for="AvailableOutcomes">@T["Available Outcomes"]</label>
<input asp-for="AvailableOutcomes" class="form-control" />
<span asp-validation-for="AvailableOutcomes"></span>
<span class="hint">@T["A comma-separated list of available outcomes."]</span>
</div>
<div class="form-group" asp-validation-class-for="Script">
<label asp-for="Script">@T["Script"]</label>
<div id="@Html.IdFor(x => x.Script)_editor" asp-for="Text" style="min-height: 400px;" class="form-control"></div>
<textarea asp-for="Script" hidden>@Html.Raw(Model.Script)</textarea>
<span asp-validation-for="Script"></span>
<span class="hint">@T["The script to execute. Make sure to call `setOutcome` with any of the specified available outcomes at least once."]</span>
</div>
<script asp-name="monaco" depends-on="admin" at="Foot"></script>
<script at="Foot" depends-on="monaco">
$(document).ready(function () {
require(['vs/editor/editor.main'], function () {
var settings= {
"automaticLayout": true,
"language": "javascript"
};
var html = document.getElementsByTagName("html")[0];
const mutationObserver = new MutationObserver(setTheme);
mutationObserver.observe(html, { attributes: true });
function setTheme() {
var theme = html.dataset.theme;
if (theme === "darkmode") {
monaco.editor.setTheme('vs-dark')
} else {
monaco.editor.setTheme('vs')
}
}
setTheme();
var editor = monaco.editor.create(document.getElementById('@Html.IdFor(x => x.Script)_editor'), settings);
var textArea = document.getElementById('@Html.IdFor(x => x.Script)');
editor.getModel().setValue(textArea.value);
window.addEventListener("submit", function () {
textArea.value = editor.getValue();
});
});
});
</script>
| @using OrchardCore.Workflows.ViewModels;
@model ScriptTaskViewModel
<div class="form-group" asp-validation-class-for="AvailableOutcomes">
<label asp-for="AvailableOutcomes">@T["Available Outcomes"]</label>
<input asp-for="AvailableOutcomes" class="form-control" />
<span asp-validation-for="AvailableOutcomes"></span>
<span class="hint">@T["A comma-separated list of available outcomes."]</span>
</div>
<div class="form-group" asp-validation-class-for="Script">
<label asp-for="Script">@T["Script"]</label>
<textarea asp-for="Script" class="form-control" placeholder="e.g. js: setOutcome('Done');"></textarea>
<span asp-validation-for="Script"></span>
<span class="hint">@T["The script to execute. Make sure to call `setOutcome` with any of the specified available outcomes at least once."]</span>
</div>
<style asp-name="codemirror"></style>
<script asp-name="codemirror" depends-on="admin" at="Foot"></script>
<script asp-name="codemirror-mode-javascript" at="Foot"></script>
<script asp-name="codemirror-addon-display-autorefresh" at="Foot"></script>
<script asp-name="codemirror-addon-mode-simple" at="Foot"></script>
<script asp-name="codemirror-addon-mode-multiplex" at="Foot"></script>
<script asp-name="codemirror-mode-xml" at="Foot"></script>
<script at="Foot">
$(function () {
var editor = CodeMirror.fromTextArea(document.getElementById('@Html.IdFor(x => x.Script)'), {
autoRefresh: true,
lineNumbers: true,
styleActiveLine: true,
matchBrackets: true,
mode: { name: "javascript" },
});
editor.on('change', function(cmEditor){
cmEditor.save();
});
});
</script>
| bsd-3-clause | C# |
c8853406afb9e79d5cf14919db0f2ca25557c0cd | Add missing namespace to resolve asset retargeting failures | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit.SDK/Features/Input/Handlers/TouchHandler.cs | Assets/MixedRealityToolkit.SDK/Features/Input/Handlers/TouchHandler.cs | using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
public class TouchHandler : MonoBehaviour, IMixedRealityTouchHandler
{
#region Event handlers
public TouchEvent OnTouchStarted = new TouchEvent();
public TouchEvent OnTouchCompleted = new TouchEvent();
public TouchEvent OnTouchUpdated = new TouchEvent();
#endregion
void IMixedRealityTouchHandler.OnTouchCompleted(HandTrackingInputEventData eventData)
{
OnTouchCompleted.Invoke(eventData);
}
void IMixedRealityTouchHandler.OnTouchStarted(HandTrackingInputEventData eventData)
{
OnTouchStarted.Invoke(eventData);
}
void IMixedRealityTouchHandler.OnTouchUpdated(HandTrackingInputEventData eventData)
{
OnTouchUpdated.Invoke(eventData);
}
}
}
| using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchHandler : MonoBehaviour, IMixedRealityTouchHandler
{
#region Event handlers
public TouchEvent OnTouchStarted = new TouchEvent();
public TouchEvent OnTouchCompleted = new TouchEvent();
public TouchEvent OnTouchUpdated = new TouchEvent();
#endregion
void IMixedRealityTouchHandler.OnTouchCompleted(HandTrackingInputEventData eventData)
{
OnTouchCompleted.Invoke(eventData);
}
void IMixedRealityTouchHandler.OnTouchStarted(HandTrackingInputEventData eventData)
{
OnTouchStarted.Invoke(eventData);
}
void IMixedRealityTouchHandler.OnTouchUpdated(HandTrackingInputEventData eventData)
{
OnTouchUpdated.Invoke(eventData);
}
}
| mit | C# |
cfac6aa02094819b1baad40c3c784e1d30211254 | fix dll reference | sebastus/AzureFunctionForSplunk | shared/obRelay.csx | shared/obRelay.csx | #r "bin\Microsoft.Azure.Relay.dll"
#load "newEvent.csx"
#load "getEnvironmentVariable.csx"
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Relay;
public static async Task obRelay(string[] standardizedEvents, TraceWriter log)
{
string newClientContent = "[";
foreach (string item in standardizedEvents)
{
if (newClientContent.Length != 1) newClientContent += ",";
newClientContent += item;
}
newClientContent += "]";
bool Done = false;
while (!Done)
{
try
{
Done = HybridAsync(newClientContent, log).GetAwaiter().GetResult();
}
catch (EndpointNotFoundException)
{
log.Info("Waiting...");
Thread.Sleep(1000);
}
catch (RelayException)
{
log.Info("Connection forcibly closed.");
}
catch (Exception ex)
{
log.Error("Error executing function: " + ex.Message);
}
}
}
static async Task<bool> HybridAsync(string newClientContent, TraceWriter log)
{
string RelayNamespace = getEnvironmentVariable("relayNamespace") + ".servicebus.windows.net";
string ConnectionName = getEnvironmentVariable("relayPath");
string KeyName = getEnvironmentVariable("policyName");
string Key = getEnvironmentVariable("policyKey");
if (RelayNamespace.Length == 0 || ConnectionName.Length == 0 || KeyName.Length == 0 || Key.Length == 0) {
log.Error("Values must be specified for RelayNamespace, relayPath, KeyName and Key.");
return true;
}
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
// Initiate the connection
var relayConnection = await client.CreateConnectionAsync();
log.Verbose("Connection accepted.");
int bufferSize = newClientContent.Length;
log.Info($"newClientContent byte count: {bufferSize}");
var writes = Task.Run(async () => {
var writer = new StreamWriter(relayConnection, Encoding.UTF8, bufferSize) { AutoFlush = true };
await writer.WriteAsync(newClientContent);
});
// Wait for both tasks to complete
await Task.WhenAll(writes);
await relayConnection.CloseAsync(CancellationToken.None);
log.Verbose("Connection closed.");
return true;
}
| #r "Microsoft.Azure.Relay"
#load "newEvent.csx"
#load "getEnvironmentVariable.csx"
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Relay;
public static async Task obRelay(string[] standardizedEvents, TraceWriter log)
{
string newClientContent = "[";
foreach (string item in standardizedEvents)
{
if (newClientContent.Length != 1) newClientContent += ",";
newClientContent += item;
}
newClientContent += "]";
bool Done = false;
while (!Done)
{
try
{
Done = HybridAsync(newClientContent, log).GetAwaiter().GetResult();
}
catch (EndpointNotFoundException)
{
log.Info("Waiting...");
Thread.Sleep(1000);
}
catch (RelayException)
{
log.Info("Connection forcibly closed.");
}
catch (Exception ex)
{
log.Error("Error executing function: " + ex.Message);
}
}
}
static async Task<bool> HybridAsync(string newClientContent, TraceWriter log)
{
string RelayNamespace = getEnvironmentVariable("relayNamespace") + ".servicebus.windows.net";
string ConnectionName = getEnvironmentVariable("relayPath");
string KeyName = getEnvironmentVariable("policyName");
string Key = getEnvironmentVariable("policyKey");
if (RelayNamespace.Length == 0 || ConnectionName.Length == 0 || KeyName.Length == 0 || Key.Length == 0) {
log.Error("Values must be specified for RelayNamespace, relayPath, KeyName and Key.");
return true;
}
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
// Initiate the connection
var relayConnection = await client.CreateConnectionAsync();
log.Verbose("Connection accepted.");
int bufferSize = newClientContent.Length;
log.Info($"newClientContent byte count: {bufferSize}");
var writes = Task.Run(async () => {
var writer = new StreamWriter(relayConnection, Encoding.UTF8, bufferSize) { AutoFlush = true };
await writer.WriteAsync(newClientContent);
});
// Wait for both tasks to complete
await Task.WhenAll(writes);
await relayConnection.CloseAsync(CancellationToken.None);
log.Verbose("Connection closed.");
return true;
}
| mit | C# |
a152ce1e7431adcf0cd766de26c3644f6b2be467 | Update AttachEditorBehavior.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Behaviors/AttachEditorBehavior.cs | src/Core2D/Behaviors/AttachEditorBehavior.cs | #nullable enable
using Avalonia.Controls;
using Avalonia.Xaml.Interactivity;
namespace Core2D.Behaviors;
public class AttachEditorBehavior : Behavior<Control>
{
private AttachEditor? _input;
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject is { })
{
_input = new AttachEditor(AssociatedObject);
}
}
protected override void OnDetaching()
{
base.OnDetaching();
if (AssociatedObject is { })
{
_input?.Detach();
}
}
}
| #nullable enable
using Avalonia.Controls;
using Avalonia.Xaml.Interactivity;
namespace Core2D.Behaviors;
public class AttachEditorBehavior : Behavior<Control>
{
private AttachEditor _input;
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject is { })
{
_input = new AttachEditor(AssociatedObject);
}
}
protected override void OnDetaching()
{
base.OnDetaching();
if (AssociatedObject is { })
{
_input?.Detach();
}
}
} | mit | C# |
9703304537027e9feed29e6515be098c57c660b5 | Implement ESDATModel test for OSM2.Actions | kgarsuta/Hatfield.EnviroData.DataAcquisition,gvassas/Hatfield.EnviroData.DataAcquisition,HatfieldConsultants/Hatfield.EnviroData.DataAcquisition | Test/Hatfield.EnviroData.DataAcquisition.ESDAT.Test/Converters/ESDATDataConverterTest.cs | Test/Hatfield.EnviroData.DataAcquisition.ESDAT.Test/Converters/ESDATDataConverterTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Moq;
using Hatfield.EnviroData.Core;
using Hatfield.EnviroData.DataAcquisition.ESDAT;
using Hatfield.EnviroData.DataAcquisition.ESDAT.Converters;
namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Test.Converters
{
[TestFixture]
public class ESDATConverterTest
{
// See https://github.com/HatfieldConsultants/Hatfield.EnviroData.Core/wiki/Loading-ESDAT-data-into-ODM2#actions for expected values
[Test]
public void ESDATConverterConvertToODMActionActionTest()
{
var mockDbContext = new Mock<IDbContext>().Object;
var esdatConverter = new ESDATConverter(mockDbContext);
ESDATModel esdatModel = new ESDATModel();
DateTime sampledDateTime = DateTime.Now;
esdatModel.SampleFileData.SampledDateTime = sampledDateTime;
var action = esdatConverter.ConvertToODMAction(esdatModel);
Assert.AreEqual(action.ActionID, 0);
Assert.AreEqual(action.ActionTypeCV, "specimenCollection");
Assert.AreEqual(action.BeginDateTime, sampledDateTime);
Assert.AreEqual(action.EndDateTime, null);
Assert.AreEqual(action.EndDateTimeUTCOffset, null);
Assert.AreEqual(action.ActionDescription, null);
Assert.AreEqual(action.ActionFileLink, null);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Test.Converters
{
class ESDATDataConverterTest
{
}
}
| mpl-2.0 | C# |
017c781279bbbe08cf790f0607d89ba5abaf8ed3 | Comment test | vbatrla/PowerManager | tests/VB.PowerManager.Tests/View/MenuItemsNotifierTests.cs | tests/VB.PowerManager.Tests/View/MenuItemsNotifierTests.cs | namespace VB.PowerManager.Tests.View
{
using System.ComponentModel;
using NSubstitute;
using NUnit.Framework;
using VB.PowerManager.View;
using VB.PowerManager.View.Interfaces;
[TestFixture]
public class MenuItemsNotifierTests
{
public MenuItemsNotifier Notifier = new MenuItemsNotifier();
[Test]
public void Attach_IsSubscribed()
{
var menuItem = Substitute.For<IMenuItem>();
Notifier.Attach(menuItem);
Assert.That(Notifier.MenuItems, Has.Member(menuItem));
}
[Test]
public void Detach_Unsubscribed()
{
var menuItem = Substitute.For<IMenuItem>();
Notifier.Attach(menuItem);
Notifier.Detach(menuItem);
Assert.That(Notifier.MenuItems, Has.No.Member(menuItem));
}
[Test]
[NUnit.Framework.Category("Integration")]
public void Notify_JustNotifyOthers_Notified()
{
var notifier = new MenuItemsNotifier();
var firstItem = new MenuItemProxy("A", (() => { }));
var secondItem = new MenuItemProxy("B", (() => { }));
// Prop which must be changed to false
secondItem.Checked = true;
notifier.Attach(firstItem);
notifier.Attach(secondItem);
// Notify others
firstItem.PerformClick();
Assert.IsFalse(secondItem.Checked);
}
[SetUp]
public void SetupEach()
{
}
}
}
| namespace VB.PowerManager.Tests.View
{
using System.ComponentModel;
using NSubstitute;
using NUnit.Framework;
using VB.PowerManager.View;
using VB.PowerManager.View.Interfaces;
[TestFixture]
public class MenuItemsNotifierTests
{
public MenuItemsNotifier Notifier = new MenuItemsNotifier();
[Test]
public void Attach_IsSubscribed()
{
var menuItem = Substitute.For<IMenuItem>();
Notifier.Attach(menuItem);
Assert.That(Notifier.MenuItems, Has.Member(menuItem));
}
[Test]
public void Detach_Unsubscribed()
{
var menuItem = Substitute.For<IMenuItem>();
Notifier.Attach(menuItem);
Notifier.Detach(menuItem);
Assert.That(Notifier.MenuItems, Has.No.Member(menuItem));
}
[Test]
[NUnit.Framework.Category("Integration")]
public void Notify_JustNotifyOthers_Notified()
{
var notifier = new MenuItemsNotifier();
var firstItem = new MenuItemProxy("A", (() => { }));
var secondItem = new MenuItemProxy("B", (() => { }));
secondItem.Checked = true;
notifier.Attach(firstItem);
notifier.Attach(secondItem);
// Notify others
firstItem.PerformClick();
Assert.IsFalse(secondItem.Checked);
}
[SetUp]
public void SetupEach()
{
}
}
} | mit | C# |
826a2274d6b8eac1e3c795d9a12b2f9dfdad6490 | Use HTTPS link | ritterim/silverpop-dotnet-api | samples/Silverpop.Client.WebTester/Views/Shared/_Layout.cshtml | samples/Silverpop.Client.WebTester/Views/Shared/_Layout.cshtml | @{
var applicationName = "Silverpop Transact Tester";
}
<!DOCTYPE html>
<html>
<head>
<title>@applicationName</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/Assets/site.css" />
</head>
<body>
<div class="container">
<div class="header">
<h1 class="text-muted">@applicationName</h1>
<p>Enabling easy testing of Silverpop Transact messages since 2015.</p>
</div>
<hr />
<div class="row">
<div class="col-lg-12">
@RenderBody()
</div>
</div>
</div>
<footer>
<div class="container">
<p class="text-muted">
Built with <span class="heart">♥</span>
by <a href="https://www.ritterim.com">Ritter Insurance Marketing</a>
</p>
</div>
</footer>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
@RenderSection("scripts", false)
</body>
</html>
| @{
var applicationName = "Silverpop Transact Tester";
}
<!DOCTYPE html>
<html>
<head>
<title>@applicationName</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/Assets/site.css" />
</head>
<body>
<div class="container">
<div class="header">
<h1 class="text-muted">@applicationName</h1>
<p>Enabling easy testing of Silverpop Transact messages since 2015.</p>
</div>
<hr />
<div class="row">
<div class="col-lg-12">
@RenderBody()
</div>
</div>
</div>
<footer>
<div class="container">
<p class="text-muted">
Built with <span class="heart">♥</span>
by <a href="http://www.ritterim.com">Ritter Insurance Marketing</a>
</p>
</div>
</footer>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
@RenderSection("scripts", false)
</body>
</html>
| mit | C# |
06ba22da6cdfce57572562c51f3ba1236ea67954 | Update XML documentation for TreeWalkerExtensions.PostOrderTraversal | jasonmcboyd/Treenumerable | Source/Treenumerable/TreeWalkerExtensions/TreeWalkerExtensions.PostOrderTraversal.cs | Source/Treenumerable/TreeWalkerExtensions/TreeWalkerExtensions.PostOrderTraversal.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Treenumerable
{
public static partial class TreeWalkerExtensions
{
/// <summary>
/// Enumerates a tree using the postorder traversal method.
/// </summary>
/// <typeparam name="T">The type of elements in the tree.</typeparam>
/// <param name="walker">
/// The <see cref="ITreeWalker<T>"/> that knows how to find the parent and child nodes.
/// </param>
/// <param name="node">The root node of the tree that is to be traversed.</param>
/// <param name="includeNode">
/// Indicates whether or not the <paramref name="node"/> is to be included in the resulting
/// <see cref="System.Collections.Generic.IEnumerable<T>"/>.
/// </param>
/// <returns>
/// An <see cref="System.Collections.Generic.IEnumerable<T>"/> that contains all the nodes
/// in the tree ordered based on a postorder traversal.
/// </returns>
public static IEnumerable<T> PostOrderTraversal<T>(this ITreeWalker<T> walker, T node, bool includeNode)
{
// Validate parameters.
if (walker == null)
{
throw new ArgumentNullException("walker");
}
if (node == null)
{
throw new ArgumentNullException("node");
}
// Loop over each child, calling PostOrderTraversal, and yield the results.
foreach (T descendant in walker.GetChildren(node).SelectMany(x => walker.PostOrderTraversal(x, true)))
{
yield return descendant;
}
// If 'includeNode' is true then yield 'node'.
if (includeNode)
{
yield return node;
}
}
/// <summary>
/// Enumerates a tree using the postorder traversal method.
/// </summary>
/// <typeparam name="T">The type of elements in the tree.</typeparam>
/// <param name="walker">
/// The <see cref="ITreeWalker<T>"/> that knows how to find the parent and child nodes.
/// </param>
/// <param name="node">The root node of the tree that is to be traversed.</param>
/// <returns>
/// An <see cref="System.Collections.Generic.IEnumerable<T>"/> that contains all the nodes
/// in the tree ordered based on a postorder traversal.
/// </returns>
public static IEnumerable<T> PostOrderTraversal<T>(this ITreeWalker<T> walker, T node)
{
return walker.PostOrderTraversal(node, false);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Treenumerable
{
public static partial class TreeWalkerExtensions
{
/// <summary>
///
/// </summary>
/// <typeparam name="T">The type of elements in the tree.</typeparam>
/// <param name="walker">
/// The <see cref="ITreeWalker<T>"/> that knows how to find the parent and child nodes.
/// </param>
/// <param name="node"></param>
/// <param name="includeNode"></param>
/// <returns></returns>
public static IEnumerable<T> PostOrderTraversal<T>(this ITreeWalker<T> walker, T node, bool includeNode)
{
// Validate parameters.
if (walker == null)
{
throw new ArgumentNullException("walker");
}
if (node == null)
{
throw new ArgumentNullException("node");
}
// Loop over each child, calling PostOrderTraversal, and yield the results.
foreach (T descendant in walker.GetChildren(node).SelectMany(x => walker.PostOrderTraversal(x, true)))
{
yield return descendant;
}
// If 'includeNode' is true then yield 'node'.
if (includeNode)
{
yield return node;
}
}
public static IEnumerable<T> PostOrderTraversal<T>(this ITreeWalker<T> walker, T node)
{
return walker.PostOrderTraversal(node, false);
}
}
}
| mit | C# |
ec76dfe8e5dbdc966ed1ad33504e267249d0c02f | add method mavenTest | exKAZUu/XMutator | XMutator/Program.cs | XMutator/Program.cs | using System;
using Mono.Options;
using Paraiba.Linq;
namespace XMutator {
internal class Program {
// run maven test
private static string mavenTest(string dirPath) {
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = false;
p.StartInfo.CreateNoWindow = true;
System.IO.Directory.SetCurrentDirectory(dirPath);
var cmd = "/c mvn test";
p.StartInfo.Arguments = cmd;
p.Start();
var res = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
return res;
}
private static void Main(string[] args) {
var csv = false;
var help = false;
var p = new OptionSet {
{ "c|csv", v => csv = v != null },
{ "h|?|help", v => help = v != null },
};
var dirPaths = p.Parse(args);
if (!dirPaths.IsEmpty() && !help) {
foreach (var dirPath in dirPaths) {
var testRes = mavenTest(dirPath);
Console.WriteLine(testRes);
// Measure mutation scores
var generatedMutatns = 10;
var killedMutants = 3;
var percentage = killedMutants * 100 / generatedMutatns;
if (csv) {
Console.WriteLine(killedMutants + "," + generatedMutatns + "," + percentage);
} else {
Console.WriteLine(dirPath + ": " + killedMutants + " / " + generatedMutatns
+ ": " + percentage + "%");
}
}
} else {
p.WriteOptionDescriptions(Console.Out);
}
}
}
} | using System;
using Mono.Options;
using Paraiba.Linq;
namespace XMutator {
internal class Program {
private static void Main(string[] args) {
var csv = false;
var help = false;
var p = new OptionSet {
{ "c|csv", v => csv = v != null },
{ "h|?|help", v => help = v != null },
};
var dirPaths = p.Parse(args);
if (!dirPaths.IsEmpty() && !help) {
foreach (var filePath in dirPaths) {
// Measure mutation scores
var generatedMutatns = 10;
var killedMutants = 3;
var percentage = killedMutants * 100 / generatedMutatns;
if (csv) {
Console.WriteLine(killedMutants + "," + generatedMutatns + "," + percentage);
} else {
Console.WriteLine(filePath + ": " + killedMutants + " / " + generatedMutatns
+ ": " + percentage + "%");
}
}
} else {
p.WriteOptionDescriptions(Console.Out);
}
}
}
} | apache-2.0 | C# |
717b3e1c4b012a9660cd19f147c9e8154147177d | Remove and sort usings | mgoertz-msft/roslyn,weltkante/roslyn,reaction1989/roslyn,tannergooding/roslyn,agocke/roslyn,panopticoncentral/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,CaptainHayashi/roslyn,abock/roslyn,amcasey/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,khyperia/roslyn,VSadov/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,AlekseyTs/roslyn,stephentoub/roslyn,tvand7093/roslyn,AArnott/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,ErikSchierboom/roslyn,xoofx/roslyn,diryboy/roslyn,AlekseyTs/roslyn,orthoxerox/roslyn,swaroop-sridhar/roslyn,mattwar/roslyn,AlekseyTs/roslyn,paulvanbrenk/roslyn,AmadeusW/roslyn,diryboy/roslyn,yeaicc/roslyn,stephentoub/roslyn,tmat/roslyn,MichalStrehovsky/roslyn,lorcanmooney/roslyn,pdelvo/roslyn,akrisiun/roslyn,AnthonyDGreen/roslyn,tmeschter/roslyn,dpoeschl/roslyn,bartdesmet/roslyn,MattWindsor91/roslyn,zooba/roslyn,aelij/roslyn,orthoxerox/roslyn,mavasani/roslyn,jamesqo/roslyn,srivatsn/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,drognanar/roslyn,mmitche/roslyn,eriawan/roslyn,kelltrick/roslyn,Giftednewt/roslyn,amcasey/roslyn,VSadov/roslyn,heejaechang/roslyn,CaptainHayashi/roslyn,bkoelman/roslyn,tvand7093/roslyn,genlu/roslyn,diryboy/roslyn,brettfo/roslyn,robinsedlaczek/roslyn,AArnott/roslyn,CyrusNajmabadi/roslyn,cston/roslyn,gafter/roslyn,mavasani/roslyn,nguerrera/roslyn,yeaicc/roslyn,aelij/roslyn,paulvanbrenk/roslyn,KirillOsenkov/roslyn,xoofx/roslyn,panopticoncentral/roslyn,mattwar/roslyn,bartdesmet/roslyn,bbarry/roslyn,khyperia/roslyn,abock/roslyn,jcouv/roslyn,gafter/roslyn,KirillOsenkov/roslyn,nguerrera/roslyn,robinsedlaczek/roslyn,genlu/roslyn,jasonmalinowski/roslyn,jkotas/roslyn,wvdd007/roslyn,MichalStrehovsky/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,jeffanders/roslyn,jamesqo/roslyn,bartdesmet/roslyn,tvand7093/roslyn,pdelvo/roslyn,reaction1989/roslyn,davkean/roslyn,xasx/roslyn,srivatsn/roslyn,MattWindsor91/roslyn,mattscheffer/roslyn,DustinCampbell/roslyn,physhi/roslyn,OmarTawfik/roslyn,jmarolf/roslyn,aelij/roslyn,tmat/roslyn,jamesqo/roslyn,sharwell/roslyn,MattWindsor91/roslyn,tannergooding/roslyn,Hosch250/roslyn,reaction1989/roslyn,khyperia/roslyn,Hosch250/roslyn,brettfo/roslyn,jmarolf/roslyn,jmarolf/roslyn,CaptainHayashi/roslyn,amcasey/roslyn,physhi/roslyn,jasonmalinowski/roslyn,cston/roslyn,jcouv/roslyn,lorcanmooney/roslyn,swaroop-sridhar/roslyn,bbarry/roslyn,paulvanbrenk/roslyn,weltkante/roslyn,KevinRansom/roslyn,physhi/roslyn,pdelvo/roslyn,xoofx/roslyn,DustinCampbell/roslyn,robinsedlaczek/roslyn,drognanar/roslyn,wvdd007/roslyn,dotnet/roslyn,sharwell/roslyn,yeaicc/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,ErikSchierboom/roslyn,TyOverby/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,abock/roslyn,brettfo/roslyn,tmat/roslyn,Giftednewt/roslyn,mattscheffer/roslyn,dpoeschl/roslyn,KevinRansom/roslyn,stephentoub/roslyn,Giftednewt/roslyn,akrisiun/roslyn,davkean/roslyn,eriawan/roslyn,mavasani/roslyn,cston/roslyn,tannergooding/roslyn,mmitche/roslyn,gafter/roslyn,xasx/roslyn,AArnott/roslyn,dotnet/roslyn,bkoelman/roslyn,wvdd007/roslyn,bkoelman/roslyn,drognanar/roslyn,weltkante/roslyn,zooba/roslyn,mattscheffer/roslyn,davkean/roslyn,orthoxerox/roslyn,agocke/roslyn,dpoeschl/roslyn,OmarTawfik/roslyn,xasx/roslyn,agocke/roslyn,mattwar/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,tmeschter/roslyn,jeffanders/roslyn,jkotas/roslyn,heejaechang/roslyn,jkotas/roslyn,jcouv/roslyn,mgoertz-msft/roslyn,AnthonyDGreen/roslyn,CyrusNajmabadi/roslyn,kelltrick/roslyn,mmitche/roslyn,TyOverby/roslyn,jeffanders/roslyn,a-ctor/roslyn,lorcanmooney/roslyn,nguerrera/roslyn,MattWindsor91/roslyn,TyOverby/roslyn,a-ctor/roslyn,Hosch250/roslyn,bbarry/roslyn,MichalStrehovsky/roslyn,tmeschter/roslyn,shyamnamboodiripad/roslyn,akrisiun/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,kelltrick/roslyn,zooba/roslyn,srivatsn/roslyn,heejaechang/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,OmarTawfik/roslyn,a-ctor/roslyn,AnthonyDGreen/roslyn | src/VisualStudio/Core/Def/Implementation/ProjectSystem/DocumentProvider.TextBufferDataEventsSink.cs | src/VisualStudio/Core/Def/Implementation/ProjectSystem/DocumentProvider.TextBufferDataEventsSink.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal partial class DocumentProvider
{
private class TextBufferDataEventsSink : IVsTextBufferDataEvents
{
private readonly Action _onDocumentLoadCompleted;
private IComEventSink _sink;
/// <summary>
/// Helper method for creating and hooking up a <c>TextBufferDataEventsSink</c>.
/// </summary>
public static void HookupHandler(IVsTextBuffer textBuffer, Action onDocumentLoadCompleted)
{
var eventHandler = new TextBufferDataEventsSink(onDocumentLoadCompleted);
eventHandler._sink = ComEventSink.Advise<IVsTextBufferDataEvents>(textBuffer, eventHandler);
}
private TextBufferDataEventsSink(Action onDocumentLoadCompleted)
{
_onDocumentLoadCompleted = onDocumentLoadCompleted;
}
public void OnFileChanged(uint grfChange, uint dwFileAttrs)
{
}
public int OnLoadCompleted(int fReload)
{
_sink.Unadvise();
_onDocumentLoadCompleted();
return VSConstants.S_OK;
}
}
}
}
| // 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.VisualStudio;
using Microsoft.VisualStudio.TextManager.Interop;
using System;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal partial class DocumentProvider
{
private class TextBufferDataEventsSink : IVsTextBufferDataEvents
{
private readonly Action _onDocumentLoadCompleted;
private IComEventSink _sink;
/// <summary>
/// Helper method for creating and hooking up a <c>TextBufferDataEventsSink</c>.
/// </summary>
public static void HookupHandler(IVsTextBuffer textBuffer, Action onDocumentLoadCompleted)
{
var eventHandler = new TextBufferDataEventsSink(onDocumentLoadCompleted);
eventHandler._sink = ComEventSink.Advise<IVsTextBufferDataEvents>(textBuffer, eventHandler);
}
private TextBufferDataEventsSink(Action onDocumentLoadCompleted)
{
_onDocumentLoadCompleted = onDocumentLoadCompleted;
}
public void OnFileChanged(uint grfChange, uint dwFileAttrs)
{
}
public int OnLoadCompleted(int fReload)
{
_sink.Unadvise();
_onDocumentLoadCompleted();
return VSConstants.S_OK;
}
}
}
}
| mit | C# |
a77df68909defb3bf62223d7bb8187b160cd9642 | Fix repository permission checks. Yes, that was stupid. | Webmine/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,Acute-sales-ltd/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,larshg/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,crowar/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,RedX2501/Bonobo-Git-Server,gencer/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,anyeloamt1/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,Ollienator/Bonobo-Git-Server,willdean/Bonobo-Git-Server,lkho/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,Webmine/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,willdean/Bonobo-Git-Server,Webmine/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,crowar/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,larshg/Bonobo-Git-Server,crowar/Bonobo-Git-Server,gencer/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,braegelno5/Bonobo-Git-Server,anyeloamt1/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,Webmine/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,anyeloamt1/Bonobo-Git-Server,RedX2501/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,forgetz/Bonobo-Git-Server,anyeloamt1/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,gencer/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,crowar/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,willdean/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,crowar/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,Ollienator/Bonobo-Git-Server,larshg/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,lkho/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,lkho/Bonobo-Git-Server,Webmine/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,Ollienator/Bonobo-Git-Server,PGM-NipponSysits/IIS.Git-Connector,igoryok-zp/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,Webmine/Bonobo-Git-Server,larshg/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,Acute-sales-ltd/Bonobo-Git-Server,forgetz/Bonobo-Git-Server,crowar/Bonobo-Git-Server,padremortius/Bonobo-Git-Server,NipponSysits/IIS.Git-Connector,gencer/Bonobo-Git-Server,willdean/Bonobo-Git-Server,willdean/Bonobo-Git-Server,lkho/Bonobo-Git-Server | Bonobo.Git.Server/Security/ADRepositoryPermissionService.cs | Bonobo.Git.Server/Security/ADRepositoryPermissionService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bonobo.Git.Server.Data;
using Bonobo.Git.Server.Models;
using Microsoft.Practices.Unity;
namespace Bonobo.Git.Server.Security
{
public class ADRepositoryPermissionService : IRepositoryPermissionService
{
[Dependency]
public IRepositoryRepository Repository { get; set; }
[Dependency]
public IRoleProvider RoleProvider { get; set; }
[Dependency]
public ITeamRepository TeamRepository { get; set; }
public bool AllowsAnonymous(string repositoryName)
{
return Repository.GetRepository(repositoryName).AnonymousAccess;
}
public bool HasPermission(string username, string repositoryName)
{
bool result = false;
RepositoryModel repositoryModel = Repository.GetRepository(repositoryName);
result |= repositoryModel.Users.Contains(username, StringComparer.OrdinalIgnoreCase);
result |= repositoryModel.Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
result |= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);
result |= TeamRepository.GetTeams(username).Any(x => repositoryModel.Teams.Contains(x.Name, StringComparer.OrdinalIgnoreCase));
return result;
}
public bool IsRepositoryAdministrator(string username, string repositoryName)
{
bool result = false;
result |= Repository.GetRepository(repositoryName).Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
result |= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);
return result;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bonobo.Git.Server.Data;
using Bonobo.Git.Server.Models;
using Microsoft.Practices.Unity;
namespace Bonobo.Git.Server.Security
{
public class ADRepositoryPermissionService : IRepositoryPermissionService
{
[Dependency]
public IRepositoryRepository Repository { get; set; }
[Dependency]
public IRoleProvider RoleProvider { get; set; }
[Dependency]
public ITeamRepository TeamRepository { get; set; }
public bool AllowsAnonymous(string repositoryName)
{
return Repository.GetRepository(repositoryName).AnonymousAccess;
}
public bool HasPermission(string username, string repositoryName)
{
bool result = true;
RepositoryModel repositoryModel = Repository.GetRepository(repositoryName);
result &= repositoryModel.Users.Contains(username, StringComparer.OrdinalIgnoreCase);
result &= repositoryModel.Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
result &= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);
result &= TeamRepository.GetTeams(username).Any(x => repositoryModel.Teams.Contains(x.Name, StringComparer.OrdinalIgnoreCase));
return result;
}
public bool IsRepositoryAdministrator(string username, string repositoryName)
{
bool result = true;
result &= Repository.GetRepository(repositoryName).Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
result &= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);
return result;
}
}
} | mit | C# |
40e64d341ae3e5a684ebcdc3ee4a8471c5757a79 | remove unused code | kreeben/resin,kreeben/resin | src/ResinCore/DocumentPosting.cs | src/ResinCore/DocumentPosting.cs | using System.Diagnostics;
namespace Resin
{
[DebuggerDisplay("{DocumentId}:{Position}")]
public struct DocumentPosting
{
public int DocumentId { get; private set; }
public int Position { get; set; }
public bool HasValue { get; set; }
public DocumentPosting(int documentId, int position)
{
DocumentId = documentId;
Position = position;
HasValue = true;
}
public override string ToString()
{
return string.Format("{0}:{1}", DocumentId, Position);
}
}
} | using System.Diagnostics;
namespace Resin
{
[DebuggerDisplay("{DocumentId}:{Position}")]
public struct DocumentPosting
{
public int DocumentId { get; private set; }
public int Position { get; set; }
public bool HasValue { get; set; }
public DocumentPosting(int documentId, int position)
{
DocumentId = documentId;
Position = position;
HasValue = true;
}
public override string ToString()
{
return string.Format("{0}:{1}", DocumentId, Position);
}
}
[DebuggerDisplay("{DocumentId}:{Position}")]
public struct Posting
{
public int DocumentId { get; private set; }
public int Position { get; set; }
public Posting(int documentId, int position)
{
DocumentId = documentId;
Position = position;
}
public override string ToString()
{
return string.Format("{0}:{1}", DocumentId, Position);
}
}
} | mit | C# |
bb2c7951b59e6edd4a082c7b9de5b418e0c60be2 | Use result of TgaSharpLib benchmark for best practice | nickbabcock/Pfim,nickbabcock/Pfim | src/Pfim.Benchmarks/TargaBenchmark.cs | src/Pfim.Benchmarks/TargaBenchmark.cs | using System.IO;
using BenchmarkDotNet.Attributes;
using DmitryBrant.ImageFormats;
using FreeImageAPI;
using ImageMagick;
using StbSharp;
using DS = DevILSharp;
namespace Pfim.Benchmarks
{
public class TargaBenchmark
{
[Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga", "rgb24_top_left.tga")]
public string Payload { get; set; }
private byte[] data;
[GlobalSetup]
public void SetupData()
{
data = File.ReadAllBytes(Payload);
DS.Bootstrap.Init();
}
[Benchmark]
public IImage Pfim() => Targa.Create(new MemoryStream(data));
[Benchmark]
public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data));
[Benchmark]
public int ImageMagick()
{
var settings = new MagickReadSettings {Format = MagickFormat.Tga};
using (var image = new MagickImage(new MemoryStream(data), settings))
{
return image.Width;
}
}
[Benchmark]
public int DevILSharp()
{
using (var image = DS.Image.Load(data, DS.ImageType.Tga))
{
return image.Width;
}
}
[Benchmark]
public int TargaImage()
{
using (var image = new Paloma.TargaImage(new MemoryStream(data)))
{
return image.Stride;
}
}
[Benchmark]
public int ImageFormats()
{
using (var img = TgaReader.Load(new MemoryStream(data)))
{
return img.Width;
}
}
[Benchmark]
public int StbSharp() => StbImage.LoadFromMemory(data, StbImage.STBI_rgb_alpha).Width;
[Benchmark]
public ushort TgaSharpLib() => TGASharpLib.TGA.FromBytes(data).Height;
}
} | using System.IO;
using BenchmarkDotNet.Attributes;
using DmitryBrant.ImageFormats;
using FreeImageAPI;
using ImageMagick;
using StbSharp;
using DS = DevILSharp;
namespace Pfim.Benchmarks
{
public class TargaBenchmark
{
[Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga", "rgb24_top_left.tga")]
public string Payload { get; set; }
private byte[] data;
[GlobalSetup]
public void SetupData()
{
data = File.ReadAllBytes(Payload);
DS.Bootstrap.Init();
}
[Benchmark]
public IImage Pfim() => Targa.Create(new MemoryStream(data));
[Benchmark]
public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data));
[Benchmark]
public int ImageMagick()
{
var settings = new MagickReadSettings {Format = MagickFormat.Tga};
using (var image = new MagickImage(new MemoryStream(data), settings))
{
return image.Width;
}
}
[Benchmark]
public int DevILSharp()
{
using (var image = DS.Image.Load(data, DS.ImageType.Tga))
{
return image.Width;
}
}
[Benchmark]
public int TargaImage()
{
using (var image = new Paloma.TargaImage(new MemoryStream(data)))
{
return image.Stride;
}
}
[Benchmark]
public int ImageFormats()
{
using (var img = TgaReader.Load(new MemoryStream(data)))
{
return img.Width;
}
}
[Benchmark]
public int StbSharp() => StbImage.LoadFromMemory(data, StbImage.STBI_rgb_alpha).Width;
[Benchmark]
public void TgaSharpLib() => TGASharpLib.TGA.FromBytes(data);
}
} | mit | C# |
03a4ded0a9eb95dde3c2b65710a19c60ae7b8b8a | Update test messages count | EasyNetQ/EasyNetQ,micdenny/EasyNetQ | Source/EasyNetQ.IntegrationTests/PubSub/When_publish_and_subscribe_with_queue_type.cs | Source/EasyNetQ.IntegrationTests/PubSub/When_publish_and_subscribe_with_queue_type.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EasyNetQ.IntegrationTests.Utils;
using FluentAssertions;
using Xunit;
namespace EasyNetQ.IntegrationTests.PubSub
{
[Collection("RabbitMQ")]
public class When_publish_and_subscribe_with_queue_type : IDisposable
{
private readonly RabbitMQFixture rmqFixture;
public When_publish_and_subscribe_with_queue_type(RabbitMQFixture rmqFixture)
{
this.rmqFixture = rmqFixture;
bus = RabbitHutch.CreateBus($"host={rmqFixture.Host};prefetchCount=1;timeout=-1");
}
public void Dispose()
{
bus.Dispose();
}
private const int MessagesCount = 10;
private readonly IBus bus;
[Fact]
public async Task Should_publish_and_consume()
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var subscriptionId = Guid.NewGuid().ToString();
var messagesSink = new MessagesSink(MessagesCount);
var messages = CreateMessages(MessagesCount);
using (await bus.PubSub.SubscribeAsync<QuorumQueueMessage>(subscriptionId, messagesSink.Receive))
{
await bus.PubSub.PublishBatchAsync(messages, cts.Token);
await messagesSink.WaitAllReceivedAsync(cts.Token);
messagesSink.ReceivedMessages.Should().Equal(messages);
}
}
private static List<QuorumQueueMessage> CreateMessages(int count)
{
var result = new List<QuorumQueueMessage>();
for (int i = 0; i < count; i++)
result.Add(new QuorumQueueMessage(i));
return result;
}
}
[Queue("QuorumQueue", QueueType = QueueType.Quorum)]
public class QuorumQueueMessage : Message
{
public QuorumQueueMessage(int id) : base(id)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EasyNetQ.IntegrationTests.Utils;
using FluentAssertions;
using Xunit;
namespace EasyNetQ.IntegrationTests.PubSub
{
[Collection("RabbitMQ")]
public class When_publish_and_subscribe_with_queue_type : IDisposable
{
private readonly RabbitMQFixture rmqFixture;
public When_publish_and_subscribe_with_queue_type(RabbitMQFixture rmqFixture)
{
this.rmqFixture = rmqFixture;
bus = RabbitHutch.CreateBus($"host={rmqFixture.Host};prefetchCount=1;timeout=-1");
}
public void Dispose()
{
bus.Dispose();
}
private const int MessagesCount = 1;
private readonly IBus bus;
[Fact]
public async Task Should_publish_and_consume()
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var subscriptionId = Guid.NewGuid().ToString();
var messagesSink = new MessagesSink(MessagesCount);
var messages = CreateMessages(MessagesCount);
using (await bus.PubSub.SubscribeAsync<QuorumQueueMessage>(subscriptionId, messagesSink.Receive))
{
await bus.PubSub.PublishBatchAsync(messages, cts.Token);
await messagesSink.WaitAllReceivedAsync(cts.Token);
messagesSink.ReceivedMessages.Should().Equal(messages);
}
}
private static List<QuorumQueueMessage> CreateMessages(int count)
{
var result = new List<QuorumQueueMessage>();
for (int i = 0; i < count; i++)
result.Add(new QuorumQueueMessage(i));
return result;
}
}
[Queue("QuorumQueue", QueueType = QueueType.Quorum)]
public class QuorumQueueMessage : Message
{
public QuorumQueueMessage(int id) : base(id)
{
}
}
}
| mit | C# |
ec259706585c58f15d9ae2cfd3840dbb46f1b787 | Fix performance tests GC | MarinAtanasov/AppBrix,MarinAtanasov/AppBrix.NetCore | Tests/AppBrix.Tests/TestUtils.cs | Tests/AppBrix.Tests/TestUtils.cs | // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using AppBrix.Configuration;
using AppBrix.Configuration.Memory;
using AppBrix.Modules;
using FluentAssertions;
using System;
using System.Linq;
namespace AppBrix.Tests
{
/// <summary>
/// Contains commonly used testing utilities.
/// </summary>
public static class TestUtils
{
#region Public and overriden methods
/// <summary>
/// Creates an app with an in-memory configuration using the provided module and its dependencies.
/// </summary>
/// <param name="module">The module to load inside the application.</param>
/// <returns>The created application.</returns>
public static IApp CreateTestApp(params Type[] modules)
{
IConfigService service = new MemoryConfigService();
var config = service.Get<AppConfig>();
modules.SelectMany(module => module.CreateObject<IModule>().GetAllDependencies())
.Concat(modules)
.Distinct()
.Select(ModuleConfigElement.Create)
.ToList()
.ForEach(config.Modules.Add);
return App.Create(service);
}
public static void TestPerformance(Action action)
{
// Invoke the action once to make sure that the assemblies are loaded.
action.ExecutionTime().Should().BeLessThan(TimeSpan.FromMilliseconds(5000), "this is a performance test");
GC.Collect();
action.ExecutionTime().Should().BeLessThan(TimeSpan.FromMilliseconds(100), "this is a performance test");
}
#endregion
}
}
| // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using AppBrix.Configuration;
using AppBrix.Configuration.Memory;
using AppBrix.Modules;
using FluentAssertions;
using System;
using System.Linq;
namespace AppBrix.Tests
{
/// <summary>
/// Contains commonly used testing utilities.
/// </summary>
public static class TestUtils
{
#region Public and overriden methods
/// <summary>
/// Creates an app with an in-memory configuration using the provided module and its dependencies.
/// </summary>
/// <param name="module">The module to load inside the application.</param>
/// <returns>The created application.</returns>
public static IApp CreateTestApp(params Type[] modules)
{
IConfigService service = new MemoryConfigService();
var config = service.Get<AppConfig>();
modules.SelectMany(module => module.CreateObject<IModule>().GetAllDependencies())
.Concat(modules)
.Distinct()
.Select(ModuleConfigElement.Create)
.ToList()
.ForEach(config.Modules.Add);
return App.Create(service);
}
public static void TestPerformance(Action action)
{
// Invoke the action once to make sure that the assemblies are loaded.
action.ExecutionTime().Should().BeLessThan(TimeSpan.FromMilliseconds(5000), "this is a performance test");
GC.TryStartNoGCRegion(8 * 1024 * 1024);
try
{
action.ExecutionTime().Should().BeLessThan(TimeSpan.FromMilliseconds(100), "this is a performance test");
}
finally
{
GC.EndNoGCRegion();
}
}
#endregion
}
}
| mit | C# |
2a1922f56f4017bff232917b25c24d80b77f37e5 | Fix incorrect exception type | csf-dev/ZPT-Sharp,csf-dev/ZPT-Sharp | ExpressionEvaluators/CSF.Zpt.ExpressionEvaluators.LoadExpressions/UnsupportedDocumentTypeException.cs | ExpressionEvaluators/CSF.Zpt.ExpressionEvaluators.LoadExpressions/UnsupportedDocumentTypeException.cs | using System;
namespace CSF.Zpt.ExpressionEvaluators.LoadExpressions
{
/// <summary>
/// Exception raised when an unsupported document type is used with a 'load:' expression.
/// </summary>
[Serializable]
public class UnsupportedDocumentTypeException : ZptException
{
/// <summary>
/// Initializes a new instance of the <see cref="T:UnsupportedDocumentTypeException"/> class
/// </summary>
public UnsupportedDocumentTypeException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:UnsupportedDocumentTypeException"/> class
/// </summary>
/// <param name="message">A <see cref="T:System.String"/> that describes the exception. </param>
public UnsupportedDocumentTypeException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:UnsupportedDocumentTypeException"/> class
/// </summary>
/// <param name="message">A <see cref="T:System.String"/> that describes the exception. </param>
/// <param name="inner">The exception that is the cause of the current exception. </param>
public UnsupportedDocumentTypeException(string message, Exception inner) : base(message, inner)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:UnsupportedDocumentTypeException"/> class
/// </summary>
/// <param name="context">The contextual information about the source or destination.</param>
/// <param name="info">The object that holds the serialized object data.</param>
protected UnsupportedDocumentTypeException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)
{
}
}
}
| using System;
namespace CSF.Zpt.ExpressionEvaluators.LoadExpressions
{
/// <summary>
/// Exception raised when an unsupported document type is used with a 'load:' expression.
/// </summary>
[Serializable]
public class UnsupportedDocumentTypeException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="T:UnsupportedDocumentTypeException"/> class
/// </summary>
public UnsupportedDocumentTypeException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:UnsupportedDocumentTypeException"/> class
/// </summary>
/// <param name="message">A <see cref="T:System.String"/> that describes the exception. </param>
public UnsupportedDocumentTypeException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:UnsupportedDocumentTypeException"/> class
/// </summary>
/// <param name="message">A <see cref="T:System.String"/> that describes the exception. </param>
/// <param name="inner">The exception that is the cause of the current exception. </param>
public UnsupportedDocumentTypeException(string message, Exception inner) : base(message, inner)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:UnsupportedDocumentTypeException"/> class
/// </summary>
/// <param name="context">The contextual information about the source or destination.</param>
/// <param name="info">The object that holds the serialized object data.</param>
protected UnsupportedDocumentTypeException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)
{
}
}
}
| mit | C# |
24e43b005815617cfad5e507754c718bb8b2f17b | Maintain checkbox/radio input state on re-displaying a form after validation errors. (#9412) | stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2 | src/OrchardCore.Modules/OrchardCore.Forms/Views/Items/InputPart.cshtml | src/OrchardCore.Modules/OrchardCore.Forms/Views/Items/InputPart.cshtml | @using OrchardCore.Forms.Models
@model ShapeViewModel<InputPart>
@{
var formElementPart = Model.Value.ContentItem.As<FormElementPart>();
var formInputElementPart = Model.Value.ContentItem.As<FormInputElementPart>();
var elementId = formElementPart.Id;
var fieldName = formInputElementPart.Name;
var fieldId = !string.IsNullOrEmpty(elementId) ? elementId : !string.IsNullOrEmpty(fieldName) ? Html.GenerateIdFromName(fieldName) : default(string);
var fieldValue = Model.Value.DefaultValue;
var fieldClass = "form-control";
var isChecked = false;
if (ViewData.ModelState.TryGetValue(fieldName, out var fieldEntry))
{
if (Model.Value.Type == "checkbox" || Model.Value.Type == "radio")
{
isChecked = fieldEntry.AttemptedValue == fieldValue;
}
else
{
fieldValue = fieldEntry.AttemptedValue;
}
if (fieldEntry.Errors.Count > 0)
{
fieldClass = "form-control input-validation-error";
}
}
}
<input id="@fieldId" name="@fieldName" type="@Model.Value.Type" class="@fieldClass" value="@fieldValue" placeholder="@Model.Value.Placeholder" @(isChecked ? "checked" : "") />
| @using OrchardCore.Forms.Models
@model ShapeViewModel<InputPart>
@{
var formElementPart = Model.Value.ContentItem.As<FormElementPart>();
var formInputElementPart = Model.Value.ContentItem.As<FormInputElementPart>();
var elementId = formElementPart.Id;
var fieldName = formInputElementPart.Name;
var fieldId = !string.IsNullOrEmpty(elementId) ? elementId : !string.IsNullOrEmpty(fieldName) ? Html.GenerateIdFromName(fieldName) : default(string);
var fieldValue = Model.Value.DefaultValue;
var fieldClass = "form-control";
if (ViewData.ModelState.TryGetValue(fieldName, out var fieldEntry))
{
fieldValue = fieldEntry.AttemptedValue;
if (fieldEntry.Errors.Count > 0)
{
fieldClass = "form-control input-validation-error";
}
}
}
<input id="@fieldId" name="@fieldName" type="@Model.Value.Type" class="@fieldClass" value="@fieldValue" placeholder="@Model.Value.Placeholder" />
| bsd-3-clause | C# |
504d5a3d6ed49988be341b33994c90e6815e761f | Add benchmark for `IBindable.CreateInstance` | ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework | osu.Framework.Benchmarks/BenchmarkBindableInstantiation.cs | osu.Framework.Benchmarks/BenchmarkBindableInstantiation.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 BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;
namespace osu.Framework.Benchmarks
{
public class BenchmarkBindableInstantiation
{
private Bindable<int> bindable;
[GlobalSetup]
public void GlobalSetup() => bindable = new Bindable<int>();
/// <summary>
/// Creates an instance of the bindable directly by construction.
/// </summary>
[Benchmark(Baseline = true)]
public Bindable<int> CreateInstanceViaConstruction() => new Bindable<int>();
/// <summary>
/// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type, object[])"/>.
/// This used to be how <see cref="Bindable{T}.GetBoundCopy"/> creates an instance before binding, which has turned out to be inefficient in performance.
/// </summary>
[Benchmark]
public Bindable<int> CreateInstanceViaActivatorWithParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), 0);
/// <summary>
/// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type)"/>.
/// More performant than <see cref="CreateInstanceViaActivatorWithParams"/>, due to not passing parameters to <see cref="Activator"/> during instance creation.
/// </summary>
[Benchmark]
public Bindable<int> CreateInstanceViaActivatorWithoutParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), true);
/// <summary>
/// Creates an instance of the bindable via <see cref="IBindable.CreateInstance"/>.
/// This is the current and most performant version used for <see cref="IBindable.GetBoundCopy"/>, as equally performant as <see cref="CreateInstanceViaConstruction"/>.
/// </summary>
[Benchmark]
public Bindable<int> CreateInstanceViaBindableCreateInstance() => bindable.CreateInstance();
}
}
| // 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 BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;
namespace osu.Framework.Benchmarks
{
public class BenchmarkBindableInstantiation
{
private Bindable<int> bindable;
[GlobalSetup]
public void GlobalSetup() => bindable = new Bindable<int>();
/// <summary>
/// Creates an instance of the bindable directly by construction.
/// </summary>
[Benchmark(Baseline = true)]
public Bindable<int> CreateInstanceViaConstruction() => new Bindable<int>();
/// <summary>
/// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type, object[])"/>.
/// This used to be how <see cref="Bindable{T}.GetBoundCopy"/> creates an instance before binding, which has turned out to be inefficient in performance.
/// </summary>
[Benchmark]
public Bindable<int> CreateInstanceViaActivatorWithParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), 0);
/// <summary>
/// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type)"/>.
/// More performant than <see cref="CreateInstanceViaActivatorWithParams"/>, due to not passing parameters to <see cref="Activator"/> during instance creation.
/// </summary>
[Benchmark]
public Bindable<int> CreateInstanceViaActivatorWithoutParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), true);
}
}
| mit | C# |
22f3fd487b9cb7f346f068200b02f4fdf611e677 | Mark test as headless | UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,peppy/osu | osu.Game.Tests/Gameplay/TestSceneGameplayClockContainer.cs | osu.Game.Tests/Gameplay/TestSceneGameplayClockContainer.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Play;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Gameplay
{
[HeadlessTest]
public class TestSceneGameplayClockContainer : OsuTestScene
{
[Test]
public void TestStartThenElapsedTime()
{
GameplayClockContainer gcc = null;
AddStep("create container", () => Add(gcc = new GameplayClockContainer(CreateWorkingBeatmap(new OsuRuleset().RulesetInfo), Array.Empty<Mod>(), 0)));
AddStep("start track", () => gcc.Start());
AddUntilStep("elapsed greater than zero", () => gcc.GameplayClock.ElapsedFrameTime > 0);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Play;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Gameplay
{
public class TestSceneGameplayClockContainer : OsuTestScene
{
[Test]
public void TestStartThenElapsedTime()
{
GameplayClockContainer gcc = null;
AddStep("create container", () => Add(gcc = new GameplayClockContainer(CreateWorkingBeatmap(new OsuRuleset().RulesetInfo), Array.Empty<Mod>(), 0)));
AddStep("start track", () => gcc.Start());
AddUntilStep("elapsed greater than zero", () => gcc.GameplayClock.ElapsedFrameTime > 0);
}
}
}
| mit | C# |
c0c449e453d2a71043386cf120a633c40ff2c123 | Remove unused using | johnneijzen/osu,2yangk23/osu,DrabWeb/osu,johnneijzen/osu,ppy/osu,DrabWeb/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,EVAST9919/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,ZLima12/osu,smoogipooo/osu,smoogipoo/osu,naoey/osu,ZLima12/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,naoey/osu,peppy/osu,2yangk23/osu,naoey/osu,NeoAdonis/osu,ppy/osu | osu.Game/Graphics/UserInterface/ScreenBreadcrumbControl.cs | osu.Game/Graphics/UserInterface/ScreenBreadcrumbControl.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Screens;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack.
/// </summary>
public class ScreenBreadcrumbControl : BreadcrumbControl<Screen>
{
private Screen last;
public ScreenBreadcrumbControl(Screen initialScreen)
{
Current.ValueChanged += newScreen =>
{
if (last != newScreen && !newScreen.IsCurrentScreen)
newScreen.MakeCurrent();
};
onPushed(initialScreen);
}
private void screenChanged(Screen newScreen)
{
if (last != null)
{
last.Exited -= screenChanged;
last.ModePushed -= onPushed;
}
last = newScreen;
newScreen.Exited += screenChanged;
newScreen.ModePushed += onPushed;
Current.Value = newScreen;
}
private void onPushed(Screen screen)
{
Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem);
AddItem(screen);
screenChanged(screen);
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Screens;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack.
/// </summary>
public class ScreenBreadcrumbControl : BreadcrumbControl<Screen>
{
private Screen last;
public ScreenBreadcrumbControl(Screen initialScreen)
{
Current.ValueChanged += newScreen =>
{
if (last != newScreen && !newScreen.IsCurrentScreen)
newScreen.MakeCurrent();
};
onPushed(initialScreen);
}
private void screenChanged(Screen newScreen)
{
if (last != null)
{
last.Exited -= screenChanged;
last.ModePushed -= onPushed;
}
last = newScreen;
newScreen.Exited += screenChanged;
newScreen.ModePushed += onPushed;
Current.Value = newScreen;
}
private void onPushed(Screen screen)
{
Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem);
AddItem(screen);
screenChanged(screen);
}
}
}
| mit | C# |
3778250fa467246b1ba031e5f73d253437b2e893 | Fix test to use the appropriate config | asd-and-Rizzo/ExpressionToCode,EamonNerbonne/ExpressionToCode | ExpressionToCodeTest/AnonymousObjectFormattingTest.cs | ExpressionToCodeTest/AnonymousObjectFormattingTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpressionToCodeLib;
using Xunit;
namespace ExpressionToCodeTest
{
public class AnonymousObjectFormattingTest
{
[Fact]
public void AnonymousObjectsRenderAsCode()
{
Assert.Equal("new {\n A = 1,\n Foo = \"Bar\",\n}", ObjectToCode.ComplexObjectToPseudoCode(new { A = 1, Foo = "Bar", }));
}
[Fact]
public void AnonymousObjectsInArray()
{
Assert.Equal("new[] {\n new {\n Val = 3,\n },\n new {\n Val = 42,\n },\n}", ObjectToCode.ComplexObjectToPseudoCode(new[] { new { Val = 3, }, new { Val = 42 } }));
}
[Fact]
public void EnumerableInAnonymousObject()
{
Assert.Equal("new {\n Nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...},\n}", ExpressionToCodeConfiguration.DefaultAssertionConfiguration.ComplexObjectToPseudoCode(new { Nums = Enumerable.Range(1, 13) }));
}
[Fact]
public void EnumInAnonymousObject()
{
Assert.Equal("new {\n Enum = ConsoleKey.A,\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Enum = ConsoleKey.A }));
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpressionToCodeLib;
using Xunit;
namespace ExpressionToCodeTest
{
public class AnonymousObjectFormattingTest
{
[Fact]
public void AnonymousObjectsRenderAsCode()
{
Assert.Equal("new {\n A = 1,\n Foo = \"Bar\",\n}", ObjectToCode.ComplexObjectToPseudoCode(new { A = 1, Foo = "Bar", }));
}
[Fact]
public void AnonymousObjectsInArray()
{
Assert.Equal("new[] {\n new {\n Val = 3,\n },\n new {\n Val = 42,\n },\n}", ObjectToCode.ComplexObjectToPseudoCode(new[] { new { Val = 3, }, new { Val = 42 } }));
}
[Fact]
public void EnumerableInAnonymousObject()
{
Assert.Equal("new {\n Nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...},\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Nums = Enumerable.Range(1, 13) }));
}
[Fact]
public void EnumInAnonymousObject()
{
Assert.Equal("new {\n Enum = ConsoleKey.A,\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Enum = ConsoleKey.A }));
}
}
} | apache-2.0 | C# |
bda998b14f4cf6b47ebe99fad7d9f00c07e277c0 | add test | prodot/ReCommended-Extension | Sources/ReCommendedExtension.Tests/test/data/ContextActions/AddConfigureAwait/Availability.cs | Sources/ReCommendedExtension.Tests/test/data/ContextActions/AddConfigureAwait/Availability.cs | using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace Test
{
internal class Availability
{
async Task TaskWithoutResult()
{
aw{on}ait Task.Run(() => { });
aw{off}ait Task.Yield();
}
async Task TaskWithResult()
{
aw{on}ait Task.Run(() => 3);
}
async Task ValueTask(ValueTask task)
{
aw{on}ait task;
}
async Task ValueTaskWithResult(ValueTask<int> task)
{
aw{on}ait task;
}
async Task AsyncDisposable()
{
aw{on}ait using (new MemoryStream()) { }
}
async Task AsyncDisposable_Variable_Type()
{
aw{on}ait using (Stream m = new MemoryStream()) { }
}
async Task AsyncDisposable_Variable()
{
aw{on}ait using (var m = new MemoryStream()) { }
}
async Task AsyncDisposable_Variable(int x)
{
if (x == 1) aw{off}ait using (var m = new MemoryStream()) { }
}
async Task AsyncDisposable_Variable_Multiple()
{
aw{off}ait using (Stream m1 = new MemoryStream(), m2 = new MemoryStream()) { }
}
async Task AsyncDisposable_UsingVar()
{
aw{off}ait using var m1 = new MemoryStream();
}
async Task AsyncIterator(IAsyncEnumerable<int> sequence)
{
aw{on}ait foreach (var item in sequence) { }
}
}
} | using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace Test
{
internal class Availability
{
async Task TaskWithoutResult()
{
aw{on}ait Task.Run(() => { });
aw{off}ait Task.Yield();
}
async Task TaskWithResult()
{
aw{on}ait Task.Run(() => 3);
}
async Task ValueTask(ValueTask task)
{
aw{on}ait task;
}
async Task ValueTaskWithResult(ValueTask<int> task)
{
aw{on}ait task;
}
async Task AsyncDisposable()
{
aw{on}ait using (new MemoryStream()) { }
}
async Task AsyncDisposable_Variable_Type()
{
aw{on}ait using (Stream m = new MemoryStream()) { }
}
async Task AsyncDisposable_Variable()
{
aw{on}ait using (var m = new MemoryStream()) { }
}
async Task AsyncDisposable_Variable_Multiple()
{
aw{off}ait using (Stream m1 = new MemoryStream(), m2 = new MemoryStream()) { }
}
async Task AsyncDisposable_UsingVar()
{
aw{off}ait using var m1 = new MemoryStream();
}
async Task AsyncIterator(IAsyncEnumerable<int> sequence)
{
aw{on}ait foreach (var item in sequence) { }
}
}
} | apache-2.0 | C# |
54b3a84a2282ae77cbe714b696adbbf5c2be008c | Use EditorGUI.EnumFlagsField instead of EditorGUI.EnumMaskField in Unity 2017.3 and newer | SlashGames/slash-framework,SlashGames/slash-framework,SlashGames/slash-framework | Source/Slash.Unity.Editor.Common/Source/Utils/EnumFlagPropertyDrawer.cs | Source/Slash.Unity.Editor.Common/Source/Utils/EnumFlagPropertyDrawer.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="EnumFlagPropertyDrawer.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.Unity.Editor.Common.Utils
{
using System;
using Slash.Unity.Common.Utils;
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(EnumFlagAttribute))]
public class EnumFlagDrawer : PropertyDrawer
{
#region Public Methods and Operators
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var flagSettings = (EnumFlagAttribute)this.attribute;
var targetEnum = GetBaseProperty<Enum>(property);
var propName = flagSettings.Name;
if (string.IsNullOrEmpty(propName))
{
propName = property.name;
}
EditorGUI.BeginProperty(position, label, property);
#if UNITY_2017_3_OR_NEWER
var enumNew = EditorGUI.EnumFlagsField(position, propName, targetEnum);
#else
var enumNew = EditorGUI.EnumMaskField(position, propName, targetEnum);
#endif
var convertedType = Convert.ChangeType(enumNew, targetEnum.GetType());
if (convertedType != null)
{
property.intValue = (int)convertedType;
}
EditorGUI.EndProperty();
}
#endregion
#region Methods
private static T GetBaseProperty<T>(SerializedProperty prop)
{
// Separate the steps it takes to get to this property
var separatedPaths = prop.propertyPath.Split('.');
// Go down to the root of this serialized property
var reflectionTarget = prop.serializedObject.targetObject as object;
// Walk down the path to get the target object
foreach (var path in separatedPaths)
{
var fieldInfo = reflectionTarget.GetType().GetField(path);
reflectionTarget = fieldInfo.GetValue(reflectionTarget);
}
return (T)reflectionTarget;
}
#endregion
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="EnumFlagPropertyDrawer.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.Unity.Editor.Common.Utils
{
using System;
using Slash.Unity.Common.Utils;
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(EnumFlagAttribute))]
public class EnumFlagDrawer : PropertyDrawer
{
#region Public Methods and Operators
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var flagSettings = (EnumFlagAttribute)this.attribute;
var targetEnum = GetBaseProperty<Enum>(property);
var propName = flagSettings.Name;
if (string.IsNullOrEmpty(propName))
{
propName = property.name;
}
EditorGUI.BeginProperty(position, label, property);
var enumNew = EditorGUI.EnumMaskField(position, propName, targetEnum);
var convertedType = Convert.ChangeType(enumNew, targetEnum.GetType());
if (convertedType != null)
{
property.intValue = (int)convertedType;
}
EditorGUI.EndProperty();
}
#endregion
#region Methods
private static T GetBaseProperty<T>(SerializedProperty prop)
{
// Separate the steps it takes to get to this property
var separatedPaths = prop.propertyPath.Split('.');
// Go down to the root of this serialized property
var reflectionTarget = prop.serializedObject.targetObject as object;
// Walk down the path to get the target object
foreach (var path in separatedPaths)
{
var fieldInfo = reflectionTarget.GetType().GetField(path);
reflectionTarget = fieldInfo.GetValue(reflectionTarget);
}
return (T)reflectionTarget;
}
#endregion
}
} | mit | C# |
e4eefdd9e12b2a4ff300b97eadb48ba892e4df54 | Add input type Url (#4535) | petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,petedavis/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2 | src/OrchardCore.Modules/OrchardCore.Forms/Views/Items/InputPart.Fields.Edit.cshtml | src/OrchardCore.Modules/OrchardCore.Forms/Views/Items/InputPart.Fields.Edit.cshtml | @using OrchardCore.Forms.ViewModels;
@model InputPartEditViewModel
<fieldset class="form-group">
<label asp-for="Type">@T["Type"]</label>
<select asp-for="Type" class="form-control content-preview-select">
<option value="text">@T["Text"]</option>
<option value="number">@T["Number"]</option>
<option value="email">@T["Email"]</option>
<option value="tel">@T["Phone"]</option>
<option value="date">@T["Date"]</option>
<option value="time">@T["Time"]</option>
<option value="datetime">@T["DateTime"]</option>
<option value="datetime-local">@T["Local DateTime"]</option>
<option value="month">@T["Month"]</option>
<option value="week">@T["Week"]</option>
<option value="hidden">@T["Hidden"]</option>
<option value="password">@T["Password"]</option>
<option value="radio">@T["Radio"]</option>
<option value="checkbox">@T["Checkbox"]</option>
<option value="color">@T["Color"]</option>
<option value="range">@T["Range"]</option>
<option value="file">@T["File"]</option>
<option value="url">@T["Url"]</option>
<option value="image">@T["Image"]</option>
<option value="reset">@T["Reset"]</option>
<option value="search">@T["Search"]</option>
<option value="submit">@T["Submit"]</option>
</select>
<span class="hint">@T["The button type."]</span>
</fieldset>
<fieldset class="form-group">
<label asp-for="Placeholder">@T["Placeholder Text"]</label>
<input asp-for="Placeholder" type="text" class="form-control content-preview-text" />
<span class="hint">@T["The text to display when the field has no value."]</span>
</fieldset>
<fieldset class="form-group">
<label asp-for="DefaultValue">@T["Default Value"]</label>
<input asp-for="DefaultValue" type="text" class="form-control content-preview-text" />
<span class="hint">@T["The default value for this field."]</span>
</fieldset> | @using OrchardCore.Forms.ViewModels;
@model InputPartEditViewModel
<fieldset class="form-group">
<label asp-for="Type">@T["Type"]</label>
<select asp-for="Type" class="form-control content-preview-select">
<option value="text">@T["Text"]</option>
<option value="number">@T["Number"]</option>
<option value="email">@T["Email"]</option>
<option value="tel">@T["Phone"]</option>
<option value="date">@T["Date"]</option>
<option value="time">@T["Time"]</option>
<option value="datetime">@T["DateTime"]</option>
<option value="datetime-local">@T["Local DateTime"]</option>
<option value="month">@T["Month"]</option>
<option value="week">@T["Week"]</option>
<option value="hidden">@T["Hidden"]</option>
<option value="password">@T["Password"]</option>
<option value="radio">@T["Radio"]</option>
<option value="checkbox">@T["Checkbox"]</option>
<option value="color">@T["Color"]</option>
<option value="range">@T["Range"]</option>
<option value="file">@T["File"]</option>
<option value="image">@T["Image"]</option>
<option value="reset">@T["Reset"]</option>
<option value="search">@T["Search"]</option>
<option value="submit">@T["Submit"]</option>
</select>
<span class="hint">@T["The button type."]</span>
</fieldset>
<fieldset class="form-group">
<label asp-for="Placeholder">@T["Placeholder Text"]</label>
<input asp-for="Placeholder" type="text" class="form-control content-preview-text" />
<span class="hint">@T["The text to display when the field has no value."]</span>
</fieldset>
<fieldset class="form-group">
<label asp-for="DefaultValue">@T["Default Value"]</label>
<input asp-for="DefaultValue" type="text" class="form-control content-preview-text" />
<span class="hint">@T["The default value for this field."]</span>
</fieldset> | bsd-3-clause | C# |
56581f712b47c480000f889f729400e7afdc6f76 | add properties | Appleseed/base,Appleseed/base | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/UserAlert.cs | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/UserAlert.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class UserAlert
{
public Guid user_id { get; set; }
public string email { get; set; }
public string name { get; set; }
public string source { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class UserAlert
{
}
}
| apache-2.0 | C# |
416a43f0b155cc8d6bd885428cde90d6b0e26a1a | Fix update installer not running as administrator due to breaking change in .NET | chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck | windows/TweetDuck/Updates/UpdateInstaller.cs | windows/TweetDuck/Updates/UpdateInstaller.cs | using System;
using System.ComponentModel;
using System.Diagnostics;
using TweetDuck.Configuration;
using TweetLib.Core;
using TweetLib.Utils.Static;
namespace TweetDuck.Updates {
sealed class UpdateInstaller {
private string Path { get; }
public UpdateInstaller(string path) {
this.Path = path;
}
public bool Launch() {
// ProgramPath has a trailing backslash
string arguments = "/SP- /SILENT /FORCECLOSEAPPLICATIONS /UPDATEPATH=\"" + App.ProgramPath + "\" /RUNARGS=\"" + Arguments.GetCurrentForInstallerCmd() + "\"" + (App.IsPortable ? " /PORTABLE=1" : "");
bool runElevated = !App.IsPortable || !FileUtils.CheckFolderWritePermission(App.ProgramPath);
try {
using (Process.Start(new ProcessStartInfo {
FileName = Path,
Arguments = arguments,
Verb = runElevated ? "runas" : string.Empty,
UseShellExecute = true,
ErrorDialog = true
})) {
return true;
}
} catch (Win32Exception e) when (e.NativeErrorCode == 0x000004C7) { // operation canceled by the user
return false;
} catch (Exception e) {
App.ErrorHandler.HandleException("Update Installer Error", "Could not launch update installer.", true, e);
return false;
}
}
}
}
| using System;
using System.ComponentModel;
using System.Diagnostics;
using TweetDuck.Configuration;
using TweetLib.Core;
using TweetLib.Utils.Static;
namespace TweetDuck.Updates {
sealed class UpdateInstaller {
private string Path { get; }
public UpdateInstaller(string path) {
this.Path = path;
}
public bool Launch() {
// ProgramPath has a trailing backslash
string arguments = "/SP- /SILENT /FORCECLOSEAPPLICATIONS /UPDATEPATH=\"" + App.ProgramPath + "\" /RUNARGS=\"" + Arguments.GetCurrentForInstallerCmd() + "\"" + (App.IsPortable ? " /PORTABLE=1" : "");
bool runElevated = !App.IsPortable || !FileUtils.CheckFolderWritePermission(App.ProgramPath);
try {
using (Process.Start(new ProcessStartInfo {
FileName = Path,
Arguments = arguments,
Verb = runElevated ? "runas" : string.Empty,
ErrorDialog = true
})) {
return true;
}
} catch (Win32Exception e) when (e.NativeErrorCode == 0x000004C7) { // operation canceled by the user
return false;
} catch (Exception e) {
App.ErrorHandler.HandleException("Update Installer Error", "Could not launch update installer.", true, e);
return false;
}
}
}
}
| mit | C# |
30ab3b1fde3908e8bba501b663ee688cee70637b | Introduce AnonymousObservable | citizenmatt/ndc-london-2013 | rx/rx/Program.cs | rx/rx/Program.cs | using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace rx
{
class Program
{
static void Main(string[] args)
{
var subject = new Subject<string>();
using (subject.Subscribe(new AnonymousBobserver<string>(s => Console.WriteLine(s),
() => Console.WriteLine("Done"),
e => Console.WriteLine(e))))
{
var wc = new WebClient();
var task = wc.DownloadStringTaskAsync("http://www.googleasdasdsad.com/robots.txt");
task.ContinueWith(t =>
{
if (t.IsFaulted)
subject.OnError(t.Exception);
else
{
subject.OnNext(t.Result);
subject.OnCompleted();
}
});
// Wait for the async call
Console.ReadLine();
}
}
}
public class Bobservable
{
public static IBobservable<T> FromTask<T>()
{
return new AnonymousBobservable<T>();
}
}
public class AnonymousBobservable<T> : IBobservable<T>
{
private readonly Func<IBobserver<T>, IDisposable> onSubscribe;
public AnonymousBobservable(Func<IBobserver<T>, IDisposable> onSubscribe)
{
this.onSubscribe = onSubscribe;
}
public IDisposable Subscribe(IBobserver<T> observer)
{
return onSubscribe(observer);
}
}
public interface IBobservable<T>
{
IDisposable Subscribe(IBobserver<T> observer);
}
public interface IBobserver<T>
{
void OnNext(T result);
void OnCompleted();
void OnError(Exception exception);
}
}
| using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace rx
{
class Program
{
static void Main(string[] args)
{
var subject = new Subject<string>();
using (subject.Subscribe(new AnonymousBobserver<string>(s => Console.WriteLine(s),
() => Console.WriteLine("Done"),
e => Console.WriteLine(e))))
{
var wc = new WebClient();
var task = wc.DownloadStringTaskAsync("http://www.googleasdasdsad.com/robots.txt");
task.ContinueWith(t =>
{
if (t.IsFaulted)
subject.OnError(t.Exception);
else
{
subject.OnNext(t.Result);
subject.OnCompleted();
}
});
// Wait for the async call
Console.ReadLine();
}
}
}
public class Bobservable
{
public static IBobservable<T> FromTask<T>()
{
}
}
public interface IBobservable<T>
{
IDisposable Subscribe(IBobserver<T> observer);
}
public interface IBobserver<T>
{
void OnNext(T result);
void OnCompleted();
void OnError(Exception exception);
}
}
| mit | C# |
687ee0f48ebee772bd79a5b7711820a9eceef3b7 | sort in dropDownElements | kicholen/SpaceShooter,kicholen/GamePrototype | Assets/EditorScript/View/Level/Hud/RightBottomPanel/RightBottomPanelViewUpdaterBase.cs | Assets/EditorScript/View/Level/Hud/RightBottomPanel/RightBottomPanelViewUpdaterBase.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class RightBottomPanelViewUpdaterBase {
protected GameObject createInputElement(string infoText, string defaultText, UnityAction<string> onValueChange) {
GameObject gameObject = UnityEngine.Object.Instantiate(Resources.Load<GameObject>("Prefab/UI/EditorView/Level/InputElement"));
gameObject.GetComponentInChildren<Text>().text = infoText;
InputField input = gameObject.GetComponentInChildren<InputField>();
input.onValueChanged.AddListener(onValueChange);
input.text = defaultText;
return gameObject;
}
protected GameObject createDropdownElement(string infoText, string defaultText, List<string> names, UnityAction<string> onValueChange) {
GameObject gameObject = UnityEngine.Object.Instantiate(Resources.Load<GameObject>("Prefab/UI/EditorView/Level/DropdownElement"));
List<Dropdown.OptionData> options = names.Select(name => new Dropdown.OptionData(name)).ToList<Dropdown.OptionData>();
options.Sort((x, y) => Convert.ToInt16(x.text).CompareTo(Convert.ToInt16(y.text)));
gameObject.GetComponentInChildren<Dropdown>().options = options;
gameObject.GetComponentInChildren<Dropdown>().value = names.IndexOf(defaultText);
gameObject.transform.FindChild("Label").GetComponent<Text>().text = infoText;
gameObject.GetComponentInChildren<Dropdown>().onValueChanged.AddListener(value => onValueChange(value.ToString()));
return gameObject;
}
}
| using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class RightBottomPanelViewUpdaterBase {
protected GameObject createInputElement(string infoText, string defaultText, UnityAction<string> onValueChange) {
GameObject gameObject = UnityEngine.Object.Instantiate(Resources.Load<GameObject>("Prefab/UI/EditorView/Level/InputElement"));
gameObject.GetComponentInChildren<Text>().text = infoText;
InputField input = gameObject.GetComponentInChildren<InputField>();
input.onValueChanged.AddListener(onValueChange);
input.text = defaultText;
return gameObject;
}
protected GameObject createDropdownElement(string infoText, string defaultText, List<string> names, UnityAction<string> onValueChange) {
GameObject gameObject = UnityEngine.Object.Instantiate(Resources.Load<GameObject>("Prefab/UI/EditorView/Level/DropdownElement"));
gameObject.GetComponentInChildren<Dropdown>().options = names.Select(name => new Dropdown.OptionData(name)).ToList<Dropdown.OptionData>();
gameObject.GetComponentInChildren<Dropdown>().value = names.IndexOf(defaultText);
gameObject.transform.FindChild("Label").GetComponent<Text>().text = infoText;
gameObject.GetComponentInChildren<Dropdown>().onValueChanged.AddListener(value => onValueChange(value.ToString()));
return gameObject;
}
}
| mit | C# |
945a20c1ab0d1d8d8badae050bcb405d87d514e5 | Update VenusianNameGenerator.cs | Team-Captain-Marvel-2016/Team-Captain-Marvel-2016-Project,Team-Captain-Marvel-2016/Team-Captain-Marvel-2016-Project,Team-Captain-Marvel-2016/TeamWorkSkeletonSample,Team-Captain-Marvel-2016/TeamWorkSkeletonSample | TeamWorkSkeleton/FootballPlayerAssembly/SpeciesNameGenerators/VenusianNameGenerator.cs | TeamWorkSkeleton/FootballPlayerAssembly/SpeciesNameGenerators/VenusianNameGenerator.cs | namespace FootballPlayerAssembly.SpeciesNameGenerators
{
using System;
using System.Collections.Generic;
using System.Text;
internal static class VenusianNameGenerator
{
internal static Dictionary<int, string> FirstPartName = new Dictionary<int, string>()
{
{ 0 , "Mia" },
{ 1 , "Riu" },
{ 2 , "Khana" },
{ 3 , "Pury" },
{ 4 , "Erikq" },
{ 5 , "Sey" },
{ 6 , "Edo" },
{ 7 , "Livo" },
{ 8 , "Xipi" },
{ 9 , "Kai" }
};
internal static Dictionary<int, string> LastPartName = new Dictionary<int, string>()
{
{ 0 , "vin" },
{ 1 , "margion" },
{ 2 , "philq" },
{ 3 , "neuron" },
{ 4 , "kakud" },
{ 5 , "novese" },
{ 6 , "muril" },
{ 7 , "fyfy" },
{ 8 , "diansin" },
{ 9 , "purl" }
};
internal static string GenerateName()
{
var random = new Random();
var sb = new StringBuilder();
sb.Append(FirstPartName[random.Next(0, 9)]);
sb.Append(LastPartName[random.Next(0, 9)]);
return sb.ToString();
}
}
} | namespace FootballPlayerAssembly.SpeciesNameGenerators
{
internal static class VenusianNameGenerator
{
internal static string GenerateName()
{
// TODO:
return "Venusian";
}
}
}
| mit | C# |
47d1065c64f15c3e3927d1299947727fbcb69608 | Exit the application at Windows shutdown | peruukki/ComputerTimeTracker | Application/TimeReport.cs | Application/TimeReport.cs | using System;
using System.Windows.Forms;
namespace ComputerTimeTracker
{
/// <summary>
/// The form that shows the computer usage time report.
/// </summary>
public partial class TimeReport : Form
{
private bool _close = false;
/// <summary>
/// Creates a new TimeReport instance.
/// </summary>
/// <param name="startTime">Computer usage start time.</param>
public TimeReport(DateTime startTime)
{
InitializeComponent();
_lblTimeStart.Text = startTime.ToLongTimeString();
FormClosing += new FormClosingEventHandler(ReportFormClosing);
}
/// <summary>
/// Actually closes the form. Calling the <see cref="Close"/> method
/// only hides the form.
/// </summary>
public void ForceClose()
{
_close = true;
Close();
}
/// <summary>
/// Updates the time report based on the given time tracker state.
/// </summary>
/// <param name="timeTracker">Time tracker.</param>
public void UpdateReport(TimeTracker timeTracker)
{
DateTime currentTime = DateTime.Now;
_lblTimeCurrent.Text = currentTime.ToLongTimeString();
TimeSpan workTime = timeTracker.GetWorkTime(currentTime);
_lblTimeWork.Text = String.Format("{0:0#}:{1:0#}:{2:0#}",
workTime.Hours, workTime.Minutes,
workTime.Seconds);
}
/// <summary>
/// Called before the form is closed.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Closing event related data.</param>
private void ReportFormClosing(object sender, FormClosingEventArgs e)
{
if ((e.CloseReason == CloseReason.UserClosing) && !_close)
{
e.Cancel = true;
Hide();
}
}
/// <summary>
/// Called when the OK button is clicked.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _btnOk_Click(object sender, EventArgs e)
{
Close();
}
}
} | using System;
using System.Windows.Forms;
namespace ComputerTimeTracker
{
/// <summary>
/// The form that shows the computer usage time report.
/// </summary>
public partial class TimeReport : Form
{
private bool _close = false;
/// <summary>
/// Creates a new TimeReport instance.
/// </summary>
/// <param name="startTime">Computer usage start time.</param>
public TimeReport(DateTime startTime)
{
InitializeComponent();
_lblTimeStart.Text = startTime.ToLongTimeString();
FormClosing += new FormClosingEventHandler(ReportFormClosing);
}
/// <summary>
/// Actually closes the form. Calling the <see cref="Close"/> method
/// only hides the form.
/// </summary>
public void ForceClose()
{
_close = true;
Close();
}
/// <summary>
/// Updates the time report based on the given time tracker state.
/// </summary>
/// <param name="timeTracker">Time tracker.</param>
public void UpdateReport(TimeTracker timeTracker)
{
DateTime currentTime = DateTime.Now;
_lblTimeCurrent.Text = currentTime.ToLongTimeString();
TimeSpan workTime = timeTracker.GetWorkTime(currentTime);
_lblTimeWork.Text = String.Format("{0:0#}:{1:0#}:{2:0#}",
workTime.Hours, workTime.Minutes,
workTime.Seconds);
}
/// <summary>
/// Called before the form is closed.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Closing event related data.</param>
private void ReportFormClosing(object sender, FormClosingEventArgs e)
{
if (!_close)
{
e.Cancel = true;
Hide();
}
}
/// <summary>
/// Called when the OK button is clicked.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _btnOk_Click(object sender, EventArgs e)
{
Close();
}
}
} | mit | C# |
bbf17d3bf6b891f5dca52349356f1750855b0e51 | fix ai gommba | llafuente/unity-platformer,llafuente/unity-platformer | Assets/UnityPlatformer/Scripts/AI/AIGoomba.cs | Assets/UnityPlatformer/Scripts/AI/AIGoomba.cs | using System;
using UnityEngine;
namespace UnityPlatformer {
///<summary>
/// Patrol Artificial inteligence.
/// NOTE does not require Actions but it's recommended:
/// CharacterActionAirMovement and/or CharacterActionGroundMovement
///</summary>
public class AIGoomba: Enemy {
#region public
public Facing initialFacing = Facing.Left;
[Comment("Distance to test if ground is on left/right side. Helps when Enemy standing on platform moving down.")]
public float rayLengthFactor = 1.0f;
[Comment("Do not fall on platform edge. Go back.")]
public bool doNotFall = true;
#endregion
#region private
Facing facing;
#endregion
public void Start() {
pc2d.onLeftWall += OnLeftWall;
pc2d.onRightWall += OnRightWall;
facing = initialFacing;
input.SetX((float) facing);
}
void OnLeftWall() {
facing = Facing.Right;
input.SetX((float) facing);
}
void OnRightWall() {
facing = Facing.Left;
input.SetX((float) facing);
}
void Toogle() {
facing = facing == Facing.Left ? Facing.Right : Facing.Left;
input.SetX((float) facing);
}
public override void ManagedUpdate(float delta) {
if (doNotFall && pc2d.collisions.below) {
if (!IsGroundOnLeft (rayLengthFactor, delta)) {
OnLeftWall ();
} else if (!IsGroundOnRight (rayLengthFactor, delta)) {
OnRightWall ();
}
}
base.ManagedUpdate(delta);
}
}
}
| using System;
using UnityEngine;
namespace UnityPlatformer {
///<summary>
/// Patrol Artificial inteligence.
/// NOTE does not require Actions but it's recommended:
/// CharacterActionAirMovement and/or CharacterActionGroundMovement
///</summary>
public class AIGoomba: Enemy {
#region public
public Facing initialFacing = Facing.Left;
[Comment("Distance to test if ground is on left/right side. Helps when Enemy standing on platform moving down.")]
public float rayLengthFactor = 1.0f;
[Comment("Do not fall on platform edge. Go back.")]
public bool doNotFall = true;
#endregion
#region private
Facing facing;
#endregion
public void Start() {
pc2d.onLeftWall += OnLeftWall;
pc2d.onRightWall += OnRightWall;
facing = initialFacing;
input.SetX((float) facing);
}
void OnLeftWall() {
facing = Facing.Right;
input.SetX((float) facing);
}
void OnRightWall() {
facing = Facing.Left;
input.SetX((float) facing);
}
void Toogle() {
facing = facing == Facing.Left ? Facing.Right : Facing.Left;
input.SetX((float) facing);
}
public override void ManagedUpdate(float delta) {
if (doNotFall) {
if (!IsGroundOnLeft (rayLengthFactor, delta)) {
OnLeftWall ();
} else if (!IsGroundOnRight (rayLengthFactor, delta)) {
OnRightWall ();
}
}
base.ManagedUpdate(delta);
}
}
}
| mit | C# |
f130b1cfbcd55a29dc0e62d9a651b1f06ae4c651 | Add missing license header | rlmcneary2/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,windygu/CefSharp,haozhouxu/CefSharp,AJDev77/CefSharp,joshvera/CefSharp,rover886/CefSharp,ITGlobal/CefSharp,dga711/CefSharp,joshvera/CefSharp,joshvera/CefSharp,gregmartinhtc/CefSharp,VioletLife/CefSharp,AJDev77/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,gregmartinhtc/CefSharp,zhangjingpu/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,dga711/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,windygu/CefSharp,Octopus-ITSM/CefSharp,illfang/CefSharp,zhangjingpu/CefSharp,VioletLife/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,Octopus-ITSM/CefSharp,wangzheng888520/CefSharp,rover886/CefSharp,battewr/CefSharp,haozhouxu/CefSharp,yoder/CefSharp,Octopus-ITSM/CefSharp,windygu/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp,battewr/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,gregmartinhtc/CefSharp,jamespearce2006/CefSharp,NumbersInternational/CefSharp,ITGlobal/CefSharp,Haraguroicha/CefSharp,AJDev77/CefSharp,Octopus-ITSM/CefSharp,Haraguroicha/CefSharp,rover886/CefSharp,battewr/CefSharp,ITGlobal/CefSharp,yoder/CefSharp,ruisebastiao/CefSharp,ITGlobal/CefSharp,dga711/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,NumbersInternational/CefSharp,yoder/CefSharp,dga711/CefSharp,rlmcneary2/CefSharp,jamespearce2006/CefSharp,joshvera/CefSharp,illfang/CefSharp,rover886/CefSharp,ruisebastiao/CefSharp,Livit/CefSharp,gregmartinhtc/CefSharp,zhangjingpu/CefSharp,Livit/CefSharp,twxstar/CefSharp,NumbersInternational/CefSharp,illfang/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,zhangjingpu/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,rover886/CefSharp,Livit/CefSharp,VioletLife/CefSharp,Haraguroicha/CefSharp,Livit/CefSharp,twxstar/CefSharp | CefSharp/Response.cs | CefSharp/Response.cs | // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp
{
public class Response : IResponse
{
public String RedirectUrl { get; private set; }
public ResponseAction Action { get; private set; }
public Response()
{
Action = ResponseAction.Continue;
}
public void Cancel()
{
Action = ResponseAction.Cancel;
}
public void Redirect(String url)
{
RedirectUrl = url;
Action = ResponseAction.Redirect;
}
}
}
| using System;
namespace CefSharp
{
public class Response : IResponse
{
public String RedirectUrl { get; private set; }
public ResponseAction Action { get; private set; }
public Response()
{
Action = ResponseAction.Continue;
}
public void Cancel()
{
Action = ResponseAction.Cancel;
}
public void Redirect(String url)
{
RedirectUrl = url;
Action = ResponseAction.Redirect;
}
}
}
| bsd-3-clause | C# |
e11032215850c9fa04707bcdad6c2f090e05c0f0 | Update ExampleApp_NetCore20_NetStandard20--added the following: | Payoneer-Escrow/payoneer-escrow-csharp-dotnet | ExampleApp_NetCore20_NetStandard20/Program.cs | ExampleApp_NetCore20_NetStandard20/Program.cs | using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace ExampleApp_NetCore20_NetStandard20
{
class Program
{
static void Main(string[] args)
{
////////////////////////////////////////////////////////////////////
// Add your API key and secret before running this example app //
////////////////////////////////////////////////////////////////////
PayoneerEscrow.Api.Client client = new PayoneerEscrow.Api.Client(
"api_key",
"api_secret",
true);
////////////////////////////////////////////////////////////////////
// Change sample data below to test proper API calls //
////////////////////////////////////////////////////////////////////
/**
* Get all accounts
*/
Console.WriteLine("\n\nGet all accounts...\n\n");
dynamic entity_accounts = client.Accounts().All();
Console.WriteLine(entity_accounts);
/**
* Get a single account
*/
Console.WriteLine("\n\nGet a single account...\n\n");
dynamic entity_account = client.Accounts().Get("account_id");
Console.WriteLine(entity_account);
/**
* Get all users associated with an account
*/
Console.WriteLine("\n\nGet all users...\n\n");
dynamic entity_users = client.Accounts().Users("account_id").All();
Console.WriteLine(entity_users);
/**
* Get a single user associated with an account
*/
Console.WriteLine("\n\nGet a single user...\n\n");
dynamic entity_user = client.Accounts().Users("account_id").Get("user_id");
Console.WriteLine(entity_user);
/**
* Create an order
*
* This example shows that a Dictionary can be used
*/
Console.WriteLine("\n\nCreate an order...\n\n");
Dictionary<string, string> params_orderCreate = new Dictionary<string, string> {
{ "seller_id", "seller_user_id" },
{ "buyer_id", "buyer_user_id" },
{ "amount", "10000" },
{ "summary", "Test Order from Payoneer Escrow C#.NET SDK" }
};
dynamic entity_orderCreated = client.Accounts().Orders("account_id").Create(params_orderCreate);
Console.WriteLine(entity_orderCreated);
/**
* Add funds to an order
*
* This example shows that a JObject can be used
*/
Console.WriteLine("\n\nUpdate an order...\n\n");
JObject params_orderUpdate = new JObject {
{ "action", "add_payment" },
{ "confirm", "true" },
{ "source_account_id", "buyer_account_id" },
{ "amount", "10000" }
};
dynamic entity_orderUpdated = client.Accounts().Orders("account_id").Update("order_id", params_orderUpdate);
Console.WriteLine(entity_orderUpdated);
/**
* Update an account
*
* This example shows that an anonymous object can be used
*/
var params_accountUpdate = new {
address = "1234 Address Street",
city = "Los Angeles",
phone = "+1 8005551234",
postal_code = "90046",
state = "CA",
country = "us",
};
dynamic entity_accountUpdated = client.Accounts().Update("account_id", params_accountUpdate);
Console.WriteLine(entity_accountUpdated);
// Keep app open
Console.Write("\n\nPress [Enter] to exit app.");
Console.ReadLine();
}
}
}
| using System;
namespace ExampleApp_NetCore20_NetStandard20
{
class Program
{
static void Main(string[] args)
{
// Get Payoneer Escrow client to make requests
PayoneerEscrow.Api.Client client = new PayoneerEscrow.Api.Client(
"your_api_key",
"your_api_secret",
true);
try
{
// Get all clients associated with the API key
Console.WriteLine("\n\nGetting all clients...\n\n");
string accounts = client.Accounts().All();
Console.WriteLine(accounts);
Console.WriteLine("\n\nGetting a single account...\n\n");
string account = client.Accounts().Get("170246583945");
Console.WriteLine(account);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
// Keep program open
Console.Write("\n\nPress [Enter] to quit.");
Console.ReadLine();
}
}
}
| mit | C# |
a141186aaad99ffd0017505da0298040efcda794 | Set default delay value = 1000 | avatar29A/Last.fm | src/Hqub.Lastfm/Configure.cs | src/Hqub.Lastfm/Configure.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hqub.Lastfm
{
public static class Configure
{
static Configure()
{
Delay = 1000;
}
/// <summary>
/// Set value delay between requests.
/// </summary>
public static int Delay { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hqub.Lastfm
{
public static class Configure
{
/// <summary>
/// Set value delay between requests.
/// </summary>
public static int Delay { get; set; }
}
}
| mit | C# |
a60e150296d29923dce1dcbf4c5f273be7dd74d7 | revert changes in DataCenterLimits.cs as the Hd...Limit gets returned as Disk...Limit | dfensgmbh/biz.dfch.CS.Abiquo.Client | src/biz.dfch.CS.Abiquo.Client/v1/Model/DataCenterLimits.cs | src/biz.dfch.CS.Abiquo.Client/v1/Model/DataCenterLimits.cs | /**
* Copyright 2016 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.ComponentModel.DataAnnotations;
namespace biz.dfch.CS.Abiquo.Client.v1.Model
{
public class DataCenterLimits : AbiquoLinkBaseDto
{
[Required]
[Range(0, Int32.MaxValue)]
public int CpuCountHardLimit { get; set; }
[Required]
[Range(0, Int32.MaxValue)]
public int CpuCountSoftLimit { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long DiskHardLimitInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long DiskSoftLimitInMb { get; set; }
public int Id { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long PublicIpsHard { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long PublicIpsSoft { get; set; }
[Required]
[Range(0, Int32.MaxValue)]
public int RamHardLimitInMb { get; set; }
[Required]
[Range(0, Int32.MaxValue)]
public int RamSoftLimitInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long RepositoryHardInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long RepositorySoftInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long StorageHardInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long StorageSoftInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long VlansHard { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long VlansSoft { get; set; }
}
}
| /**
* Copyright 2016 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.ComponentModel.DataAnnotations;
namespace biz.dfch.CS.Abiquo.Client.v1.Model
{
public class DataCenterLimits : AbiquoLinkBaseDto
{
[Required]
[Range(0, Int32.MaxValue)]
public int CpuCountHardLimit { get; set; }
[Required]
[Range(0, Int32.MaxValue)]
public int CpuCountSoftLimit { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long DiskHardLimitInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long DiskSoftLimitInMb { get; set; }
public int Id { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long PublicIpsHard { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long PublicIpsSoft { get; set; }
[Required]
[Range(0, Int32.MaxValue)]
public int RamHardLimitInMb { get; set; }
[Required]
[Range(0, Int32.MaxValue)]
public int RamSoftLimitInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long RepositoryHardInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long RepositorySoftInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long StorageHardInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long StorageSoftInMb { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long VlansHard { get; set; }
[Required]
[Range(0, Int64.MaxValue)]
public long VlansSoft { get; set; }
//extended
[Range(0, Int64.MaxValue)]
public long HdSoftLimitInMb { get; set; }
[Range(0, Int64.MaxValue)]
public long HdHardLimitInMb { get; set; }
}
}
| apache-2.0 | C# |
0a99d9617d9e7e9a2d7ce07a0e6bccf408733527 | Update IBattery.shared.cs | jamesmontemagno/BatteryPlugin | src/Battery.Plugin/IBattery.shared.cs | src/Battery.Plugin/IBattery.shared.cs | using System;
namespace Plugin.Battery.Abstractions
{
/// <summary>
/// Interface for Battery
/// </summary>
public interface IBattery : IDisposable
{
/// <summary>
/// Current battery level 0 - 100
/// </summary>
int RemainingChargePercent { get; }
/// <summary>
/// Current status of the battery
/// </summary>
BatteryStatus Status { get; }
/// <summary>
/// Currently how the battery is being charged.
/// </summary>
PowerSource PowerSource { get; }
/// <summary>
/// Event handler when battery changes
/// </summary>
event BatteryChangedEventHandler BatteryChanged;
}
/// <summary>
/// Arguments to pass to event handlers
/// </summary>
public class BatteryChangedEventArgs : EventArgs
{
/// <summary>
/// If the battery level is considered low
/// </summary>
public bool IsLow { get; set; }
/// <summary>
/// Gets the remaining charge percentage of the battery
/// </summary>
public int RemainingChargePercent { get; set; }
/// <summary>
/// Current status of battery
/// </summary>
public BatteryStatus Status { get; set; }
/// <summary>
/// Get the source of power.
/// </summary>
public PowerSource PowerSource { get; set; }
}
/// <summary>
/// Battery Level changed event handlers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void BatteryChangedEventHandler(object sender, BatteryChangedEventArgs e);
}
| using System;
namespace Plugin.Battery.Abstractions
{
/// <summary>
/// Interface for Battery
/// </summary>
public interface IBattery : IDisposable
{
/// <summary>
/// Current battery level 0 - 100
/// </summary>
int RemainingChargePercent { get; }
/// <summary>
/// Current status of the battery
/// </summary>
BatteryStatus Status { get; }
/// <summary>
/// Currently how the battery is being charged.
/// </summary>
PowerSource PowerSource { get; }
/// <summary>
/// Event handler when battery changes
/// </summary>
event BatteryChangedEventHandler BatteryChanged;
}
/// <summary>
/// Arguments to pass to event handlers
/// </summary>
public class BatteryChangedEventArgs : EventArgs
{
/// <summary>
/// If the battery level is considered low
/// </summary>
public bool IsLow { get; set; }
/// <summary>
/// Gets if there is an active internet connection
/// </summary>
public int RemainingChargePercent { get; set; }
/// <summary>
/// Current status of battery
/// </summary>
public BatteryStatus Status { get; set; }
/// <summary>
/// Get the source of power.
/// </summary>
public PowerSource PowerSource { get; set; }
}
/// <summary>
/// Battery Level changed event handlers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void BatteryChangedEventHandler(object sender, BatteryChangedEventArgs e);
}
| mit | C# |
46448980dadfb0bf5861f6122f6e16a4c07695ff | Remove .netstandard1.3 from build.cake | AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp | build.cake | build.cake | var target = Argument("target", "Default");
var projectName = "AngleSharp";
var solutionName = "AngleSharp.Core";
var frameworks = new Dictionary<String, String>
{
{ "net46", "net46" },
{ "net461", "net461" },
{ "net472", "net472" },
{ "netstandard2.0", "netstandard2.0" },
};
#load tools/anglesharp.cake
RunTarget(target);
| var target = Argument("target", "Default");
var projectName = "AngleSharp";
var solutionName = "AngleSharp.Core";
var frameworks = new Dictionary<String, String>
{
{ "net46", "net46" },
{ "net461", "net461" },
{ "net472", "net472" },
{ "netstandard1.3", "netstandard1.3" },
{ "netstandard2.0", "netstandard2.0" },
};
#load tools/anglesharp.cake
RunTarget(target);
| mit | C# |
36fb382b3754a550ea807b2a9dd149cb3c808c41 | Rename enum value | bartlomiejwolk/ActionTrigger | Enums/TriggerType.cs | Enums/TriggerType.cs | // Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com)
//
// This file is part of the ActionTrigger extension for Unity.
// Licensed under the MIT license. See LICENSE file in the project root folder.
namespace ActionTrigger {
public enum TriggerType { OnTriggerEnter, OnTriggerExit, ExternalCall }
} | // Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com)
//
// This file is part of the ActionTrigger extension for Unity.
// Licensed under the MIT license. See LICENSE file in the project root folder.
namespace ActionTrigger {
public enum TriggerType { OnTriggerEnter, OnTriggerExit, Method }
} | mit | C# |
9f23080cf8df6d2e74d7ee695b6b40dc1055fa63 | Fix parameters supported in `Recurring` for `PriceData` across the API | stripe/stripe-dotnet | src/Stripe.net/Services/SubscriptionItems/SubscriptionItemPriceDataRecurringOptions.cs | src/Stripe.net/Services/SubscriptionItems/SubscriptionItemPriceDataRecurringOptions.cs | namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class SubscriptionItemPriceDataRecurringOptions : INestedOptions
{
/// <summary>
/// he frequency at which a subscription is billed. One of <c>day</c>, <c>week</c>,
/// <c>month</c> or <c>year</c>.
/// </summary>
[JsonProperty("interval")]
public string Interval { get; set; }
/// <summary>
/// The number of intervals (specified in the <see cref="Interval"/> property) between
/// subscription billings.
/// </summary>
[JsonProperty("interval_count")]
public long? IntervalCount { get; set; }
}
}
| namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class SubscriptionItemPriceDataRecurringOptions : INestedOptions
{
/// <summary>
/// Specifies a usage aggregation strategy for prices where <see cref="UsageType"/> is
/// <c>metered</c>. Allowed values are <c>sum</c> for summing up all usage during a period,
/// <c>last_during_period</c> for picking the last usage record reported within a period,
/// <c>last_ever</c> for picking the last usage record ever (across period bounds) or
/// <c>max</c> which picks the usage record with the maximum reported usage during a
/// period. Defaults to <c>sum</c>.
/// </summary>
[JsonProperty("aggregate_usage")]
public string AggregateUsage { get; set; }
/// <summary>
/// he frequency at which a subscription is billed. One of <c>day</c>, <c>week</c>,
/// <c>month</c> or <c>year</c>.
/// </summary>
[JsonProperty("interval")]
public string Interval { get; set; }
/// <summary>
/// The number of intervals (specified in the <see cref="Interval"/> property) between
/// subscription billings.
/// </summary>
[JsonProperty("interval_count")]
public long? IntervalCount { get; set; }
/// <summary>
/// Default number of trial days when subscribing a customer to this price using
/// <c>trial_from_price=true</c>.
/// </summary>
[JsonProperty("trial_period_days")]
public long? TrialPeriodDays { get; set; }
/// <summary>
/// Configures how the quantity per period should be determined, can be either
/// <c>metered</c> or <c>licensed</c>. <c>licensed</c> will automatically bill the quantity
/// set for a price when adding it to a subscription, <c>metered</c> will aggregate the
/// total usage based on usage records. Defaults to <c>licensed</c>.
/// </summary>
[JsonProperty("usage_type")]
public string UsageType { get; set; }
}
}
| apache-2.0 | C# |
1a89e65745cfb5aa1459321e7eaa5b228984ae24 | Fix bad maths in Memory Map. | DanTup/DaNES | DaNES.Emulation/MemoryMap.cs | DaNES.Emulation/MemoryMap.cs | using System;
using System.Linq;
namespace DanTup.DaNES.Emulation
{
class MemoryMap
{
Memory working = new Memory(0x800);
Memory registers = new Memory(0x20);
Memory expansion = new Memory(0x1FDF);
Memory sram = new Memory(0x2000);
Memory cart1;
Memory cart2;
Ppu ppu;
public MemoryMap(Ppu ppu)
{
this.ppu = ppu;
}
public void LoadCart(params byte[] program)
{
if (program.Length > 0x4000)
{
cart1 = new Memory(0x4000);
cart2 = new Memory(0x4000);
cart1.Write(0x0, new ArraySegment<byte>(program, 0, 0x4000).ToArray());
cart2.Write(0x0, new ArraySegment<byte>(program, 0x4000, 0x4000).ToArray());
}
else
{
cart1 = new Memory(0x4000);
cart2 = cart1;
cart1.Write(0x0, program);
}
}
public byte Read(ushort address)
{
if (address < 0x2000)
return working.Read((ushort)(address % 0x800));
else if (address < 0x4000)
return ppu.ReadRegister((ushort)(0x2000 + ((address - 0x2000) % 8)));
else if (address < 0x4020)
return registers.Read((ushort)(address - 0x4000));
else if (address < 0x8000)
return sram.Read((ushort)(address - 0x4020));
else if (address < 0xC000)
return cart1.Read((ushort)(address - 0x8000));
else
return cart2.Read((ushort)(address - 0xC000));
}
public byte Write(ushort address, byte value)
{
if (address < 0x2000)
return working.Write((ushort)(address % 0x800), value);
else if (address < 0x4000)
return ppu.WriteRegister((ushort)(0x2000 + ((address - 0x2000) % 8)), value);
else if (address < 0x4020)
return registers.Write((ushort)(address - 0x4000), value);
else if (address < 0x8000)
return sram.Write((ushort)(address - 0x4020), value);
else if (address < 0xC000)
return cart1.Write((ushort)(address - 0x8000), value);
else
return cart2.Write((ushort)(address - 0xC000), value);
}
}
}
| using System;
using System.Linq;
namespace DanTup.DaNES.Emulation
{
class MemoryMap
{
Memory working = new Memory(0x800);
Memory registers = new Memory(0x20);
Memory expansion = new Memory(0x1FDF);
Memory sram = new Memory(0x2000);
Memory cart1;
Memory cart2;
Ppu ppu;
public MemoryMap(Ppu ppu)
{
this.ppu = ppu;
}
public void LoadCart(params byte[] program)
{
if (program.Length > 0x4000)
{
cart1 = new Memory(0x4000);
cart2 = new Memory(0x4000);
cart1.Write(0x0, new ArraySegment<byte>(program, 0, 0x4000).ToArray());
cart2.Write(0x0, new ArraySegment<byte>(program, 0x4000, 0x4000).ToArray());
}
else
{
cart1 = new Memory(0x4000);
cart2 = cart1;
cart1.Write(0x0, program);
}
}
public byte Read(ushort address)
{
if (address < 0x2000)
return working.Read((ushort)(address % 0x800));
else if (address < 0x4000)
return ppu.ReadRegister((ushort)(0x2000 + ((address - 0x2000) % 8)));
else if (address < 0x4020)
return registers.Read((ushort)(address - 0x4020));
else if (address < 0x8000)
return sram.Read((ushort)(address - 0x4020));
else if (address < 0xC000)
return cart1.Read((ushort)(address - 0x8000));
else
return cart2.Read((ushort)(address - 0xC000));
}
public byte Write(ushort address, byte value)
{
if (address < 0x2000)
return working.Write((ushort)(address % 0x800), value);
else if (address < 0x4000)
return ppu.WriteRegister((ushort)(0x2000 + ((address - 0x2000) % 8)), value);
else if (address < 0x4020)
return registers.Write((ushort)(address - 0x4020), value);
else if (address < 0x8000)
return sram.Write((ushort)(address - 0x4020), value);
else if (address < 0xC000)
return cart1.Write((ushort)(address - 0x8000), value);
else
return cart2.Write((ushort)(address - 0xC000), value);
}
}
}
| mit | C# |
2fc6b6f41863613b400c7810ee7ac040264f98e8 | Remove unused dependencies | noobot/SlackConnector | src/SlackConnector.Tests.Unit/SlackConnectionTests/PingTests.cs | src/SlackConnector.Tests.Unit/SlackConnectionTests/PingTests.cs | using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using SlackConnector.Connections.Sockets;
using SlackConnector.Connections.Sockets.Messages.Outbound;
using SlackConnector.Models;
namespace SlackConnector.Tests.Unit.SlackConnectionTests
{
internal class PingTests
{
[Test, AutoMoqData]
public async Task should_send_ping(Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
{
// given
const string slackKey = "key-yay";
var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey };
await slackConnection.Initialise(connectionInfo);
// when
await slackConnection.Ping();
// then
webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>()));
}
}
} | using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Ploeh.AutoFixture.NUnit3;
using SlackConnector.Connections;
using SlackConnector.Connections.Sockets;
using SlackConnector.Connections.Sockets.Messages.Outbound;
using SlackConnector.Models;
namespace SlackConnector.Tests.Unit.SlackConnectionTests
{
internal class PingTests
{
[Test, AutoMoqData]
public async Task should_send_ping([Frozen]Mock<IConnectionFactory> connectionFactory,
Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
{
// given
const string slackKey = "key-yay";
var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey };
await slackConnection.Initialise(connectionInfo);
// when
await slackConnection.Ping();
// then
webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>()));
}
}
} | mit | C# |
03a3610b45305bd68b3a2f702bfed7bece2b1c5d | Add missing override | hey-red/Mime | src/Mime/MagicException.cs | src/Mime/MagicException.cs | using System;
namespace HeyRed.Mime
{
public class MagicException : Exception
{
public MagicException()
{
}
public MagicException(string message) : base(message)
{
}
public MagicException(string message, string additionalInfo) : base(message ?? additionalInfo)
{
}
public MagicException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
| using System;
namespace HeyRed.Mime
{
public class MagicException : Exception
{
public MagicException()
{
}
public MagicException(string message) : base(message)
{
}
public MagicException(string message, string additionalInfo) : base(message ?? additionalInfo)
{
}
}
}
| mit | C# |
215547f59924683e378da334f0445e2697728e49 | Add usage comment to interface | heejaechang/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,dotnet/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,genlu/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,tannergooding/roslyn,dotnet/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,weltkante/roslyn,AmadeusW/roslyn,tmat/roslyn,panopticoncentral/roslyn,tmat/roslyn,mavasani/roslyn,aelij/roslyn,AmadeusW/roslyn,eriawan/roslyn,physhi/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,genlu/roslyn,KirillOsenkov/roslyn,tannergooding/roslyn,jmarolf/roslyn,aelij/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,sharwell/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,brettfo/roslyn,sharwell/roslyn,sharwell/roslyn,diryboy/roslyn,heejaechang/roslyn,genlu/roslyn,physhi/roslyn,eriawan/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,diryboy/roslyn,weltkante/roslyn,AlekseyTs/roslyn,weltkante/roslyn,brettfo/roslyn,KirillOsenkov/roslyn,aelij/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,stephentoub/roslyn,bartdesmet/roslyn,physhi/roslyn,jmarolf/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,gafter/roslyn,KevinRansom/roslyn,mavasani/roslyn,gafter/roslyn,gafter/roslyn,mavasani/roslyn | src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptRemoteLanguageServiceWorkspace.cs | src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptRemoteLanguageServiceWorkspace.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
/// <summary>
/// Used to acquire the RemoteLanguageServiceWorkspace. Its members should be accessed by casting to <see cref="Workspace"/>.
/// </summary>
interface IVsTypeScriptRemoteLanguageServiceWorkspace
{
}
}
| // 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.
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
interface IVsTypeScriptRemoteLanguageServiceWorkspace
{
}
}
| mit | C# |
05418dd18af08d67639d1ef97b4c2782210c69ff | Use corefx implementation | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Server.Kestrel/Infrastructure/LongExtensions.cs | src/Microsoft.AspNet.Server.Kestrel/Infrastructure/LongExtensions.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.
namespace Microsoft.AspNet.Server.Kestrel.Extensions
{
public static class LongExtensions
{
public static int BitCount(this long value)
{
// see https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/BitArithmetic.cs
const ulong Mask01010101 = 0x5555555555555555UL;
const ulong Mask00110011 = 0x3333333333333333UL;
const ulong Mask00001111 = 0x0F0F0F0F0F0F0F0FUL;
const ulong Mask00000001 = 0x0101010101010101UL;
var v = (ulong)value;
v = v - ((v >> 1) & Mask01010101);
v = (v & Mask00110011) + ((v >> 2) & Mask00110011);
return (int)(unchecked(((v + (v >> 4)) & Mask00001111) * Mask00000001) >> 56);
}
}
}
| // 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.
namespace Microsoft.AspNet.Server.Kestrel.Extensions
{
public static class LongExtensions
{
public static int BitCount(this long value)
{
// Parallel bit count for a 64-bit integer
var v = (ulong)value;
v = v - ((v >> 1) & 0x5555555555555555);
v = (v & 0x3333333333333333) + ((v >> 2) & 0x3333333333333333);
v = (v + (v >> 4) & 0x0f0f0f0f0f0f0f0f);
return (int)((v * 0x0101010101010101) >> 56);
}
}
}
| apache-2.0 | C# |
750ff208a1c772309b615063b7e4828fa88bc3f4 | Remove OpenIddictTokenDescriptor.Properties | openiddict/openiddict-core,openiddict/core,openiddict/openiddict-core,openiddict/openiddict-core,openiddict/core,openiddict/openiddict-core,openiddict/openiddict-core | src/OpenIddict.Abstractions/Descriptors/OpenIddictTokenDescriptor.cs | src/OpenIddict.Abstractions/Descriptors/OpenIddictTokenDescriptor.cs | using System;
using System.Security.Claims;
namespace OpenIddict.Abstractions
{
/// <summary>
/// Represents an OpenIddict token descriptor.
/// </summary>
public class OpenIddictTokenDescriptor
{
/// <summary>
/// Gets or sets the application identifier associated with the token.
/// </summary>
public string ApplicationId { get; set; }
/// <summary>
/// Gets or sets the authorization identifier associated with the token.
/// </summary>
public string AuthorizationId { get; set; }
/// <summary>
/// Gets or sets the creation date associated with the token.
/// </summary>
public DateTimeOffset? CreationDate { get; set; }
/// <summary>
/// Gets or sets the expiration date associated with the token.
/// </summary>
public DateTimeOffset? ExpirationDate { get; set; }
/// <summary>
/// Gets or sets the payload associated with the token.
/// </summary>
public string Payload { get; set; }
/// <summary>
/// Gets or sets the optional principal associated with the token.
/// Note: this property is not stored by the default token stores.
/// </summary>
public ClaimsPrincipal Principal { get; set; }
/// <summary>
/// Gets or sets the reference identifier associated with the token.
/// Note: depending on the application manager used when creating it,
/// this property may be hashed or encrypted for security reasons.
/// </summary>
public string ReferenceId { get; set; }
/// <summary>
/// Gets or sets the status associated with the token.
/// </summary>
public string Status { get; set; }
/// <summary>
/// Gets or sets the subject associated with the token.
/// </summary>
public string Subject { get; set; }
/// <summary>
/// Gets or sets the token type.
/// </summary>
public string Type { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace OpenIddict.Abstractions
{
/// <summary>
/// Represents an OpenIddict token descriptor.
/// </summary>
public class OpenIddictTokenDescriptor
{
/// <summary>
/// Gets or sets the application identifier associated with the token.
/// </summary>
public string ApplicationId { get; set; }
/// <summary>
/// Gets or sets the authorization identifier associated with the token.
/// </summary>
public string AuthorizationId { get; set; }
/// <summary>
/// Gets or sets the creation date associated with the token.
/// </summary>
public DateTimeOffset? CreationDate { get; set; }
/// <summary>
/// Gets or sets the expiration date associated with the token.
/// </summary>
public DateTimeOffset? ExpirationDate { get; set; }
/// <summary>
/// Gets or sets the payload associated with the token.
/// </summary>
public string Payload { get; set; }
/// <summary>
/// Gets or sets the optional principal associated with the token.
/// Note: this property is not stored by the default token stores.
/// </summary>
public ClaimsPrincipal Principal { get; set; }
/// <summary>
/// Gets the optional authentication properties associated with the token.
/// Note: this property is not stored by the default token stores.
/// </summary>
public IDictionary<string, string> Properties { get; } =
new Dictionary<string, string>(StringComparer.Ordinal);
/// <summary>
/// Gets or sets the reference identifier associated with the token.
/// Note: depending on the application manager used when creating it,
/// this property may be hashed or encrypted for security reasons.
/// </summary>
public string ReferenceId { get; set; }
/// <summary>
/// Gets or sets the status associated with the token.
/// </summary>
public string Status { get; set; }
/// <summary>
/// Gets or sets the subject associated with the token.
/// </summary>
public string Subject { get; set; }
/// <summary>
/// Gets or sets the token type.
/// </summary>
public string Type { get; set; }
}
}
| apache-2.0 | C# |
034a4b3ef6de9f9d0f0ea454dc6f5ac6973490d3 | Add long support to PluralizationUtility | SaberSnail/GoldenAnvil.Utility | GoldenAnvil.Utility/PluralizationUtility.cs | GoldenAnvil.Utility/PluralizationUtility.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Resources;
namespace GoldenAnvil.Utility
{
/// <summary>
/// This class enables the localization of pluralizable strings. This is based on the data available at
/// http://cldr.unicode.org/index/cldr-spec/plural-rules
/// </summary>
public static class PluralizationUtility
{
public static string Pluralize(this ResourceManager resources, string baseKey, long value)
{
var language = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
var pattern = s_patterns.GetValueOrDefault(language);
if (pattern == null)
throw new InvalidOperationException($"Unsupported pluralization language ({language}) in {nameof(PluralizationUtility)}.");
return resources.GetString(baseKey + pattern.GetCardinalRuleName(value));
}
private interface IPluralizationPattern
{
string GetCardinalRuleName(long value);
}
private class EnglishPattern : IPluralizationPattern
{
public string GetCardinalRuleName(long value)
{
if (value == 1)
return c_one;
return c_other;
}
}
const string c_one = "_One";
const string c_other = "_Other";
static Dictionary<string, IPluralizationPattern> s_patterns = new Dictionary<string, IPluralizationPattern>
{
{ "en", new EnglishPattern() },
};
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Resources;
namespace GoldenAnvil.Utility
{
/// <summary>
/// This class enables the localization of pluralizable strings. This is based on the data available at
/// http://cldr.unicode.org/index/cldr-spec/plural-rules
/// </summary>
public static class PluralizationUtility
{
public static string Pluralize(this ResourceManager resources, string baseKey, int value)
{
var language = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
var pattern = s_patterns.GetValueOrDefault(language);
if (pattern == null)
throw new InvalidOperationException($"Unsupported pluralization language ({language}) in {nameof(PluralizationUtility)}.");
return resources.GetString(baseKey + pattern.GetCardinalRuleName(value));
}
private interface IPluralizationPattern
{
string GetCardinalRuleName(int value);
}
private class EnglishPattern : IPluralizationPattern
{
public string GetCardinalRuleName(int value)
{
if (value == 1)
return c_one;
return c_other;
}
}
const string c_one = "_One";
const string c_other = "_Other";
static Dictionary<string, IPluralizationPattern> s_patterns = new Dictionary<string, IPluralizationPattern>
{
{ "en", new EnglishPattern() },
};
}
}
| mit | C# |
a9f06a179dbf97d90d18909668ba6064c0957e29 | Disable tests coverage for unsupported Unity versions | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Rider/UnityRiderUnitTestCoverageAvailabilityChecker.cs | resharper/resharper-unity/src/Rider/UnityRiderUnitTestCoverageAvailabilityChecker.cs | using System;
using JetBrains.Application;
using JetBrains.Application.Components;
using JetBrains.Collections.Viewable;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features;
using JetBrains.ReSharper.Host.Features.UnitTesting;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Rider.Model;
namespace JetBrains.ReSharper.Plugins.Unity.Rider
{
[ShellComponent]
public class UnityRiderUnitTestCoverageAvailabilityChecker : IRiderUnitTestCoverageAvailabilityChecker, IHideImplementation<DefaultRiderUnitTestCoverageAvailabilityChecker>
{
private static readonly Version ourMinSupportedUnityVersion = new Version(2018, 3);
// this method should be very fast as it gets called a lot
public HostProviderAvailability GetAvailability(IUnitTestElement element)
{
var solution = element.Id.Project.GetSolution();
var tracker = solution.GetComponent<UnitySolutionTracker>();
if (tracker.IsUnityProject.HasValue() && !tracker.IsUnityProject.Value)
return HostProviderAvailability.Available;
var rdUnityModel = solution.GetProtocolSolution().GetRdUnityModel();
switch (rdUnityModel.UnitTestPreference.Value)
{
case UnitTestLaunchPreference.NUnit:
return HostProviderAvailability.Available;
case UnitTestLaunchPreference.PlayMode:
return HostProviderAvailability.Nonexistent;
case UnitTestLaunchPreference.EditMode:
{
var unityVersion = UnityVersion.Parse(rdUnityModel.ApplicationVersion.Maybe.ValueOrDefault ?? string.Empty);
return unityVersion == null || unityVersion < ourMinSupportedUnityVersion
? HostProviderAvailability.Nonexistent
: HostProviderAvailability.Available;
}
default:
return HostProviderAvailability.Nonexistent;
}
}
}
} | using JetBrains.Application;
using JetBrains.Application.Components;
using JetBrains.Collections.Viewable;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features;
using JetBrains.ReSharper.Host.Features.UnitTesting;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Rider.Model;
namespace JetBrains.ReSharper.Plugins.Unity.Rider
{
[ShellComponent]
public class UnityRiderUnitTestCoverageAvailabilityChecker : IRiderUnitTestCoverageAvailabilityChecker, IHideImplementation<DefaultRiderUnitTestCoverageAvailabilityChecker>
{
// this method should be very fast as it gets called a lot
public HostProviderAvailability GetAvailability(IUnitTestElement element)
{
var solution = element.Id.Project.GetSolution();
var tracker = solution.GetComponent<UnitySolutionTracker>();
if (tracker.IsUnityProject.HasValue() && !tracker.IsUnityProject.Value)
return HostProviderAvailability.Available;
var rdUnityModel = solution.GetProtocolSolution().GetRdUnityModel();
if (rdUnityModel.UnitTestPreference.Value != UnitTestLaunchPreference.PlayMode)
return HostProviderAvailability.Available;
return HostProviderAvailability.Nonexistent;
}
}
} | apache-2.0 | C# |
d1c28a6a1b3dd6e3697a30497c5f3c249552541b | implement View Inbox | marc1404/GmailNotifier | GmailNotifier/MailForm.cs | GmailNotifier/MailForm.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GmailNotifier
{
public class MailForm : Form
{
private ContextMenu trayMenu;
private NotifyIcon trayIcon;
public MailForm()
{
trayMenu = initTrayMenu();
trayIcon = initTrayIcon(trayMenu);
}
protected override void OnLoad(EventArgs e)
{
this.Visible = false;
this.ShowInTaskbar = false;
}
private void onViewInbox(object sender, EventArgs e)
{
Process.Start("https://mail.google.com/mail");
}
private void onExit(object sender, EventArgs e)
{
Application.Exit();
}
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
trayIcon.Dispose();
}
base.Dispose(isDisposing);
}
private ContextMenu initTrayMenu()
{
ContextMenu trayMenu = new ContextMenu();
MenuItem viewInbox = new MenuItem("View Inbox", onViewInbox);
viewInbox.DefaultItem = true;
trayMenu.MenuItems.Add(viewInbox);
trayMenu.MenuItems.Add("Check Mail Now");
trayMenu.MenuItems.Add("Tell me Again...");
trayMenu.MenuItems.Add("Options");
trayMenu.MenuItems.Add("About...");
trayMenu.MenuItems.Add("-");
trayMenu.MenuItems.Add("Exit", onExit);
return trayMenu;
}
private NotifyIcon initTrayIcon(ContextMenu trayMenu)
{
NotifyIcon trayIcon = new NotifyIcon();
trayIcon.Text = "No unread mail";
trayIcon.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;
return trayIcon;
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GmailNotifier
{
public class MailForm : Form
{
private ContextMenu trayMenu;
private NotifyIcon trayIcon;
public MailForm()
{
trayMenu = initTrayMenu();
trayIcon = initTrayIcon(trayMenu);
}
protected override void OnLoad(EventArgs e)
{
this.Visible = false;
this.ShowInTaskbar = false;
}
private void onExit(object sender, EventArgs e)
{
Application.Exit();
}
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
trayIcon.Dispose();
}
base.Dispose(isDisposing);
}
private ContextMenu initTrayMenu()
{
ContextMenu trayMenu = new ContextMenu();
MenuItem viewInbox = new MenuItem("View Inbox");
viewInbox.DefaultItem = true;
trayMenu.MenuItems.Add(viewInbox);
trayMenu.MenuItems.Add("Check Mail Now");
trayMenu.MenuItems.Add("Tell me Again...");
trayMenu.MenuItems.Add("Options");
trayMenu.MenuItems.Add("About...");
trayMenu.MenuItems.Add("-");
trayMenu.MenuItems.Add("Exit", onExit);
return trayMenu;
}
private NotifyIcon initTrayIcon(ContextMenu trayMenu)
{
NotifyIcon trayIcon = new NotifyIcon();
trayIcon.Text = "No unread mail";
trayIcon.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;
return trayIcon;
}
}
}
| mit | C# |
cbfd5157a692089979ec2f2390d429333a20b2bf | Fix stylecop issues | pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,Microsoft/ApplicationInsights-dotnet | src/Core/Managed/Shared/Extensibility/Implementation/InternalContext.cs | src/Core/Managed/Shared/Extensibility/Implementation/InternalContext.cs | namespace Microsoft.ApplicationInsights.Extensibility.Implementation
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility.Implementation.External;
/// <summary>
/// Encapsulates Internal information.
/// </summary>
public sealed class InternalContext
{
private readonly IDictionary<string, string> tags;
internal InternalContext(IDictionary<string, string> tags)
{
this.tags = tags;
}
/// <summary>
/// Gets or sets application insights SDK version.
/// </summary>
public string SdkVersion
{
get { return this.tags.GetTagValueOrNull(ContextTagKeys.Keys.InternalSdkVersion); }
set { this.tags.SetStringValueOrRemove(ContextTagKeys.Keys.InternalSdkVersion, value); }
}
/// <summary>
/// Gets or sets application insights agent version.
/// </summary>
public string AgentVersion
{
get { return this.tags.GetTagValueOrNull(ContextTagKeys.Keys.InternalAgentVersion); }
set { this.tags.SetStringValueOrRemove(ContextTagKeys.Keys.InternalAgentVersion, value); }
}
/// <summary>
/// Gets or sets node name for the billing purposes. Use this filed to override the standard way node names got detected.
/// </summary>
public string NodeName
{
get { return this.tags.GetTagValueOrNull(ContextTagKeys.Keys.InternalNodeName); }
set { this.tags.SetStringValueOrRemove(ContextTagKeys.Keys.InternalNodeName, value); }
}
}
}
| namespace Microsoft.ApplicationInsights.Extensibility.Implementation
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility.Implementation.External;
/// <summary>
/// Encapsulates Internal information.
/// </summary>
public sealed class InternalContext
{
private readonly IDictionary<string, string> tags;
internal InternalContext(IDictionary<string, string> tags)
{
this.tags = tags;
}
/// <summary>
/// Gets or sets application insights SDK version.
/// </summary>
public string SdkVersion
{
get { return this.tags.GetTagValueOrNull(ContextTagKeys.Keys.InternalSdkVersion); }
set { this.tags.SetStringValueOrRemove(ContextTagKeys.Keys.InternalSdkVersion, value); }
}
/// <summary>
/// Gets or sets application insights agent version.
/// </summary>
public string AgentVersion
{
get { return this.tags.GetTagValueOrNull(ContextTagKeys.Keys.InternalAgentVersion); }
set { this.tags.SetStringValueOrRemove(ContextTagKeys.Keys.InternalAgentVersion, value); }
}
/// <summary>
/// Node name for the billing purposes. Use this filed to override the standard way node names got detected.
/// </summary>
public string NodeName
{
get { return this.tags.GetTagValueOrNull(ContextTagKeys.Keys.InternalNodeName); }
set { this.tags.SetStringValueOrRemove(ContextTagKeys.Keys.InternalNodeName, value); }
}
}
}
| mit | C# |
1778900ab47bc4642372e3623a401d45bfd3fc91 | Fix using | Xablu/Xablu.WebApiClient | src/Xablu.WebApiClient/HttpExtensions/WebApiClientProgressExtensions.cs | src/Xablu.WebApiClient/HttpExtensions/WebApiClientProgressExtensions.cs | using System.Threading;
using System.Threading.Tasks;
using Fusillade;
using Xablu.WebApiClient.HttpContentExtensions;
namespace Xablu.WebApiClient.HttpExtensions
{
public static class WebApiClientProgressExtension
{
public static async Task<TResult> PostAsync<TContent, TResult>(this WebApiClient webApiClient, Priority priority, string path, TContent content = default(TContent), ProgressDelegate progressDelegate = null, IHttpContentResolver contentResolver = null)
{
var httpClient = webApiClient.GetWebApiClient(priority);
webApiClient.SetHttpRequestHeaders(httpClient);
var httpContent = webApiClient.ResolveHttpContent(content);
var stream = await httpContent.ReadAsStreamAsync();
var progressContent = new ProgressStreamContent(httpContent.Headers, stream, CancellationToken.None);
progressContent.Progress = progressDelegate;
var response = await httpClient
.PostAsync(path, progressContent)
.ConfigureAwait(false);
if (!await response.EnsureSuccessStatusCodeAsync())
return default(TResult);
return await webApiClient.HttpResponseResolver.ResolveHttpResponseAsync<TResult>(response);
}
}
}
| using System.Threading;
using System.Threading.Tasks;
using Fusillade;
using Xablu.WebApiClient.HttpExtensions;
namespace Xablu.WebApiClient.HttpExtensions
{
public static class WebApiClientProgressExtension
{
public static async Task<TResult> PostAsync<TContent, TResult>(this WebApiClient webApiClient, Priority priority, string path, TContent content = default(TContent), ProgressDelegate progressDelegate = null, IHttpContentResolver contentResolver = null)
{
var httpClient = webApiClient.GetWebApiClient(priority);
webApiClient.SetHttpRequestHeaders(httpClient);
var httpContent = webApiClient.ResolveHttpContent(content);
var stream = await httpContent.ReadAsStreamAsync();
var progressContent = new ProgressStreamContent(httpContent.Headers, stream, CancellationToken.None);
progressContent.Progress = progressDelegate;
var response = await httpClient
.PostAsync(path, progressContent)
.ConfigureAwait(false);
if (!await response.EnsureSuccessStatusCodeAsync())
return default(TResult);
return await webApiClient.HttpResponseResolver.ResolveHttpResponseAsync<TResult>(response);
}
}
}
| mit | C# |
072999ba42ebc8c03f5ab65d854e295a04d9f4f5 | Update NotesRepository.cs | CarmelSoftware/MVCDataRepositoryXML | Models/NotesRepository.cs | Models/NotesRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace IoCDependencyInjection.Models
{
public class NotesRepository : INotesRepository
{
private List<Note> notes = new List<Note>();
private int iNumberOfEntries = 1;
private XDocument doc;
public NotesRepository()
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace IoCDependencyInjection.Models
{
public class NotesRepository : INotesRepository
{
private List<Note> notes = new List<Note>();
private int iNumberOfEntries = 1;
private XDocument doc;
| mit | C# |
c04cff91c7411481799ccc17dce77b9e259dda3b | use errorMessage overload in UserConnections | AlejandroCano/framework,avifatal/framework,signumsoftware/framework,AlejandroCano/framework,signumsoftware/framework,avifatal/framework | Signum.Engine/Connection/UserConnections.cs | Signum.Engine/Connection/UserConnections.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Signum.Engine;
using System.Data.SqlClient;
using System.Diagnostics;
using Signum.Engine.Maps;
using Signum.Utilities;
using System.Text.RegularExpressions;
namespace Signum.Engine
{
public static class UserConnections
{
public static string FileName = @"C:\UserConnections.txt";
static Dictionary<string, string> replacements = null;
public static Dictionary<string, string> LoadReplacements()
{
if (!File.Exists(FileName))
return new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
return File.ReadAllLines(FileName).Where(s=> !string.IsNullOrWhiteSpace(s) && !s.StartsWith("-") && !s.StartsWith("/")).ToDictionary(a => a.Before('>'), a => a.After('>'), "UserConnections");
}
public static string Replace(string connectionString)
{
if (replacements == null)
replacements = LoadReplacements();
Match m = Regex.Match(connectionString, @"(Initial Catalog|Database)\s*=\s*(?<databaseName>[^;]*)\s*;?", RegexOptions.IgnoreCase);
if (!m.Success)
throw new InvalidOperationException("Database name not found");
string databaseName = m.Groups["databaseName"].Value;
return replacements.TryGetC(databaseName) ?? connectionString;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Signum.Engine;
using System.Data.SqlClient;
using System.Diagnostics;
using Signum.Engine.Maps;
using Signum.Utilities;
using System.Text.RegularExpressions;
namespace Signum.Engine
{
public static class UserConnections
{
public static string FileName = @"C:\UserConnections.txt";
static Dictionary<string, string> replacements = null;
public static Dictionary<string, string> LoadReplacements()
{
if (!File.Exists(FileName))
return new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
return File.ReadAllLines(FileName).Where(s=> !string.IsNullOrWhiteSpace(s) && !s.StartsWith("-") && !s.StartsWith("/")).ToDictionary(a => a.Before('>'), a => a.After('>'));
}
public static string Replace(string connectionString)
{
if (replacements == null)
replacements = LoadReplacements();
Match m = Regex.Match(connectionString, @"(Initial Catalog|Database)\s*=\s*(?<databaseName>[^;]*)\s*;?", RegexOptions.IgnoreCase);
if (!m.Success)
throw new InvalidOperationException("Database name not found");
string databaseName = m.Groups["databaseName"].Value;
return replacements.TryGetC(databaseName) ?? connectionString;
}
}
}
| mit | C# |
49d0e92978ca2beb922731743091a7e8a29747f2 | fix comment | mnadel/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,etishor/Metrics.NET,mnadel/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,Recognos/Metrics.NET,ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,Liwoj/Metrics.NET,Liwoj/Metrics.NET,huoxudong125/Metrics.NET,DeonHeyns/Metrics.NET,etishor/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET | Src/Metrics/Gauge.cs | Src/Metrics/Gauge.cs |
namespace Metrics
{
/// <summary>
/// A gauge is the simplest metric type. It just represents a value.
/// No operation can be triggered on the metric directly.
/// Custom implementations can hook into any value provider.
/// <see cref="Core.FunctionGauge"/> and <see cref="Core.DerivedGauge"/>
/// </summary>
public interface Gauge : Utils.IHideObjectMembers
{
}
/// <summary>
/// Combines the value of a gauge with the defined unit for the value.
/// </summary>
public sealed class GaugeValueSource : MetricValueSource<double>
{
public GaugeValueSource(string name, MetricValueProvider<double> value, Unit unit)
: base(name, value, unit)
{ }
}
}
|
namespace Metrics
{
/// <summary>
/// A gauge is the simplest metric type. It just returns a value.
/// No operation can be triggered on the metric directly.
/// Custom implementations can hook into any value provider.
/// <see cref="Core.FunctionGauge"/> and <see cref="Core.DerivedGauge"/>
/// </summary>
public interface Gauge : Utils.IHideObjectMembers
{
}
/// <summary>
/// Combines the value of a gauge with the defined unit for the value.
/// </summary>
public sealed class GaugeValueSource : MetricValueSource<double>
{
public GaugeValueSource(string name, MetricValueProvider<double> value, Unit unit)
: base(name, value, unit)
{ }
}
}
| apache-2.0 | C# |
c26ff1a55d63f626e52062cc5ce5677ae55d4b7f | fix URL | mayuki/RadioWhip | KnightsOfSidonia-News.cshtml | KnightsOfSidonia-News.cshtml | @RadioWhip.Feedify(
"http://www.knightsofsidonia.com/news/",
"シドニアの騎士|新着情報",
(content, cq) =>
{
return cq[".detail"]
.Select(x => x.Cq())
.Select(x => new RadioWhip.Entry
{
Title = System.Text.RegularExpressions.Regex.Replace(x.Find("h3").Text(), @"^\d\.\d+\.\d+", "").Trim(),
Url = "http://www.knightsofsidonia.com/news/#" + x.Attr("id"),
Content = x.Find(".text").Html(),
Updated = DateTime.ParseExact(x.Find(".newsdate").Text().Trim(), "yyyy.M.d", null)
});
}) | @RadioWhip.Feedify(
"http://www.knightsofsidonia.com/news/",
"シドニアの騎士|新着情報",
(content, cq) =>
{
return cq[".detail"]
.Select(x => x.Cq())
.Select(x => new RadioWhip.Entry
{
Title = System.Text.RegularExpressions.Regex.Replace(x.Find("h3").Text(), @"^\d\.\d+\.\d+", "").Trim(),
Url = "http://www.knightsofsidonia.com/news/" + x.Attr("id"),
Content = x.Find(".text").Html(),
Updated = DateTime.ParseExact(x.Find(".newsdate").Text().Trim(), "yyyy.M.d", null)
});
}) | mit | C# |
cb9aecd83f8636aff8c657ee82eddacd6e7f2d4d | Make Response<T> a class (#7741) | ayeletshpigelman/azure-sdk-for-net,markcowl/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,stankovski/azure-sdk-for-net,hyonholee/azure-sdk-for-net,hyonholee/azure-sdk-for-net,hyonholee/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,stankovski/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net | sdk/core/Azure.Core/src/Response{T}.cs | sdk/core/Azure.Core/src/Response{T}.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.ComponentModel;
namespace Azure
{
public class Response<T>
{
private readonly Response _rawResponse;
public Response(Response response, T parsed)
{
_rawResponse = response;
Value = parsed;
}
public virtual Response GetRawResponse() => _rawResponse;
public virtual T Value { get; }
public static implicit operator T(Response<T> response) => response.Value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => base.Equals(obj);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => base.GetHashCode();
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString() => base.ToString();
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.ComponentModel;
namespace Azure
{
public readonly struct Response<T>
{
private readonly Response _rawResponse;
public Response(Response response, T parsed)
{
_rawResponse = response;
Value = parsed;
}
public Response GetRawResponse() => _rawResponse;
public T Value { get; }
public static implicit operator T(Response<T> response) => response.Value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => base.Equals(obj);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => base.GetHashCode();
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString() => base.ToString();
}
}
| mit | C# |
bf4620665bfb5bfb58a3f6479f576564844439ea | use vanilla disqus js | MacsDickinson/blog,MacsDickinson/blog | Snow/_layouts/post.cshtml | Snow/_layouts/post.cshtml | @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<Snow.ViewModels.PostViewModel>
@using System.Collections.Generic
@{
Layout = "default.cshtml";
}
@section menu {
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav sf-menu">
<li class="current"><a href="/">Blog</a></li>
<!--<li><a href="/projects">Projects</a></li>-->
<li><a href="/categories">Categories</a></li>
<li><a href="/archive">Archive</a></li>
</ul>
</div>
}
<div class="post">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h2>
@Model.Title
<span>@Model.PostDate.ToString("dd MMM yyyy")</span>
</h2>
<p>
@foreach (var category in Model.Categories) {
<a class="btn btn-default btn-sm" href="/category/@category.Url"><i class="fa fa-tag"></i> @category.Name</a>
}
</p>
@Html.RenderSeries()
@Html.Raw(Model.PostContent)
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'macsenblog'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-****"></script>
</div>
<div>
</div> | @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<Snow.ViewModels.PostViewModel>
@using System.Collections.Generic
@{
Layout = "default.cshtml";
}
@section menu {
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav sf-menu">
<li class="current"><a href="/">Blog</a></li>
<!--<li><a href="/projects">Projects</a></li>-->
<li><a href="/categories">Categories</a></li>
<li><a href="/archive">Archive</a></li>
</ul>
</div>
}
<div class="post">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h2>
@Model.Title
<span>@Model.PostDate.ToString("dd MMM yyyy")</span>
</h2>
<p>
@foreach (var category in Model.Categories) {
<a class="btn btn-default btn-sm" href="/category/@category.Url"><i class="fa fa-tag"></i> @category.Name</a>
}
</p>
@Html.RenderSeries()
@Html.Raw(Model.PostContent)
@Html.RenderDisqusComments("macsenblog")
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-****"></script>
</div>
<div>
</div> | mit | C# |
2c1944fea1a3cb8f3cf3572cd662e3e186ef42f8 | Update Version : 1.7.171.0 URL Changes + Fix User Manager Delete | Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal | Master/Appleseed/Projects/Appleseed.Framework.UrlRewriting/Properties/AssemblyInfo.cs | Master/Appleseed/Projects/Appleseed.Framework.UrlRewriting/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Appleseed.UrlRewriting")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System : URL Rewriting ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed Portal")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("01d79d33-2176-4a6d-a8aa-7cc02f308240")]
// 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 Revision and Build Numbers
[assembly: AssemblyVersion("1.7.171.0")]
[assembly: AssemblyFileVersion("1.7.171.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Appleseed.UrlRewriting")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System : URL Rewriting ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed Portal")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("01d79d33-2176-4a6d-a8aa-7cc02f308240")]
// 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 Revision and Build Numbers
[assembly: AssemblyVersion("1.6.160.540")]
[assembly: AssemblyFileVersion("1.6.160.540")] | apache-2.0 | C# |
a4c6cd13754fdb67f25acb99c1b4630c97a07f14 | Fix error | SnpM/Lockstep-Framework | Core/Simulation/Physics/Core/Legacy/Editor/LegacyEditorLSBody.cs | Core/Simulation/Physics/Core/Legacy/Editor/LegacyEditorLSBody.cs | using UnityEngine;
using System.Collections;
using UnityEditor;
using Lockstep.Legacy;
using System.Collections.Generic;
using System;
namespace Lockstep.Legacy.Integration
{
[CustomEditor (typeof(Legacy.LSBody), true),UnityEditor.CanEditMultipleObjects]
public class EditorLSBody : Editor
{
static int boom = 0;
public override void OnInspectorGUI ()
{
boom--;
if (GUILayout.Button ("Update LSBody")) {
if (boom <= 0) {
boom = 10;
ReplaceLegacy ();
}
}
}
void ReplaceLegacy ()
{
//special thanks to hpjohn <3
//http://forum.unity3d.com/threads/editor-want-to-check-all-prefabs-in-a-project-for-an-attached-monobehaviour.253149/
string[] allPrefabs = GetAllPrefabs ();
List<string> listResult = new List<string> ();
MonoScript targetScript = null;
foreach (var monoScript in Resources.FindObjectsOfTypeAll<MonoScript>()) {
if (monoScript.GetClass () == typeof(LSBody)) {
targetScript = monoScript;
}
}
string targetPath = AssetDatabase.GetAssetPath (targetScript);
foreach (string prefab in allPrefabs) {
string[] single = new string[] { prefab };
string[] dependencies = AssetDatabase.GetDependencies (single);
foreach (string dependedAsset in dependencies) {
if (dependedAsset == targetPath) {
listResult.Add (prefab);
}
}
}
foreach (var path in listResult) {
var source = AssetDatabase.LoadAssetAtPath<GameObject> (path);
var fab = GameObject.Instantiate(source);
var legacy = fab.GetComponent<LSBody> ();
legacy.Replace ();
DestroyImmediate (legacy);
PrefabUtility.ReplacePrefab(fab, source, ReplacePrefabOptions.ConnectToPrefab | ReplacePrefabOptions.ReplaceNameBased );
GameObject.DestroyImmediate(fab);
}
}
public static string[] GetAllPrefabs ()
{
string[] temp = AssetDatabase.GetAllAssetPaths ();
List<string> result = new List<string> ();
foreach (string s in temp) {
if (s.Contains (".prefab"))
result.Add (s);
}
return result.ToArray ();
}
}
} | using UnityEngine;
using System.Collections;
using UnityEditor;
using Lockstep.Legacy;
using System.Collections.Generic;
using System;
namespace Lockstep.Legacy.Integration
{
[CustomEditor (typeof(Legacy.LSBody), true),UnityEditor.CanEditMultipleObjects]
public class EditorLSBody : Editor
{
static int boom = 0;
public override void OnInspectorGUI ()
{
boom--;
if (GUILayout.Button ("Update LSBody")) {
if (boom <= 0) {
boom = 10;
ReplaceLegacy ();
}
}
}
void ReplaceLegacy ()
{
//special thanks to hpjohn <3
//http://forum.unity3d.com/threads/editor-want-to-check-all-prefabs-in-a-project-for-an-attached-monobehaviour.253149/
string[] allPrefabs = GetAllPrefabs ();
List<string> listResult = new List<string> ();
MonoScript targetScript = null;
foreach (var monoScript in Resources.FindObjectsOfTypeAll<MonoScript>()) {
if (monoScript.GetClass () == typeof(LSBody)) {
targetScript = monoScript;
}
}
string targetPath = AssetDatabase.GetAssetPath (targetScript);
foreach (string prefab in allPrefabs) {
string[] single = new string[] { prefab };
string[] dependencies = AssetDatabase.GetDependencies (single);
foreach (string dependedAsset in dependencies) {
if (dependedAsset == targetPath) {
listResult.Add (prefab);
}
}
}
foreach (var path in listResult) {
var source = AssetDatabase.LoadAssetAtPath<GameObject> (path);
var fab = GameObject.Instantiate(source);
var legacy = fab.GetComponent<LSBody> ();
legacy.Replace ();
DestroyImmediate (legacy);
PrefabUtility.MergeAllPrefabInstances(source);
GameObject.DestroyImmediate(fab);
}
}
public static string[] GetAllPrefabs ()
{
string[] temp = AssetDatabase.GetAllAssetPaths ();
List<string> result = new List<string> ();
foreach (string s in temp) {
if (s.Contains (".prefab"))
result.Add (s);
}
return result.ToArray ();
}
}
} | mit | C# |
5d0d83b6bf8b6a8546e8df4b0313199f439ca138 | Add basic xmldoc | peppy/osu-new,EVAST9919/osu,peppy/osu,johnneijzen/osu,2yangk23/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,UselessToucan/osu,2yangk23/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu | osu.Game/Graphics/UserInterface/SeekLimitedSearchTextBox.cs | osu.Game/Graphics/UserInterface/SeekLimitedSearchTextBox.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A <see cref="SearchTextBox"/> which does not handle left/right arrow keys for seeking.
/// </summary>
public class SeekLimitedSearchTextBox : SearchTextBox
{
public override bool HandleLeftRightArrows => false;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Graphics.UserInterface
{
public class SeekLimitedSearchTextBox : SearchTextBox
{
public override bool HandleLeftRightArrows => false;
}
}
| mit | C# |
d399aeebff865c857e076df75e1483b617dc8c9b | change version to 1.0.0 | config-r/config-r | src/ConfigR/Properties/AssemblyInfo.cs | src/ConfigR/Properties/AssemblyInfo.cs | // <copyright file="AssemblyInfo.cs" company="ConfigR contributors">
// Copyright (c) ConfigR contributors. (configr.net@gmail.com)
// </copyright>
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ConfigR")]
[assembly: AssemblyDescription("Write your .NET configuration files in C#.")]
[assembly: AssemblyCompany("ConfigR contributors")]
[assembly: AssemblyProduct("ConfigR")]
[assembly: AssemblyCopyright("Copyright (c) ConfigR contributors. (configr.net@gmail.com)")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
| // <copyright file="AssemblyInfo.cs" company="ConfigR contributors">
// Copyright (c) ConfigR contributors. (configr.net@gmail.com)
// </copyright>
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ConfigR")]
[assembly: AssemblyDescription("Write your .NET configuration files in C#.")]
[assembly: AssemblyCompany("ConfigR contributors")]
[assembly: AssemblyProduct("ConfigR")]
[assembly: AssemblyCopyright("Copyright (c) ConfigR contributors. (configr.net@gmail.com)")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("0.15.0")]
[assembly: AssemblyFileVersion("0.15.0")]
[assembly: AssemblyInformationalVersion("0.15.0")]
| mit | C# |
a0076396ddd9434494cc8984352a9fecd03e06c6 | Add documentation for person images. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Objects/Get/People/TraktPersonImages.cs | Source/Lib/TraktApiSharp/Objects/Get/People/TraktPersonImages.cs | namespace TraktApiSharp.Objects.Get.People
{
using Basic;
using Newtonsoft.Json;
/// <summary>A collection of images and image sets for a Trakt person.</summary>
public class TraktPersonImages
{
/// <summary>Gets or sets the headshot image set.</summary>
[JsonProperty(PropertyName = "headshot")]
public TraktImageSet Headshot { get; set; }
/// <summary>Gets or sets the fan art image set.</summary>
[JsonProperty(PropertyName = "fanart")]
public TraktImageSet FanArt { get; set; }
}
}
| namespace TraktApiSharp.Objects.Get.People
{
using Basic;
using Newtonsoft.Json;
public class TraktPersonImages
{
[JsonProperty(PropertyName = "headshot")]
public TraktImageSet Headshot { get; set; }
[JsonProperty(PropertyName = "fanart")]
public TraktImageSet FanArt { get; set; }
}
}
| mit | C# |
ba0701a5deda51ec468a88e8842788d7d50bba7b | Fix NPCSpawnMapEntity data size. It should be 8. It was 10. Derp. | ethanmoffat/EndlessClient | EOLib.IO/Map/NPCSpawnMapEntity.cs | EOLib.IO/Map/NPCSpawnMapEntity.cs | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using System.Collections.Generic;
using EOLib.IO.Services;
namespace EOLib.IO.Map
{
public class NPCSpawnMapEntity : IMapEntity
{
public int DataSize { get { return 8; } }
public int X { get; set; }
public int Y { get; set; }
public short ID { get; set; }
public byte SpawnType { get; set; }
public short RespawnTime { get; set; }
public byte Amount { get; set; }
public byte[] SerializeToByteArray(INumberEncoderService numberEncoderService,
IMapStringEncoderService mapStringEncoderService)
{
var retBytes = new List<byte>(DataSize);
retBytes.AddRange(numberEncoderService.EncodeNumber(X, 1));
retBytes.AddRange(numberEncoderService.EncodeNumber(Y, 1));
retBytes.AddRange(numberEncoderService.EncodeNumber(ID, 2));
retBytes.AddRange(numberEncoderService.EncodeNumber(SpawnType, 1));
retBytes.AddRange(numberEncoderService.EncodeNumber(RespawnTime, 2));
retBytes.AddRange(numberEncoderService.EncodeNumber(Amount, 1));
return retBytes.ToArray();
}
public void DeserializeFromByteArray(byte[] data,
INumberEncoderService numberEncoderService,
IMapStringEncoderService mapStringEncoderService)
{
if (data.Length != DataSize)
throw new ArgumentException("Data is improperly sized for deserialization", "data");
X = numberEncoderService.DecodeNumber(data[0]);
Y = numberEncoderService.DecodeNumber(data[1]);
ID = (short) numberEncoderService.DecodeNumber(data[2], data[3]);
SpawnType = (byte) numberEncoderService.DecodeNumber(data[4]);
RespawnTime = (short) numberEncoderService.DecodeNumber(data[5], data[6]);
Amount = (byte) numberEncoderService.DecodeNumber(data[7]);
}
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using System.Collections.Generic;
using EOLib.IO.Services;
namespace EOLib.IO.Map
{
public class NPCSpawnMapEntity : IMapEntity
{
public int DataSize { get { return 10; } }
public int X { get; set; }
public int Y { get; set; }
public short ID { get; set; }
public byte SpawnType { get; set; }
public short RespawnTime { get; set; }
public byte Amount { get; set; }
public byte[] SerializeToByteArray(INumberEncoderService numberEncoderService,
IMapStringEncoderService mapStringEncoderService)
{
var retBytes = new List<byte>(DataSize);
retBytes.AddRange(numberEncoderService.EncodeNumber(X, 1));
retBytes.AddRange(numberEncoderService.EncodeNumber(Y, 1));
retBytes.AddRange(numberEncoderService.EncodeNumber(ID, 2));
retBytes.AddRange(numberEncoderService.EncodeNumber(SpawnType, 1));
retBytes.AddRange(numberEncoderService.EncodeNumber(RespawnTime, 2));
retBytes.AddRange(numberEncoderService.EncodeNumber(Amount, 1));
return retBytes.ToArray();
}
public void DeserializeFromByteArray(byte[] data,
INumberEncoderService numberEncoderService,
IMapStringEncoderService mapStringEncoderService)
{
if (data.Length != DataSize)
throw new ArgumentException("Data is improperly sized for deserialization", "data");
X = numberEncoderService.DecodeNumber(data[0]);
Y = numberEncoderService.DecodeNumber(data[1]);
ID = (short) numberEncoderService.DecodeNumber(data[2], data[3]);
SpawnType = (byte) numberEncoderService.DecodeNumber(data[4]);
RespawnTime = (short) numberEncoderService.DecodeNumber(data[5], data[6]);
Amount = (byte) numberEncoderService.DecodeNumber(data[7]);
}
}
}
| mit | C# |
ffc28ea4b61d11a8d277149a3029b247800e0493 | Fix problems with the form. | Aurel/rbya_election,Aurel/rbya_election,Aurel/rbya_election | Elections/Views/Home/Index.cshtml | Elections/Views/Home/Index.cshtml | @{
ViewData["Title"] = "RBYA Elections";
}
<div class="center-block text-center container">
<div class="row" style="margin-bottom:100px;">
<img src="~/images/elections.png" style="margin:auto; width:50%;" />
</div>
<div class="col-md-6 col-xs-12">
<form role="form">
<div class="panel panel-default" style="margin:20px;">
<div class="panel-heading">
<label class="control-label" for="email">Sign Up To Vote</label>
</div>
<div class="panel-body">
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-primary">Sign Up</button>
</div>
</div>
</form>
</div>
<div class="col-md-6 col-xs-12">
<form role="form">
<div class="panel panel-default" style="margin:20px;">
<div class="panel-heading">
<label class="control-label" for="code">Log in with your secret code</label>
</div>
<div class="panel-body">
<div class="form-group">
<input type="email" class="form-control" id="code" placeholder="Secret Code">
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</div>
</div>
</form>
</div>
</div>
| @{
ViewData["Title"] = "RBYA Elections";
}
<div class="center-block text-center container">
<div class="row" style="margin-bottom:100px;">
<img src="~/images/elections.png" style="margin:auto; width:50%;" />
</div>
<div class="col-md-6 col-xs-12">
<div class="panel panel-default" style="margin:20px;">
<div class="panel-body">
<form role="form">
<div class="form-group">
<label class="control-label" for="exampleInputEmail">Sign Up To Vote</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-primary">Sign Up</button>
</form>
</div>
</div>
</div>
<div class="col-md-6 col-xs-12">
<form role="form">
<div class="panel panel-default" style="margin:20px;">
<div class="panel-heading">
<label class="control-label" for="exampleInputEmail">Log in with your secret code</label>
</div>
<div class="panel-body">
<div class="form-group">
<input type="email" class="form-control" id="code" placeholder="Secret Code">
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</div>
</div>
</form>
</div>
</div>
| mit | C# |
ac4c7164b060367a22f24d55f982998bfaff82cc | Fix dispose UnityTextureData | DragonBones/DragonBonesCSharp | Unity/Demos/Assets/Scripts/DragonBones/unity/UnityTextureData.cs | Unity/Demos/Assets/Scripts/DragonBones/unity/UnityTextureData.cs | using UnityEngine;
namespace DragonBones
{
/**
* @language zh_CN
* Unity 贴图集数据。
* @version DragonBones 3.0
*/
public class UnityTextureAtlasData : TextureAtlasData
{
/**
* @private
*/
internal bool _disposeTexture;
/**
* @language zh_CN
* Unity 贴图。
* @version DragonBones 3.0
*/
public Material texture;
public Material uiTexture;
/**
* @private
*/
public UnityTextureAtlasData()
{
}
/**
* @private
*/
override protected void _onClear()
{
base._onClear();
if (_disposeTexture && texture != null)
{
#if UNITY_EDITOR
//Object.DestroyImmediate(texture);
#else
Object.Destroy(texture);
#endif
}
if (_disposeTexture && uiTexture != null)
{
#if UNITY_EDITOR
//Object.DestroyImmediate(uiTexture);
#else
Object.Destroy(uiTexture);
#endif
}
_disposeTexture = false;
texture = null;
uiTexture = null;
}
/**
* @private
*/
override public TextureData GenerateTextureData()
{
return BaseObject.BorrowObject<UnityTextureData>();
}
}
/**
* @private
*/
public class UnityTextureData : TextureData
{
public UnityTextureData()
{
}
}
} | using UnityEngine;
namespace DragonBones
{
/**
* @language zh_CN
* Unity 贴图集数据。
* @version DragonBones 3.0
*/
public class UnityTextureAtlasData : TextureAtlasData
{
/**
* @private
*/
internal bool _disposeTexture;
/**
* @language zh_CN
* Unity 贴图。
* @version DragonBones 3.0
*/
public Material texture;
public Material uiTexture;
/**
* @private
*/
public UnityTextureAtlasData()
{
}
/**
* @private
*/
override protected void _onClear()
{
base._onClear();
if (_disposeTexture && texture != null)
{
#if UNITY_EDITOR
//Object.DestroyImmediate(texture);
#else
Object.Destroy(texture);
#endif
}
_disposeTexture = false;
texture = null;
}
/**
* @private
*/
override public TextureData GenerateTextureData()
{
return BaseObject.BorrowObject<UnityTextureData>();
}
}
/**
* @private
*/
public class UnityTextureData : TextureData
{
public UnityTextureData()
{
}
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.