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
f1ee3e9d24d2b1bfd1fcb82d4a8cba6e451571af
Add License #region.
PenguinF/sandra-three
Sandra.UI.WF/Storage/PType.cs
Sandra.UI.WF/Storage/PType.cs
#region License /********************************************************************************* * PType.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ #endregion namespace Sandra.UI.WF.Storage { /// <summary> /// Represents a type of <see cref="PValue"/>, which controls the range of values that are possible. /// </summary> /// <typeparam name="T"> /// The .NET target <see cref="System.Type"/> to convert to and from. /// </typeparam> public abstract class PType<T> { /// <summary> /// Attempts to convert a raw <see cref="PValue"/> to the target .NET type <typeparamref name="T"/>. /// </summary> /// <param name="value"> /// The value to convert from. /// </param> /// <param name="targetValue"> /// The target value to convert to, if conversion succeeds. /// </param> /// <returns> /// Whether or not conversion succeeded. /// </returns> public abstract bool TryGetValidValue(PValue value, out T targetValue); /// <summary> /// Converts a value of the target .NET type <typeparamref name="T"/> to a <see cref="PValue"/>. /// Assumed is that this is the reverse operation of <see cref="TryGetValidValue(PValue, out T)"/>, i.e.: /// <code> /// if (TryGetValidValue(value, out targetValue)) /// { /// PValue convertedValue = GetPValue(targetValue); /// Debug.Assert(PValueEqualityComparer.Instance.AreEqual(value, convertedValue), "This should always succeed."); /// } /// </code> /// And vice versa. /// </summary> /// <param name="value"> /// The value to convert from. /// </param> /// <returns> /// The converted target value. /// </returns> public abstract PValue GetPValue(T value); } }
/********************************************************************************* * PType.cs * * Copyright (c) 2004-2018 Henk Nicolai * * 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 Sandra.UI.WF.Storage { /// <summary> /// Represents a type of <see cref="PValue"/>, which controls the range of values that are possible. /// </summary> /// <typeparam name="T"> /// The .NET target <see cref="System.Type"/> to convert to and from. /// </typeparam> public abstract class PType<T> { /// <summary> /// Attempts to convert a raw <see cref="PValue"/> to the target .NET type <typeparamref name="T"/>. /// </summary> /// <param name="value"> /// The value to convert from. /// </param> /// <param name="targetValue"> /// The target value to convert to, if conversion succeeds. /// </param> /// <returns> /// Whether or not conversion succeeded. /// </returns> public abstract bool TryGetValidValue(PValue value, out T targetValue); /// <summary> /// Converts a value of the target .NET type <typeparamref name="T"/> to a <see cref="PValue"/>. /// Assumed is that this is the reverse operation of <see cref="TryGetValidValue(PValue, out T)"/>, i.e.: /// <code> /// if (TryGetValidValue(value, out targetValue)) /// { /// PValue convertedValue = GetPValue(targetValue); /// Debug.Assert(PValueEqualityComparer.Instance.AreEqual(value, convertedValue), "This should always succeed."); /// } /// </code> /// And vice versa. /// </summary> /// <param name="value"> /// The value to convert from. /// </param> /// <returns> /// The converted target value. /// </returns> public abstract PValue GetPValue(T value); } }
apache-2.0
C#
c31bf068b726120211edea328e9519090d777a8f
Fix test.
CobraCalle/helix-toolkit,smischke/helix-toolkit,helix-toolkit/helix-toolkit,0x53A/helix-toolkit,jotschgl/helix-toolkit,Iluvatar82/helix-toolkit,JeremyAnsel/helix-toolkit,holance/helix-toolkit,chrkon/helix-toolkit
Source/HelixToolkit.Wpf.SharpDX.Tests/Controls/CanvasMock.cs
Source/HelixToolkit.Wpf.SharpDX.Tests/Controls/CanvasMock.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CanvasMock.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using SharpDX; using SharpDX.Direct3D11; namespace HelixToolkit.Wpf.SharpDX.Tests.Controls { class CanvasMock : IRenderHost { public CanvasMock() { RenderTechniquesManager = new RenderTechniquesManager(); RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Phong]; EffectsManager = new EffectsManager(RenderTechniquesManager); Device = EffectsManager.Device; } public Device Device { get; private set; } public Color4 ClearColor { get; private set; } public bool IsShadowMapEnabled { get; private set; } public bool IsMSAAEnabled { get; private set; } public IRenderer Renderable { get; private set; } public RenderTechnique RenderTechnique { get; private set; } public double ActualHeight { get; private set; } public double ActualWidth { get; private set; } public EffectsManager EffectsManager { get; private set; } public IRenderTechniquesManager RenderTechniquesManager { get; private set; } public void SetDefaultRenderTargets() { throw new NotImplementedException(); } public void SetDefaultColorTargets(DepthStencilView dsv) { throw new NotImplementedException(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CanvasMock.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using SharpDX; using SharpDX.Direct3D11; namespace HelixToolkit.Wpf.SharpDX.Tests.Controls { class CanvasMock : IRenderHost { public CanvasMock() { Device = EffectsManager.Device; RenderTechniquesManager = new RenderTechniquesManager(); RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Phong]; EffectsManager = new EffectsManager(RenderTechniquesManager); } public Device Device { get; private set; } public Color4 ClearColor { get; private set; } public bool IsShadowMapEnabled { get; private set; } public bool IsMSAAEnabled { get; private set; } public IRenderer Renderable { get; private set; } public RenderTechnique RenderTechnique { get; private set; } public double ActualHeight { get; private set; } public double ActualWidth { get; private set; } public EffectsManager EffectsManager { get; private set; } public IRenderTechniquesManager RenderTechniquesManager { get; private set; } public void SetDefaultRenderTargets() { throw new NotImplementedException(); } public void SetDefaultColorTargets(DepthStencilView dsv) { throw new NotImplementedException(); } } }
mit
C#
f1f36647d725c53ac032408b0483bd04f98e7b57
Add SafeLazyChildSyntaxOrEmpty.
PenguinF/sandra-three
Sandra.Chess/Pgn/PgnEmptySyntax.cs
Sandra.Chess/Pgn/PgnEmptySyntax.cs
#region License /********************************************************************************* * PgnEmptySyntax.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using Eutherion; using System; namespace Sandra.Chess.Pgn { /// <summary> /// Represents an empty placeholder node. /// </summary> // This exists primarily to simplify length and count offset calculation code. public sealed class PgnEmptySyntax : PgnSyntax { /// <summary> /// Gets the start position of this syntax node relative to its parent's start position. /// </summary> public override int Start { get; } /// <summary> /// Gets the length of the text span corresponding with this syntax node. /// </summary> public override int Length => 0; /// <summary> /// Gets the parent syntax node of this instance. /// </summary> public override PgnSyntax ParentSyntax { get; } internal PgnEmptySyntax(PgnSyntax parentSyntax, int start) { ParentSyntax = parentSyntax; Start = start; } } /// <summary> /// Wraps either an empty syntax or a lazy child node of the specified type. /// </summary> internal struct SafeLazyChildSyntaxOrEmpty<TChildSyntax> where TChildSyntax : PgnSyntax { private readonly SafeLazyObject<TChildSyntax> lazyNodeIfNonEmpty; private readonly PgnEmptySyntax nodeIfEmpty; public TChildSyntax ChildNodeOrNull => nodeIfEmpty == null ? lazyNodeIfNonEmpty.Object : null; public PgnSyntax ChildNodeOrEmpty => nodeIfEmpty == null ? lazyNodeIfNonEmpty.Object : (PgnSyntax)nodeIfEmpty; /// <summary> /// Initializes as lazy child node. /// </summary> public SafeLazyChildSyntaxOrEmpty(Func<TChildSyntax> childConstructor) { lazyNodeIfNonEmpty = new SafeLazyObject<TChildSyntax>(childConstructor); nodeIfEmpty = null; } /// <summary> /// Initializes as empty. /// </summary> public SafeLazyChildSyntaxOrEmpty(PgnSyntax parent, int start) { lazyNodeIfNonEmpty = default; nodeIfEmpty = new PgnEmptySyntax(parent, start); } } }
#region License /********************************************************************************* * PgnEmptySyntax.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion namespace Sandra.Chess.Pgn { /// <summary> /// Represents an empty placeholder node. /// </summary> // This exists primarily to simplify length and count offset calculation code. public sealed class PgnEmptySyntax : PgnSyntax { /// <summary> /// Gets the start position of this syntax node relative to its parent's start position. /// </summary> public override int Start { get; } /// <summary> /// Gets the length of the text span corresponding with this syntax node. /// </summary> public override int Length => 0; /// <summary> /// Gets the parent syntax node of this instance. /// </summary> public override PgnSyntax ParentSyntax { get; } internal PgnEmptySyntax(PgnSyntax parentSyntax, int start) { ParentSyntax = parentSyntax; Start = start; } } }
apache-2.0
C#
b5abc67de985efb63f242105f8fbcfad90b92474
remove the old monospace thing from yesterday
liddictm/BrawlManagers,liddictm/BrawlManagers,libertyernie/BrawlManagers,libertyernie/BrawlManagers
StageManager/NameCreator.cs
StageManager/NameCreator.cs
using System; using System.Drawing; using System.Windows.Forms; namespace BrawlStageManager { public class NameCreator { public static NameCreatorSettings selectFont(NameCreatorSettings previous = null) { using (NameCreatorDialog d = new NameCreatorDialog()) { if (previous != null) d.Settings = previous; if (d.ShowDialog() == DialogResult.OK) { return d.Settings; } else { return null; } } } public static Bitmap createImage(NameCreatorSettings fontData, string text) { int linebreak = text.IndexOf("\\n"); if (linebreak > -1) { return createImage(fontData, text.Substring(0, linebreak), text.Substring(linebreak + 2)); } Bitmap b = new Bitmap(208, 56); Graphics g = Graphics.FromImage(b); g.FillRectangle(new SolidBrush(Color.Black), 0, 0, 208, 56); g.DrawString(text, fontData.Font, new SolidBrush(Color.White), 104, 28 - fontData.VerticalOffset, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, }); return b; } public static Bitmap createImage(NameCreatorSettings fontData, string line1, string line2) { Bitmap b = new Bitmap(208, 56); Graphics g = Graphics.FromImage(b); g.FillRectangle(new SolidBrush(Color.Black), 0, 0, 208, 56); g.DrawString(line1, fontData.Font, new SolidBrush(Color.White), 104, 13 - fontData.VerticalOffset, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, }); g.DrawString(line2, fontData.Font, new SolidBrush(Color.White), 104, 43 - fontData.VerticalOffset, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, }); return b; } } }
using System; using System.Drawing; using System.Windows.Forms; namespace BrawlStageManager { public class NameCreator { public static NameCreatorSettings selectFont(NameCreatorSettings previous = null) { using (NameCreatorDialog d = new NameCreatorDialog()) { if (previous != null) d.Settings = previous; if (d.ShowDialog() == DialogResult.OK) { return d.Settings; } else { return null; } } } public static Bitmap createImage(NameCreatorSettings fontData, string text) { int linebreak = text.IndexOf("\\n"); int linebreak2 = text.Substring(linebreak + 2).IndexOf("\\n"); if (linebreak2 > -1) { return createImageMonospace(text.Replace("\\n", "\n").Split('\n')); } else if (linebreak > -1) { return createImage(fontData, text.Substring(0, linebreak), text.Substring(linebreak + 2)); } Bitmap b = new Bitmap(208, 56); Graphics g = Graphics.FromImage(b); g.FillRectangle(new SolidBrush(Color.Black), 0, 0, 208, 56); g.DrawString(text, fontData.Font, new SolidBrush(Color.White), 104, 28 - fontData.VerticalOffset, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, }); return b; } public static Bitmap createImageMonospace(params string[] line) { StringFormat format = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center, }; Bitmap b = new Bitmap(208, 56); Graphics g = Graphics.FromImage(b); g.FillRectangle(new SolidBrush(Color.Black), 0, 0, 208, 56); g.DrawString(line[0], new Font("Consolas", 12, FontStyle.Bold), new SolidBrush(Color.White), -3, 8, format); g.DrawString(line[1], new Font("Consolas", 12, FontStyle.Bold), new SolidBrush(Color.White), -3, 28, format); g.DrawString(line[2], new Font("Consolas", 12, FontStyle.Bold), new SolidBrush(Color.White), -3, 48, format); return b; } public static Bitmap createImage(NameCreatorSettings fontData, string line1, string line2) { Bitmap b = new Bitmap(208, 56); Graphics g = Graphics.FromImage(b); g.FillRectangle(new SolidBrush(Color.Black), 0, 0, 208, 56); g.DrawString(line1, fontData.Font, new SolidBrush(Color.White), 104, 13 - fontData.VerticalOffset, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, }); g.DrawString(line2, fontData.Font, new SolidBrush(Color.White), 104, 43 - fontData.VerticalOffset, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, }); return b; } } }
mit
C#
0699cb6e6895bbc8099c49641e49209a4c3b75c3
Add TroubleshootingTests ShowBuildPlan
kendaleiv/di-servicelocation-structuremap,kendaleiv/di-servicelocation-structuremap,kendaleiv/di-servicelocation-structuremap
Tests/TroubleshootingTests.cs
Tests/TroubleshootingTests.cs
using Core; using StructureMap; using System.Diagnostics; using Xunit; namespace Tests { public class TroubleshootingTests { [Fact] public void ShowBuildPlan() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var buildPlan = container.Model.For<IService>() .Default .DescribeBuildPlan(); var expectedBuildPlan = @"PluginType: Core.IService Lifecycle: Transient new Service() "; Assert.Equal(expectedBuildPlan, buildPlan); } [Fact] public void WhatDoIHave() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var whatDoIHave = container.WhatDoIHave(); Trace.Write(whatDoIHave); } } }
using Core; using StructureMap; using System.Diagnostics; using Xunit; namespace Tests { public class TroubleshootingTests { [Fact] public void WhatDoIHave() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var whatDoIHave = container.WhatDoIHave(); Trace.Write(whatDoIHave); } } }
mit
C#
79e36fc54b2c9ed8daaa9d182eee83db7bd4d2de
Update MessageData.cs
pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,Microsoft/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet
src/Microsoft.ApplicationInsights/Extensibility/Implementation/External/MessageData.cs
src/Microsoft.ApplicationInsights/Extensibility/Implementation/External/MessageData.cs
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.External { using System; using System.Diagnostics; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; /// <summary> /// Partial class to add the EventData attribute and any additional customizations to the generated type. /// </summary> #if !NET45 // .Net 4.5 has a custom implementation of RichPayloadEventSource [System.Diagnostics.Tracing.EventData(Name = "PartB_MessageData")] #endif internal partial class MessageData { public MessageData DeepClone() { var other = new MessageData(); other.ver = this.ver; other.message = this.message; other.severityLevel = this.severityLevel; Debug.Assert(other.properties != null, "The constructor should have allocated properties dictionary"); Utils.CopyDictionary(this.properties, other.properties); return other; } } }
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.External { using System; using System.Diagnostics; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; /// <summary> /// Partial class to add the EventData attribute and any additional customizations to the generated type. /// </summary> #if !NET45 // .Net 4.5 has a custom implementation of RichPayloadEventSource [System.Diagnostics.Tracing.EventData(Name = "PartB_AvailabilityData")] #endif internal partial class MessageData { public MessageData DeepClone() { var other = new MessageData(); other.ver = this.ver; other.message = this.message; other.severityLevel = this.severityLevel; Debug.Assert(other.properties != null, "The constructor should have allocated properties dictionary"); Utils.CopyDictionary(this.properties, other.properties); return other; } } }
mit
C#
6873a2399354b1dea3d5f7ac69cbb2e6063db18d
Add using
DustinCampbell/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
src/OmniSharp.Cake/Services/RequestHandlers/Navigation/FindSymbolsHandler.cs
src/OmniSharp.Cake/Services/RequestHandlers/Navigation/FindSymbolsHandler.cs
using System; using System.Composition; using System.Threading.Tasks; using OmniSharp.Cake.Extensions; using OmniSharp.Extensions; using OmniSharp.Mef; using OmniSharp.Models; using OmniSharp.Models.FindSymbols; using static OmniSharp.Cake.Constants; namespace OmniSharp.Cake.Services.RequestHandlers.Navigation { [OmniSharpHandler(OmniSharpEndpoints.FindSymbols, Constants.LanguageNames.Cake), Shared] public class FindSymbolsHandler : CakeRequestHandler<FindSymbolsRequest, QuickFixResponse> { [ImportingConstructor] public FindSymbolsHandler(OmniSharpWorkspace workspace) : base(workspace) { } public override Task<QuickFixResponse> Handle(FindSymbolsRequest request) { Func<string, bool> isMatch = candidate => request != null ? candidate.IsValidCompletionFor(request.Filter) : true; return Workspace.CurrentSolution.FindSymbols(isMatch, p => p.Name.EndsWith(LanguageNames.Cake, StringComparison.OrdinalIgnoreCase)); } protected override Task<QuickFixResponse> TranslateResponse(QuickFixResponse response, FindSymbolsRequest request) { return response.TranslateAsync(Workspace); } } }
using System; using System.Composition; using System.Threading.Tasks; using OmniSharp.Cake.Extensions; using OmniSharp.Extensions; using OmniSharp.Mef; using OmniSharp.Models; using OmniSharp.Models.FindSymbols; namespace OmniSharp.Cake.Services.RequestHandlers.Navigation { [OmniSharpHandler(OmniSharpEndpoints.FindSymbols, Constants.LanguageNames.Cake), Shared] public class FindSymbolsHandler : CakeRequestHandler<FindSymbolsRequest, QuickFixResponse> { [ImportingConstructor] public FindSymbolsHandler(OmniSharpWorkspace workspace) : base(workspace) { } public override Task<QuickFixResponse> Handle(FindSymbolsRequest request) { Func<string, bool> isMatch = candidate => request != null ? candidate.IsValidCompletionFor(request.Filter) : true; return Workspace.CurrentSolution.FindSymbols(isMatch, p => p.Name.EndsWith(LanguageNames.Cake, StringComparison.OrdinalIgnoreCase)); } protected override Task<QuickFixResponse> TranslateResponse(QuickFixResponse response, FindSymbolsRequest request) { return response.TranslateAsync(Workspace); } } }
mit
C#
f6b10eab266200fc8289ae76e2d39870fae47750
Put StreamReader into using blog
riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm
src/DotVVM.Framework/ResourceManagement/InlineStylesheetResource.cs
src/DotVVM.Framework/ResourceManagement/InlineStylesheetResource.cs
using System; using System.IO; using DotVVM.Framework.Controls; using DotVVM.Framework.Hosting; using Newtonsoft.Json; namespace DotVVM.Framework.ResourceManagement { /// <summary> /// CSS in header. It's perfect for small css. For example critical CSS. /// </summary> public class InlineStylesheetResource : ResourceBase { private string code; private readonly ILocalResourceLocation resourceLocation; [JsonConstructor] public InlineStylesheetResource(ILocalResourceLocation resourceLocation) : base(ResourceRenderPosition.Head) { this.resourceLocation = resourceLocation; } /// <inheritdoc/> public override void Render(IHtmlWriter writer, IDotvvmRequestContext context, string resourceName) { if (code == null) { using (var resourceStream = resourceLocation.LoadResource(context)) { using (var resourceStreamReader = new StreamReader(resourceStream)) { code = resourceStreamReader.ReadToEnd(); } } } if (!string.IsNullOrWhiteSpace(code)) { writer.RenderBeginTag("style"); writer.WriteUnencodedText(code); writer.RenderEndTag(); } } } }
using System; using System.IO; using DotVVM.Framework.Controls; using DotVVM.Framework.Hosting; using Newtonsoft.Json; namespace DotVVM.Framework.ResourceManagement { /// <summary> /// CSS in header. It's perfect for critical CSS. /// </summary> public class InlineStylesheetResource : ResourceBase { private string code; private readonly ILocalResourceLocation resourceLocation; [JsonConstructor] public InlineStylesheetResource(ILocalResourceLocation resourceLocation) : base(ResourceRenderPosition.Head) { this.resourceLocation = resourceLocation; } /// <inheritdoc/> public override void Render(IHtmlWriter writer, IDotvvmRequestContext context, string resourceName) { if (code == null) { using (var resourceStream = resourceLocation.LoadResource(context)) { code = new StreamReader(resourceStream).ReadToEnd(); } } if (!string.IsNullOrWhiteSpace(code)) { writer.RenderBeginTag("style"); writer.WriteUnencodedText(code); writer.RenderEndTag(); } } } }
apache-2.0
C#
bba9ced1409ae069b6d16946a054cab2c21165d3
Allow using 2 digit tags
Sitecore/Sitecore-Instance-Manager
src/SIM.ContainerInstaller/Repositories/TagRepository/GitHubTagRepository.cs
src/SIM.ContainerInstaller/Repositories/TagRepository/GitHubTagRepository.cs
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using SIM.ContainerInstaller.Repositories.TagRepository.Models; using SIM.ContainerInstaller.Repositories.TagRepository.Parsers; namespace SIM.ContainerInstaller.Repositories.TagRepository { public class GitHubTagRepository : ITagRepository { private readonly string _shortTagPattern = @"^([0-9]+.[0-9]+.[0-9]+|[0-9]+.[0-9]+)-[^-]+$"; // tag examples: "10.0.0-ltsc2019", "10.0-2004" private IEnumerable<SitecoreTagsEntity> _sitecoreTagsEntities; private IEnumerable<SitecoreTagsEntity> SitecoreTagsEntities => _sitecoreTagsEntities ?? (_sitecoreTagsEntities = new SitecoreTagsParser().GetTagsEntities()); private static GitHubTagRepository _instance; public static GitHubTagRepository GetInstance() { return _instance ?? (_instance = new GitHubTagRepository()); } public IEnumerable<string> GetTags() { return SitecoreTagsEntities?.Select(entity => entity.Tags) .SelectMany(tags => tags.Select(tag => tag.Tag)); } private IEnumerable<string> GetSitecoreTags(string sitecoreVersionParam, string namespaceParam) { return SitecoreTagsEntities?.Where(entity => entity.Namespace == namespaceParam) .Select(entity => entity.Tags).SelectMany(tags => tags.Select(tag => tag.Tag)) .Where(t => t.StartsWith(sitecoreVersionParam)); } public IEnumerable<string> GetSortedShortSitecoreTags(string sitecoreVersionParam, string namespaceParam) { IEnumerable<string> tags = this.GetSitecoreTags(sitecoreVersionParam, namespaceParam); if (tags != null) { Regex regex = new Regex(_shortTagPattern); return tags.Where(tag => regex.IsMatch(tag)).Distinct().OrderBy(tag => tag); } return new List<string>(); } } }
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using SIM.ContainerInstaller.Repositories.TagRepository.Models; using SIM.ContainerInstaller.Repositories.TagRepository.Parsers; namespace SIM.ContainerInstaller.Repositories.TagRepository { public class GitHubTagRepository : ITagRepository { private readonly string _shortTagPattern = @"^[0-9]+.[0-9]+.[0-9]+-.[^-]+$"; // tag example: 10.0.0-ltsc2019 private IEnumerable<SitecoreTagsEntity> _sitecoreTagsEntities; private IEnumerable<SitecoreTagsEntity> SitecoreTagsEntities => _sitecoreTagsEntities ?? (_sitecoreTagsEntities = new SitecoreTagsParser().GetTagsEntities()); private static GitHubTagRepository _instance; public static GitHubTagRepository GetInstance() { return _instance ?? (_instance = new GitHubTagRepository()); } public IEnumerable<string> GetTags() { return SitecoreTagsEntities?.Select(entity => entity.Tags) .SelectMany(tags => tags.Select(tag => tag.Tag)); } private IEnumerable<string> GetSitecoreTags(string sitecoreVersionParam, string namespaceParam) { return SitecoreTagsEntities?.Where(entity => entity.Namespace == namespaceParam) .Select(entity => entity.Tags).SelectMany(tags => tags.Select(tag => tag.Tag)) .Where(t => t.StartsWith(sitecoreVersionParam)); } public IEnumerable<string> GetSortedShortSitecoreTags(string sitecoreVersionParam, string namespaceParam) { IEnumerable<string> tags = this.GetSitecoreTags(sitecoreVersionParam, namespaceParam); if (tags != null) { Regex regex = new Regex(_shortTagPattern); return tags.Where(tag => regex.IsMatch(tag)).Distinct().OrderBy(tag => tag); } return new List<string>(); } } }
mit
C#
7ed04de826d20790f7fddde8e1bc46ca629ac7f9
Fix build
suvroc/WebAPI-OWASP-App-Sensor
Tests/Owasp.AppSensor.Demo.Tests/RE1.TestUnexpectedHttpCommand.cs
Tests/Owasp.AppSensor.Demo.Tests/RE1.TestUnexpectedHttpCommand.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Owin.Testing; using Newtonsoft.Json; using NUnit.Framework; using Owasp.AppSensor.Demo.Api; namespace Owasp.AppSensor.Demo.Tests { [TestFixture] public class TestUnexpectedHttpCommand { [Test] [Category("RequireDatabase")] public async Task TestGoodMethod() { try { using (var server = TestServer.Create<Startup>()) { var result = await server.HttpClient.GetAsync("api/book"); string responseContent = await result.Content.ReadAsStringAsync(); var entity = JsonConvert.DeserializeObject<List<string>>(responseContent); Assert.IsTrue(entity.Count == 3); } } catch (Exception) { throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Owin.Testing; using Newtonsoft.Json; using NUnit.Framework; using Owasp.AppSensor.Demo.Api; namespace Owasp.AppSensor.Demo.Tests { [TestFixture] public class TestUnexpectedHttpCommand { [Test] public async Task TestGoodMethod() { try { using (var server = TestServer.Create<Startup>()) { var result = await server.HttpClient.GetAsync("api/book"); string responseContent = await result.Content.ReadAsStringAsync(); var entity = JsonConvert.DeserializeObject<List<string>>(responseContent); Assert.IsTrue(entity.Count == 3); } } catch (Exception) { throw; } } } }
mit
C#
057a77f35fad3057a0f699c72a52a1c2e88d80dc
Add xmldocs for GitHubContext
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.Exports/Services/GitHubContext.cs
src/GitHub.Exports/Services/GitHubContext.cs
using GitHub.Exports; using GitHub.Primitives; namespace GitHub.Services { /// <summary> /// Information used to map betwen a GitHub URL and some other context. This might be used to navigate /// between a GitHub URL and the location a repository file. Alternatively it might be used to map between /// the line a in a blame view and GitHub URL. /// </summary> public class GitHubContext { /// <summary> /// The owner of a repository. /// </summary> public string Owner { get; set; } /// <summary> /// The name of a repository. /// </summary> public string RepositoryName { get; set; } /// <summary> /// The host of a repository ("github.com" or a GitHub Enterprise host). /// </summary> public string Host { get; set; } /// <summary> /// The name of a branch stored on GitHub (not the local branch name). /// </summary> public string BranchName { get; set; } /// <summary> /// Like a tree-ish but with ':' changed to '/' (e.g. "master/src" not "master:src"). /// </summary> public string TreeishPath { get; set; } /// <summary> /// The name of a file on GitHub. /// </summary> public string BlobName { get; set; } /// <summary> /// A PR number if this context represents a PR. /// </summary> public int? PullRequest { get; set; } /// <summary> /// An issue number if this context represents an issue. /// </summary> public int? Issue { get; set; } /// <summary> /// The line number in a file. /// </summary> public int? Line { get; set; } /// <summary> /// The end line number if this context represents a range. /// </summary> public int? LineEnd { get; set; } /// <summary> /// The source Url of the context (when context originated from a URL). /// </summary> public UriString Url { get; set; } /// <summary> /// The type of context if known (blob, blame etc). /// </summary> public LinkType LinkType { get; set; } } }
using GitHub.Exports; using GitHub.Primitives; namespace GitHub.Services { public class GitHubContext { public string Owner { get; set; } public string RepositoryName { get; set; } public string Host { get; set; } public string BranchName { get; set; } /// <summary> /// Like a tree-ish but with ':' changed to '/' (e.g. "master/src" not "master:src"). /// </summary> public string TreeishPath { get; set; } public string BlobName { get; set; } public int? PullRequest { get; set; } public int? Issue { get; set; } public int? Line { get; set; } public int? LineEnd { get; set; } public UriString Url { get; set; } public LinkType LinkType { get; set; } } }
mit
C#
243b0c9e755372f10236ffc28306bda3c331a9ec
Update AssemblyInfo
ZacMarcus/YahooFinance.NET
YahooFinance.NET/Properties/AssemblyInfo.cs
YahooFinance.NET/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("YahooFinance.NET")] [assembly: AssemblyDescription("Download historical end of day stock data and historical dividend data via the Yahoo Finance API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("https://github.com/ZacMarcus")] [assembly: AssemblyProduct("YahooFinance.NET")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ffaa8437-97a3-43dc-972a-8c358d37a98f")] // 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("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("YahooFinance.NET")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("YahooFinance.NET")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ffaa8437-97a3-43dc-972a-8c358d37a98f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
293da35a504d9c96d801632113d478b36c94309d
Remove unnecessary using
rubberduck203/GitNStats,rubberduck203/GitNStats
tests/gitnstats.core.tests/Analysis/DateFilter.cs
tests/gitnstats.core.tests/Analysis/DateFilter.cs
using System; using GitNStats.Core.Tests; using Xunit; using static GitNStats.Core.Analysis; using static GitNStats.Core.Tests.Fakes; namespace GitNStats.Tests.Analysis { public class DateFilter { static TimeSpan AdtOffset = new TimeSpan(-3,0,0); static TimeSpan EstOffset = new TimeSpan(-4,0,0); static TimeSpan CstOffset = new TimeSpan(-6,0,0); static DateTime TestTime = new DateTime(2017,6,21,13,30,0); [Fact] public void LaterThanFilter_ReturnsTrue() { var commitTime = new DateTimeOffset(TestTime, EstOffset) + TimeSpan.FromDays(1); var commit = Commit().WithAuthor(commitTime); var predicate = OnOrAfter(TestTime.Date); Assert.True(predicate(Diff(commit))); } [Fact] public void PriorToFilter_ReturnsFalse() { var commitTime = new DateTimeOffset(TestTime, EstOffset) - TimeSpan.FromDays(1); var commit = Commit().WithAuthor(commitTime); var predicate = OnOrAfter(TestTime.Date); Assert.False(predicate(Diff(commit))); } [Fact] public void GivenTimeInESTAndCommitWasInADT_ReturnsFalse() { var commit = Commit().WithAuthor(new DateTimeOffset(TestTime, AdtOffset)); var predicate = OnOrAfter(new DateTimeOffset(TestTime, EstOffset).LocalDateTime); Assert.False(predicate(Diff(commit))); } [Fact] public void WhenEqualTo_ReturnTrue() { var commitTime = new DateTimeOffset(TestTime, EstOffset); var commit = Commit().WithAuthor(commitTime); var predicate = OnOrAfter(commitTime.LocalDateTime); Assert.True(predicate(Diff(commit))); } [Fact] public void GivenTimeInESTAndCommitWasCST_ReturnsTrue() { var commit = Commit().WithAuthor(new DateTimeOffset(TestTime, CstOffset)); var predicate = OnOrAfter(new DateTimeOffset(TestTime, EstOffset).LocalDateTime); Assert.True(predicate(Diff(commit))); } } }
using System; using GitNStats.Core.Tests; using LibGit2Sharp; using Xunit; using static GitNStats.Core.Analysis; using static GitNStats.Core.Tests.Fakes; namespace GitNStats.Tests.Analysis { public class DateFilter { static TimeSpan AdtOffset = new TimeSpan(-3,0,0); static TimeSpan EstOffset = new TimeSpan(-4,0,0); static TimeSpan CstOffset = new TimeSpan(-6,0,0); static DateTime TestTime = new DateTime(2017,6,21,13,30,0); [Fact] public void LaterThanFilter_ReturnsTrue() { var commitTime = new DateTimeOffset(TestTime, EstOffset) + TimeSpan.FromDays(1); var commit = Commit().WithAuthor(commitTime); var predicate = OnOrAfter(TestTime.Date); Assert.True(predicate(Diff(commit))); } [Fact] public void PriorToFilter_ReturnsFalse() { var commitTime = new DateTimeOffset(TestTime, EstOffset) - TimeSpan.FromDays(1); var commit = Commit().WithAuthor(commitTime); var predicate = OnOrAfter(TestTime.Date); Assert.False(predicate(Diff(commit))); } [Fact] public void GivenTimeInESTAndCommitWasInADT_ReturnsFalse() { var commit = Commit().WithAuthor(new DateTimeOffset(TestTime, AdtOffset)); var predicate = OnOrAfter(new DateTimeOffset(TestTime, EstOffset).LocalDateTime); Assert.False(predicate(Diff(commit))); } [Fact] public void WhenEqualTo_ReturnTrue() { var commitTime = new DateTimeOffset(TestTime, EstOffset); var commit = Commit().WithAuthor(commitTime); var predicate = OnOrAfter(commitTime.LocalDateTime); Assert.True(predicate(Diff(commit))); } [Fact] public void GivenTimeInESTAndCommitWasCST_ReturnsTrue() { var commit = Commit().WithAuthor(new DateTimeOffset(TestTime, CstOffset)); var predicate = OnOrAfter(new DateTimeOffset(TestTime, EstOffset).LocalDateTime); Assert.True(predicate(Diff(commit))); } } }
mit
C#
307d94a9d03cd9b9c0cc387ec0c7789f6d99eb68
comment modified
marek-vysoky/box-windows-sdk-v2,box/box-windows-sdk-v2
Box.V2/Models/BoxPreflightCheck.cs
Box.V2/Models/BoxPreflightCheck.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Box.V2.Models { /// <summary> /// Box representation of a preflight check response /// </summary> public class BoxPreflightCheck { public const string FieldUploadUrl = "upload_url"; public const string FieldUploadToken = "upload_token"; /// <summary> /// The upload URL to optionally use when uploading the file /// </summary> [JsonProperty(PropertyName = FieldUploadUrl)] public string UploadUrl { get; private set; } /// <summary> /// Convenience method to create Uri instance from UploadUrl string value /// </summary> public Uri UploadUri { get { return new Uri(this.UploadUrl); } } /// <summary> /// Currently not used. /// </summary> [JsonProperty(PropertyName = FieldUploadToken)] public string UploadToken { get; private set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Box.V2.Models { /// <summary> /// Box representation of a preflight check response /// </summary> public class BoxPreflightCheck { public const string FieldUploadUrl = "upload_url"; public const string FieldUploadToken = "upload_token"; /// <summary> /// The upload URL to optionally use when uploading the file (e.g. when upload acceleration is enabled for your Enterprise). /// </summary> [JsonProperty(PropertyName = FieldUploadUrl)] public string UploadUrl { get; private set; } /// <summary> /// Convenience method to create Uri instance from UploadUrl string value /// </summary> public Uri UploadUri { get { return new Uri(this.UploadUrl); } } /// <summary> /// Currently not used. /// </summary> [JsonProperty(PropertyName = FieldUploadToken)] public string UploadToken { get; private set; } } }
apache-2.0
C#
2beb08e090fe527e4322b96e99894e763d11d0d3
Test Scan being lazy
smzinovyev/MoreLINQ,ddpruitt/morelinq,morelinq/MoreLINQ,Agbar/MoreLINQ,Agbar/MoreLINQ,fsateler/MoreLINQ,ddpruitt/morelinq,fsateler/MoreLINQ,morelinq/MoreLINQ
MoreLinq.Test/ScanTest.cs
MoreLinq.Test/ScanTest.cs
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2008 Jonathan Skeet. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Linq; using NUnit.Framework; namespace MoreLinq.Test { [TestFixture] public class ScanTest { [Test] [ExpectedException(typeof(InvalidOperationException))] public void ScanEmpty() { (new int[] { }).Scan(SampleData.Plus).Count(); } [Test] public void ScanSum() { var result = SampleData.Values.Scan(SampleData.Plus); var gold = SampleData.Values.PreScan(SampleData.Plus, 0).ZipShortest(SampleData.Values, SampleData.Plus); result.AssertSequenceEqual(gold); } [Test] public void ScanIsLazy() { new BreakingSequence<object>().Scan<object>(delegate { throw new NotImplementedException(); }); } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2008 Jonathan Skeet. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Linq; using NUnit.Framework; namespace MoreLinq.Test { [TestFixture] public class ScanTest { [Test] [ExpectedException(typeof(InvalidOperationException))] public void ScanEmpty() { (new int[] { }).Scan(SampleData.Plus).Count(); } [Test] public void ScanSum() { var result = SampleData.Values.Scan(SampleData.Plus); var gold = SampleData.Values.PreScan(SampleData.Plus, 0).ZipShortest(SampleData.Values, SampleData.Plus); result.AssertSequenceEqual(gold); } } }
apache-2.0
C#
cd727671501d64b98c2588fa2a93009e651b5874
Update NameProtection.cs
Desolath/ConfuserEx3
Confuser.Renamer/NameProtection.cs
Confuser.Renamer/NameProtection.cs
using System; using System.IO; using Confuser.Core; namespace Confuser.Renamer { internal class NameProtection : Protection { public const string _Id = "rename"; public const string _FullId = "Ki.Rename"; public const string _ServiceId = "Ki.Rename"; public override string Name { get { return "Name Protection"; } } public override string Description { get { return "This protection obfuscate the symbols' name so the decompiled source code can neither be compiled nor read."; } } public override string Id { get { return _Id; } } public override string FullId { get { return _FullId; } } public override ProtectionPreset Preset { get { return ProtectionPreset.Maximum; } } protected override void Initialize(ConfuserContext context) { context.Registry.RegisterService(_ServiceId, typeof(INameService), new NameService(context)); } protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPostStage(PipelineStage.Inspection, new AnalyzePhase(this)); pipeline.InsertPostStage(PipelineStage.BeginModule, new RenamePhase(this)); pipeline.InsertPreStage(PipelineStage.EndModule, new PostRenamePhase(this)); pipeline.InsertPostStage(PipelineStage.SaveModules, new ExportMapPhase(this)); } class ExportMapPhase : ProtectionPhase { public ExportMapPhase(NameProtection parent) : base(parent) { } public override ProtectionTargets Targets { get { return ProtectionTargets.Modules; } } public override string Name { get { return "Export symbol map"; } } public override bool ProcessAll { get { return true; } } protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { var srv = (NameService)context.Registry.GetService<INameService>(); var map = srv.GetNameMap(); if (map.Count == 0) return; string path = Path.GetFullPath(Path.Combine(context.OutputDirectory, "symbols.map")); string dir = Path.GetDirectoryName(path); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); using (var writer = new StreamWriter(File.OpenWrite(path))) { foreach (var entry in map) writer.WriteLine("{0}\t{1}", entry.Key, entry.Value); } } } } }
using System; using System.IO; using Confuser.Core; namespace Confuser.Renamer { internal class NameProtection : Protection { public const string _Id = "rename"; public const string _FullId = "Ki.Rename"; public const string _ServiceId = "Ki.Rename"; public override string Name { get { return "Name Protection"; } } public override string Description { get { return "This protection obfuscate the symbols' name so the decompiled source code can neither be compiled nor read."; } } public override string Id { get { return _Id; } } public override string FullId { get { return _FullId; } } public override ProtectionPreset Preset { get { return ProtectionPreset.Minimum; } } protected override void Initialize(ConfuserContext context) { context.Registry.RegisterService(_ServiceId, typeof(INameService), new NameService(context)); } protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPostStage(PipelineStage.Inspection, new AnalyzePhase(this)); pipeline.InsertPostStage(PipelineStage.BeginModule, new RenamePhase(this)); pipeline.InsertPreStage(PipelineStage.EndModule, new PostRenamePhase(this)); pipeline.InsertPostStage(PipelineStage.SaveModules, new ExportMapPhase(this)); } class ExportMapPhase : ProtectionPhase { public ExportMapPhase(NameProtection parent) : base(parent) { } public override ProtectionTargets Targets { get { return ProtectionTargets.Modules; } } public override string Name { get { return "Export symbol map"; } } public override bool ProcessAll { get { return true; } } protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { var srv = (NameService)context.Registry.GetService<INameService>(); var map = srv.GetNameMap(); if (map.Count == 0) return; string path = Path.GetFullPath(Path.Combine(context.OutputDirectory, "symbols.map")); string dir = Path.GetDirectoryName(path); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); using (var writer = new StreamWriter(File.OpenWrite(path))) { foreach (var entry in map) writer.WriteLine("{0}\t{1}", entry.Key, entry.Value); } } } } }
mit
C#
2d6b7df6832085510f242e2e5d86e1450c6a507c
Update AssemblyInfo.cs
Softlr/selenium-webdriver-extensions,Softlr/selenium-webdriver-extensions,RaYell/selenium-webdriver-extensions,Softlr/Selenium.WebDriver.Extensions
test/Selenium.WebDriver.Extensions.Tests/Properties/AssemblyInfo.cs
test/Selenium.WebDriver.Extensions.Tests/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("Selenium.WebDriver.Extensions.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lukasz Rajchel")] [assembly: AssemblyProduct("Selenium.WebDriver.Extensions.Tests")] [assembly: AssemblyCopyright("Copyright © Lukasz Rajchel")] [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("cb33e53c-2174-49c8-8f5f-217a0bf8c9de")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.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("Selenium.WebDriver.Extensions.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Unic AG")] [assembly: AssemblyProduct("Selenium.WebDriver.Extensions.Tests")] [assembly: AssemblyCopyright("Copyright © Unic AG 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("cb33e53c-2174-49c8-8f5f-217a0bf8c9de")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
6cdd8d774bfdecc74c0204002e99296364507f47
Fix OfficerAppointmentLink tests
kevbite/CompaniesHouse.NET
src/CompaniesHouse.Tests/CompaniesHouseOfficersAppointmentClientTests/OfficerBuilder.cs
src/CompaniesHouse.Tests/CompaniesHouseOfficersAppointmentClientTests/OfficerBuilder.cs
using AutoFixture; using CompaniesHouse.Response.Officers; namespace CompaniesHouse.Tests.CompaniesHouseOfficersAppointmentClientTests { public static class OfficerBuilder { public static ResourceBuilders.Officer Build(CompaniesHouseOfficerByAppointmentTestCase testCase) { var fixture = new Fixture(); fixture.Customizations.Add(new UniversalDateSpecimenBuilder<ResourceBuilders.Officer>(x => x.AppointedOn)); fixture.Customizations.Add(new UniversalDateSpecimenBuilder<ResourceBuilders.Officer>(x => x.ResignedOn)); return fixture .Build<ResourceBuilders.Officer>() .With(x => x.Links, fixture .Build<OfficerLinks>() .With(x => x.Officer, fixture .Build<OfficerAppointmentLink>() .With(x => x.AppointmentsResource, "/officer/xyz/appointments") .Create()) .Create()) .With(x => x.OfficerRole, testCase.OfficerRole) .Create(); } } }
using AutoFixture; namespace CompaniesHouse.Tests.CompaniesHouseOfficersAppointmentClientTests { public static class OfficerBuilder { public static ResourceBuilders.Officer Build(CompaniesHouseOfficerByAppointmentTestCase testCase) { var fixture = new Fixture(); fixture.Customizations.Add(new UniversalDateSpecimenBuilder<ResourceBuilders.Officer>(x => x.AppointedOn)); fixture.Customizations.Add(new UniversalDateSpecimenBuilder<ResourceBuilders.Officer>(x => x.ResignedOn)); return fixture .Build<ResourceBuilders.Officer>() .With(x => x.OfficerRole, testCase.OfficerRole) .Create(); } } }
mit
C#
2ad77f005b6fad299f2bc28e117ce41ebb451b80
Add static to class definition because reasons.
Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net
LearnosityDemo/Program.cs
LearnosityDemo/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace LearnosityDemo { public static class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace LearnosityDemo { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
apache-2.0
C#
9d3e9c513e9fc6bdf9f19ed0e5febb16ec7d2c71
Update WebDownloader.cs
milkshakesoftware/PreMailer.Net
PreMailer.Net/PreMailer.Net/Downloaders/WebDownloader.cs
PreMailer.Net/PreMailer.Net/Downloaders/WebDownloader.cs
using System; using System.IO; using System.Net; using System.Text; namespace PreMailer.Net.Downloaders { public class WebDownloader : IWebDownloader { private static IWebDownloader _sharedDownloader; public static IWebDownloader SharedDownloader { get { if (_sharedDownloader == null) { _sharedDownloader = new WebDownloader(); } return _sharedDownloader; } set { _sharedDownloader = value; } } public string DownloadString(Uri uri) { var request = WebRequest.Create(uri); using (var response = (HttpWebResponse)request.GetResponse()) { string Charset = response.CharacterSet; Encoding encoding = Encoding.GetEncoding( Charset ); using( var stream = response.GetResponseStream( ) ) using( var reader = new StreamReader( stream, encoding ) ) { return reader.ReadToEnd( ); } } } } }
using System; using System.IO; using System.Net; namespace PreMailer.Net.Downloaders { public class WebDownloader : IWebDownloader { private static IWebDownloader _sharedDownloader; public static IWebDownloader SharedDownloader { get { if (_sharedDownloader == null) { _sharedDownloader = new WebDownloader(); } return _sharedDownloader; } set { _sharedDownloader = value; } } public string DownloadString(Uri uri) { var request = WebRequest.Create(uri); using (var response = (HttpWebResponse)request.GetResponse()) { string Charset = response.CharacterSet; Encoding encoding = Encoding.GetEncoding( Charset ); using( var stream = response.GetResponseStream( ) ) using( var reader = new StreamReader( stream, encoding ) ) { return reader.ReadToEnd( ); } } } } }
mit
C#
46ee71c2ea5020aeb42db77f4834ec903dcf72a8
Fix declaration of P/Invoke methods.
cube-soft/Cube.FileSystem,cube-soft/Cube.Core,cube-soft/Cube.Core,cube-soft/Cube.FileSystem
Libraries/NativeMethods/Shell32.cs
Libraries/NativeMethods/Shell32.cs
/* ------------------------------------------------------------------------- */ /// /// Copyright (c) 2010 CubeSoft, 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. /// /* ------------------------------------------------------------------------- */ using System; using System.Runtime.InteropServices; namespace Cube.FileSystem.Shell32 { /* --------------------------------------------------------------------- */ /// /// Shell32.NativeMethods /// /// <summary> /// shell32.dll に定義された関数を宣言するためのクラスです。 /// </summary> /// /* --------------------------------------------------------------------- */ internal static class NativeMethods { /* ----------------------------------------------------------------- */ /// /// SHGetFileInfo /// /// <summary> /// https://msdn.microsoft.com/en-us/library/windows/desktop/bb762179.aspx /// </summary> /// /* ----------------------------------------------------------------- */ [DllImport(LibName, CharSet = CharSet.Unicode)] public static extern IntPtr SHGetFileInfo( string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags ); #region Fields private const string LibName = "shell32.dll"; #endregion } }
/* ------------------------------------------------------------------------- */ /// /// Copyright (c) 2010 CubeSoft, 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. /// /* ------------------------------------------------------------------------- */ using System; using System.Runtime.InteropServices; namespace Cube.FileSystem.Shell32 { /* --------------------------------------------------------------------- */ /// /// Shell32.NativeMethods /// /// <summary> /// shell32.dll に定義された関数を宣言するためのクラスです。 /// </summary> /// /* --------------------------------------------------------------------- */ internal static class NativeMethods { /* ----------------------------------------------------------------- */ /// /// SHGetFileInfo /// /// <summary> /// https://msdn.microsoft.com/en-us/library/windows/desktop/bb762179.aspx /// </summary> /// /* ----------------------------------------------------------------- */ [DllImport(LibName, CharSet = CharSet.Unicode)] public static extern IntPtr SHGetFileInfo( string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags ); #region Fields private const string LibName = "shell32.dll"; public const uint SHGFI_USEFILEATTRIBUTES = 0x00000010; public const uint SHGFI_TYPENAME = 0x00000400; public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; #endregion } }
apache-2.0
C#
c3511fcfadf9296da2b787a435d8585d7ba8e9d3
Include Headers property in ApiException
actionshrimp/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,mattgray/SevenDigital.Api.Wrapper,knocte/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper
src/SevenDigital.Api.Wrapper/Exceptions/ApiException.cs
src/SevenDigital.Api.Wrapper/Exceptions/ApiException.cs
using System; using System.Collections.Generic; using System.Net; using System.Runtime.Serialization; using SevenDigital.Api.Wrapper.Http; namespace SevenDigital.Api.Wrapper.Exceptions { public abstract class ApiException : Exception { public string Uri { get; internal set; } public HttpStatusCode StatusCode { get; private set; } public string ResponseBody { get; private set; } public IDictionary<string, string> Headers { get; private set; } protected ApiException() { } protected ApiException(string message) : base(message) { } protected ApiException(string message, Exception innerException) : base(message, innerException) { } protected ApiException(string message, Exception innerException, Response response) : base(message, innerException) { ResponseBody = response.Body; Headers = response.Headers; StatusCode = response.StatusCode; } protected ApiException(string message, Response response) : base(message) { ResponseBody = response.Body; Headers = response.Headers; StatusCode = response.StatusCode; } protected ApiException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System; using System.Net; using System.Runtime.Serialization; using SevenDigital.Api.Wrapper.Http; namespace SevenDigital.Api.Wrapper.Exceptions { public abstract class ApiException : Exception { public string Uri { get; internal set; } public HttpStatusCode StatusCode { get; private set; } public string ResponseBody { get; private set; } protected ApiException() { } protected ApiException(string message) : base(message) { } protected ApiException(string message, Exception innerException) : base(message, innerException) { } protected ApiException(string message, Exception innerException, Response response) : base(message, innerException) { ResponseBody = response.Body; StatusCode = response.StatusCode; } protected ApiException(string message, Response response) : base(message) { ResponseBody = response.Body; StatusCode = response.StatusCode; } protected ApiException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
mit
C#
2fc2bd6e29cb2ef37aea34f059cc88efc32d64df
Fix assertion for CPlusPlusSWIGBindingGeneratorWorksTest on Windows
Protobuild/Protobuild,hach-que/Protobuild,hach-que/Protobuild,Protobuild/Protobuild,silasary/Protobuild,silasary/Protobuild,Protobuild/Protobuild,Protobuild/Protobuild,silasary/Protobuild,Protobuild/Protobuild,hach-que/Protobuild
Protobuild.FunctionalTests/CPlusPlusSWIGBindingGeneratorWorksTest.cs
Protobuild.FunctionalTests/CPlusPlusSWIGBindingGeneratorWorksTest.cs
namespace Protobuild.Tests { using System.IO; using Xunit; public class CPlusPlusSWIGBindingGeneratorWorksTest : ProtobuildTest { [Fact] public void GenerationIsCorrect() { this.SetupTest("CPlusPlusSWIGBindingGeneratorWorks"); this.Generate("Windows"); Assert.True( File.Exists(this.GetPath(@"Library\Library.Windows.cproj")) || File.Exists(this.GetPath(@"Library\Library.Windows.vcxproj"))); if (File.Exists(this.GetPath(@"Library\Library.Windows.cproj"))) { var consoleContents = this.ReadFile(@"Library\Library.Windows.cproj"); Assert.Contains("swig -csharp -dllimport libLibrary util.i", consoleContents); } else if (File.Exists(this.GetPath(@"Library\Library.Windows.vcxproj"))) { var consoleContents = this.ReadFile(@"Library\Library.Windows.vcxproj"); Assert.Contains("swig\" -csharp -dllimport Library.dll util.i", consoleContents); } } } }
namespace Protobuild.Tests { using System.IO; using Xunit; public class CPlusPlusSWIGBindingGeneratorWorksTest : ProtobuildTest { [Fact] public void GenerationIsCorrect() { this.SetupTest("CPlusPlusSWIGBindingGeneratorWorks"); this.Generate("Windows"); Assert.True( File.Exists(this.GetPath(@"Library\Library.Windows.cproj")) || File.Exists(this.GetPath(@"Library\Library.Windows.vcxproj"))); if (File.Exists(this.GetPath(@"Library\Library.Windows.cproj"))) { var consoleContents = this.ReadFile(@"Library\Library.Windows.cproj"); Assert.Contains("swig -csharp -dllimport libLibrary util.i", consoleContents); } else if (File.Exists(this.GetPath(@"Library\Library.Windows.vcxproj"))) { var consoleContents = this.ReadFile(@"Library\Library.Windows.vcxproj"); Assert.Contains("swig -csharp -dllimport Library.dll util.i", consoleContents); } } } }
mit
C#
af4c643bceb5becac0c09032d51603afd3550db0
Update custom_web_view doc region to only include BookshelfWebViewPage<T> class
GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet
aspnet/4-auth/Views/BookshelfWebViewPage.cs
aspnet/4-auth/Views/BookshelfWebViewPage.cs
using System.Web.Mvc; using GoogleCloudSamples.Models; namespace GoogleCloudSamples.Views { // [START custom_web_view] public abstract class BookshelfWebViewPage<TModel> : WebViewPage<TModel> { public User CurrentUser => new User(this.User); } // [END custom_web_view] public abstract class BookshelfWebViewPage : WebViewPage { } }
using System.Web.Mvc; using GoogleCloudSamples.Models; // [START custom_web_view] namespace GoogleCloudSamples.Views { public abstract class BookshelfWebViewPage<TModel> : WebViewPage<TModel> { public User CurrentUser => new User(this.User); } public abstract class BookshelfWebViewPage : WebViewPage { } } // [END custom_web_view]
apache-2.0
C#
bd5d3743950a8d5a7fdce0c5864c85e3c0b85134
Add apollographql client name and version HTTP headers
ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates
Source/GraphQLTemplate/Source/GraphQLTemplate/ApplicationBuilderExtensions.cs
Source/GraphQLTemplate/Source/GraphQLTemplate/ApplicationBuilderExtensions.cs
namespace GraphQLTemplate { using System; using System.Linq; using Boxed.AspNetCore; using GraphQLTemplate.Constants; using GraphQLTemplate.Options; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Serilog; public static partial class ApplicationBuilderExtensions { /// <summary> /// Uses the static files middleware to serve static files. Also adds the Cache-Control and Pragma HTTP /// headers. The cache duration is controlled from configuration. /// See http://andrewlock.net/adding-cache-control-headers-to-static-files-in-asp-net-core/. /// </summary> public static IApplicationBuilder UseStaticFilesWithCacheControl(this IApplicationBuilder application) { var cacheProfile = application .ApplicationServices .GetRequiredService<CacheProfileOptions>() .Where(x => string.Equals(x.Key, CacheProfileName.StaticFiles, StringComparison.Ordinal)) .Select(x => x.Value) .SingleOrDefault(); return application .UseStaticFiles( new StaticFileOptions() { OnPrepareResponse = context => context.Context.ApplyCacheProfile(cacheProfile), }); } /// <summary> /// Uses custom serilog request logging. Adds additional properties to each log. /// See https://github.com/serilog/serilog-aspnetcore. /// </summary> public static IApplicationBuilder UseCustomSerilogRequestLogging(this IApplicationBuilder application) => application.UseSerilogRequestLogging( options => options.EnrichDiagnosticContext = (diagnosticContext, httpContext) => { var clientName = httpContext.Request.Headers["apollographql-client-name"]; if (clientName.Any()) { diagnosticContext.Set("ClientName", clientName); } var clientVersion = httpContext.Request.Headers["apollographql-client-version"]; if (clientVersion.Any()) { diagnosticContext.Set("ClientVersion", clientVersion); } diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value); diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme); }); } }
namespace GraphQLTemplate { using System; using System.Linq; using Boxed.AspNetCore; using GraphQLTemplate.Constants; using GraphQLTemplate.Options; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Serilog; public static partial class ApplicationBuilderExtensions { /// <summary> /// Uses the static files middleware to serve static files. Also adds the Cache-Control and Pragma HTTP /// headers. The cache duration is controlled from configuration. /// See http://andrewlock.net/adding-cache-control-headers-to-static-files-in-asp-net-core/. /// </summary> public static IApplicationBuilder UseStaticFilesWithCacheControl(this IApplicationBuilder application) { var cacheProfile = application .ApplicationServices .GetRequiredService<CacheProfileOptions>() .Where(x => string.Equals(x.Key, CacheProfileName.StaticFiles, StringComparison.Ordinal)) .Select(x => x.Value) .SingleOrDefault(); return application .UseStaticFiles( new StaticFileOptions() { OnPrepareResponse = context => context.Context.ApplyCacheProfile(cacheProfile), }); } /// <summary> /// Uses custom serilog request logging. Adds additional properties to each log. /// See https://github.com/serilog/serilog-aspnetcore. /// </summary> public static IApplicationBuilder UseCustomSerilogRequestLogging(this IApplicationBuilder application) => application.UseSerilogRequestLogging( options => options.EnrichDiagnosticContext = (diagnosticContext, httpContext) => { diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value); diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme); }); } }
mit
C#
b2e8a02f92bce7caab5437f28650f1b1b8ff51ed
Update HtmlHelperExtensions to take baseUri
mike-ward/Nancy.Markdown.Blog,mike-ward/Nancy.Markdown.Blog
Nancy.Blog/HtmlHelperExtensions.cs
Nancy.Blog/HtmlHelperExtensions.cs
using System.IO; using Nancy.ViewEngines.Razor; namespace Nancy.Markdown.Blog { public static class HtmlHelperExtensions { public static IHtmlString Markdown<TModel>(this HtmlHelpers<TModel> helpers, string text, string baseUri = null) { var md = new MarkdownDeep.Markdown {ExtraMode = true, UrlBaseLocation = baseUri}; var html = md.Transform(text); return new NonEncodedHtmlString(html); } public static IHtmlString MarkdownLoad<TModel>(this HtmlHelpers<TModel> helpers, string path, string baseUri = null) { return helpers.Markdown(File.ReadAllText(path), baseUri); } } }
using System.IO; using MarkdownDeep; using Nancy.ViewEngines.Razor; namespace Nancy.Markdown.Blog { public static class HtmlHelperExtensions { public static IHtmlString Markdown<TModel>(this HtmlHelpers<TModel> helpers, string text) { var md = new MarkdownDeep.Markdown {ExtraMode = true}; var html = md.Transform(text); return new NonEncodedHtmlString(html); } public static IHtmlString MarkdownLoad<TModel>(this HtmlHelpers<TModel> helpers, string path) { return helpers.Markdown(File.ReadAllText(path)); } } }
mit
C#
74d57221f805ad341dc2089bf0c0a7ff6c014a71
change xml documentation comments
saideldah/BLogicEngine
RuleEngine/RuleManager.cs
RuleEngine/RuleManager.cs
using System; using Jint; using System.Web.Script.Serialization; namespace RuleEngine { public class RuleManager { /// <summary> /// function to validate json object based on JavaScript Logical Expression /// </summary> /// <param name="jsLogicalExpression">JavaScript Logical Expression</param> /// <param name="jsonObjectToValidate">json Object To Validate</param> /// <returns>boolean result</returns> private static bool evaluateJavaScriptExpression(string jsLogicalExpression, string jsonObjectToValidate) { var JSEngine = new Engine(cfg => cfg.AllowClr()); bool outPut = false; try { var executeResult = JSEngine.Execute(@" var object = " + jsonObjectToValidate + "; var output = " + jsLogicalExpression + ";").GetValue("output"); outPut = Convert.ToBoolean(executeResult.ToString()); } catch (Jint.Runtime.JavaScriptException Ex) { Console.WriteLine(Ex.Message); } return outPut; } /// <summary> /// function to validate object based on BLogic language Logical Expression /// </summary> /// <param name="bLogicalExpression">BLogic Logical Expression</param> /// <param name="objectToValidate">C# object To Validate</param> /// <returns>boolean result</returns> public static bool Evaluate(string bLogicalExpression, object objectToValidate) { bool evaluationResult = false; //Transpile BLogical Expressions to javascript Logical Expressions string jsLogicExpression = Transpiler.BLogicToJavaScript(bLogicalExpression); //Conver objectToValidate to JSON string var jsonString = new JavaScriptSerializer().Serialize(objectToValidate); evaluationResult = evaluateJavaScriptExpression(jsLogicExpression, jsonString); return evaluationResult; } } }
using System; using Jint; using System.Web.Script.Serialization; namespace RuleEngine { public class RuleManager { /// <summary> /// function to validate json object based on JavaScript Logical Expression /// </summary> /// <param name="jsLogicalExpression">JavaScript Logical Expression</param> /// <param name="jsonObjectToValidate">json Object To Validate</param> /// <returns>boolean result</returns> private static bool evaluateJavaScriptExpression(string jsLogicalExpression, string jsonObjectToValidate) { var JSEngine = new Engine(cfg => cfg.AllowClr()); bool outPut = false; try { var executeResult = JSEngine.Execute(@" var object = " + jsonObjectToValidate + "; var output = " + jsLogicalExpression + ";").GetValue("output"); outPut = Convert.ToBoolean(executeResult.ToString()); } catch (Jint.Runtime.JavaScriptException Ex) { Console.WriteLine(Ex.Message); } return outPut; } /// <summary> /// function to validate json object based on JavaScript Logical Expression /// </summary> /// <param name="bLogicalExpression">JavaScript BLogical Expression</param> /// <param name="objectToValidate">C# object To Validate</param> /// <returns>boolean result</returns> public static bool Evaluate(string bLogicalExpression, object objectToValidate) { bool evaluationResult = false; //Transpile BLogical Expressions to javascript Logical Expressions string jsLogicExpression = Transpiler.BLogicToJavaScript(bLogicalExpression); //Conver objectToValidate to JSON string var jsonString = new JavaScriptSerializer().Serialize(objectToValidate); evaluationResult = evaluateJavaScriptExpression(jsLogicExpression, jsonString); return evaluationResult; } } }
mit
C#
3a05d4af3ce0bc6a08f8bb0337e9cdfb201e1680
Convert SassCompiler to use new tree structure and make sure it still works,
akatakritos/SassSharp
SassSharp/SassCompiler.cs
SassSharp/SassCompiler.cs
using SassSharp.Ast; using SassSharp.Tokens; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SassSharp { public class SassCompiler { public string Compile(string sass) { var tokenizer = new Tokenizer(); var builder = new SassSyntaxTreeBuilder(tokenizer.Tokenize(sass)); var compiler = new AstCompiler(); var render = new CssRenderer(); var ast = builder.Build(); Console.WriteLine(SassSyntaxTreeDumper.Dump(ast)); return render.Render(compiler.Compile(ast)); } } }
using SassSharp.Ast; using SassSharp.Tokens; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SassSharp { public class SassCompiler { public string Compile(string sass) { var tokenizer = new Tokenizer(); var builder = new AstBuilder(); var ruleEmitter = new CssRuleEmitter(); var render = new CssRenderer(); return render.Render(ruleEmitter.EmitRules(builder.Build(tokenizer.Tokenize(sass)))); } } }
mit
C#
c76897332505ddf2cd59f17ecf9f149e1eb46aa2
Include components namespace
mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection
Views/_ViewImports.cshtml
Views/_ViewImports.cshtml
@using System.Net.Http @using Microsoft.AspNetCore.Authorization @using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web @using Microsoft.JSInterop @using Cash_Flow_Projection @using Cash_Flow_Projection.Components.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using Cash_Flow_Projection @using System.Net.Http @using Microsoft.AspNetCore.Authorization @using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web @using Microsoft.JSInterop @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
mit
C#
31887c26b965f3c4b299a105c124424475028d77
Return the preprocessor command
FlorianRappl/Mages,FlorianRappl/Mages
src/Mages.Core/Tokens/PreprocessorToken.cs
src/Mages.Core/Tokens/PreprocessorToken.cs
namespace Mages.Core.Tokens { using Mages.Core.Source; using System; sealed class PreprocessorToken : IToken { private readonly TextPosition _start; private readonly TextPosition _end; private readonly String _payload; public PreprocessorToken(String payload, TextPosition start, TextPosition end) { _payload = payload; _start = start; _end = end; } public TokenType Type { get { return TokenType.Preprocessor; } } public TextPosition End { get { return _end; } } public TextPosition Start { get { return _start; } } public String Command { get { if (_payload.Length > 0 && Specification.IsNameStart((Int32)_payload[0])) { var length = 1; while (length < _payload.Length && Specification.IsName((Int32)_payload[length])) { length++; } return _payload.Substring(0, length); } return String.Empty; } } public String Payload { get { return _payload; } } } }
namespace Mages.Core.Tokens { using System; sealed class PreprocessorToken : IToken { private readonly TextPosition _start; private readonly TextPosition _end; private readonly String _payload; public PreprocessorToken(String payload, TextPosition start, TextPosition end) { _payload = payload; _start = start; _end = end; } public TokenType Type { get { return TokenType.Preprocessor; } } public TextPosition End { get { return _end; } } public TextPosition Start { get { return _start; } } public String Payload { get { return _payload; } } } }
mit
C#
5f863f2c0dc27ca3cc722339a6dad7d49e36200b
Remove InvocationReasons enum boxing
nguerrera/roslyn,mgoertz-msft/roslyn,VSadov/roslyn,agocke/roslyn,lorcanmooney/roslyn,wvdd007/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,Giftednewt/roslyn,robinsedlaczek/roslyn,ErikSchierboom/roslyn,TyOverby/roslyn,tmeschter/roslyn,mavasani/roslyn,sharwell/roslyn,srivatsn/roslyn,dotnet/roslyn,jkotas/roslyn,CaptainHayashi/roslyn,mavasani/roslyn,swaroop-sridhar/roslyn,ErikSchierboom/roslyn,MichalStrehovsky/roslyn,tmat/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,kelltrick/roslyn,davkean/roslyn,wvdd007/roslyn,diryboy/roslyn,eriawan/roslyn,dpoeschl/roslyn,AmadeusW/roslyn,reaction1989/roslyn,pdelvo/roslyn,reaction1989/roslyn,jcouv/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,robinsedlaczek/roslyn,lorcanmooney/roslyn,xasx/roslyn,jmarolf/roslyn,AmadeusW/roslyn,tannergooding/roslyn,Hosch250/roslyn,TyOverby/roslyn,Giftednewt/roslyn,bkoelman/roslyn,gafter/roslyn,tmat/roslyn,dpoeschl/roslyn,KevinRansom/roslyn,cston/roslyn,CaptainHayashi/roslyn,swaroop-sridhar/roslyn,panopticoncentral/roslyn,dotnet/roslyn,jmarolf/roslyn,AnthonyDGreen/roslyn,diryboy/roslyn,tvand7093/roslyn,tmeschter/roslyn,tmeschter/roslyn,jcouv/roslyn,weltkante/roslyn,AmadeusW/roslyn,aelij/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,cston/roslyn,AlekseyTs/roslyn,MattWindsor91/roslyn,mattscheffer/roslyn,physhi/roslyn,paulvanbrenk/roslyn,Hosch250/roslyn,jamesqo/roslyn,dotnet/roslyn,bkoelman/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,jamesqo/roslyn,genlu/roslyn,genlu/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,srivatsn/roslyn,KirillOsenkov/roslyn,DustinCampbell/roslyn,bartdesmet/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,jmarolf/roslyn,Giftednewt/roslyn,lorcanmooney/roslyn,CaptainHayashi/roslyn,jamesqo/roslyn,heejaechang/roslyn,jkotas/roslyn,abock/roslyn,tvand7093/roslyn,AnthonyDGreen/roslyn,pdelvo/roslyn,paulvanbrenk/roslyn,bkoelman/roslyn,robinsedlaczek/roslyn,OmarTawfik/roslyn,abock/roslyn,OmarTawfik/roslyn,VSadov/roslyn,tannergooding/roslyn,xasx/roslyn,stephentoub/roslyn,khyperia/roslyn,eriawan/roslyn,physhi/roslyn,paulvanbrenk/roslyn,MattWindsor91/roslyn,khyperia/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,kelltrick/roslyn,orthoxerox/roslyn,cston/roslyn,tvand7093/roslyn,xasx/roslyn,stephentoub/roslyn,VSadov/roslyn,MichalStrehovsky/roslyn,weltkante/roslyn,heejaechang/roslyn,AnthonyDGreen/roslyn,kelltrick/roslyn,mgoertz-msft/roslyn,srivatsn/roslyn,nguerrera/roslyn,mattscheffer/roslyn,tmat/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,gafter/roslyn,gafter/roslyn,brettfo/roslyn,OmarTawfik/roslyn,physhi/roslyn,dpoeschl/roslyn,orthoxerox/roslyn,DustinCampbell/roslyn,mmitche/roslyn,mattscheffer/roslyn,panopticoncentral/roslyn,genlu/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,sharwell/roslyn,bartdesmet/roslyn,mmitche/roslyn,aelij/roslyn,davkean/roslyn,bartdesmet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,brettfo/roslyn,MattWindsor91/roslyn,orthoxerox/roslyn,agocke/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,pdelvo/roslyn,khyperia/roslyn,mmitche/roslyn,jkotas/roslyn,aelij/roslyn,TyOverby/roslyn,swaroop-sridhar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jcouv/roslyn,DustinCampbell/roslyn,agocke/roslyn,KirillOsenkov/roslyn,abock/roslyn,MichalStrehovsky/roslyn,reaction1989/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,Hosch250/roslyn,MattWindsor91/roslyn
src/Workspaces/Core/Portable/SolutionCrawler/InvocationReasons.cs
src/Workspaces/Core/Portable/SolutionCrawler/InvocationReasons.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial struct InvocationReasons : IEnumerable<string> { public static readonly InvocationReasons Empty = new InvocationReasons(ImmutableHashSet<string>.Empty); private readonly ImmutableHashSet<string> _reasons; public InvocationReasons(string reason) : this(ImmutableHashSet.Create<string>(reason)) { } private InvocationReasons(ImmutableHashSet<string> reasons) { _reasons = reasons; } public bool Contains(string reason) { return _reasons.Contains(reason); } public InvocationReasons With(InvocationReasons invocationReasons) { return new InvocationReasons((_reasons ?? ImmutableHashSet<string>.Empty).Union(invocationReasons._reasons)); } public InvocationReasons With(string reason) { return new InvocationReasons((_reasons ?? ImmutableHashSet<string>.Empty).Add(reason)); } public bool IsEmpty { get { return _reasons == null || _reasons.Count == 0; } } public ImmutableHashSet<string>.Enumerator GetEnumerator() { return _reasons.GetEnumerator(); } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return _reasons.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _reasons.GetEnumerator(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial struct InvocationReasons : IEnumerable<string> { public static readonly InvocationReasons Empty = new InvocationReasons(ImmutableHashSet<string>.Empty); private readonly ImmutableHashSet<string> _reasons; public InvocationReasons(string reason) : this(ImmutableHashSet.Create<string>(reason)) { } private InvocationReasons(ImmutableHashSet<string> reasons) { _reasons = reasons; } public bool Contains(string reason) { return _reasons.Contains(reason); } public InvocationReasons With(InvocationReasons invocationReasons) { return new InvocationReasons((_reasons ?? ImmutableHashSet<string>.Empty).Union(invocationReasons._reasons)); } public InvocationReasons With(string reason) { return new InvocationReasons((_reasons ?? ImmutableHashSet<string>.Empty).Add(reason)); } public bool IsEmpty { get { return _reasons == null || _reasons.Count == 0; } } public IEnumerator<string> GetEnumerator() { return _reasons.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
mit
C#
e9ba32b596ea7bd6451eaa0d0250b804f28d06d2
Replace dispose method with destructor
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade.Test/Core/ArkadeProcessingAreaTest.cs
src/Arkivverket.Arkade.Test/Core/ArkadeProcessingAreaTest.cs
using System; using System.IO; using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Util; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.Test.Core { public class ArkadeProcessingAreaTest { private readonly string _locationPath; private readonly DirectoryInfo _location; public ArkadeProcessingAreaTest() { _locationPath = Path.Combine(Environment.CurrentDirectory, "TestData", "ProcessingAreaTests"); _location = new DirectoryInfo(_locationPath); _location.Create(); } [Fact] public void ProcessingAreaIsEstablished() { ArkadeProcessingArea.Establish(_locationPath); ArkadeProcessingArea.Location.FullName.Should().Be(_locationPath); ArkadeProcessingArea.RootDirectory.FullName.Should().Be(_locationPath + "\\Arkade"); ArkadeProcessingArea.WorkDirectory.FullName.Should().Be(_locationPath + "\\Arkade\\work"); ArkadeProcessingArea.LogsDirectory.FullName.Should().Be(_locationPath + "\\Arkade\\logs"); } [Fact (Skip="Failing on buildserver ...")] public void ProcessingAreaIsEstablishedWithInvalidLocation() { string nonExistingLocation = Path.Combine(Environment.CurrentDirectory, "TestData", "NonExistingDirectory"); ArkadeProcessingArea.Establish(nonExistingLocation); ProcessingAreaIsSetupWithTemporaryLogsDirectoryOnly(); } [Fact (Skip = "Failing on buildserver ...")] public void ProcessingAreaIsEstablishedWithMissingLocation() { ArkadeProcessingArea.Establish(""); ProcessingAreaIsSetupWithTemporaryLogsDirectoryOnly(); } private static void ProcessingAreaIsSetupWithTemporaryLogsDirectoryOnly() { string temporaryLogsDirectoryPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ArkadeConstants.DirectoryNameTemporaryLogsLocation ); ArkadeProcessingArea.LogsDirectory.FullName.Should().Be(temporaryLogsDirectoryPath); ArkadeProcessingArea.Location.Should().BeNull(); ArkadeProcessingArea.RootDirectory.Should().BeNull(); ArkadeProcessingArea.WorkDirectory.Should().BeNull(); } ~ArkadeProcessingAreaTest() { _location.Delete(true); } } }
using System; using System.IO; using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Util; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.Test.Core { public class ArkadeProcessingAreaTest : IDisposable { private readonly string _locationPath; private readonly DirectoryInfo _location; public ArkadeProcessingAreaTest() { _locationPath = Path.Combine(Environment.CurrentDirectory, "TestData", "ProcessingAreaTests"); _location = new DirectoryInfo(_locationPath); _location.Create(); } [Fact] public void ProcessingAreaIsEstablished() { ArkadeProcessingArea.Establish(_locationPath); ArkadeProcessingArea.Location.FullName.Should().Be(_locationPath); ArkadeProcessingArea.RootDirectory.FullName.Should().Be(_locationPath + "\\Arkade"); ArkadeProcessingArea.WorkDirectory.FullName.Should().Be(_locationPath + "\\Arkade\\work"); ArkadeProcessingArea.LogsDirectory.FullName.Should().Be(_locationPath + "\\Arkade\\logs"); } [Fact (Skip="Failing on buildserver ...")] public void ProcessingAreaIsEstablishedWithInvalidLocation() { string nonExistingLocation = Path.Combine(Environment.CurrentDirectory, "TestData", "NonExistingDirectory"); ArkadeProcessingArea.Establish(nonExistingLocation); ProcessingAreaIsSetupWithTemporaryLogsDirectoryOnly(); } [Fact (Skip = "Failing on buildserver ...")] public void ProcessingAreaIsEstablishedWithMissingLocation() { ArkadeProcessingArea.Establish(""); ProcessingAreaIsSetupWithTemporaryLogsDirectoryOnly(); } private static void ProcessingAreaIsSetupWithTemporaryLogsDirectoryOnly() { string temporaryLogsDirectoryPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ArkadeConstants.DirectoryNameTemporaryLogsLocation ); ArkadeProcessingArea.LogsDirectory.FullName.Should().Be(temporaryLogsDirectoryPath); ArkadeProcessingArea.Location.Should().BeNull(); ArkadeProcessingArea.RootDirectory.Should().BeNull(); ArkadeProcessingArea.WorkDirectory.Should().BeNull(); } public void Dispose() { _location.Delete(true); } } }
agpl-3.0
C#
f974897dec2f4f8efe0017034680953b02238e92
Add authentication type to AuthenticateResponse (#5116)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/XPack/Security/Authenticate/AuthenticateResponse.cs
src/Nest/XPack/Security/Authenticate/AuthenticateResponse.cs
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Collections.Generic; using System.Runtime.Serialization; namespace Nest { public class RealmInfo { [DataMember(Name = "name")] public string Name { get; internal set; } [DataMember(Name = "type")] public string Type { get; internal set; } } public class AuthenticateResponse : ResponseBase { [DataMember(Name = "email")] public string Email { get; internal set; } [DataMember(Name = "full_name")] public string FullName { get; internal set; } [DataMember(Name = "metadata")] public IReadOnlyDictionary<string, object> Metadata { get; internal set; } = EmptyReadOnly<string, object>.Dictionary; [DataMember(Name = "roles")] public IReadOnlyCollection<string> Roles { get; internal set; } = EmptyReadOnly<string>.Collection; [DataMember(Name = "username")] public string Username { get; internal set; } [DataMember(Name = "authentication_realm")] public RealmInfo AuthenticationRealm { get; internal set; } [DataMember(Name = "lookup_realm")] public RealmInfo LookupRealm { get; internal set; } [DataMember(Name = "authentication_type")] public string AuthenticationType { get; internal set; } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Collections.Generic; using System.Runtime.Serialization; namespace Nest { public class RealmInfo { [DataMember(Name = "name")] public string Name { get; internal set; } [DataMember(Name = "type")] public string Type { get; internal set; } } public class AuthenticateResponse : ResponseBase { [DataMember(Name = "email")] public string Email { get; internal set; } [DataMember(Name = "full_name")] public string FullName { get; internal set; } [DataMember(Name = "metadata")] public IReadOnlyDictionary<string, object> Metadata { get; internal set; } = EmptyReadOnly<string, object>.Dictionary; [DataMember(Name = "roles")] public IReadOnlyCollection<string> Roles { get; internal set; } = EmptyReadOnly<string>.Collection; [DataMember(Name = "username")] public string Username { get; internal set; } [DataMember(Name = "authentication_realm")] public RealmInfo AuthenticationRealm { get; internal set; } [DataMember(Name = "lookup_realm")] public RealmInfo LookupRealm { get; internal set; } } }
apache-2.0
C#
3ae4af53ff809aa905e3e3078e1203aeb3496c4b
Fix typo
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/IWQController.cs
Battery-Commander.Web/Controllers/IWQController.cs
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using BatteryCommander.Web.Services; namespace BatteryCommander.Web.Controllers { [Authorize] public class IWQController : Controller { private readonly Database db; public IWQController(Database db) { this.db = db; } // List status for all soldiers by - filter by unit // Bulk update qual status/date public async Task<IActionResult> Index(SoldierSearchService.Query query) { var soldiers = await SoldierSearchService.Filter(db, query); return View("List", soldiers); } [HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> Save(IEnumerable<DTO> model) { // For each DTO posted, update the soldier info foreach (var dto in model) { var soldier = await db .Soldiers .Where(_ => _.Id == dto.SoldierId) .SingleOrDefaultAsync(); // Update IWQ info } await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } public class DTO { public Soldier Soldier { get; set; } public int SoldierId { get; set; } [DataType(DataType.Date)] public DateTime? QualificationDate { get; set; } } } }
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using BatteryCommander.Web.Services; namespace BatteryCommander.Web.Controllers { [Authorize] public class IWQController : Controller { private readonly Database db; public IWQController(Database db) { this.db = db; } // List status for all soldiers by - filter by unit // Bulk update qual status/date public async Task<IActionResult> Index(SoldierSearchService.Query query) { var soldiers = await SoldierSearchService.Find(db, query); return View("List", soldiers); } [HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> Save(IEnumerable<DTO> model) { // For each DTO posted, update the soldier info foreach (var dto in model) { var soldier = await db .Soldiers .Where(_ => _.Id == dto.SoldierId) .SingleOrDefaultAsync(); // Update IWQ info } await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } public class DTO { public Soldier Soldier { get; set; } public int SoldierId { get; set; } [DataType(DataType.Date)] public DateTime? QualificationDate { get; set; } } } }
mit
C#
d3ec8b11b7b4103513378032b12b919286e4b4ed
Update Import.cshtml
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Views/Soldiers/Import.cshtml
Battery-Commander.Web/Views/Soldiers/Import.cshtml
<form method="post" enctype="multipart/form-data" asp-controller="Soldiers" asp-action="Import"> @Html.AntiForgeryToken() @Html.Hidden("unitId", (int)ViewBag.UnitId) <div class="form-group"> <div class="col-md-10"> <p> In DTMS, go to Reporting -> Soldier -> Soldier Roster. Go to "Column Selection" and "Select All". Click "Excel Export". </p> <p>Upload the DTMS Soldier Roster Report here (Must be XLSX Format!):</p> <input type="file" name="file" /> </div> </div> <div class="form-group"> <div class="col-md-10"> <input type="submit" value="Upload" /> </div> </div> </form>
<form method="post" enctype="multipart/form-data" asp-controller="Soldiers" asp-action="Import"> @Html.AntiForgeryToken() @Html.Hidden("unitId", ViewBag.UnitId) <div class="form-group"> <div class="col-md-10"> <p> In DTMS, go to Reporting -> Soldier -> Soldier Roster. Go to "Column Selection" and "Select All". Click "Excel Export". </p> <p>Upload the DTMS Soldier Roster Report here (Must be XLSX Format!):</p> <input type="file" name="file" /> </div> </div> <div class="form-group"> <div class="col-md-10"> <input type="submit" value="Upload" /> </div> </div> </form>
mit
C#
eb187482ee4c5afd57eb6ffe3f990b9c351f6b38
Update IApplicationDbContext
ivantomchev/ImdbLiteSE,ivantomchev/ImdbLiteSE,ivantomchev/ImdbLiteSE
Source/Data/ImdbLite.Data/IApplicationDbContext.cs
Source/Data/ImdbLite.Data/IApplicationDbContext.cs
namespace ImdbLite.Data { using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using ImdbLite.Data.Models; public interface IApplicationDbContext { IDbSet<Celebrity> Celebrities { get; set; } IDbSet<Movie> Movies { get; set; } IDbSet<Genre> Genres { get; set; } IDbSet<Character> Characters { get; set; } IDbSet<CastMember> CastMembers { get; set; } IDbSet<CelebrityMainPhoto> CelebrityMainPhotos { get; set; } int SaveChanges(); void Dispose(); DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class; IDbSet<T> Set<T>() where T : class; } }
namespace ImdbLite.Data { using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using ImdbLite.Data.Models; public interface IApplicationDbContext { int SaveChanges(); void Dispose(); DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class; IDbSet<T> Set<T>() where T : class; } }
mit
C#
38540a639895feab4d8868ee46d9f0c7608ee0b7
update empty template
IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates
src/IdentityServer4Empty/Startup.cs
src/IdentityServer4Empty/Startup.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace IdentityServer4Empty { public class Startup { public IWebHostEnvironment Environment { get; } public Startup(IWebHostEnvironment environment) { Environment = environment; } public void ConfigureServices(IServiceCollection services) { // uncomment, if you want to add an MVC-based UI //services.AddControllersWithViews(); var builder = services.AddIdentityServer() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(Config.GetApis()) .AddInMemoryClients(Config.GetClients()); // not recommended for production - you need to store your key material somewhere secure builder.AddDeveloperSigningCredential(); } public void Configure(IApplicationBuilder app) { if (Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // uncomment if you want to support MVC //app.UseStaticFiles(); //app.UseRouting(); app.UseIdentityServer(); // uncomment, if you want to add MVC-based //app.UseAuthorization(); //app.UseEndpoints(endpoints => //{ // endpoints.MapDefaultControllerRoute(); //}); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace IdentityServer4Empty { public class Startup { public IWebHostEnvironment Environment { get; } public Startup(IWebHostEnvironment environment) { Environment = environment; } public void ConfigureServices(IServiceCollection services) { // uncomment, if you want to add an MVC-based UI //services.AddControllersWithViews(); var builder = services.AddIdentityServer() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(Config.GetApis()) .AddInMemoryClients(Config.GetClients()); // not recommended for production - you need to store your key material somewhere secure builder.AddDeveloperSigningCredential(); } public void Configure(IApplicationBuilder app) { if (Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // uncomment if you want to support static files //app.UseStaticFiles(); app.UseIdentityServer(); // uncomment, if you want to add an MVC-based UI //app.UseEndpoints(endpoints => //{ // endpoints.MapDefaultControllerRoute(); //}); } } }
apache-2.0
C#
0ca72d245472866f80a509bfa59277213b7d2cec
fix param ordering
SixLabors/Fonts
src/SixLabors.Fonts/TextRenderer.cs
src/SixLabors.Fonts/TextRenderer.cs
using SixLabors.Primitives; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Numerics; using System.Threading.Tasks; namespace SixLabors.Fonts { /// <summary> /// Encapulated logic for laying out and then rendering text to a <see cref="IGlyphRenderer"/> surface. /// </summary> public class TextRenderer { private TextLayout layoutEngine; private IGlyphRenderer renderer; internal TextRenderer(IGlyphRenderer renderer, TextLayout layoutEngine) { this.layoutEngine = layoutEngine; this.renderer = renderer; } /// <summary> /// Initializes a new instance of the <see cref="TextRenderer"/> class. /// </summary> /// <param name="renderer">The renderer.</param> public TextRenderer(IGlyphRenderer renderer) : this(renderer, TextLayout.Default) { } /// <summary> /// Renders the text to the <paramref name="renderer"/>. /// </summary> /// <param name="renderer">The target renderer.</param> /// <param name="text">The text.</param> /// <param name="options">The style.</param> public static void RenderTextTo(IGlyphRenderer renderer, string text, RendererOptions options) { new TextRenderer(renderer).RenderText(text, options); } /// <summary> /// Renders the text. /// </summary> /// <param name="text">The text.</param> /// <param name="options">The style.</param> public void RenderText(string text, RendererOptions options) { ImmutableArray<GlyphLayout> glyphsToRender = this.layoutEngine.GenerateLayout(text, options); var dpi = new Vector2(options.DpiX, options.DpiY); RectangleF rect = TextMeasurer.GetBounds(glyphsToRender, dpi); this.renderer.BeginText(rect); foreach (GlyphLayout g in glyphsToRender.Where(x => x.Glyph.HasValue)) { g.Glyph.Value.RenderTo(this.renderer, g.Location, options.DpiX, options.DpiY, g.LineHeight); } this.renderer.EndText(); } } }
using SixLabors.Primitives; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Numerics; using System.Threading.Tasks; namespace SixLabors.Fonts { /// <summary> /// Encapulated logic for laying out and then rendering text to a <see cref="IGlyphRenderer"/> surface. /// </summary> public class TextRenderer { private TextLayout layoutEngine; private IGlyphRenderer renderer; internal TextRenderer(IGlyphRenderer renderer, TextLayout layoutEngine) { this.layoutEngine = layoutEngine; this.renderer = renderer; } /// <summary> /// Initializes a new instance of the <see cref="TextRenderer"/> class. /// </summary> /// <param name="renderer">The renderer.</param> public TextRenderer(IGlyphRenderer renderer) : this(renderer, TextLayout.Default) { } /// <summary> /// Renders the text to the <paramref name="renderer"/>. /// </summary> /// <param name="text">The text.</param> /// <param name="options">The style.</param> /// <param name="renderer">The target renderer.</param> public static void RenderTextTo(string text, RendererOptions options, IGlyphRenderer renderer) { new TextRenderer(renderer).RenderText(text, options); } /// <summary> /// Renders the text. /// </summary> /// <param name="text">The text.</param> /// <param name="options">The style.</param> public void RenderText(string text, RendererOptions options) { ImmutableArray<GlyphLayout> glyphsToRender = this.layoutEngine.GenerateLayout(text, options); var dpi = new Vector2(options.DpiX, options.DpiY); RectangleF rect = TextMeasurer.GetBounds(glyphsToRender, dpi); this.renderer.BeginText(rect); foreach (GlyphLayout g in glyphsToRender.Where(x => x.Glyph.HasValue)) { g.Glyph.Value.RenderTo(this.renderer, g.Location, options.DpiX, options.DpiY, g.LineHeight); } this.renderer.EndText(); } } }
apache-2.0
C#
4380c6878bb2cf2fcc17f043c8a5951fd1824cb5
Change some clock widget settings names
danielchalmers/DesktopWidgets
DesktopWidgets/WidgetBase/Settings/WidgetClockSettingsBase.cs
DesktopWidgets/WidgetBase/Settings/WidgetClockSettingsBase.cs
using System; using System.Collections.Generic; using System.ComponentModel; namespace DesktopWidgets.WidgetBase.Settings { public class WidgetClockSettingsBase : WidgetSettingsBase { protected WidgetClockSettingsBase() { Style.FontSettings.FontSize = 24; } [Category("General")] [DisplayName("Update Interval")] public int UpdateInterval { get; set; } = -1; [Category("Style")] [DisplayName("Date/Time Format")] public List<string> DateTimeFormat { get; set; } = new List<string> {"{hh}:{mm} {tt}"}; [Category("General")] [DisplayName("Date/Time Offset")] public TimeSpan TimeOffset { get; set; } [Category("Behavior")] [DisplayName("Copy Text On Double Click")] public bool CopyTextOnDoubleClick { get; set; } = true; } }
using System; using System.Collections.Generic; using System.ComponentModel; namespace DesktopWidgets.WidgetBase.Settings { public class WidgetClockSettingsBase : WidgetSettingsBase { protected WidgetClockSettingsBase() { Style.FontSettings.FontSize = 24; } [Category("General")] [DisplayName("Refresh Interval")] public int UpdateInterval { get; set; } = -1; [Category("Style")] [DisplayName("Time Format")] public List<string> DateTimeFormat { get; set; } = new List<string> {"{hh}:{mm} {tt}"}; [Category("General")] [DisplayName("Time Offset")] public TimeSpan TimeOffset { get; set; } [Category("Behavior")] [DisplayName("Copy Time On Double Click")] public bool CopyTextOnDoubleClick { get; set; } = true; } }
apache-2.0
C#
091f9a937db24340483c842d8da49dae070f575e
Fix AddIfNullOrEmpty method
svedm/monodevelop-hg-addin
MonoDevelop.VersionControl.Mercurial/Hg.Net/ArgumentHelper.cs
MonoDevelop.VersionControl.Mercurial/Hg.Net/ArgumentHelper.cs
using System; using System.Collections.Generic; using System.Linq; namespace Hg.Net { public class ArgumentHelper { private readonly List<string> _argumentsList; public ArgumentHelper () { _argumentsList = new List<string>(); } public void AddIf(bool condition, params string[] arguments) { if (condition) { _argumentsList.AddRange(arguments); } } public void AddIfNotNullOrEmpty(bool throwExceptonIfFalse, params string[] arguments) { if (arguments.Any(x => string.IsNullOrEmpty(x))) { if (throwExceptonIfFalse) { throw new ArgumentException("can not be bull or empty", arguments.First(x => string.IsNullOrEmpty(x))); } return; } _argumentsList.AddRange(arguments); } public void Add(params string[] argumets) { _argumentsList.AddRange(argumets); } public List<string> GetList() { return _argumentsList; } public override string ToString() { return string.Join(" ", _argumentsList); } } }
using System; using System.Collections.Generic; namespace Hg.Net { public class ArgumentHelper { private readonly List<string> _argumentsList; public ArgumentHelper () { _argumentsList = new List<string>(); } public void AddIf(bool condition, params string[] arguments) { if (condition) { _argumentsList.AddRange(arguments); } } public void AddIfNotNullOrEmpty(bool throwExceptonIfFalse, params string[] arguments) { foreach (var argument in arguments) { if (!string.IsNullOrEmpty(argument)) { _argumentsList.Add(argument); } else if (throwExceptonIfFalse) { throw new ArgumentException("can not be bull or empty", argument); } } } public void Add(params string[] argumets) { _argumentsList.AddRange(argumets); } public List<string> GetList() { return _argumentsList; } public override string ToString() { return string.Concat(_argumentsList, ' '); } } }
mit
C#
1e6e0c4d98ff443f0d52e75f684f4dcf1c76035f
Update validation rules in Stylet.Samples.ModelValidation
cH40z-Lord/Stylet,canton7/Stylet,canton7/Stylet,cH40z-Lord/Stylet
Samples/Stylet.Samples.ModelValidation/Pages/UserViewModel.cs
Samples/Stylet.Samples.ModelValidation/Pages/UserViewModel.cs
using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.ModelValidation.Pages { public class UserViewModel : Screen { public string UserName { get; set; } public string Email { get; set; } public string Password { get; set; } public string PasswordConfirmation { get; set; } public Stringable<int> Age { get; set; } public bool AutoValidate { get { return this.autoValidate; } set { this.autoValidate = value; this.NotifyOfPropertyChange(); } } public UserViewModel(IModelValidator<UserViewModel> validator) : base(validator) { } protected override void OnValidationStateChanged(IEnumerable<string> changedProperties) { base.OnValidationStateChanged(changedProperties); // Fody can't weave other assemblies, so we have to manually raise this this.NotifyOfPropertyChange(() => this.CanSubmit); } public bool CanSubmit { get { return !this.AutoValidate || !this.HasErrors; } } public void Submit() { if (this.Validate()) System.Windows.MessageBox.Show("Successfully submitted"); } } public class UserViewModelValidator : AbstractValidator<UserViewModel> { public UserViewModelValidator() { RuleFor(x => x.UserName).NotEmpty().Length(1, 20); RuleFor(x => x.Email).NotEmpty().EmailAddress(); RuleFor(x => x.Password).NotEmpty().Matches("[0-9]").WithMessage("{PropertyName} must contain a number"); RuleFor(x => x.PasswordConfirmation).Equal(s => s.Password).WithMessage("{PropertyName} should match Password"); RuleFor(x => x.Age).Must(x => x != null && x.IsValid).WithMessage("{PropertyName} must be a valid number"); When(x => x.Age != null && x.Age.IsValid, () => { RuleFor(x => x.Age.Value).GreaterThan(0).WithName("Age"); }); } } }
using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.ModelValidation.Pages { public class UserViewModel : Screen { public string UserName { get; set; } public string Email { get; set; } public string Password { get; set; } public string PasswordConfirmation { get; set; } public Stringable<int> Age { get; set; } public bool AutoValidate { get { return this.autoValidate; } set { this.autoValidate = value; this.NotifyOfPropertyChange(); } } public UserViewModel(IModelValidator<UserViewModel> validator) : base(validator) { } protected override void OnValidationStateChanged(IEnumerable<string> changedProperties) { base.OnValidationStateChanged(changedProperties); // Fody can't weave other assemblies, so we have to manually raise this this.NotifyOfPropertyChange(() => this.CanSubmit); } public bool CanSubmit { get { return !this.AutoValidate || !this.HasErrors; } } public void Submit() { if (this.Validate()) System.Windows.MessageBox.Show("Successfully submitted"); } } public class UserViewModelValidator : AbstractValidator<UserViewModel> { public UserViewModelValidator() { RuleFor(x => x.UserName).NotEmpty().Length(1, 20); RuleFor(x => x.Email).NotEmpty().EmailAddress(); RuleFor(x => x.Password).NotEmpty().Matches("[0-9]").WithMessage("{PropertyName} must contain a number"); RuleFor(x => x.PasswordConfirmation).Equal(s => s.Password).WithMessage("{PropertyName} should match Password"); RuleFor(x => x.Age).Must(x => x.IsValid).WithMessage("{PropertyName} must be a valid number"); When(x => x.Age.IsValid, () => { RuleFor(x => x.Age.Value).GreaterThan(0).WithName("Age"); }); } } }
mit
C#
6b2863b8735591cc7c427c3aac4c33fd5abb2610
Switch to v1.0.2
Abc-Arbitrage/Zebus.Persistence,Abc-Arbitrage/Zebus
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.0.2")] [assembly: AssemblyFileVersion("1.0.2")] [assembly: AssemblyInformationalVersion("1.0.2")]
using System.Reflection; [assembly: AssemblyVersion("1.0.1")] [assembly: AssemblyFileVersion("1.0.1")] [assembly: AssemblyInformationalVersion("1.0.1")]
mit
C#
7ad713c33b8d44382e73517b82b87f1579f834b6
Set default timeout to 100 seconds
ivandrofly/octokit.net,editor-tools/octokit.net,thedillonb/octokit.net,nsnnnnrn/octokit.net,Red-Folder/octokit.net,octokit-net-test-org/octokit.net,chunkychode/octokit.net,SamTheDev/octokit.net,gabrielweyer/octokit.net,editor-tools/octokit.net,octokit-net-test/octokit.net,Sarmad93/octokit.net,fffej/octokit.net,khellang/octokit.net,SLdragon1989/octokit.net,cH40z-Lord/octokit.net,ChrisMissal/octokit.net,shana/octokit.net,gabrielweyer/octokit.net,octokit/octokit.net,eriawan/octokit.net,kolbasov/octokit.net,SamTheDev/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,devkhan/octokit.net,dampir/octokit.net,alfhenrik/octokit.net,geek0r/octokit.net,hitesh97/octokit.net,thedillonb/octokit.net,mminns/octokit.net,nsrnnnnn/octokit.net,shiftkey-tester/octokit.net,dlsteuer/octokit.net,rlugojr/octokit.net,daukantas/octokit.net,SmithAndr/octokit.net,TattsGroup/octokit.net,gdziadkiewicz/octokit.net,hahmed/octokit.net,ivandrofly/octokit.net,octokit/octokit.net,chunkychode/octokit.net,shiftkey/octokit.net,forki/octokit.net,shana/octokit.net,gdziadkiewicz/octokit.net,yonglehou/octokit.net,dampir/octokit.net,darrelmiller/octokit.net,devkhan/octokit.net,rlugojr/octokit.net,shiftkey-tester/octokit.net,M-Zuber/octokit.net,shiftkey/octokit.net,M-Zuber/octokit.net,SmithAndr/octokit.net,magoswiat/octokit.net,brramos/octokit.net,octokit-net-test-org/octokit.net,bslliw/octokit.net,fake-organization/octokit.net,michaKFromParis/octokit.net,hahmed/octokit.net,yonglehou/octokit.net,alfhenrik/octokit.net,naveensrinivasan/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,takumikub/octokit.net,Sarmad93/octokit.net,eriawan/octokit.net,kdolan/octokit.net,mminns/octokit.net,adamralph/octokit.net,TattsGroup/octokit.net,khellang/octokit.net
Octokit/Http/Request.cs
Octokit/Http/Request.cs
using System; using System.Collections.Generic; using System.Net.Http; namespace Octokit.Internal { public class Request : IRequest { public Request() { Headers = new Dictionary<string, string>(); Parameters = new Dictionary<string, string>(); AllowAutoRedirect = true; Timeout = TimeSpan.FromSeconds(100); } public object Body { get; set; } public Dictionary<string, string> Headers { get; private set; } public HttpMethod Method { get; set; } public Dictionary<string, string> Parameters { get; private set; } public Uri BaseAddress { get; set; } public Uri Endpoint { get; set; } public TimeSpan Timeout { get; set; } public string ContentType { get; set; } public bool AllowAutoRedirect { get; set; } } }
using System; using System.Collections.Generic; using System.Net.Http; namespace Octokit.Internal { public class Request : IRequest { public Request() { Headers = new Dictionary<string, string>(); Parameters = new Dictionary<string, string>(); AllowAutoRedirect = true; } public object Body { get; set; } public Dictionary<string, string> Headers { get; private set; } public HttpMethod Method { get; set; } public Dictionary<string, string> Parameters { get; private set; } public Uri BaseAddress { get; set; } public Uri Endpoint { get; set; } public TimeSpan Timeout { get; set; } public string ContentType { get; set; } public bool AllowAutoRedirect { get; set; } } }
mit
C#
1c66f2fdaa23ace5bd2ce37cac195858f43d8465
Sort the i18n keys by descending length Fix 'FullHP' getting overridden by 'Full'.
MeltWS/proshine,bobus15/proshine,Silv3rPRO/proshine
PROProtocol/Language.cs
PROProtocol/Language.cs
using System; using System.Collections.Generic; using System.IO; using System.Xml; namespace PROProtocol { public class Language { private class DescendingLengthComparer : IComparer<string> { public int Compare(string x, string y) { int result = y.Length.CompareTo(x.Length); return result != 0 ? result : x.CompareTo(y); } } private const string FileName = "Resources/Lang.xml"; private SortedDictionary<string, string> _texts = new SortedDictionary<string, string>(); public Language() { _texts = new SortedDictionary<string, string>(new DescendingLengthComparer()); if (File.Exists(FileName)) { XmlDocument xml = new XmlDocument(); xml.Load(FileName); LoadXmlDocument(xml); } } private void LoadXmlDocument(XmlDocument xml) { XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0]; if (languageNode != null) { foreach (XmlElement textNode in languageNode) { _texts.Add(textNode.GetAttribute("name"), textNode.InnerText); } } } public string GetText(string name) { return _texts[name]; } public string Replace(string originalText) { if (originalText.IndexOf('$') != -1) { foreach (var text in _texts) { originalText = originalText.Replace("$" + text.Key, text.Value); } } return originalText; } } }
using System.Collections.Generic; using System.IO; using System.Xml; namespace PROProtocol { public class Language { private const string FileName = "Resources/Lang.xml"; private Dictionary<string, string> _texts = new Dictionary<string, string>(); public Language() { if (File.Exists(FileName)) { XmlDocument xml = new XmlDocument(); xml.Load(FileName); LoadXmlDocument(xml); } } private void LoadXmlDocument(XmlDocument xml) { XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0]; if (languageNode != null) { foreach (XmlElement textNode in languageNode) { _texts.Add(textNode.GetAttribute("name"), textNode.InnerText); } } } public string GetText(string name) { return _texts[name]; } public string Replace(string originalText) { if (originalText.IndexOf('$') != -1) { foreach (var text in _texts) { originalText = originalText.Replace("$" + text.Key, text.Value); } } return originalText; } } }
mit
C#
6a1c2a487bdaf8b7603a5226e82df32340432cef
fix compilation
RubiusGroup/Realmius
RealmIos/AppDelegate.cs
RealmIos/AppDelegate.cs
using Foundation; using Realms; using RealmSync; using RealmSync.Model; using RealmSync.SyncService; using UIKit; namespace RealmIos { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register("AppDelegate")] public class AppDelegate : UIApplicationDelegate { // class-level declarations public static IRealmSyncService RealmSync; public static Realm Realm; public override UIWindow Window { get; set; } public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method var config = new RealmConfiguration() { SchemaVersion = 3, MigrationCallback = (migration, oldSchemaVersion) => { }, }; Realm = Realm.GetInstance(config); //RealmSync = SyncServiceFactory.CreateUsingPolling(()=>Realm.GetInstance(config), new System.Uri("http://192.168.38.1:44980/realmupload") // , new System.Uri("http://192.168.38.1:44980/realmdownload") // , typeof(ChatMessage)); RealmSync = SyncServiceFactory.CreateUsingSignalR(() => Realm.GetInstance(config), new System.Uri("http://192.168.38.1:44980/signalr"), Constants.SignalRHubName , typeof(ChatMessage)); return true; } public override void OnResignActivation(UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) // or when the user quits the application and it begins the transition to the background state. // Games should use this method to pause the game. } public override void DidEnterBackground(UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } public override void WillEnterForeground(UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } public override void OnActivated(UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } public override void WillTerminate(UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } } }
using Foundation; using Realms; using RealmSync; using RealmSync.Model; using RealmSync.SyncService; using UIKit; namespace RealmIos { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register("AppDelegate")] public class AppDelegate : UIApplicationDelegate { // class-level declarations public static RealmSyncService RealmSync; public static Realm Realm; public override UIWindow Window { get; set; } public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method var config = new RealmConfiguration() { SchemaVersion = 2, }; Realm = Realm.GetInstance(config); //RealmSync = SyncServiceFactory.CreateUsingPolling(()=>Realm.GetInstance(config), new System.Uri("http://192.168.38.1:44980/realmupload") // , new System.Uri("http://192.168.38.1:44980/realmdownload") // , typeof(ChatMessage)); RealmSync = SyncServiceFactory.CreateUsingSignalR(() => Realm.GetInstance(config), new System.Uri("http://192.168.38.1:44980/signalr"), Constants.SignalRHubName , typeof(ChatMessage)); return true; } public override void OnResignActivation(UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) // or when the user quits the application and it begins the transition to the background state. // Games should use this method to pause the game. } public override void DidEnterBackground(UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } public override void WillEnterForeground(UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } public override void OnActivated(UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } public override void WillTerminate(UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } } }
apache-2.0
C#
a8528ac73c65bee69fe897cc79dbb7e3606b4ec3
Update CameraKeyboardController.cs
quill18/MostlyCivilizedHexEngine
Assets/CameraKeyboardController.cs
Assets/CameraKeyboardController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraKeyboardController : MonoBehaviour { // Use this for initialization void Start () { } float moveSpeed = 3.5f; // Update is called once per frame void Update () { Vector3 translate = new Vector3 ( Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical") ); this.transform.Translate( translate * moveSpeed * Time.deltaTime * (1 + this.transform.position.y / 2), Space.World); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraKeyboardController : MonoBehaviour { // Use this for initialization void Start () { } float moveSpeed = 25; // Update is called once per frame void Update () { Vector3 translate = new Vector3 ( Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical") ); this.transform.Translate( translate * moveSpeed * Time.deltaTime, Space.World); } }
mit
C#
6b978004523e7108ba8e680e679b5776c36cca45
Use physics for player movement
TheBeardFarm/Tethered
Assets/Scripts/PlayerController.cs
Assets/Scripts/PlayerController.cs
using System; using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] public class PlayerController : MonoBehaviour { private Animator _animator; private Rigidbody2D _rb2d; private float _horizontalSpeed = 5f; [SerializeField] private PlayerIdentity _identity; private void Start() { _rb2d = GetComponent<Rigidbody2D>(); _rb2d.drag = 1; } private void Update() { HandleInput(); } private void HandleInput() { bool leftKey = IsLeftButtonDown(); bool rightKey = IsRightButtonDown(); if (leftKey) { HandleInputLeft(); } if (rightKey) { HandleInputRight(); } if (!leftKey && !rightKey) { HandleInputNone(); } } private bool IsLeftButtonDown() { switch (_identity) { case PlayerIdentity.Red: return Input.GetKey("left"); case PlayerIdentity.Blue: return Input.GetKey("a"); } throw new NotSupportedException(); } private bool IsRightButtonDown() { switch (_identity) { case PlayerIdentity.Red: return Input.GetKey("right"); case PlayerIdentity.Blue: return Input.GetKey("d"); } throw new NotSupportedException(); } private void HandleInputLeft() { _rb2d.velocity = new Vector2(_horizontalSpeed, _rb2d.velocity.y); //transform.position += Vector3.left * _horizontalSpeed * Time.deltaTime; } private void HandleInputRight() { _rb2d.velocity = new Vector2(-_horizontalSpeed, _rb2d.velocity.y); //transform.position += Vector3.right * _horizontalSpeed * Time.deltaTime; private void HandleInputNone() { _rb2d.velocity = new Vector2(0, _rb2d.velocity.y); } }
using System; using UnityEngine; public class PlayerController : MonoBehaviour { private Animator _animator; private float _horizontalSpeed = 5f; [SerializeField] private PlayerIdentity _identity; private void Start() { } private void Update() { HandleInput(); } private void HandleInput() { bool leftKey = IsLeftButtonDown(); bool rightKey = IsRightButtonDown(); if (leftKey) { HandleInputLeft(); } if (rightKey) { HandleInputRight(); } } private bool IsLeftButtonDown() { switch (_identity) { case PlayerIdentity.Red: return Input.GetKey("left"); case PlayerIdentity.Blue: return Input.GetKey("a"); } throw new NotSupportedException(); } private bool IsRightButtonDown() { switch (_identity) { case PlayerIdentity.Red: return Input.GetKey("right"); case PlayerIdentity.Blue: return Input.GetKey("d"); } throw new NotSupportedException(); } private void HandleInputLeft() { transform.position += Vector3.left * _horizontalSpeed * Time.deltaTime; } private void HandleInputRight() { transform.position += Vector3.right * _horizontalSpeed * Time.deltaTime; } }
mit
C#
d3028bebdc2133b05b6344a00451d0544ef02f9c
Fix constants.
exKAZUu/Code2Xml,exKAZUu/Code2Xml,exKAZUu/Code2Xml,exKAZUu/Code2Xml
Code2Xml.Core/Code2XmlConstants.cs
Code2Xml.Core/Code2XmlConstants.cs
#region License // Copyright (C) 2011-2014 Kazunori Sakamoto // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace Code2Xml.Core { public class Code2XmlConstants { public const string SyntaxTreeCacheExtension = ".cached_xml"; public const string LearningCacheExtension = ".learning_cache5"; public const string DependenciesDirectoryName = "Dependencies"; public const string EofTokenName = "EOF"; public const string EofRuleId = "EOF"; public const string DefaultRuleId = ""; public const string DefaultHiddenRuleId = "-1"; public const string StartLineName = "startline"; public const string StartPositionName = "startpos"; public const string EndLineName = "endline"; // Inclusive public const string EndPositionName = "endpos"; // Inclusive public const string HiddenAttributeName = "hidden"; public const string IdAttributeName = "id"; public const string TokenElementName = "TOKEN"; public const string HiddenElementName = "HIDDEN"; public const string TokenSetElementName = "TOKENS"; } }
#region License // Copyright (C) 2011-2014 Kazunori Sakamoto // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace Code2Xml.Core { public class Code2XmlConstants { public const string SyntaxTreeCacheExtension = ".cached_xml"; public const string LearningCacheExtension = ".learning_cache4"; public const string DependenciesDirectoryName = "Dependencies"; public const string EofTokenName = "EOF"; public const string EofRuleId = "EOF"; public const string DefaultRuleId = ""; public const string DefaultHiddenRuleId = "-1"; public const string StartLineName = "startline"; public const string StartPositionName = "startpos"; public const string EndLineName = "endline"; // Inclusive public const string EndPositionName = "endpos"; // Inclusive public const string HiddenAttributeName = "hidden"; public const string IdAttributeName = "id"; public const string TokenElementName = "TOKEN"; public const string HiddenElementName = "HIDDEN"; public const string TokenSetElementName = "TOKENS"; } }
apache-2.0
C#
d199707fe1824f4a99f6f4048d01681c1f236af7
Make NetworkInit public
CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos
source/Cosmos.HAL2/Network/NetworkInit.cs
source/Cosmos.HAL2/Network/NetworkInit.cs
using System; using System.Collections.Generic; using System.Text; using Cosmos.HAL.Drivers.PCI.Network; namespace Cosmos.HAL.Network { public class NetworkInit { public static void Init() { int NetworkDeviceID = 0; Console.WriteLine("Searching for Ethernet Controllers..."); foreach (PCIDevice device in PCI.Devices) { if ((device.ClassCode == 0x02) && (device.Subclass == 0x00) && // is Ethernet Controller device == PCI.GetDevice(device.bus, device.slot, device.function)) { Console.WriteLine("Found " + PCIDevice.DeviceClass.GetDeviceString(device) + " on PCI " + device.bus + ":" + device.slot + ":" + device.function); #region PCNETII if (device.VendorID == (ushort)VendorID.AMD && device.DeviceID == (ushort)DeviceID.PCNETII) { Console.WriteLine("NIC IRQ: " + device.InterruptLine); var AMDPCNetIIDevice = new AMDPCNetII(device); AMDPCNetIIDevice.NameID = ("eth" + NetworkDeviceID); Console.WriteLine("Registered at " + AMDPCNetIIDevice.NameID + " (" + AMDPCNetIIDevice.MACAddress.ToString() + ")"); AMDPCNetIIDevice.Enable(); NetworkDeviceID++; } #endregion } } if (NetworkDevice.Devices.Count == 0) { Console.WriteLine("No supported network card found!!"); } else { Console.WriteLine("Network initialization done!"); } } } }
using System; using System.Collections.Generic; using System.Text; using Cosmos.HAL.Drivers.PCI.Network; namespace Cosmos.HAL.Network { class NetworkInit { public static void Init() { int NetworkDeviceID = 0; Console.WriteLine("Searching for Ethernet Controllers..."); foreach (PCIDevice device in PCI.Devices) { if ((device.ClassCode == 0x02) && (device.Subclass == 0x00) && // is Ethernet Controller device == PCI.GetDevice(device.bus, device.slot, device.function)) { Console.WriteLine("Found " + PCIDevice.DeviceClass.GetDeviceString(device) + " on PCI " + device.bus + ":" + device.slot + ":" + device.function); #region PCNETII if (device.VendorID == (ushort)VendorID.AMD && device.DeviceID == (ushort)DeviceID.PCNETII) { Console.WriteLine("NIC IRQ: " + device.InterruptLine); var AMDPCNetIIDevice = new AMDPCNetII(device); AMDPCNetIIDevice.NameID = ("eth" + NetworkDeviceID); Console.WriteLine("Registered at " + AMDPCNetIIDevice.NameID + " (" + AMDPCNetIIDevice.MACAddress.ToString() + ")"); AMDPCNetIIDevice.Enable(); NetworkDeviceID++; } #endregion } } if (NetworkDevice.Devices.Count == 0) { Console.WriteLine("No supported network card found!!"); } else { Console.WriteLine("Network initialization done!"); } } } }
bsd-3-clause
C#
7f09f87df4d42b982bf2e42e4f831d89778ad558
use NRT
diryboy/roslyn,diryboy/roslyn,mavasani/roslyn,eriawan/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,diryboy/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,KevinRansom/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,mavasani/roslyn,wvdd007/roslyn,dotnet/roslyn,eriawan/roslyn,weltkante/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,wvdd007/roslyn,sharwell/roslyn,bartdesmet/roslyn,sharwell/roslyn,eriawan/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,physhi/roslyn,physhi/roslyn
src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/IConverter.cs
src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/IConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery { internal interface IConverter<TForEachStatement, TStatement> { ForEachInfo<TForEachStatement, TStatement> ForEachInfo { get; } void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery { internal interface IConverter<TForEachStatement, TStatement> { ForEachInfo<TForEachStatement, TStatement> ForEachInfo { get; } void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken); } }
mit
C#
b8130bd3669f447a8179c13ba889207f261c262c
Make mania selection blueprint abstract
NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu
osu.Game.Rulesets.Mania/Edit/Blueprints/ManiaSelectionBlueprint.cs
osu.Game.Rulesets.Mania/Edit/Blueprints/ManiaSelectionBlueprint.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Mania.Edit.Blueprints { public abstract class ManiaSelectionBlueprint : OverlaySelectionBlueprint { public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject; [Resolved] private IScrollingInfo scrollingInfo { get; set; } [Resolved] private IManiaHitObjectComposer composer { get; set; } protected ManiaSelectionBlueprint(DrawableHitObject drawableObject) : base(drawableObject) { RelativeSizeAxes = Axes.None; } protected override void Update() { base.Update(); Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero)); } public override void Show() { DrawableObject.AlwaysAlive = true; base.Show(); } public override void Hide() { DrawableObject.AlwaysAlive = false; base.Hide(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Mania.Edit.Blueprints { public class ManiaSelectionBlueprint : OverlaySelectionBlueprint { public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject; [Resolved] private IScrollingInfo scrollingInfo { get; set; } [Resolved] private IManiaHitObjectComposer composer { get; set; } public ManiaSelectionBlueprint(DrawableHitObject drawableObject) : base(drawableObject) { RelativeSizeAxes = Axes.None; } protected override void Update() { base.Update(); Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero)); } public override void Show() { DrawableObject.AlwaysAlive = true; base.Show(); } public override void Hide() { DrawableObject.AlwaysAlive = false; base.Hide(); } } }
mit
C#
064a6d1e3ba491912564809998b9e79aec2aba4a
Fix doc typo
Joe4evr/Discord.Addons
src/Discord.Addons.SimplePermissions/Attributes/HiddenAttribute.cs
src/Discord.Addons.SimplePermissions/Attributes/HiddenAttribute.cs
using System; namespace Discord.Addons.SimplePermissions { /// <summary> /// Instructs the <see cref="PermissionsModule"/>'s help command to not /// display this particular command or overload. This is a marker attribute. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class HiddenAttribute : Attribute { } }
using System; namespace Discord.Addons.SimplePermissions { /// <summary> /// Instructs the <see cref="PermissionsService"/>'s help command to not /// display this particular command or overload. This is a marker attribute. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class HiddenAttribute : Attribute { } }
mit
C#
e4739b2468a6b47e3769ffe3ce4e444b706b0269
Add path and line to GH console output
laedit/vika
src/NVika/BuildServers/GitHub.cs
src/NVika/BuildServers/GitHub.cs
using System; using System.ComponentModel.Composition; using System.Text; using NVika.Abstractions; using NVika.Parsers; namespace NVika.BuildServers { internal sealed class GitHub : BuildServerBase { private readonly IEnvironment _environment; [ImportingConstructor] internal GitHub(IEnvironment environment) { _environment = environment; } public override string Name => nameof(GitHub); public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS")); public override void WriteMessage(Issue issue) { var outputString = new StringBuilder(); switch (issue.Severity) { case IssueSeverity.Error: outputString.Append("::error "); break; case IssueSeverity.Warning: outputString.Append("::warning"); break; } var details = issue.Message; if (issue.FilePath != null) { var absolutePath = issue.FilePath.Replace('\\', '/'); var relativePath = issue.Project != null ? issue.FilePath.Replace($"{issue.Project.Replace('\\', '/')}/", string.Empty) : absolutePath; outputString.Append($"file={absolutePath},"); details = $"{issue.Message} in {relativePath} on line {issue.Line}"; } if (issue.Offset != null) outputString.Append($"col={issue.Offset.Start},"); outputString.Append($"line={issue.Line}::{details}"); Console.WriteLine(outputString.ToString()); } } }
using System; using System.ComponentModel.Composition; using System.Text; using NVika.Abstractions; using NVika.Parsers; namespace NVika.BuildServers { internal sealed class GitHub : BuildServerBase { private readonly IEnvironment _environment; [ImportingConstructor] internal GitHub(IEnvironment environment) { _environment = environment; } public override string Name => nameof(GitHub); public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS")); public override void WriteMessage(Issue issue) { var outputString = new StringBuilder(); switch (issue.Severity) { case IssueSeverity.Error: outputString.Append("::error "); break; case IssueSeverity.Warning: outputString.Append("::warning"); break; } if (issue.FilePath != null) { var file = issue.FilePath.Replace('\\', '/'); outputString.Append($"file={file},"); } if (issue.Offset != null) outputString.Append($"col={issue.Offset.Start},"); outputString.Append($"line={issue.Line}::{issue.Message}"); Console.WriteLine(outputString.ToString()); } } }
apache-2.0
C#
e6db6e75bfb292fb4262909588c31b288ebd0a17
fix custom validation rule
WTobor/BoardGamesNook,WTobor/BoardGamesNook,WTobor/BoardGamesNook,WTobor/BoardGamesNook
BoardGamesNook/Validators/GameResultValidator.cs
BoardGamesNook/Validators/GameResultValidator.cs
using BoardGamesNook.ViewModels.GameResult; using FluentValidation; namespace BoardGamesNook.Validators { public class GameResultValidator : AbstractValidator<GameResultViewModel> { public GameResultValidator() { RuleFor(gameResult => gameResult.PlayersNumber) .GreaterThanOrEqualTo(gameResult => gameResult.Place.Value) .When(gameResult => gameResult.Place.HasValue) .WithMessage("Maksymalna liczba graczy musi być większa lub równa zajętemu miejscu!"); } } }
using BoardGamesNook.ViewModels.GameResult; using FluentValidation; namespace BoardGamesNook.Validators { public class GameResultValidator : AbstractValidator<GameResultViewModel> { public GameResultValidator() { RuleFor(gameResult => gameResult) .Must(gameResult => gameResult.PlayersNumber >= gameResult.Place) .WithMessage("Maksymalna liczba graczy musi być większa lub równa zajętemu miejscu!"); } } }
mit
C#
484d33840cb644c665b0049cb525a60a6b81d9d9
Enable the batch fixes for SA1100
DotNetAnalyzers/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers/ReadabilityRules/SA1100CodeFixProvider.cs
StyleCop.Analyzers/StyleCop.Analyzers/ReadabilityRules/SA1100CodeFixProvider.cs
namespace StyleCop.Analyzers.ReadabilityRules { using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SpacingRules; [ExportCodeFixProvider(nameof(SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists), LanguageNames.CSharp)] [Shared] public class SA1100CodeFixProvider : CodeFixProvider { private static readonly ImmutableArray<string> _fixableDiagnostics = ImmutableArray.Create(SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists.DiagnosticId); /// <inheritdoc/> public override ImmutableArray<string> GetFixableDiagnosticIds() { return _fixableDiagnostics; } /// <inheritdoc/> public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } /// <inheritdoc/> public override async Task ComputeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { if (!diagnostic.Id.Equals(SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists.DiagnosticId)) continue; var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(diagnostic.Location.SourceSpan) as BaseExpressionSyntax; if (node == null) { return; } var thisExpressionSyntax = SyntaxFactory.ThisExpression() .WithTriviaFrom(node) .WithoutFormatting(); var newSyntaxRoot = root.ReplaceNode(node, thisExpressionSyntax); context.RegisterFix( CodeAction.Create("Replace with this", context.Document.WithSyntaxRoot(newSyntaxRoot)), diagnostic); } } } }
namespace StyleCop.Analyzers.ReadabilityRules { using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SpacingRules; [ExportCodeFixProvider(nameof(SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists), LanguageNames.CSharp)] [Shared] public class SA1100CodeFixProvider : CodeFixProvider { private static readonly ImmutableArray<string> _fixableDiagnostics = ImmutableArray.Create(SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists.DiagnosticId); public override ImmutableArray<string> GetFixableDiagnosticIds() { return _fixableDiagnostics; } public override async Task ComputeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { if (!diagnostic.Id.Equals(SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists.DiagnosticId)) continue; var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(diagnostic.Location.SourceSpan) as BaseExpressionSyntax; if (node == null) { return; } var thisExpressionSyntax = SyntaxFactory.ThisExpression() .WithTriviaFrom(node) .WithoutFormatting(); var newSyntaxRoot = root.ReplaceNode(node, thisExpressionSyntax); context.RegisterFix( CodeAction.Create("Replace with this", context.Document.WithSyntaxRoot(newSyntaxRoot)), diagnostic); } } } }
mit
C#
f4d11f89a313b3897216fb34eeb4990c9117732e
update sample to monitor changes
Pixate/Xamarin-PixateFreestyle,Pixate/Xamarin-PixateFreestyle
Examples/HelloWorld/HelloWorld/AppDelegate.cs
Examples/HelloWorld/HelloWorld/AppDelegate.cs
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using PixateFramework; namespace HelloWorld { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; HelloWorldViewController viewController; // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); Pixate.CurrentApplicationStylesheet ().MonitorChanges = true; Console.WriteLine ("CSS FILE: " + Pixate.CurrentApplicationStylesheet ().FilePath); // Make the main window styleable window.SetStyleMode (PXStylingMode.PXStylingNormal); viewController = new HelloWorldViewController (); window.RootViewController = viewController; // Show how to add two new CSS classes to the main view viewController.View.AddStyleClass ("gray"); viewController.View.AddStyleClass ("bordered"); window.MakeKeyAndVisible (); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using PixateFramework; namespace HelloWorld { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; HelloWorldViewController viewController; // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); // Make the main window styleable window.SetStyleMode (PXStylingMode.PXStylingNormal); viewController = new HelloWorldViewController (); window.RootViewController = viewController; // Show how to add two new CSS classes to the main view viewController.View.AddStyleClass ("gray"); viewController.View.AddStyleClass ("bordered"); window.MakeKeyAndVisible (); return true; } } }
apache-2.0
C#
9d92b4639a4cc0d1f3ca3043cedd30ea7d0d0b0d
Change exception message and pass innerexception to argumentexception
appharbor/appharbor-cli
src/AppHarbor/TypeNameMatcher.cs
src/AppHarbor/TypeNameMatcher.cs
using System; using System.Collections.Generic; using System.Linq; namespace AppHarbor { public class TypeNameMatcher<T> { private readonly IEnumerable<Type> _candidateTypes; public TypeNameMatcher(IEnumerable<Type> candidateTypes) { if (candidateTypes.Any(x => !typeof(T).IsAssignableFrom(x))) { throw new ArgumentException(string.Format("{0} must be assignable from all injected types", typeof(T).FullName), "candidateTypes"); } _candidateTypes = candidateTypes; } public Type GetMatchedType(string commandName, string scope) { var scopedTypes = _candidateTypes.Where(x => x.Name.EndsWith(string.Concat(scope, "Command"))); try { return scopedTypes.Single(x => x.Name.ToLower().StartsWith(commandName.ToLower())); } catch (InvalidOperationException exception) { throw new ArgumentException("Error while matching type", "commandName", exception); } } } }
using System; using System.Collections.Generic; using System.Linq; namespace AppHarbor { public class TypeNameMatcher<T> { private readonly IEnumerable<Type> _candidateTypes; public TypeNameMatcher(IEnumerable<Type> candidateTypes) { if (candidateTypes.Any(x => !typeof(T).IsAssignableFrom(x))) { throw new ArgumentException(string.Format("{0} must be assignable from all injected types", typeof(T).FullName), "candidateTypes"); } _candidateTypes = candidateTypes; } public Type GetMatchedType(string commandName, string scope) { var scopedTypes = _candidateTypes.Where(x => x.Name.EndsWith(string.Concat(scope, "Command"))); try { return scopedTypes.Single(x => x.Name.ToLower().StartsWith(commandName.ToLower())); } catch (InvalidOperationException) { throw new ArgumentException("No candidate type matches", "commandName"); } } } }
mit
C#
7b5b9541974cdc5da2ba4421adb7a5c48f86b314
Change domain data type
shahriarhossain/MailChimp.Api.Net
MailChimp.Api.Net/Domain/Reports/ListStats.cs
MailChimp.Api.Net/Domain/Reports/ListStats.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MailChimp.Api.Net.Domain.Reports { public class ListStats { public double sub_rate { get; set; } public double unsub_rate { get; set; } public double open_rate { get; set; } public double click_rate { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MailChimp.Api.Net.Domain.Reports { public class ListStats { public int sub_rate { get; set; } public int unsub_rate { get; set; } public double open_rate { get; set; } public double click_rate { get; set; } } }
mit
C#
974797fe3f2a9ab15fbc99d8947170679362bbb2
fix exception message
OBeautifulCode/OBeautifulCode.AccountingTime
OBeautifulCode.AccountingTime/ReportingPeriod/ReportingPeriod{T}.cs
OBeautifulCode.AccountingTime/ReportingPeriod/ReportingPeriod{T}.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ReportingPeriod{T}.cs" company="OBeautifulCode"> // Copyright (c) OBeautifulCode. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- // ReSharper disable CheckNamespace namespace OBeautifulCode.AccountingTime { using System; /// <summary> /// Represents a range of time over which to report. /// </summary> /// <typeparam name="T">The unit-of-time used to define the start and end of the reporting period.</typeparam> public abstract class ReportingPeriod<T> where T : UnitOfTime { /// <summary> /// Initializes a new instance of the <see cref="ReportingPeriod{T}"/> class. /// </summary> /// <param name="start">The start of the reporting period.</param> /// <param name="end">The end of the reporting period.</param> /// <exception cref="ArgumentNullException"><paramref name="start"/> or <paramref name="end"/> are null.</exception> /// <exception cref="ArgumentException"><paramref name="start"/> and <paramref name="end"/> are not of the same type.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> must be less than equal to <paramref name="end"/>.</exception> protected ReportingPeriod(T start, T end) { if (start == null) { throw new ArgumentNullException(nameof(start)); } if (end == null) { throw new ArgumentNullException(nameof(end)); } if (start.GetType() != end.GetType()) { throw new ArgumentException("start and end are different kinds of units-of-time"); } if ((dynamic)start > (dynamic)end) { throw new ArgumentOutOfRangeException(nameof(start), "start is great than end"); } this.Start = start; this.End = end; } /// <summary> /// Gets the start of the reporting period. /// </summary> public T Start { get; private set; } /// <summary> /// Gets the end of the reporting period. /// </summary> public T End { get; private set; } } } // ReSharper restore CheckNamespace
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ReportingPeriod{T}.cs" company="OBeautifulCode"> // Copyright (c) OBeautifulCode. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- // ReSharper disable CheckNamespace namespace OBeautifulCode.AccountingTime { using System; /// <summary> /// Represents a range of time over which to report. /// </summary> /// <typeparam name="T">The unit-of-time used to define the start and end of the reporting period.</typeparam> public abstract class ReportingPeriod<T> where T : UnitOfTime { /// <summary> /// Initializes a new instance of the <see cref="ReportingPeriod{T}"/> class. /// </summary> /// <param name="start">The start of the reporting period.</param> /// <param name="end">The end of the reporting period.</param> /// <exception cref="ArgumentNullException"><paramref name="start"/> or <paramref name="end"/> are null.</exception> /// <exception cref="ArgumentException"><paramref name="start"/> and <paramref name="end"/> are not of the same type.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> must be less than equal to <paramref name="end"/>.</exception> protected ReportingPeriod(T start, T end) { if (start == null) { throw new ArgumentNullException(nameof(start)); } if (end == null) { throw new ArgumentNullException(nameof(end)); } if (start.GetType() != end.GetType()) { throw new ArgumentException("start and end are different kinds of units-of-time"); } if ((dynamic)start > (dynamic)end) { throw new ArgumentOutOfRangeException(nameof(start), "start must be less than or equal to end"); } this.Start = start; this.End = end; } /// <summary> /// Gets the start of the reporting period. /// </summary> public T Start { get; private set; } /// <summary> /// Gets the end of the reporting period. /// </summary> public T End { get; private set; } } } // ReSharper restore CheckNamespace
mit
C#
f18263aa70dc215af08e6b008c74a5be7a700d39
Add tests
smoogipoo/osu,UselessToucan/osu,2yangk23/osu,ppy/osu,ppy/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu,2yangk23/osu,EVAST9919/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,peppy/osu
osu.Game.Tests/Visual/Online/TestSceneFavouriteButton.cs
osu.Game.Tests/Visual/Online/TestSceneFavouriteButton.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Overlays.BeatmapSet.Buttons; using osuTK; namespace osu.Game.Tests.Visual.Online { public class TestSceneFavouriteButton : OsuTestScene { private FavouriteButton favourite; [SetUpSteps] public void SetUpSteps() { AddStep("create button", () => Child = favourite = new FavouriteButton { RelativeSizeAxes = Axes.None, Size = new Vector2(50), Anchor = Anchor.Centre, Origin = Anchor.Centre, }); } [Test] public void TestLoggedOutIn() { AddStep("set valid beatmap", () => favourite.BeatmapSet.Value = new BeatmapSetInfo { OnlineBeatmapSetID = 88 }); AddStep("log out", () => API.Logout()); checkEnabled(false); AddStep("log in", () => API.Login("test", "test")); checkEnabled(true); } [Test] public void TestBeatmapChange() { AddStep("log in", () => API.Login("test", "test")); AddStep("set valid beatmap", () => favourite.BeatmapSet.Value = new BeatmapSetInfo { OnlineBeatmapSetID = 88 }); checkEnabled(true); AddStep("set invalid beatmap", () => favourite.BeatmapSet.Value = new BeatmapSetInfo()); checkEnabled(false); } private void checkEnabled(bool expected) { AddAssert("is " + (expected ? "enabled" : "disabled"), () => favourite.Enabled.Value == expected); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Overlays.BeatmapSet.Buttons; namespace osu.Game.Tests.Visual.Online { public class TestSceneFavouriteButton : OsuTestScene { private FavouriteButton favourite; [SetUpSteps] public void SetUpSteps() { AddStep("create button", () => Child = favourite = new FavouriteButton()); } [Test] public void TestLoggedOutIn() { AddStep("set valid beatmap", () => favourite.BeatmapSet.Value = new BeatmapSetInfo { OnlineBeatmapSetID = 88 }); AddStep("log out", () => API.Logout()); checkEnabled(false); AddStep("log in", () => API.Login("test", "test")); checkEnabled(true); } [Test] public void TestBeatmapChange() { AddStep("log in", () => API.Login("test", "test")); AddStep("set valid beatmap", () => favourite.BeatmapSet.Value = new BeatmapSetInfo { OnlineBeatmapSetID = 88 }); checkEnabled(true); AddStep("set invalid beatmap", () => favourite.BeatmapSet.Value = new BeatmapSetInfo()); checkEnabled(true); } private void checkEnabled(bool expected) { AddAssert("is " + (expected ? "enabled" : "disabled"), () => favourite.Enabled.Value == expected); } } }
mit
C#
4f845fc20438e0edb113d2f720cd3753e671a41b
fix build after merging
WaltChen/NDatabase,WaltChen/NDatabase
src/Tool/DictionaryExtensions.cs
src/Tool/DictionaryExtensions.cs
using System; using System.Collections.Generic; namespace NDatabase.Tool { internal static class DictionaryExtensions { internal static TItem GetOrAdd<TKey, TItem>(this Dictionary<TKey, TItem> self, TKey key, Func<TKey, TItem> produce) { TItem value; var success = self.TryGetValue(key, out value); if (success) return value; value = produce(key); self.Add(key, value); return value; } internal static TItem GetOrAdd<TKey, TItem>(this Dictionary<TKey, TItem> self, TKey key, TItem item) { TItem value; var success = self.TryGetValue(key, out value); if (success) return value; self.Add(key, item); return item; } } }
using System; using System.Collections.Generic; namespace NDatabase.Tool { internal static class DictionaryExtensions { <<<<<<< HEAD public static TItem GetOrAdd<TKey, TItem>(this Dictionary<TKey, TItem> self, TKey key, Func<TKey, TItem> produce) ======= internal static TItem GetOrAdd<TKey, TItem>(this Dictionary<TKey, TItem> self, TKey key, Func<TKey, TItem> produce) >>>>>>> master { TItem value; var success = self.TryGetValue(key, out value); if (success) return value; value = produce(key); self.Add(key, value); return value; } <<<<<<< HEAD public static TItem GetOrAdd<TKey, TItem>(this Dictionary<TKey, TItem> self, TKey key, TItem item) ======= internal static TItem GetOrAdd<TKey, TItem>(this Dictionary<TKey, TItem> self, TKey key, TItem item) >>>>>>> master { TItem value; var success = self.TryGetValue(key, out value); if (success) return value; self.Add(key, item); return item; } } }
apache-2.0
C#
1f22c2900476f7ee12d3cf2c5fad480f5f85f193
Fix crash problem
hug3id/Xamarin.Forms.BaiduMaps,hug3id/Xamarin.Forms.BaiduMaps
Xamarin.Forms.BaiduMaps.iOS/FormsBaiduMaps.cs
Xamarin.Forms.BaiduMaps.iOS/FormsBaiduMaps.cs
using System.Diagnostics; using BMapBinding; namespace Xamarin { public static class FormsBaiduMaps { public static void Init(string APIKey) { BMKMapManager mgr = new BMKMapManager(); mgr.Start(APIKey, new GeneralDelegate()); } } class GeneralDelegate : BMKGeneralDelegate { public override void OnGetNetworkState(int iError) { Debug.WriteLine("OnGetNetworkState: " + iError); } public override void OnGetPermissionState(int iError) { Debug.WriteLine("OnGetPermissionState: " + iError); } } }
using BMapBinding; namespace Xamarin { public static class FormsBaiduMaps { public static void Init(string APIKey) { BMKMapManager mgr = new BMKMapManager(); mgr.Start(APIKey, new BMKGeneralDelegate()); } } }
apache-2.0
C#
e878ff8b74f38e2a42e105f48c4b59a1b14ff22d
fix copyright info
dietsche/infinite-putty-tunnel
Infinite-PuTTY-Tunnel/Properties/AssemblyInfo.cs
Infinite-PuTTY-Tunnel/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("Infinite PuTTY Tunnel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Infinite PuTTY Tunnel")] [assembly: AssemblyCopyright("Copyright 2016 Gregory L Dietsche. Copyright 2009 Joeri Bekker.")] [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("26409fc0-5677-469d-acff-f41414b538f3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.1")]
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("Infinite PuTTY Tunnel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Infinite PuTTY Tunnel")] [assembly: AssemblyCopyright("Copyright 2016 Gregory L Dietsche. Copyright 2009-2009 Joeri Bekker.")] [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("26409fc0-5677-469d-acff-f41414b538f3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.1")]
mit
C#
426627c616b561507e239062937dfd504e8e4cc0
tweak Unit.id comment
ad510/plausible-deniability
Assets/Scripts/Unit.cs
Assets/Scripts/Unit.cs
// Copyright (c) 2013 Andrew Downing // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; /// <summary> /// identity of a unit /// </summary> /// <remarks>how unit moves is stored in Path class, not here</remarks> public class Unit { public readonly Sim g; public readonly int id; // index in unit list public readonly int type; public readonly int player; public int nTimeHealth; public long[] timeHealth; // times at which each health increment is removed (TODO: change how this is stored to allow switching units on a path) public long timeAttack; // latest time that attacked a unit public Unit(Sim simVal, int idVal, int typeVal, int playerVal) { g = simVal; id = idVal; type = typeVal; player = playerVal; nTimeHealth = 0; timeHealth = new long[g.unitT[type].maxHealth]; timeAttack = long.MinValue; } /// <summary> /// remove 1 health increment at specified time /// </summary> public void takeHealth(long time, int path) { if (nTimeHealth < g.unitT[type].maxHealth) { nTimeHealth++; timeHealth[nTimeHealth - 1] = time; if (nTimeHealth >= g.unitT[type].maxHealth) { // unit lost all health, so remove it from path int seg = g.paths[path].insertSegment(time); g.paths[path].segments[seg].units.Remove (id); // if path no longer has any units, indicate to delete and recalculate later TileMoveEvts for this path if (g.paths[path].segments[seg].units.Count == 0 && !g.movedPaths.Contains(path)) g.movedPaths.Add(path); } } } /// <summary> /// returns health of this unit at latest possible time /// </summary> public int healthLatest() { return g.unitT[type].maxHealth - nTimeHealth; } /// <summary> /// returns health of this unit at specified time /// </summary> public int healthWhen(long time) { int i = nTimeHealth; while (i > 0 && time < timeHealth[i - 1]) i--; return g.unitT[type].maxHealth - i; } }
// Copyright (c) 2013 Andrew Downing // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; /// <summary> /// identity of a unit /// </summary> /// <remarks>how unit moves is stored in Path class, not here</remarks> public class Unit { public readonly Sim g; public readonly int id; // index in unit array public readonly int type; public readonly int player; public int nTimeHealth; public long[] timeHealth; // times at which each health increment is removed (TODO: change how this is stored to allow switching units on a path) public long timeAttack; // latest time that attacked a unit public Unit(Sim simVal, int idVal, int typeVal, int playerVal) { g = simVal; id = idVal; type = typeVal; player = playerVal; nTimeHealth = 0; timeHealth = new long[g.unitT[type].maxHealth]; timeAttack = long.MinValue; } /// <summary> /// remove 1 health increment at specified time /// </summary> public void takeHealth(long time, int path) { if (nTimeHealth < g.unitT[type].maxHealth) { nTimeHealth++; timeHealth[nTimeHealth - 1] = time; if (nTimeHealth >= g.unitT[type].maxHealth) { // unit lost all health, so remove it from path int seg = g.paths[path].insertSegment(time); g.paths[path].segments[seg].units.Remove (id); // if path no longer has any units, indicate to delete and recalculate later TileMoveEvts for this path if (g.paths[path].segments[seg].units.Count == 0 && !g.movedPaths.Contains(path)) g.movedPaths.Add(path); } } } /// <summary> /// returns health of this unit at latest possible time /// </summary> public int healthLatest() { return g.unitT[type].maxHealth - nTimeHealth; } /// <summary> /// returns health of this unit at specified time /// </summary> public int healthWhen(long time) { int i = nTimeHealth; while (i > 0 && time < timeHealth[i - 1]) i--; return g.unitT[type].maxHealth - i; } }
mit
C#
bb839d73c5032922c95e089d098c63ac30202001
Adjust test
tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date
Src/Nager.Date.UnitTest/Country/SingaporeTest.cs
Src/Nager.Date.UnitTest/Country/SingaporeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using Nager.Date.Extensions; using System; using System.Linq; namespace Nager.Date.UnitTest.Country { [TestClass] public class SingaporeTest { [TestMethod] public void TestSingapore() { var publicHolidays = DateSystem.GetPublicHolidays(2022, CountryCode.SG).ToArray(); Assert.AreEqual("New Year’s Day", publicHolidays[0].Name); } [TestMethod] public void HolidayCount() { for (var year = 2018; year <= 2022; year++) { var publicHolidays = DateSystem.GetPublicHolidays(year, CountryCode.SG).ToArray(); Assert.AreEqual(11, publicHolidays.Length); } } [TestMethod] [DataRow(2022, 1, 1, true)] [DataRow(2022, 1, 3, false)] [DataRow(2022, 5, 2, true)] [DataRow(2022, 7, 9, true)] public void Year2022(int year, int month, int day, bool expected) { // Arrange var date = new DateTime(year, month, day); // Act var result = DateSystem.IsPublicHoliday(date, CountryCode.SG); // Assert Assert.AreEqual(expected, result); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Nager.Date.Extensions; using System; using System.Linq; namespace Nager.Date.UnitTest.Country { [TestClass] public class SingaporeTest { [TestMethod] public void TestSingapore() { var publicHolidays = DateSystem.GetPublicHolidays(2022, CountryCode.SG).ToArray(); Assert.AreEqual("New Year’s Day", publicHolidays[0].Name); } [TestMethod] public void HolidayCount() { for (var year = 2018; year <= 2022; year++) { var publicHolidays = DateSystem.GetPublicHolidays(year, CountryCode.SG).ToArray(); Assert.AreEqual(11, publicHolidays.Length); } } [TestMethod] [DataRow(2022, 1, 1, true)] [DataRow(2022, 1, 3, false)] [DataRow(2022, 5, 2, true)] [DataRow(2022, 7, 29, true)] public void Year2022(int year, int month, int day, bool expected) { // Arrange var date = new DateTime(year, month, day); // Act var result = DateSystem.IsPublicHoliday(date, CountryCode.SG); // Assert Assert.AreEqual(expected, result); } } }
mit
C#
6a005763d2f526b6b6970f00aec91954ce6b89fc
Add missing user defined func param array for ReportFactory execute
once-ler/Store
Store.Reports/src/ReportFactory.cs
Store.Reports/src/ReportFactory.cs
using System; using System.Linq; using System.Collections.Generic; using Store.Models; using Store.Storage; namespace Store.Reports { public class ReportType { public enum ContentFormat { HTML, JSON, XML } public ReportType(ContentFormat contentType) { outgoingFormat = contentType; } public ContentFormat outgoingFormat { get; set; } public string process(IEnumerable<dynamic> context, Func<IEnumerable<dynamic>, IEnumerable<dynamic>> transformFunc, Func<IEnumerable<dynamic>, IEnumerable<dynamic>> themeFunc = null, params Func<IEnumerable<dynamic>, IEnumerable<dynamic>>[] userDefinedFuncs) { var e = processImpl(context, transformFunc, themeFunc); e = processImpl(context, userDefinedFuncs); return string.Join("", e.Select(a => (string)a).ToArray<string>()); } private IEnumerable<dynamic> processImpl(IEnumerable<dynamic> context, params Func<IEnumerable<dynamic>, IEnumerable<dynamic>>[] funcs) { foreach (var func in funcs) { if (func != null) context = func(context); } return context; } } public class ReportFactory<T> where T : ReportType { public ReportType reportType { get; private set; } public ReportFactory(T reportType_) { reportType = reportType_; } public dynamic execute(BasicClient client, string statement, Func<IEnumerable<dynamic>, IEnumerable<dynamic>> transform, Func<IEnumerable<dynamic>, IEnumerable<dynamic>> themeFunc = null, params Func<IEnumerable<dynamic>, IEnumerable<dynamic>>[] userDefinedFuncs) { dynamic retval = null; try { retval = client.runSqlDynamic(statement); } catch (Exception err) { // No op } return reportType.process(retval, transform, themeFunc, userDefinedFuncs); } } }
using System; using System.Linq; using System.Collections.Generic; using Store.Models; using Store.Storage; namespace Store.Reports { public class ReportType { public enum ContentFormat { HTML, JSON, XML } public ReportType(ContentFormat contentType) { outgoingFormat = contentType; } public ContentFormat outgoingFormat { get; set; } public string process(IEnumerable<dynamic> context, Func<IEnumerable<dynamic>, IEnumerable<dynamic>> transformFunc, Func<IEnumerable<dynamic>, IEnumerable<dynamic>> themeFunc = null, params Func<IEnumerable<dynamic>, IEnumerable<dynamic>>[] userDefinedFuncs) { var e = processImpl(context, transformFunc, themeFunc); e = processImpl(context, userDefinedFuncs); return string.Join("", e.Select(a => (string)a).ToArray<string>()); } private IEnumerable<dynamic> processImpl(IEnumerable<dynamic> context, params Func<IEnumerable<dynamic>, IEnumerable<dynamic>>[] funcs) { foreach (var func in funcs) { if (func != null) context = func(context); } return context; } } public class ReportFactory<T> where T : ReportType { public ReportType reportType { get; private set; } public ReportFactory(T reportType_) { reportType = reportType_; } public dynamic execute(BasicClient client, string statement, Func<IEnumerable<dynamic>, IEnumerable<dynamic>> transform, Func<IEnumerable<dynamic>, IEnumerable<dynamic>> themeFunc = null) { dynamic retval = null; try { retval = client.runSqlDynamic(statement); } catch (Exception err) { // No op } return reportType.process(retval, transform, themeFunc); } } }
mit
C#
4e1ee754ffc48dde87a481ff6747f286cce00c20
Handle empty airdate.
jonasf/tv-show-reminder
TvShowReminder.TvMazeApi/Domain/TvMazeEpisode.cs
TvShowReminder.TvMazeApi/Domain/TvMazeEpisode.cs
using System; using Newtonsoft.Json; namespace TvShowReminder.TvMazeApi.Domain { public class TvMazeEpisode { public string Name { get; set; } public int Season { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public int Number { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public DateTime AirDate { get; set; } } }
using System; using Newtonsoft.Json; namespace TvShowReminder.TvMazeApi.Domain { public class TvMazeEpisode { public string Name { get; set; } public int Season { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public int Number { get; set; } public DateTime AirDate { get; set; } } }
mit
C#
1d22a7550a1f554225e8432740451a2f4815bffd
fix razor
ucdavis/CRP,ucdavis/CRP,ucdavis/CRP
CRP.Mvc/Views/Help/WatchVideo.cshtml
CRP.Mvc/Views/Help/WatchVideo.cshtml
@model CRP.Core.Domain.HelpTopic @using CRP.Controllers.Helpers @{ ViewBag.Title = "How to"; } @Html.HtmlEncode(Model.Answer) <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="single1" name="CRP how to" width="720" height="576"> <param name="movie" value="http://v.caes.ucdavis.edu/JWPlayer/player.swf"> <param name="allowfullscreen" value="true"> <param name="allowscriptaccess" value="always"> <param name="wmode" value="transparent"> <param name="flashvars" value="author=CRP&amp;file=http://v.caes.ucdavis.edu/CRP/Video/@(Model.VideoName).flv&amp; image=http://v.caes.ucdavis.edu/CRP/Video@(Model.VideoName).jpg&amp; plugins=captions-1,audiodescription-1"> <embed type="application/x-shockwave-flash" id="single2" name="single2" src="http://v.caes.ucdavis.edu/JWPlayer/player.swf" bgcolor="undefined" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" flashvars="author=ASI&amp;file=http://v.caes.ucdavis.edu/CRP/Video/@(Model.VideoName).flv&amp; image=http://v.caes.ucdavis.edu/CRP/Video/@(Model.VideoName).jpg&amp; plugins=captions-1,audiodescription-1" width="720" height="576"> </object> <p> <a href="javascript:history.go(-1)" onMouseOver="self.status=document.referrer;return true">BACK</a> </p>
@model CRP.Core.Domain.HelpTopic @using CRP.Controllers.Helpers @{ ViewBag.Title = "How to"; } @Html.HtmlEncode(Model.Answer) <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="single1" name="CRP how to" width="720" height="576"> <param name="movie" value="http://v.caes.ucdavis.edu/JWPlayer/player.swf"> <param name="allowfullscreen" value="true"> <param name="allowscriptaccess" value="always"> <param name="wmode" value="transparent"> <param name="flashvars" value="author=CRP&amp;file=http://v.caes.ucdavis.edu/CRP/Video/@Model.VideoName.flv&amp; image=http://v.caes.ucdavis.edu/CRP/Video@Model.VideoName.jpg&amp; plugins=captions-1,audiodescription-1"> <embed type="application/x-shockwave-flash" id="single2" name="single2" src="http://v.caes.ucdavis.edu/JWPlayer/player.swf" bgcolor="undefined" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" flashvars="author=ASI&amp;file=http://v.caes.ucdavis.edu/CRP/Video/@Model.VideoName.flv&amp; image=http://v.caes.ucdavis.edu/CRP/Video/@Model.VideoName.jpg&amp; plugins=captions-1,audiodescription-1" width="720" height="576"> </object> <p> <a href="javascript:history.go(-1)" onMouseOver="self.status=document.referrer;return true">BACK</a> </p>
mit
C#
676f6098494e73622af2d97f1a0170ba8494b72c
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.NetworkAdapters/ValuesOut.cs
RegistryPlugin.NetworkAdapters/ValuesOut.cs
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.NetworkAdapters { public class ValuesOut : IValueOut { public ValuesOut(string driverdesc, string driverdate, string driverversion, string deviceinstanceid, string providername, DateTimeOffset? timestamp) { DriverDesc = driverdesc; DriverDate = driverdate; DriverVersion = driverversion; ProviderName = providername; DeviceInstanceid = deviceinstanceid; Timestamp = timestamp; } public DateTimeOffset? Timestamp { get; } public string DriverDesc { get; } public string DriverDate { get; } public string DriverVersion { get; } public string ProviderName { get; } public string DeviceInstanceid { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"DriveName: {DriverDesc} DriverDate: {DriverDate} DriverVersion: {DriverVersion} ProviderName: {ProviderName}"; public string BatchValueData2 => $"DeviceInstanceid: {DeviceInstanceid}"; public string BatchValueData3 => $"Timestamp: {Timestamp?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}"; } }
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.NetworkAdapters { public class ValuesOut : IValueOut { public ValuesOut(string driverdesc, string driverdate, string driverversion, string deviceinstanceid, string providername, DateTimeOffset? timestamp) { DriverDesc = driverdesc; DriverDate = driverdate; DriverVersion = driverversion; ProviderName = providername; DeviceInstanceid = deviceinstanceid; Timestamp = timestamp; } public DateTimeOffset? Timestamp { get; } public string DriverDesc { get; } public string DriverDate { get; } public string DriverVersion { get; } public string ProviderName { get; } public string DeviceInstanceid { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"DriveName: {DriverDesc} DriverDate: {DriverDate} DriverVersion: {DriverVersion} ProviderName: {ProviderName}"; public string BatchValueData2 => $"DeviceInstanceid: {DeviceInstanceid}"; public string BatchValueData3 => $"Timestamp: {Timestamp?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff} "; } }
mit
C#
94c7e9e0bb81a50c13ef1c74fb79a2d6b3ca8fdf
Fix compile issue from merge
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/src/resharper-unity/Feature/Services/LiveTemplates/Scope/InUnityShaderLabFile.cs
resharper/src/resharper-unity/Feature/Services/LiveTemplates/Scope/InUnityShaderLabFile.cs
using System; using System.Collections.Generic; using JetBrains.ReSharper.Feature.Services.LiveTemplates.Scope; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi; using JetBrains.ReSharper.Psi; namespace JetBrains.ReSharper.Plugins.Unity.Feature.Services.LiveTemplates.Scope { public class InUnityShaderLabFile : InAnyLanguageFile, IMainScopePoint { private static readonly Guid DefaultUID = new Guid("ED25967E-EAEA-47CC-AB3C-C549C5F3F378"); private static readonly Guid QuickUID = new Guid("1149A991-197E-468A-90E0-07700A01FBD3"); public override Guid GetDefaultUID() => DefaultUID; public override PsiLanguageType RelatedLanguage => ShaderLabLanguage.Instance; public override string PresentableShortName => "ShaderLab (Unity)"; protected override IEnumerable<string> GetExtensions() { yield return ShaderLabProjectFileType.SHADERLAB_EXTENSION; } public override string ToString() => "ShaderLab (Unity)"; public new string QuickListTitle => "Unity files"; public new Guid QuickListUID => QuickUID; } }
using System; using System.Collections.Generic; using JetBrains.ReSharper.Feature.Services.LiveTemplates.Scope; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi; using JetBrains.ReSharper.Psi; namespace JetBrains.ReSharper.Plugins.Unity.Feature.Services.LiveTemplates.Scope { public class InUnityShaderLabFile : InAnyLanguageFile, IMainScopePoint { private static readonly Guid DefaultUID = new Guid("ED25967E-EAEA-47CC-AB3C-C549C5F3F378"); private static readonly Guid QuickUID = new Guid("1149A991-197E-468A-90E0-07700A01FBD3"); public override Guid GetDefaultUID() => DefaultUID; public override PsiLanguageType RelatedLanguage => ShaderLabLanguage.Instance; public override string PresentableShortName => "ShaderLab (Unity)"; protected override IEnumerable<string> GetExtensions() { yield return ShaderLabProjectFileType.SHADER_EXTENSION; } public override string ToString() => "ShaderLab (Unity)"; public new string QuickListTitle => "Unity files"; public new Guid QuickListUID => QuickUID; } }
apache-2.0
C#
9141d2e18c3e6f8cac3bfadc9f625e84b7379675
Remove a dependency on System.Drawing.Common by using a compatible color parser.
ClosedXML/ClosedXML
ClosedXML/Utils/ColorStringParser.cs
ClosedXML/Utils/ColorStringParser.cs
using System; using System.ComponentModel; using System.Drawing; using System.Globalization; namespace ClosedXML.Utils { internal static class ColorStringParser { public static Color ParseFromHtml(string htmlColor) { try { if (htmlColor[0] == '#' && (htmlColor.Length == 4 || htmlColor.Length == 7)) { if (htmlColor.Length == 4) { var r = ReadHex(htmlColor, 1, 1); var g = ReadHex(htmlColor, 2, 1); var b = ReadHex(htmlColor, 3, 1); return Color.FromArgb( (r << 4) | r, (g << 4) | g, (b << 4) | b); } return Color.FromArgb( ReadHex(htmlColor, 1, 2), ReadHex(htmlColor, 3, 2), ReadHex(htmlColor, 5, 2)); } return (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString(htmlColor); } catch { // https://github.com/ClosedXML/ClosedXML/issues/675 // When regional settings list separator is # , the standard ColorTranslator.FromHtml fails return Color.FromArgb(int.Parse(htmlColor.Replace("#", ""), NumberStyles.AllowHexSpecifier)); } } private static int ReadHex(string text, int start, int length) { return Convert.ToInt32(text.Substring(start, length), 16); } } }
using System.Drawing; using System.Globalization; namespace ClosedXML.Utils { internal static class ColorStringParser { public static Color ParseFromHtml(string htmlColor) { try { if (htmlColor[0] != '#') htmlColor = '#' + htmlColor; return ColorTranslator.FromHtml(htmlColor); } catch { // https://github.com/ClosedXML/ClosedXML/issues/675 // When regional settings list separator is # , the standard ColorTranslator.FromHtml fails return Color.FromArgb(int.Parse(htmlColor.Replace("#", ""), NumberStyles.AllowHexSpecifier)); } } } }
mit
C#
d43643a8d717aa1cf78d5d5002096c64cf08379d
Update context that is passed through
mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype
src/Glimpse.Agent.Web/Framework/IIgnoredRequestPolicy.cs
src/Glimpse.Agent.Web/Framework/IIgnoredRequestPolicy.cs
using System; using Glimpse.Web; namespace Glimpse.Agent.Web { public interface IIgnoredRequestPolicy { bool ShouldIgnore(IHttpContext context); } }
using System; namespace Glimpse.Agent.Web { public interface IIgnoredRequestPolicy { bool ShouldIgnore(IContext context); } }
mit
C#
1a951a52a3ea045f5de33977199837158b1f1189
Handle action execution errors
danielchalmers/DesktopWidgets
DesktopWidgets/Actions/ActionBase.cs
DesktopWidgets/Actions/ActionBase.cs
using System; using System.ComponentModel; using System.Windows; using DesktopWidgets.Classes; namespace DesktopWidgets.Actions { public abstract class ActionBase { [DisplayName("Delay")] public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0); public void Execute() { DelayedAction.RunAction((int) Delay.TotalMilliseconds, () => { try { ExecuteAction(); } catch (Exception ex) { Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}", image: MessageBoxImage.Error); } }); } public virtual void ExecuteAction() { } } }
using System; using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Actions { public abstract class ActionBase { [DisplayName("Delay")] public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0); public void Execute() { DelayedAction.RunAction((int) Delay.TotalMilliseconds, ExecuteAction); } public virtual void ExecuteAction() { } } }
apache-2.0
C#
127a8138d98bcfcc7f4e4d6dd7fc8a59dc9f5f58
Make a class again.
AlekseyTs/roslyn,mgoertz-msft/roslyn,cston/roslyn,mgoertz-msft/roslyn,robinsedlaczek/roslyn,MattWindsor91/roslyn,dpoeschl/roslyn,jeffanders/roslyn,genlu/roslyn,sharwell/roslyn,brettfo/roslyn,physhi/roslyn,swaroop-sridhar/roslyn,gafter/roslyn,eriawan/roslyn,zooba/roslyn,CyrusNajmabadi/roslyn,paulvanbrenk/roslyn,tmeschter/roslyn,stephentoub/roslyn,jamesqo/roslyn,lorcanmooney/roslyn,bbarry/roslyn,OmarTawfik/roslyn,pdelvo/roslyn,genlu/roslyn,zooba/roslyn,lorcanmooney/roslyn,aelij/roslyn,Hosch250/roslyn,panopticoncentral/roslyn,AnthonyDGreen/roslyn,amcasey/roslyn,VSadov/roslyn,AlekseyTs/roslyn,khyperia/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,yeaicc/roslyn,kelltrick/roslyn,agocke/roslyn,khyperia/roslyn,MattWindsor91/roslyn,jeffanders/roslyn,CaptainHayashi/roslyn,DustinCampbell/roslyn,dotnet/roslyn,jkotas/roslyn,bkoelman/roslyn,abock/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,sharwell/roslyn,MattWindsor91/roslyn,CyrusNajmabadi/roslyn,amcasey/roslyn,eriawan/roslyn,mavasani/roslyn,mavasani/roslyn,lorcanmooney/roslyn,agocke/roslyn,brettfo/roslyn,abock/roslyn,heejaechang/roslyn,robinsedlaczek/roslyn,bkoelman/roslyn,stephentoub/roslyn,kelltrick/roslyn,drognanar/roslyn,jmarolf/roslyn,srivatsn/roslyn,tannergooding/roslyn,MichalStrehovsky/roslyn,KevinRansom/roslyn,davkean/roslyn,heejaechang/roslyn,xasx/roslyn,akrisiun/roslyn,jkotas/roslyn,mattwar/roslyn,akrisiun/roslyn,drognanar/roslyn,paulvanbrenk/roslyn,yeaicc/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,nguerrera/roslyn,reaction1989/roslyn,akrisiun/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,CaptainHayashi/roslyn,AmadeusW/roslyn,jcouv/roslyn,tvand7093/roslyn,jasonmalinowski/roslyn,jmarolf/roslyn,agocke/roslyn,srivatsn/roslyn,physhi/roslyn,MattWindsor91/roslyn,AlekseyTs/roslyn,paulvanbrenk/roslyn,physhi/roslyn,weltkante/roslyn,dotnet/roslyn,bartdesmet/roslyn,bbarry/roslyn,mavasani/roslyn,nguerrera/roslyn,Giftednewt/roslyn,dotnet/roslyn,diryboy/roslyn,mattscheffer/roslyn,yeaicc/roslyn,orthoxerox/roslyn,Hosch250/roslyn,genlu/roslyn,CaptainHayashi/roslyn,brettfo/roslyn,jcouv/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,TyOverby/roslyn,tmat/roslyn,abock/roslyn,orthoxerox/roslyn,dpoeschl/roslyn,xasx/roslyn,diryboy/roslyn,dpoeschl/roslyn,gafter/roslyn,xasx/roslyn,Giftednewt/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,AnthonyDGreen/roslyn,bbarry/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,zooba/roslyn,jeffanders/roslyn,mmitche/roslyn,tmeschter/roslyn,reaction1989/roslyn,stephentoub/roslyn,swaroop-sridhar/roslyn,jamesqo/roslyn,jcouv/roslyn,VSadov/roslyn,DustinCampbell/roslyn,srivatsn/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,DustinCampbell/roslyn,tvand7093/roslyn,diryboy/roslyn,TyOverby/roslyn,panopticoncentral/roslyn,TyOverby/roslyn,MichalStrehovsky/roslyn,tmat/roslyn,nguerrera/roslyn,davkean/roslyn,mgoertz-msft/roslyn,aelij/roslyn,weltkante/roslyn,bartdesmet/roslyn,OmarTawfik/roslyn,tvand7093/roslyn,wvdd007/roslyn,MichalStrehovsky/roslyn,cston/roslyn,robinsedlaczek/roslyn,bartdesmet/roslyn,mattwar/roslyn,tannergooding/roslyn,bkoelman/roslyn,jasonmalinowski/roslyn,pdelvo/roslyn,tmat/roslyn,kelltrick/roslyn,orthoxerox/roslyn,drognanar/roslyn,mattwar/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,VSadov/roslyn,jkotas/roslyn,wvdd007/roslyn,mattscheffer/roslyn,eriawan/roslyn,jamesqo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,khyperia/roslyn,cston/roslyn,KevinRansom/roslyn,pdelvo/roslyn,aelij/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,amcasey/roslyn,tannergooding/roslyn,Hosch250/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,mmitche/roslyn,Giftednewt/roslyn,tmeschter/roslyn,davkean/roslyn,gafter/roslyn,AnthonyDGreen/roslyn,mattscheffer/roslyn,CyrusNajmabadi/roslyn,reaction1989/roslyn
src/Workspaces/Core/Portable/NamingStyles/NamingStyleRules.cs
src/Workspaces/Core/Portable/NamingStyles/NamingStyleRules.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal class NamingStyleRules { public ImmutableArray<NamingRule> NamingRules { get; } public NamingStyleRules(ImmutableArray<NamingRule> namingRules) { NamingRules = namingRules; } internal bool TryGetApplicableRule(ISymbol symbol, out NamingRule applicableRule) { if (NamingRules != null && IsSymbolNameAnalyzable(symbol)) { foreach (var namingRule in NamingRules) { if (namingRule.SymbolSpecification.AppliesTo(symbol)) { applicableRule = namingRule; return true; } } } applicableRule = default(NamingRule); return false; } private bool IsSymbolNameAnalyzable(ISymbol symbol) { if (symbol.Kind == SymbolKind.Method) { return ((IMethodSymbol)symbol).MethodKind == MethodKind.Ordinary; } if (symbol.Kind == SymbolKind.Property) { return !((IPropertySymbol)symbol).IsIndexer; } return true; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal struct NamingStyleRules { public ImmutableArray<NamingRule> NamingRules { get; } public NamingStyleRules(ImmutableArray<NamingRule> namingRules) { NamingRules = namingRules; } internal bool TryGetApplicableRule(ISymbol symbol, out NamingRule applicableRule) { if (NamingRules != null && IsSymbolNameAnalyzable(symbol)) { foreach (var namingRule in NamingRules) { if (namingRule.SymbolSpecification.AppliesTo(symbol)) { applicableRule = namingRule; return true; } } } applicableRule = default(NamingRule); return false; } private bool IsSymbolNameAnalyzable(ISymbol symbol) { if (symbol.Kind == SymbolKind.Method) { return ((IMethodSymbol)symbol).MethodKind == MethodKind.Ordinary; } if (symbol.Kind == SymbolKind.Property) { return !((IPropertySymbol)symbol).IsIndexer; } return true; } } }
apache-2.0
C#
2077d8e496ffedccb913b0c225b3c8ad2e5089a8
Fix bug: remember me checkbox needs 1 value
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
Zk/Views/Account/_LoginForm.cshtml
Zk/Views/Account/_LoginForm.cshtml
@model LoginOrRegisterViewModel @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class="form-horizontal", @role="form"})) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div class="input-group box-margin"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <span> @Html.TextBoxFor(vm => vm.Login.UserName, new { @class = "form-control", @placeholder = "Gebruikersnaam of e-mailadres" }) </span> </div> <div class="input-group box-margin"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> @Html.PasswordFor(vm => vm.Login.Password, new { @class = "form-control", @placeholder = "Wachtwoord" }) </div> <div class="input-group"> <div class="checkbox"> <label class="form-text"> @Html.CheckBoxFor(vm => vm.Login.RememberMe, new { @class = "checkbox" }) Onthoud mij. </label> </div> </div> <div class="form-group form-group-margin"> <!-- Button --> <div class="col-sm-12 controls"> <button type="submit" class="btn btn-success">Inloggen</button> @if(ViewData.ModelState.ContainsKey("registration")){ @ViewData.ModelState["registration"].Errors.First().ErrorMessage; } </div> </div> <div class="form-group"> <div class="col-md-12 control"> <div class="box-border"> Ik heb nog geen account! <a href="#" id="register-link"> Registreren. </a> </div> </div> </div> }
@model LoginOrRegisterViewModel @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class="form-horizontal", @role="form"})) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div class="input-group box-margin"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <span> @Html.TextBoxFor(vm => vm.Login.UserName, new { @class = "form-control", @placeholder = "Gebruikersnaam of e-mailadres" }) </span> </div> <div class="input-group box-margin"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> @Html.PasswordFor(vm => vm.Login.Password, new { @class = "form-control", @placeholder = "Wachtwoord" }) </div> <div class="input-group"> <div class="checkbox"> <label class="form-text"> @Html.CheckBoxFor(vm => vm.Login.RememberMe, new { @class = "checkbox", @value = "1" }) Onthoud mij. </label> </div> </div> <div class="form-group form-group-margin"> <!-- Button --> <div class="col-sm-12 controls"> <button type="submit" class="btn btn-success">Inloggen</button> @if(ViewData.ModelState.ContainsKey("registration")){ @ViewData.ModelState["registration"].Errors.First().ErrorMessage; } </div> </div> <div class="form-group"> <div class="col-md-12 control"> <div class="box-border"> Ik heb nog geen account! <a href="#" id="register-link"> Registreren. </a> </div> </div> </div> }
mit
C#
2387ea29b5052402792ef7f0a76000ec9ad187f7
Change attribute usage. Now it can be applied to field of any part apart from string.
lukyad/Eco
Eco/Attributes/ConverterAttribute.cs
Eco/Attributes/ConverterAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace Eco { /// <summary> /// Provides custom serialization (ToString and FromString) methods for the given field. /// /// Converter contract: /// The Converter type that is passed as an argument to the attribute's constructor /// should define the following two methods: /// public static string ToString(string format, object source); /// public static object FromString(string format, string source); /// /// Usage: /// Can be applied to a field of any type apart from String. /// /// Compatibility: /// Incompatible with the Id, Inline, ItemName, KnownTypes and Ref attributes and compatible with all others. /// </summary> [AttributeUsage(AttributeTargets.Field)] public class ConverterAttribute : Attribute { static readonly HashSet<Type> _incompatibleAttributeTypes = new HashSet<Type> { typeof(IdAttribute), typeof(InlineAttribute), typeof(ItemNameAttribute), typeof(KnownTypesAttribute), typeof(RefAttribute) }; public ConverterAttribute(Type converterType) : this(converterType, null) { } public ConverterAttribute(Type converterType, string format) { this.Type = converterType; this.Format = format; this.ToString = GetToStringMethod(converterType, format); this.FromString = GetFromStringMethod(converterType, format); } public Type Type { get; set; } public string Format { get; set; } public new Func<object, string> ToString { get; private set; } public Func<string, object> FromString { get; private set; } public void ValidateContext(FieldInfo context) { if (context.FieldType == typeof(string)) { throw new ConfigurationException( "{0} cannot be applied to {1}.{2}. Expected field of a non-String type", typeof(ChoiceAttribute).Name, context.DeclaringType.Name, context.Name ); } AttributeValidator.CheckAttributesCompatibility(context, _incompatibleAttributeTypes); } static Func<object, string> GetToStringMethod(Type converterType, string format) { MethodInfo toStringMethod = converterType.GetMethod("ToString", new[] { typeof(string), typeof(object) }); if (toStringMethod == null || toStringMethod.ReturnType != typeof(string)) ThrowMissingMethodException(converterType, "string ToString(string format, object source)"); return value => (string)toStringMethod.Invoke(null, new[] { format, value }); } static Func<string, object> GetFromStringMethod(Type converterType, string format) { MethodInfo fromStringMethod = converterType.GetMethod("FromString", new[] { typeof(string), typeof(string) }); if (fromStringMethod == null || fromStringMethod.ReturnType != typeof(object)) ThrowMissingMethodException(converterType, "object FromString(string format, string source)"); return str => fromStringMethod.Invoke(null, new[] { format, str }); } static void ThrowMissingMethodException(Type methodContainer, string methodSignature) { throw new ConfigurationException("{0} type doesn't have required method: {1}", methodContainer.Name, methodSignature); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace Eco { /// <summary> /// Provides custom serialization (ToString and FromString) methods for the given field. /// /// Converter contract: /// The Converter type that is passed as an argument to the attribute's constructor /// should define the following two methods: /// public static string ToString(string format, object source); /// public static object FromString(string format, string source); /// /// Usage: /// Can be applied to a field of any type including string. /// /// Compatibility: /// Incompatible with the Id, Inline, ItemName, KnownTypes and Ref attributes and compatible with all others. /// </summary> [AttributeUsage(AttributeTargets.Field)] public class ConverterAttribute : Attribute { public ConverterAttribute(Type converterType) : this(converterType, null) { } public ConverterAttribute(Type converterType, string format) { this.Type = converterType; this.Format = format; this.ToString = GetToStringMethod(converterType, format); this.FromString = GetFromStringMethod(converterType, format); } public Type Type { get; set; } public string Format { get; set; } public new Func<object, string> ToString { get; private set; } public Func<string, object> FromString { get; private set; } public void ValidateContext(FieldInfo context) { // do nothing } static Func<object, string> GetToStringMethod(Type converterType, string format) { MethodInfo toStringMethod = converterType.GetMethod("ToString", new[] { typeof(string), typeof(object) }); if (toStringMethod == null || toStringMethod.ReturnType != typeof(string)) ThrowMissingMethodException(converterType, "string ToString(string format, object source)"); return value => (string)toStringMethod.Invoke(null, new[] { format, value }); } static Func<string, object> GetFromStringMethod(Type converterType, string format) { MethodInfo fromStringMethod = converterType.GetMethod("FromString", new[] { typeof(string), typeof(string) }); if (fromStringMethod == null || fromStringMethod.ReturnType != typeof(object)) ThrowMissingMethodException(converterType, "object FromString(string format, string source)"); return str => fromStringMethod.Invoke(null, new[] { format, str }); } static void ThrowMissingMethodException(Type methodContainer, string methodSignature) { throw new ConfigurationException("{0} type doesn't have required method: {1}", methodContainer.Name, methodSignature); } } }
apache-2.0
C#
84ca49b1d17f34b9f4f7afadff8e8c7623d27593
Improve short time parsing
IvionSauce/MeidoBot
MeidoCommon/Parsing.cs
MeidoCommon/Parsing.cs
using System; using System.Text.RegularExpressions; namespace MeidoCommon.Parsing { public static class Parse { public static TimeSpan ShortTimeString(string shortTime) { if (shortTime == null) throw new ArgumentNullException(nameof(shortTime)); var timeRegexp = new Regex( @"^\s*([+-])?\s* (?:(\d*\.?\d+)h\s*)? (?:(\d*\.?\d+)m\s*)? (?:(\d*\.?\d+)s\s*)?$", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace ); var m = timeRegexp.Match(shortTime); var signGrp = m.Groups[1]; var hourGrp = m.Groups[2]; var minuteGrp = m.Groups[3]; var secondGrp = m.Groups[4]; double hours = 0; double minutes = 0; double seconds = 0; if (hourGrp.Success) hours = double.Parse(hourGrp.Value); if (minuteGrp.Success) minutes = double.Parse(minuteGrp.Value); if (secondGrp.Success) seconds = double.Parse(secondGrp.Value); var ts = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes) + TimeSpan.FromSeconds(seconds); if (signGrp.Value == "-") ts = TimeSpan.Zero - ts; return ts; } } }
using System; using System.Text.RegularExpressions; namespace MeidoCommon.Parsing { public static class Parse { public static TimeSpan ShortTimeString(string shortTime) { if (shortTime == null) throw new ArgumentNullException(nameof(shortTime)); var timeRegexp = new Regex(@"(?i)(\d*\.?\d+)([hms])"); double seconds = 0; double minutes = 0; double hours = 0; foreach (Match m in timeRegexp.Matches(shortTime)) { var amount = double.Parse(m.Groups[1].Value); var unit = m.Groups[2].Value; switch (unit) { case "s": seconds += amount; break; case "m": minutes += amount; break; case "h": hours += amount; break; } } return TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes) + TimeSpan.FromSeconds(seconds); } } }
bsd-2-clause
C#
3ff2bb5e6c7fe1520c7fbf609ce2ee9eb5e2e5b9
Make ShellProgressBar.Progress implement the IDisposable interface (#73)
Mpdreamz/shellprogressbar
src/ShellProgressBar/Progress.cs
src/ShellProgressBar/Progress.cs
using System; namespace ShellProgressBar { internal class Progress<T> : IProgress<T>, IDisposable { private readonly WeakReference<IProgressBar> _progressBar; private readonly Func<T, string> _message; private readonly Func<T, double?> _percentage; public Progress(IProgressBar progressBar, Func<T, string> message, Func<T, double?> percentage) { _progressBar = new WeakReference<IProgressBar>(progressBar); _message = message; _percentage = percentage ?? (value => value as double? ?? value as float?); } public void Report(T value) { if (!_progressBar.TryGetTarget(out var progressBar)) return; var message = _message?.Invoke(value); var percentage = _percentage(value); if (percentage.HasValue) progressBar.Tick((int)(percentage * progressBar.MaxTicks), message); else progressBar.Tick(message); } public void Dispose() { if (_progressBar.TryGetTarget(out var progressBar)) { progressBar.Dispose(); } } } }
using System; namespace ShellProgressBar { internal class Progress<T> : IProgress<T> { private readonly WeakReference<IProgressBar> _progressBar; private readonly Func<T, string> _message; private readonly Func<T, double?> _percentage; public Progress(IProgressBar progressBar, Func<T, string> message, Func<T, double?> percentage) { _progressBar = new WeakReference<IProgressBar>(progressBar); _message = message; _percentage = percentage ?? (value => value as double? ?? value as float?); } public void Report(T value) { if (!_progressBar.TryGetTarget(out var progressBar)) return; var message = _message?.Invoke(value); var percentage = _percentage(value); if (percentage.HasValue) progressBar.Tick((int)(percentage * progressBar.MaxTicks), message); else progressBar.Tick(message); } } }
mit
C#
91fe2beac59a4cc3c257d6c45f102114c3e6e7a1
Update SockJSOptions.JSClientLibraryUrl to 1.0.1
tmds/Tmds.SockJS,tmds/Tmds.SockJS
src/Tmds.SockJS/SockJSOptions.cs
src/Tmds.SockJS/SockJSOptions.cs
// Copyright (C) 2015 Tom Deseyn // Licensed under GNU LGPL, Version 2.1. See LICENSE in the project root for license information. using Microsoft.AspNet.Http; using System; namespace Tmds.SockJS { public class SockJSOptions { public SockJSOptions() { JSClientLibraryUrl = "http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"; MaxResponseLength = 128 * 1024; UseWebSocket = true; SetJSessionIDCookie = false; HeartbeatInterval = TimeSpan.FromSeconds(25); DisconnectTimeout = TimeSpan.FromSeconds(50); RewritePath = null; } public string JSClientLibraryUrl { get; set; } public int MaxResponseLength{ get; set; } public bool UseWebSocket { get; set; } public bool SetJSessionIDCookie { get; set; } public TimeSpan HeartbeatInterval { get; set; } public TimeSpan DisconnectTimeout { get; set; } public PathString RewritePath { get; set; } } }
// Copyright (C) 2015 Tom Deseyn // Licensed under GNU LGPL, Version 2.1. See LICENSE in the project root for license information. using Microsoft.AspNet.Http; using System; namespace Tmds.SockJS { public class SockJSOptions { public SockJSOptions() { JSClientLibraryUrl = "http://cdn.jsdelivr.net/sockjs/0.3.4/sockjs.min.js"; MaxResponseLength = 128 * 1024; UseWebSocket = true; SetJSessionIDCookie = false; HeartbeatInterval = TimeSpan.FromSeconds(25); DisconnectTimeout = TimeSpan.FromSeconds(50); RewritePath = null; } public string JSClientLibraryUrl { get; set; } public int MaxResponseLength{ get; set; } public bool UseWebSocket { get; set; } public bool SetJSessionIDCookie { get; set; } public TimeSpan HeartbeatInterval { get; set; } public TimeSpan DisconnectTimeout { get; set; } public PathString RewritePath { get; set; } } }
mit
C#
6e7769890452cea44304d9e9b5bb5b903e2b3249
Update ITagCache registration (#5828)
stevetayloruk/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2
src/OrchardCore/OrchardCore.Infrastructure/Cache/OrchardCoreBuilderExtensions.cs
src/OrchardCore/OrchardCore.Infrastructure/Cache/OrchardCoreBuilderExtensions.cs
using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using OrchardCore.Environment.Cache; using OrchardCore.Environment.Cache.CacheContextProviders; using OrchardCore.Infrastructure.Cache; namespace Microsoft.Extensions.DependencyInjection { public static partial class OrchardCoreBuilderExtensions { /// <summary> /// Adds tenant level caching services. /// </summary> public static OrchardCoreBuilder AddCaching(this OrchardCoreBuilder builder) { builder.ConfigureServices(services => { services.AddScoped<ITagCache, DefaultTagCache>(); services.AddSingleton<ISignal, Signal>(); services.AddScoped<ICacheContextManager, CacheContextManager>(); services.AddScoped<ICacheScopeManager, CacheScopeManager>(); services.AddScoped<ICacheContextProvider, FeaturesCacheContextProvider>(); services.AddScoped<ICacheContextProvider, QueryCacheContextProvider>(); services.AddScoped<ICacheContextProvider, RolesCacheContextProvider>(); services.AddScoped<ICacheContextProvider, RouteCacheContextProvider>(); services.AddScoped<ICacheContextProvider, UserCacheContextProvider>(); services.AddScoped<ICacheContextProvider, KnownValueCacheContextProvider>(); // IMemoryCache is registered at the tenant level so that there is one instance for each tenant. services.AddSingleton<IMemoryCache, MemoryCache>(); // MemoryDistributedCache needs to be registered as a singleton as it owns a MemoryCache instance. services.AddSingleton<IDistributedCache, MemoryDistributedCache>(); // Provides a distributed cache service that can return existing references in the current scope. services.AddScoped<IScopedDistributedCache, ScopedDistributedCache>(); }); return builder; } } }
using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using OrchardCore.Environment.Cache; using OrchardCore.Environment.Cache.CacheContextProviders; using OrchardCore.Infrastructure.Cache; namespace Microsoft.Extensions.DependencyInjection { public static partial class OrchardCoreBuilderExtensions { /// <summary> /// Adds tenant level caching services. /// </summary> public static OrchardCoreBuilder AddCaching(this OrchardCoreBuilder builder) { builder.ConfigureServices(services => { services.AddTransient<ITagCache, DefaultTagCache>(); services.AddSingleton<ISignal, Signal>(); services.AddScoped<ICacheContextManager, CacheContextManager>(); services.AddScoped<ICacheScopeManager, CacheScopeManager>(); services.AddScoped<ICacheContextProvider, FeaturesCacheContextProvider>(); services.AddScoped<ICacheContextProvider, QueryCacheContextProvider>(); services.AddScoped<ICacheContextProvider, RolesCacheContextProvider>(); services.AddScoped<ICacheContextProvider, RouteCacheContextProvider>(); services.AddScoped<ICacheContextProvider, UserCacheContextProvider>(); services.AddScoped<ICacheContextProvider, KnownValueCacheContextProvider>(); // IMemoryCache is registered at the tenant level so that there is one instance for each tenant. services.AddSingleton<IMemoryCache, MemoryCache>(); // MemoryDistributedCache needs to be registered as a singleton as it owns a MemoryCache instance. services.AddSingleton<IDistributedCache, MemoryDistributedCache>(); // Provides a distributed cache service that can return existing references in the current scope. services.AddScoped<IScopedDistributedCache, ScopedDistributedCache>(); }); return builder; } } }
bsd-3-clause
C#
39064952dc7274b0e2b18ad04d082d9ef791ca7b
Change error page style.
LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform
src/CompetitionPlatform/Views/Shared/CreateClosed.cshtml
src/CompetitionPlatform/Views/Shared/CreateClosed.cshtml
@{ ViewData["Title"] = "Access Denied"; } <br> <br> <br> <div class="container"> <h2 class="text-danger">Creating projects is unavailable.</h2> <p> The Function "сreating project" is only available for lykke community members with an approved KYC Status. </p> </div>
@{ ViewData["Title"] = "Access Denied"; } <div class="container"> <h2 class="text-danger">Creating projects is unavailable.</h2> <p> The Function "сreating project" is only available for lykke community members with an approved KYC Status. </p> </div>
mit
C#
c17401dfb7198c64359181d712b6128f24de403f
Allow alternate streams to be passed (#37)
a9upam/monotouch-samples,hongnguyenpro/monotouch-samples,peteryule/monotouch-samples,W3SS/monotouch-samples,YOTOV-LIMITED/monotouch-samples,iFreedive/monotouch-samples,W3SS/monotouch-samples,andypaul/monotouch-samples,sakthivelnagarajan/monotouch-samples,nelzomal/monotouch-samples,YOTOV-LIMITED/monotouch-samples,haithemaraissia/monotouch-samples,YOTOV-LIMITED/monotouch-samples,nelzomal/monotouch-samples,hongnguyenpro/monotouch-samples,nervevau2/monotouch-samples,haithemaraissia/monotouch-samples,nervevau2/monotouch-samples,nelzomal/monotouch-samples,W3SS/monotouch-samples,albertoms/monotouch-samples,labdogg1003/monotouch-samples,andypaul/monotouch-samples,markradacz/monotouch-samples,a9upam/monotouch-samples,kingyond/monotouch-samples,andypaul/monotouch-samples,davidrynn/monotouch-samples,kingyond/monotouch-samples,nervevau2/monotouch-samples,nervevau2/monotouch-samples,a9upam/monotouch-samples,labdogg1003/monotouch-samples,kingyond/monotouch-samples,markradacz/monotouch-samples,haithemaraissia/monotouch-samples,robinlaide/monotouch-samples,albertoms/monotouch-samples,xamarin/monotouch-samples,labdogg1003/monotouch-samples,sakthivelnagarajan/monotouch-samples,haithemaraissia/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,davidrynn/monotouch-samples,robinlaide/monotouch-samples,iFreedive/monotouch-samples,xamarin/monotouch-samples,davidrynn/monotouch-samples,sakthivelnagarajan/monotouch-samples,nelzomal/monotouch-samples,robinlaide/monotouch-samples,peteryule/monotouch-samples,andypaul/monotouch-samples,peteryule/monotouch-samples,hongnguyenpro/monotouch-samples,a9upam/monotouch-samples,peteryule/monotouch-samples,albertoms/monotouch-samples,YOTOV-LIMITED/monotouch-samples,xamarin/monotouch-samples,hongnguyenpro/monotouch-samples,davidrynn/monotouch-samples,markradacz/monotouch-samples
StreamingAudio/MainViewController.cs
StreamingAudio/MainViewController.cs
using System; using MonoTouch.UIKit; namespace StreamingAudio { public enum PlayerOption { Stream = 0, StreamAndSave } public partial class MainViewController : UIViewController { private const string LetsStopTheWarUrl = "http://ccmixter.org/content/bradstanfield/bradstanfield_-_People_Let_s_Stop_The_War.mp3"; public MainViewController() : base("MainViewController", null) { } public override void ViewDidLoad() { base.ViewDidLoad(); Title = "Streaming MP3"; streamAndPlayButton.TouchUpInside += (sender, e) => OpenPlayerView(PlayerOption.Stream); streamSaveAndPlayButton.TouchUpInside += (sender, e) => OpenPlayerView(PlayerOption.StreamAndSave); urlTextbox.Text = LetsStopTheWarUrl; urlTextbox.EditingDidEnd += (sender, e) => { urlTextbox.ResignFirstResponder(); }; } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); statusLabel.Text = string.Empty; } private void OpenPlayerView(PlayerOption option) { statusLabel.Text = "Starting HTTP request"; var url = string.IsNullOrEmpty(urlTextbox.Text) ? LetsStopTheWarUrl : urlTextbox.Text; var playerViewController = new PlayerViewController(option, url); playerViewController.ErrorOccurred += HandleError; NavigationController.PushViewController(playerViewController, true); } private void HandleError(string message) { InvokeOnMainThread(delegate { statusLabel.Text = message; }); } } }
using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace StreamingAudio { public enum PlayerOption { Stream = 0, StreamAndSave } public partial class MainViewController : UIViewController { private const string LetsStopTheWarUrl = "http://ccmixter.org/content/bradstanfield/bradstanfield_-_People_Let_s_Stop_The_War.mp3"; public MainViewController () : base ("MainViewController", null) { } public override void ViewDidLoad () { base.ViewDidLoad (); Title = "Streaming MP3"; streamAndPlayButton.TouchUpInside += (sender, e) => OpenPlayerView(PlayerOption.Stream); streamSaveAndPlayButton.TouchUpInside += (sender, e) => OpenPlayerView(PlayerOption.StreamAndSave); urlTextbox.Text = LetsStopTheWarUrl; urlTextbox.EditingDidEnd += (sender, e) => urlTextbox.ResignFirstResponder (); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); statusLabel.Text = string.Empty; } private void OpenPlayerView(PlayerOption option) { statusLabel.Text = "Starting HTTP request"; var playerViewController = new PlayerViewController (option, LetsStopTheWarUrl); playerViewController.ErrorOccurred += HandleError; NavigationController.PushViewController (playerViewController, true); } private void HandleError(string message) { InvokeOnMainThread (delegate { statusLabel.Text = message; }); } } }
mit
C#
c9963529c7b60bc2beca5b8b2bd9486a0a50cd50
Add scaffolding for skipping ease-in
makerslocal/LudumDare38
bees-in-the-trap/Assets/Scripts/MainCamera.cs
bees-in-the-trap/Assets/Scripts/MainCamera.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainCamera : MonoBehaviour { public GameObject cursor; private IEnumerator currentMove; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //this.transform.position.z = -10; //NO } public void scootTo(Vector3 endpos) { double time = .6; bool skipEaseIn = false; if (currentMove != null) { //if we're moving, fuck that StopCoroutine (currentMove); skipEaseIn = true; } Debug.Log ("Scoot TO:"); Debug.Log(endpos); currentMove = SmoothMove (this.transform.position, endpos, time, skipEaseIn); StartCoroutine (currentMove); } IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, double seconds, bool skipEaseIn = false) { double t = 0.0; if (skipEaseIn) { //DO SOMETHING??? //t = 0.1; } endpos.z = this.transform.position.z; //NEVER move forward or backward (Hack because we are in 2D) while ( t <= 1.0 ) { t += Time.deltaTime/seconds; transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep((float) 0.0, (float) 1.0, (float) t)); yield return null; //WHY } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainCamera : MonoBehaviour { public GameObject cursor; private IEnumerator currentMove; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //this.transform.position.z = -10; //NO } public void scootTo(Vector3 endpos) { if (currentMove != null) { //if we're moving, fuck that StopCoroutine (currentMove); } Debug.Log ("Scoot TO:"); Debug.Log(endpos); currentMove = SmoothMove (this.transform.position, endpos, 5.0); StartCoroutine (currentMove); } IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, double seconds) { double t = 0.0; endpos.z = this.transform.position.z; //NEVER move forward or backward (Hack because we are in 2D) while ( t <= 1.0 ) { //Debug.Log ("t=" + t); t += Time.deltaTime/seconds; transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep((float) 0.0, (float) 1.0, (float) t)); //Debug.Log (transform.position); yield return null; //WHY } } }
mit
C#
d76681aa825ac01d17a45c393f09163ce3c3dce3
use IApplicableToBeatmap instead of IApplicableToRulesetContainer
DrabWeb/osu,DrabWeb/osu,ppy/osu,ZLima12/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,johnneijzen/osu,peppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,2yangk23/osu,DrabWeb/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,EVAST9919/osu,ZLima12/osu,smoogipooo/osu,NeoAdonis/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu
osu.Game/Rulesets/Mods/ModWindUp.cs
osu.Game/Rulesets/Mods/ModWindUp.cs
using System; using System.Collections.Generic; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Configuration; using osu.Framework.Timing; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Rulesets.Mods { public abstract class ModWindUp : Mod { public override string Name => "Wind Up"; public override string Acronym => "WU"; public override ModType Type => ModType.Fun; public override FontAwesome Icon => FontAwesome.fa_chevron_circle_up; public override string Description => "Crank it up!"; public override double ScoreMultiplier => 1; public override Type[] IncompatibleMods => new[] { typeof(ModDoubleTime), typeof(ModHalfTime) }; public abstract double AppendRate { get; } } public abstract class ModWindUp<T> : ModWindUp, IUpdatableByPlayfield, IApplicableToClock, IApplicableToBeatmap<T> where T : HitObject { private double LastObjectEndTime; private IAdjustableClock Clock; private IHasPitchAdjust ClockAdjust; public override double AppendRate => 0.5; public virtual void ApplyToClock(IAdjustableClock clock) { Clock = clock; ClockAdjust = clock as IHasPitchAdjust; } public virtual void ApplyToBeatmap(Beatmap<T> beatmap) { HitObject LastObject = beatmap.HitObjects[beatmap.HitObjects.Count - 1]; LastObjectEndTime = (LastObject as IHasEndTime)?.EndTime ?? LastObject?.StartTime ?? 0; } public virtual void Update(Playfield playfield) { double newRate = 1 + (AppendRate * (Clock.CurrentTime / LastObjectEndTime)); Clock.Rate = newRate; ClockAdjust.PitchAdjust = newRate; } } }
using System; using System.Collections.Generic; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Configuration; using osu.Framework.Timing; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Mods { public abstract class ModWindUp : Mod { public override string Name => "Wind Up"; public override string Acronym => "WU"; public override ModType Type => ModType.Fun; public override FontAwesome Icon => FontAwesome.fa_chevron_circle_up; public override string Description => "Crank it up!"; public override double ScoreMultiplier => 1; public override Type[] IncompatibleMods => new[] { typeof(ModDoubleTime), typeof(ModHalfTime) }; public abstract double AppendRate { get; } } public class ModWindUp<T> : ModWindUp, IUpdatableByPlayfield, IApplicableToClock, IApplicableToRulesetContainer<T> where T : HitObject { private Track Track; private IAdjustableClock Clock; private IHasPitchAdjust ClockAdjust; public override double AppendRate => 0.5; public virtual void ApplyToClock(IAdjustableClock clock) { Clock = clock; ClockAdjust = clock as IHasPitchAdjust; } public virtual void ApplyToRulesetContainer(RulesetContainer<T> ruleset) { Track = ruleset.WorkingBeatmap.Track; } public virtual void Update(Playfield playfield) { double newRate = 1 + (AppendRate * (Track.CurrentTime / Track.Length)); Clock.Rate = newRate; ClockAdjust.PitchAdjust = newRate; } } }
mit
C#
235c0ed620e4525b78fcc7a7e03a956092c1f9e1
Set default for Reminder mapping to 'JustUpcoming'.
aluxnimm/outlookcaldavsynchronizer
CalDavSynchronizer/Contracts/EventMappingConfiguration.cs
CalDavSynchronizer/Contracts/EventMappingConfiguration.cs
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Security.Cryptography; using System.Text; using System.Xml.Serialization; using CalDavSynchronizer.Implementation; using CalDavSynchronizer.Ui; namespace CalDavSynchronizer.Contracts { public class EventMappingConfiguration : MappingConfigurationBase { public ReminderMapping MapReminder { get; set; } public bool MapAttendees { get; set; } public bool MapBody { get; set; } public EventMappingConfiguration () { MapReminder = ReminderMapping.JustUpcoming; MapAttendees = true; MapBody = true; } public override IConfigurationForm<MappingConfigurationBase> CreateConfigurationForm (IConfigurationFormFactory factory) { return factory.Create (this); } } }
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Security.Cryptography; using System.Text; using System.Xml.Serialization; using CalDavSynchronizer.Implementation; using CalDavSynchronizer.Ui; namespace CalDavSynchronizer.Contracts { public class EventMappingConfiguration : MappingConfigurationBase { public ReminderMapping MapReminder { get; set; } public bool MapAttendees { get; set; } public bool MapBody { get; set; } public EventMappingConfiguration () { MapReminder = ReminderMapping.@true; MapAttendees = true; MapBody = true; } public override IConfigurationForm<MappingConfigurationBase> CreateConfigurationForm (IConfigurationFormFactory factory) { return factory.Create (this); } } }
agpl-3.0
C#
5b96f734175c5f94db1c2095fd2f6596e943e071
Set AssemblyInfo for PlaceAutocompleteTest.
mklimmasch/google-maps,yonglehou/google-maps,maximn/google-maps,yonglehou/google-maps,maximn/google-maps,mklimmasch/google-maps
GoogleMapsApi.PlaceAutocompleteTest/Properties/AssemblyInfo.cs
GoogleMapsApi.PlaceAutocompleteTest/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("GoogleMapsApi.PlaceAutocompleteTest")] [assembly: AssemblyDescription("Google Place Autocomplete API test/demonstration tool")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("google-maps")] [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("767feaa1-e2f9-4d70-9e96-0a4c46cdae85")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GoogleMapsApi.PlaceAutocompleteTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("GoogleMapsApi.PlaceAutocompleteTest")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("767feaa1-e2f9-4d70-9e96-0a4c46cdae85")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bsd-2-clause
C#
f30df1dcb0f919da3e8a3c6cbae763b73acffc3a
Fix emailVote issue in case UserDetails is not yet saved.
enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api
Infopulse.EDemocracy.Data/Repositories/UserDetailRepository.cs
Infopulse.EDemocracy.Data/Repositories/UserDetailRepository.cs
using System; using Infopulse.EDemocracy.Data.Interfaces; using Infopulse.EDemocracy.Model; using System.Data; using System.Data.Entity; using System.Data.SqlClient; using System.Linq; namespace Infopulse.EDemocracy.Data.Repositories { public class UserDetailRepository : BaseRepository, IUserDetailRepository { public int GetUserId(string userEmail) { using (var db = new EDEntities()) { var userID = db.Database.SqlQuery<int>( "sp_User_GetIdByEmail @UserEmail", new SqlParameter() { ParameterName = "UserEmail", DbType = DbType.String, Value = userEmail, Direction = ParameterDirection.Input }); return userID.SingleOrDefault(); } } public UserDetail Update(UserDetail user) { using (var db = new EDEntities()) { var userDetailFromDb = db.UserDetails.SingleOrDefault(ud => ud.UserID == user.UserID); if (userDetailFromDb == null) { user.CreatedBy = this.UnknownAppUser; user.CreatedDate = DateTime.UtcNow; db.UserDetails.Add(user); } else { user.ID = userDetailFromDb.ID; var entry = db.Entry(userDetailFromDb); entry.CurrentValues.SetValues(user); entry.Property(u => u.CreatedBy).IsModified = false; entry.Property(u => u.CreatedDate).IsModified = false; } db.SaveChanges(); return db.UserDetails.SingleOrDefault(ud => ud.ID == user.ID); } } } }
using Infopulse.EDemocracy.Data.Interfaces; using Infopulse.EDemocracy.Model; using System.Data; using System.Data.Entity; using System.Data.SqlClient; using System.Linq; namespace Infopulse.EDemocracy.Data.Repositories { public class UserDetailRepository : IUserDetailRepository { public int GetUserId(string userEmail) { using (var db = new EDEntities()) { var userID = db.Database.SqlQuery<int>( "sp_User_GetIdByEmail @UserEmail", new SqlParameter() { ParameterName = "UserEmail", DbType = DbType.String, Value = userEmail, Direction = ParameterDirection.Input }); return userID.SingleOrDefault(); } } public UserDetail Update(UserDetail user) { using (var db = new EDEntities()) { var userDetailFromDb = db.UserDetails.SingleOrDefault(ud => ud.UserID == user.UserID); user.ID = userDetailFromDb.ID; var entry = db.Entry(userDetailFromDb); entry.CurrentValues.SetValues(user); entry.Property(u => u.CreatedBy).IsModified = false; entry.Property(u => u.CreatedDate).IsModified = false; db.SaveChanges(); return db.UserDetails.SingleOrDefault(ud => ud.ID == user.ID); } } } }
cc0-1.0
C#
47a208ec048693838a384b3ee253f112a2623f69
Add Win/Lose Scene Transition Hooks
ludimation/Winter,ludimation/Winter,ludimation/Winter
Winter/Assets/Scripts/GUIBehavior.cs
Winter/Assets/Scripts/GUIBehavior.cs
using UnityEngine; using System.Collections; public class GUIBehavior : MonoBehaviour { public Texture barTexture; public wolf wolfData; public int boxWidth = 34; public int boxHeight = 30; void OnGUI () { //Print the bar GUI.Box (new Rect(Screen.width - barTexture.width - 18,10,barTexture.width + 8, barTexture.height + 8),barTexture); //Print the box GUI.Box (new Rect(Screen.width - barTexture.width / 2 - 14 - boxWidth / 2 , 8f + .97f * barTexture.height * (100f - wolfData.GetTemp()) / 100f,boxWidth,boxHeight), ""); } void Update () { if(Input.GetKey ("t")) { // TRIGGER THE WIN SCENE print ("STUFF"); } else if (Input.GetKey ("g")) { // TRIGGER THE LOSE SCENE print ("LOSE"); } } }
using UnityEngine; using System.Collections; public class GUIBehavior : MonoBehaviour { public Texture barTexture; public wolf wolfData; public int boxWidth = 34; public int boxHeight = 30; void OnGUI () { //Print the bar GUI.Box (new Rect(Screen.width - barTexture.width - 18,10,barTexture.width + 8, barTexture.height + 8),barTexture); //Print the box GUI.Box (new Rect(Screen.width - barTexture.width / 2 - 14 - boxWidth / 2 , 8f + .97f * barTexture.height * (100f - wolfData.GetTemp()) / 100f,boxWidth,boxHeight), ""); } }
mit
C#
f0774786c0b634d493cb98f041ee8aab39f5c3f1
return null in Material.FromImage if textures are not found
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
Bindings/Portable/Material.cs
Bindings/Portable/Material.cs
namespace Urho { partial class Material { public static Material FromImage(string image, string normals) { if (string.IsNullOrEmpty(normals)) return FromImage(image); var cache = Application.Current.ResourceCache; var diff = cache.GetTexture2D(image); if (diff == null) return null; var normal = cache.GetTexture2D(normals); if (normal == null) return FromImage(image); var material = new Material(); material.SetTexture(TextureUnit.Diffuse, diff); material.SetTexture(TextureUnit.Normal, normal); material.SetTechnique(0, CoreAssets.Techniques.DiffNormal, 0, 0); return material; } public static Material FromImage(string image) { var cache = Application.Current.ResourceCache; var diff = cache.GetTexture2D(image); if (diff == null) return null; var material = new Material(); material.SetTexture(TextureUnit.Diffuse, diff); material.SetTechnique(0, CoreAssets.Techniques.Diff, 0, 0); return material; } public static Material FromColor(Color color) { return FromColor(color, false); } public static Material FromColor(Color color, bool unlit) { var material = new Material(); var cache = Application.Current.ResourceCache; if (unlit) material.SetTechnique(0, color.A == 1 ? CoreAssets.Techniques.NoTextureUnlit : CoreAssets.Techniques.NoTextureUnlitAlpha, 1, 1); else material.SetTechnique(0, color.A == 1 ? CoreAssets.Techniques.NoTexture : CoreAssets.Techniques.NoTextureAlpha, 1, 1); material.SetShaderParameter("MatDiffColor", color); return material; } public static Material SkyboxFromImages( string imagePositiveX, string imageNegativeX, string imagePositiveY, string imageNegativeY, string imagePositiveZ, string imageNegativeZ) { var cache = Application.Current.ResourceCache; var material = new Material(); TextureCube cube = new TextureCube(); cube.SetData(CubeMapFace.PositiveX, cache.GetFile(imagePositiveX, false)); cube.SetData(CubeMapFace.NegativeX, cache.GetFile(imageNegativeX, false)); cube.SetData(CubeMapFace.PositiveY, cache.GetFile(imagePositiveY, false)); cube.SetData(CubeMapFace.NegativeY, cache.GetFile(imageNegativeY, false)); cube.SetData(CubeMapFace.PositiveZ, cache.GetFile(imagePositiveZ, false)); cube.SetData(CubeMapFace.NegativeZ, cache.GetFile(imageNegativeZ, false)); material.SetTexture(TextureUnit.Diffuse, cube); material.SetTechnique(0, CoreAssets.Techniques.DiffSkybox, 0, 0); material.CullMode = CullMode.None; return material; } public static Material SkyboxFromImage(string image) { return SkyboxFromImages(image, image, image, image, image, image); } } }
namespace Urho { partial class Material { public static Material FromImage(string image, string normals) { if (string.IsNullOrEmpty(normals)) return FromImage(image); var cache = Application.Current.ResourceCache; var material = new Material(); material.SetTexture(TextureUnit.Diffuse, cache.GetTexture2D(image)); material.SetTexture(TextureUnit.Normal, cache.GetTexture2D(normals)); material.SetTechnique(0, CoreAssets.Techniques.DiffNormal, 0, 0); return material; } public static Material FromImage(string image) { var cache = Application.Current.ResourceCache; var material = new Material(); material.SetTexture(TextureUnit.Diffuse, cache.GetTexture2D(image)); material.SetTechnique(0, CoreAssets.Techniques.Diff, 0, 0); return material; } public static Material FromColor(Color color) { return FromColor(color, false); } public static Material FromColor(Color color, bool unlit) { var material = new Material(); var cache = Application.Current.ResourceCache; if (unlit) material.SetTechnique(0, color.A == 1 ? CoreAssets.Techniques.NoTextureUnlit : CoreAssets.Techniques.NoTextureUnlitAlpha, 1, 1); else material.SetTechnique(0, color.A == 1 ? CoreAssets.Techniques.NoTexture : CoreAssets.Techniques.NoTextureAlpha, 1, 1); material.SetShaderParameter("MatDiffColor", color); return material; } public static Material SkyboxFromImages( string imagePositiveX, string imageNegativeX, string imagePositiveY, string imageNegativeY, string imagePositiveZ, string imageNegativeZ) { var cache = Application.Current.ResourceCache; var material = new Material(); TextureCube cube = new TextureCube(); cube.SetData(CubeMapFace.PositiveX, cache.GetFile(imagePositiveX, false)); cube.SetData(CubeMapFace.NegativeX, cache.GetFile(imageNegativeX, false)); cube.SetData(CubeMapFace.PositiveY, cache.GetFile(imagePositiveY, false)); cube.SetData(CubeMapFace.NegativeY, cache.GetFile(imageNegativeY, false)); cube.SetData(CubeMapFace.PositiveZ, cache.GetFile(imagePositiveZ, false)); cube.SetData(CubeMapFace.NegativeZ, cache.GetFile(imageNegativeZ, false)); material.SetTexture(TextureUnit.Diffuse, cube); material.SetTechnique(0, CoreAssets.Techniques.DiffSkybox, 0, 0); material.CullMode = CullMode.None; return material; } public static Material SkyboxFromImage(string image) { return SkyboxFromImages(image, image, image, image, image, image); } } }
mit
C#
28db07c69ae5ed779736b8c20157840180139a14
fix already simplified
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Upgrades/Upgrade_20211109_SimplifyNamespaces.cs
Signum.Upgrade/Upgrades/Upgrade_20211109_SimplifyNamespaces.cs
using Signum.Utilities; namespace Signum.Upgrade.Upgrades; class Upgrade_20211109_SimplifyNamespaces : CodeUpgradeBase { public override string Description => "Uses file-scoped namespaces declarations to recover ident space"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile(@"*.cs", file => { file.WarningLevel = WarningLevel.Warning; file.ProcessLines(lines => { var index = lines.FindIndex(a => a.StartsWith("namespace ")); if (index == -1) { file.Warning($"File {file.FilePath} has no namespace ?!?"); return false; } if (lines[index].EndsWith(";")) { file.Warning($"File {file.FilePath} already simplified"); return false; } var ns = lines[index].After("namespace "); var startIndex = lines.FindIndex(index, a => a.Trim() == "{"); var endIndex = lines.FindLastIndex(a => a.Trim() == "}"); if (startIndex == -1 || endIndex == -1) { file.Warning($"File {file.FilePath} has no namespace ?!?"); return false; } for (int i = startIndex +1; i < endIndex; i++) { var line = lines[i]; lines[i] = line.StartsWith("\t") ? line.Substring(1) : line.StartsWith(" ") ? line.Substring(4) : line; } lines[index] = "namespace " + ns + ";"; lines[startIndex] = ""; lines.RemoveAt(endIndex); return true; }); }); } }
using Signum.Utilities; namespace Signum.Upgrade.Upgrades; class Upgrade_20211109_SimplifyNamespaces : CodeUpgradeBase { public override string Description => "Uses file-scoped namespaces declarations to recover ident space"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile(@"*.cs", file => { file.WarningLevel = WarningLevel.Warning; file.ProcessLines(lines => { var index = lines.FindIndex(a => a.StartsWith("namespace ")); if (index == -1) { file.Warning($"File {file.FilePath} has no namespace ?!?"); return false; } var ns = lines[index].After("namespace "); var startIndex = lines.FindIndex(index, a => a.Trim() == "{"); var endIndex = lines.FindLastIndex(a => a.Trim() == "}"); if (startIndex == -1 || endIndex == -1) { file.Warning($"File {file.FilePath} has no namespace ?!?"); return false; } for (int i = startIndex +1; i < endIndex; i++) { var line = lines[i]; lines[i] = line.StartsWith("\t") ? line.Substring(1) : line.StartsWith(" ") ? line.Substring(4) : line; } lines[index] = "namespace " + ns + ";"; lines[startIndex] = ""; lines.RemoveAt(endIndex); return true; }); }); } }
mit
C#
e1bafea1fb2bb9da50ea39abc5aba68ede2b115a
Apply swap via deconstructor
peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework.Android/Graphics/Textures/AndroidTextureLoaderStore.cs
osu.Framework.Android/Graphics/Textures/AndroidTextureLoaderStore.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using Android.Graphics; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using SixLabors.ImageSharp; namespace osu.Framework.Android.Graphics.Textures { internal class AndroidTextureLoaderStore : TextureLoaderStore { public AndroidTextureLoaderStore(IResourceStore<byte[]> store) : base(store) { } protected override Image<TPixel> ImageFromStream<TPixel>(Stream stream) { using (var bitmap = BitmapFactory.DecodeStream(stream)) { int[] pixels = new int[bitmap.Width * bitmap.Height]; bitmap.GetPixels(pixels, 0, bitmap.Width, 0, 0, bitmap.Width, bitmap.Height); byte[] result = new byte[pixels.Length * sizeof(int)]; Buffer.BlockCopy(pixels, 0, result, 0, result.Length); for (int i = 0; i < pixels.Length; i++) { (result[i * 4], result[i * 4 + 2]) = (result[i * 4 + 2], result[i * 4]); } bitmap.Recycle(); return Image.LoadPixelData<TPixel>(result, bitmap.Width, bitmap.Height); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using Android.Graphics; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using SixLabors.ImageSharp; namespace osu.Framework.Android.Graphics.Textures { internal class AndroidTextureLoaderStore : TextureLoaderStore { public AndroidTextureLoaderStore(IResourceStore<byte[]> store) : base(store) { } protected override Image<TPixel> ImageFromStream<TPixel>(Stream stream) { using (var bitmap = BitmapFactory.DecodeStream(stream)) { int[] pixels = new int[bitmap.Width * bitmap.Height]; bitmap.GetPixels(pixels, 0, bitmap.Width, 0, 0, bitmap.Width, bitmap.Height); byte[] result = new byte[pixels.Length * sizeof(int)]; Buffer.BlockCopy(pixels, 0, result, 0, result.Length); for (int i = 0; i < pixels.Length; i++) { byte b = result[i * 4]; result[i * 4] = result[i * 4 + 2]; result[i * 4 + 2] = b; } bitmap.Recycle(); return Image.LoadPixelData<TPixel>(result, bitmap.Width, bitmap.Height); } } } }
mit
C#
8ed7449b9333812c8edef1052af1d32e58dc8cd2
Convert timestamp to UTC.
bitstadium/HockeySDK-Windows,ChristopheLav/HockeySDK-Windows,dkackman/HockeySDK-Windows
Src/Core.Shared/Extensibility/Implementation/Telemetry.cs
Src/Core.Shared/Extensibility/Implementation/Telemetry.cs
namespace Microsoft.HockeyApp.Extensibility.Implementation { using System.Globalization; using Channel; using DataContracts; // TODO: Move Telemetry class to DataContracts namespace for discoverability. internal static class Telemetry { public static void WriteEnvelopeProperties(this ITelemetry telemetry, IJsonWriter json) { json.WriteProperty("time", telemetry.Timestamp.UtcDateTime.ToString("o", CultureInfo.InvariantCulture)); json.WriteProperty("seq", telemetry.Sequence); ((IJsonSerializable)telemetry.Context).Serialize(json); } public static void WriteTelemetryName(this ITelemetry telemetry, IJsonWriter json, string telemetryName) { // A different event name prefix is sent for normal mode and developer mode. bool isDevMode = false; string devModeProperty; var telemetryWithProperties = telemetry as ISupportProperties; if (telemetryWithProperties != null && telemetryWithProperties.Properties.TryGetValue("DeveloperMode", out devModeProperty)) { bool.TryParse(devModeProperty, out isDevMode); } // Format the event name using the following format: // Microsoft.[ProductName].[Dev].<normalized-instrumentation-key>.<event-type> var eventName = string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}{1}{2}", isDevMode ? Constants.DevModeTelemetryNamePrefix : Constants.TelemetryNamePrefix, NormalizeInstrumentationKey(telemetry.Context.InstrumentationKey), telemetryName); json.WriteProperty("name", eventName); } /// <summary> /// Normalize instrumentation key by removing dashes ('-') and making string in the lowercase. /// In case no InstrumentationKey is available just return empty string. /// In case when InstrumentationKey is available return normalized key + dot ('.') /// as a separator between instrumentation key part and telemetry name part. /// </summary> private static string NormalizeInstrumentationKey(string instrumentationKey) { if (instrumentationKey.IsNullOrWhiteSpace()) { return string.Empty; } return instrumentationKey.Replace("-", string.Empty).ToLowerInvariant() + "."; } } }
namespace Microsoft.HockeyApp.Extensibility.Implementation { using Channel; using DataContracts; // TODO: Move Telemetry class to DataContracts namespace for discoverability. internal static class Telemetry { public static void WriteEnvelopeProperties(this ITelemetry telemetry, IJsonWriter json) { json.WriteProperty("time", telemetry.Timestamp.ToString("o", System.Globalization.CultureInfo.InvariantCulture)); json.WriteProperty("seq", telemetry.Sequence); ((IJsonSerializable)telemetry.Context).Serialize(json); } public static void WriteTelemetryName(this ITelemetry telemetry, IJsonWriter json, string telemetryName) { // A different event name prefix is sent for normal mode and developer mode. bool isDevMode = false; string devModeProperty; var telemetryWithProperties = telemetry as ISupportProperties; if (telemetryWithProperties != null && telemetryWithProperties.Properties.TryGetValue("DeveloperMode", out devModeProperty)) { bool.TryParse(devModeProperty, out isDevMode); } // Format the event name using the following format: // Microsoft.[ProductName].[Dev].<normalized-instrumentation-key>.<event-type> var eventName = string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}{1}{2}", isDevMode ? Constants.DevModeTelemetryNamePrefix : Constants.TelemetryNamePrefix, NormalizeInstrumentationKey(telemetry.Context.InstrumentationKey), telemetryName); json.WriteProperty("name", eventName); } /// <summary> /// Normalize instrumentation key by removing dashes ('-') and making string in the lowercase. /// In case no InstrumentationKey is available just return empty string. /// In case when InstrumentationKey is available return normalized key + dot ('.') /// as a separator between instrumentation key part and telemetry name part. /// </summary> private static string NormalizeInstrumentationKey(string instrumentationKey) { if (instrumentationKey.IsNullOrWhiteSpace()) { return string.Empty; } return instrumentationKey.Replace("-", string.Empty).ToLowerInvariant() + "."; } } }
mit
C#
6178717d8d949c4f54824c852fc16772b575aea5
fix unable to close tabs.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/ViewModels/WasabiDocumentTabViewModel.cs
WalletWasabi.Gui/ViewModels/WasabiDocumentTabViewModel.cs
using AvalonStudio.Documents; using AvalonStudio.Extensibility; using AvalonStudio.Shell; using Dock.Model; using ReactiveUI; namespace WalletWasabi.Gui.ViewModels { public abstract class WasabiDocumentTabViewModel : ViewModelBase, IDocumentTabViewModel { public WasabiDocumentTabViewModel(string title) { Title = title; } public WasabiDocumentTabViewModel() { } public string Id { get; set; } public virtual string Title { get; set; } public object Context { get; set; } public double Width { get; set; } public double Height { get; set; } public IView Parent { get; set; } private bool _isSelected; public bool IsSelected { get { return _isSelected; } set { this.RaiseAndSetIfChanged(ref _isSelected, value); } } public bool IsDirty { get; set; } public virtual void Close() { IoC.Get<IShell>().RemoveDocument(this); IsSelected = false; } public virtual void OnSelected() { IsSelected = true; } public virtual void OnDeselected() { IsSelected = false; } public bool OnClose() { return true; } } }
using AvalonStudio.Documents; using AvalonStudio.Extensibility; using AvalonStudio.Shell; using Dock.Model; using ReactiveUI; namespace WalletWasabi.Gui.ViewModels { public abstract class WasabiDocumentTabViewModel : ViewModelBase, IDocumentTabViewModel { public WasabiDocumentTabViewModel(string title) { Title = title; } public WasabiDocumentTabViewModel() { } public string Id { get; set; } public virtual string Title { get; set; } public object Context { get; set; } public double Width { get; set; } public double Height { get; set; } public IView Parent { get; set; } private bool _isSelected; public bool IsSelected { get { return _isSelected; } set { this.RaiseAndSetIfChanged(ref _isSelected, value); } } public bool IsDirty { get; set; } public virtual void Close() { IoC.Get<IShell>().RemoveDocument(this); IsSelected = false; } public virtual void OnSelected() { IsSelected = true; } public virtual void OnDeselected() { IsSelected = false; } public bool OnClose() { return false; } } }
mit
C#
9bb329f3e9423246b0fa486f9f678ff83ec069a0
Fix for memory leak
JodyAndrews/ScriptableObjectUtility
ScriptableObjectUtility/Assets/Editor/ScriptableObjectEditor/DefaultItemWindow.cs
ScriptableObjectUtility/Assets/Editor/ScriptableObjectEditor/DefaultItemWindow.cs
using UnityEngine; using UnityEditor; using Voodoo.Utilities; public class DefaultItemWindow { #region Declarations ScriptableObject _data; ScriptableEditorWindow _ownerWindow; Editor _editor; #endregion #region Constructors public DefaultItemWindow (ScriptableEditorWindow ownerWindow, ScriptableObject data) { this._data = data; this._ownerWindow = ownerWindow; } #endregion #region Properties public Rect WindowRect { get; set; } public int Id { get; } public ScriptableObject Data { get { return _data; } } #endregion #region Methods public void DrawWindow (int id) { if (_editor == null) _editor = Editor.CreateEditor (_data); _editor.DrawDefaultInspector (); // We can also display the path if necessary, commented this out as if the path is large it makes the window width excessive //string path = AssetDatabase.GetAssetPath (_data); //GUILayout.Label(path); GUILayout.BeginHorizontal (); if (GUILayout.Button ("Remove")) { _ownerWindow.ViewableObjectWindows.RemoveAt (id); } if (GUILayout.Button ("Delete")) { } GUILayout.EndHorizontal (); } #endregion }
using UnityEngine; using UnityEditor; using Voodoo.Utilities; public class DefaultItemWindow { #region Declarations ScriptableObject _data; ScriptableEditorWindow _ownerWindow; #endregion #region Constructors public DefaultItemWindow (ScriptableEditorWindow ownerWindow, ScriptableObject data) { this._data = data; this._ownerWindow = ownerWindow; } #endregion #region Properties public Rect WindowRect { get; set; } public int Id { get; set; } public ScriptableObject Data { get { return _data; } } #endregion #region Methods public void DrawWindow (int id) { Editor editor = Editor.CreateEditor (_data); editor.DrawDefaultInspector (); // We can also display the path if necessary, commented this out as if the path is large it makes the window width excessive //string path = AssetDatabase.GetAssetPath (_data); //GUILayout.Label(path); GUILayout.BeginHorizontal (); if (GUILayout.Button ("Remove")) { _ownerWindow.ViewableObjectWindows.RemoveAt (id); } if (GUILayout.Button ("Delete")) { } GUILayout.EndHorizontal (); } #endregion }
mit
C#
af39e9e6a73b093ffa9948c9210c25f5ef051638
Set default wait interval for Run command to be 60 seconds
kjelliverb/condep-dsl-operations
ConDep.Dsl/Operations/Application/Execution/RunCmd/RunCmdProvider.cs
ConDep.Dsl/Operations/Application/Execution/RunCmd/RunCmdProvider.cs
using ConDep.Dsl.SemanticModel; using ConDep.Dsl.SemanticModel.WebDeploy; using Microsoft.Web.Deployment; namespace ConDep.Dsl.Operations.Application.Execution.RunCmd { public class RunCmdProvider : WebDeployProviderBase { private const string NAME = "runCommand"; public RunCmdProvider(string command) { DestinationPath = command; WaitIntervalInSeconds = 60; } public override DeploymentProviderOptions GetWebDeploySourceProviderOptions() { return new DeploymentProviderOptions(NAME) { Path = DestinationPath }; } public override string Name { get { return NAME; } } public override DeploymentProviderOptions GetWebDeployDestinationProviderOptions() { var destProviderOptions = new DeploymentProviderOptions("Auto");// { Path = DestinationPath }; //DeploymentProviderSetting dontUseCmdExe; //if (destProviderOptions.ProviderSettings.TryGetValue("dontUseCommandExe", out dontUseCmdExe)) //{ // dontUseCmdExe.Value = true; //} return destProviderOptions; } public override bool IsValid(Notification notification) { return !string.IsNullOrWhiteSpace(DestinationPath) || string.IsNullOrWhiteSpace(SourcePath); } } }
using ConDep.Dsl.SemanticModel; using ConDep.Dsl.SemanticModel.WebDeploy; using Microsoft.Web.Deployment; namespace ConDep.Dsl.Operations.Application.Execution.RunCmd { public class RunCmdProvider : WebDeployProviderBase { private const string NAME = "runCommand"; public RunCmdProvider(string command) { DestinationPath = command; } public override DeploymentProviderOptions GetWebDeploySourceProviderOptions() { return new DeploymentProviderOptions(NAME) { Path = DestinationPath }; } public override string Name { get { return NAME; } } public override DeploymentProviderOptions GetWebDeployDestinationProviderOptions() { var destProviderOptions = new DeploymentProviderOptions("Auto");// { Path = DestinationPath }; //DeploymentProviderSetting dontUseCmdExe; //if (destProviderOptions.ProviderSettings.TryGetValue("dontUseCommandExe", out dontUseCmdExe)) //{ // dontUseCmdExe.Value = true; //} return destProviderOptions; } public override bool IsValid(Notification notification) { return !string.IsNullOrWhiteSpace(DestinationPath) || string.IsNullOrWhiteSpace(SourcePath); } } }
bsd-2-clause
C#
2b7933cf4ec34da305e9abcbe7d9b031c96a8205
Fix obsolete warnings.
themotleyfool/NuGet.Lucene,Stift/NuGet.Lucene
source/NuGet.Lucene/NuGetQueryParser.cs
source/NuGet.Lucene/NuGetQueryParser.cs
using System; using System.Collections.Generic; using System.Linq; using Lucene.Net.Linq; using Lucene.Net.Linq.Mapping; using Version = Lucene.Net.Util.Version; namespace NuGet.Lucene { /// <summary> /// A query parser that mimics the behavior specified at /// http://docs.nuget.org/docs/reference/search-syntax. /// /// Uses case-insensitive matching for field names and /// uses a default field when the specified field is not found. /// /// Treats the field <c>Id</c> as a partial match / fuzzy search /// and the field <c>PackageId</c> as an exact match. /// </summary> public class NuGetQueryParser : FieldMappingQueryParser<LucenePackage> { private const string DefaultSearchFieldName = "SearchId"; private static readonly IDictionary<string, string> AliasMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { {"Id", "SearchId"}, {"PackageId", "Id"} }; public NuGetQueryParser(Version matchVersion, IDocumentMapper<LucenePackage> documentMapper) : base(matchVersion, DefaultSearchFieldName, documentMapper) { } public NuGetQueryParser(FieldMappingQueryParser<LucenePackage> parser) : this(parser.MatchVersion, parser.DocumentMapper) { } public static IDictionary<string, string> IndexedPropertyAliases { get { return new Dictionary<string, string>(AliasMap); } } protected override IFieldMappingInfo GetMapping(string field) { string aliasTarget; if (AliasMap.TryGetValue(field, out aliasTarget)) { field = aliasTarget; } field = DocumentMapper.IndexedProperties.FirstOrDefault( p => string.Equals(p, field, StringComparison.OrdinalIgnoreCase)) ?? DefaultSearchFieldName; return base.GetMapping(field); } } }
using System; using System.Collections.Generic; using System.Linq; using Lucene.Net.Linq; using Lucene.Net.Linq.Mapping; using Version = Lucene.Net.Util.Version; namespace NuGet.Lucene { /// <summary> /// A query parser that mimics the behavior specified at /// http://docs.nuget.org/docs/reference/search-syntax. /// /// Uses case-insensitive matching for field names and /// uses a default field when the specified field is not found. /// /// Treats the field <c>Id</c> as a partial match / fuzzy search /// and the field <c>PackageId</c> as an exact match. /// </summary> public class NuGetQueryParser : FieldMappingQueryParser<LucenePackage> { private static readonly IDictionary<string, string> AliasMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { {"Id", "SearchId"}, {"PackageId", "Id"} }; public NuGetQueryParser(Version matchVersion, IDocumentMapper<LucenePackage> documentMapper) : base(matchVersion, documentMapper) { DefaultSearchProperty = "SearchId"; } public NuGetQueryParser(FieldMappingQueryParser<LucenePackage> parser) : this(parser.MatchVersion, parser.DocumentMapper) { } public static IDictionary<string, string> IndexedPropertyAliases { get { return new Dictionary<string, string>(AliasMap); } } protected override IFieldMappingInfo GetMapping(string field) { string aliasTarget; if (AliasMap.TryGetValue(field, out aliasTarget)) { field = aliasTarget; } field = DocumentMapper.IndexedProperties.FirstOrDefault( p => String.Equals(p, field, StringComparison.OrdinalIgnoreCase)) ?? DefaultSearchProperty; return base.GetMapping(field); } } }
apache-2.0
C#
2cd57415e0caa22b097c7ea71f18c58c2382ecd5
Add overload for AddDictionary
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/Utilities/Collections/Dictionary.AddDictionary.cs
source/Nuke.Common/Utilities/Collections/Dictionary.AddDictionary.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System.Collections.Generic; namespace Nuke.Common.Utilities.Collections { public static partial class DictionaryExtensions { public static TDictionary AddDictionary<TDictionary, TKey, TValue>( this TDictionary dictionary, IDictionary<TKey, TValue> otherDictionary) where TDictionary : IDictionary<TKey, TValue> { foreach (var (key, value) in otherDictionary) dictionary.AddPair(key, value); return dictionary; } public static TDictionary AddDictionary<TDictionary, TKey, TValue>( this TDictionary dictionary, IReadOnlyDictionary<TKey, TValue> otherDictionary) where TDictionary : IDictionary<TKey, TValue> { foreach (var (key, value) in otherDictionary) dictionary.AddPair(key, value); return dictionary; } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System.Collections.Generic; namespace Nuke.Common.Utilities.Collections { public static partial class DictionaryExtensions { public static Dictionary<TKey, TValue> AddDictionary<TKey, TValue>( this Dictionary<TKey, TValue> dictionary, IReadOnlyDictionary<TKey, TValue> otherDictionary) { foreach (var (key, value) in otherDictionary) dictionary.AddPair(key, value); return dictionary; } } }
mit
C#
89d5782ef422b5db8b8c09e37f3ec25765541d40
Update DynamicProperty.cs
aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,luchaoshuai/aspnetboilerplate
src/Abp/DynamicEntityProperties/DynamicProperty.cs
src/Abp/DynamicEntityProperties/DynamicProperty.cs
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Abp.Domain.Entities; namespace Abp.DynamicEntityProperties { [Table("AbpDynamicProperties")] public class DynamicProperty : Entity, IMayHaveTenant { public string PropertyName { get; set; } public string DisplayName { get; set; } public string InputType { get; set; } public string Permission { get; set; } public int? TenantId { get; set; } public virtual ICollection<DynamicPropertyValue> DynamicPropertyValues { get; set; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Abp.Domain.Entities; namespace Abp.DynamicEntityProperties { [Table("AbpDynamicProperties")] public class DynamicProperty : Entity, IMayHaveTenant { public string PropertyName { get; set; } public string InputType { get; set; } public string Permission { get; set; } public int? TenantId { get; set; } public virtual ICollection<DynamicPropertyValue> DynamicPropertyValues { get; set; } } }
mit
C#
5eba749197085005334150d7215a2b242344c45f
Remove TODO #2542 was closed already.
dotnet-bot/corefx,seanshpark/corefx,stone-li/corefx,stone-li/corefx,wtgodbe/corefx,parjong/corefx,wtgodbe/corefx,ViktorHofer/corefx,ellismg/corefx,gkhanna79/corefx,alexperovich/corefx,rjxby/corefx,billwert/corefx,seanshpark/corefx,khdang/corefx,dhoehna/corefx,JosephTremoulet/corefx,mmitche/corefx,MaggieTsang/corefx,cartermp/corefx,dotnet-bot/corefx,richlander/corefx,billwert/corefx,Jiayili1/corefx,zhenlan/corefx,DnlHarvey/corefx,Jiayili1/corefx,shahid-pk/corefx,lggomez/corefx,jlin177/corefx,DnlHarvey/corefx,tstringer/corefx,iamjasonp/corefx,dhoehna/corefx,parjong/corefx,elijah6/corefx,axelheer/corefx,JosephTremoulet/corefx,manu-silicon/corefx,zhenlan/corefx,billwert/corefx,jhendrixMSFT/corefx,jlin177/corefx,DnlHarvey/corefx,nchikanov/corefx,elijah6/corefx,shahid-pk/corefx,parjong/corefx,dhoehna/corefx,elijah6/corefx,ptoonen/corefx,twsouthwick/corefx,SGuyGe/corefx,marksmeltzer/corefx,cartermp/corefx,zhenlan/corefx,Ermiar/corefx,weltkante/corefx,Ermiar/corefx,rubo/corefx,fgreinacher/corefx,jlin177/corefx,tijoytom/corefx,seanshpark/corefx,yizhang82/corefx,DnlHarvey/corefx,MaggieTsang/corefx,alexperovich/corefx,richlander/corefx,SGuyGe/corefx,mazong1123/corefx,cydhaselton/corefx,Ermiar/corefx,rahku/corefx,DnlHarvey/corefx,khdang/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,cydhaselton/corefx,marksmeltzer/corefx,ptoonen/corefx,ellismg/corefx,rubo/corefx,parjong/corefx,ericstj/corefx,stephenmichaelf/corefx,rahku/corefx,alphonsekurian/corefx,seanshpark/corefx,ericstj/corefx,parjong/corefx,tijoytom/corefx,stone-li/corefx,lggomez/corefx,Jiayili1/corefx,Petermarcu/corefx,tijoytom/corefx,zhenlan/corefx,wtgodbe/corefx,nchikanov/corefx,cydhaselton/corefx,ericstj/corefx,Priya91/corefx-1,stone-li/corefx,stephenmichaelf/corefx,shmao/corefx,billwert/corefx,rahku/corefx,shmao/corefx,iamjasonp/corefx,the-dwyer/corefx,alexperovich/corefx,BrennanConroy/corefx,iamjasonp/corefx,nbarbettini/corefx,mazong1123/corefx,manu-silicon/corefx,ptoonen/corefx,seanshpark/corefx,tijoytom/corefx,alphonsekurian/corefx,BrennanConroy/corefx,ravimeda/corefx,iamjasonp/corefx,krk/corefx,jlin177/corefx,khdang/corefx,mmitche/corefx,shimingsg/corefx,stephenmichaelf/corefx,cydhaselton/corefx,Priya91/corefx-1,manu-silicon/corefx,krk/corefx,gkhanna79/corefx,Chrisboh/corefx,billwert/corefx,SGuyGe/corefx,rahku/corefx,adamralph/corefx,shimingsg/corefx,jhendrixMSFT/corefx,JosephTremoulet/corefx,weltkante/corefx,krk/corefx,Priya91/corefx-1,adamralph/corefx,tijoytom/corefx,Priya91/corefx-1,gkhanna79/corefx,manu-silicon/corefx,richlander/corefx,rahku/corefx,yizhang82/corefx,alphonsekurian/corefx,axelheer/corefx,rjxby/corefx,stephenmichaelf/corefx,the-dwyer/corefx,the-dwyer/corefx,gkhanna79/corefx,alexperovich/corefx,billwert/corefx,MaggieTsang/corefx,nchikanov/corefx,ellismg/corefx,elijah6/corefx,shahid-pk/corefx,ViktorHofer/corefx,krytarowski/corefx,dsplaisted/corefx,elijah6/corefx,nchikanov/corefx,ptoonen/corefx,cydhaselton/corefx,nbarbettini/corefx,ellismg/corefx,dhoehna/corefx,parjong/corefx,rubo/corefx,krytarowski/corefx,ptoonen/corefx,shmao/corefx,dsplaisted/corefx,axelheer/corefx,Ermiar/corefx,yizhang82/corefx,parjong/corefx,axelheer/corefx,zhenlan/corefx,JosephTremoulet/corefx,shmao/corefx,weltkante/corefx,billwert/corefx,rjxby/corefx,dhoehna/corefx,cartermp/corefx,ericstj/corefx,jhendrixMSFT/corefx,YoupHulsebos/corefx,ravimeda/corefx,ViktorHofer/corefx,YoupHulsebos/corefx,Chrisboh/corefx,dotnet-bot/corefx,MaggieTsang/corefx,tstringer/corefx,SGuyGe/corefx,ravimeda/corefx,ericstj/corefx,twsouthwick/corefx,dotnet-bot/corefx,alexperovich/corefx,MaggieTsang/corefx,rjxby/corefx,Chrisboh/corefx,khdang/corefx,the-dwyer/corefx,shahid-pk/corefx,twsouthwick/corefx,shimingsg/corefx,yizhang82/corefx,lggomez/corefx,manu-silicon/corefx,Jiayili1/corefx,BrennanConroy/corefx,gkhanna79/corefx,gkhanna79/corefx,Petermarcu/corefx,fgreinacher/corefx,nbarbettini/corefx,seanshpark/corefx,tstringer/corefx,Jiayili1/corefx,Jiayili1/corefx,alexperovich/corefx,JosephTremoulet/corefx,stephenmichaelf/corefx,twsouthwick/corefx,YoupHulsebos/corefx,krytarowski/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,shmao/corefx,richlander/corefx,elijah6/corefx,tstringer/corefx,marksmeltzer/corefx,dhoehna/corefx,manu-silicon/corefx,jhendrixMSFT/corefx,shimingsg/corefx,DnlHarvey/corefx,seanshpark/corefx,Ermiar/corefx,Petermarcu/corefx,nchikanov/corefx,shahid-pk/corefx,nbarbettini/corefx,zhenlan/corefx,dotnet-bot/corefx,Petermarcu/corefx,krytarowski/corefx,nbarbettini/corefx,rahku/corefx,lggomez/corefx,nbarbettini/corefx,richlander/corefx,mmitche/corefx,Ermiar/corefx,stone-li/corefx,nbarbettini/corefx,khdang/corefx,iamjasonp/corefx,cydhaselton/corefx,rjxby/corefx,elijah6/corefx,Jiayili1/corefx,the-dwyer/corefx,twsouthwick/corefx,marksmeltzer/corefx,ravimeda/corefx,MaggieTsang/corefx,lggomez/corefx,mmitche/corefx,shimingsg/corefx,tijoytom/corefx,weltkante/corefx,JosephTremoulet/corefx,gkhanna79/corefx,shmao/corefx,weltkante/corefx,cartermp/corefx,mmitche/corefx,mmitche/corefx,mazong1123/corefx,Priya91/corefx-1,zhenlan/corefx,ericstj/corefx,shimingsg/corefx,fgreinacher/corefx,mazong1123/corefx,richlander/corefx,axelheer/corefx,wtgodbe/corefx,manu-silicon/corefx,jhendrixMSFT/corefx,the-dwyer/corefx,dsplaisted/corefx,krk/corefx,Ermiar/corefx,mazong1123/corefx,shahid-pk/corefx,richlander/corefx,ravimeda/corefx,marksmeltzer/corefx,alphonsekurian/corefx,stone-li/corefx,rjxby/corefx,mazong1123/corefx,Petermarcu/corefx,SGuyGe/corefx,ravimeda/corefx,weltkante/corefx,Chrisboh/corefx,dotnet-bot/corefx,wtgodbe/corefx,ptoonen/corefx,krk/corefx,adamralph/corefx,alphonsekurian/corefx,nchikanov/corefx,mazong1123/corefx,yizhang82/corefx,lggomez/corefx,JosephTremoulet/corefx,marksmeltzer/corefx,iamjasonp/corefx,Petermarcu/corefx,wtgodbe/corefx,Chrisboh/corefx,rubo/corefx,jlin177/corefx,cydhaselton/corefx,krk/corefx,twsouthwick/corefx,YoupHulsebos/corefx,shimingsg/corefx,tijoytom/corefx,twsouthwick/corefx,DnlHarvey/corefx,Priya91/corefx-1,ericstj/corefx,krytarowski/corefx,YoupHulsebos/corefx,the-dwyer/corefx,shmao/corefx,alexperovich/corefx,jlin177/corefx,krytarowski/corefx,Chrisboh/corefx,MaggieTsang/corefx,alphonsekurian/corefx,yizhang82/corefx,dotnet-bot/corefx,ellismg/corefx,lggomez/corefx,ViktorHofer/corefx,stone-li/corefx,alphonsekurian/corefx,weltkante/corefx,fgreinacher/corefx,SGuyGe/corefx,khdang/corefx,dhoehna/corefx,rjxby/corefx,ptoonen/corefx,stephenmichaelf/corefx,tstringer/corefx,Petermarcu/corefx,tstringer/corefx,mmitche/corefx,wtgodbe/corefx,marksmeltzer/corefx,cartermp/corefx,jhendrixMSFT/corefx,ellismg/corefx,ViktorHofer/corefx,axelheer/corefx,stephenmichaelf/corefx,jhendrixMSFT/corefx,rahku/corefx,rubo/corefx,ravimeda/corefx,krk/corefx,nchikanov/corefx,krytarowski/corefx,cartermp/corefx,jlin177/corefx,yizhang82/corefx,iamjasonp/corefx
src/Common/src/System/Net/Http/WinHttpException.cs
src/Common/src/System/Net/Http/WinHttpException.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace System.Net.Http { internal class WinHttpException : Win32Exception { public WinHttpException(int error, string message) : base(error, message) { this.HResult = ConvertErrorCodeToHR(error); } public static int ConvertErrorCodeToHR(int error) { // This method allows common error detection code to be used by consumers // of HttpClient. This method converts the ErrorCode returned by WinHTTP // to the same HRESULT value as is provided in the .Net Native implementation // of HttpClient under the same error conditions. Clients would access // HttpRequestException.InnerException.HRESULT to discover what caused // the exception. switch ((uint)error) { case Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR: return unchecked((int)Interop.WinHttp.WININET_E_CONNECTION_RESET); default: // Marshal.GetHRForLastWin32Error can't be used as not all error codes originate from native // code. return Interop.mincore.HRESULT_FROM_WIN32(error); } } public static void ThrowExceptionUsingLastError() { throw CreateExceptionUsingLastError(); } public static WinHttpException CreateExceptionUsingLastError() { int lastError = Marshal.GetLastWin32Error(); return CreateExceptionUsingError(lastError); } public static WinHttpException CreateExceptionUsingError(int error) { return new WinHttpException(error, GetErrorMessage(error)); } public static string GetErrorMessage(int error) { // Look up specific error message in WINHTTP.DLL since it is not listed in default system resources // and thus can't be found by default .Net interop. IntPtr moduleHandle = Interop.mincore.GetModuleHandle(Interop.Libraries.WinHttp); return Interop.mincore.GetMessage(moduleHandle, error); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace System.Net.Http { // TODO(Issue 2542): Unify this code (and other common code) with WinHttpHandler. internal class WinHttpException : Win32Exception { public WinHttpException(int error, string message) : base(error, message) { this.HResult = ConvertErrorCodeToHR(error); } public static int ConvertErrorCodeToHR(int error) { // This method allows common error detection code to be used by consumers // of HttpClient. This method converts the ErrorCode returned by WinHTTP // to the same HRESULT value as is provided in the .Net Native implementation // of HttpClient under the same error conditions. Clients would access // HttpRequestException.InnerException.HRESULT to discover what caused // the exception. switch ((uint)error) { case Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR: return unchecked((int)Interop.WinHttp.WININET_E_CONNECTION_RESET); default: // Marshal.GetHRForLastWin32Error can't be used as not all error codes originate from native // code. return Interop.mincore.HRESULT_FROM_WIN32(error); } } public static void ThrowExceptionUsingLastError() { throw CreateExceptionUsingLastError(); } public static WinHttpException CreateExceptionUsingLastError() { int lastError = Marshal.GetLastWin32Error(); return CreateExceptionUsingError(lastError); } public static WinHttpException CreateExceptionUsingError(int error) { return new WinHttpException(error, GetErrorMessage(error)); } public static string GetErrorMessage(int error) { // Look up specific error message in WINHTTP.DLL since it is not listed in default system resources // and thus can't be found by default .Net interop. IntPtr moduleHandle = Interop.mincore.GetModuleHandle(Interop.Libraries.WinHttp); return Interop.mincore.GetMessage(moduleHandle, error); } } }
mit
C#
fa72328bc7993ce7193c3b227755382bcea69860
Change extension type
mpOzelot/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
src/GitHub.Api/Extensions/EnvironmentExtensions.cs
src/GitHub.Api/Extensions/EnvironmentExtensions.cs
using System; namespace GitHub.Unity { static class EnvironmentExtensions { public static string GetRepositoryPath(this IEnvironment environment, string path) { Guard.ArgumentNotNull(path, nameof(path)); if (environment.UnityProjectPath == environment.RepositoryPath) { return path; } var projectPath = environment.UnityProjectPath.ToNPath(); var repositoryPath = environment.RepositoryPath.ToNPath(); if (repositoryPath.IsChildOf(projectPath)) { throw new InvalidOperationException($"RepositoryPath:\"{repositoryPath}\" should not be child of ProjectPath:\"{projectPath}\""); } return projectPath.RelativeTo(repositoryPath).Combine(path).ToString(); } public static string GetAssetPath(this IEnvironment environment, string path) { Guard.ArgumentNotNull(path, nameof(path)); if (environment.UnityProjectPath == environment.RepositoryPath) { return path; } var projectPath = environment.UnityProjectPath.ToNPath(); var repositoryPath = environment.RepositoryPath.ToNPath(); if (repositoryPath.IsChildOf(projectPath)) { throw new InvalidOperationException($"RepositoryPath:\"{repositoryPath}\" should not be child of ProjectPath:\"{projectPath}\""); } return repositoryPath.Combine(path).MakeAbsolute().RelativeTo(projectPath); } } }
using System; namespace GitHub.Unity { static class EnvironmentExtensions { public static string GetRepositoryPath(this IEnvironment environment, string path) { Guard.ArgumentNotNull(path, nameof(path)); if (environment.UnityProjectPath == environment.RepositoryPath) { return path; } var projectPath = environment.UnityProjectPath.ToNPath(); var repositoryPath = environment.RepositoryPath.ToNPath(); if (repositoryPath.IsChildOf(projectPath)) { throw new Exception($"RepositoryPath:\"{repositoryPath}\" should not be child of ProjectPath:\"{projectPath}\""); } return projectPath.RelativeTo(repositoryPath).Combine(path).ToString(); } public static string GetAssetPath(this IEnvironment environment, string path) { Guard.ArgumentNotNull(path, nameof(path)); if (environment.UnityProjectPath == environment.RepositoryPath) { return path; } var projectPath = environment.UnityProjectPath.ToNPath(); var repositoryPath = environment.RepositoryPath.ToNPath(); if (repositoryPath.IsChildOf(projectPath)) { throw new Exception($"RepositoryPath:\"{repositoryPath}\" should not be child of ProjectPath:\"{projectPath}\""); } return repositoryPath.Combine(path).MakeAbsolute().RelativeTo(projectPath); } } }
mit
C#