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
f538ad3138450fc42bfce27b59535b6139388872
rewrite ParsecStateStreamEnumerator
acple/ParsecSharp
ParsecSharp/Data/Internal/ParsecStateStreamEnumerator.cs
ParsecSharp/Data/Internal/ParsecStateStreamEnumerator.cs
using System; using System.Collections; using System.Collections.Generic; namespace ParsecSharp.Internal { public sealed class ParsecStateStreamEnumerator<TToken> : IEnumerator<TToken> { private readonly IParsecStateStream<TToken> _source; private IParsecStateStream<TToken> current; public TToken Current => this.current.Current; object IEnumerator.Current => this.Current; public ParsecStateStreamEnumerator(IParsecStateStream<TToken> stream) { this._source = stream; } public bool MoveNext() => (this.current = this.current?.Next ?? this._source).HasValue; void IEnumerator.Reset() => throw new NotSupportedException(); public void Dispose() => this.current = EmptyStream<TToken>.Instance; } }
using System; using System.Collections; using System.Collections.Generic; namespace ParsecSharp.Internal { public sealed class ParsecStateStreamEnumerator<TToken> : IEnumerator<TToken> { private IParsecStateStream<TToken> stream; public TToken Current { get; private set; } object IEnumerator.Current => this.Current; public ParsecStateStreamEnumerator(IParsecStateStream<TToken> stream) { this.stream = stream; } public bool MoveNext() { if (!this.stream.HasValue) return false; this.Current = this.stream.Current; this.stream = this.stream.Next; return true; } void IEnumerator.Reset() => throw new NotSupportedException(); public void Dispose() { this.Current = default; this.stream = EmptyStream<TToken>.Instance; } } }
mit
C#
06e6e632f3ff1c6432d282c551c388d2e8c233cf
Make AllTypesHelper public
modulexcite/dnlib,0xd4d/dnlib,yck1509/dnlib,Arthur2e5/dnlib,picrap/dnlib,ZixiangBoy/dnlib,jorik041/dnlib,kiootic/dnlib,ilkerhalil/dnlib
src/DotNet/AllTypesHelper.cs
src/DotNet/AllTypesHelper.cs
using System.Collections.Generic; namespace dot10.DotNet { /// <summary> /// Returns types without getting stuck in an infinite loop /// </summary> public struct AllTypesHelper { Dictionary<TypeDef, bool> visited; RecursionCounter recursionCounter; /// <summary> /// Gets a list of all types and nested types /// </summary> /// <param name="types">A list of types</param> public static IEnumerable<TypeDef> Types(IEnumerable<TypeDef> types) { var helper = new AllTypesHelper(); helper.visited = new Dictionary<TypeDef, bool>(); return helper.GetTypes(types); } IEnumerable<TypeDef> GetTypes(IEnumerable<TypeDef> types) { if (!recursionCounter.Increment()) { } else { foreach (var type in types) { if (visited.ContainsKey(type)) continue; visited[type] = true; yield return type; if (type.NestedTypes.Count > 0) { foreach (var nested in GetTypes(type.NestedTypes)) yield return nested; } } recursionCounter.Decrement(); } } } }
using System.Collections.Generic; namespace dot10.DotNet { struct AllTypesHelper { Dictionary<TypeDef, bool> visited; RecursionCounter recursionCounter; /// <summary> /// Gets a list of all types and nested types /// </summary> /// <param name="types">A list of types</param> public static IEnumerable<TypeDef> Types(IEnumerable<TypeDef> types) { var helper = new AllTypesHelper(); helper.visited = new Dictionary<TypeDef, bool>(); return helper.GetTypes(types); } IEnumerable<TypeDef> GetTypes(IEnumerable<TypeDef> types) { if (!recursionCounter.Increment()) { } else { foreach (var type in types) { if (visited.ContainsKey(type)) continue; visited[type] = true; yield return type; if (type.NestedTypes.Count > 0) { foreach (var nested in GetTypes(type.NestedTypes)) yield return nested; } } recursionCounter.Decrement(); } } } }
mit
C#
970ef6d602acd228c45ffb97a7ba2629612cf0bb
Update AssemblyInfo.cs
Jarlotee/xCache
src/xCache.Aop.Unity/Properties/AssemblyInfo.cs
src/xCache.Aop.Unity/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("xCache.Aop.Unity")] [assembly: AssemblyDescription("Decoupled Caching Abstraction for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jared Lotti")] [assembly: AssemblyProduct("xCache.Aop.Unity")] [assembly: AssemblyCopyright("Copyright © Jared Lotti 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b1ef2017-d343-4ecd-95f5-90ce3aaed96e")] // 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.6.0.0")] [assembly: AssemblyFileVersion("0.6.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("xCache.Aop.Unity")] [assembly: AssemblyDescription("Decoupled Caching Abstraction for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jared Lotti")] [assembly: AssemblyProduct("xCache.Aop.Unity")] [assembly: AssemblyCopyright("Copyright © Jared Lotti 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b1ef2017-d343-4ecd-95f5-90ce3aaed96e")] // 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.5.0.0")] [assembly: AssemblyFileVersion("0.5.0.0")]
mit
C#
603b7bc512706e60c5a4d1a3ca5a341896d97767
Apply migrations at startup
fujiy/FujiyBlog,fujiy/FujiyBlog,fujiy/FujiyBlog
src/FujiyBlog.Web/Program.cs
src/FujiyBlog.Web/Program.cs
using FujiyBlog.Core.EntityFramework; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace FujiyBlog.Web { public class Program { public static void Main(string[] args) { var webHost = BuildWebHost(args); using (var scope = webHost.Services.CreateScope()) { var services = scope.ServiceProvider; var db = services.GetRequiredService<FujiyBlogDatabase>(); db.Database.Migrate(); } webHost.Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace FujiyBlog.Web { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
mit
C#
3ce735eef404b30c0814c28757f05ae07220fab2
Resolve field.
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/Middlewares.cs
backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/Middlewares.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using GraphQL; using GraphQL.Instrumentation; using GraphQL.Types; using Squidex.Infrastructure; using Squidex.Infrastructure.Log; namespace Squidex.Domain.Apps.Entities.Contents.GraphQL { public static class Middlewares { public static Func<ISchema, FieldMiddlewareDelegate, FieldMiddlewareDelegate> Logging(ISemanticLog log) { Guard.NotNull(log, nameof(log)); return (_, next) => { return async context => { try { return await next(context); } catch (Exception ex) { log.LogWarning(ex, w => w .WriteProperty("action", "resolveField") .WriteProperty("status", "failed") .WriteProperty("field", context.FieldName)); throw; } }; }; } public static Func<ISchema, FieldMiddlewareDelegate, FieldMiddlewareDelegate> Errors() { return (_, next) => { return async context => { try { return await next(context); } catch (DomainException ex) { throw new ExecutionError(ex.Message); } }; }; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using GraphQL; using GraphQL.Instrumentation; using GraphQL.Types; using Squidex.Infrastructure; using Squidex.Infrastructure.Log; namespace Squidex.Domain.Apps.Entities.Contents.GraphQL { public static class Middlewares { public static Func<ISchema, FieldMiddlewareDelegate, FieldMiddlewareDelegate> Logging(ISemanticLog log) { Guard.NotNull(log, nameof(log)); return (_, next) => { return async context => { try { return await next(context); } catch (Exception ex) { log.LogWarning(ex, w => w .WriteProperty("action", "reolveField") .WriteProperty("status", "failed") .WriteProperty("field", context.FieldName)); throw; } }; }; } public static Func<ISchema, FieldMiddlewareDelegate, FieldMiddlewareDelegate> Errors() { return (_, next) => { return async context => { try { return await next(context); } catch (DomainException ex) { throw new ExecutionError(ex.Message); } }; }; } } }
mit
C#
61f7b7d00e433f5660be9e015f7e5660f3545714
Remove unused code
DataGenSoftware/DataGen.Validation
DataGen.Validation.UnitTests/ValidationRuleTests.cs
DataGen.Validation.UnitTests/ValidationRuleTests.cs
using NSubstitute; using NUnit.Framework; using System.Collections.Generic; using System.Linq; using Validation.Contracts; using Validation.Model; using Validation.Providers; namespace DataGen.Validation.UnitTests { [TestFixture] public class ValidationRuleTests { [Test] public void ValudationRule_Run_InvalidObject_ReturnFalse() { var objectToValidate = new { PropertyToValidate = 3 }; var validationRule = new ValidationRule<dynamic>(x => x.PropertyToValidate > 7, "PropertyToValidate has to be grater than seven."); var actual = validationRule.Run(objectToValidate); Assert.IsFalse(actual); } [Test] public void ValudationRule_Run_ValidObject_ReturnTrue() { var objectToValidate = new { PropertyToValidate = 9 }; var validationRule = new ValidationRule<dynamic>(x => x.PropertyToValidate > 7, "PropertyToValidate has to be grater than seven."); var actual = validationRule.Run(objectToValidate); Assert.IsTrue(actual); } } }
using NSubstitute; using NUnit.Framework; using System.Collections.Generic; using System.Linq; using Validation.Contracts; using Validation.Model; using Validation.Providers; namespace DataGen.Validation.UnitTests { [TestFixture] public class ValidationRuleTests { [Test] public void ValudationRule_Run_InvalidObject_ReturnFalse() { var objectToValidate = new { PropertyToValidate = 3 }; var validationRule = new ValidationRule<dynamic>(x => x.PropertyToValidate > 7, "PropertyToValidate has to be grater than seven."); //var validationRules = new List<IValidationRule<dynamic>>() { validationRule }; //var validator = Substitute.For<IValidator<dynamic>>(validationRules); var actual = validationRule.Run(objectToValidate); Assert.IsFalse(actual); } [Test] public void ValudationRule_Run_ValidObject_ReturnTrue() { var objectToValidate = new { PropertyToValidate = 9 }; var validationRule = new ValidationRule<dynamic>(x => x.PropertyToValidate > 7, "PropertyToValidate has to be grater than seven."); var actual = validationRule.Run(objectToValidate); Assert.IsTrue(actual); } } }
mit
C#
58fc0a2622b52277fc333cecef99ac4fe2b0b19c
Make TabControl test label more clear
DrabWeb/osu,ppy/osu,ZLima12/osu,peppy/osu-new,nyaamara/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,ppy/osu,naoey/osu,ppy/osu,ZLima12/osu,Damnae/osu,smoogipoo/osu,Drezi126/osu,peppy/osu,NeoAdonis/osu,osu-RP/osu-RP,DrabWeb/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,Nabile-Rahmani/osu,NeoAdonis/osu,naoey/osu,2yangk23/osu,smoogipooo/osu,2yangk23/osu,RedNesto/osu,UselessToucan/osu,johnneijzen/osu,DrabWeb/osu,Frontear/osuKyzer,UselessToucan/osu,naoey/osu,NeoAdonis/osu,tacchinotacchi/osu,smoogipoo/osu,EVAST9919/osu
osu.Desktop.VisualTests/Tests/TestCaseTabControl.cs
osu.Desktop.VisualTests/Tests/TestCaseTabControl.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK; using osu.Framework.Graphics.Primitives; using osu.Framework.Screens.Testing; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Screens.Select.Filter; namespace osu.Desktop.VisualTests.Tests { public class TestCaseTabControl : TestCase { public override string Description => @"Filter for song select"; public override void Reset() { base.Reset(); OsuSpriteText text; OsuTabControl<GroupMode> filter; Add(filter = new OsuTabControl<GroupMode> { Width = 229, AutoSort = true }); Add(text = new OsuSpriteText { Text = "None", Margin = new MarginPadding(4), Position = new Vector2(275, 5) }); filter.PinTab(GroupMode.All); filter.PinTab(GroupMode.RecentlyPlayed); filter.ValueChanged += (sender, mode) => { text.Text = "Currently Selected: " + mode.ToString(); }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Diagnostics; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Screens.Testing; using osu.Game.Graphics.Sprites; using osu.Game.Screens.Select.Filter; using osu.Game.Graphics.UserInterface; namespace osu.Desktop.VisualTests.Tests { public class TestCaseTabControl : TestCase { public override string Description => @"Filter for song select"; public override void Reset() { base.Reset(); OsuSpriteText text; OsuTabControl<GroupMode> filter; Add(new FillFlowContainer { Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, Children = new Drawable[] { filter = new OsuTabControl<GroupMode> { Width = 229, AutoSort = true }, text = new OsuSpriteText { Text = "None", Margin = new MarginPadding(4) } } }); filter.PinTab(GroupMode.All); filter.PinTab(GroupMode.RecentlyPlayed); filter.ValueChanged += (sender, mode) => { Debug.WriteLine($"Selected {mode}"); text.Text = mode.ToString(); }; } } }
mit
C#
5c02c4b027231eb863799a15fc76a3a927d61aa6
Add artificial wait to fix tests
JosephWoodward/GlobalExceptionHandlerDotNet,JosephWoodward/GlobalExceptionHandlerDotNet
src/GlobalExceptionHandler.Tests/WebApi/LoggerTests/LogExceptionTests.cs
src/GlobalExceptionHandler.Tests/WebApi/LoggerTests/LogExceptionTests.cs
using System; using System.Net.Http; using System.Threading.Tasks; using GlobalExceptionHandler.Tests.WebApi.Fixtures; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Shouldly; using Xunit; namespace GlobalExceptionHandler.Tests.WebApi.LoggerTests { public class LogExceptionTests : IClassFixture<WebApiServerFixture> { private Exception _exception; private HttpContext _context; public LogExceptionTests(WebApiServerFixture fixture) { // Arrange const string requestUri = "/api/productnotfound"; var webHost = fixture.CreateWebHost(); webHost.Configure(app => { app.UseWebApiGlobalExceptionHandler(x => { x.OnError((ex, context) => { _exception = ex; _context = context; return Task.CompletedTask; }); }); app.Map(requestUri, config => { config.Run(context => throw new ArgumentException("Invalid request")); }); }); // Act var server = new TestServer(webHost); using (var client = server.CreateClient()) { var requestMessage = new HttpRequestMessage(new HttpMethod("GET"), requestUri); client.SendAsync(requestMessage).Wait(); Task.Delay(1000); } } [Fact] public void Invoke_logger() { _exception.ShouldBeOfType<ArgumentException>(); } [Fact] public void Context_is_set() { _context.ShouldBeOfType<DefaultHttpContext>(); } } }
using System; using System.Net.Http; using System.Threading.Tasks; using GlobalExceptionHandler.Tests.WebApi.Fixtures; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Shouldly; using Xunit; namespace GlobalExceptionHandler.Tests.WebApi.LoggerTests { public class LogExceptionTests : IClassFixture<WebApiServerFixture> { private Exception _exception; private HttpContext _context; public LogExceptionTests(WebApiServerFixture fixture) { // Arrange const string requestUri = "/api/productnotfound"; var webHost = fixture.CreateWebHost(); webHost.Configure(app => { app.UseWebApiGlobalExceptionHandler(x => { x.OnError((ex, context) => { Console.WriteLine("Log error"); _exception = ex; _context = context; return Task.CompletedTask; }); }); app.Map(requestUri, config => { config.Run(context => throw new ArgumentException("Invalid request")); }); }); // Act var server = new TestServer(webHost); using (var client = server.CreateClient()) { var requestMessage = new HttpRequestMessage(new HttpMethod("GET"), requestUri); client.SendAsync(requestMessage).Wait(); Task.Delay(TimeSpan.FromSeconds(3)); } } [Fact] public void Invoke_logger() { _exception.ShouldBeOfType<ArgumentException>(); } [Fact] public void Context_is_set() { _context.ShouldBeOfType<DefaultHttpContext>(); } } }
mit
C#
e8de7c58fccc0406e192e9cfe38158cc8ff21aa1
Expand interface to meet requests at http://forum.botengine.de/t/new-fighters/85/29 and http://forum.botengine.de/t/new-fighters/85/31 and http://forum.botengine.de/t/new-fighters/85/36
bozoweed/Sanderling,Arcitectus/Sanderling,exodus444/Sanderling
src/Sanderling.Interface/Sanderling.Interface/MemoryStruct/SquadronUI.cs
src/Sanderling.Interface/Sanderling.Interface/MemoryStruct/SquadronUI.cs
using System; using System.Collections.Generic; namespace Sanderling.Interface.MemoryStruct { public interface ISquadronsUI { IEnumerable<ISquadronUI> SetSquadron { get; } IUIElement LaunchAllButton { get; } IUIElement OpenBayButton { get; } IUIElement RecallAllButton { get; } } public interface ISquadronUI : IUIElement { ISquadronContainer Squadron { get; } IEnumerable<ISquadronAbilityIcon> SetAbilityIcon { get; } } public interface ISquadronContainer : IContainer { int? SquadronNumber { get; } ISquadronHealth Health { get; } bool? IsSelected { get; } string Hint { get; } } public interface ISquadronHealth { int? SquadronSizeMax { get; } int? SquadronSizeCurrent { get; } } public interface ISquadronAbilityIcon : IUIElement { int? Quantity { get; } bool? RampActive { get; } } public class SquadronsUI : Container, ISquadronsUI { public IUIElement LaunchAllButton { set; get; } public IUIElement OpenBayButton { set; get; } public IUIElement RecallAllButton { set; get; } public IEnumerable<ISquadronUI> SetSquadron { set; get; } public SquadronsUI() { } public SquadronsUI(IUIElement @base) : base(@base) { } } public class SquadronUI : UIElement, ISquadronUI { public ISquadronContainer Squadron { set; get; } public IEnumerable<ISquadronAbilityIcon> SetAbilityIcon { set; get; } public SquadronUI() { } public SquadronUI(IUIElement @base) : base(@base) { } } public class SquadronContainer : Container, ISquadronContainer { public int? SquadronNumber { set; get; } public ISquadronHealth Health { set; get; } public bool? IsSelected { set; get; } public string Hint { set; get; } public SquadronContainer() { } public SquadronContainer(IUIElement @base) : base(@base) { } } public class SquadronHealth : ISquadronHealth { public int? SquadronSizeMax { set; get; } public int? SquadronSizeCurrent { set; get; } } public class SquadronAbilityIcon : UIElement, ISquadronAbilityIcon { public int? Quantity { set; get; } public bool? RampActive { set; get; } public SquadronAbilityIcon() { } public SquadronAbilityIcon(IUIElement @base) : base(@base) { } } }
using System; using System.Collections.Generic; namespace Sanderling.Interface.MemoryStruct { public interface ISquadronsUI { IEnumerable<ISquadronUI> SetSquadron { get; } IUIElement LaunchAllButton { get; } IUIElement OpenBayButton { get; } IUIElement RecallAllButton { get; } } public interface ISquadronUI : IUIElement { ISquadronContainer Squadron { get; } IEnumerable<ISquadronAbilityIcon> SetAbilityIcon { get; } } public interface ISquadronContainer : IContainer { int? SquadronNumber { get; } ISquadronHealth Health { get; } } public interface ISquadronHealth { int? SquadronSizeMax { get; } int? SquadronSizeCurrent { get; } } public interface ISquadronAbilityIcon : IUIElement { int? Quantity { get; } } public class SquadronsUI : Container, ISquadronsUI { public IUIElement LaunchAllButton { set; get; } public IUIElement OpenBayButton { set; get; } public IUIElement RecallAllButton { set; get; } public IEnumerable<ISquadronUI> SetSquadron { set; get; } public SquadronsUI() { } public SquadronsUI(IUIElement @base) : base(@base) { } } public class SquadronUI : UIElement, ISquadronUI { public ISquadronContainer Squadron { set; get; } public IEnumerable<ISquadronAbilityIcon> SetAbilityIcon { set; get; } public SquadronUI() { } public SquadronUI(IUIElement @base) : base(@base) { } } public class SquadronContainer : Container, ISquadronContainer { public int? SquadronNumber { set; get; } public ISquadronHealth Health { set; get; } public SquadronContainer() { } public SquadronContainer(IUIElement @base) : base(@base) { } } public class SquadronHealth : ISquadronHealth { public int? SquadronSizeMax { set; get; } public int? SquadronSizeCurrent { set; get; } } public class SquadronAbilityIcon : UIElement, ISquadronAbilityIcon { public int? Quantity { set; get; } public SquadronAbilityIcon() { } public SquadronAbilityIcon(IUIElement @base) : base(@base) { } } }
apache-2.0
C#
c93dcd003d5157511eaf1884064f0e8a0f18ab55
Fix content headers
DBCG/Dataphor,DBCG/Dataphor,DBCG/Dataphor,DBCG/Dataphor,DBCG/Dataphor,DBCG/Dataphor
Dataphoria/Dataphoria.Web.FHIR/Models/FhirMediaType.cs
Dataphoria/Dataphoria.Web.FHIR/Models/FhirMediaType.cs
using Hl7.Fhir.Model; using Hl7.Fhir.Rest; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Web; namespace Alphora.Dataphor.Dataphoria.Web.FHIR.Models { public static class FhirMediaType { // API: This class can be merged into HL7.Fhir.Rest.ContentType public const string XmlResource = "application/xml+fhir"; public const string XmlTagList = "application/xml+fhir"; public const string JsonResource = "application/json+fhir"; public const string JsonTagList = "application/json+fhir"; public const string BinaryResource = "application/fhir+binary"; public static ICollection<string> StrictFormats { get { return new List<string>() { XmlResource, JsonResource }; } } public static string[] LooseXmlFormats = { "xml", "text/xml", "application/xml" }; public static readonly string[] LooseJsonFormats = { "json", "application/json" }; /// <summary> /// Transforms loose formats to their strict variant /// </summary> /// <param name="format">Mime type</param> /// <returns></returns> public static string Interpret(string format) { if (format == null) return XmlResource; if (StrictFormats.Contains(format)) return format; if (LooseXmlFormats.Contains(format)) return XmlResource; if (LooseJsonFormats.Contains(format)) return JsonResource; return format; } public static ResourceFormat GetResourceFormat(string format) { string strict = Interpret(format); if (strict == XmlResource) return ResourceFormat.Xml; else if (strict == JsonResource) return ResourceFormat.Json; else return ResourceFormat.Xml; } public static string GetContentType(Type type, ResourceFormat format) { if (typeof(Resource).IsAssignableFrom(type) || type == typeof(Resource) || type == typeof(FhirResponse)) { switch (format) { case ResourceFormat.Json: return JsonResource; case ResourceFormat.Xml: return XmlResource; default: return XmlResource; } } else return "application/octet-stream"; } public static string GetMediaType(this HttpRequestMessage request) { MediaTypeHeaderValue headervalue = request.Content.Headers.ContentType; string s = (headervalue != null) ? headervalue.MediaType : null; return Interpret(s); } public static MediaTypeHeaderValue GetMediaTypeHeaderValue(Type type, ResourceFormat format) { string mediatype = FhirMediaType.GetContentType(type, format); MediaTypeHeaderValue header = new MediaTypeHeaderValue(mediatype); header.CharSet = Encoding.UTF8.WebName; return header; } } }
using Hl7.Fhir.Model; using Hl7.Fhir.Rest; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Web; namespace Alphora.Dataphor.Dataphoria.Web.FHIR.Models { public static class FhirMediaType { // API: This class can be merged into HL7.Fhir.Rest.ContentType public const string XmlResource = "application/xml+fhir"; public const string XmlTagList = "application/xml+fhir"; public const string JsonResource = "application/json+fhir"; public const string JsonTagList = "application/json+fhir"; public const string BinaryResource = "application/fhir+binary"; public static ICollection<string> StrictFormats { get { return new List<string>() { XmlResource, JsonResource }; } } public static string[] LooseXmlFormats = { "xml", "text/xml", "application/xml" }; public static readonly string[] LooseJsonFormats = { "json", "application/json" }; /// <summary> /// Transforms loose formats to their strict variant /// </summary> /// <param name="format">Mime type</param> /// <returns></returns> public static string Interpret(string format) { if (format == null) return XmlResource; if (StrictFormats.Contains(format)) return format; if (LooseXmlFormats.Contains(format)) return XmlResource; if (LooseJsonFormats.Contains(format)) return JsonResource; return format; } public static ResourceFormat GetResourceFormat(string format) { string strict = Interpret(format); if (strict == XmlResource) return ResourceFormat.Xml; else if (strict == JsonResource) return ResourceFormat.Json; else return ResourceFormat.Xml; } public static string GetContentType(Type type, ResourceFormat format) { if (typeof(Resource).IsAssignableFrom(type) || type == typeof(Resource)) { switch (format) { case ResourceFormat.Json: return JsonResource; case ResourceFormat.Xml: return XmlResource; default: return XmlResource; } } else return "application/octet-stream"; } public static string GetMediaType(this HttpRequestMessage request) { MediaTypeHeaderValue headervalue = request.Content.Headers.ContentType; string s = (headervalue != null) ? headervalue.MediaType : null; return Interpret(s); } public static MediaTypeHeaderValue GetMediaTypeHeaderValue(Type type, ResourceFormat format) { string mediatype = FhirMediaType.GetContentType(type, format); MediaTypeHeaderValue header = new MediaTypeHeaderValue(mediatype); header.CharSet = Encoding.UTF8.WebName; return header; } } }
bsd-3-clause
C#
9ca4bbfdc7b0792d18c6eb00c1536ae7d49f69eb
refactor index display and counter
hatelove/MyMvcHomework,hatelove/MyMvcHomework,hatelove/MyMvcHomework
MyMoney/MyMoney/Views/Accounting/ShowHistory.cshtml
MyMoney/MyMoney/Views/Accounting/ShowHistory.cshtml
@model IEnumerable<MyMoney.Models.ViewModels.AccountingViewModel> <table class="table table-bordered table-hover"> <tr> <th>#</th> <th> @Html.DisplayNameFor(model => model.Type) </th> <th> @Html.DisplayNameFor(model => model.Amount) </th> <th> @Html.DisplayNameFor(model => model.Date) </th> <th> @Html.DisplayNameFor(model => model.Remark) </th> </tr> @{ var index = 1;} @foreach (var item in Model) { <tr> <td>@(index++)</td> <td> @Html.DisplayFor(modelItem => item.Type) </td> <td> @Html.DisplayFor(modelItem => item.Amount) </td> <td> @Html.DisplayFor(modelItem => item.Date) </td> <td> @Html.DisplayFor(modelItem => item.Remark) </td> </tr> } </table>
@model IEnumerable<MyMoney.Models.ViewModels.AccountingViewModel> <table class="table table-bordered table-hover"> <tr> <th>#</th> <th> @Html.DisplayNameFor(model => model.Type) </th> <th> @Html.DisplayNameFor(model => model.Amount) </th> <th> @Html.DisplayNameFor(model => model.Date) </th> <th> @Html.DisplayNameFor(model => model.Remark) </th> </tr> @{ var index = 1;} @foreach (var item in Model) { <tr> <td>@(index)</td> <td> @Html.DisplayFor(modelItem => item.Type) </td> <td> @Html.DisplayFor(modelItem => item.Amount) </td> <td> @Html.DisplayFor(modelItem => item.Date) </td> <td> @Html.DisplayFor(modelItem => item.Remark) </td> </tr> index++; } </table>
mit
C#
f189b7078710c62d543e70aa5228421c892a2650
Implement of PSCredential
WimObiwan/Pash,sillvan/Pash,Jaykul/Pash,mrward/Pash,ForNeVeR/Pash,sillvan/Pash,sillvan/Pash,sillvan/Pash,ForNeVeR/Pash,Jaykul/Pash,ForNeVeR/Pash,sburnicki/Pash,WimObiwan/Pash,WimObiwan/Pash,mrward/Pash,sburnicki/Pash,sburnicki/Pash,WimObiwan/Pash,Jaykul/Pash,ForNeVeR/Pash,sburnicki/Pash,mrward/Pash,mrward/Pash,Jaykul/Pash
Source/System.Management/Automation/PSCredential.cs
Source/System.Management/Automation/PSCredential.cs
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System; using System.Net; using System.Security; namespace System.Management.Automation { public sealed class PSCredential { string username; SecureString password; public string UserName { get { return this.username; } } public SecureString Password { get { return this.password; } } public static PSCredential Empty { get { throw new NotImplementedException (); } } public PSCredential(string userName, SecureString password) { this.username = userName; this.password = password; } public NetworkCredential GetNetworkCredential() { throw new NotImplementedException (); } public static explicit operator NetworkCredential(PSCredential credential) { throw new NotImplementedException (); } } }
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System; using System.Collections.Generic; using System.Text; namespace System.Management.Automation { public sealed class PSCredential { /* public PSCredential(string userName, SecureString password) { throw new NotImplementedException(); } public static explicit operator NetworkCredential(PSCredential credential) { throw new NotImplementedException(); } public static PSCredential Empty { get; } public SecureString Password { get; } public string UserName { get; } public NetworkCredential GetNetworkCredential() { throw new NotImplementedException(); } */ } }
bsd-3-clause
C#
33453e70b77f77ed98fd4913ba3c994ae6c3c4e3
Allow retrieving DependencyProperty's through WpfControl aspect.
Whathecode/Framework-Class-Library-Extension,Whathecode/Framework-Class-Library-Extension
Whathecode.PresentationFramework.Aspects/Windows/DependencyPropertyFactory/Aspects/WpfControlAspect.cs
Whathecode.PresentationFramework.Aspects/Windows/DependencyPropertyFactory/Aspects/WpfControlAspect.cs
using System; using System.Collections.Generic; using System.Reflection; using System.Windows; using PostSharp.Aspects; using PostSharp.Aspects.Advices; using Whathecode.System.Reflection.Extensions; using Whathecode.System.Windows.DependencyPropertyFactory.Attributes; using Visibility = PostSharp.Reflection.Visibility; namespace Whathecode.System.Windows.DependencyPropertyFactory.Aspects { /// <summary> /// Aspect which when applied to a DependencyObject, allows using the <see cref = "DependencyPropertyFactory" /> without having to /// add it to the class, or delegate calls to it in the property getters and setters. /// </summary> /// <typeparam name = "T">Enum type specifying all the dependency properties.</typeparam> [Serializable] public class WpfControlAspect<T> : IInstanceScopedAspect, IAspectProvider { class ConcreteDependencyPropertyFactory : DependencyPropertyFactory<T> { public ConcreteDependencyPropertyFactory( Type ownerType ) : base( ownerType, false, false ) { } } [NonSerialized] object _instance; [NonSerialized] static DependencyPropertyFactory<T> _propertyFactory; [IntroduceMember( Visibility = Visibility.Private )] public DependencyPropertyFactory<T> PropertyFactory { get { return _propertyFactory; } private set { _propertyFactory = value; } } readonly List<DependencyPropertyAspect<T>> _propertyAspects = new List<DependencyPropertyAspect<T>>(); public object CreateInstance( AdviceArgs adviceArgs ) { var newAspect = (WpfControlAspect<T>)MemberwiseClone(); newAspect._instance = adviceArgs.Instance; return newAspect; } public void RuntimeInitializeInstance() { if ( PropertyFactory == null ) { PropertyFactory = new ConcreteDependencyPropertyFactory( _instance.GetType() ); _propertyAspects.ForEach( p => p.Factory = PropertyFactory ); } } public IEnumerable<AspectInstance> ProvideAspects( object targetElement ) { var targetType = (Type)targetElement; Dictionary<MemberInfo, DependencyPropertyAttribute[]> attributedProperties = targetType.GetAttributedMembers<DependencyPropertyAttribute>( MemberTypes.Property ); foreach ( var member in attributedProperties ) { var attribute = member.Value[ 0 ]; var propertyAspect = new DependencyPropertyAspect<T>( (T)attribute.GetId() ); _propertyAspects.Add( propertyAspect ); yield return new AspectInstance( member.Key, propertyAspect ); } } public static DependencyProperty GetDependencyProperty( T property ) { return _propertyFactory[ property ]; } } }
using System; using System.Collections.Generic; using System.Reflection; using PostSharp.Aspects; using PostSharp.Aspects.Advices; using PostSharp.Reflection; using Whathecode.System.Reflection.Extensions; using Whathecode.System.Windows.DependencyPropertyFactory.Attributes; namespace Whathecode.System.Windows.DependencyPropertyFactory.Aspects { /// <summary> /// Aspect which when applied to a DependencyObject, allows using the <see cref = "DependencyPropertyFactory" /> without having to /// add it to the class, or delegate calls to it in the property getters and setters. /// </summary> /// <typeparam name = "T">Enum type specifying all the dependency properties.</typeparam> [Serializable] public class WpfControlAspect<T> : IInstanceScopedAspect, IAspectProvider { class ConcreteDependencyPropertyFactory : DependencyPropertyFactory<T> { public ConcreteDependencyPropertyFactory( Type ownerType ) : base( ownerType, false, false ) { } } [NonSerialized] object _instance; [NonSerialized] static DependencyPropertyFactory<T> _propertyFactory; [IntroduceMember( Visibility = Visibility.Private )] public DependencyPropertyFactory<T> PropertyFactory { get { return _propertyFactory; } private set { _propertyFactory = value; } } readonly List<DependencyPropertyAspect<T>> _propertyAspects = new List<DependencyPropertyAspect<T>>(); public object CreateInstance( AdviceArgs adviceArgs ) { var newAspect = (WpfControlAspect<T>)MemberwiseClone(); newAspect._instance = adviceArgs.Instance; return newAspect; } public void RuntimeInitializeInstance() { if ( PropertyFactory == null ) { PropertyFactory = new ConcreteDependencyPropertyFactory( _instance.GetType() ); _propertyAspects.ForEach( p => p.Factory = PropertyFactory ); } } public IEnumerable<AspectInstance> ProvideAspects( object targetElement ) { var targetType = (Type)targetElement; Dictionary<MemberInfo, DependencyPropertyAttribute[]> attributedProperties = targetType.GetAttributedMembers<DependencyPropertyAttribute>( MemberTypes.Property ); foreach ( var member in attributedProperties ) { var attribute = member.Value[ 0 ]; var propertyAspect = new DependencyPropertyAspect<T>( (T)attribute.GetId() ); _propertyAspects.Add( propertyAspect ); yield return new AspectInstance( member.Key, propertyAspect ); } } } }
mit
C#
5a7f7c205e0d974ab6de6738eb93d465e0661701
Update ConvertChartToPdf.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/CSharp/Files/Utility/ConvertChartToPdf.cs
Examples/CSharp/Files/Utility/ConvertChartToPdf.cs
using System; using Aspose.Cells; using Aspose.Cells.Charts; namespace Aspose.Cells.Examples.Files.Utility { class ConvertChartToPdf { //ExStart:1 static void Main() { string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string inputPath = dataDir + "Sample.xlsx"; string outputPath = dataDir + "Output-Chart.out.pdf"; //Load excel file containing charts Workbook workbook = new Workbook(inputPath); //Access first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Access first chart inside the worksheet Chart chart = worksheet.Charts[0]; //Save the chart into pdf format chart.ToPdf(outputPath); Console.WriteLine("File saved {0}", outputPath); //ExEnd:1 } } }
using System; using Aspose.Cells; using Aspose.Cells.Charts; namespace Aspose.Cells.Examples.Files.Utility { class ConvertChartToPdf { static void Main() { string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string inputPath = dataDir + "Sample.xlsx"; string outputPath = dataDir + "Output-Chart.out.pdf"; //Load excel file containing charts Workbook workbook = new Workbook(inputPath); //Access first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Access first chart inside the worksheet Chart chart = worksheet.Charts[0]; //Save the chart into pdf format chart.ToPdf(outputPath); Console.WriteLine("File saved {0}", outputPath); } } }
mit
C#
cbb5cb59d5f19611a76549472e3975d3ec83bb5f
Increase logging to Verbose for examples
Livit/CefSharp,Livit/CefSharp,windygu/CefSharp,twxstar/CefSharp,windygu/CefSharp,windygu/CefSharp,zhangjingpu/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,ruisebastiao/CefSharp,illfang/CefSharp,twxstar/CefSharp,jamespearce2006/CefSharp,Haraguroicha/CefSharp,ITGlobal/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,joshvera/CefSharp,twxstar/CefSharp,gregmartinhtc/CefSharp,dga711/CefSharp,yoder/CefSharp,haozhouxu/CefSharp,Livit/CefSharp,dga711/CefSharp,windygu/CefSharp,AJDev77/CefSharp,haozhouxu/CefSharp,Haraguroicha/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,zhangjingpu/CefSharp,rlmcneary2/CefSharp,NumbersInternational/CefSharp,ruisebastiao/CefSharp,gregmartinhtc/CefSharp,jamespearce2006/CefSharp,gregmartinhtc/CefSharp,jamespearce2006/CefSharp,ruisebastiao/CefSharp,ITGlobal/CefSharp,haozhouxu/CefSharp,Haraguroicha/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,illfang/CefSharp,battewr/CefSharp,battewr/CefSharp,NumbersInternational/CefSharp,Octopus-ITSM/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,AJDev77/CefSharp,rover886/CefSharp,rover886/CefSharp,AJDev77/CefSharp,twxstar/CefSharp,gregmartinhtc/CefSharp,rover886/CefSharp,NumbersInternational/CefSharp,rover886/CefSharp,VioletLife/CefSharp,ITGlobal/CefSharp,haozhouxu/CefSharp,VioletLife/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,battewr/CefSharp,VioletLife/CefSharp,NumbersInternational/CefSharp,ITGlobal/CefSharp,Octopus-ITSM/CefSharp,illfang/CefSharp,ruisebastiao/CefSharp,yoder/CefSharp,Octopus-ITSM/CefSharp,yoder/CefSharp,wangzheng888520/CefSharp,Haraguroicha/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,Octopus-ITSM/CefSharp,joshvera/CefSharp,Livit/CefSharp,illfang/CefSharp,joshvera/CefSharp,battewr/CefSharp
CefSharp.Example/CefExample.cs
CefSharp.Example/CefExample.cs
using System; using System.Linq; namespace CefSharp.Example { public static class CefExample { public const string DefaultUrl = "custom://cefsharp/home"; // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work. private const bool debuggingSubProcess = false; public static void Init() { var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; settings.LogSeverity = LogSeverity.Verbose; if (debuggingSubProcess) { settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\x86\\Debug\\CefSharp.BrowserSubprocess.exe"; } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() }); if (!Cef.Initialize(settings)) { if (Environment.GetCommandLineArgs().Contains("--type=renderer")) { Environment.Exit(0); } else { return; } } Cef.RegisterJsObject("bound", new BoundObject()); } } }
using System; using System.Linq; namespace CefSharp.Example { public static class CefExample { public const string DefaultUrl = "custom://cefsharp/home"; // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work. private const bool debuggingSubProcess = false; public static void Init() { var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; if (debuggingSubProcess) { settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\x86\\Debug\\CefSharp.BrowserSubprocess.exe"; } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() }); if (!Cef.Initialize(settings)) { if (Environment.GetCommandLineArgs().Contains("--type=renderer")) { Environment.Exit(0); } else { return; } } Cef.RegisterJsObject("bound", new BoundObject()); } } }
bsd-3-clause
C#
f9369553687a3417aec1e4231b8a21b33dc62017
Rewrite markup for password reminder form
peterblazejewicz/aspnet-5-bootstrap-4,peterblazejewicz/aspnet-5-bootstrap-4
WebApplication/Views/Account/ForgotPassword.cshtml
WebApplication/Views/Account/ForgotPassword.cshtml
@model ForgotPasswordViewModel @{ ViewData["Title"] = "Forgot your password?"; } <h2>@ViewData["Title"].</h2> <p> For more information on how to enable reset password please see this <a href="http://go.microsoft.com/fwlink/?LinkID=532713">article</a>. </p> @* <form asp-controller="Account" asp-action="ForgotPassword" method="post" role="form"> <h4>Enter your email.</h4> <hr /> <div asp-validation-summary="ValidationSummary.All" class="text-danger"></div> <fieldset> <div class="form-group row"> <label asp-for="Email" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> </div> <div class="form-group row"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </fieldset> </form> *@ @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } }
@model ForgotPasswordViewModel @{ ViewData["Title"] = "Forgot your password?"; } <h2>@ViewData["Title"].</h2> <p> For more information on how to enable reset password please see this <a href="http://go.microsoft.com/fwlink/?LinkID=532713">article</a>. </p> @*<form asp-controller="Account" asp-action="ForgotPassword" method="post" role="form"> <h4>Enter your email.</h4> <hr /> <div asp-validation-summary="ValidationSummary.All" class="text-danger"></div> <div class="form-group"> <label asp-for="Email" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </form>*@ @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } }
mit
C#
58810a299eb20b23ee4f66013d94accd62d84d21
Add a and x ions
XRSHEERAN/MetaMorpheus,lonelu/MetaMorpheus,hoffmann4/MetaMorpheus,rmillikin/MetaMorpheus,smith-chem-wisc/MetaMorpheus,zrolfs/MetaMorpheus,lschaffer2/MetaMorpheus
EngineLayer/Proteomics/ProductTypeToTerminusType.cs
EngineLayer/Proteomics/ProductTypeToTerminusType.cs
using System.Collections.Generic; namespace EngineLayer { static class ProductTypeToTerminusType { public static TerminusType IdentifyTerminusType(List<ProductType> lp) { if ((lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C) || lp.Contains(ProductType.Adot)) && (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot) || lp.Contains(ProductType.X))) { return TerminusType.None; } else if (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot) || lp.Contains(ProductType.X)) { return TerminusType.C; } else //if(lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C) || lp.Contains(ProductType.Adot)) { return TerminusType.N; } } } }
using System.Collections.Generic; namespace EngineLayer { static class ProductTypeToTerminusType { public static TerminusType IdentifyTerminusType(List<ProductType> lp) { if ((lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C)) && (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot))) { return TerminusType.None; } else if (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot)) { return TerminusType.C; } else //if(lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C)) { return TerminusType.N; } } } }
mit
C#
cfc6c8f99cb41559f8ba3ff27da8a55f96c7db0e
send some more parameters to client as a test
kreuzhofer/SignalR.ConnectionManager,kreuzhofer/SignalR.ConnectionManager
SignalR.ConnectionManager/HubTest.WebApp/Hubs/MyHub.cs
SignalR.ConnectionManager/HubTest.WebApp/Hubs/MyHub.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; namespace HubTest.WebApp.Hubs { public class MyHub : Hub { public void Hello() { Clients.All.hello("This is the message", "second parameter", 100, true, DateTime.UtcNow); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; namespace HubTest.WebApp.Hubs { public class MyHub : Hub { public void Hello() { Clients.All.hello(); } } }
mit
C#
48934ea11a3e83f24335b48fc2e7a4c0b0be5b4b
Add another test for unrecognized characters.
pvasys/PillarRomanNumeralKata
VasysRomanNumeralsKataTest/FromRomanNumeralsTest.cs
VasysRomanNumeralsKataTest/FromRomanNumeralsTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using VasysRomanNumeralsKata; namespace VasysRomanNumeralsKataTest { [TestClass] public class FromRomanNumeralsTest { [TestMethod] public void WhenStringExtensionIsPassedXItReturns10() { Assert.IsTrue(10 == "X".ParseAsRomanNumeralToLong()); } [TestMethod] public void WhenStringExtensionIsPassedARomanNumeralItReturnsArabic() { Assert.IsTrue(6 == "VI".ParseAsRomanNumeralToLong()); } [TestMethod] public void WhenStringExtensionIsPassedARomanNumeralWithUnrecognizedCharactersItReturnsArabicRepresentingTheCharactersRecognized() { Assert.IsTrue(4 == "I V".ParseAsRomanNumeralToLong()); Assert.IsTrue(4 == "IQV".ParseAsRomanNumeralToLong()); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using VasysRomanNumeralsKata; namespace VasysRomanNumeralsKataTest { [TestClass] public class FromRomanNumeralsTest { [TestMethod] public void WhenStringExtensionIsPassedXItReturns10() { Assert.IsTrue(10 == "X".ParseAsRomanNumeralToLong()); } [TestMethod] public void WhenStringExtensionIsPassedARomanNumeralItReturnsArabic() { Assert.IsTrue(6 == "VI".ParseAsRomanNumeralToLong()); } [TestMethod] public void WhenStringExtensionIsPassedARomanNumeralWithUnrecognizedCharactersItReturnsArabicRepresentingTheCharactersRecognized() { Assert.IsTrue(4 == "I V".ParseAsRomanNumeralToLong()); } } }
mit
C#
04685194078c98b2181aa37be0b86cacb12c430a
Add comma between HttpMethod and Path
kobake/AspNetCore.RouteAnalyzer,kobake/AspNetCore.RouteAnalyzer,kobake/AspNetCore.RouteAnalyzer
AspNetCore.RouteAnalyzer/RouteInformation.cs
AspNetCore.RouteAnalyzer/RouteInformation.cs
namespace AspNetCore.RouteAnalyzer { public class RouteInformation { public string HttpMethod { get; set; } = "GET"; public string Area { get; set; } = ""; public string Path { get; set; } = ""; public string Invocation { get; set; } = ""; public override string ToString() { return $"RouteInformation{{Area:\"{Area}\", HttpMethod: \"{HttpMethod}\", Path:\"{Path}\", Invocation:\"{Invocation}\"}}"; } } }
namespace AspNetCore.RouteAnalyzer { public class RouteInformation { public string HttpMethod { get; set; } = "GET"; public string Area { get; set; } = ""; public string Path { get; set; } = ""; public string Invocation { get; set; } = ""; public override string ToString() { return $"RouteInformation{{Area:\"{Area}\", HttpMethod: \"{HttpMethod}\" Path:\"{Path}\", Invocation:\"{Invocation}\"}}"; } } }
mit
C#
1b285060a4a62e055b2a1e961b155d31612ae35f
Use ViewComponent in index.cshtml
bigfont/StackOverflow,bigfont/StackOverflow,bigfont/StackOverflow,bigfont/StackOverflow
AspNetCorePlayground/Views/Home/Index.cshtml
AspNetCorePlayground/Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <h1 class="page-header">TagHelper</h1> <h2>TagHelper Structure</h2> <!-- Index.cshtml --> <my-first my-string-property="My Property Value" my-date-time-property="new DateTime()"> This is the original Inner HTML from the *.cshtml file. </my-first> <vc:my-first> This is the original Inner HTML from the *.cshtml file. </vc:my-first>
@{ ViewData["Title"] = "Home Page"; } <h1 class="page-header">TagHelper</h1> <h2>TagHelper Structure</h2> <my-first my-string-property="My Property Value" my-date-time-property="new DateTime()"> This is the original Inner HTML from the *.cshtml file. </my-first>
mit
C#
79d01d02e6b4c33258071c34d1dc0ff05c02f5f8
Bump assembly version to 1.0
alexshtf/autodiff
AutoDiff/AutoDiff/Properties/AssemblyInfo.cs
AutoDiff/AutoDiff/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("AutoDiff")] [assembly: AssemblyDescription("High-performance and high-accuracy automatic function-differentiation library suitable for optimization and numeric computing.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alex Shtof")] [assembly: AssemblyProduct("AutoDiff")] [assembly: AssemblyCopyright("Copyright © NA 2010")] [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("e294e492-271d-48ae-a047-c03bc13b9f6f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AutoDiff")] [assembly: AssemblyDescription("High-performance and high-accuracy automatic function-differentiation library suitable for optimization and numeric computing.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alex Shtof")] [assembly: AssemblyProduct("AutoDiff")] [assembly: AssemblyCopyright("Copyright © NA 2010")] [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("e294e492-271d-48ae-a047-c03bc13b9f6f")] // 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.5.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
e1e4754fac69a5df223fa361ee064b2b09dbde7e
Add guid attribute
arvydas/BlinkStickInterop,arvydas/BlinkStickInterop,arvydas/BlinkStickInterop,arvydas/BlinkStickInterop
BlinkStickInterop/Properties/AssemblyInfo.cs
BlinkStickInterop/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("BlinkStickDotNet.Interop")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Agile Innovative Ltd")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("(c) Agile Innovative Ltd")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] [assembly: GuidAttribute("1147AA5E-F138-4B3D-8759-0CDB6665DBB3")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("BlinkStickDotNet.Interop")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Agile Innovative Ltd")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("(c) Agile Innovative Ltd")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
C#
8bdc4149c91e9b43843390e8b0814599c6b7e7c6
Fix pattern: Create Disposable in OnOpen
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/ViewModels/TextResourceViewModelBase.cs
WalletWasabi.Gui/ViewModels/TextResourceViewModelBase.cs
using Avalonia; using Avalonia.Platform; using ReactiveUI; using System; using System.Collections.Generic; using System.IO; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Text; using System.Threading.Tasks; namespace WalletWasabi.Gui.ViewModels { public abstract class TextResourceViewModelBase : WasabiDocumentTabViewModel { protected CompositeDisposable Disposables { get; private set; } public string _text; public TextResourceViewModelBase(Global global, string title, Uri target) : base(global, title) { Text = ""; Target = target; } public string Text { get => _text; set => this.RaiseAndSetIfChanged(ref _text, value); } public Uri Target { get; } private async Task<string> LoadDocumentAsync(Uri target) { var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>(); using (var stream = assetLocator.Open(target)) using (var reader = new StreamReader(stream)) { return await reader.ReadToEndAsync(); } } public override void OnOpen() { base.OnOpen(); Disposables = new CompositeDisposable(); LoadDocumentAsync(Target) .ToObservable() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => Text = x) .DisposeWith(Disposables); } public override bool OnClose() { Disposables?.Dispose(); Disposables = null; return base.OnClose(); } } }
using Avalonia; using Avalonia.Platform; using ReactiveUI; using System; using System.Collections.Generic; using System.IO; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Text; using System.Threading.Tasks; namespace WalletWasabi.Gui.ViewModels { public abstract class TextResourceViewModelBase : WasabiDocumentTabViewModel { protected CompositeDisposable Disposables { get; private set; } = new CompositeDisposable(); public string _text; public TextResourceViewModelBase(Global global, string title, Uri target) : base(global, title) { Text = ""; LoadDocumentAsync(target) .ToObservable() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => Text = x) .DisposeWith(Disposables); } public string Text { get => _text; set => this.RaiseAndSetIfChanged(ref _text, value); } private async Task<string> LoadDocumentAsync(Uri target) { var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>(); using (var stream = assetLocator.Open(target)) using (var reader = new StreamReader(stream)) { return await reader.ReadToEndAsync(); } } public override bool OnClose() { Disposables?.Dispose(); Disposables = null; return base.OnClose(); } } }
mit
C#
2c6583884da70e626ae9f8a3e7177efdac6d1030
Increase news version.
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
backend/src/Squidex/Areas/Api/Controllers/News/Service/FeaturesService.cs
backend/src/Squidex/Areas/Api/Controllers/News/Service/FeaturesService.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Options; using Squidex.Areas.Api.Controllers.News.Models; using Squidex.ClientLibrary; namespace Squidex.Areas.Api.Controllers.News.Service { public sealed class FeaturesService { private const int FeatureVersion = 9; private readonly QueryContext flatten = QueryContext.Default.Flatten(); private readonly IContentsClient<NewsEntity, FeatureDto> client; public sealed class NewsEntity : Content<FeatureDto> { } public FeaturesService(IOptions<MyNewsOptions> options) { if (options.Value.IsConfigured()) { var squidexOptions = new SquidexOptions { AppName = options.Value.AppName, ClientId = options.Value.ClientId, ClientSecret = options.Value.ClientSecret, Url = "https://cloud.squidex.io" }; var clientManager = new SquidexClientManager(squidexOptions); client = clientManager.CreateContentsClient<NewsEntity, FeatureDto>("feature-news"); } } public async Task<FeaturesDto> GetFeaturesAsync(int version = 0) { var result = new FeaturesDto { Features = new List<FeatureDto>(), Version = FeatureVersion }; if (client != null && version < FeatureVersion) { var query = new ContentQuery { Filter = $"data/version/iv ge {FeatureVersion}" }; var features = await client.GetAsync(query, flatten); result.Features.AddRange(features.Items.Select(x => x.Data)); } return result; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Options; using Squidex.Areas.Api.Controllers.News.Models; using Squidex.ClientLibrary; namespace Squidex.Areas.Api.Controllers.News.Service { public sealed class FeaturesService { private const int FeatureVersion = 8; private readonly QueryContext flatten = QueryContext.Default.Flatten(); private readonly IContentsClient<NewsEntity, FeatureDto> client; public sealed class NewsEntity : Content<FeatureDto> { } public FeaturesService(IOptions<MyNewsOptions> options) { if (options.Value.IsConfigured()) { var squidexOptions = new SquidexOptions { AppName = options.Value.AppName, ClientId = options.Value.ClientId, ClientSecret = options.Value.ClientSecret, Url = "https://cloud.squidex.io" }; var clientManager = new SquidexClientManager(squidexOptions); client = clientManager.CreateContentsClient<NewsEntity, FeatureDto>("feature-news"); } } public async Task<FeaturesDto> GetFeaturesAsync(int version = 0) { var result = new FeaturesDto { Features = new List<FeatureDto>(), Version = FeatureVersion }; if (client != null && version < FeatureVersion) { var query = new ContentQuery { Filter = $"data/version/iv ge {FeatureVersion}" }; var features = await client.GetAsync(query, flatten); result.Features.AddRange(features.Items.Select(x => x.Data)); } return result; } } }
mit
C#
ddd52f1230f1a8f2806b2ea9b5e25402cecb065b
Increase feature version.
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
backend/src/Squidex/Areas/Api/Controllers/News/Service/FeaturesService.cs
backend/src/Squidex/Areas/Api/Controllers/News/Service/FeaturesService.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Options; using Squidex.Areas.Api.Controllers.News.Models; using Squidex.ClientLibrary; namespace Squidex.Areas.Api.Controllers.News.Service { public sealed class FeaturesService { private const int FeatureVersion = 16; private readonly QueryContext flatten = QueryContext.Default.Flatten(); private readonly IContentsClient<NewsEntity, FeatureDto> client; public sealed class NewsEntity : Content<FeatureDto> { } public FeaturesService(IOptions<MyNewsOptions> options) { if (options.Value.IsConfigured()) { var squidexOptions = new SquidexOptions { AppName = options.Value.AppName, ClientId = options.Value.ClientId, ClientSecret = options.Value.ClientSecret, Url = "https://cloud.squidex.io" }; var clientManager = new SquidexClientManager(squidexOptions); client = clientManager.CreateContentsClient<NewsEntity, FeatureDto>("feature-news"); } } public async Task<FeaturesDto> GetFeaturesAsync(int version = 0) { var result = new FeaturesDto { Features = new List<FeatureDto>(), Version = FeatureVersion }; if (client != null && version < FeatureVersion) { var query = new ContentQuery { Filter = $"data/version/iv ge {FeatureVersion}" }; var features = await client.GetAsync(query, flatten); result.Features.AddRange(features.Items.Select(x => x.Data)); } return result; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Options; using Squidex.Areas.Api.Controllers.News.Models; using Squidex.ClientLibrary; namespace Squidex.Areas.Api.Controllers.News.Service { public sealed class FeaturesService { private const int FeatureVersion = 15; private readonly QueryContext flatten = QueryContext.Default.Flatten(); private readonly IContentsClient<NewsEntity, FeatureDto> client; public sealed class NewsEntity : Content<FeatureDto> { } public FeaturesService(IOptions<MyNewsOptions> options) { if (options.Value.IsConfigured()) { var squidexOptions = new SquidexOptions { AppName = options.Value.AppName, ClientId = options.Value.ClientId, ClientSecret = options.Value.ClientSecret, Url = "https://cloud.squidex.io" }; var clientManager = new SquidexClientManager(squidexOptions); client = clientManager.CreateContentsClient<NewsEntity, FeatureDto>("feature-news"); } } public async Task<FeaturesDto> GetFeaturesAsync(int version = 0) { var result = new FeaturesDto { Features = new List<FeatureDto>(), Version = FeatureVersion }; if (client != null && version < FeatureVersion) { var query = new ContentQuery { Filter = $"data/version/iv ge {FeatureVersion}" }; var features = await client.GetAsync(query, flatten); result.Features.AddRange(features.Items.Select(x => x.Data)); } return result; } } }
mit
C#
0dece10552783e228b046a7f5a7cc9da162dfc48
fix nancy tests by using different metric name
huoxudong125/Metrics.NET,etishor/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,Liwoj/Metrics.NET,alhardy/Metrics.NET,etishor/Metrics.NET,Recognos/Metrics.NET,mnadel/Metrics.NET,mnadel/Metrics.NET,ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,MetaG8/Metrics.NET,cvent/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET
Src/Metrics.Tests/NancyAdapter/NancyAdapterTests.cs
Src/Metrics.Tests/NancyAdapter/NancyAdapterTests.cs
 using FluentAssertions; using Nancy; using Nancy.Metrics; using Nancy.Testing; using Xunit; namespace Metrics.Tests.NancyAdapter { public class NancyAdapterTests { public class TestModule : NancyModule { public TestModule() : base("test") { Get["/"] = _ => Response.AsText("test"); Post["/"] = _ => HttpStatusCode.OK; } } [Fact] public void NancyMetricsShouldBeAbleToRecordPostRequestSize() { var browser = new Browser(with => { with.ApplicationStartup((c, p) => NancyMetrics.RegisterPostRequestSizeHistogram(p, "testPostRequest", "nancy")); with.Module<TestModule>(); }); var response = browser.Post("/test", ctx => ctx.Body("test")); response.StatusCode.Should().Be(HttpStatusCode.OK); var histogram = Metric.Histogram("nancy.testPostRequest", Unit.None).Value; histogram.Count.Should().Be(1); histogram.Max.Should().Be("test".Length); } [Fact] public void NancyMetricsShouldBeAbleToRecordGetResponseSize() { var browser = new Browser(with => { with.ApplicationStartup((c, p) => NancyMetrics.RegisterGetResponseSizeHistogram(p, "testGetRequest", "nancy")); with.Module<TestModule>(); }); var response = browser.Get("/test"); response.StatusCode.Should().Be(HttpStatusCode.OK); var histogram = Metric.Histogram("nancy.testGetRequest", Unit.None).Value; histogram.Count.Should().Be(1); histogram.Max.Should().Be("test".Length); } } }
 using FluentAssertions; using Nancy; using Nancy.Metrics; using Nancy.Testing; using Xunit; namespace Metrics.Tests.NancyAdapter { public class NancyAdapterTests { public class TestModule : NancyModule { public TestModule() : base("test") { Get["/"] = _ => Response.AsText("test"); Post["/"] = _ => HttpStatusCode.OK; } } [Fact] public void NancyMetricsShouldBeAbleToRecordPostRequestSize() { var browser = new Browser(with => { with.ApplicationStartup((c, p) => NancyMetrics.RegisterPostRequestSizeHistogram(p, "test", "nancy")); with.Module<TestModule>(); }); var response = browser.Post("/test", ctx => ctx.Body("test")); response.StatusCode.Should().Be(HttpStatusCode.OK); var histogram = Metric.Histogram("nancy.test", Unit.None).Value; histogram.Count.Should().Be(1); histogram.Max.Should().Be("test".Length); } [Fact] public void NancyMetricsShouldBeAbleToRecordGetResponseSize() { var browser = new Browser(with => { with.ApplicationStartup((c, p) => NancyMetrics.RegisterGetResponseSizeHistogram(p, "test", "nancy")); with.Module<TestModule>(); }); var response = browser.Get("/test"); response.StatusCode.Should().Be(HttpStatusCode.OK); var histogram = Metric.Histogram("nancy.test", Unit.None).Value; histogram.Count.Should().Be(1); histogram.Max.Should().Be("test".Length); } } }
apache-2.0
C#
11c2b9ea9f846e984700b6009d433f7c47dae7ef
Update Index.cshtml
joakimskoog/AnApiOfIceAndFire,joakimskoog/AnApiOfIceAndFire
AnApiOfIceAndFire/Views/Documentation/Index.cshtml
AnApiOfIceAndFire/Views/Documentation/Index.cshtml
@using AnApiOfIceAndFire.Infrastructure.Html @{ ViewBag.Title = "Documentation"; } <h2>Documentation</h2> <div class="row"> <div class="col-sm-3 col-md-3"> <h5>Overview</h5> <div class="list-group"> <a href="#intro" class="list-group-item">Introduction</a> <a href="#current_version" class="list-group-item">Current Version</a> <a href="#authentication" class="list-group-item">Authentication</a> <a href="#pagination" class="list-group-item">Pagination</a> <a href="#rate_limiting" class="list-group-item">Rate Limiting</a> <a href="#caching" class="list-group-item">Caching</a> <a href="#versioning" class="list-group-item">Versioning</a> </div> <h5>Resources</h5> <div class="list-group"> <a href="#books" class="list-group-item">Books</a> <a href="#characters" class="list-group-item">Characters</a> <a href="#houses" class="list-group-item">Houses</a> </div> <h5>Libraries</h5> <div class="list-group"> <a href="#library-graphql" class="list-group-item">GraphQL</a> <a href="#library-node" class="list-group-item">Node</a> <a href="#library-swift" class="list-group-item">Swift</a> </div> </div> <div id="documentation" class="col-md-9 col-sm-9"> @Html.Markdown("~/Content/Documentation/Documentation.md") @Html.Markdown("~/Content/Documentation/Books.md") @Html.Markdown("~/Content/Documentation/Characters.md") @Html.Markdown("~/Content/Documentation/Houses.md") @Html.Markdown("~/Content/Documentation/Libraries.md") </div> </div>
@using AnApiOfIceAndFire.Infrastructure.Html @{ ViewBag.Title = "Documentation"; } <h2>Documentation</h2> <div class="row"> <div class="col-sm-3 col-md-3"> <h5>Overview</h5> <div class="list-group"> <a href="#intro" class="list-group-item">Introduction</a> <a href="#current_version" class="list-group-item">Current Version</a> <a href="#authentication" class="list-group-item">Authentication</a> <a href="#pagination" class="list-group-item">Pagination</a> <a href="#rate_limiting" class="list-group-item">Rate Limiting</a> <a href="#caching" class="list-group-item">Caching</a> <a href="#versioning" class="list-group-item">Versioning</a> </div> <h5>Resources</h5> <div class="list-group"> <a href="#books" class="list-group-item">Books</a> <a href="#characters" class="list-group-item">Characters</a> <a href="#houses" class="list-group-item">Houses</a> </div> <h5>Libraries</h5> <div class="list-group"> <a href="#library-node" class="list-group-item">Node</a> <a href="#library-swift" class="list-group-item">Swift</a> </div> </div> <div id="documentation" class="col-md-9 col-sm-9"> @Html.Markdown("~/Content/Documentation/Documentation.md") @Html.Markdown("~/Content/Documentation/Books.md") @Html.Markdown("~/Content/Documentation/Characters.md") @Html.Markdown("~/Content/Documentation/Houses.md") @Html.Markdown("~/Content/Documentation/Libraries.md") </div> </div>
bsd-3-clause
C#
881157bd68446793cfc2f5a45ad25f94db10d914
Debug license removed.
Scandit/barcodescanner-sdk-xamarin-samples,Scandit/barcodescanner-sdk-xamarin-samples
Native/ExtendedSample/ExtendedSample/PickerView.cs
Native/ExtendedSample/ExtendedSample/PickerView.cs
using System; using Xamarin.Forms; namespace ExtendedSample { public class PickerView : View { public event EventHandler StartScanningRequested; public event EventHandler PauseScanningRequested; public IScannerDelegate Delegate { get; set; } public Settings Settings { get; set; } public static string GetAppKey() { return "--ENTER YOUR SCANDIT LICENSE KEY HERE--"; } public void StartScanning() { StartScanningRequested?.Invoke(this, EventArgs.Empty); } public void PauseScanning() { PauseScanningRequested?.Invoke(this, EventArgs.Empty); } public void DidScan(string symbology, string code) { if (Delegate != null) { Delegate.DidScan(symbology, code); } } } }
using System; using Xamarin.Forms; namespace ExtendedSample { public class PickerView : View { public event EventHandler StartScanningRequested; public event EventHandler PauseScanningRequested; public IScannerDelegate Delegate { get; set; } public Settings Settings { get; set; } public static string GetAppKey() { return "AUSrZQgfFegTMaMl3UPk11YKZtj3KdetWX+nLv5jFRMEdXd3SkM0xi5uMs5JTR8xJl/FR2Vs7yCObka2yCEWaUVv/sZkc9OKzBgjasdRwmH7XkE0Sn5D/CNpJnXEd35fp2yQoQxzPfeCaG9HWUXwLvVW8aAzfib6G1ETKlFD0vGyVtEiPUrebqt8iem+cFxa10MwWfZg6Tp7bGq3XXRoaz50a1L5dtXdE3gRfrhOL6irauTmkXRiYkRWcON6aQCjsU7zNDpUijiBbCnKy2LPBtdccFtfQy2QYnS+FL0o9zF/d8WMOXDdI2Rcqe4pQU/1c0i4Ce4GpzNgC6XazhQjH6mFunp59E2nbOhbhZaTUZQm00SodYoX9iryvcYqjnepqT8WEGORPZzb2bry8t0X0HPNvlrnjSMuxnCjLl9n4CseLqisJVNlgJsWoSD67UbvFjMkNKXrZDLFHBhUh8tG9LIkVu/5f1gBJqtvOUQ4cKNHjH7yrTAMkk+P0XwupLHXVp/yDnafCDv8Tn1jAlC/+OpQsjeF7zkI1j7jOrV09IxWCT+eiGOo/9eGFYtAEo7KsQSHTvUECaSwwKd/gOZt4bh7SfDmNuIP10d5myF1rFYVbcOTeRVrmmr0PhrO3s4LyBRp8QK3GzSCs/Jp6TLfQCIBz3nHbW/wcVBmCyGTA8zOPzYuJFAXV/drQQUwpQavKiA1h8g71foX20Dn2bqYnAJK4goXu2bdK/9637MoLjsRTAZvT3pVrG/1aM2kkKPVgFQtDVcaQLdsHJuTyXX2M0ni40sTkCQN0YfiFjgAasnozw/5uUuDCzJVcNFq6JGdfM/zSNiK+EQaP/w2kLlf1gw1bg7iHw5CtQHqvKa2mOP0g3zntApB88ClErDwiYO4VmhQM20BalxtTbKkUhPE7lVz+e2/9z8yOPLKpIiQgqWo7xIauOjbBY3iUjgRYndtfeSM3hWXBW/1KKc8+a9ptrZPSWV+QsMNngID6rspuxsD7ScM+OH8GSperqPXGA=="; } public void StartScanning() { StartScanningRequested?.Invoke(this, EventArgs.Empty); } public void PauseScanning() { PauseScanningRequested?.Invoke(this, EventArgs.Empty); } public void DidScan(string symbology, string code) { if (Delegate != null) { Delegate.DidScan(symbology, code); } } } }
apache-2.0
C#
491db0650033bc7ba7ef5e2db205ffd603441f8a
Implement FactExceptOnUnix (working?)
PKRoma/git-tfs,pmiossec/git-tfs,vzabavnov/git-tfs,andyrooger/git-tfs,git-tfs/git-tfs
GitTfsTest/FactExceptOnUnix.cs
GitTfsTest/FactExceptOnUnix.cs
using System; using System.Collections.Generic; using Xunit; using Xunit.Sdk; namespace Sep.Git.Tfs.Test { public class FactExceptOnUnixAttribute : FactAttribute { public override string Skip { get { if (IsUnix()) return "Skipped because run on Unix"; return base.Skip; } set { base.Skip = value; } } private bool IsUnix() { return Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX; } } }
using System; using System.Collections.Generic; using Xunit; using Xunit.Sdk; namespace Sep.Git.Tfs.Test { public class FactExceptOnUnixAttribute : FactAttribute { protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { yield return new FactExceptOnUnixTestCommand(method); } private class FactExceptOnUnixTestCommand : FactCommand { public FactExceptOnUnixTestCommand(IMethodInfo method) : base(method) { } public override MethodResult Execute(object testClass) { if (IsUnix()) return new SkipResult(testMethod, DisplayName, "This test does not work on unix-like OSes yet."); return base.Execute(testClass); } private bool IsUnix() { return Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX; } } } }
apache-2.0
C#
e5956e9c5b4b44f674ab7befbbe8f33632a73270
Fix typo in XML comment (#4054)
ElanHasson/orleans,ibondy/orleans,SoftWar1923/orleans,waynemunro/orleans,ashkan-saeedi-mazdeh/orleans,waynemunro/orleans,pherbel/orleans,ElanHasson/orleans,dVakulen/orleans,hoopsomuah/orleans,dVakulen/orleans,dVakulen/orleans,sergeybykov/orleans,jokin/orleans,ashkan-saeedi-mazdeh/orleans,MikeHardman/orleans,MikeHardman/orleans,Liversage/orleans,sergeybykov/orleans,Liversage/orleans,yevhen/orleans,jthelin/orleans,brhinescot/orleans,jokin/orleans,Liversage/orleans,hoopsomuah/orleans,benjaminpetit/orleans,dotnet/orleans,brhinescot/orleans,veikkoeeva/orleans,SoftWar1923/orleans,amccool/orleans,brhinescot/orleans,jokin/orleans,jason-bragg/orleans,ibondy/orleans,dotnet/orleans,pherbel/orleans,galvesribeiro/orleans,yevhen/orleans,amccool/orleans,ReubenBond/orleans,ashkan-saeedi-mazdeh/orleans,amccool/orleans,galvesribeiro/orleans
src/Orleans.Core/Lifecycle/ServiceLifecycleStage.cs
src/Orleans.Core/Lifecycle/ServiceLifecycleStage.cs
namespace Orleans { /// <summary> /// Lifecycle stages of an orlean service. Cluster Client, or Silo /// </summary> public static class ServiceLifecycleStage { /// <summary> /// First stage in service's lifecycle /// </summary> public const int First = int.MinValue; /// <summary> /// Initialize runtime /// </summary> public const int RuntimeInitialize = 2000; /// <summary> /// Start runtime services /// </summary> public const int RuntimeServices = 4000; /// <summary> /// Initialize runtime storage /// </summary> public const int RuntimeStorageServices = 6000; /// <summary> /// Start runtime services /// </summary> public const int RuntimeGrainServices = 8000; /// <summary> /// Start application layer services /// </summary> public const int ApplicationServices = 10000; /// <summary> /// Service is active. /// </summary> public const int Active = 20000; /// <summary> /// Last stage in service's lifecycle /// </summary> public const int Last = int.MaxValue; } }
namespace Orleans { /// <summary> /// Lifecycle stages of an orlean service. Cluster Client, or Silo /// </summary> public static class ServiceLifecycleStage { /// <summary> /// First stage in service's lifecycle /// </summary> public const int First = int.MinValue; /// <summary> /// Initialize runtime /// </summary> public const int RuntimeInitialize = 2000; /// <summary> /// Start runtime services /// </summary> public const int RuntimeServices = 4000; /// <summary> /// Initialize runtime storage /// </summary> public const int RuntimeStorageServices = 6000; /// <summary> /// Start runtime services /// </summary> public const int RuntimeGrainServices = 8000; /// <summary> /// Start application layer services /// </summary> public const int ApplicationServices = 10000; /// <summary> /// Service is active. /// </summary> public const int Active = 20000; /// <summary> /// First stage in service's lifecycle /// </summary> public const int Last = int.MaxValue; } }
mit
C#
9cfb8792a54bb1463cefd8863a6aea12032f71f8
Update obsoletion warning for ISiloBuilderConfigurator (#6461)
ibondy/orleans,jason-bragg/orleans,yevhen/orleans,yevhen/orleans,waynemunro/orleans,galvesribeiro/orleans,amccool/orleans,ibondy/orleans,ElanHasson/orleans,hoopsomuah/orleans,ReubenBond/orleans,dotnet/orleans,benjaminpetit/orleans,ElanHasson/orleans,amccool/orleans,hoopsomuah/orleans,dotnet/orleans,amccool/orleans,galvesribeiro/orleans,waynemunro/orleans,veikkoeeva/orleans,jthelin/orleans
src/Orleans.TestingHost/ISiloBuilderConfigurator.cs
src/Orleans.TestingHost/ISiloBuilderConfigurator.cs
using System; using Orleans.Hosting; namespace Orleans.TestingHost { /// <summary> /// Allows implementations to configure the host builder when starting up each silo in the test cluster. /// </summary> [Obsolete("Implement " + nameof(ISiloConfigurator) + " and " + nameof(IHostConfigurator) + " instead.")] public interface ISiloBuilderConfigurator { /// <summary> /// Configures the silo host builder. /// </summary> void Configure(ISiloHostBuilder hostBuilder); } }
using System; using Orleans.Hosting; namespace Orleans.TestingHost { /// <summary> /// Allows implementations to configure the host builder when starting up each silo in the test cluster. /// </summary> [Obsolete("Use " + nameof(ISiloConfigurator) + " instead")] public interface ISiloBuilderConfigurator { /// <summary> /// Configures the silo host builder. /// </summary> void Configure(ISiloHostBuilder hostBuilder); } }
mit
C#
f0a8839c6b96d0846d975b0e4e649d95a58bc587
Remove unneeded setting of SqlParameter.Offset
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
src/SqlPersistence/Config/SqlDialect_MsSqlServer.cs
src/SqlPersistence/Config/SqlDialect_MsSqlServer.cs
namespace NServiceBus { using System; using System.Data.Common; public abstract partial class SqlDialect { /// <summary> /// Microsoft SQL Server /// </summary> public partial class MsSqlServer : SqlDialect { /// <summary> /// Microsoft SQL Server /// </summary> public MsSqlServer() { Schema = "dbo"; } internal override void AddCreationScriptParameters(DbCommand command) { command.AddParameter("schema", Schema); } internal override void SetJsonParameterValue(DbParameter parameter, object value) { SetParameterValue(parameter, value); } internal override void SetParameterValue(DbParameter parameter, object value) { if (value is ArraySegment<char> charSegment) { parameter.Value = charSegment.Array; parameter.Size = charSegment.Count; } else { parameter.Value = value; } } internal override CommandWrapper CreateCommand(DbConnection connection) { var command = connection.CreateCommand(); return new CommandWrapper(command, this); } internal override object GetCustomDialectDiagnosticsInfo() { return new { CustomSchema = string.IsNullOrEmpty(Schema), DoNotUseTransportConnection }; } internal string Schema { get; set; } } } }
namespace NServiceBus { using System; using System.Data.Common; using System.Data.SqlClient; public abstract partial class SqlDialect { /// <summary> /// Microsoft SQL Server /// </summary> public partial class MsSqlServer : SqlDialect { /// <summary> /// Microsoft SQL Server /// </summary> public MsSqlServer() { Schema = "dbo"; } internal override void AddCreationScriptParameters(DbCommand command) { command.AddParameter("schema", Schema); } internal override void SetJsonParameterValue(DbParameter parameter, object value) { SetParameterValue(parameter, value); } internal override void SetParameterValue(DbParameter parameter, object value) { //TODO: do ArraySegment fro outbox if (value is ArraySegment<char> charSegment) { var sqlParameter = (SqlParameter)parameter; sqlParameter.Value = charSegment.Array; sqlParameter.Offset = charSegment.Offset; sqlParameter.Size = charSegment.Count; } else { parameter.Value = value; } } internal override CommandWrapper CreateCommand(DbConnection connection) { var command = connection.CreateCommand(); return new CommandWrapper(command, this); } internal override object GetCustomDialectDiagnosticsInfo() { return new { CustomSchema = string.IsNullOrEmpty(Schema), DoNotUseTransportConnection }; } internal string Schema { get; set; } } } }
mit
C#
9168121327db386fff46b38fb12a04ad12206738
Change Course.cs
codinghouselondon/ContosoUniversity,codinghouselondon/ContosoUniversity
CotosoUniveristy/CotosoUniversity/Models/Course.cs
CotosoUniveristy/CotosoUniversity/Models/Course.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace CotosoUniversity.Models { public class Course { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace CotosoUniversity.Models { public class Course { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } }
mit
C#
220306b188e782e14974642fb7087e9790668938
add modifyCard command
pashchuk/Hospital-MVVM-
Hospital/DesktopApp/ViewModel/FullCardViewModel.cs
Hospital/DesktopApp/ViewModel/FullCardViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DesktopApp.Commands; using DesktopApp.Model; namespace DesktopApp.ViewModel { public class FullCardViewModel : ViewModelBase { private Card _card; private bool _state = false; public string DoctorName { get { return string.Format("{0} {1}",_card.OwnerDoctor.FirstName,_card.OwnerDoctor.LastName); } } public string FirstName { get { return _card.Patient.FirstName; } set { _card.Patient.FirstName = value; OnPropertyChanged("FirstName"); } } public string LastName { get { return _card.Patient.LastName; } set { _card.Patient.LastName = value; OnPropertyChanged("LastName"); } } public string MiddleName { get { return _card.Patient.MiddleName; } set { _card.Patient.MiddleName = value; OnPropertyChanged("MiddleName"); } } public int Age { get { return _card.Patient.Age; } set { _card.Patient.Age = value; OnPropertyChanged("Age"); } } public string Address { get { return _card.Patient.Address; } set { _card.Patient.Address = value; OnPropertyChanged("Address"); } } public string Email { get { return _card.Patient.Email; } set { _card.Patient.Email = value; OnPropertyChanged("Email"); } } public string Sex { get { return _card.Patient.Sex; } set { _card.Patient.Sex = value; OnPropertyChanged("Sex"); } } public string Phone { get { return _card.Patient.Phone; } set { _card.Patient.Phone = value; OnPropertyChanged("Phone"); } } public bool State { get { return _state; } set { _state = value; OnPropertyChanged("State"); } } public RelayCommand ModifyCardCommand { get; private set; } #region Commends void InitCommands() { ModifyCardCommand = new RelayCommand(ModifyCardExecute, ModifyCardCanExecute); } bool ModifyCardCanExecute() { return !State; } void ModifyCardExecute() { State = true; } #endregion public FullCardViewModel(Card card) { InitCommands(); _card = card; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DesktopApp.Model; namespace DesktopApp.ViewModel { class FullCardViewModel : ViewModelBase { private Card _card; public string DoctorName { get { return _card.OwnerDoctor.FirstName + _card.OwnerDoctor.LastName; } } public string FirstName { get { return _card.Patient.FirstName; } set { _card.Patient.FirstName = value; OnPropertyChanged("FirstName"); } } public string LastName { get { return _card.Patient.LastName; } set { _card.Patient.LastName = value; OnPropertyChanged("LastName"); } } public string MiddleName { get { return _card.Patient.MiddleName; } set { _card.Patient.MiddleName = value; OnPropertyChanged("MiddleName"); } } public int Age { get { return _card.Patient.Age; } set { _card.Patient.Age = value; OnPropertyChanged("Age"); } } public string Address { get { return _card.Patient.Address; } set { _card.Patient.Address = value; OnPropertyChanged("Address"); } } public string Email { get { return _card.Patient.Email; } set { _card.Patient.Email = value; OnPropertyChanged("Email"); } } public string Sex { get { return _card.Patient.Sex; } set { _card.Patient.Sex = value; OnPropertyChanged("Sex"); } } public string Phone { get { return _card.Patient.Phone; } set { _card.Patient.Phone = value; OnPropertyChanged("Phone"); } } public FullCardViewModel(Card card) { _card = card; } } }
mit
C#
cc35071617d8bcbedd0551772a7eb1b6a0ae0f6c
update expected number of lines in file loading tests
pauldambra/ModulusChecker,pauldambra/ModulusChecker
ModulusCheckingTests/Loaders/ModulusWeightTests.cs
ModulusCheckingTests/Loaders/ModulusWeightTests.cs
using System.Linq; using ModulusChecking.Loaders; using ModulusChecking.Models; using NUnit.Framework; namespace ModulusCheckingTests.Loaders { public class ModulusWeightTests { [Test] public void CanReadWeightFileResource() { var weightFile = ModulusChecking.Properties.Resources.valacdos; Assert.NotNull(weightFile); Assert.IsInstanceOf(typeof(string),weightFile); } [Test] public void CanLoadWeightFileRows() { var modulusWeight = ModulusWeightTable.GetInstance; Assert.AreEqual(1014, modulusWeight.RuleMappings.Count()); } [Test] public void CanGetRuleMappings() { var modulusWeight = ModulusWeightTable.GetInstance; Assert.NotNull(modulusWeight.RuleMappings); Assert.AreEqual(1014, modulusWeight.RuleMappings.Count); Assert.IsInstanceOf<ModulusWeightMapping>(modulusWeight.RuleMappings.ElementAt(0)); } [Test] public void ThereAreNoMod10MappingsWithExceptionFive() { var modulusWeight = ModulusWeightTable.GetInstance; Assert.IsFalse(modulusWeight.RuleMappings.Any(rm=>rm.Exception==5 && rm.Algorithm==ModulusAlgorithm.Mod10)); } [Test] public void AllExceptionNineRowsAreModEleven() { var modulusWeight = ModulusWeightTable.GetInstance; var exceptionNineRows = modulusWeight.RuleMappings.Where(rm => rm.Exception == 9).ToList(); Assert.IsTrue(exceptionNineRows.All(r => r.Algorithm == ModulusAlgorithm.Mod11)); } } }
using System.Linq; using ModulusChecking.Loaders; using ModulusChecking.Models; using NUnit.Framework; namespace ModulusCheckingTests.Loaders { public class ModulusWeightTests { [Test] public void CanReadWeightFileResource() { var weightFile = ModulusChecking.Properties.Resources.valacdos; Assert.NotNull(weightFile); Assert.IsInstanceOf(typeof(string),weightFile); } [Test] public void CanLoadWeightFileRows() { var modulusWeight = ModulusWeightTable.GetInstance; Assert.AreEqual(992, modulusWeight.RuleMappings.Count()); } [Test] public void CanGetRuleMappings() { var modulusWeight = ModulusWeightTable.GetInstance; Assert.NotNull(modulusWeight.RuleMappings); Assert.AreEqual(992, modulusWeight.RuleMappings.Count); Assert.IsInstanceOf<ModulusWeightMapping>(modulusWeight.RuleMappings.ElementAt(0)); } [Test] public void ThereAreNoMod10MappingsWithExceptionFive() { var modulusWeight = ModulusWeightTable.GetInstance; Assert.IsFalse(modulusWeight.RuleMappings.Any(rm=>rm.Exception==5 && rm.Algorithm==ModulusAlgorithm.Mod10)); } [Test] public void AllExceptionNineRowsAreModEleven() { var modulusWeight = ModulusWeightTable.GetInstance; var exceptionNineRows = modulusWeight.RuleMappings.Where(rm => rm.Exception == 9).ToList(); Assert.IsTrue(exceptionNineRows.All(r => r.Algorithm == ModulusAlgorithm.Mod11)); } } }
mit
C#
6695f206d55cd97a5ee661c764c750b0965be3ec
Use Enum.Parse overload available in PCL
cureos/Evil-DICOM,SuneBuur/Evil-DICOM
EvilDICOM.Core/EvilDICOM.Core/Helpers/EnumHelper.cs
EvilDICOM.Core/EvilDICOM.Core/Helpers/EnumHelper.cs
using System; namespace EvilDICOM.Core.Helpers { public class EnumHelper { public static T StringToEnum<T>(string name) { return (T) Enum.Parse(typeof (T), name, false); } } }
using System; namespace EvilDICOM.Core.Helpers { public class EnumHelper { public static T StringToEnum<T>(string name) { return (T) Enum.Parse(typeof (T), name); } } }
mit
C#
a659d0a22f8efbadb30f081f2aae47d47eb6e294
Fix RealmInvalidObjectException parent
realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet
Realm.Shared/exceptions/RealmInvalidObjectException.cs
Realm.Shared/exceptions/RealmInvalidObjectException.cs
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// namespace Realms { public class RealmInvalidObjectException : RealmException { internal RealmInvalidObjectException(string message) : base(message) { } } }
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// namespace Realms { public class RealmInvalidObjectException : RealmFileAccessErrorException { internal RealmInvalidObjectException(string message) : base(message) { } } }
apache-2.0
C#
f5bcaa176814d7db1c1ebe668ad687b29d4fabbb
return error
ferreirix/restratp
Controllers/HealthStatus.cs
Controllers/HealthStatus.cs
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace restratp.Controllers { [Route("/")] public class HealthStatusController : Controller { /// <summary> /// Endpoint to check the service availability. /// </summary> /// <remarks> /// </remarks> /// <returns code="200">Service is available.</returns> [HttpGet] public IActionResult Get() { try { return Ok(); } catch (Exception ex) { return BadRequest(ex.ToString()); } } } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace restratp.Controllers { [Route("/")] public class HealthStatusController : Controller { /// <summary> /// Endpoint to check the service availability. /// </summary> /// <remarks> /// </remarks> /// <returns code="200">Service is available.</returns> [HttpGet] public IActionResult Get() { return Ok(); } } }
mit
C#
d1af1429b3dd8d79ba36bc5d41ac02a75ad86bac
Fix inspection
UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new
osu.Game/Tests/Visual/RateAdjustedBeatmapTestScene.cs
osu.Game/Tests/Visual/RateAdjustedBeatmapTestScene.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; namespace osu.Game.Tests.Visual { /// <summary> /// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests. /// </summary> public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene { protected override void Update() { base.Update(); // note that this will override any mod rate application if (MusicController.TrackLoaded) { Debug.Assert(MusicController.CurrentTrack != null); MusicController.CurrentTrack.Tempo.Value = Clock.Rate; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using osu.Framework.Extensions.ObjectExtensions; namespace osu.Game.Tests.Visual { /// <summary> /// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests. /// </summary> public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene { protected override void Update() { base.Update(); // note that this will override any mod rate application if (MusicController.TrackLoaded) { Debug.Assert(MusicController.CurrentTrack != null); MusicController.CurrentTrack.Tempo.Value = Clock.Rate; } } } }
mit
C#
e9de3acbc7b5da9dafe783af74f73f5e4d7fdfd4
Update unit test pertaining to #2018 to have PG min version as 10
ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten
src/DocumentDbTests/Bugs/Bug_2018_fts_string_list.cs
src/DocumentDbTests/Bugs/Bug_2018_fts_string_list.cs
using System; using System.Collections.Generic; using Marten.Testing.Harness; using Xunit; namespace DocumentDbTests.Bugs { public class Bug_2018_fts_string_list: BugIntegrationContext { public sealed class BugFullTextSearchFields { public Guid Id { get; set; } public string Text { get; set; } public List<string> Data { get; set; } } public Bug_2018_fts_string_list() { StoreOptions(_ => _.Schema .For<BugFullTextSearchFields>() .GinIndexJsonData() .FullTextIndex(index => { index.Name = "mt_custom_my_index_name_fulltext_search"; index.RegConfig = "english"; }, x => x.Text, x => x.Data) .UseOptimisticConcurrency(true)); } [PgVersionTargetedFact(MinimumVersion = "10.0")] public void can_do_index_with_full_text_search() { using (var session = theStore.OpenSession()) { session.Store(new BugFullTextSearchFields() { Id = Guid.NewGuid(), Text = "Hello my Darling, this is a long text", Data = new List<string>() { "Foo", "VeryLongEntry", "Baz" }, }); session.SaveChanges(); } } } }
using System; using System.Collections.Generic; using Marten.Testing.Harness; using Xunit; namespace DocumentDbTests.Bugs { public class Bug_2018_fts_string_list: BugIntegrationContext { public sealed class BugFullTextSearchFields { public Guid Id { get; set; } public string Text { get; set; } public List<string> Data { get; set; } } public Bug_2018_fts_string_list() { StoreOptions(_ => _.Schema .For<BugFullTextSearchFields>() .GinIndexJsonData() .FullTextIndex(index => { index.Name = "mt_custom_my_index_name_fulltext_search"; index.RegConfig = "english"; }, x => x.Text, x => x.Data) .UseOptimisticConcurrency(true)); } [PgVersionTargetedFact(MinimumVersion = "13.0")] public void can_do_index_with_full_text_search() { using (var session = theStore.OpenSession()) { session.Store(new BugFullTextSearchFields() { Id = Guid.NewGuid(), Text = "Hello my Darling, this is a long text", Data = new List<string>() { "Foo", "VeryLongEntry", "Baz" }, }); session.SaveChanges(); } } } }
mit
C#
74ec643e4d75a7282d87a2d60a91e874356d78f7
Include non-public fields of the enum class when adding EnumItemDetail
edvineshagh/bitdiffer,grennis/bitdiffer
Source/BitDiffer.Common/Detail/EnumDetail.cs
Source/BitDiffer.Common/Detail/EnumDetail.cs
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using BitDiffer.Common.Utility; using BitDiffer.Common.Misc; using BitDiffer.Common.Configuration; namespace BitDiffer.Common.Model { [Serializable] public class EnumDetail : TypeDetail { public EnumDetail() { } public EnumDetail(RootDetail parent, Type type) : base(parent, type) { _visibility = VisibilityUtil.GetVisibilityFor(type); _category = "enum"; foreach (string name in Enum.GetNames(type)) { _children.Add( new EnumItemDetail( this, name, Convert.ToInt64( type.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static) .GetRawConstantValue()), _visibility)); } CodeStringBuilder csb = new CodeStringBuilder(); AppendAttributesDeclaration(csb); csb.Mode = AppendMode.Html; csb.AppendVisibility(_visibility); csb.AppendText(" "); csb.Mode = AppendMode.Both; csb.AppendKeyword("enum "); csb.AppendText(type.Name); csb.Mode = AppendMode.Html; csb.AppendNewline(); csb.AppendText("{"); csb.AppendNewline(); foreach (EnumItemDetail eid in FilterChildren<EnumItemDetail>()) { csb.AppendIndent(); csb.AppendText(eid.GetHtmlDeclaration()); csb.AppendText(","); csb.AppendNewline(); } csb.RemoveCharsFromEnd("<br>".Length); csb.RemoveCharsFromEnd(",".Length); csb.AppendNewline(); csb.AppendText("}"); csb.Mode = AppendMode.Both; _declaration = csb.ToString(); _declarationHtml = csb.ToHtmlString(); } public override bool CollapseChildren { get { return true; } } protected override string SerializeGetElementName() { return "Enum"; } } }
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using BitDiffer.Common.Utility; using BitDiffer.Common.Misc; using BitDiffer.Common.Configuration; namespace BitDiffer.Common.Model { [Serializable] public class EnumDetail : TypeDetail { public EnumDetail() { } public EnumDetail(RootDetail parent, Type type) : base(parent, type) { _visibility = VisibilityUtil.GetVisibilityFor(type); _category = "enum"; foreach (string name in Enum.GetNames(type)) { _children.Add( new EnumItemDetail( this, name, Convert.ToInt64( type.GetField(name) .GetRawConstantValue()), _visibility)); } CodeStringBuilder csb = new CodeStringBuilder(); AppendAttributesDeclaration(csb); csb.Mode = AppendMode.Html; csb.AppendVisibility(_visibility); csb.AppendText(" "); csb.Mode = AppendMode.Both; csb.AppendKeyword("enum "); csb.AppendText(type.Name); csb.Mode = AppendMode.Html; csb.AppendNewline(); csb.AppendText("{"); csb.AppendNewline(); foreach (EnumItemDetail eid in FilterChildren<EnumItemDetail>()) { csb.AppendIndent(); csb.AppendText(eid.GetHtmlDeclaration()); csb.AppendText(","); csb.AppendNewline(); } csb.RemoveCharsFromEnd("<br>".Length); csb.RemoveCharsFromEnd(",".Length); csb.AppendNewline(); csb.AppendText("}"); csb.Mode = AppendMode.Both; _declaration = csb.ToString(); _declarationHtml = csb.ToHtmlString(); } public override bool CollapseChildren { get { return true; } } protected override string SerializeGetElementName() { return "Enum"; } } }
mit
C#
74ee6ef6ee795099f9530ce04bd36e872667489c
Mark RainbowFolder.Name as obsolete
PhannGor/unity3d-rainbow-folders
Assets/RainbowFoldersAsset/RainbowFolders/Editor/Settings/RainbowFolder.cs
Assets/RainbowFoldersAsset/RainbowFolders/Editor/Settings/RainbowFolder.cs
/* * 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 UnityEngine; namespace Borodar.RainbowFolders.Editor.Settings { [Serializable] public class RainbowFolder { [ObsoleteAttribute("Use RainbowFolder.Key and RainbowFolder.Type instead.", false)] public string Name; public string Key; public KeyType Type; public Texture2D SmallIcon; public Texture2D LargeIcon; public enum KeyType { Name, Path } } }
/* * 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 UnityEngine; namespace Borodar.RainbowFolders.Editor.Settings { [Serializable] public class RainbowFolder { public string Name; // Just for backward compatibility, should be removed in later versions public string Key; public KeyType Type; public Texture2D SmallIcon; public Texture2D LargeIcon; public enum KeyType { Name, Path } } }
apache-2.0
C#
7b1c1b376df52d8e0f55c5e8802f8450ee838b33
fix unit tests
makmu/outlook-matters,maxlmo/outlook-matters,maxlmo/outlook-matters,makmu/outlook-matters
OutlookMatters.Test/MailItemContextMenuEntryTest.cs
OutlookMatters.Test/MailItemContextMenuEntryTest.cs
using FluentAssertions; using Microsoft.Office.Core; using Moq; using NUnit.Framework; using OutlookMatters.ContextMenu; using OutlookMatters.Mail; using OutlookMatters.Mattermost; using OutlookMatters.Settings; namespace OutlookMatters.Test { [TestFixture] public class MailItemContextMenuEntryTest { [Test] public void GetCustomUI_ReturnsCustomUiForExplorer() { var classUnderTest = new MailItemContextMenuEntry(Mock.Of<IMailExplorer>(), Mock.Of<IMattermost>(), Mock.Of<ISettingsProvider>()); var result = classUnderTest.GetCustomUI("Microsoft.Outlook.Explorer"); result.Should().NotBeEmpty("because there should be custom UI xml for the outlook explorer"); } [Test] public void OnPostClick_CreatesPostUsingSession() { const string url = "http://localhost"; const string teamId = "team"; const string username = "username"; const string password = "password"; const string channelId = "channelId"; const string message = "message"; var session = new Mock<ISession>(); var settings = new Mock<ISettingsProvider>(); settings.Setup(x => x.ChannelId).Returns(channelId); settings.Setup(x => x.Password).Returns(password); settings.Setup(x => x.TeamId).Returns(teamId); settings.Setup(x => x.Url).Returns(url); settings.Setup(x => x.Username).Returns(username); var explorer = new Mock<IMailExplorer>(); explorer.Setup(x => x.GetSelectedMailBody()).Returns(message); var mattermost = new Mock<IMattermost>(); mattermost.Setup(x => x.LoginByUsername(url, teamId, username, password)).Returns(session.Object); mattermost.Setup( x => x.LoginByUsername(url, teamId, username, password)) .Returns(session.Object); var classUnderTest = new MailItemContextMenuEntry(explorer.Object, mattermost.Object, settings.Object); classUnderTest.OnPostClick(Mock.Of<IRibbonControl>()); session.Verify(x => x.CreatePost(channelId, message)); } } }
using FluentAssertions; using Microsoft.Office.Core; using Moq; using NUnit.Framework; using OutlookMatters.ContextMenu; using OutlookMatters.Mail; using OutlookMatters.Mattermost; using OutlookMatters.Settings; namespace OutlookMatters.Test { [TestFixture] public class MailItemContextMenuEntryTest { [Test] public void GetCustomUI_ReturnsCustomUiForExplorer() { var classUnderTest = new MailItemContextMenuEntry(Mock.Of<IMailExplorer>(), Mock.Of<IMattermost>(), Mock.Of<ISettingsProvider>()); var result = classUnderTest.GetCustomUI("Microsoft.Outlook.Explorer"); result.Should().NotBeEmpty("because there should be custom UI xml for the outlook explorer"); } [Test] public void OnPostClick_CreatesPostUsingSession() { const string url = "http://localhost"; const string teamId = "team"; const string username = "username"; const string password = "password"; const string channelId = "channelId"; const string message = "message"; var session = new Mock<ISession>(); var settings = new Mock<ISettingsProvider>(); settings.Setup(x => x.ChannelId).Returns(channelId); settings.Setup(x => x.Password).Returns(password); settings.Setup(x => x.TeamId).Returns(teamId); settings.Setup(x => x.Url).Returns(url); settings.Setup(x => x.Username).Returns(username); var explorer = new Mock<IMailExplorer>(); explorer.Setup(x => x.GetSelectedMailBody()).Returns(message); var mattermost = new Mock<IMattermost>(); mattermost.Setup(x => x.LoginByUsername(url, teamId, username, password)).Returns(session.Object); mattermost.Setup( x => x.LoginByUsername(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Returns(Mock.Of<ISession>()); var classUnderTest = new MailItemContextMenuEntry(explorer.Object, mattermost.Object, settings.Object); classUnderTest.OnPostClick(Mock.Of<IRibbonControl>()); session.Verify(x => x.CreatePost(channelId, message)); } } }
mit
C#
7f96d07e0d732351eaf1ac04486c0ff8fe45781f
improve the error message when a location isn't given correctly.
LHCAtlas/AtlasSSH
PSAtlasDatasetCommands/ValidateLocationAttribute.cs
PSAtlasDatasetCommands/ValidateLocationAttribute.cs
using AtlasWorkFlows; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using System.Threading.Tasks; namespace PSAtlasDatasetCommands { /// <summary> /// Add for a location argument, makes sure that only the available locations can /// be x-checked. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] sealed class ValidateLocationAttribute : ValidateArgumentsAttribute { /// <summary> /// Setup defaults, prime with legal items. /// </summary> public ValidateLocationAttribute() { } /// <summary> /// Check against legal values. /// </summary> /// <param name="arguments"></param> /// <param name="engineIntrinsics"></param> protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { var s = arguments as string; if (s == null) { throw new ValidationMetadataException("Argument is not a string."); } if (!_validLocations.Value.Contains(s)) { var err = _validLocations.Value.Aggregate(new StringBuilder(), (bld, loc) => bld.Append($" {loc}")); throw new ValidationMetadataException($"Illegal value for Location ({s}) - possible values:{err.ToString()}"); } } public IList<string> ValidValues { get { return _validLocations.Value; } } /// <summary> /// The list of valid location. /// </summary> /// <remarks> /// Lazy so we determine it once. Also, can't put it in the ctor as that will cause /// it to be created on a simple command completion operation in powershell! /// Note: If the computer changes location after this has been initialized, it won't /// get updated! /// </remarks> private Lazy<string[]> _validLocations = new Lazy<string[]>(() => DatasetManager.ValidLocations); } }
using AtlasWorkFlows; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using System.Threading.Tasks; namespace PSAtlasDatasetCommands { /// <summary> /// Add for a location argument, makes sure that only the available locations can /// be x-checked. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] sealed class ValidateLocationAttribute : ValidateArgumentsAttribute { /// <summary> /// Setup defaults, prime with legal items. /// </summary> public ValidateLocationAttribute() { } /// <summary> /// Check against legal values. /// </summary> /// <param name="arguments"></param> /// <param name="engineIntrinsics"></param> protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { var s = arguments as string; if (s == null) { throw new ValidationMetadataException("Argument is not a string."); } if (!_validLocations.Value.Contains(s)) { var err = _validLocations.Value.Aggregate(new StringBuilder(), (bld, loc) => bld.Append($" {loc}")); throw new ValidationMetadataException($"Illegal value for Location - possible values:{err.ToString()}"); } } public IList<string> ValidValues { get { return _validLocations.Value; } } /// <summary> /// The list of valid location. /// </summary> /// <remarks> /// Lazy so we determine it once. Also, can't put it in the ctor as that will cause /// it to be created on a simple command completion operation in powershell! /// Note: If the computer changes location after this has been initialized, it won't /// get updated! /// </remarks> private Lazy<string[]> _validLocations = new Lazy<string[]>(() => DatasetManager.ValidLocations); } }
mit
C#
ab3c6a913f0c97f464e9d6a0ee5734f8ef4fca29
Fix compilation error - new requirement for IMenuAction
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
Test/AdventureWorksLegacy.AppLib/menu/MenuAction.cs
Test/AdventureWorksLegacy.AppLib/menu/MenuAction.cs
 namespace AdventureWorksLegacy.AppLib; public class MenuAction : IMenuAction { public MenuAction(string methodName, string displayName = null) { Name = methodName.ToLower().StartsWith("action") ? methodName : "Action" + methodName; DisplayName = displayName; } public string Name { get; init; } public string DisplayName { get; init; } }
 namespace AdventureWorksLegacy.AppLib; public class MenuAction : IMenuAction { public MenuAction(string name) => Name = name.ToLower().StartsWith("action") ? name : "Action" + name; public string Name { get; init; } }
apache-2.0
C#
d3cb1f56683776cadf9fa872ed12757e74bb935d
Add [Authorize] to ExecuteCommand action
bdb-opensource/whitelist-executer,bdb-opensource/whitelist-executer,bdb-opensource/whitelist-executer
WhitelistExecuter.Web/Controllers/HomeController.cs
WhitelistExecuter.Web/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WhitelistExecuter.Lib; using WhitelistExecuter.Web.Filters; using WhitelistExecuter.Web.Models; namespace WhitelistExecuter.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Whitelist Executer."; return View(new HomeModel()); } [Authorize] [HttpPost] public ActionResult ExecuteCommand(HomeModel model) { model.Error = null; using (var client = new WhitelistExecuterClient()) { ExecutionResult result; try { result = client.API.ExecuteCommand(model.Command, model.RelativePath); } catch (Exception e) { model.Error = (e.InnerException ?? e).Message; return View("Index", model); } //.....ViewBag.ViewBag.mo model.StandardOutput = result.StandardOutput; model.StandardError = result.StandardError; } return View("Index", model); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WhitelistExecuter.Lib; using WhitelistExecuter.Web.Models; namespace WhitelistExecuter.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Whitelist Executer."; return View(new HomeModel()); } [HttpPost] public ActionResult ExecuteCommand(HomeModel model) { model.Error = null; using (var client = new WhitelistExecuterClient()) { ExecutionResult result; try { result = client.API.ExecuteCommand(model.Command, model.RelativePath); } catch (Exception e) { model.Error = (e.InnerException ?? e).Message; return View("Index", model); } //.....ViewBag.ViewBag.mo model.StandardOutput = result.StandardOutput; model.StandardError = result.StandardError; } return View("Index", model); } } }
mit
C#
50e6a2910676684649a475902b35b74464545869
Fix for a crash that can occur while exporting from the level editor - falling back to the global scene manager if we can't find a scene manager attached to the dom node tree
xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE
Foreign/SonyLE/LevelEditorXLE/Services/Extensions.cs
Foreign/SonyLE/LevelEditorXLE/Services/Extensions.cs
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) using System; using Sce.Atf.Adaptation; namespace LevelEditorXLE.Extensions { internal static class ExtensionsClass { internal static GUILayer.EditorSceneManager GetSceneManager(this Sce.Atf.Dom.DomNodeAdapter adapter) { // Prefer to return the SceneManager object associated // with the root game document. If we can't find one, fall // back to the GlobalSceneManager var root = adapter.DomNode.GetRoot(); if (root != null) { var gameExt = root.As<Game.GameExtensions>(); if (gameExt != null) { var man = gameExt.SceneManager; if (man != null) return man; } } return XLEBridgeUtils.Utils.GlobalSceneManager; } } }
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) using System; using Sce.Atf.Adaptation; namespace LevelEditorXLE.Extensions { internal static class ExtensionsClass { internal static GUILayer.EditorSceneManager GetSceneManager(this Sce.Atf.Dom.DomNodeAdapter adapter) { var root = adapter.DomNode.GetRoot(); System.Diagnostics.Debug.Assert(root != null); if (root == null) return null; var gameExt = root.As<Game.GameExtensions>(); System.Diagnostics.Debug.Assert(gameExt != null); if (gameExt == null) return null; return gameExt.SceneManager; } } }
mit
C#
3849f24839c0a8c2d0c7dd9077cc2af437a1f8ec
fix failing test - use Fake Metrics initializer
gigya/microdot
tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceHost.cs
tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceHost.cs
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Ninject; using Gigya.Microdot.Orleans.Ninject.Host; using Ninject; using Ninject.Syntax; namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService { public class FakesLoggersModules : ILoggingModule { private readonly bool _useHttpLog; public FakesLoggersModules(bool useHttpLog) { _useHttpLog = useHttpLog; } public void Bind(IBindingToSyntax<ILog> logBinding, IBindingToSyntax<IEventPublisher> eventPublisherBinding) { if(_useHttpLog) logBinding.To<HttpLog>(); else logBinding.To<ConsoleLog>(); eventPublisherBinding.To<NullEventPublisher>(); } } public class CalculatorServiceHost : MicrodotOrleansServiceHost { private ILoggingModule LoggingModule { get; } public CalculatorServiceHost() : this(true) { } public CalculatorServiceHost(bool useHttpLog) { LoggingModule = new FakesLoggersModules(useHttpLog); } protected override string ServiceName => "TestService"; public override ILoggingModule GetLoggingModule() { return LoggingModule; } protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig) { kernel.Rebind<IMetricsInitializer>().To<MetricsInitializerFake>(); } } }
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Ninject; using Gigya.Microdot.Orleans.Ninject.Host; using Ninject; using Ninject.Syntax; namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService { public class FakesLoggersModules : ILoggingModule { private readonly bool _useHttpLog; public FakesLoggersModules(bool useHttpLog) { _useHttpLog = useHttpLog; } public void Bind(IBindingToSyntax<ILog> logBinding, IBindingToSyntax<IEventPublisher> eventPublisherBinding) { if(_useHttpLog) logBinding.To<HttpLog>(); else logBinding.To<ConsoleLog>(); eventPublisherBinding.To<NullEventPublisher>(); } } public class CalculatorServiceHost : MicrodotOrleansServiceHost { private ILoggingModule LoggingModule { get; } public CalculatorServiceHost() : this(true) { } public CalculatorServiceHost(bool useHttpLog) { LoggingModule = new FakesLoggersModules(useHttpLog); } protected override string ServiceName => "TestService"; public override ILoggingModule GetLoggingModule() { return LoggingModule; } protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig) { } } }
apache-2.0
C#
a564839bb639bfa301cf2c19394a323adb1b2737
Replace dashes with underlines
RSuter/NJsonSchema,NJsonSchema/NJsonSchema
src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs
src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs
//----------------------------------------------------------------------- // <copyright file="DefaultEnumNameGenerator.cs" company="NJsonSchema"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license> // <author>Rico Suter, [email protected]</author> //----------------------------------------------------------------------- namespace NJsonSchema.CodeGeneration { /// <summary>The default enumeration name generator.</summary> public class DefaultEnumNameGenerator : IEnumNameGenerator { /// <summary>Generates the enumeration name/key of the given enumeration entry.</summary> /// <param name="index">The index of the enumeration value (check <see cref="JsonSchema4.Enumeration" /> and <see cref="JsonSchema4.EnumerationNames" />).</param> /// <param name="name">The name/key.</param> /// <param name="value">The value.</param> /// <param name="schema">The schema.</param> /// <returns>The enumeration name.</returns> public string Generate(int index, string name, object value, JsonSchema4 schema) { return ConversionUtilities.ConvertToUpperCamelCase(name .Replace(":", "-").Replace(@"""", @""), true) .Replace("-", "_") .Replace(".", "_") .Replace("#", "_") .Replace("\\", "_"); } } }
//----------------------------------------------------------------------- // <copyright file="DefaultEnumNameGenerator.cs" company="NJsonSchema"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license> // <author>Rico Suter, [email protected]</author> //----------------------------------------------------------------------- namespace NJsonSchema.CodeGeneration { /// <summary>The default enumeration name generator.</summary> public class DefaultEnumNameGenerator : IEnumNameGenerator { /// <summary>Generates the enumeration name/key of the given enumeration entry.</summary> /// <param name="index">The index of the enumeration value (check <see cref="JsonSchema4.Enumeration" /> and <see cref="JsonSchema4.EnumerationNames" />).</param> /// <param name="name">The name/key.</param> /// <param name="value">The value.</param> /// <param name="schema">The schema.</param> /// <returns>The enumeration name.</returns> public string Generate(int index, string name, object value, JsonSchema4 schema) { if (schema.Type == JsonObjectType.Integer) return name.Replace("-", "_"); return ConversionUtilities.ConvertToUpperCamelCase(name .Replace(":", "-").Replace(@"""", @""), true) .Replace(".", "_") .Replace("#", "_") .Replace("\\", "_"); } } }
mit
C#
0bd03727e4d87ad83a805917ef105c7e22310018
Update ConvertorHex.cs
smad2005/ConvertorHexString
HexToString/ConvertorHex.cs
HexToString/ConvertorHex.cs
using System; using System.Globalization; using System.Linq; using System.Text; namespace HexToString { public static class ConvertorHex { public static string BytesToHex(Byte [] bytes) { return string.Concat(bytes.Select(y => y.ToString("x2")).ToArray()); } public static string StringToHex(string text, Encoding encoding) { return BytesToHex(encoding.GetBytes(text)); } public static string StringToHex(string text) { return StringToHex(text, Encoding.Default); } public static byte[] HexToBytes(string hexTex) { return String.IsNullOrEmpty(hexTex) ?null :Enumerable.Range(0, hexTex.Length - 1).Where(y => (y & 1) == 0).Select(y => Byte.Parse(hexTex[y] + hexTex[y + 1].ToString(), NumberStyles.HexNumber)).ToArray(); } public static string HexToString(string hexTex, Encoding encoding) { return String.IsNullOrEmpty(hexTex) ? String.Empty : encoding.GetString(HexToBytes(hexTex)); } public static string HexToString(string hexTex) { return HexToString(hexTex, Encoding.Default); } } }
using System; using System.Globalization; using System.Linq; using System.Text; namespace HexToString { public class ConvertorHex { public string StringToHex(string text, Encoding encoding) { return String.Join(String.Empty, encoding.GetBytes(text).Select(y => y.ToString("x"))); } public string StringToHex(string text) { return StringToHex(text, Encoding.Default); } public string HexToString(string hexTex, Encoding encoding) { return String.IsNullOrEmpty(hexTex)? String.Empty: encoding.GetString(Enumerable.Range(0, hexTex.Length - 1).Where(y => (y & 1) == 0).Select(y => Byte.Parse(hexTex[y] + hexTex[y + 1].ToString(), NumberStyles.HexNumber)).ToArray()); } public string HexToString(string hexTex) { return HexToString(hexTex, Encoding.Default); } } }
mit
C#
6cb7ea2e7568ae5350ac50b0a36d735378f46603
optimize XMLserializer
23S163PR/system-programming
Novak.Andriy/parallel-extension-demo/XMLSerilizer.cs
Novak.Andriy/parallel-extension-demo/XMLSerilizer.cs
using System; using System.IO; using System.Runtime.Serialization; using System.Xml.Serialization; namespace parallel_extension_demo { public static class XSerializer<T> { private static readonly XmlSerializer XmlSerializer; static XSerializer() { XmlSerializer = new XmlSerializer(typeof(T)); } public static void XSerilizer(T obj, string fileName) { try { if (obj == null) return; using (var fs = new FileStream(string.Format(@"../../Groups Employee/{0}",fileName), FileMode.OpenOrCreate)) { XmlSerializer.Serialize(fs, obj); fs.Flush(); } } catch (SerializationException xe) { Console.WriteLine(xe.Message); } catch (IOException e) { Console.WriteLine(e.Message); } } } }
using System; using System.IO; using System.Runtime.Serialization; using System.Xml.Serialization; namespace parallel_extension_demo { public static class XSerializer { public static void XSerilizer<T>(T obj, string fileName) { try { if (obj == null) return; var xmlSerializer = new XmlSerializer(typeof(T)); using (var fs = new FileStream(string.Format(@"../../Groups Employee/{0}",fileName), FileMode.OpenOrCreate)) { xmlSerializer.Serialize(fs, obj); fs.Flush(); } } catch (SerializationException xe) { Console.WriteLine(xe.Message); } catch (IOException e) { Console.WriteLine(e.Message); } } } }
cc0-1.0
C#
18c45a6b0ba58b548f24aa378a775e110595b571
Add digits
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
LeetCode/remote/add_digits.cs
LeetCode/remote/add_digits.cs
using System; using System.Linq; static class Program { static int DigitalRoot(this int x) { while (x.ToString().Length != 1) { x = x.ToString().Select(a => a - '0').Sum(); } return x; } static int AddDigits(this int x) { if (x == 0) return 0; if (x % 9 == 0) return 9; return x % 9; } static void Main() { for (int i = 0; i < int.MaxValue / 1000; i++) { if (i.DigitalRoot() != i.AddDigits()) { throw new Exception("You are dumb"); } } } } // https://leetcode.com/submissions/detail/58787808/ public class Solution { public int AddDigits(int num) { return num % 9 == 0 && num != 0 ? 9 : num % 9; } }
using System; using System.Linq; static class Program { static int DigitalRoot(this int x) { while (x.ToString().Length != 1) { x = x.ToString().Select(a => a - '0').Sum(); } return x; } static int AddDigits(this int x) { if (x == 0) return 0; if (x % 9 == 0) return 9; return x % 9; } static void Main() { for (int i = 0; i < int.MaxValue / 1000; i++) { if (i.DigitalRoot() != i.AddDigits()) { throw new Exception("You are dumb"); } } } }
mit
C#
2ca5f3b6874b97ec171bf406e2dd9c3b85119091
Reduce number of items
henrikfroehling/RangeIt
Source/Tests/Iterator.Performance.Tests/Constants.cs
Source/Tests/Iterator.Performance.Tests/Constants.cs
namespace Iterator.Performance.Tests { public static class Constants { public const int MAX_ITEMS = 1000; } }
namespace Iterator.Performance.Tests { public static class Constants { public const int MAX_ITEMS = 10000; } }
mit
C#
1e18359ad3172dd8d6f36e2b70b6a153d8edcfda
clean up
british-proverbs/british-proverbs-mvc-6,british-proverbs/british-proverbs-mvc-6
src/BritishProverbs.Web/Controllers/HomeController.cs
src/BritishProverbs.Web/Controllers/HomeController.cs
using System.Threading.Tasks; using BritishProverbs.Domain; using BritishProverbs.Web.Models; using Microsoft.AspNet.Mvc; namespace BritishProverbs.Web.Controllers { public class HomeController : Controller { private readonly IBritishProverbsContext _context; public HomeController(IBritishProverbsContext context) { _context = context; } public async Task<IActionResult> Index() { var proverb = await _context.GetRandomAsync(); return View(new ProverbViewModel { Content = proverb.Content }); } public IActionResult Error() { return View("~/Views/Shared/Error.cshtml"); } } }
using System; using System.Threading.Tasks; using BritishProverbs.Domain; using BritishProverbs.Web.Models; using Microsoft.AspNet.Mvc; namespace BritishProverbs.Web.Controllers { public class HomeController : Controller { private readonly IBritishProverbsContext _context; public HomeController(IBritishProverbsContext context) { _context = context; } public async Task<IActionResult> Index() { var proverb = await _context.GetRandomAsync(); return View(new ProverbViewModel { Content = proverb.Content }); } public IActionResult Error() { return View("~/Views/Shared/Error.cshtml"); } } }
mit
C#
ea81d615bfbeec73cafd8d513b53cff33e015207
remove unneeded dbset for mapping table
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Data/Contexts/FilterListsDbContext.cs
src/FilterLists.Data/Contexts/FilterListsDbContext.cs
using FilterLists.Data.Entities; using FilterLists.Data.EntityTypeConfigurations; using Microsoft.EntityFrameworkCore; namespace FilterLists.Data.Contexts { public class FilterListsDbContext : DbContext, IFilterListsDbContext { public FilterListsDbContext(DbContextOptions options) : base(options) { } public DbSet<FilterList> FilterLists { get; set; } public DbSet<Maintainer> Maintainers { get; set; } public DbSet<Language> Languages { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new FilterListTypeConfiguration()); modelBuilder.ApplyConfiguration(new MaintainerTypeConfiguration()); modelBuilder.ApplyConfiguration(new LanguageTypeConfiguration()); modelBuilder.ApplyConfiguration(new FilterListLanguageTypeConfiguration()); base.OnModelCreating(modelBuilder); } } }
using FilterLists.Data.Entities; using FilterLists.Data.EntityTypeConfigurations; using Microsoft.EntityFrameworkCore; namespace FilterLists.Data.Contexts { public class FilterListsDbContext : DbContext, IFilterListsDbContext { public FilterListsDbContext(DbContextOptions options) : base(options) { } public DbSet<FilterListLanguage> FilterListLanguages { get; set; } public DbSet<FilterList> FilterLists { get; set; } public DbSet<Maintainer> Maintainers { get; set; } public DbSet<Language> Languages { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new FilterListTypeConfiguration()); modelBuilder.ApplyConfiguration(new MaintainerTypeConfiguration()); modelBuilder.ApplyConfiguration(new LanguageTypeConfiguration()); modelBuilder.ApplyConfiguration(new FilterListLanguageTypeConfiguration()); base.OnModelCreating(modelBuilder); } } }
mit
C#
fbceb413151d91c7b035dbfd56efb45ff3f2aadd
fix #289 errors in multisearch
starckgates/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,alanprot/elasticsearch-net,TheFireCookie/elasticsearch-net,LeoYao/elasticsearch-net,Grastveit/NEST,NickCraver/NEST,KodrAus/elasticsearch-net,gayancc/elasticsearch-net,NickCraver/NEST,wawrzyn/elasticsearch-net,jonyadamit/elasticsearch-net,SeanKilleen/elasticsearch-net,Grastveit/NEST,UdiBen/elasticsearch-net,LeoYao/elasticsearch-net,joehmchan/elasticsearch-net,tkirill/elasticsearch-net,robertlyson/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,junlapong/elasticsearch-net,LeoYao/elasticsearch-net,RossLieberman/NEST,abibell/elasticsearch-net,gayancc/elasticsearch-net,alanprot/elasticsearch-net,robertlyson/elasticsearch-net,junlapong/elasticsearch-net,CSGOpenSource/elasticsearch-net,cstlaurent/elasticsearch-net,adam-mccoy/elasticsearch-net,geofeedia/elasticsearch-net,KodrAus/elasticsearch-net,wawrzyn/elasticsearch-net,amyzheng424/elasticsearch-net,elastic/elasticsearch-net,ststeiger/elasticsearch-net,TheFireCookie/elasticsearch-net,geofeedia/elasticsearch-net,SeanKilleen/elasticsearch-net,robrich/elasticsearch-net,DavidSSL/elasticsearch-net,alanprot/elasticsearch-net,azubanov/elasticsearch-net,mac2000/elasticsearch-net,CSGOpenSource/elasticsearch-net,abibell/elasticsearch-net,tkirill/elasticsearch-net,amyzheng424/elasticsearch-net,amyzheng424/elasticsearch-net,jonyadamit/elasticsearch-net,cstlaurent/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,DavidSSL/elasticsearch-net,SeanKilleen/elasticsearch-net,gayancc/elasticsearch-net,ststeiger/elasticsearch-net,joehmchan/elasticsearch-net,tkirill/elasticsearch-net,KodrAus/elasticsearch-net,faisal00813/elasticsearch-net,jonyadamit/elasticsearch-net,robrich/elasticsearch-net,mac2000/elasticsearch-net,UdiBen/elasticsearch-net,junlapong/elasticsearch-net,ststeiger/elasticsearch-net,joehmchan/elasticsearch-net,abibell/elasticsearch-net,geofeedia/elasticsearch-net,elastic/elasticsearch-net,robertlyson/elasticsearch-net,mac2000/elasticsearch-net,adam-mccoy/elasticsearch-net,robrich/elasticsearch-net,wawrzyn/elasticsearch-net,Grastveit/NEST,starckgates/elasticsearch-net,starckgates/elasticsearch-net,azubanov/elasticsearch-net,alanprot/elasticsearch-net,faisal00813/elasticsearch-net,DavidSSL/elasticsearch-net,faisal00813/elasticsearch-net,RossLieberman/NEST,NickCraver/NEST
src/Nest/Resolvers/Converters/MultiSearchConverter.cs
src/Nest/Resolvers/Converters/MultiSearchConverter.cs
using System; using System.Collections.Generic; using System.Linq; using Nest.Domain; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Reflection; namespace Nest.Resolvers.Converters { public class MultiSearchConverter : JsonConverter { private class MultiHitTuple { public JToken Hit { get; set; } public KeyValuePair<string, SearchDescriptorBase> Descriptor { get; set; } } private readonly MultiSearchDescriptor _descriptor; private static MethodInfo MakeDelegateMethodInfo = typeof(MultiSearchConverter).GetMethod("CreateMultiHit", BindingFlags.Static | BindingFlags.NonPublic); public MultiSearchConverter(MultiSearchDescriptor descriptor) { _descriptor = descriptor; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotSupportedException(); } private static void CreateMultiHit<T>(MultiHitTuple tuple, JsonSerializer serializer, IDictionary<string, object> collection) where T : class { var hit = new QueryResponse<T>(); var reader = tuple.Hit.CreateReader(); serializer.Populate(reader, hit); var errorProperty = tuple.Hit.Children<JProperty>().FirstOrDefault(c=>c.Name == "error"); if (errorProperty != null) { hit.IsValid = false; hit.ConnectionStatus = new ConnectionStatus(new ConnectionError(errorProperty.Value.ToString(), 500)); } collection.Add(tuple.Descriptor.Key, hit); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var response = new MultiSearchResponse(); var jsonObject = JObject.Load(reader); var docsJarray = (JArray)jsonObject["responses"]; if (docsJarray == null) return response; var multiSearchDescriptor = this._descriptor; if (this._descriptor == null) return multiSearchDescriptor; var withMeta = docsJarray.Zip(this._descriptor._Operations, (doc, desc) => new MultiHitTuple { Hit = doc, Descriptor = desc }); foreach (var m in withMeta) { var generic = MakeDelegateMethodInfo.MakeGenericMethod(m.Descriptor.Value._ClrType); generic.Invoke(null, new object[] { m, serializer, response._Responses }); } return response; } public override bool CanConvert(Type objectType) { return objectType == typeof(MultiSearchResponse); } } }
using System; using System.Collections.Generic; using System.Linq; using Nest.Domain; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Reflection; namespace Nest.Resolvers.Converters { public class MultiSearchConverter : JsonConverter { private class MultiHitTuple { public JToken Hit { get; set; } public KeyValuePair<string, SearchDescriptorBase> Descriptor { get; set; } } private readonly MultiSearchDescriptor _descriptor; private static MethodInfo MakeDelegateMethodInfo = typeof(MultiSearchConverter).GetMethod("CreateMultiHit", BindingFlags.Static | BindingFlags.NonPublic); public MultiSearchConverter(MultiSearchDescriptor descriptor) { _descriptor = descriptor; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotSupportedException(); } private static void CreateMultiHit<T>(MultiHitTuple tuple, JsonSerializer serializer, IDictionary<string, object> collection) where T : class { var hit = new QueryResponse<T>(); var reader = tuple.Hit.CreateReader(); serializer.Populate(reader, hit); collection.Add(tuple.Descriptor.Key, hit); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var response = new MultiSearchResponse(); var jsonObject = JObject.Load(reader); var docsJarray = (JArray)jsonObject["responses"]; if (docsJarray == null) return response; var multiSearchDescriptor = this._descriptor; if (this._descriptor == null) return multiSearchDescriptor; var withMeta = docsJarray.Zip(this._descriptor._Operations, (doc, desc) => new MultiHitTuple { Hit = doc, Descriptor = desc }); foreach (var m in withMeta) { var generic = MakeDelegateMethodInfo.MakeGenericMethod(m.Descriptor.Value._ClrType); generic.Invoke(null, new object[] { m, serializer, response._Responses }); } return response; } public override bool CanConvert(Type objectType) { return objectType == typeof(MultiSearchResponse); } } }
apache-2.0
C#
4471bf434b32a704513cbe8eb7f15dd2d449abfb
Refactor CacheMiss test
vanashimko/MPP.Mapper
MapperTests/DtoMapperTests.cs
MapperTests/DtoMapperTests.cs
using System; using Xunit; using Mapper; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Moq; namespace Mapper.Tests { public class DtoMapperTests { [Fact] public void Map_NullPassed_ExceptionThrown() { IMapper mapper = new DtoMapper(); Assert.Throws<ArgumentNullException>(() => mapper.Map<object, object>(null)); } [Fact] public void Map_TwoCompatibleFields_TwoFieldsAssigned() { IMapper mapper = new DtoMapper(); var source = new Source { FirstProperty = 1, SecondProperty = "a", ThirdProperty = 3.14, FourthProperty = 2 }; var expected = new Destination { FirstProperty = source.FirstProperty, SecondProperty = source.SecondProperty, }; Destination actual = mapper.Map<Source, Destination>(source); Assert.Equal(expected, actual); } [Fact] public void Map_CacheMiss_GetCacheForDidNotCalled() { var mockCache = Mock.Of<IMappingFunctionsCache>(); IMapper mapper = new DtoMapper(mockCache); mapper.Map<object, object>(new object()); Mock.Get(mockCache).Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Never); } [Fact] public void Map_CacheHit_GetCacheForCalled() { var mockCache = new Mock<IMappingFunctionsCache>(); mockCache.Setup(mock => mock.HasCacheFor(It.IsAny<MappingEntryInfo>())).Returns(true); mockCache.Setup(mock => mock.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>())).Returns(x => x); IMapper mapper = new DtoMapper(mockCache.Object); mapper.Map<object, object>(new object()); mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Once); } } }
using System; using Xunit; using Mapper; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Moq; namespace Mapper.Tests { public class DtoMapperTests { [Fact] public void Map_NullPassed_ExceptionThrown() { IMapper mapper = new DtoMapper(); Assert.Throws<ArgumentNullException>(() => mapper.Map<object, object>(null)); } [Fact] public void Map_TwoCompatibleFields_TwoFieldsAssigned() { IMapper mapper = new DtoMapper(); var source = new Source { FirstProperty = 1, SecondProperty = "a", ThirdProperty = 3.14, FourthProperty = 2 }; var expected = new Destination { FirstProperty = source.FirstProperty, SecondProperty = source.SecondProperty, }; Destination actual = mapper.Map<Source, Destination>(source); Assert.Equal(expected, actual); } [Fact] public void Map_CacheMiss_GetCacheForDidNotCalled() { var mockCache = new Mock<IMappingFunctionsCache>(); IMapper mapper = new DtoMapper(mockCache.Object); mapper.Map<object, object>(new object()); mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Never); } [Fact] public void Map_CacheHit_GetCacheForCalled() { var mockCache = new Mock<IMappingFunctionsCache>(); mockCache.Setup(mock => mock.HasCacheFor(It.IsAny<MappingEntryInfo>())).Returns(true); mockCache.Setup(mock => mock.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>())).Returns(x => x); IMapper mapper = new DtoMapper(mockCache.Object); mapper.Map<object, object>(new object()); mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Once); } } }
mit
C#
c9e1a10426c08c8bdda0f4b0e42521266e0a815e
Add warning about item source
kamsar/Unicorn,kamsar/Unicorn
src/Unicorn/PowerShell/NewUnicornItemSourceCommand.cs
src/Unicorn/PowerShell/NewUnicornItemSourceCommand.cs
using System.Collections.Generic; using System.Linq; using System.Management.Automation; using Cognifide.PowerShell.Commandlets.Packages; using Sitecore.Configuration; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Globalization; using Sitecore.Install; using Sitecore.Install.Configuration; using Sitecore.Install.Items; using Sitecore.Install.Utils; using Unicorn.Configuration; using Unicorn.Predicates; namespace Unicorn.PowerShell { /// <summary> /// $foo = $config | New-UnicornItemSource [-Project] [-Name] [-InstallMode] [-MergeMode] [-SkipVersions] /// /// Complete example, packaging several Unicorn configurations: /// $pkg = New-Package /// Get-UnicornConfiguration "Foundation.*" | New-UnicornItemSource -Project $pkg /// Export-Package -Project $pkg -Path "C:\foo.zip" /// /// NOTE: This cmdlet generates the package based off the database state, not serialized state. /// Make sure you sync your database with serialized before generating packages with this. /// </summary> [Cmdlet(VerbsCommon.New, "UnicornItemSource")] [OutputType(typeof(ExplicitItemSource))] public class NewUnicornItemSourceCommand : BasePackageCommand { [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Mandatory = true)] public IConfiguration Configuration { get; set; } [Parameter(Position = 0)] public string Name { get; set; } [Parameter(Position = 1)] public SwitchParameter SkipVersions { get; set; } [Parameter] public InstallMode InstallMode { get; set; } [Parameter] public MergeMode MergeMode { get; set; } /// <summary> /// If set adds the source(s) generated to a package project created with New-Package /// </summary> [Parameter] public PackageProject Project { get; set; } protected override void ProcessRecord() { var source = new ExplicitItemSource { Name = Name ?? Configuration.Name, SkipVersions = SkipVersions.IsPresent }; if (InstallMode != InstallMode.Undefined) { source.Converter.Transforms.Add( new InstallerConfigurationTransform(new BehaviourOptions(InstallMode, MergeMode))); } var predicate = Configuration.Resolve<IPredicate>(); var roots = predicate.GetRootPaths(); var processingQueue = new Queue<Item>(); foreach (var root in roots) { var db = Factory.GetDatabase(root.DatabaseName); var item = db.GetItem(root.Path); if (item == null) continue; processingQueue.Enqueue(item); } while (processingQueue.Count > 0) { var item = processingQueue.Dequeue(); source.Entries.Add(new ItemReference(item.Database.Name, item.Paths.Path, item.ID, Language.Invariant, Version.Latest).ToString()); foreach (var child in item.Children.Where(chd => predicate.Includes(new Rainbow.Storage.Sc.ItemData(chd)).IsIncluded)) { processingQueue.Enqueue(child); } } if(Project == null) WriteObject(source, false); Project?.Sources.Add(source); } } }
using System.Collections.Generic; using System.Linq; using System.Management.Automation; using Cognifide.PowerShell.Commandlets.Packages; using Sitecore.Configuration; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Globalization; using Sitecore.Install; using Sitecore.Install.Configuration; using Sitecore.Install.Items; using Sitecore.Install.Utils; using Unicorn.Configuration; using Unicorn.Predicates; namespace Unicorn.PowerShell { /// <summary> /// $foo = $config | New-UnicornItemSource [-Project] [-Name] [-InstallMode] [-MergeMode] [-SkipVersions] /// /// Complete example, packaging several Unicorn configurations: /// $pkg = New-Package /// Get-UnicornConfiguration "Foundation.*" | New-UnicornItemSource -Project $pkg /// Export-Package -Project $pkg -Path "C:\foo.zip" /// </summary> [Cmdlet(VerbsCommon.New, "UnicornItemSource")] [OutputType(typeof(ExplicitItemSource))] public class NewUnicornItemSourceCommand : BasePackageCommand { [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Mandatory = true)] public IConfiguration Configuration { get; set; } [Parameter(Position = 0)] public string Name { get; set; } [Parameter(Position = 1)] public SwitchParameter SkipVersions { get; set; } [Parameter] public InstallMode InstallMode { get; set; } [Parameter] public MergeMode MergeMode { get; set; } /// <summary> /// If set adds the source(s) generated to a package project created with New-Package /// </summary> [Parameter] public PackageProject Project { get; set; } protected override void ProcessRecord() { var source = new ExplicitItemSource { Name = Name ?? Configuration.Name, SkipVersions = SkipVersions.IsPresent }; if (InstallMode != InstallMode.Undefined) { source.Converter.Transforms.Add( new InstallerConfigurationTransform(new BehaviourOptions(InstallMode, MergeMode))); } var predicate = Configuration.Resolve<IPredicate>(); var roots = predicate.GetRootPaths(); var processingQueue = new Queue<Item>(); foreach (var root in roots) { var db = Factory.GetDatabase(root.DatabaseName); var item = db.GetItem(root.Path); if (item == null) continue; processingQueue.Enqueue(item); } while (processingQueue.Count > 0) { var item = processingQueue.Dequeue(); source.Entries.Add(new ItemReference(item.Database.Name, item.Paths.Path, item.ID, Language.Invariant, Version.Latest).ToString()); foreach (var child in item.Children.Where(chd => predicate.Includes(new Rainbow.Storage.Sc.ItemData(chd)).IsIncluded)) { processingQueue.Enqueue(child); } } if(Project == null) WriteObject(source, false); Project?.Sources.Add(source); } } }
mit
C#
f2a75cc5f404610ec07163e1b647eb0e0f1ac214
bump version
alecgorge/adzerk-dot-net
Adzerk.Api/Properties/AssemblyInfo.cs
Adzerk.Api/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("Adzerk.Api")] [assembly: AssemblyDescription("Unofficial Adzerk API client.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stack Exchange")] [assembly: AssemblyProduct("Adzerk.Api")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")] // 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.0.0.15")] [assembly: AssemblyFileVersion("0.0.0.15")]
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("Adzerk.Api")] [assembly: AssemblyDescription("Unofficial Adzerk API client.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stack Exchange")] [assembly: AssemblyProduct("Adzerk.Api")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")] // 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.0.0.14")] [assembly: AssemblyFileVersion("0.0.0.14")]
mit
C#
ef8bbca8cd61cdf8c038296e2b69e5b12ba0904f
Bump assembly version to 3.0.0
ericburcham/Reflections
Source/AssemblyVersionInfo.cs
Source/AssemblyVersionInfo.cs
using System.Reflection; // Version information for an assembly consists of the following four values: // // We use Semantic Versioning: http://semver.org/ // Given a version number MAJOR.MINOR.PATCH.REVISION, increment the: // // MAJOR Version - When you make incompatible API changes, // MINOR Version - When you add functionality in a backwards-compatible manner, and // PATCH Version - When you make backwards-compatible bug fixes. // REVISION Version - Never. [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")]
using System.Reflection; // Version information for an assembly consists of the following four values: // // We use Semantic Versioning: http://semver.org/ // Given a version number MAJOR.MINOR.PATCH.REVISION, increment the: // // MAJOR Version - When you make incompatible API changes, // MINOR Version - When you add functionality in a backwards-compatible manner, and // PATCH Version - When you make backwards-compatible bug fixes. // REVISION Version - Never. [assembly: AssemblyVersion("2.1.1.0")] [assembly: AssemblyFileVersion("2.1.1.0")]
mit
C#
12b1a8620ef03fc271d4760ef8c5db5c490891fd
Update price source
mplacona/BargainHunter
BargainHunter/Helpers/AmazonHelper.cs
BargainHunter/Helpers/AmazonHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using NKCraddock.AmazonItemLookup.Client; namespace BargainHunter.Helpers { public class AmazonHelper { private static readonly String AwsAccessKey = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY"); private static readonly String AwsSecretKey = Environment.GetEnvironmentVariable("AWS_SECRET_KEY"); private static readonly String AwsAssociateTag = Environment.GetEnvironmentVariable("AWS_ASSOCIATE_TAG"); public double? GetPriceByAsin(String asin) { return GetClient().ItemLookupByAsin(asin).OfferPrice; } private static AwsProductApiClient GetClient() { var client = new AwsProductApiClient(new ProductApiConnectionInfo { AWSAccessKey = AwsAccessKey, AWSSecretKey = AwsSecretKey, AWSAssociateTag = AwsAssociateTag, AWSServerUri = "webservices.amazon.co.uk" }); return client; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using NKCraddock.AmazonItemLookup.Client; namespace BargainHunter.Helpers { public class AmazonHelper { private static readonly String AwsAccessKey = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY"); private static readonly String AwsSecretKey = Environment.GetEnvironmentVariable("AWS_SECRET_KEY"); private static readonly String AwsAssociateTag = Environment.GetEnvironmentVariable("AWS_ASSOCIATE_TAG"); public double? GetPriceByAsin(String asin) { return GetClient().ItemLookupByAsin(asin).ListPrice; } private static AwsProductApiClient GetClient() { var client = new AwsProductApiClient(new ProductApiConnectionInfo { AWSAccessKey = AwsAccessKey, AWSSecretKey = AwsSecretKey, AWSAssociateTag = AwsAssociateTag, AWSServerUri = "webservices.amazon.co.uk" }); return client; } } }
mit
C#
b9bc40aee1a65390e942200691cbb738f7c2d52d
Fix compilation issue
another-guy/CSharpToTypeScript,another-guy/CSharpToTypeScript
CSharpToTypeScript.Tests/TestFiles.cs
CSharpToTypeScript.Tests/TestFiles.cs
using System; using System.IO; using System.Reflection; using CSharpToTypeScript.Tests.Integration; namespace CSharpToTypeScript.Tests { public sealed class TestFiles { public string GetSampleFile(string fileName) { return new FileInfo(GetAssemblyLocation()) .Directory .Parent .Parent .Parent .UseAsArgFor(directory => Path.Combine(directory.FullName, "SampleFiles", fileName)); } public string GetAssemblyLocation() { return typeof(TargetTypesLocatorTest) .GetTypeInfo() .Assembly .Location; } } }
using System; using System.IO; using System.Reflection; namespace CSharpToTypeScript.Tests { public sealed class TestFiles { public string GetSampleFile(string fileName) { return new FileInfo(GetAssemblyLocation()) .Directory .Parent .Parent .Parent .UseAsArgFor(directory => Path.Combine(directory.FullName, "SampleFiles", fileName)); } public string GetAssemblyLocation() { return typeof(TargetTypesLocatorTest) .GetTypeInfo() .Assembly .Location; } } }
mit
C#
4fdf578fee97c8e79e5e96b23f7e52444aa9d642
Add integration tests for links and forms
mattgwagner/CertiPay.Common
CertiPay.PDF.Tests/PDFServiceTests.cs
CertiPay.PDF.Tests/PDFServiceTests.cs
using NUnit.Framework; using System.IO; namespace CertiPay.PDF.Tests { public class PDFServiceTests { [Test] public void ShouldGenerateMultiPagePDF() { IPDFService svc = new PDFService(); byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { @"http://google.com", @"http://github.com" } }); File.WriteAllBytes("Output.pdf", output); } [Test] public void Should_Generate_Landscape_PDF() { IPDFService svc = new PDFService { }; byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { "http://google.com" }, UseLandscapeOrientation = true }); File.WriteAllBytes("Output-Landscape.pdf", output); } [Test] public void Should_Generate_Live_Form_PDF() { IPDFService svc = new PDFService { }; byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { "http://google.com" }, UseForms = true }); File.WriteAllBytes("Output-Form.pdf", output); } [Test] public void Should_Generate_Live_Links_PDF() { IPDFService svc = new PDFService { }; byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { "http://google.com" }, UseLinks = true }); File.WriteAllBytes("Output-Links.pdf", output); } } }
using NUnit.Framework; using System.IO; namespace CertiPay.PDF.Tests { public class PDFServiceTests { [Test] public void ShouldGenerateMultiPagePDF() { IPDFService svc = new PDFService(); byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { @"http://google.com", @"http://github.com" } }); File.WriteAllBytes("Output.pdf", output); } [Test] public void Should_Generate_Landscape_PDF() { IPDFService svc = new PDFService { }; byte[] output = svc.CreatePdf(new PDFService.Settings { Uris = new[] { "http://google.com" }, UseLandscapeOrientation = true }); File.WriteAllBytes("Output-Landscape.pdf", output); } } }
mit
C#
d37e5a6429686e6f2b7544081e514e7b1c9bf52f
Fix for #621.
ryancyq/aspnetboilerplate,MDSNet2016/aspnetboilerplate,zquans/aspnetboilerplate,4nonym0us/aspnetboilerplate,zclmoon/aspnetboilerplate,ryancyq/aspnetboilerplate,oceanho/aspnetboilerplate,berdankoca/aspnetboilerplate,luchaoshuai/aspnetboilerplate,MDSNet2016/aspnetboilerplate,jaq316/aspnetboilerplate,lemestrez/aspnetboilerplate,chenkaibin/aspnetboilerplate,verdentk/aspnetboilerplate,ZhaoRd/aspnetboilerplate,oceanho/aspnetboilerplate,daywrite/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,Nongzhsh/aspnetboilerplate,chenkaibin/aspnetboilerplate,jaq316/aspnetboilerplate,yhhno/aspnetboilerplate,verdentk/aspnetboilerplate,carldai0106/aspnetboilerplate,fengyeju/aspnetboilerplate,beratcarsi/aspnetboilerplate,s-takatsu/aspnetboilerplate,ryancyq/aspnetboilerplate,AndHuang/aspnetboilerplate,AlexGeller/aspnetboilerplate,fengyeju/aspnetboilerplate,ShiningRush/aspnetboilerplate,4nonym0us/aspnetboilerplate,Tobyee/aspnetboilerplate,lemestrez/aspnetboilerplate,ZhaoRd/aspnetboilerplate,690486439/aspnetboilerplate,verdentk/aspnetboilerplate,virtualcca/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ShiningRush/aspnetboilerplate,ilyhacker/aspnetboilerplate,oceanho/aspnetboilerplate,lvjunlei/aspnetboilerplate,yuzukwok/aspnetboilerplate,Nongzhsh/aspnetboilerplate,beratcarsi/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate,SXTSOFT/aspnetboilerplate,Nongzhsh/aspnetboilerplate,luchaoshuai/aspnetboilerplate,4nonym0us/aspnetboilerplate,daywrite/aspnetboilerplate,lvjunlei/aspnetboilerplate,virtualcca/aspnetboilerplate,s-takatsu/aspnetboilerplate,yhhno/aspnetboilerplate,Tobyee/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,AlexGeller/aspnetboilerplate,AlexGeller/aspnetboilerplate,daywrite/aspnetboilerplate,ddNils/aspnetboilerplate,andmattia/aspnetboilerplate,carldai0106/aspnetboilerplate,SXTSOFT/aspnetboilerplate,burakaydemir/aspnetboilerplate,jaq316/aspnetboilerplate,zquans/aspnetboilerplate,lemestrez/aspnetboilerplate,andmattia/aspnetboilerplate,zquans/aspnetboilerplate,berdankoca/aspnetboilerplate,ShiningRush/aspnetboilerplate,nineconsult/Kickoff2016Net,chendong152/aspnetboilerplate,Tobyee/aspnetboilerplate,chenkaibin/aspnetboilerplate,690486439/aspnetboilerplate,chendong152/aspnetboilerplate,berdankoca/aspnetboilerplate,lvjunlei/aspnetboilerplate,virtualcca/aspnetboilerplate,ZhaoRd/aspnetboilerplate,nineconsult/Kickoff2016Net,ryancyq/aspnetboilerplate,s-takatsu/aspnetboilerplate,fengyeju/aspnetboilerplate,yuzukwok/aspnetboilerplate,ddNils/aspnetboilerplate,zclmoon/aspnetboilerplate,yuzukwok/aspnetboilerplate,AndHuang/aspnetboilerplate,SXTSOFT/aspnetboilerplate,carldai0106/aspnetboilerplate,beratcarsi/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,zclmoon/aspnetboilerplate,andmattia/aspnetboilerplate,burakaydemir/aspnetboilerplate,690486439/aspnetboilerplate,carldai0106/aspnetboilerplate,ddNils/aspnetboilerplate,AndHuang/aspnetboilerplate
src/Abp.RedisCache/RedisCache/AbpRedisCache.cs
src/Abp.RedisCache/RedisCache/AbpRedisCache.cs
using Abp.Runtime.Caching; using StackExchange.Redis; using System; using Abp.RedisCache.Configuration; using Abp.RedisCache.RedisImpl; namespace Abp.RedisCache { public class AbpRedisCache : CacheBase { private readonly ConnectionMultiplexer _connectionMultiplexer; private readonly AbpRedisCacheConfig _config; public IDatabase Database { get { return _connectionMultiplexer.GetDatabase(); } } /// <summary> /// Constructor. /// </summary> public AbpRedisCache(string name, IAbpRedisConnectionProvider redisConnectionProvider, AbpRedisCacheConfig config) : base(name) { _config = config; var connectionString = redisConnectionProvider.GetConnectionString(_config.ConnectionStringKey); _connectionMultiplexer = redisConnectionProvider.GetConnection(connectionString); } public override object GetOrDefault(string key) { var objbyte = Database.StringGet(GetLocalizedKey(key)); return objbyte.HasValue ? SerializeUtil.Deserialize(objbyte) : null; } public override void Set(string key, object value, TimeSpan? slidingExpireTime = null) { if (value == null) { throw new AbpException("Can not insert null values to the cache!"); } Database.StringSet( GetLocalizedKey(key), SerializeUtil.Serialize(value), slidingExpireTime ); } public override void Remove(string key) { Database.KeyDelete(GetLocalizedKey(key)); } public override void Clear() { Database.KeyDeleteWithPrefix(GetLocalizedKey("*")); } private string GetLocalizedKey(string key) { return "n:" + Name + ",c:" + key; } } }
using Abp.Runtime.Caching; using StackExchange.Redis; using System; using Abp.RedisCache.Configuration; using Abp.RedisCache.RedisImpl; namespace Abp.RedisCache { public class AbpRedisCache : CacheBase { private readonly ConnectionMultiplexer _connectionMultiplexer; private readonly AbpRedisCacheConfig _config; public IDatabase Database { get { return _connectionMultiplexer.GetDatabase(); } } /// <summary> /// Constructor. /// </summary> public AbpRedisCache(string name, IAbpRedisConnectionProvider redisConnectionProvider, AbpRedisCacheConfig config) : base(name) { _config = config; var connectionString = redisConnectionProvider.GetConnectionString(_config.ConnectionStringKey); _connectionMultiplexer = redisConnectionProvider.GetConnection(connectionString); } public override object GetOrDefault(string key) { var objbyte = Database.StringGet(GetLocalizedKey(key)); return objbyte.HasValue ? SerializeUtil.Deserialize(objbyte) : null; } public override void Set(string key, object value, TimeSpan? slidingExpireTime = null) { if (value == null) { throw new AbpException("Can not insert null values to the cache!"); } Database.StringSet( GetLocalizedKey(key), SerializeUtil.Serialize(value), slidingExpireTime ); } public override void Remove(string key) { Database.KeyDelete(key); } public override void Clear() { Database.KeyDeleteWithPrefix(GetLocalizedKey("*")); } private string GetLocalizedKey(string key) { return "n:" + Name + ",c:" + key; } } }
mit
C#
45c91ddfb8914cfb821174635e616cc8195cb5f7
update AssemblyProduct
AspectCore/Lite,AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Abstractions
src/AspectCore.Lite/Properties/AssemblyInfo.cs
src/AspectCore.Lite/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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AspectCore.Lite")] [assembly: AssemblyTrademark("")] // 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("ecf5a0e5-3d63-410d-bcdc-4c46b2c79f23")]
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AspectCore.Lite.Abstractions")] [assembly: AssemblyTrademark("")] // 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("ecf5a0e5-3d63-410d-bcdc-4c46b2c79f23")]
mit
C#
f71d6b64c1085a6b0d1aaaf221e1c56248eaf1dc
add new Path measurement API on IGeometryImpl.cs
jkoritzinsky/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,grokys/Perspex
src/Avalonia.Visuals/Platform/IGeometryImpl.cs
src/Avalonia.Visuals/Platform/IGeometryImpl.cs
using Avalonia.Media; namespace Avalonia.Platform { /// <summary> /// Defines the platform-specific interface for a <see cref="Geometry"/>. /// </summary> public interface IGeometryImpl { /// <summary> /// Gets the geometry's bounding rectangle. /// </summary> Rect Bounds { get; } /// <summary> /// Gets the geometry's total length as if all its contours are placed /// in a straight line. /// </summary> double ContourLength { get; } /// <summary> /// Gets the geometry's bounding rectangle with the specified pen. /// </summary> /// <param name="pen">The pen to use. May be null.</param> /// <returns>The bounding rectangle.</returns> Rect GetRenderBounds(IPen pen); /// <summary> /// Indicates whether the geometry's fill contains the specified point. /// </summary> /// <param name="point">The point.</param> /// <returns><c>true</c> if the geometry contains the point; otherwise, <c>false</c>.</returns> bool FillContains(Point point); /// <summary> /// Intersects the geometry with another geometry. /// </summary> /// <param name="geometry">The other geometry.</param> /// <returns>A new <see cref="IGeometryImpl"/> representing the intersection.</returns> IGeometryImpl Intersect(IGeometryImpl geometry); /// <summary> /// Indicates whether the geometry's stroke contains the specified point. /// </summary> /// <param name="pen">The stroke to use.</param> /// <param name="point">The point.</param> /// <returns><c>true</c> if the geometry contains the point; otherwise, <c>false</c>.</returns> bool StrokeContains(IPen pen, Point point); /// <summary> /// Makes a clone of the geometry with the specified transform. /// </summary> /// <param name="transform">The transform.</param> /// <returns>The cloned geometry.</returns> ITransformedGeometryImpl WithTransform(Matrix transform); /// <summary> /// Attempts to get the corresponding point from the /// specified distance /// </summary> /// <param name="distance">The contour distance to get from.</param> /// <param name="point">The point in the specified distance.</param> /// <returns>If there's valid point at the specified distance.</returns> bool TryGetPointAtDistance(double distance, out Point point); /// <summary> /// Attempts to get the corresponding point and /// tangent from the specified distance along the /// contour of the geometry. /// </summary> /// <param name="distance">The contour distance to get from.</param> /// <param name="point">The point in the specified distance.</param> /// <param name="tangent">The tangent in the specified distance.</param> /// <returns>If there's valid point and tangent at the specified distance.</returns> bool TryGetPositionAndTangentAtDistance (double distance, out Point position, out Point tangent); } }
using Avalonia.Media; namespace Avalonia.Platform { /// <summary> /// Defines the platform-specific interface for a <see cref="Geometry"/>. /// </summary> public interface IGeometryImpl { /// <summary> /// Gets the geometry's bounding rectangle. /// </summary> Rect Bounds { get; } /// <summary> /// Gets the geometry's bounding rectangle with the specified pen. /// </summary> /// <param name="pen">The pen to use. May be null.</param> /// <returns>The bounding rectangle.</returns> Rect GetRenderBounds(IPen pen); /// <summary> /// Indicates whether the geometry's fill contains the specified point. /// </summary> /// <param name="point">The point.</param> /// <returns><c>true</c> if the geometry contains the point; otherwise, <c>false</c>.</returns> bool FillContains(Point point); /// <summary> /// Intersects the geometry with another geometry. /// </summary> /// <param name="geometry">The other geometry.</param> /// <returns>A new <see cref="IGeometryImpl"/> representing the intersection.</returns> IGeometryImpl Intersect(IGeometryImpl geometry); /// <summary> /// Indicates whether the geometry's stroke contains the specified point. /// </summary> /// <param name="pen">The stroke to use.</param> /// <param name="point">The point.</param> /// <returns><c>true</c> if the geometry contains the point; otherwise, <c>false</c>.</returns> bool StrokeContains(IPen pen, Point point); /// <summary> /// Makes a clone of the geometry with the specified transform. /// </summary> /// <param name="transform">The transform.</param> /// <returns>The cloned geometry.</returns> ITransformedGeometryImpl WithTransform(Matrix transform); } }
mit
C#
dc25f6e303bb158026d26409f59eb4a20f78db15
Update BehaviorOfT.cs
XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors,XamlBehaviors/XamlBehaviors
src/Avalonia.Xaml.Interactivity/BehaviorOfT.cs
src/Avalonia.Xaml.Interactivity/BehaviorOfT.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.ComponentModel; namespace Avalonia.Xaml.Interactivity { /// <summary> /// A base class for behaviors making them code compatible with older frameworks, /// and allow for typed associated objects. /// </summary> /// <typeparam name="T">The object type to attach to</typeparam> public abstract class Behavior<T> : Behavior where T : AvaloniaObject { /// <summary> /// Gets the object to which this behavior is attached. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public new T AssociatedObject => base.AssociatedObject as T; /// <summary> /// Called after the behavior is attached to the <see cref="Behavior.AssociatedObject"/>. /// </summary> /// <remarks> /// Override this to hook up functionality to the <see cref="Behavior.AssociatedObject"/> /// </remarks> protected override void OnAttached() { base.OnAttached(); if (AssociatedObject == null) { string actualType = base.AssociatedObject.GetType().FullName; string expectedType = typeof(T).FullName; string message = string.Format("AssociatedObject is of type {0} but should be of type {1}.", actualType, expectedType); throw new InvalidOperationException(message); } } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Avalonia.Xaml.Interactivity { /// <summary> /// A base class for behaviors making them code compatible with older frameworks, /// and allow for typed associated objects. /// </summary> /// <typeparam name="T">The object type to attach to</typeparam> public abstract class Behavior<T> : Behavior where T : AvaloniaObject { /// <summary> /// Gets the object to which this behavior is attached. /// </summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public new T AssociatedObject => base.AssociatedObject as T; /// <summary> /// Called after the behavior is attached to the <see cref="Behavior.AssociatedObject"/>. /// </summary> /// <remarks> /// Override this to hook up functionality to the <see cref="Behavior.AssociatedObject"/> /// </remarks> protected override void OnAttached() { base.OnAttached(); if (AssociatedObject == null) { string actualType = base.AssociatedObject.GetType().FullName; string expectedType = typeof(T).FullName; string message = string.Format("AssociatedObject is of type {0} but should be of type {1}.", actualType, expectedType); throw new InvalidOperationException(message); } } } }
mit
C#
0998c46a85d69aa1088fce794be17343721fdc4d
Add missing StructLayout attribute
vbfox/pinvoke,AArnott/pinvoke,jmelosegui/pinvoke
src/BCrypt/BCrypt+BCRYPT_PKCS1_PADDING_INFO.cs
src/BCrypt/BCrypt+BCRYPT_PKCS1_PADDING_INFO.cs
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System.Runtime.InteropServices; /// <content> /// Contains the <see cref="BCRYPT_PKCS1_PADDING_INFO"/> nested type. /// </content> public partial class BCrypt { /// <summary> /// The BCRYPT_PKCS1_PADDING_INFO structure is used to provide options for the PKCS #1 padding scheme. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct BCRYPT_PKCS1_PADDING_INFO { /// <summary> /// A pointer to a null-terminated Unicode string that identifies the cryptographic algorithm to use to create the padding. This algorithm must be a hashing algorithm. When creating a signature, the object identifier (OID) that corresponds to this algorithm is added to the DigestInfo element in the signature, and if this member is NULL, then the OID is not added. When verifying a signature, the verification fails if the OID that corresponds to this member is not the same as the OID in the signature. If there is no OID in the signature, then verification fails unless this member is NULL. /// </summary> public string pszAlgId; } } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { /// <content> /// Contains the <see cref="BCRYPT_PKCS1_PADDING_INFO"/> nested type. /// </content> public partial class BCrypt { /// <summary> /// The BCRYPT_PKCS1_PADDING_INFO structure is used to provide options for the PKCS #1 padding scheme. /// </summary> public struct BCRYPT_PKCS1_PADDING_INFO { /// <summary> /// A pointer to a null-terminated Unicode string that identifies the cryptographic algorithm to use to create the padding. This algorithm must be a hashing algorithm. When creating a signature, the object identifier (OID) that corresponds to this algorithm is added to the DigestInfo element in the signature, and if this member is NULL, then the OID is not added. When verifying a signature, the verification fails if the OID that corresponds to this member is not the same as the OID in the signature. If there is no OID in the signature, then verification fails unless this member is NULL. /// </summary> public string pszAlgId; } } }
mit
C#
25aea091d9d8aaf7fbdc8ce777fa11ae9b5c752b
add comment
zyouyowa/Unity_cs
lockOnScripts/PlayerLockOn.cs
lockOnScripts/PlayerLockOn.cs
using UnityEngine; using System.Collections; /* * これは使用例 * こんな感じに使う */ public class PlayerLockOn : MonoBehaviour { private bool flag_down, flag, flag_up; private LockOnManager lockOnManager; private GameObject target; private bool lookOn; void Start () { flag_down = flag = flag_up = false; lockOnManager = GameObject.FindWithTag ("GameManager").GetComponent<LockOnManager> (); lookOn = false; } void Update () { /* if(Input.GetAxis("Fire1")==1.0f)でもいいはず * 実数の比較はなんか信用できないので↓のようにしただけ。わりとどうでもいい */ flag = !(Input.GetAxis ("Fire1") != 1.0f); if (flag) { flag_up = true; if (flag_down) { OnFire1Down (); flag_down = false; } } else { flag_down = true; if (flag_up) { OnFire1Up (); flag_up = false; } } } void FixedUpdate () { if (flag) { OnFire1 (); } if (lookOn) { } else { } } //down,upはフレームレートに依存しないのでFixed内でしなくていいと思われる。 void OnFire1Down () { lookOn = !lookOn; if (lookOn) { target = lockOnManager.FindNearestObject (transform); //だいたいnullを返してくるから↓は必須 if (target == null) { lookOn = false; } } } void OnFire1Up () { } void OnFire1 () { } }
using UnityEngine; using System.Collections; /* * これは使用例 * こんな感じに使う */ public class PlayerLockOn : MonoBehaviour { private bool flag_down, flag, flag_up; private LockOnManager lockOnManager; private GameObject target; private bool lookOn; void Start () { flag_down = flag = flag_up = false; lockOnManager = GameObject.FindWithTag ("GameManager").GetComponent<LockOnManager> (); lookOn = false; } void Update () { /* if(Input.GetAxis("Fire1")==1.0f)でもいいはず * 実数の比較はなんか信用できないので↓のようにしただけ。わりとどうでもいい */ flag = !(Input.GetAxis ("Fire1") != 1.0f); if (flag) { flag_up = true; if (flag_down) { OnFire1Down (); flag_down = false; } } else { flag_down = true; if (flag_up) { OnFire1Up (); flag_up = false; } } } void FixedUpdate () { if (flag) { OnFire1 (); } if (lookOn) { } else { } } //down,upはフレームレートに依存しないのでFixed内でしなくていいと思われる。 void OnFire1Down () { lookOn = !lookOn; if (lookOn) { target = lockOnManager.FindNearestObject (transform); if (target == null) { lookOn = false; } } } void OnFire1Up () { } void OnFire1 () { } }
mit
C#
5654353e0e670148bab719bb3d11fb6134d4f37d
Use NonGeneric entry point for MessagePack-CSharp serializer
inter8ection/Obvs,megakid/Obvs.Serialization,inter8ection/Obvs.Serialization
Obvs.Serialization.MessagePack-CSharp/MessagePackCSharpMessageSerializer.cs
Obvs.Serialization.MessagePack-CSharp/MessagePackCSharpMessageSerializer.cs
using System.IO; using MessagePack; using MessagePack.Resolvers; namespace Obvs.Serialization.MessagePack { public class MessagePackCSharpMessageSerializer : IMessageSerializer { private readonly IFormatterResolver _resolver; public MessagePackCSharpMessageSerializer() : this(null) { } public MessagePackCSharpMessageSerializer(IFormatterResolver resolver) { _resolver = resolver ?? StandardResolver.Instance; } public void Serialize(Stream destination, object message) { MessagePackSerializer.NonGeneric.Serialize(message.GetType(), destination, message, _resolver); } } }
using System.IO; using MessagePack; using MessagePack.Resolvers; namespace Obvs.Serialization.MessagePack { public class MessagePackCSharpMessageSerializer : IMessageSerializer { private readonly IFormatterResolver _resolver; public MessagePackCSharpMessageSerializer() : this(null) { } public MessagePackCSharpMessageSerializer(IFormatterResolver resolver) { _resolver = resolver ?? StandardResolver.Instance; } public void Serialize(Stream destination, object message) { MessagePackSerializer.Serialize(destination, message, _resolver); } } }
mit
C#
9684db07cbbe3ef208c15b035b2c4299235ae431
Update grammar in RethrowExceptionAnalyzer.cs #839
carloscds/code-cracker,code-cracker/code-cracker,giggio/code-cracker,code-cracker/code-cracker,carloscds/code-cracker,eriawan/code-cracker,jwooley/code-cracker
src/CSharp/CodeCracker/Usage/RethrowExceptionAnalyzer.cs
src/CSharp/CodeCracker/Usage/RethrowExceptionAnalyzer.cs
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using System.Linq; namespace CodeCracker.CSharp.Usage { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class RethrowExceptionAnalyzer : DiagnosticAnalyzer { internal const string Title = "Your throw does nothing"; internal const string MessageFormat = "{0}"; internal const string Category = SupportedCategories.Naming; const string Description = "If a exception is caught and then thrown again the original stack trace will be lost. " + "Instead it is best to throw the exception without using any parameters."; internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId.RethrowException.ToDiagnosticId(), Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.RethrowException)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ThrowStatement); private static void Analyzer(SyntaxNodeAnalysisContext context) { if (context.IsGenerated()) return; var throwStatement = (ThrowStatementSyntax)context.Node; var ident = throwStatement.Expression as IdentifierNameSyntax; if (ident == null) return; var exSymbol = context.SemanticModel.GetSymbolInfo(ident).Symbol as ILocalSymbol; if (exSymbol == null) return; var catchClause = context.Node.Parent.AncestorsAndSelf().OfType<CatchClauseSyntax>().FirstOrDefault(); if (catchClause == null) return; var catchExSymbol = context.SemanticModel.GetDeclaredSymbol(catchClause.Declaration); if (!catchExSymbol.Equals(exSymbol)) return; var diagnostic = Diagnostic.Create(Rule, throwStatement.GetLocation(), "Throwing the same exception that was caught will loose the original stack trace."); context.ReportDiagnostic(diagnostic); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using System.Linq; namespace CodeCracker.CSharp.Usage { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class RethrowExceptionAnalyzer : DiagnosticAnalyzer { internal const string Title = "Your throw does nothing"; internal const string MessageFormat = "{0}"; internal const string Category = SupportedCategories.Naming; const string Description = "Throwing the same exception as passed to the 'catch' block lose the original " + "stack trace and will make debugging this exception a lot more difficult.\r\n" + "The correct way to rethrow an exception without changing it is by using 'throw' without any parameter."; internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId.RethrowException.ToDiagnosticId(), Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.RethrowException)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ThrowStatement); private static void Analyzer(SyntaxNodeAnalysisContext context) { if (context.IsGenerated()) return; var throwStatement = (ThrowStatementSyntax)context.Node; var ident = throwStatement.Expression as IdentifierNameSyntax; if (ident == null) return; var exSymbol = context.SemanticModel.GetSymbolInfo(ident).Symbol as ILocalSymbol; if (exSymbol == null) return; var catchClause = context.Node.Parent.AncestorsAndSelf().OfType<CatchClauseSyntax>().FirstOrDefault(); if (catchClause == null) return; var catchExSymbol = context.SemanticModel.GetDeclaredSymbol(catchClause.Declaration); if (!catchExSymbol.Equals(exSymbol)) return; var diagnostic = Diagnostic.Create(Rule, throwStatement.GetLocation(), "Don't throw the same exception you caught, you lose the original stack trace."); context.ReportDiagnostic(diagnostic); } } }
apache-2.0
C#
c1b8f3abf39a4856e5f48a20a59ecc14580947a0
Fix doc comment
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Identity/IQueryableUserStore.cs
src/Microsoft.AspNetCore.Identity/IQueryableUserStore.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; namespace Microsoft.AspNetCore.Identity { /// <summary> /// Provides an abstraction for querying users in a User store. /// </summary> /// <typeparam name="TUser">The type encapsulating a user.</typeparam> public interface IQueryableUserStore<TUser> : IUserStore<TUser> where TUser : class { /// <summary> /// Returns an <see cref="IQueryable{T}"/> collection of users. /// </summary> /// <value>An <see cref="IQueryable{T}"/> collection of users.</value> IQueryable<TUser> Users { get; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; namespace Microsoft.AspNetCore.Identity { /// <summary> /// Provides an abstraction for querying roles in a User store. /// </summary> /// <typeparam name="TUser">The type encapsulating a user.</typeparam> public interface IQueryableUserStore<TUser> : IUserStore<TUser> where TUser : class { /// <summary> /// Returns an <see cref="IQueryable{T}"/> collection of users. /// </summary> /// <value>An <see cref="IQueryable{T}"/> collection of users.</value> IQueryable<TUser> Users { get; } } }
apache-2.0
C#
d8bc967dd9895d2a2e2ad9ba7e0ed54bc1410941
Remove inheritance chain for ChargeShippingOptions
stripe/stripe-dotnet
src/Stripe.net/Services/Charges/ChargeShippingOptions.cs
src/Stripe.net/Services/Charges/ChargeShippingOptions.cs
namespace Stripe { using Newtonsoft.Json; public class ChargeShippingOptions : INestedOptions { /// <summary> /// Shipping address. /// </summary> [JsonProperty("address")] public AddressOptions Address { get; set; } /// <summary> /// The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. /// </summary> [JsonProperty("carrier")] public string Carrier { get; set; } /// <summary> /// Recipient name. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// Recipient phone (including extension). /// </summary> [JsonProperty("phone")] public string Phone { get; set; } /// <summary> /// The tracking number for a physical product, obtained from the delivery service. If /// multiple tracking numbers were generated for this purchase, please separate them with /// commas. /// </summary> [JsonProperty("tracking_number")] public string TrackingNumber { get; set; } } }
namespace Stripe { using Newtonsoft.Json; public class ChargeShippingOptions : ShippingOptions { [JsonProperty("carrier")] public string Carrier { get; set; } [JsonProperty("tracking_number")] public string TrackingNumber { get; set; } } }
apache-2.0
C#
effd342f3afc9e6a2e98f0166a766d63366ee2af
Handle pixels that supposed to obscure sprite parts
k-t/SharpHaven
MonoHaven.Client/Graphics/Sprites/SpriteSheet.cs
MonoHaven.Client/Graphics/Sprites/SpriteSheet.cs
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using MonoHaven.Resources; namespace MonoHaven.Graphics.Sprites { public class SpriteSheet : IEnumerable<SpritePart>, IDisposable { private Texture tex; private readonly List<SpritePart> parts; public SpriteSheet(IEnumerable<ImageData> images, Point center) { parts = new List<SpritePart>(); Pack(images.ToArray(), center); } public void Dispose() { if (tex != null) tex.Dispose(); } public IEnumerator<SpritePart> GetEnumerator() { return parts.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } private void Pack(ImageData[] images, Point center) { var bitmaps = new Bitmap[images.Length]; var regions = new Rectangle[images.Length]; try { var packer = new NaiveHorizontalPacker(); // calculate pack for (int i = 0; i < images.Length; i++) using (var ms = new MemoryStream(images[i].Data)) { bitmaps[i] = MakeTransparent(new Bitmap(ms)); regions[i] = packer.Add(bitmaps[i].Size); } tex = new Texture(packer.PackWidth, packer.PackHeight); // add sprite parts to the texture for (int i = 0; i < images.Length; i++) { var slice = new TextureSlice(tex, regions[i]); slice.Update(bitmaps[i]); var img = images[i]; var off = Point.Subtract(img.DrawOffset, (Size)center); parts.Add(new SpritePart(img.Id, slice, off, regions[i].Size, img.Z, img.SubZ)); } } finally { foreach (var bitmap in bitmaps.Where(x => x != null)) bitmap.Dispose(); } } private static Bitmap MakeTransparent(Bitmap bitmap) { for (int i = 0; i < bitmap.Width; i++) for (int j = 0; j < bitmap.Height; j++) if ((bitmap.GetPixel(i, j).ToArgb() & 0x00ffffff) == 0x00ff0080) bitmap.SetPixel(i, j, Color.FromArgb(128, 0, 0, 0)); return bitmap; } private class NaiveHorizontalPacker { private const int Padding = 1; private int packWidth; private int packHeight; public int PackWidth { get { return packWidth; } } public int PackHeight { get { return packHeight; } } public Rectangle Add(Size sz) { var rect = new Rectangle(packWidth, 0, sz.Width, sz.Height); packWidth += sz.Width + Padding; packHeight = Math.Max(packHeight, sz.Height); return rect; } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using MonoHaven.Resources; namespace MonoHaven.Graphics.Sprites { public class SpriteSheet : IEnumerable<SpritePart>, IDisposable { private Texture tex; private readonly List<SpritePart> parts; public SpriteSheet(IEnumerable<ImageData> images, Point center) { parts = new List<SpritePart>(); Pack(images.ToArray(), center); } public void Dispose() { if (tex != null) tex.Dispose(); } public IEnumerator<SpritePart> GetEnumerator() { return parts.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } private void Pack(ImageData[] images, Point center) { var bitmaps = new Bitmap[images.Length]; var regions = new Rectangle[images.Length]; try { var packer = new NaiveHorizontalPacker(); // calculate pack for (int i = 0; i < images.Length; i++) using (var ms = new MemoryStream(images[i].Data)) { bitmaps[i] = new Bitmap(ms); regions[i] = packer.Add(bitmaps[i].Size); } tex = new Texture(packer.PackWidth, packer.PackHeight); // add sprite parts to the texture for (int i = 0; i < images.Length; i++) { var slice = new TextureSlice(tex, regions[i]); slice.Update(bitmaps[i]); var img = images[i]; var off = Point.Subtract(img.DrawOffset, (Size)center); parts.Add(new SpritePart(img.Id, slice, off, regions[i].Size, img.Z, img.SubZ)); } } finally { foreach (var bitmap in bitmaps.Where(x => x != null)) bitmap.Dispose(); } } private class NaiveHorizontalPacker { private const int Padding = 1; private int packWidth; private int packHeight; public int PackWidth { get { return packWidth; } } public int PackHeight { get { return packHeight; } } public Rectangle Add(Size sz) { var rect = new Rectangle(packWidth, 0, sz.Width, sz.Height); packWidth += sz.Width + Padding; packHeight = Math.Max(packHeight, sz.Height); return rect; } } } }
mit
C#
d995d027d10a4740982ff17459f56c1518e2cc16
Convert EncryptedString to String explicitly
detunized/lastpass-sharp,rottenorange/lastpass-sharp,detunized/lastpass-sharp
example/Program.cs
example/Program.cs
using System; using System.IO; using LastPass; namespace Example { class Program { static void Main(string[] args) { // Read LastPass credentials from a file // The file should contain 2 lines: username and password. // See credentials.txt.example for an example. var credentials = File.ReadAllLines("../../credentials.txt"); var username = credentials[0]; var password = credentials[1]; // Fetch and create the vault from LastPass var vault = Vault.Create(username, password); // Decrypt all accounts vault.DecryptAllAccounts(Account.Field.Name | Account.Field.Username | Account.Field.Password | Account.Field.Group, username, password); // Dump all the accounts for (var i = 0; i < vault.Accounts.Length; ++i) { var account = vault.Accounts[i]; // Need explicit converstion to string. // String.Format doesn't do that for EncryptedString. Console.WriteLine("{0}: {1} {2} {3} {4} {5} {6}", i + 1, account.Id, (string)account.Name, (string)account.Username, (string)account.Password, account.Url, (string)account.Group); } } } }
using System; using System.IO; using LastPass; namespace Example { class Program { static void Main(string[] args) { // Read LastPass credentials from a file // The file should contain 2 lines: username and password. // See credentials.txt.example for an example. var credentials = File.ReadAllLines("../../credentials.txt"); var username = credentials[0]; var password = credentials[1]; // Fetch and create the vault from LastPass var vault = Vault.Create(username, password); // Decrypt all accounts vault.DecryptAllAccounts(Account.Field.Name | Account.Field.Username | Account.Field.Password | Account.Field.Group, username, password); // Dump all the accounts for (var i = 0; i < vault.Accounts.Length; ++i) { var account = vault.Accounts[i]; Console.WriteLine("{0}: {1} {2} {3} {4} {5} {6}", i + 1, account.Id, account.Name, account.Username, account.Password, account.Url, account.Group); } } } }
mit
C#
b9c7f662b7464340c3e427d99448c81e25d0107e
Revert "Revert "Revert "疑问"""
wangzheng888520/CefSharp,wangzheng888520/CefSharp,wangzheng888520/CefSharp,wangzheng888520/CefSharp
CefSharp.WinForms.Example/Program.cs
CefSharp.WinForms.Example/Program.cs
// Copyright © 2010-2015 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; using System.Windows.Forms; using CefSharp.Example; using CefSharp.WinForms.Example.Minimal; namespace CefSharp.WinForms.Example { public class Program { [STAThread] public static void Main() { #if DEBUG if (!System.Diagnostics.Debugger.IsAttached) { MessageBox.Show("When running this Example outside of Visual Studio" + "please make sure you compile in `Release` mode.", "Warning"); } #endif const bool multiThreadedMessageLoop = true; CefExample.Init(false, multiThreadedMessageLoop: multiThreadedMessageLoop); if(multiThreadedMessageLoop == false) { //http://magpcss.org/ceforum/apidocs3/projects/%28default%29/%28_globals%29.html#CefDoMessageLoopWork%28%29 //Perform a single iteration of CEF message loop processing. //This function is used to integrate the CEF message loop into an existing application message loop. //Care must be taken to balance performance against excessive CPU usage. //This function should only be called on the main application thread and only if CefInitialize() is called with a CefSettings.multi_threaded_message_loop value of false. //This function will not block. Application.Idle += (s, e) => Cef.DoMessageLoopWork(); } var browser = new BrowserForm(); //var browser = new SimpleBrowserForm(); //var browser = new TabulationDemoForm(); Application.Run(browser); } } }
// Copyright © 2010-2015 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; using System.Windows.Forms; using CefSharp.Example; using CefSharp.WinForms.Example.Minimal; namespace CefSharp.WinForms.Example { public class Program { [STAThread] public static void Main() { #if DEBUG if (!System.Diagnostics.Debugger.IsAttached) { MessageBox.Show("When running this Example outside of Visual Studio" + "please make sure you compile in `Release` mode.", "Warning"); } #endif //坑爹呢 .NET4.5编译的项目啊 让XP怎么办呢? const bool multiThreadedMessageLoop = true; CefExample.Init(false, multiThreadedMessageLoop: multiThreadedMessageLoop); if(multiThreadedMessageLoop == false) { //http://magpcss.org/ceforum/apidocs3/projects/%28default%29/%28_globals%29.html#CefDoMessageLoopWork%28%29 //Perform a single iteration of CEF message loop processing. //This function is used to integrate the CEF message loop into an existing application message loop. //Care must be taken to balance performance against excessive CPU usage. //This function should only be called on the main application thread and only if CefInitialize() is called with a CefSettings.multi_threaded_message_loop value of false. //This function will not block. Application.Idle += (s, e) => Cef.DoMessageLoopWork(); } var browser = new BrowserForm(); //var browser = new SimpleBrowserForm(); //var browser = new TabulationDemoForm(); Application.Run(browser); } } }
bsd-3-clause
C#
5dcac9cf89ca1d328f47eb4e49fbc96bbd14c3a8
Use static factory method for constructing Notification class
pawotter/mastodon-api-cs
Mastodon.API/Entities/Notification.cs
Mastodon.API/Entities/Notification.cs
using System; using Newtonsoft.Json; namespace Mastodon.API { /// <summary> /// Notification. /// https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#notification /// </summary> public class Notification { [JsonProperty(PropertyName = "id")] public string Id { get; set; } [JsonProperty(PropertyName = "type")] public string Type { get; set; } [JsonProperty(PropertyName = "created_at")] public string CreatedAt { get; set; } [JsonProperty(PropertyName = "account")] public Account Account { get; set; } [JsonProperty(PropertyName = "status")] public Status Status { get; set; } internal Notification() { } Notification(string id, string type, string createdAt, Account account, Status status) { Id = id; Type = type; CreatedAt = createdAt; Account = account; Status = status; } public static Notification create(string id, string type, string createdAt, Account account, Status status) { return new Notification(id, type, createdAt, account, status); } public override string ToString() { return string.Format("[Notification: Id={0}, Type={1}, CreatedAt={2}, Account={3}, Status={4}]", Id, Type, CreatedAt, Account, Status); } public override bool Equals(object obj) { var o = obj as Notification; if (o == null) return false; return Equals(Id, o.Id) && Equals(Type, o.Type) && Equals(CreatedAt, o.CreatedAt) && Equals(Account, o.Account) && Equals(Status, o.Status); } public override int GetHashCode() { return Object.GetHashCode(Id, Type, CreatedAt, Account, Status); } } }
using System; using Newtonsoft.Json; namespace Mastodon.API { /// <summary> /// Notification. /// https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#notification /// </summary> public class Notification { [JsonProperty(PropertyName = "id")] public string Id { get; set; } [JsonProperty(PropertyName = "type")] public string Type { get; set; } [JsonProperty(PropertyName = "created_at")] public string CreatedAt { get; set; } [JsonProperty(PropertyName = "account")] public Account Account { get; set; } [JsonProperty(PropertyName = "status")] public Status Status { get; set; } public Notification(string id, string type, string createdAt, Account account, Status status) { Id = id; Type = type; CreatedAt = createdAt; Account = account; Status = status; } public override string ToString() { return string.Format("[Notification: Id={0}, Type={1}, CreatedAt={2}, Account={3}, Status={4}]", Id, Type, CreatedAt, Account, Status); } public override bool Equals(object obj) { var o = obj as Notification; if (o == null) return false; return Equals(Id, o.Id) && Equals(Type, o.Type) && Equals(CreatedAt, o.CreatedAt) && Equals(Account, o.Account) && Equals(Status, o.Status); } public override int GetHashCode() { return Object.GetHashCode(Id, Type, CreatedAt, Account, Status); } } }
mit
C#
8721cc1988a1f62f816be62e9e23625b2bed9ee5
Change starting search from 1 billion because none before
fredatgithub/UsefulFunctions
ConsoleAppPrimesByHundred/Program.cs
ConsoleAppPrimesByHundred/Program.cs
using System; using FonctionsUtiles.Fred.Csharp; namespace ConsoleAppPrimesByHundred { internal class Program { private static void Main() { Action<string> display = Console.WriteLine; display("Prime numbers by hundred:"); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000)) { display($"{kvp.Key} - {kvp.Value}"); } display(string.Empty); display("Prime numbers by thousand:"); display(string.Empty); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000)) { display($"{kvp.Key} - {kvp.Value}"); } int count = 0; for (int i = 1000000001; i <= int.MaxValue - 4; i += 2) { if (FunctionsPrimes.IsPrimeTriplet(i)) { count++; } display($"Number of prime found: {count} and i: {i}"); } display("Press any key to exit"); Console.ReadKey(); } } }
using System; using FonctionsUtiles.Fred.Csharp; namespace ConsoleAppPrimesByHundred { internal class Program { private static void Main() { Action<string> display = Console.WriteLine; display("Prime numbers by hundred:"); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000)) { display($"{kvp.Key} - {kvp.Value}"); } display(string.Empty); display("Prime numbers by thousand:"); display(string.Empty); foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000)) { display($"{kvp.Key} - {kvp.Value}"); } int count = 0; for (int i = 3; i <= int.MaxValue - 4; i += 2) { if (FunctionsPrimes.IsPrimeTriplet(i)) { count++; } display($"Number of prime found: {count} and i: {i}"); } display("Press any key to exit"); Console.ReadKey(); } } }
mit
C#
6100e33dfb05e0400d68330a6d33a5e6d2447f40
Remove unused code
kiyoaki/bitflyer-api-dotnet-client
test/BitFlyer.Apis.Test/Properties/AssemblyInfo.cs
test/BitFlyer.Apis.Test/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("BitFlyer.Apis.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BitFlyer.Apis.Test")] [assembly: AssemblyCopyright("Copyright © Kiyoaki Tsurutani 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("628cec6e-cccf-463e-a22d-036162f99086")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("BitFlyer.Apis.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BitFlyer.Apis.Test")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから // 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("628cec6e-cccf-463e-a22d-036162f99086")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 以下のように '*' を使用します: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
2219a4b0d31589351d47285d89276ac16a4046e2
Add serializable attribute
MHeasell/Mappy,MHeasell/Mappy
Mappy/Maybe/MaybeWasNoneException.cs
Mappy/Maybe/MaybeWasNoneException.cs
namespace Mappy.Maybe { using System; [Serializable] public class MaybeWasNoneException : Exception { } }
namespace Mappy.Maybe { using System; public class MaybeWasNoneException : Exception { } }
mit
C#
1808c0f789eba410c0c6178422fef9d8d17f9b42
Increment assembly version.
feliperomero3/MVVMSandbox
MicroMvvm/Properties/AssemblyInfo.cs
MicroMvvm/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MicroMvvm")] [assembly: AssemblyDescription("Custom minimal MVVM framework")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Desiem")] [assembly: AssemblyProduct("MicroMvvm")] [assembly: AssemblyCopyright("Copyright © 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("67a8f9a0-e0d6-434f-89d9-6404883a9732")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: NeutralResourcesLanguage("en-US")]
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("MicroMvvm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MicroMvvm")] [assembly: AssemblyCopyright("Copyright © 2011")] [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("67a8f9a0-e0d6-434f-89d9-6404883a9732")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
mit
C#
1214ba241cefb67bf3fc60fd56861a088ec15e3b
Fix default values when instatntiating a UniqueRowsXml
Seddryck/NBi,Seddryck/NBi
NBi.Xml/Constraints/UniqueRowsXml.cs
NBi.Xml/Constraints/UniqueRowsXml.cs
using NBi.Core.ResultSet; using NBi.Xml.Items.ResultSet; using System.Collections.Generic; using System.ComponentModel; using System.Xml.Serialization; namespace NBi.Xml.Constraints { public class UniqueRowsXml : AbstractConstraintXml { public UniqueRowsXml() { KeysSet = SettingsIndexResultSet.KeysChoice.All; ValuesSet = SettingsIndexResultSet.ValuesChoice.None; } [XmlAttribute("keys")] [DefaultValue(SettingsIndexResultSet.KeysChoice.All)] public SettingsIndexResultSet.KeysChoice KeysSet { get; set; } [XmlAttribute("values")] [DefaultValue(SettingsIndexResultSet.ValuesChoice.None)] public SettingsIndexResultSet.ValuesChoice ValuesSet { get; set; } [XmlElement("column")] public List<ColumnDefinitionXml> Columns { get; set; } } }
using NBi.Core.ResultSet; using NBi.Xml.Items.ResultSet; using System.Collections.Generic; using System.ComponentModel; using System.Xml.Serialization; namespace NBi.Xml.Constraints { public class UniqueRowsXml : AbstractConstraintXml { public UniqueRowsXml() { } [XmlAttribute("keys")] [DefaultValue(SettingsIndexResultSet.KeysChoice.All)] public SettingsIndexResultSet.KeysChoice KeysSet { get; set; } [XmlAttribute("values")] [DefaultValue(SettingsIndexResultSet.ValuesChoice.None)] public SettingsIndexResultSet.ValuesChoice ValuesSet { get; set; } [XmlElement("column")] public List<ColumnDefinitionXml> Columns { get; set; } } }
apache-2.0
C#
c75e945e329be442d2236133178575199500025c
Bump version to 2.0.0-alpha2
HangfireIO/Hangfire.Dashboard.Authorization
Hangfire.Dashboard.Authorization/Properties/AssemblyInfo.cs
Hangfire.Dashboard.Authorization/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("Hangfire.Dashboard.Authorization")] [assembly: AssemblyDescription("Some authorization filters for Hangfire's Dashboard.")] [assembly: AssemblyProduct("Hangfire")] [assembly: AssemblyCopyright("Copyright © 2014 Sergey Odinokov")] // 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("34dd541a-5bdb-402f-8ec0-9aac8e3331ae")] [assembly: AssemblyInformationalVersion("2.0.0-alpha2")] [assembly: AssemblyVersion("2.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Hangfire.Dashboard.Authorization")] [assembly: AssemblyDescription("Some authorization filters for Hangfire's Dashboard.")] [assembly: AssemblyProduct("Hangfire")] [assembly: AssemblyCopyright("Copyright © 2014 Sergey Odinokov")] // 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("34dd541a-5bdb-402f-8ec0-9aac8e3331ae")] [assembly: AssemblyInformationalVersion("2.0.0-alpha1")] [assembly: AssemblyVersion("2.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
8480e77d73d349244f8b72fd4a578703883c8133
Speed up razor
NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare
Assets/Microgames/KagerouCut/Scripts/RazorController.cs
Assets/Microgames/KagerouCut/Scripts/RazorController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RazorController : MonoBehaviour { private float speed = 120f; private bool has_moved = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { int direction = 0; if (Input.GetKey(KeyCode.LeftArrow)) direction = -1; else if (Input.GetKey(KeyCode.RightArrow)) direction = 1; transform.Rotate(0f, 0f, direction * Time.deltaTime * speed); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RazorController : MonoBehaviour { private float speed = 100f; private bool has_moved = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { int direction = 0; if (Input.GetKey(KeyCode.LeftArrow)) direction = -1; else if (Input.GetKey(KeyCode.RightArrow)) direction = 1; transform.Rotate(0f, 0f, direction * Time.deltaTime * speed); } }
mit
C#
f6b249350dde9e69b9651e0a068b3cd51ae0c571
Update 06-DeleteTable.cs
awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples
.dotnet/example_code/DynamoDB/TryDax/06-DeleteTable.cs
.dotnet/example_code/DynamoDB/TryDax/06-DeleteTable.cs
// snippet-sourcedescription:[ ] // snippet-service:[dynamodb] // snippet-keyword:[dotNET] // snippet-keyword:[Amazon DynamoDB] // snippet-keyword:[Code Sample] // snippet-keyword:[ ] // snippet-sourcetype:[full-example] // snippet-sourcedate:[ ] // snippet-sourceauthor:[AWS] // snippet-start:[dynamodb.dotNET.trydax.06-DeleteTable] /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file 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 Amazon.DynamoDBv2.Model; using Amazon.DynamoDBv2; namespace ClientTest { class Program { static void Main(string[] args) { AmazonDynamoDBClient client = new AmazonDynamoDBClient(); var tableName = "TryDaxTable"; var request = new DeleteTableRequest() { TableName = tableName }; var response = client.DeleteTableAsync(request).Result; Console.WriteLine("Hit <enter> to continue..."); Console.ReadLine(); } } } // snippet-end:[dynamodb.dotNET.trydax.06-DeleteTable]
// snippet-sourcedescription:[ ] // snippet-service:[dynamodb] // snippet-keyword:[dotNET] // snippet-keyword:[Amazon DynamoDB] // snippet-keyword:[Code Sample] // snippet-keyword:[ ] // snippet-sourcetype:[full-example] // snippet-sourcedate:[ ] // snippet-sourceauthor:[AWS] // snippet-start:[dynamodb.dotNET.trydax.06-DeleteTable] /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file 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 Amazon.DynamoDBv2.Model; using System; using Amazon.DynamoDBv2; namespace ClientTest { class Program { static void Main(string[] args) { AmazonDynamoDBClient client = new AmazonDynamoDBClient(); var tableName = "TryDaxTable"; var request = new DeleteTableRequest() { TableName = tableName }; var response = client.DeleteTableAsync(request).Result; Console.WriteLine("Hit <enter> to continue..."); Console.ReadLine(); } } } // snippet-end:[dynamodb.dotNET.trydax.06-DeleteTable]
apache-2.0
C#
91b5be7ed1f8de33ab62d745e387428b53176d3c
select EventArgs
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/Behaviors/FocusOnEnableBehavior.cs
WalletWasabi.Fluent/Behaviors/FocusOnEnableBehavior.cs
using Avalonia; using Avalonia.Controls; using Avalonia.Xaml.Interactivity; using System; using System.Reactive.Linq; namespace WalletWasabi.Fluent.Behaviors { public class FocusOnEnableBehavior : Behavior<Control> { protected override void OnAttached() { base.OnAttached(); Observable. FromEventPattern<AvaloniaPropertyChangedEventArgs>(AssociatedObject, nameof(AssociatedObject.PropertyChanged)) .Select(x => x.EventArgs) .Where(x => x.Property.Name == nameof(AssociatedObject.IsEffectivelyEnabled) && x.NewValue is { } && (bool)x.NewValue == true) .Subscribe(_ => AssociatedObject!.Focus()); } protected override void OnDetaching() { base.OnDetaching(); } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Xaml.Interactivity; using System; using System.Reactive.Linq; namespace WalletWasabi.Fluent.Behaviors { public class FocusOnEnableBehavior : Behavior<Control> { protected override void OnAttached() { base.OnAttached(); Observable. FromEventPattern<AvaloniaPropertyChangedEventArgs>(AssociatedObject, nameof(AssociatedObject.PropertyChanged)) .Where(x => x.EventArgs.Property.Name == nameof(AssociatedObject.IsEffectivelyEnabled) && x.EventArgs.NewValue is { } newValue && (bool)newValue == true) .Subscribe(_ => AssociatedObject!.Focus()); } protected override void OnDetaching() { base.OnDetaching(); } } }
mit
C#
a37c644838720a68fd66c62691d3b16b003a36ae
Optimize wind collision
TheNextGuy32/blindfold
Assets/Scripts/WindManager.cs
Assets/Scripts/WindManager.cs
using UnityEngine; using System.Collections.Generic; public class WindManager : MonoBehaviour { public List<GameObject> wind = new List<GameObject>(); public float maxWindDistance; public float maxWindForce; // Update is called once per frame void Update() { for (int w = 0; w < wind.Count; w++) { Transform wT = wind[w].GetComponent<Transform>(); Wind wW = wind[w].GetComponent<Wind>(); for (int q = w+1; q < wind.Count; q++) { Transform qT = wind[q].GetComponent<Transform>(); Wind qW = wind[q].GetComponent<Wind>(); float distance = Vector3.Distance(wT.position, qT.position); if (distance < maxWindDistance) { float ratio = 1 - (distance / maxWindDistance); // At a distance of 0, we apply the max force, at a distance of maxWindDistance, we apply 0 force // This would mean at a ratio of 0.5 we have 0.5 max force, its linear. float force = (maxWindForce * ratio) / qW.mass; // Since each object looks at all others, we only worry about apply the force to OTHER object nto ourselves Vector3 directionToOther = Vector3.Normalize(qT.position - wT.position); Vector3 acceleration = directionToOther * force; // Apply the force to the other qW.velocity += acceleration; wW.velocity += -1*acceleration; } } } } }
using UnityEngine; using System.Collections.Generic; public class WindManager : MonoBehaviour { public List<GameObject> wind = new List<GameObject>(); public float maxWindDistance; public float maxWindForce; // Update is called once per frame void Update() { for (int w = 0; w < wind.Count; w++) { for (int q = 0; q < wind.Count; q++) { if (w == q) continue; Transform wT = wind[w].GetComponent<Transform>(); Transform qT = wind[q].GetComponent<Transform>(); Wind qW = wind[q].GetComponent<Wind>(); float distance = Vector3.Distance(wT.position, qT.position); if (distance < maxWindDistance) { float ratio = 1 - (distance / maxWindDistance); // At a distance of 0, we apply the max force, at a distance of maxWindDistance, we apply 0 force // This would mean at a ratio of 0.5 we have 0.5 max force, its linear. float force = (maxWindForce * ratio) / qW.mass; // Since each object looks at all others, we only worry about apply the force to OTHER object nto ourselves Vector3 directionToOther = Vector3.Normalize(qT.position - wT.position); Vector3 acceleration = directionToOther * force; // Apply the force to the other qW.velocity += acceleration; } } } } }
mit
C#
144f039ffe9e6eb723fccc578c1ace99ad2123a7
fix build error
andyfmiller/LtiLibrary
test/LtiLibrary.NetCore.Tests/SecureClientShould.cs
test/LtiLibrary.NetCore.Tests/SecureClientShould.cs
using System; using System.Collections.Generic; using System.Net.Http; using LtiLibrary.NetCore.Clients; using LtiLibrary.NetCore.Common; using LtiLibrary.NetCore.Extensions; using LtiLibrary.NetCore.Lis.v1; using LtiLibrary.NetCore.Lti.v1; using LtiLibrary.NetCore.OAuth; using LtiLibrary.NetCore.Tests.TestHelpers; using Xunit; namespace LtiLibrary.NetCore.Tests { public class SecureClientShould { #region SignRequest Tests [Fact] public async System.Threading.Tasks.Task HeaderContainsSHA256_IfSignatureMethodParamSetToSHA256() { //arrange var httpClient = new HttpClient(); var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://www.test.com/membership") { Content = new StringContent("", System.Text.Encoding.UTF8) }; //act await SecuredClient.SignRequest(httpClient, requestMessage, "TestConsumerKey", "TestConsumerSecret", SignatureMethod.HmacSha256); //assert Assert.NotNull(httpClient); Assert.NotNull(httpClient.DefaultRequestHeaders); Assert.NotNull(httpClient.DefaultRequestHeaders.Authorization); var headervalues = httpClient.DefaultRequestHeaders.Authorization.Parameter; var headerValuesList = headervalues.Split(','); Assert.True(headervalues.Contains("oauth_signature_method=\"HMAC-SHA256\"")); } #endregion } }
using System; using System.Collections.Generic; using System.Net.Http; using LtiLibrary.NetCore.Clients; using LtiLibrary.NetCore.Common; using LtiLibrary.NetCore.Extensions; using LtiLibrary.NetCore.Lis.v1; using LtiLibrary.NetCore.Lti.v1; using LtiLibrary.NetCore.OAuth; using LtiLibrary.NetCore.Tests.TestHelpers; using Xunit; namespace LtiLibrary.NetCore.Tests { public class SecureClientShould { #region SignRequest Tests [Fact] public async System.Threading.Tasks.Task HeaderContainsSHA256_IfSignatureMethodParamSetToSHA256() { //arrange var httpClient = new HttpClient(); //act await SecuredClient.SignRequest(httpClient, new HttpMethod("GET"), "https://www.test.com/membership", new StringContent("", System.Text.Encoding.UTF8), "TestConsumerKey", "TestConsumerSecret", SignatureMethod.HmacSha256); //assert Assert.NotNull(httpClient); Assert.NotNull(httpClient.DefaultRequestHeaders); Assert.NotNull(httpClient.DefaultRequestHeaders.Authorization); var headervalues = httpClient.DefaultRequestHeaders.Authorization.Parameter; var headerValuesList = headervalues.Split(','); Assert.True(headervalues.Contains("oauth_signature_method=\"HMAC-SHA256\"")); } #endregion } }
apache-2.0
C#
f4a38437314b00f99122c2b36d14a016c26a8c52
Fix unit test
AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia
tests/Avalonia.Controls.UnitTests/TextBlockTests.cs
tests/Avalonia.Controls.UnitTests/TextBlockTests.cs
using System; using Avalonia.Controls.Documents; using Avalonia.Data; using Avalonia.Media; using Avalonia.Rendering; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests { public class TextBlockTests { [Fact] public void DefaultBindingMode_Should_Be_OneWay() { Assert.Equal( BindingMode.OneWay, TextBlock.TextProperty.GetMetadata(typeof(TextBlock)).DefaultBindingMode); } [Fact] public void Default_Text_Value_Should_Be_Null() { var textBlock = new TextBlock(); Assert.Equal(null, textBlock.Text); } [Fact] public void Changing_Background_Brush_Color_Should_Invalidate_Visual() { var target = new TextBlock() { Background = new SolidColorBrush(Colors.Red), }; var root = new TestRoot(target); var renderer = Mock.Get(root.Renderer); renderer.Invocations.Clear(); ((SolidColorBrush)target.Background).Color = Colors.Green; renderer.Verify(x => x.AddDirty(target), Times.Once); } [Fact] public void Changing_Foreground_Brush_Color_Should_Invalidate_Visual() { var target = new TextBlock() { Foreground = new SolidColorBrush(Colors.Red), }; var root = new TestRoot(target); var renderer = Mock.Get(root.Renderer); renderer.Invocations.Clear(); ((SolidColorBrush)target.Foreground).Color = Colors.Green; renderer.Verify(x => x.AddDirty(target), Times.Once); } } }
using System; using Avalonia.Controls.Documents; using Avalonia.Data; using Avalonia.Media; using Avalonia.Rendering; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests { public class TextBlockTests { [Fact] public void DefaultBindingMode_Should_Be_OneWay() { Assert.Equal( BindingMode.OneWay, TextBlock.TextProperty.GetMetadata(typeof(TextBlock)).DefaultBindingMode); } [Fact] public void Default_Text_Value_Should_Be_EmptyString() { var textBlock = new TextBlock(); Assert.Equal( "", textBlock.Text); } [Fact] public void Changing_Background_Brush_Color_Should_Invalidate_Visual() { var target = new TextBlock() { Background = new SolidColorBrush(Colors.Red), }; var root = new TestRoot(target); var renderer = Mock.Get(root.Renderer); renderer.Invocations.Clear(); ((SolidColorBrush)target.Background).Color = Colors.Green; renderer.Verify(x => x.AddDirty(target), Times.Once); } [Fact] public void Changing_Foreground_Brush_Color_Should_Invalidate_Visual() { var target = new TextBlock() { Foreground = new SolidColorBrush(Colors.Red), }; var root = new TestRoot(target); var renderer = Mock.Get(root.Renderer); renderer.Invocations.Clear(); ((SolidColorBrush)target.Foreground).Color = Colors.Green; renderer.Verify(x => x.AddDirty(target), Times.Once); } } }
mit
C#
6e87725f067fe229c9ade6f8a3c8c6f41bc56c71
Increment the version to 1.1.2.0
ladimolnar/BitcoinBlockchain
Sources/BitcoinBlockchain/Properties/AssemblyInfo.cs
Sources/BitcoinBlockchain/Properties/AssemblyInfo.cs
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs"> // Copyright © Ladislau Molnar. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; 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("BitcoinBlockchain")] [assembly: AssemblyDescription("A .NET Class Library that provides parsing functionality over files containing the Bitcoin blockchain.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ladislau Molnar")] [assembly: AssemblyProduct("BitcoinBlockchain")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // 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("4d8ebb2b-d182-4106-8d15-5fb864de6706")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.2.0")] [assembly: AssemblyFileVersion("1.1.2.0")]
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs"> // Copyright © Ladislau Molnar. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; 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("BitcoinBlockchain")] [assembly: AssemblyDescription("A .NET Class Library that provides parsing functionality over files containing the Bitcoin blockchain.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ladislau Molnar")] [assembly: AssemblyProduct("BitcoinBlockchain")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // 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("4d8ebb2b-d182-4106-8d15-5fb864de6706")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")]
apache-2.0
C#
1a160a63cf015db7687575da3995411997ae4892
Fix user name detection for some regions
Gl0/CasualMeter
Tera.Core/Game/Messages/Server/LoginServerMessage.cs
Tera.Core/Game/Messages/Server/LoginServerMessage.cs
// Copyright (c) Gothos // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Tera.Game.Messages { public class LoginServerMessage : ParsedMessage { public EntityId Id { get; private set; } public uint PlayerId { get; private set; } public string Name { get; private set; } public string GuildName { get; private set; } public PlayerClass Class { get { return RaceGenderClass.Class; } } public RaceGenderClass RaceGenderClass { get; private set; } internal LoginServerMessage(TeraMessageReader reader) : base(reader) { reader.Skip(10); RaceGenderClass = new RaceGenderClass(reader.ReadInt32()); Id = reader.ReadEntityId(); reader.Skip(4); PlayerId = reader.ReadUInt32(); //reader.Skip(260); //This network message doesn't have a fixed size between different region reader.Skip(220); var nameFirstBit = false; while (true) { var b = reader.ReadByte(); if (b == 0x80) { nameFirstBit = true; continue; } if (b == 0x3F && nameFirstBit) { break; } nameFirstBit = false; } reader.Skip(9); Name = reader.ReadTeraString(); } } }
// Copyright (c) Gothos // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Tera.Game.Messages { public class LoginServerMessage : ParsedMessage { public EntityId Id { get; private set; } public uint PlayerId { get; private set; } public string Name { get; private set; } public string GuildName { get; private set; } public PlayerClass Class { get { return RaceGenderClass.Class; } } public RaceGenderClass RaceGenderClass { get; private set; } internal LoginServerMessage(TeraMessageReader reader) : base(reader) { reader.Skip(10); RaceGenderClass = new RaceGenderClass(reader.ReadInt32()); Id = reader.ReadEntityId(); reader.Skip(4); PlayerId = reader.ReadUInt32(); reader.Skip(260); Name = reader.ReadTeraString(); } } }
mit
C#
20bd8e54042eb20925d46f38f62ed7f0e6dabc4e
Fix event action "Select Widget" cancel still applying
danielchalmers/DesktopWidgets
DesktopWidgets/Windows/EventActionPairEditor.xaml.cs
DesktopWidgets/Windows/EventActionPairEditor.xaml.cs
using System.Windows; using DesktopWidgets.Actions; using DesktopWidgets.Classes; using DesktopWidgets.Events; using DesktopWidgets.Helpers; namespace DesktopWidgets.Windows { /// <summary> /// Interaction logic for EventActionPairEditor.xaml /// </summary> public partial class EventActionPairEditor : Window { public EventActionPairEditor(EventActionPair pair) { InitializeComponent(); EventActionPair = pair; DataContext = this; } public EventActionPair EventActionPair { get; set; } private void btnOK_OnClick(object sender, RoutedEventArgs e) { DialogResult = true; } private void btnSelectWidgetForEvent_OnClick(object sender, RoutedEventArgs e) { var chosenWidget = WidgetHelper.ChooseWidget(); if (chosenWidget != null) ((WidgetEventBase) EventActionPair.Event).WidgetId = chosenWidget; } private void btnSelectWidgetForAction_OnClick(object sender, RoutedEventArgs e) { var chosenWidget = WidgetHelper.ChooseWidget(); if (chosenWidget != null) ((WidgetActionBase) EventActionPair.Action).WidgetId = chosenWidget; } } }
using System.Windows; using DesktopWidgets.Actions; using DesktopWidgets.Classes; using DesktopWidgets.Events; using DesktopWidgets.Helpers; namespace DesktopWidgets.Windows { /// <summary> /// Interaction logic for EventActionPairEditor.xaml /// </summary> public partial class EventActionPairEditor : Window { public EventActionPairEditor(EventActionPair pair) { InitializeComponent(); EventActionPair = pair; DataContext = this; } public EventActionPair EventActionPair { get; set; } private void btnOK_OnClick(object sender, RoutedEventArgs e) { DialogResult = true; } private void btnSelectWidgetForEvent_OnClick(object sender, RoutedEventArgs e) { ((WidgetEventBase) EventActionPair.Event).WidgetId = WidgetHelper.ChooseWidget(); } private void btnSelectWidgetForAction_OnClick(object sender, RoutedEventArgs e) { ((WidgetActionBase) EventActionPair.Action).WidgetId = WidgetHelper.ChooseWidget(); } } }
apache-2.0
C#
b06caa2c546ae1cbb6e204b064404e44eb25f348
Change the SendReceiveAsync() implementation to support commands that do not have responses
tparviainen/oscilloscope
LAN/LANInterface.cs
LAN/LANInterface.cs
using PluginContracts; using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; namespace LAN { public class LANInterface : IPluginV1 { public string Name { get; } = "LAN"; public string Description { get; } = "LAN communication interface for oscilloscopes such as Rigol DS1054Z"; public IPEndPoint IPEndPoint { get; set; } public int ReadTimeout { get; set; } = 500; public async Task<byte[]> SendReceiveAsync(string command) { using (var client = new TcpClient()) { await client.ConnectAsync(IPEndPoint.Address, IPEndPoint.Port); using (var stream = client.GetStream()) { stream.ReadTimeout = ReadTimeout; var writer = new BinaryWriter(stream); writer.Write(command + "\n"); writer.Flush(); using (var ms = new MemoryStream()) { try { var reader = new BinaryReader(stream); do { var value = reader.ReadByte(); ms.WriteByte(value); if (client.Available != 0) { var values = reader.ReadBytes(client.Available); ms.Write(values, 0, values.Length); } } while (true); } catch (Exception ex) when (ex.InnerException.GetType() == typeof(SocketException)) { // ReadByte() method will eventually timeout ... } return ms.ToArray(); } } } } } }
using PluginContracts; using System; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Text; using System.IO; namespace LAN { public class LANInterface : IPluginV1 { public string Name { get; } = "LAN"; public string Description { get; } = "LAN communication interface for oscilloscopes such as Rigol DS1054Z"; public IPEndPoint IPEndPoint { get; set; } public async Task<byte[]> SendReceiveAsync(string command) { using (var socket = new Socket(IPEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(IPEndPoint); // Start with the initial size of the socket receive buffer using (var ms = new MemoryStream(socket.ReceiveBufferSize)) { socket.Send(Encoding.ASCII.GetBytes(command + "\n")); var data = new byte[1024]; int received = 0; do { // Receive will block if no data available received = socket.Receive(data, data.Length, 0); // Zero bytes received means that socket has been closed by the remote host if (received != 0) { await ms.WriteAsync(data, 0, received); } // Read until terminator '\n' (0x0A) found from buffer } while (received != 0 && data[received - 1] != 0x0A); return ms.ToArray(); } } } } }
mit
C#
5926596ad9f63bb0daf6f8c9dec3b1839ab40bdf
Edit accounts of 'all' page.
grae22/BoozeHoundCloud,grae22/BoozeHoundCloud,grae22/BoozeHoundCloud
BoozeHoundCloud/Areas/Core/Views/Account/Index.cshtml
BoozeHoundCloud/Areas/Core/Views/Account/Index.cshtml
@Html.Partial("_AccountTypeLinks") <h2>All Accounts</h2> <table id="accountsTable" class="table table-bordered table-hover"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Balance</th> </tr> </thead> </table> @section scripts { <script> $(document).ready(function() { $('#accountsTable').DataTable({ ajax: { url: '/api/Core/Account', dataSrc: '' }, columns: [ { data: 'Name', render: function (data, type, account) { return "<a href='/Core/Account/Edit/" + account.Id + "'>" + data + "</a>"; } }, { data: 'AccountType.Name' }, { data: 'Balance' } ] }); }); </script> }
@Html.Partial("_AccountTypeLinks") <h2>All Accounts</h2> <table id="accountsTable" class="table table-bordered table-hover"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Balance</th> </tr> </thead> </table> @section scripts { <script> $(document).ready(function() { $('#accountsTable').DataTable({ ajax: { url: '/api/Core/Account', dataSrc: '' }, columns: [ { data: 'Name' }, { data: 'AccountType.Name' }, { data: 'Balance' } ] }); }); </script> }
mit
C#
c6bc6be1280dfff8db52757ab51ab8aa9111b28b
Fix toolbox expand being interrupted by gaps between groups
peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu
osu.Game/Rulesets/Edit/ExpandingToolboxContainer.cs
osu.Game/Rulesets/Edit/ExpandingToolboxContainer.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Game.Graphics.Containers; using osuTK; namespace osu.Game.Rulesets.Edit { public class ExpandingToolboxContainer : ExpandingContainer { protected override double HoverExpansionDelay => 250; public ExpandingToolboxContainer(float contractedWidth, float expandedWidth) : base(contractedWidth, expandedWidth) { RelativeSizeAxes = Axes.Y; FillFlow.Spacing = new Vector2(10); } protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos); public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos); private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos); protected override bool OnMouseDown(MouseDownEvent e) => true; protected override bool OnClick(ClickEvent e) => true; } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Game.Graphics.Containers; using osuTK; namespace osu.Game.Rulesets.Edit { public class ExpandingToolboxContainer : ExpandingContainer { protected override double HoverExpansionDelay => 250; public ExpandingToolboxContainer(float contractedWidth, float expandedWidth) : base(contractedWidth, expandedWidth) { RelativeSizeAxes = Axes.Y; FillFlow.Spacing = new Vector2(10); } protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos); public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos); private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.Children.Any(d => d.ScreenSpaceDrawQuad.Contains(screenSpacePos)); protected override bool OnMouseDown(MouseDownEvent e) => true; protected override bool OnClick(ClickEvent e) => true; } }
mit
C#
9a64ba55b066304056ecf86a0a46c6e1bac71724
Add some xml doc and properties for retired, disqualified and classified
Krusen/ErgastApi.Net
src/ErgastiApi/Responses/Models/RaceInfo/RaceResult.cs
src/ErgastiApi/Responses/Models/RaceInfo/RaceResult.cs
using System; using ErgastApi.Ids; using ErgastApi.Serialization; using ErgastApi.Serialization.Converters; using Newtonsoft.Json; namespace ErgastApi.Responses.Models.RaceInfo { public class RaceResult : ResultBase { /// <summary> /// Finishing position. /// R = Retired, D = Disqualified, E = Excluded, W = Withdrawn, F = Failed to qualify, N = Not classified. /// See <see cref="StatusText"/> for more info. /// </summary> [JsonProperty("positionText")] public string PositionText { get; private set; } public bool Retired { get { if (PositionText == "R") return true; return Status > FinishingStatusId.Disqualified && !Status.ToString().StartsWith("Laps"); } } public bool Disqualified => PositionText == "D"; /// <summary> /// Indicates if the driver was classified (not retired and finished 90% of the race). /// </summary> public bool Classified => int.TryParse(PositionText, out _); [JsonProperty("points")] public int Points { get; private set; } /// <summary> /// Grid position, i.e. starting position. /// A value of 0 means the driver started from the pit lane. /// </summary> [JsonProperty("grid")] public int Grid { get; private set; } public bool StartedFromPitLane => Grid == 0; [JsonProperty("laps")] public int Laps { get; private set; } [JsonProperty("status")] public string StatusText { get; private set; } [JsonIgnore] public FinishingStatusId Status => FinishingStatusIdParser.Parse(StatusText); [JsonProperty("FastestLap")] public FastestLap FastestLap { get; private set; } /// <summary> /// Total race time. This is null for lapped cars. /// </summary> [JsonPathProperty("Time.millis")] [JsonConverter(typeof(MillisecondsTimeSpanConverter))] public TimeSpan? TotalRaceTime { get; private set; } /// <summary> /// Gap to winner. This is null for the winner and lapped cars. /// </summary> [JsonPathProperty("Time.time")] [JsonConverter(typeof(StringGapTimeSpanConverter))] public TimeSpan? GapToWinner { get; private set; } } }
using System; using ErgastApi.Ids; using ErgastApi.Serialization; using ErgastApi.Serialization.Converters; using Newtonsoft.Json; namespace ErgastApi.Responses.Models.RaceInfo { public class RaceResult : ResultBase { // TODO: Docu: equals Position or "R" retired, "D" disqualified, "E" excluded, "W" withdrawn, "F" failed to qualify, "N" not classified. See Status for more info [JsonProperty("positionText")] public string PositionText { get; private set; } [JsonProperty("points")] public int Points { get; private set; } // TODO: Docu: 0 means starting from pit lane [JsonProperty("grid")] public int Grid { get; private set; } public bool StartedFromPitLane => Grid == 0; [JsonProperty("laps")] public int Laps { get; private set; } // TODO: Enum? (FinishingStatusId) Value contains stuff like "+1 Lap". Probably needs to be mapped on enum and then custom converter [JsonProperty("status")] public string StatusText { get; private set; } [JsonIgnore] public FinishingStatusId Status => FinishingStatusIdParser.Parse(StatusText); [JsonProperty("FastestLap")] public FastestLap FastestLap { get; private set; } // TODO: Docu: Null for lapped cars [JsonPathProperty("Time.millis")] [JsonConverter(typeof(MillisecondsTimeSpanConverter))] public TimeSpan? TotalRaceTime { get; private set; } // TODO: Docu: Null for winner and lapped cars [JsonPathProperty("Time.time")] [JsonConverter(typeof(StringGapTimeSpanConverter))] public TimeSpan? GapToWinner { get; private set; } } }
unlicense
C#
9604c1a705be65f526b5c3b612416b84fabda425
Add support for `type` when listing Products
richardlawley/stripe.net,stripe/stripe-dotnet
src/Stripe.net/Services/Products/ProductListOptions.cs
src/Stripe.net/Services/Products/ProductListOptions.cs
namespace Stripe { using Newtonsoft.Json; public class ProductListOptions : ListOptionsWithCreated { [JsonProperty("active")] public bool? Active { get; set; } [JsonProperty("ids")] public string[] Ids { get; set; } [JsonProperty("shippable")] public bool? Shippable { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("url")] public string Url { get; set; } } }
namespace Stripe { using Newtonsoft.Json; public class ProductListOptions : ListOptionsWithCreated { [JsonProperty("active")] public bool? Active { get; set; } [JsonProperty("ids")] public string[] Ids { get; set; } [JsonProperty("shippable")] public bool? Shippable { get; set; } [JsonProperty("url")] public string Url { get; set; } } }
apache-2.0
C#
cd10c8b3e1c58c19eb7c76590f6ed97205d1ab63
Update StringExtensions.cs
BenjaminAbt/snippets
CSharp/StringExtensions.cs
CSharp/StringExtensions.cs
using System; namespace SchwabenCode.StringExtensions { public static class StringExtensions { /// <summary> /// Cuts a string with the given max length /// </summary> public static string WithMaxLength(this string value, int maxLength) { return value?.Substring(0, Math.Min(value.Length, maxLength)); } } }
public static class StringExtensions { /// <summary> /// Cuts a string with the given max length /// </summary> public static string WithMaxLength(this string value, int maxLength) { return value?.Substring(0, Math.Min(value.Length, maxLength)); } }
mit
C#
47b681e1b849eb1e4ab827c782a73c8f10d95ecd
Add content type for downloads
claudiospizzi/DSCPullServerWeb
Sources/DSCPullServerWeb/Helpers/FileActionResult.cs
Sources/DSCPullServerWeb/Helpers/FileActionResult.cs
using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace DSCPullServerWeb.Helpers { public class FileActionResult : IHttpActionResult { private FileInfo _file; public FileActionResult(FileInfo file) { _file = file; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(); response.Content = new StreamContent(File.OpenRead(_file.FullName)); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); return Task.FromResult(response); } } }
using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace DSCPullServerWeb.Helpers { public class FileActionResult : IHttpActionResult { private FileInfo _file; public FileActionResult(FileInfo file) { _file = file; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(); response.Content = new StreamContent(File.OpenRead(_file.FullName)); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); return Task.FromResult(response); } } }
mit
C#