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 |
|---|---|---|---|---|---|---|---|---|
3085647ce23fd71c22ea6bca597d26a1081bfb4e | Fix bug in ESFFile uncovered by unit testing | ethanmoffat/EndlessClient | EOLib.IO/Pub/ESFFile.cs | EOLib.IO/Pub/ESFFile.cs | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Diagnostics;
using System.IO;
using System.Text;
using EOLib.IO.Services;
namespace EOLib.IO.Pub
{
public class ESFFile : BasePubFile<ESFRecord>
{
public override string FileType
{
get { return "ESF"; }
}
public override void DeserializeFromByteArray(byte[] bytes, INumberEncoderService numberEncoderService)
{
using (var mem = new MemoryStream(bytes))
ReadFromStream(mem, numberEncoderService);
}
private void ReadFromStream(Stream mem, INumberEncoderService numberEncoderService)
{
mem.Seek(3, SeekOrigin.Begin);
var checksum = new byte[4];
mem.Read(checksum, 0, 4);
CheckSum = numberEncoderService.DecodeNumber(checksum);
var lenBytes = new byte[2];
mem.Read(lenBytes, 0, 2);
var recordsInFile = (short)numberEncoderService.DecodeNumber(lenBytes);
mem.Seek(1, SeekOrigin.Current);
var rawData = new byte[ESFRecord.DATA_SIZE];
for (int i = 0; i < recordsInFile && mem.Position < mem.Length; ++i)
{
var nameLength = numberEncoderService.DecodeNumber((byte)mem.ReadByte());
var shoutLength = numberEncoderService.DecodeNumber((byte)mem.ReadByte());
var rawName = new byte[nameLength];
var rawShout = new byte[shoutLength];
mem.Read(rawName, 0, nameLength);
mem.Read(rawShout, 0, shoutLength);
mem.Read(rawData, 0, ESFRecord.DATA_SIZE);
var record = new ESFRecord
{
ID = i,
Name = Encoding.ASCII.GetString(rawName),
Shout = Encoding.ASCII.GetString(rawShout)
};
record.DeserializeFromByteArray(rawData, numberEncoderService);
_data.Add(record);
}
if (recordsInFile != Length)
throw new IOException("Mismatch between expected length and actual length!");
}
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Diagnostics;
using System.IO;
using System.Text;
using EOLib.IO.Services;
namespace EOLib.IO.Pub
{
public class ESFFile : BasePubFile<ESFRecord>
{
public override string FileType
{
get { return "ESF"; }
}
public override void DeserializeFromByteArray(byte[] bytes, INumberEncoderService numberEncoderService)
{
using (var mem = new MemoryStream(bytes))
ReadFromStream(mem, numberEncoderService);
}
private void ReadFromStream(Stream mem, INumberEncoderService numberEncoderService)
{
mem.Seek(3, SeekOrigin.Begin);
var checksum = new byte[4];
mem.Read(checksum, 0, 4);
CheckSum = numberEncoderService.DecodeNumber(checksum);
var lenBytes = new byte[2];
mem.Read(lenBytes, 0, 2);
var recordsInFile = (short)numberEncoderService.DecodeNumber(lenBytes);
mem.Seek(1, SeekOrigin.Current);
var rawData = new byte[ESFRecord.DATA_SIZE];
for (int i = 0; i < recordsInFile && mem.Position < mem.Length; ++i)
{
var nameLength = numberEncoderService.DecodeNumber((byte)mem.ReadByte());
var shoutLength = numberEncoderService.DecodeNumber((byte)mem.ReadByte());
var rawName = new byte[nameLength];
var rawShout = new byte[shoutLength];
mem.Read(rawName, 0, nameLength);
mem.Read(rawShout, 0, shoutLength);
mem.Read(rawData, 0, ESFRecord.DATA_SIZE);
var record = new ESFRecord { ID = i, Name = Encoding.ASCII.GetString(rawName) };
record.DeserializeFromByteArray(rawData, numberEncoderService);
_data.Add(record);
}
if (recordsInFile != Length)
throw new IOException("Mismatch between expected length and actual length!");
}
}
}
| mit | C# |
2fd7b4f3855379e0964a14d1aaed66c04213ef54 | Update comment | charlenni/Mapsui,charlenni/Mapsui | Mapsui.Nts/Extensions/GeometryExtensions.cs | Mapsui.Nts/Extensions/GeometryExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Mapsui.GeometryLayers;
using NetTopologySuite.Geometries;
namespace Mapsui.Nts.Extensions
{
public static class GeometryExtensions
{
//!!! todo: Remove method and replace with direct call to Geometry.Coordinates
public static IEnumerable<Coordinate> AllVertices(this Geometry? geometry)
{
if (geometry == null) return Array.Empty<Coordinate>();
return geometry.Coordinates;
}
//!!! todo: Remove method and replace with direct call to Geometry.Coordinates
private static IEnumerable<Coordinate> AllVertices(IEnumerable<Geometry> collection)
{
if (collection == null) throw new ArgumentNullException(nameof(collection));
foreach (var geometry in collection)
foreach (var point in geometry.AllVertices())
yield return point;
}
//!!! todo: Rename to ToEnvelope after everything compiles
public static Envelope BoundingBox(this Geometry geometry)
{
return geometry.EnvelopeInternal;
}
public static GeometryFeature ToFeature(this Geometry geometry)
{
return new GeometryFeature(geometry);
}
public static IEnumerable<GeometryFeature> ToFeatures(this IEnumerable<Geometry> geometries)
{
return geometries.Select(g => new GeometryFeature(g)).ToList();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Mapsui.GeometryLayers;
using NetTopologySuite.Geometries;
namespace Mapsui.Nts.Extensions
{
public static class GeometryExtensions
{
//!!! todo: Remove method and replace with direct call to Geometry.Coordinates
public static IEnumerable<Coordinate> AllVertices(this Geometry? geometry)
{
if (geometry == null) return Array.Empty<Coordinate>();
return geometry.Coordinates;
}
//!!! todo: Remove method and replace with direct call to Geometry.Coordinates
private static IEnumerable<Coordinate> AllVertices(IEnumerable<Geometry> collection)
{
if (collection == null) throw new ArgumentNullException(nameof(collection));
foreach (var geometry in collection)
foreach (var point in geometry.AllVertices())
yield return point;
}
//!!! todo: Rename to GetBoundingBox
public static Envelope BoundingBox(this Geometry geometry)
{
return geometry.EnvelopeInternal;
}
public static GeometryFeature ToFeature(this Geometry geometry)
{
return new GeometryFeature(geometry);
}
public static IEnumerable<GeometryFeature> ToFeatures(this IEnumerable<Geometry> geometries)
{
return geometries.Select(g => new GeometryFeature(g)).ToList();
}
}
} | mit | C# |
43b65ca46ce3a1abd4609c951c126bc1bacc5523 | Update the documentation for IViewComponentHelper.InvokeAsync | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Mvc.ViewFeatures/IViewComponentHelper.cs | src/Microsoft.AspNetCore.Mvc.ViewFeatures/IViewComponentHelper.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// Supports the rendering of view components in a view.
/// </summary>
public interface IViewComponentHelper
{
/// <summary>
/// Invokes a view component with the specified <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the view component.</param>
/// <param name="arguments">
/// An <see cref="object"/> containing arguments to be passed to the invoked view component method.
/// Alternatively, an <see cref="IDictionary{string, object}"/> instance containing the invocation arguments.
/// </param>
/// <returns>A <see cref="Task"/> that on completion returns the rendered <see cref="IHtmlContent" />.
/// </returns>
Task<IHtmlContent> InvokeAsync(string name, object arguments);
/// <summary>
/// Invokes a view component of type <paramref name="componentType" />.
/// </summary>
/// <param name="componentType">The view component <see cref="Type"/>.</param>
/// <param name="arguments">
/// An <see cref="object"/> containing arguments to be passed to the invoked view component method.
/// Alternatively, an <see cref="IDictionary{string, object}"/> instance containing the invocation arguments.
/// </param>
/// <returns>A <see cref="Task"/> that on completion returns the rendered <see cref="IHtmlContent" />.
/// </returns>
Task<IHtmlContent> InvokeAsync(Type componentType, object arguments);
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// Supports the rendering of view components in a view.
/// </summary>
public interface IViewComponentHelper
{
/// <summary>
/// Invokes a view component with the specified <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the view component.</param>
/// <param name="arguments">Arguments to be passed to the invoked view component method.</param>
/// <returns>A <see cref="Task"/> that on completion returns the rendered <see cref="IHtmlContent" />.
/// </returns>
Task<IHtmlContent> InvokeAsync(string name, object arguments);
/// <summary>
/// Invokes a view component of type <paramref name="componentType" />.
/// </summary>
/// <param name="componentType">The view component <see cref="Type"/>.</param>
/// <param name="arguments">Arguments to be passed to the invoked view component method.</param>
/// <returns>A <see cref="Task"/> that on completion returns the rendered <see cref="IHtmlContent" />.
/// </returns>
Task<IHtmlContent> InvokeAsync(Type componentType, object arguments);
}
}
| apache-2.0 | C# |
2597963e9cb842144c5b1b9d4a7349553677685a | Add System.ComponentModel.TypeConverter serialization | krk/corefx,Ermiar/corefx,alexperovich/corefx,ptoonen/corefx,parjong/corefx,rahku/corefx,alexperovich/corefx,Ermiar/corefx,ViktorHofer/corefx,billwert/corefx,marksmeltzer/corefx,ravimeda/corefx,twsouthwick/corefx,gkhanna79/corefx,lggomez/corefx,lggomez/corefx,dotnet-bot/corefx,krk/corefx,weltkante/corefx,dotnet-bot/corefx,marksmeltzer/corefx,krytarowski/corefx,krk/corefx,Jiayili1/corefx,mazong1123/corefx,seanshpark/corefx,rjxby/corefx,MaggieTsang/corefx,mmitche/corefx,mazong1123/corefx,krytarowski/corefx,zhenlan/corefx,wtgodbe/corefx,nbarbettini/corefx,seanshpark/corefx,seanshpark/corefx,krk/corefx,gkhanna79/corefx,axelheer/corefx,axelheer/corefx,seanshpark/corefx,krytarowski/corefx,parjong/corefx,rjxby/corefx,ptoonen/corefx,ericstj/corefx,stephenmichaelf/corefx,marksmeltzer/corefx,gkhanna79/corefx,ravimeda/corefx,elijah6/corefx,nchikanov/corefx,rubo/corefx,stephenmichaelf/corefx,twsouthwick/corefx,wtgodbe/corefx,krk/corefx,yizhang82/corefx,elijah6/corefx,the-dwyer/corefx,jlin177/corefx,dhoehna/corefx,elijah6/corefx,mmitche/corefx,dhoehna/corefx,yizhang82/corefx,mazong1123/corefx,nbarbettini/corefx,mazong1123/corefx,shimingsg/corefx,YoupHulsebos/corefx,ravimeda/corefx,the-dwyer/corefx,ericstj/corefx,cydhaselton/corefx,nbarbettini/corefx,weltkante/corefx,parjong/corefx,dotnet-bot/corefx,MaggieTsang/corefx,ViktorHofer/corefx,yizhang82/corefx,JosephTremoulet/corefx,weltkante/corefx,JosephTremoulet/corefx,rjxby/corefx,tijoytom/corefx,marksmeltzer/corefx,tijoytom/corefx,ViktorHofer/corefx,stone-li/corefx,yizhang82/corefx,shimingsg/corefx,DnlHarvey/corefx,nbarbettini/corefx,Jiayili1/corefx,lggomez/corefx,fgreinacher/corefx,twsouthwick/corefx,ViktorHofer/corefx,rubo/corefx,twsouthwick/corefx,richlander/corefx,yizhang82/corefx,weltkante/corefx,rahku/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,ravimeda/corefx,mazong1123/corefx,cydhaselton/corefx,zhenlan/corefx,twsouthwick/corefx,rjxby/corefx,nbarbettini/corefx,ViktorHofer/corefx,parjong/corefx,nchikanov/corefx,nbarbettini/corefx,shimingsg/corefx,ericstj/corefx,dhoehna/corefx,wtgodbe/corefx,dhoehna/corefx,YoupHulsebos/corefx,YoupHulsebos/corefx,ptoonen/corefx,elijah6/corefx,jlin177/corefx,MaggieTsang/corefx,richlander/corefx,stone-li/corefx,BrennanConroy/corefx,stephenmichaelf/corefx,fgreinacher/corefx,axelheer/corefx,rubo/corefx,rjxby/corefx,JosephTremoulet/corefx,the-dwyer/corefx,Jiayili1/corefx,stone-li/corefx,mmitche/corefx,Ermiar/corefx,seanshpark/corefx,dotnet-bot/corefx,shimingsg/corefx,Petermarcu/corefx,wtgodbe/corefx,ravimeda/corefx,twsouthwick/corefx,YoupHulsebos/corefx,marksmeltzer/corefx,Petermarcu/corefx,cydhaselton/corefx,ptoonen/corefx,richlander/corefx,Petermarcu/corefx,MaggieTsang/corefx,zhenlan/corefx,nchikanov/corefx,marksmeltzer/corefx,dotnet-bot/corefx,alexperovich/corefx,gkhanna79/corefx,the-dwyer/corefx,axelheer/corefx,Ermiar/corefx,DnlHarvey/corefx,gkhanna79/corefx,weltkante/corefx,jlin177/corefx,Ermiar/corefx,Petermarcu/corefx,ericstj/corefx,DnlHarvey/corefx,wtgodbe/corefx,cydhaselton/corefx,DnlHarvey/corefx,richlander/corefx,rjxby/corefx,marksmeltzer/corefx,ericstj/corefx,ptoonen/corefx,zhenlan/corefx,nchikanov/corefx,weltkante/corefx,YoupHulsebos/corefx,stone-li/corefx,krk/corefx,alexperovich/corefx,billwert/corefx,rahku/corefx,billwert/corefx,Petermarcu/corefx,parjong/corefx,elijah6/corefx,mmitche/corefx,dhoehna/corefx,Ermiar/corefx,rubo/corefx,Petermarcu/corefx,krytarowski/corefx,stone-li/corefx,zhenlan/corefx,ericstj/corefx,elijah6/corefx,krytarowski/corefx,krytarowski/corefx,rubo/corefx,shimingsg/corefx,seanshpark/corefx,shimingsg/corefx,the-dwyer/corefx,ptoonen/corefx,cydhaselton/corefx,tijoytom/corefx,Jiayili1/corefx,yizhang82/corefx,mmitche/corefx,zhenlan/corefx,ViktorHofer/corefx,alexperovich/corefx,stone-li/corefx,rjxby/corefx,MaggieTsang/corefx,stephenmichaelf/corefx,Petermarcu/corefx,Ermiar/corefx,nbarbettini/corefx,parjong/corefx,ravimeda/corefx,rahku/corefx,YoupHulsebos/corefx,jlin177/corefx,nchikanov/corefx,MaggieTsang/corefx,weltkante/corefx,richlander/corefx,rahku/corefx,nchikanov/corefx,zhenlan/corefx,lggomez/corefx,rahku/corefx,tijoytom/corefx,krytarowski/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,elijah6/corefx,billwert/corefx,ericstj/corefx,dotnet-bot/corefx,stephenmichaelf/corefx,wtgodbe/corefx,axelheer/corefx,dhoehna/corefx,lggomez/corefx,stephenmichaelf/corefx,fgreinacher/corefx,seanshpark/corefx,twsouthwick/corefx,axelheer/corefx,BrennanConroy/corefx,DnlHarvey/corefx,mazong1123/corefx,ViktorHofer/corefx,lggomez/corefx,yizhang82/corefx,JosephTremoulet/corefx,the-dwyer/corefx,nchikanov/corefx,dhoehna/corefx,dotnet-bot/corefx,tijoytom/corefx,Jiayili1/corefx,mmitche/corefx,alexperovich/corefx,billwert/corefx,ravimeda/corefx,jlin177/corefx,richlander/corefx,cydhaselton/corefx,billwert/corefx,alexperovich/corefx,mmitche/corefx,billwert/corefx,tijoytom/corefx,krk/corefx,richlander/corefx,fgreinacher/corefx,BrennanConroy/corefx,mazong1123/corefx,gkhanna79/corefx,lggomez/corefx,parjong/corefx,stone-li/corefx,Jiayili1/corefx,wtgodbe/corefx,shimingsg/corefx,cydhaselton/corefx,YoupHulsebos/corefx,JosephTremoulet/corefx,ptoonen/corefx,Jiayili1/corefx,gkhanna79/corefx,MaggieTsang/corefx,the-dwyer/corefx,tijoytom/corefx,jlin177/corefx,rahku/corefx,jlin177/corefx,JosephTremoulet/corefx | src/System.ComponentModel.TypeConverter/src/System/ComponentModel/InvalidAsynchronousStateException.cs | src/System.ComponentModel.TypeConverter/src/System/ComponentModel/InvalidAsynchronousStateException.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.Runtime.Serialization;
namespace System.ComponentModel
{
/// <summary>
/// <para>The exception that is thrown when a thread that an operation should execute on no longer exists or is not pumping messages</para>
/// </summary>
[Serializable]
public class InvalidAsynchronousStateException : ArgumentException
{
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.InvalidAsynchronousStateException'/> class without a message.</para>
/// </summary>
public InvalidAsynchronousStateException() : this(null)
{
}
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.InvalidAsynchronousStateException'/> class with
/// the specified message.</para>
/// </summary>
public InvalidAsynchronousStateException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the Exception class with a specified error message and a
/// reference to the inner exception that is the cause of this exception.
/// </summary>
public InvalidAsynchronousStateException(string message, Exception innerException)
: base(message, innerException)
{
}
protected InvalidAsynchronousStateException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
| // 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.Runtime.Serialization;
namespace System.ComponentModel
{
/// <summary>
/// <para>The exception that is thrown when a thread that an operation should execute on no longer exists or is not pumping messages</para>
/// </summary>
public class InvalidAsynchronousStateException : ArgumentException
{
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.InvalidAsynchronousStateException'/> class without a message.</para>
/// </summary>
public InvalidAsynchronousStateException() : this(null)
{
}
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.InvalidAsynchronousStateException'/> class with
/// the specified message.</para>
/// </summary>
public InvalidAsynchronousStateException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the Exception class with a specified error message and a
/// reference to the inner exception that is the cause of this exception.
/// </summary>
public InvalidAsynchronousStateException(string message, Exception innerException)
: base(message, innerException)
{
}
protected InvalidAsynchronousStateException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
| mit | C# |
d1c9d4382f8bc41f65329d4114c53948d836ad3b | use factory method in sample | tibel/Caliburn.Light | samples/Demo.SimpleMDI/ShellViewModel.cs | samples/Demo.SimpleMDI/ShellViewModel.cs | using Caliburn.Light;
using System;
using System.Threading.Tasks;
namespace Demo.SimpleMDI
{
public class ShellViewModel : Conductor<TabViewModel>.Collection.OneActive
{
private readonly Func<TabViewModel> _createTabViewModel;
private int _count = 0;
private bool _canClosePending;
public ShellViewModel(Func<TabViewModel> createTabViewModel)
{
if (createTabViewModel == null)
throw new ArgumentNullException(nameof(createTabViewModel));
_createTabViewModel = createTabViewModel;
}
public void OpenTab()
{
var tab = _createTabViewModel();
tab.DisplayName = "Tab " + ++_count;
ActivateItem(tab);
}
public override async Task<bool> CanCloseAsync()
{
if (_canClosePending) return false;
_canClosePending = true;
await Task.Delay(1000);
_canClosePending = false;
return true;
}
}
}
| using Caliburn.Light;
using System.Threading.Tasks;
namespace Demo.SimpleMDI
{
public class ShellViewModel : Conductor<TabViewModel>.Collection.OneActive
{
private int _count = 1;
private bool _canClosePending;
public void OpenTab()
{
var tab = IoC.GetInstance<TabViewModel>();
tab.DisplayName = "Tab " + _count++;
ActivateItem(tab);
}
public override async Task<bool> CanCloseAsync()
{
if (_canClosePending) return false;
_canClosePending = true;
await Task.Delay(1000);
_canClosePending = false;
return true;
}
}
}
| mit | C# |
aaf2edace9d43e9cadfcfb874ef5d8a68be660f6 | remove code from old incorrect test | peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu | osu.Game.Tests/Visual/Multiplayer/TestMultiplayerModLoading.cs | osu.Game.Tests/Visual/Multiplayer/TestMultiplayerModLoading.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Screens.Select;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestMultiplayerModLoading : OsuGameTestScene
{
[SetUp]
public void SetUp() => Schedule(() =>
{
SelectedMods.Value = Array.Empty<Mod>();
});
/// <summary>
/// This is a regression test that tests whether a singleplayer mod can transfer over to a multiplayer screen.
/// It should not carry over from these screens, prevents regression on https://github.com/ppy/osu/pull/17352
/// </summary>
[Test]
public void TestSingleplayerModsDontCarryToMultiplayerScreens()
{
PushAndConfirm(() => new PlaySongSelect());
// Select Mods while a "singleplayer" screen is active
var osuAutomationMod = new OsuModAutoplay();
var expectedMods = new[] { osuAutomationMod };
AddStep("Toggle on the automation Mod.", () => { SelectedMods.Value = expectedMods; });
AddAssert("", () => SelectedMods.Value == expectedMods);
PushAndConfirm(() => new TestMultiplayerComponents());
AddAssert("Mods are Empty After A Multiplayer Screen Loads", () => SelectedMods.Value.Count == 0);
AddStep("Retoggle on the automation Mod.", () => { SelectedMods.Value = expectedMods; });
AddAssert("", () => SelectedMods.Value == expectedMods);
// TODO: Implement TestPlaylistComponents?
//PushAndConfirm(() => new TestPlaylistComponents());
//AddAssert("Mods are Empty After Playlist Screen Loads", () => !SelectedMods.Value.Any());
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Screens.Select;
// Resolve these names to types because there is a Namespace called "Playlists" and "Multiplayer" which conflicts
using MultiplayerScreenAlias = osu.Game.Screens.OnlinePlay.Multiplayer.Multiplayer;
using PlaylistsScreenAlias = osu.Game.Screens.OnlinePlay.Playlists.Playlists;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestMultiplayerModLoading : OsuGameTestScene
{
[SetUp]
public void SetUp() => Schedule(() =>
{
SelectedMods.Value = Array.Empty<Mod>();
});
/// <summary>
/// This is a regression test that tests whether a singleplayer mod can transfer over to a multiplayer screen.
/// It should not carry over from these screens, prevents regression on https://github.com/ppy/osu/pull/17352
/// </summary>
[Test]
public void TestSingleplayerModsDontCarryToMultiplayerScreens()
{
PushAndConfirm(() => new PlaySongSelect());
// Select Mods while a "singleplayer" screen is active
var osuAutomationMod = new OsuModAutoplay();
var expectedMods = new[] { osuAutomationMod };
AddStep("Toggle on the automation Mod.", () => { SelectedMods.Value = expectedMods; });
AddAssert("", () => SelectedMods.Value == expectedMods);
PushAndConfirm(() => new TestMultiplayerComponents());
AddAssert("Mods are Empty After A Multiplayer Screen Loads", () => SelectedMods.Value.Count == 0);
AddStep("Retoggle on the automation Mod.", () => { SelectedMods.Value = expectedMods; });
AddAssert("", () => SelectedMods.Value == expectedMods);
// TODO: Implement TestPlaylistComponents?
//PushAndConfirm(() => new TestPlaylistComponents());
//AddAssert("Mods are Empty After Playlist Screen Loads", () => !SelectedMods.Value.Any());
}
}
}
| mit | C# |
b4d0a219086f7c3d0013e4053a084a19c13ed10e | Fix message | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit/Definitions/Utilities/TrackedObjectType.cs | Assets/MixedRealityToolkit/Definitions/Utilities/TrackedObjectType.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
public enum TrackedObjectType
{
/// <summary>
/// Calculates position and orientation from the main camera.
/// </summary>
Head = 0,
/// <summary>
/// (Obsolete) Calculates position and orientation from the left motion-tracked controller.
/// </summary>
[Obsolete("Use TrackedObjectType.ControllerRay and TrackedHandedness instead")]
MotionControllerLeft = 1,
/// <summary>
/// (Obsolete) Calculates position and orientation from the right motion-tracked controller.
/// </summary>
[Obsolete("Use TrackedObjectType.ControllerRay and TrackedHandedness instead")]
MotionControllerRight = 2,
/// <summary>
/// (Obsolete) Calculates position and orientation from a tracked hand joint on the left hand.
/// </summary>
[Obsolete("Use TrackedObjectType.HandJoint and TrackedHandedness instead")]
HandJointLeft = 3,
/// <summary>
/// (Obsolete) Calculates position and orientation from a tracked hand joint on the right hand.
/// </summary>
[Obsolete("Use TrackedObjectType.HandJoint and TrackedHandedness instead")]
HandJointRight = 4,
/// <summary>
/// Calculates position and orientation from the system-calculated ray of available controller (i.e motion controllers, hands, etc.)
/// </summary>
ControllerRay = 5,
/// <summary>
/// Calculates position and orientation from a tracked hand joint
/// </summary>
HandJoint = 6,
/// <summary>
/// Calculates position and orientation from a tracked hand joint
/// </summary>
CustomOverride = 7,
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
public enum TrackedObjectType
{
/// <summary>
/// Calculates position and orientation from the main camera.
/// </summary>
Head = 0,
/// <summary>
/// (Obsolete) Calculates position and orientation from the left motion-tracked controller.
/// </summary>
[Obsolete("Use TrackedObjectType.MotionController and TrackedHandedness instead")]
MotionControllerLeft = 1,
/// <summary>
/// (Obsolete) Calculates position and orientation from the right motion-tracked controller.
/// </summary>
[Obsolete("Use TrackedObjectType.MotionController and TrackedHandedness instead")]
MotionControllerRight = 2,
/// <summary>
/// (Obsolete) Calculates position and orientation from a tracked hand joint on the left hand.
/// </summary>
[Obsolete("Use TrackedObjectType.HandJoint and TrackedHandedness instead")]
HandJointLeft = 3,
/// <summary>
/// (Obsolete) Calculates position and orientation from a tracked hand joint on the right hand.
/// </summary>
[Obsolete("Use TrackedObjectType.HandJoint and TrackedHandedness instead")]
HandJointRight = 4,
/// <summary>
/// Calculates position and orientation from the system-calculated ray of available controller (i.e motion controllers, hands, etc.)
/// </summary>
ControllerRay = 5,
/// <summary>
/// Calculates position and orientation from a tracked hand joint
/// </summary>
HandJoint = 6,
/// <summary>
/// Calculates position and orientation from a tracked hand joint
/// </summary>
CustomOverride = 7,
}
} | mit | C# |
80d3b64a5f047161e44b2a31687d679e9e321409 | Change summary of UmbracoUserTimeoutFilterAttribute to more accurately describe what it does now | marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS | src/Umbraco.Web.Common/Filters/UmbracoUserTimeoutFilterAttribute.cs | src/Umbraco.Web.Common/Filters/UmbracoUserTimeoutFilterAttribute.cs | using System.Globalization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Umbraco.Extensions;
namespace Umbraco.Web.Common.Filters
{
/// <summary>
/// This will check if the user making the request is authenticated and if there's an auth ticket tied to the user
/// we will add a custom header to the response indicating how many seconds are remaining for the
/// user's session. This allows us to keep track of a user's session effectively in the back office.
/// </summary>
public class UmbracoUserTimeoutFilterAttribute : TypeFilterAttribute
{
public UmbracoUserTimeoutFilterAttribute() : base(typeof(UmbracoUserTimeoutFilter))
{
}
private class UmbracoUserTimeoutFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
//this can occur if an error has already occurred.
if (context.HttpContext.Response is null) return;
var remainingSeconds = context.HttpContext.User.GetRemainingAuthSeconds();
context.HttpContext.Response.Headers.Add("X-Umb-User-Seconds", remainingSeconds.ToString(CultureInfo.InvariantCulture));
}
public void OnActionExecuting(ActionExecutingContext context)
{
// Noop
}
}
}
}
| using System.Globalization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Umbraco.Extensions;
namespace Umbraco.Web.Common.Filters
{
/// <summary>
/// This will check if the request is authenticated and if there's an auth ticket present we will
/// add a custom header to the response indicating how many seconds are remaining for the current
/// user's session. This allows us to keep track of a user's session effectively in the back office.
/// </summary>
public class UmbracoUserTimeoutFilterAttribute : TypeFilterAttribute
{
public UmbracoUserTimeoutFilterAttribute() : base(typeof(UmbracoUserTimeoutFilter))
{
}
private class UmbracoUserTimeoutFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
//this can occur if an error has already occurred.
if (context.HttpContext.Response is null) return;
var remainingSeconds = context.HttpContext.User.GetRemainingAuthSeconds();
context.HttpContext.Response.Headers.Add("X-Umb-User-Seconds", remainingSeconds.ToString(CultureInfo.InvariantCulture));
}
public void OnActionExecuting(ActionExecutingContext context)
{
// Noop
}
}
}
}
| mit | C# |
35d417ad57ff504062625fb182be9679ef09ebe2 | Rename one more method | another-guy/Peppermint | Peppermint/PrimitiveTypes/TypeExtensions.cs | Peppermint/PrimitiveTypes/TypeExtensions.cs | using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace System
{
public static class TypeExtensions
{
public static IEnumerable<Type> GetAllBaseTypes(this Type type)
{
var currentType = type;
while (true)
{
if ((currentType = currentType.GetTypeInfo().BaseType) == null)
yield break;
yield return currentType;
}
}
public static bool IsParentTypeOf(this Type parentType, Type childType)
{
return childType.IsChildTypeOf(parentType);
}
public static bool IsChildTypeOf(this Type childType, Type parentType)
{
return parentType.IsAssignableFrom(childType);
}
public static bool IsParentOrPossiblyOpenGenericParentOf(this Type parentType, Type childType)
{
return childType.IsChildTypeOfPossiblyOpenGeneric(parentType);
}
public static bool IsChildTypeOfPossiblyOpenGeneric(this Type childType, Type parentClassType)
{
if (childType.IsChildTypeOf(parentClassType))
return true;
var parentTypeInfo = parentClassType.GetTypeInfo();
if (parentTypeInfo.IsGenericTypeDefinition)
{
var childArgs = childType.GetGenericArguments();
var constraints = parentTypeInfo
.GetGenericArguments()
.Select(genericArgument => genericArgument.GetTypeInfo().GetGenericParameterConstraints())
.ToArray();
return childArgs.Length == constraints.Length;
}
return false;
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace System
{
public static class TypeExtensions
{
public static IEnumerable<Type> GetAllBaseTypes(this Type type)
{
var currentType = type;
while (true)
{
if ((currentType = currentType.GetTypeInfo().BaseType) == null)
yield break;
yield return currentType;
}
}
public static bool IsParentTypeOf(this Type parentType, Type childType)
{
return childType.IsChildTypeOf(parentType);
}
public static bool IsChildTypeOf(this Type childType, Type parentType)
{
return parentType.IsAssignableFrom(childType);
}
public static bool IsPossiblyOpenGenericParentOf(this Type parentType, Type childType)
{
return childType.IsChildTypeOfPossiblyOpenGeneric(parentType);
}
public static bool IsChildTypeOfPossiblyOpenGeneric(this Type childType, Type parentClassType)
{
if (childType.IsChildTypeOf(parentClassType))
return true;
var parentTypeInfo = parentClassType.GetTypeInfo();
if (parentTypeInfo.IsGenericTypeDefinition)
{
var childArgs = childType.GetGenericArguments();
var constraints = parentTypeInfo
.GetGenericArguments()
.Select(genericArgument => genericArgument.GetTypeInfo().GetGenericParameterConstraints())
.ToArray();
return childArgs.Length == constraints.Length;
}
return false;
}
}
}
| mit | C# |
8f998da8a87e20f387bb47ac3287f09c41359592 | Remove unused message id | praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui | Ooui/Message.cs | Ooui/Message.cs | using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Ooui
{
public class Message
{
[JsonProperty("m")]
public MessageType MessageType = MessageType.Nop;
[JsonProperty("id")]
public string TargetId = "";
[JsonProperty("k")]
public string Key = "";
[JsonProperty("v", NullValueHandling = NullValueHandling.Ignore)]
public object Value = null;
public static Message Call (string targetId, string method, params object[] args) => new Message {
MessageType = MessageType.Call,
TargetId = targetId,
Key = method,
Value = args,
};
public static Message Event (string targetId, string eventType) => new Message {
MessageType = MessageType.Event,
TargetId = targetId,
Key = eventType,
};
}
[JsonConverter (typeof (StringEnumConverter))]
public enum MessageType
{
[EnumMember(Value = "nop")]
Nop,
[EnumMember(Value = "create")]
Create,
[EnumMember(Value = "set")]
Set,
[EnumMember(Value = "call")]
Call,
[EnumMember(Value = "listen")]
Listen,
[EnumMember(Value = "event")]
Event,
}
}
| using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Ooui
{
public class Message
{
[JsonProperty("mid")]
public long Id = GenerateId ();
[JsonProperty("m")]
public MessageType MessageType = MessageType.Nop;
[JsonProperty("id")]
public string TargetId = "";
[JsonProperty("k")]
public string Key = "";
[JsonProperty("v")]
public object Value = null;
public static Message Call (string targetId, string method, params object[] args) => new Message {
MessageType = MessageType.Call,
TargetId = targetId,
Key = method,
Value = args,
};
public static Message Event (string targetId, string eventType) => new Message {
MessageType = MessageType.Event,
TargetId = targetId,
Key = eventType,
};
static long idCounter = 0;
static long GenerateId ()
{
return System.Threading.Interlocked.Increment (ref idCounter);
}
}
[JsonConverter (typeof (StringEnumConverter))]
public enum MessageType
{
[EnumMember(Value = "nop")]
Nop,
[EnumMember(Value = "create")]
Create,
[EnumMember(Value = "set")]
Set,
[EnumMember(Value = "call")]
Call,
[EnumMember(Value = "listen")]
Listen,
[EnumMember(Value = "event")]
Event,
}
}
| mit | C# |
7bf55c2298b77f2fa698f64aa2ffdce45e9c4297 | fix test | zpisgod/CIDemo,zpisgod/CIDemo | src/CIDemo/Controllers/HomeController.cs | src/CIDemo/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CIDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return Content(System.Configuration.ConfigurationManager.AppSettings["test"]);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Test()
{
return Content("Test");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CIDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return Content(System.Configuration.ConfigurationManager.AppSettings["test"]);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Test()
{
return Content("Test1");
}
}
} | mit | C# |
96ef3e05373d4f030d86151faec9fa31397c36eb | change game state to playing in awake | MrErdalUral/Cyborg-Ninja-Training-Program | Assets/Script/GameManager.cs | Assets/Script/GameManager.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public static GameManager Instance;
public GameState GameState = GameState.PLAYING;
/// <summary>
/// Awake is called when the script instance is being loaded.
/// </summary>
void Awake()
{
DontDestroyOnLoad(this);
if (Instance != this)
{
Destroy(Instance);
}
Instance = this;
GameState = GameState.PLAYING;
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
switch (GameState)
{
case GameState.MENU:
case GameState.LEVEL_START:
case GameState.LEVEL_ENDED:
case GameState.PLAYING:
case GameState.PAUSED:
case GameState.DEAD:
default:
return;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public static GameManager Instance;
public GameState GameState = GameState.PLAYING;
/// <summary>
/// Awake is called when the script instance is being loaded.
/// </summary>
void Awake()
{
DontDestroyOnLoad(this);
if (Instance != this)
{
Destroy(Instance);
}
Instance = this;
GameState = GameState.MENU;
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
switch (GameState)
{
case GameState.MENU:
case GameState.LEVEL_START:
case GameState.LEVEL_ENDED:
case GameState.PLAYING:
case GameState.PAUSED:
case GameState.DEAD:
default:
return;
}
}
}
| apache-2.0 | C# |
9f62521889a77ef0b5097dc8810f5f7cdbffb026 | prepare release | alexvictoor/BrowserLog,alexvictoor/BrowserLog,alexvictoor/BrowserLog | Global.AssemblyInfo.cs | Global.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: AssemblyCompany("Alexandre Victoor")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("1.5.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: AssemblyCompany("Alexandre Victoor")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
| apache-2.0 | C# |
32cc694891a679fa8cbb20f602ea31df54fcb27c | Fix that check not null message didn't contain argument name | paiden/Nett | Source/Nett/Extensions/GenericExtensions.cs | Source/Nett/Extensions/GenericExtensions.cs | namespace Nett.Extensions
{
using System;
internal static class GenericExtensions
{
public static T CheckNotNull<T>(this T toCheck, string argName)
where T : class
{
if (toCheck == null) { throw new ArgumentNullException(argName); }
return toCheck;
}
}
}
| namespace Nett.Extensions
{
using System;
internal static class GenericExtensions
{
public static T CheckNotNull<T>(this T toCheck, string argName)
where T : class
{
if (toCheck == null) { throw new ArgumentNullException(nameof(argName)); }
return toCheck;
}
}
}
| mit | C# |
f6f73cfc46cdbdaf4cfc57d6ced65e1f7cbf59be | Fix to the browse images coming up 404. | MichaelHorsch/ImageResizer.Sitecore.Plugin | ImageResizer.Sitecore.Plugin/SitecoreVirtualImageProviderPlugin.cs | ImageResizer.Sitecore.Plugin/SitecoreVirtualImageProviderPlugin.cs | using ImageResizer.Plugins;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImageResizer.Sitecore.Plugin
{
public class SitecoreVirtualImageProviderPlugin : IPlugin, IVirtualImageProvider
{
public IPlugin Install(global::ImageResizer.Configuration.Config c)
{
c.Plugins.add_plugin(this);
return this;
}
public bool Uninstall(global::ImageResizer.Configuration.Config c)
{
c.Plugins.remove_plugin(this);
return true;
}
private string FixVirtualPath(string virtualPath)
{
var subIndex = virtualPath.LastIndexOf("~");
if (subIndex < 0)
{
subIndex = virtualPath.LastIndexOf("-");
}
if (subIndex > 0)
{
return virtualPath.Substring(subIndex);
}
else
{
return virtualPath;
}
}
public bool FileExists(string virtualPath, NameValueCollection queryString)
{
if (virtualPath.StartsWith("/sitecore/shell/-"))
{
return false;
}
virtualPath = FixVirtualPath(virtualPath);
DynamicLink dynamicLink;
return queryString.Count > 0 && DynamicLink.TryParse(virtualPath, out dynamicLink);
}
public IVirtualFile GetFile(string virtualPath, NameValueCollection queryString)
{
virtualPath = FixVirtualPath(virtualPath);
return new SitecoreVirtualFile(virtualPath);
}
}
}
| using ImageResizer.Plugins;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImageResizer.Sitecore.Plugin
{
public class SitecoreVirtualImageProviderPlugin : IPlugin, IVirtualImageProvider
{
public IPlugin Install(global::ImageResizer.Configuration.Config c)
{
c.Plugins.add_plugin(this);
return this;
}
public bool Uninstall(global::ImageResizer.Configuration.Config c)
{
c.Plugins.remove_plugin(this);
return true;
}
private string FixVirtualPath(string virtualPath)
{
var subIndex = virtualPath.LastIndexOf("~");
if (subIndex < 0)
{
subIndex = virtualPath.LastIndexOf("-");
}
if (subIndex > 0)
{
return virtualPath.Substring(subIndex);
}
else
{
return virtualPath;
}
}
public bool FileExists(string virtualPath, NameValueCollection queryString)
{
virtualPath = FixVirtualPath(virtualPath);
DynamicLink dynamicLink;
return queryString.Count > 0 && DynamicLink.TryParse(virtualPath, out dynamicLink);
}
public IVirtualFile GetFile(string virtualPath, NameValueCollection queryString)
{
virtualPath = FixVirtualPath(virtualPath);
return new SitecoreVirtualFile(virtualPath);
}
}
}
| apache-2.0 | C# |
a979fc31c4cbaececfe02c9c408e2ce60c1485e1 | Update HttpHelpers.cs | mperdeck/jsnlog | src/JSNLog/Infrastructure/HttpHelpers.cs | src/JSNLog/Infrastructure/HttpHelpers.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
#if NET40
using System.Web;
#else
using Microsoft.AspNetCore.Http;
#endif
namespace JSNLog.Infrastructure
{
internal static class HttpHelpers
{
private static Regex _regex = new Regex(@";\s*charset=(?<charset>[^\s;]+)");
public static Encoding GetEncoding(string contentType)
{
if (string.IsNullOrEmpty(contentType))
{
return Encoding.UTF8;
}
string charset = "utf-8";
var match = _regex.Match(contentType);
if (match.Success)
{
charset = match.Groups["charset"].Value;
}
try
{
return Encoding.GetEncoding(charset);
}
catch
{
return Encoding.UTF8;
}
}
public static string GetUserIp(this HttpContext httpContext)
{
#if NET40
string userIp = (string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? httpContext.Request.UserHostAddress : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
#else
string userIp = (string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? Utils.SafeToString(httpContext.Connection.RemoteIpAddress) : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
#endif
return userIp;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
#if NET40
using System.Web;
#else
using Microsoft.AspNetCore.Http;
#endif
namespace JSNLog.Infrastructure
{
internal static class HttpHelpers
{
private static Regex _regex = new Regex(@";\s*charset=(?<charset>[^\s;]+)");
public static Encoding GetEncoding(string contentType)
{
if (string.IsNullOrEmpty(contentType))
{
return Encoding.UTF8;
}
string charset = "utf-8";
var match = _regex.Match(contentType);
if (match.Success)
{
charset = match.Groups["charset"].Value;
}
try
{
return Encoding.GetEncoding(charset);
}
catch
{
return Encoding.UTF8;
}
}
public static string GetUserIp(this HttpContext httpContext)
{
#if NET40
string userIp = httpContext.Request.UserHostAddress;
#else
string userIp = Utils.SafeToString(httpContext.Connection.RemoteIpAddress);
#endif
return userIp;
}
}
}
| mit | C# |
832481685ac5d22e785fe7aa15fa074c68bb9836 | Use type to find E I | ReiiYuki/KU-Structure | Assets/Scripts/Beam/MemberProperty.cs | Assets/Scripts/Beam/MemberProperty.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MemberProperty : MonoBehaviour {
public float length;
public int number,type;
float[] E = { 1 };
float[] I = { 1 };
public float GetI()
{
return I[type];
}
public float GetE()
{
return E[type];
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MemberProperty : MonoBehaviour {
public float E, I, length;
public int number;
}
| mit | C# |
5f7cc41f57a30dbec90003f44941f892f119d801 | Update src/Tools/ExternalAccess/AspNetCore/EmbeddedLanguages/AspNetCoreEmbeddedLanguageClassificationContext.cs | weltkante/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,bartdesmet/roslyn,dotnet/roslyn,mavasani/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,weltkante/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn | src/Tools/ExternalAccess/AspNetCore/EmbeddedLanguages/AspNetCoreEmbeddedLanguageClassificationContext.cs | src/Tools/ExternalAccess/AspNetCore/EmbeddedLanguages/AspNetCoreEmbeddedLanguageClassificationContext.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.Classification;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.AspNetCore.EmbeddedLanguages
{
internal readonly struct AspNetCoreEmbeddedLanguageClassificationContext
{
private readonly EmbeddedLanguageClassificationContext _context;
public AspNetCoreEmbeddedLanguageClassificationContext(EmbeddedLanguageClassificationContext context)
{
_context = context;
}
/// <inheritdoc cref="EmbeddedLanguageClassificationContext.SyntaxToken"/>
public SyntaxToken SyntaxToken => _context.SyntaxToken;
/// <inheritdoc cref="EmbeddedLanguageClassificationContext.SemanticModel"/>
public SemanticModel SemanticModel => _context.SemanticModel;
/// <inheritdoc cref="EmbeddedLanguageClassificationContext.CancellationToken"/>
public CancellationToken CancellationToken => _context.CancellationToken;
public void AddClassification(string classificationType, TextSpan span)
=> _context.AddClassification(classificationType, span);
}
}
| // 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.Classification;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.AspNetCore.EmbeddedLanguages
{
internal struct AspNetCoreEmbeddedLanguageClassificationContext
{
private readonly EmbeddedLanguageClassificationContext _context;
public AspNetCoreEmbeddedLanguageClassificationContext(EmbeddedLanguageClassificationContext context)
{
_context = context;
}
/// <inheritdoc cref="EmbeddedLanguageClassificationContext.SyntaxToken"/>
public SyntaxToken SyntaxToken => _context.SyntaxToken;
/// <inheritdoc cref="EmbeddedLanguageClassificationContext.SemanticModel"/>
public SemanticModel SemanticModel => _context.SemanticModel;
/// <inheritdoc cref="EmbeddedLanguageClassificationContext.CancellationToken"/>
public CancellationToken CancellationToken => _context.CancellationToken;
public void AddClassification(string classificationType, TextSpan span)
=> _context.AddClassification(classificationType, span);
}
}
| mit | C# |
28955c9ceda1279bd0008acedb17d1a151ebf1b3 | fix test std err vs std out | nh43de/ToTypeScriptD,nh43de/ToTypeScriptD,nh43de/cstsd,ToTypeScriptD/ToTypeScriptD,nh43de/ToTypeScriptD,nh43de/cstsd,ToTypeScriptD/ToTypeScriptD,ToTypeScriptD/ToTypeScriptD,nh43de/ToTypeScriptD,ToTypeScriptD/ToTypeScriptD,ToTypeScriptD/ToTypeScriptD,nh43de/ToTypeScriptD | ToTypeScriptD.Tests/ExeTests/ExeTestBase.cs | ToTypeScriptD.Tests/ExeTests/ExeTestBase.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ToTypeScriptD.Tests.ExeTests
{
public class ExeTestBase
{
string TypeScriptDExePath = @"../../../bin/ToTypeScriptD.exe";
public async Task<ExeProcessResult> Execute(string args)
{
return await Execute(new[] { args });
}
public Task<ExeProcessResult> Execute(IEnumerable<string> args)
{
var processStartInfo = new ProcessStartInfo
{
FileName = TypeScriptDExePath,
Arguments = string.Join(" ", args),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
var process = Process.Start(processStartInfo);
var stdOut = process.StandardOutput.ReadToEnd();
var stdErr = process.StandardError.ReadToEnd();
var tcs = new TaskCompletionSource<ExeProcessResult>();
process.Exited += (sender, argsX) =>
{
tcs.SetResult(new ExeProcessResult
{
StdErr = stdErr,
StdOut = stdOut,
ExitCode = process.ExitCode,
});
process.Dispose();
};
process.Start();
return tcs.Task;
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ToTypeScriptD.Tests.ExeTests
{
public class ExeTestBase
{
string TypeScriptDExePath = @"../../../bin/ToTypeScriptD.exe";
public async Task<ExeProcessResult> Execute(string args)
{
return await Execute(new[] { args });
}
public Task<ExeProcessResult> Execute(IEnumerable<string> args)
{
var processStartInfo = new ProcessStartInfo
{
FileName = TypeScriptDExePath,
Arguments = string.Join(" ", args),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
var process = Process.Start(processStartInfo);
var stdErr = process.StandardOutput.ReadToEnd();
var stdOut = process.StandardError.ReadToEnd();
var tcs = new TaskCompletionSource<ExeProcessResult>();
process.Exited += (sender, argsX) =>
{
tcs.SetResult(new ExeProcessResult
{
StdErr = stdErr,
StdOut = stdOut,
ExitCode = process.ExitCode,
});
process.Dispose();
};
process.Start();
return tcs.Task;
}
}
}
| mit | C# |
c203fd7f6b9c0ebac226c59f6d6408693ff54646 | rename shared series test | hulihutu9/Live-Charts,rusanov-vladimir/Live-Charts,DeadlyEmbrace/Live-Charts,henninltn/Live-Charts,beto-rodriguez/Live-Charts | UnitTesting/General/SeriesSharedInCharts.cs | UnitTesting/General/SeriesSharedInCharts.cs | using LiveCharts;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTesting.General
{
public partial class GeneralTest
{
[TestMethod, TestCategory("General")]
public void SharedSeries()
{
var sharedSeries = new LineSeries {Values = new ChartValues<double> {1, 2, 3}};
var lineChart1 = new BarChart
{
Series = new SeriesCollection
{
sharedSeries
}
};
lineChart1.UnsafeRedraw();
var lineChart2 = new LineChart
{
Series = new SeriesCollection
{
sharedSeries
}
};
lineChart2.UnsafeRedraw();
}
}
}
| using LiveCharts;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTesting.General
{
public partial class GeneralTest
{
[TestMethod, TestCategory("General")]
public void SharedSeriesValues()
{
var sharedSeries = new LineSeries {Values = new ChartValues<double> {1, 2, 3}};
var lineChart1 = new BarChart
{
Series = new SeriesCollection
{
sharedSeries
}
};
lineChart1.UnsafeRedraw();
var lineChart2 = new LineChart
{
Series = new SeriesCollection
{
sharedSeries
}
};
lineChart2.UnsafeRedraw();
}
}
}
| mit | C# |
8c02ab26ea9948ef6bbc8c9e04e329155b4e5faa | fix paths | nessos/Vagabond,nessos/Vagabond,mbraceproject/Vagabond,mbraceproject/Vagabond | samples/ThunkServer/thunkServer.csx | samples/ThunkServer/thunkServer.csx | #r "bin/Debug/netstandard2.0/FsPickler.dll"
#r "bin/Debug/netstandard2.0/Vagabond.AssemblyParser.dll"
#r "bin/Debug/netstandard2.0/Vagabond.dll"
#r "bin/Debug/netstandard2.0/ThunkServer.exe"
// before running sample, don't forget to set binding redirects to FSharp.Core in InteractiveHost.exe
using System.Linq;
using ThunkServer;
ThunkClient.Executable = "bin/Debug/net45/ThunkServer.exe";
var client = ThunkClient.InitLocal();
client.EvaluateDelegate(() => Console.WriteLine("C# Interactive, meet Vagabond!"));
client.EvaluateDelegate(() => System.Diagnostics.Process.GetCurrentProcess().Id);
client.EvaluateDelegate(() => Enumerable.Range(0, 10).Select(x => x + 1).Where(x => x % 2 == 0).Sum());
int x = 1;
for (int i = 0; i < 10; i++)
x = client.EvaluateDelegate(() => x + x);
x; | #r "bin/Debug/net45/FsPickler.dll"
#r "bin/Debug/net45/Vagabond.AssemblyParser.dll"
#r "bin/Debug/net45/Vagabond.dll"
#r "bin/Debug/net45/ThunkServer.exe"
// before running sample, don't forget to set binding redirects to FSharp.Core in InteractiveHost.exe
using System.Linq;
using ThunkServer;
ThunkClient.Executable = "bin/Debug/net45/ThunkServer.exe";
var client = ThunkClient.InitLocal();
client.EvaluateDelegate(() => Console.WriteLine("C# Interactive, meet Vagabond!"));
client.EvaluateDelegate(() => System.Diagnostics.Process.GetCurrentProcess().Id);
client.EvaluateDelegate(() => Enumerable.Range(0, 10).Select(x => x + 1).Where(x => x % 2 == 0).Sum());
int x = 1;
for (int i = 0; i < 10; i++)
x = client.EvaluateDelegate(() => x + x);
x; | mit | C# |
52d2eada1d38c18dd93462c6e34cb72f44da9a4b | remove warnings on mono | huoxudong125/Metrics.NET,cvent/Metrics.NET,ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET,etishor/Metrics.NET,alhardy/Metrics.NET,Recognos/Metrics.NET,mnadel/Metrics.NET,huoxudong125/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET,ntent-ad/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,Recognos/Metrics.NET,mnadel/Metrics.NET | Samples/Metrics.Samples/MultiRegistryMetrics.cs | Samples/Metrics.Samples/MultiRegistryMetrics.cs | using System;
using System.Linq;
using Metrics.Core;
using Metrics.Reporters;
namespace Metrics.Samples
{
public class MultiRegistryMetrics
{
private readonly MetricsRegistry first = new LocalRegistry("First Registry");
private readonly MetricsRegistry second = new LocalRegistry("Second Registry");
private readonly Counter firstCounter;
private readonly Meter secondMeter;
public MultiRegistryMetrics()
{
this.firstCounter = first.Counter("Counter In First Registry", Unit.Requests);
this.secondMeter = second.Meter("Meter In Second Registry", Unit.Errors, TimeUnit.Seconds);
}
public void Run()
{
this.firstCounter.Increment();
this.secondMeter.Mark();
}
public void Report()
{
var jsonFirst = RegistrySerializer.GetAsJson(this.first);
var jsonSecond = RegistrySerializer.GetAsJson(this.second);
var countersFromFirst = this.first.Counters.Select(c => new { Name = c.Name, Value = c.Value })
.ToArray();
Console.WriteLine(jsonFirst);
Console.WriteLine(jsonSecond);
Console.WriteLine(countersFromFirst.Length);
}
}
}
| using System.Linq;
using Metrics.Core;
using Metrics.Reporters;
namespace Metrics.Samples
{
public class MultiRegistryMetrics
{
private readonly MetricsRegistry first = new LocalRegistry("First Registry");
private readonly MetricsRegistry second = new LocalRegistry("Second Registry");
private readonly Counter firstCounter;
private readonly Meter secondMeter;
public MultiRegistryMetrics()
{
this.firstCounter = first.Counter("Counter In First Registry", Unit.Requests);
this.secondMeter = second.Meter("Meter In Second Registry", Unit.Errors, TimeUnit.Seconds);
}
public void Run()
{
this.firstCounter.Increment();
this.secondMeter.Mark();
}
public void Report()
{
var jsonFirst = RegistrySerializer.GetAsJson(this.first);
var jsonSecond = RegistrySerializer.GetAsJson(this.second);
var countersFromFirst = this.first.Counters.Select(c => new { Name = c.Name, Value = c.Value })
.ToArray();
}
}
}
| apache-2.0 | C# |
ab1a681b2fda3c8cf4a332f993728c15872e5b0a | Add remind_on to insert statement | schlos/denver-schedules-api,codeforamerica/denver-schedules-api,codeforamerica/denver-schedules-api,schlos/denver-schedules-api | Schedules.API/Tasks/Reminders/CreateReminder.cs | Schedules.API/Tasks/Reminders/CreateReminder.cs | using System;
using Simpler;
using Schedules.API.Models;
using Dapper;
using System.Linq;
namespace Schedules.API.Tasks
{
public class CreateReminder: InOutTask<CreateReminder.Input, CreateReminder.Output>
{
public FetchReminderType FetchReminderType { get; set; }
public class Input
{
public Reminder Reminder { get; set; }
public String ReminderTypeName { get; set; }
}
public class Output
{
public Reminder Reminder { get; set; }
}
public override void Execute()
{
FetchReminderType.In.ReminderTypeName = In.ReminderTypeName;
FetchReminderType.Execute();
In.Reminder.ReminderType = FetchReminderType.Out.ReminderType;
Out.Reminder = new Reminder ();
using (var connection = Db.Connect ()) {
try{
Out.Reminder = connection.Query<Reminder, ReminderType, Reminder>(
sql,
(reminder, reminderType) => {reminder.ReminderType = reminderType; return reminder;},
In.Reminder).SingleOrDefault();
}
catch(Exception ex){
Console.WriteLine (ex);
}
}
}
const string sql = @"
with insertReminder as (
insert into Reminders(contact, message, remind_on, verified, address, reminder_type_id)
values(@Contact, @Message, @RemindOn, @Verified, @Address, @ReminderTypeId) returning *
)
select *
from insertReminder r
left join reminder_types t
on t.id = r.reminder_type_id
;
";
}
}
| using System;
using Simpler;
using Schedules.API.Models;
using Dapper;
using System.Linq;
namespace Schedules.API.Tasks
{
public class CreateReminder: InOutTask<CreateReminder.Input, CreateReminder.Output>
{
public FetchReminderType FetchReminderType { get; set; }
public class Input
{
public Reminder Reminder { get; set; }
public String ReminderTypeName { get; set; }
}
public class Output
{
public Reminder Reminder { get; set; }
}
public override void Execute()
{
FetchReminderType.In.ReminderTypeName = In.ReminderTypeName;
FetchReminderType.Execute();
In.Reminder.ReminderType = FetchReminderType.Out.ReminderType;
Out.Reminder = new Reminder ();
using (var connection = Db.Connect ()) {
try{
Out.Reminder = connection.Query<Reminder, ReminderType, Reminder>(
sql,
(reminder, reminderType) => {reminder.ReminderType = reminderType; return reminder;},
In.Reminder).SingleOrDefault();
}
catch(Exception ex){
Console.WriteLine (ex);
}
}
}
const string sql = @"
with insertReminder as (
insert into Reminders(contact, message, verified, address, reminder_type_id)
values(@Contact, @Message, @Verified, @Address, @ReminderTypeId) returning *
)
select *
from insertReminder r
left join reminder_types t
on t.id = r.reminder_type_id
;
";
}
}
| mit | C# |
c9eb4bd4c1d332d058e0090a7b918c406ed43e51 | Fix Poland 100th anniversary | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Src/Nager.Date/PublicHolidays/PolandProvider.cs | Src/Nager.Date/PublicHolidays/PolandProvider.cs | using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class PolandProvider : CatholicBaseProvider
{
public override IEnumerable<PublicHoliday> Get(int year)
{
//Poland
//https://en.wikipedia.org/wiki/Public_holidays_in_Poland
var countryCode = CountryCode.PL;
var easterSunday = base.EasterSunday(year);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "Nowy Rok", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 1, 6, "Święto Trzech Króli", "Epiphany", countryCode));
items.Add(new PublicHoliday(easterSunday, "pierwszy dzień Wielkiej Nocy", "Easter Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(1), "drugi dzień Wielkiej Nocy", "Easter Monday", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "Święto Państwowe", "May Day", countryCode));
items.Add(new PublicHoliday(year, 5, 3, "Święto Narodowe Trzeciego Maja", "Constitution Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(49), "pierwszy dzień Zielonych Świątek", "Pentecost Sunday", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(60), "dzień Bożego Ciała", "Corpus Christi", countryCode));
items.Add(new PublicHoliday(year, 8, 15, "Wniebowzięcie Najświętszej Maryi Panny", "Assumption Day", countryCode));
items.Add(new PublicHoliday(year, 11, 1, "Wszystkich Świętych", "All Saints' Day", countryCode));
items.Add(new PublicHoliday(year, 11, 11, "Narodowe Święto Niepodległości", "Independence Day", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "pierwszy dzień Bożego Narodzenia", "Christmas Day", countryCode));
items.Add(new PublicHoliday(year, 12, 26, "drugi dzień Bożego Narodzenia", "St. Stephen's Day", countryCode));
if (year == 2018)
{
//100th anniversary
items.Add(new PublicHoliday(year, 11, 12, "Narodowe Święto Niepodległości", "Independence Day", countryCode));
}
return items.OrderBy(o => o.Date);
}
}
}
| using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class PolandProvider : CatholicBaseProvider
{
public override IEnumerable<PublicHoliday> Get(int year)
{
//Poland
//https://en.wikipedia.org/wiki/Public_holidays_in_Poland
var countryCode = CountryCode.PL;
var easterSunday = base.EasterSunday(year);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "Nowy Rok", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 1, 6, "Święto Trzech Króli", "Epiphany", countryCode));
items.Add(new PublicHoliday(easterSunday, "pierwszy dzień Wielkiej Nocy", "Easter Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(1), "drugi dzień Wielkiej Nocy", "Easter Monday", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "Święto Państwowe", "May Day", countryCode));
items.Add(new PublicHoliday(year, 5, 3, "Święto Narodowe Trzeciego Maja", "Constitution Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(49), "pierwszy dzień Zielonych Świątek", "Pentecost Sunday", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(60), "dzień Bożego Ciała", "Corpus Christi", countryCode));
items.Add(new PublicHoliday(year, 8, 15, "Wniebowzięcie Najświętszej Maryi Panny", "Assumption Day", countryCode));
items.Add(new PublicHoliday(year, 11, 1, "Wszystkich Świętych", "All Saints' Day", countryCode));
items.Add(new PublicHoliday(year, 11, 11, "Narodowe Święto Niepodległości", "Independence Day", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "pierwszy dzień Bożego Narodzenia", "Christmas Day", countryCode));
items.Add(new PublicHoliday(year, 12, 26, "drugi dzień Bożego Narodzenia", "St. Stephen's Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| mit | C# |
f6a00e250f75e0a07fa18570cfeacde8377bb4bd | update version | IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates | build.cake | build.cake | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var buildArtifacts = Directory("./artifacts/packages");
var packageVersion = "2.3.1";
///////////////////////////////////////////////////////////////////////////////
// Clean
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[]
{
buildArtifacts,
Directory("./feed/content/UI")
});
});
///////////////////////////////////////////////////////////////////////////////
// Copy
///////////////////////////////////////////////////////////////////////////////
Task("Copy")
.IsDependentOn("Clean")
.Does(() =>
{
CreateDirectory("./feed/content");
// copy the singel csproj templates
var files = GetFiles("./src/**/*.*");
CopyFiles(files, "./feed/content", true);
// copy the UI files
files = GetFiles("./ui/**/*.*");
CopyFiles(files, "./feed/content/ui", true);
});
///////////////////////////////////////////////////////////////////////////////
// Pack
///////////////////////////////////////////////////////////////////////////////
Task("Pack")
.IsDependentOn("Clean")
.IsDependentOn("Copy")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = packageVersion,
OutputDirectory = buildArtifacts
};
if (AppVeyor.IsRunningOnAppVeyor)
{
settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings);
});
Task("Default")
.IsDependentOn("Pack");
RunTarget(target); | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var buildArtifacts = Directory("./artifacts/packages");
var packageVersion = "2.3.0";
///////////////////////////////////////////////////////////////////////////////
// Clean
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[]
{
buildArtifacts,
Directory("./feed/content/UI")
});
});
///////////////////////////////////////////////////////////////////////////////
// Copy
///////////////////////////////////////////////////////////////////////////////
Task("Copy")
.IsDependentOn("Clean")
.Does(() =>
{
CreateDirectory("./feed/content");
// copy the singel csproj templates
var files = GetFiles("./src/**/*.*");
CopyFiles(files, "./feed/content", true);
// copy the UI files
files = GetFiles("./ui/**/*.*");
CopyFiles(files, "./feed/content/ui", true);
});
///////////////////////////////////////////////////////////////////////////////
// Pack
///////////////////////////////////////////////////////////////////////////////
Task("Pack")
.IsDependentOn("Clean")
.IsDependentOn("Copy")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = packageVersion,
OutputDirectory = buildArtifacts
};
if (AppVeyor.IsRunningOnAppVeyor)
{
settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings);
});
Task("Default")
.IsDependentOn("Pack");
RunTarget(target); | apache-2.0 | C# |
c59e04991c55e4a18cb6cd80d83b4219237aba73 | Add Octopus Deploy | dcomartin/Cake.Demo | build.cake | build.cake | #tool "nuget:?package=xunit.runner.console"
#tool "nuget:?package=OctopusTools"
var target = Argument("target", "Build");
Task("Default")
.IsDependentOn("xUnit")
.IsDependentOn("Pack")
.IsDependentOn("OctoPush")
.IsDependentOn("OctoRelease");
Task("Build")
.Does(() =>
{
MSBuild("./src/CakeDemo.sln");
});
Task("xUnit")
.IsDependentOn("Build")
.Does(() =>
{
XUnit2("./src/CakeDemo.Tests/bin/Debug/CakeDemo.Tests.dll");
});
Task("Pack")
.IsDependentOn("Build")
.Does(() => {
var nuGetPackSettings = new NuGetPackSettings {
Id = "CakeDemo",
Version = "0.0.0.1",
Title = "Cake Demo",
Authors = new[] {"Derek Comartin"},
Description = "Demo of creating cake.build scripts.",
Summary = "Excellent summary of what the Cake (C# Make) build tool does.",
ProjectUrl = new Uri("https://github.com/dcomartin/Cake.Demo"),
Files = new [] {
new NuSpecContent {Source = "CakeDemo.exe", Target = "bin"},
},
BasePath = "./src/CakeDemo/bin/Debug",
OutputDirectory = "./nuget"
};
NuGetPack(nuGetPackSettings);
});
Task("OctoPush")
.IsDependentOn("Pack")
.Does(() => {
OctoPush("http://your.octopusdeploy.server/", "YOUR_API_KEY", new FilePath("./nuget/CakeDemo.0.0.0.1.nupkg"),
new OctopusPushSettings {
ReplaceExisting = true
});
});
Task("OctoRelease")
.IsDependentOn("OctoPush")
.Does(() => {
OctoCreateRelease("CakeDemo", new CreateReleaseSettings {
Server = "http://your.octopusdeploy.server/",
ApiKey = "YOUR_API_KEY",
ReleaseNumber = "0.0.0.1"
});
});
RunTarget(target); | #tool "nuget:?package=xunit.runner.console"
var target = Argument("target", "Build");
Task("Default")
.IsDependentOn("xUnit");
Task("Build")
.Does(() =>
{
MSBuild("./src/CakeDemo.sln");
});
Task("xUnit")
.IsDependentOn("Build")
.Does(() =>
{
XUnit2("./src/CakeDemo.Tests/bin/Debug/CakeDemo.Tests.dll");
});
RunTarget(target); | mit | C# |
6da5d5c24538bd3322dc912965bd56a73548066f | Correct the JSON name for the position length on tokens (#5499) | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Nest/Indices/Analyze/AnalyzeToken.cs | src/Nest/Indices/Analyze/AnalyzeToken.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.Runtime.Serialization;
namespace Nest
{
[DataContract]
public class AnalyzeToken
{
[DataMember(Name ="end_offset")]
public long EndOffset { get; internal set; }
[DataMember(Name ="position")]
public long Position { get; internal set; }
[DataMember(Name ="positionLength")]
public long? PositionLength { get; internal set; }
[DataMember(Name ="start_offset")]
public long StartOffset { get; internal set; }
[DataMember(Name ="token")]
public string Token { get; internal set; }
[DataMember(Name ="type")]
public string Type { 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.Runtime.Serialization;
namespace Nest
{
[DataContract]
public class AnalyzeToken
{
[DataMember(Name ="end_offset")]
public long EndOffset { get; internal set; }
[DataMember(Name ="position")]
public long Position { get; internal set; }
[DataMember(Name ="position_length")]
public long? PositionLength { get; internal set; }
[DataMember(Name ="start_offset")]
public long StartOffset { get; internal set; }
[DataMember(Name ="token")]
public string Token { get; internal set; }
[DataMember(Name ="type")]
public string Type { get; internal set; }
}
}
| apache-2.0 | C# |
4780f49edbfc96aa683867169e0f47fb64031281 | Set background color to black | ashokgelal/MacCaptureSample | CaptureDevice/MainWindowController.cs | CaptureDevice/MainWindowController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.AVFoundation;
namespace CaptureDevice
{
public partial class MainWindowController : MonoMac.AppKit.NSWindowController
{
#region Constructors
// Called when created from unmanaged code
public MainWindowController(IntPtr handle) : base(handle)
{
Initialize();
}
// Called when created directly from a XIB file
[Export("initWithCoder:")]
public MainWindowController(NSCoder coder) : base(coder)
{
Initialize();
}
// Call to load from the XIB/NIB file
public MainWindowController() : base("MainWindow")
{
Initialize();
}
// Shared initialization code
void Initialize()
{
}
#endregion
//strongly typed window accessor
public new MainWindow Window
{
get
{
return (MainWindow)base.Window;
}
}
public override void AwakeFromNib()
{
Window.BackgroundColor = NSColor.Black;
}
AVCaptureSession session;
public override void WindowDidLoad()
{
base.WindowDidLoad();
session = new AVCaptureSession() { SessionPreset = AVCaptureSession.PresetMedium };
var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
var input = AVCaptureDeviceInput.FromDevice(captureDevice);
if (input == null)
{
Console.WriteLine("No input - this won't work on the simulator, try a physical device");
}
session.AddInput(input);
var captureVideoPreviewLayer = new AVCaptureVideoPreviewLayer(session);
var contentView = Window.ContentView;
contentView.WantsLayer = true;
captureVideoPreviewLayer.Frame = contentView.Bounds;
contentView.Layer.AddSublayer(captureVideoPreviewLayer);
session.StartRunning();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.AVFoundation;
namespace CaptureDevice
{
public partial class MainWindowController : MonoMac.AppKit.NSWindowController
{
#region Constructors
// Called when created from unmanaged code
public MainWindowController(IntPtr handle) : base(handle)
{
Initialize();
}
// Called when created directly from a XIB file
[Export("initWithCoder:")]
public MainWindowController(NSCoder coder) : base(coder)
{
Initialize();
}
// Call to load from the XIB/NIB file
public MainWindowController() : base("MainWindow")
{
Initialize();
}
// Shared initialization code
void Initialize()
{
}
#endregion
//strongly typed window accessor
public new MainWindow Window
{
get
{
return (MainWindow)base.Window;
}
}
AVCaptureSession session;
public override void WindowDidLoad()
{
base.WindowDidLoad();
session = new AVCaptureSession() { SessionPreset = AVCaptureSession.PresetMedium };
var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
var input = AVCaptureDeviceInput.FromDevice(captureDevice);
if (input == null)
{
Console.WriteLine("No input - this won't work on the simulator, try a physical device");
}
session.AddInput(input);
var captureVideoPreviewLayer = new AVCaptureVideoPreviewLayer(session);
var contentView = Window.ContentView;
contentView.WantsLayer = true;
captureVideoPreviewLayer.Frame = contentView.Bounds;
contentView.Layer.AddSublayer(captureVideoPreviewLayer);
session.StartRunning();
}
}
}
| mit | C# |
1f341abb8e95ac0657afade56534b062e7628ad9 | Add ToString method to empty object | textamina/scriban,lunet-io/scriban | src/Scriban/Runtime/EmptyScriptObject.cs | src/Scriban/Runtime/EmptyScriptObject.cs | // Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using Scriban.Parsing;
using Scriban.Syntax;
namespace Scriban.Runtime
{
/// <summary>
/// The empty object (unique singleton, cannot be modified, does not contain any properties)
/// </summary>
[DebuggerDisplay("<empty object>")]
public sealed class EmptyScriptObject : IScriptObject
{
public static readonly EmptyScriptObject Default = new EmptyScriptObject();
private EmptyScriptObject()
{
}
public int Count => 0;
public IEnumerable<string> GetMembers()
{
yield break;
}
public bool Contains(string member)
{
return false;
}
public bool IsReadOnly
{
get => true;
set { }
}
public bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value)
{
value = null;
return false;
}
public bool CanWrite(string member)
{
return false;
}
public void SetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly)
{
throw new ScriptRuntimeException(span, "Cannot set a property on the empty object");
}
public bool Remove(string member)
{
return false;
}
public void SetReadOnly(string member, bool readOnly)
{
}
public IScriptObject Clone(bool deep)
{
return this;
}
public override string ToString()
{
return string.Empty;
}
}
} | // Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System.Collections.Generic;
using Scriban.Parsing;
using Scriban.Syntax;
namespace Scriban.Runtime
{
/// <summary>
/// The empty object (unique singleton, cannot be modified, does not contain any properties)
/// </summary>
public sealed class EmptyScriptObject : IScriptObject
{
public static readonly EmptyScriptObject Default = new EmptyScriptObject();
private EmptyScriptObject()
{
}
public int Count => 0;
public IEnumerable<string> GetMembers()
{
yield break;
}
public bool Contains(string member)
{
return false;
}
public bool IsReadOnly
{
get => true;
set { }
}
public bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value)
{
value = null;
return false;
}
public bool CanWrite(string member)
{
return false;
}
public void SetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly)
{
throw new ScriptRuntimeException(span, "Cannot set a property on the empty object");
}
public bool Remove(string member)
{
return false;
}
public void SetReadOnly(string member, bool readOnly)
{
}
public IScriptObject Clone(bool deep)
{
return this;
}
}
} | bsd-2-clause | C# |
a36e1c3faf0e45a83b8cf68fbd69d0a0b47572c1 | Add String Argument Extension method | thnetii/dotnet-common | src/THNETII.Common/ArgumentExtensions.cs | src/THNETII.Common/ArgumentExtensions.cs | using System;
namespace THNETII.Common
{
public static class ArgumentExtensions
{
public static T ThrowIfNull<T>(this T instance, string name) where T : class
=> instance ?? throw new ArgumentNullException(name);
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
public static string ThrowIfNullOrWhiteSpace(this string value, string name)
{
if (string.IsNullOrWhiteSpace(value))
throw value == null ? new ArgumentNullException(nameof(name)) : new ArgumentException("value must neither be empty, nor null, nor whitespace-only.", name);
return value;
}
}
}
| using System;
namespace THNETII.Common
{
public static class ArgumentExtensions
{
public static T ThrowIfNull<T>(this T instance, string name) where T : class
=> instance ?? throw new ArgumentNullException(name);
}
}
| mit | C# |
d02fd4c931a015eb76a5fac7d3b76fc3e2b5a31f | add version info to home page | IdentityServer/IdentityServer4.Quickstart.UI,IdentityServer/IdentityServer4.Quickstart.UI,IdentityServer/IdentityServer4.Quickstart.UI,IdentityServer/IdentityServer4.Quickstart.UI | Views/Home/Index.cshtml | Views/Home/Index.cshtml | @{
var version = typeof(IdentityServer4.Hosting.IdentityServerMiddleware).Assembly.GetName().Version.ToString();
}
<div class="welcome-page">
<div class="row page-header">
<div class="col-sm-10">
<h1>
<img class="icon" src="~/icon.jpg">
Welcome to IdentityServer4
<small>(version @version)</small>
</h1>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<p>
IdentityServer publishes a
<a href="~/.well-known/openid-configuration">discovery document</a>
where you can find metadata and links to all the endpoints, key material, etc.
</p>
</div>
<div class="col-sm-8">
<p>
Click <a href="~/grants">here</a> to manage your stored grants.
</p>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<p>
Here are links to the
<a href="https://github.com/identityserver/IdentityServer4">source code repository</a>,
and <a href="https://github.com/identityserver/IdentityServer4.Samples">ready to use samples</a>.
</p>
</div>
</div>
</div>
| <div class="welcome-page">
<div class="row page-header">
<div class="col-sm-10">
<h1>
<img class="icon" src="~/icon.jpg">
Welcome to IdentityServer4
@*<small>(build {version})</small>*@
</h1>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<p>
IdentityServer publishes a
<a href="~/.well-known/openid-configuration">discovery document</a>
where you can find metadata and links to all the endpoints, key material, etc.
</p>
</div>
<div class="col-sm-8">
<p>
Click <a href="~/grants">here</a> to manage your stored grants.
</p>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<p>
Here are links to the
<a href="https://github.com/identityserver/IdentityServer4">source code repository</a>,
and <a href="https://github.com/identityserver/IdentityServer4.Samples">ready to use samples</a>.
</p>
</div>
</div>
</div>
| apache-2.0 | C# |
ebd7d1b7654419e07d4a5faa2b38202440969596 | Update Call.cs | RR-Studio/RealEstateCrm,RR-Studio/RealEstateCrm,RR-Studio/RealEstateCrm | WebApp/Entities/Call.cs | WebApp/Entities/Call.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApp.Models;
namespace WebApp.Entities
{
public class Call
{
public int Id { get; set; }
public string Status { get; set; }
public DateTime Date { get; set; }
public int HousingId { get; set; }
public Housing Housing { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser User { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApp.Models;
namespace WebApp.Entities
{
public class Call
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser User { get; set; }
}
}
| mit | C# |
f160f0ab7a444726ac829176242f2b693faa78a0 | Update copyright info | hydna/Hydna.NET | src/Hydna.Net/Properties/AssemblyInfo.cs | src/Hydna.Net/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("Hydna.Net")]
[assembly: AssemblyDescription (".NET bindings for Hydna")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("Hydna AB")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("(c) Hydna AB 2013-2014")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("0.1.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("Hydna.Net")]
[assembly: AssemblyDescription (".NET bindings for Hydna")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("Hydna AB")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Hydna AB")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("0.1.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# |
e78564bb898d07be9f3ea38b24b774dd12797372 | Fix docs | DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MRTK/SDK/Editor/Migration/ButtonConfigHelperMigrationHandler.cs | Assets/MRTK/SDK/Editor/Migration/ButtonConfigHelperMigrationHandler.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.UI;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Migration handler for migrating buttons with custom icons to the button config helper.
/// </summary>
public class ButtonConfigHelperMigrationHandler : IMigrationHandler
{
/// <inheritdoc />
public bool CanMigrate(GameObject gameObject)
{
ButtonConfigHelper bch = gameObject.GetComponent<ButtonConfigHelper>();
return bch != null && bch.EditorCheckForCustomIcon();
}
/// <inheritdoc />
public void Migrate(GameObject gameObject)
{
ButtonConfigHelper bch = gameObject.GetComponent<ButtonConfigHelper>();
bch.EditorUpgradeCustomIcon();
}
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.UI;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Migration handler for migrating buttons with custom icons to the button config helper.
/// </summary>
public class ButtonConfigHelperMigrationHandler : IMigrationHandler
{
public bool CanMigrate(GameObject gameObject)
{
ButtonConfigHelper bch = gameObject.GetComponent<ButtonConfigHelper>();
return bch != null && bch.EditorCheckForCustomIcon();
}
public void Migrate(GameObject gameObject)
{
ButtonConfigHelper bch = gameObject.GetComponent<ButtonConfigHelper>();
bch.EditorUpgradeCustomIcon();
}
}
} | mit | C# |
fae5abe70b88a1232e289ac158326e1b98692fe1 | Remove unnecessary, and wrong, check | IvionSauce/MeidoBot | MiscUtils/ExtensionMethods.cs | MiscUtils/ExtensionMethods.cs | using System;
public static class ExtensionMethods
{
public static string Str(this TimeSpan duration)
{
var hours = Math.Abs((int)duration.TotalHours);
var minutes = Math.Abs(duration.Minutes);
int seconds = Math.Abs(duration.Seconds);
if (duration >= TimeSpan.Zero)
return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
else
return string.Format("-{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
}
} | using System;
public static class ExtensionMethods
{
public static string Str(this TimeSpan duration)
{
var hours = Math.Abs((int)duration.TotalHours);
var minutes = Math.Abs(duration.Minutes);
int seconds = Math.Abs(duration.Seconds);
if (Math.Abs(duration.Milliseconds) >= 500)
seconds++;
if (duration >= TimeSpan.Zero)
return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
else
return string.Format("-{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
}
} | bsd-2-clause | C# |
9dfbdfea764dd9e9793c5190e35e6458f5b414cc | Update help message | matteocontrini/locuspocusbot | LocusPocusBot/Handlers/HelpHandler.cs | LocusPocusBot/Handlers/HelpHandler.cs | using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types.Enums;
namespace LocusPocusBot.Handlers
{
public class HelpHandler : HandlerBase
{
private readonly IBotService bot;
public HelpHandler(IBotService botService)
{
this.bot = botService;
}
public override async Task Run()
{
StringBuilder msg = new StringBuilder();
msg.AppendLine("*LocusPocus* è il bot per controllare la disponibilità delle aule presso i poli di Mesiano e Povo (Polo Ferrari) dell'Università di Trento 🎓");
msg.AppendLine();
msg.AppendLine("*Scrivi* /povo *oppure* /mesiano *per ottenere la lista delle aule libere.*");
msg.AppendLine();
msg.AppendLine("Sviluppato da Matteo Contrini (@matteocontrini). Si ringraziano Alessandro Conti per il nome del bot e Dario Crisafulli per il logo.");
msg.AppendLine();
msg.AppendLine("Il bot è [open source](https://github.com/matteocontrini/locuspocusbot) 🤓");
await this.bot.Client.SendTextMessageAsync(
chatId: this.Chat.Id,
text: msg.ToString(),
parseMode: ParseMode.Markdown
);
}
}
}
| using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types.Enums;
namespace LocusPocusBot.Handlers
{
public class HelpHandler : HandlerBase
{
private readonly IBotService bot;
public HelpHandler(IBotService botService)
{
this.bot = botService;
}
public override async Task Run()
{
StringBuilder msg = new StringBuilder();
msg.AppendLine("*LocusPocus* è il bot per controllare la disponibilità delle aule presso i poli di Mesiano e Povo (Polo Ferrari) dell'Università di Trento 🎓");
msg.AppendLine();
msg.AppendLine("Scrivi /povo oppure /mesiano per ottenere la lista delle aule libere.");
msg.AppendLine();
msg.AppendLine("Sviluppato da Matteo Contrini (@matteocontrini). Si ringraziano Alessandro Conti per il nome del bot e Dario Crisafulli per il logo.");
msg.AppendLine();
msg.AppendLine("Il bot è [open source](https://github.com/matteocontrini/locuspocusbot) 🤓");
await this.bot.Client.SendTextMessageAsync(
chatId: this.Chat.Id,
text: msg.ToString(),
parseMode: ParseMode.Markdown
);
}
}
}
| mit | C# |
16b170dea8af4eaeed9fe1b7bd61e34ebf7bf038 | Revert "Dont make RasterFeature disposable" | charlenni/Mapsui,charlenni/Mapsui,pauldendulk/Mapsui | Mapsui.Core/Features/RasterFeature.cs | Mapsui.Core/Features/RasterFeature.cs |
using System;
namespace Mapsui.Layers
{
public class RasterFeature : BaseFeature, IFeature, IDisposable
{
#pragma warning disable IDISP008
public MRaster? Raster { get; }
#pragma warning restore IDISP008
public MRect? Extent => Raster;
public RasterFeature(RasterFeature rasterFeature) : base(rasterFeature)
{
Raster = rasterFeature.Raster == null ? null : new MRaster(rasterFeature.Raster);
}
public RasterFeature(MRaster? raster)
{
Raster = raster;
}
public void CoordinateVisitor(Action<double, double, CoordinateSetter> visit)
{
if (Raster != null)
foreach (var point in new[] { Raster.Min, Raster.Max })
visit(point.X, point.Y, (x, y) => {
point.X = x;
point.Y = x;
});
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Raster?.Dispose();
}
}
}
}
|
using System;
namespace Mapsui.Layers
{
public class RasterFeature : BaseFeature, IFeature
{
#pragma warning disable IDISP008
public MRaster? Raster { get; }
#pragma warning restore IDISP008
public MRect? Extent => Raster;
public RasterFeature(RasterFeature rasterFeature) : base(rasterFeature)
{
Raster = rasterFeature.Raster == null ? null : new MRaster(rasterFeature.Raster);
}
public RasterFeature(MRaster? raster)
{
Raster = raster;
}
public void CoordinateVisitor(Action<double, double, CoordinateSetter> visit)
{
if (Raster != null)
foreach (var point in new[] { Raster.Min, Raster.Max })
visit(point.X, point.Y, (x, y) => {
point.X = x;
point.Y = x;
});
}
}
}
| mit | C# |
a942f6789a973abaed71449c66ca7ddbcdc5ae9c | Reduce render blocking JavaScript | martincostello/website,martincostello/website,martincostello/website,martincostello/website | src/Website/Views/Shared/_Scripts.cshtml | src/Website/Views/Shared/_Scripts.cshtml | @model BowerVersions
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js" asp-append-version="true"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js" asp-append-version="true"></script>
<script src="~/lib/jquery.lazyload/jquery.lazyload.min.js" asp-append-version="true"></script>
<script src="~/lib/moment/moment.js" asp-append-version="true"></script>
<script src="~/assets/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/@Model["jquery"]/jquery.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous" async
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/@Model["bootstrap"]/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous" defer
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/@Model["jquery.lazyload"]/jquery.lazyload.min.js" integrity="sha256-rXnOfjTRp4iAm7hTAxEz3irkXzwZrElV2uRsdJAYjC4=" crossorigin="anonymous" defer
asp-fallback-src="~/lib/jquery.lazyload/jquery.lazyload.min.js"
asp-fallback-test="window.$.fn.lazyload">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/@Model["moment"]/moment.min.js" integrity="sha384-7pfELK0arQ3VANqV4kiPWPh5wOsrfitjFGF/NdyHXUJ3JJPy/rNhasPtdkaNKhul" crossorigin="anonymous" async
asp-fallback-src="~/lib/moment/min/moment.min.js"
asp-fallback-test="window.moment">
</script>
<script src="~/assets/js/site.min.js" asp-append-version="true" defer></script>
</environment>
| @model BowerVersions
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js" asp-append-version="true"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js" asp-append-version="true"></script>
<script src="~/lib/jquery.lazyload/jquery.lazyload.min.js" asp-append-version="true"></script>
<script src="~/lib/moment/moment.js" asp-append-version="true"></script>
<script src="~/assets/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/@Model["jquery"]/jquery.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/@Model["bootstrap"]/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/@Model["jquery.lazyload"]/jquery.lazyload.min.js" integrity="sha256-rXnOfjTRp4iAm7hTAxEz3irkXzwZrElV2uRsdJAYjC4=" crossorigin="anonymous"
asp-fallback-src="~/lib/jquery.lazyload/jquery.lazyload.min.js"
asp-fallback-test="window.$.fn.lazyload">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/@Model["moment"]/moment.min.js" integrity="sha384-7pfELK0arQ3VANqV4kiPWPh5wOsrfitjFGF/NdyHXUJ3JJPy/rNhasPtdkaNKhul" crossorigin="anonymous"
asp-fallback-src="~/lib/moment/min/moment.min.js"
asp-fallback-test="window.moment">
</script>
<script src="~/assets/js/site.min.js" asp-append-version="true"></script>
</environment>
| apache-2.0 | C# |
fd12cacd37d528a5d517384b435b991fd47c2864 | Remove empty line. | taskmatics/aspnet-windows-service,taskmatics/aspnet-windows-service | src/AspNetWindowsService/Program.cs | src/AspNetWindowsService/Program.cs | using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Hosting.Internal;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
namespace MyDnxService
{
public class Program : ServiceBase
{
private readonly IServiceProvider _serviceProvider;
private IHostingEngine _hostingEngine;
private IDisposable _shutdownServerDisposable;
public Program(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void Main(string[] args)
{
try
{
if (args.Contains("--windows-service"))
{
Run(this);
return;
}
OnStart(null);
Console.ReadLine();
OnStop();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw;
}
}
protected override void OnStart(string[] args)
{
var config = new ConfigurationBuilder(new MemoryConfigurationSource()).Build();
config.Set("server.urls", "http://localhost:5000");
var builder = new WebHostBuilder(_serviceProvider, config);
builder.UseServer("Microsoft.AspNet.Server.WebListener");
builder.UseServices(services => services.AddMvc());
builder.UseStartup(appBuilder =>
{
appBuilder.UseDefaultFiles();
appBuilder.UseStaticFiles();
appBuilder.UseMvc();
});
_hostingEngine = builder.Build();
_shutdownServerDisposable = _hostingEngine.Start();
}
protected override void OnStop()
{
if (_shutdownServerDisposable != null)
_shutdownServerDisposable.Dispose();
}
}
}
| using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Hosting.Internal;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
namespace MyDnxService
{
public class Program : ServiceBase
{
private readonly IServiceProvider _serviceProvider;
private IHostingEngine _hostingEngine;
private IDisposable _shutdownServerDisposable;
public Program(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void Main(string[] args)
{
try
{
if (args.Contains("--windows-service"))
{
Run(this);
return;
}
OnStart(null);
Console.ReadLine();
OnStop();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw;
}
}
protected override void OnStart(string[] args)
{
var config = new ConfigurationBuilder(new MemoryConfigurationSource()).Build();
config.Set("server.urls", "http://localhost:5000");
var builder = new WebHostBuilder(_serviceProvider, config);
builder.UseServer("Microsoft.AspNet.Server.WebListener");
builder.UseServices(services => services.AddMvc());
builder.UseStartup(appBuilder =>
{
appBuilder.UseDefaultFiles();
appBuilder.UseStaticFiles();
appBuilder.UseMvc();
});
_hostingEngine = builder.Build();
_shutdownServerDisposable = _hostingEngine.Start();
}
protected override void OnStop()
{
if (_shutdownServerDisposable != null)
_shutdownServerDisposable.Dispose();
}
}
}
| mit | C# |
3ddca30acd44c62fba4325c3d90910a470c39af9 | Add comments and debugger display | TattsGroup/octokit.net,brramos/octokit.net,SLdragon1989/octokit.net,fffej/octokit.net,SamTheDev/octokit.net,Sarmad93/octokit.net,khellang/octokit.net,mminns/octokit.net,shiftkey/octokit.net,ivandrofly/octokit.net,SmithAndr/octokit.net,TattsGroup/octokit.net,adamralph/octokit.net,forki/octokit.net,Sarmad93/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,devkhan/octokit.net,rlugojr/octokit.net,khellang/octokit.net,kolbasov/octokit.net,gabrielweyer/octokit.net,chunkychode/octokit.net,chunkychode/octokit.net,eriawan/octokit.net,octokit-net-test-org/octokit.net,magoswiat/octokit.net,octokit/octokit.net,daukantas/octokit.net,shiftkey/octokit.net,thedillonb/octokit.net,darrelmiller/octokit.net,thedillonb/octokit.net,devkhan/octokit.net,shana/octokit.net,bslliw/octokit.net,shiftkey-tester/octokit.net,takumikub/octokit.net,naveensrinivasan/octokit.net,hahmed/octokit.net,SmithAndr/octokit.net,gdziadkiewicz/octokit.net,shiftkey-tester/octokit.net,octokit/octokit.net,octokit-net-test/octokit.net,ChrisMissal/octokit.net,dampir/octokit.net,geek0r/octokit.net,M-Zuber/octokit.net,hitesh97/octokit.net,alfhenrik/octokit.net,dampir/octokit.net,cH40z-Lord/octokit.net,gdziadkiewicz/octokit.net,editor-tools/octokit.net,michaKFromParis/octokit.net,mminns/octokit.net,Red-Folder/octokit.net,ivandrofly/octokit.net,SamTheDev/octokit.net,fake-organization/octokit.net,gabrielweyer/octokit.net,dlsteuer/octokit.net,alfhenrik/octokit.net,kdolan/octokit.net,hahmed/octokit.net,editor-tools/octokit.net,nsnnnnrn/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,M-Zuber/octokit.net,nsrnnnnn/octokit.net,octokit-net-test-org/octokit.net,rlugojr/octokit.net,shana/octokit.net,eriawan/octokit.net | Octokit/Models/Response/OauthToken.cs | Octokit/Models/Response/OauthToken.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class OauthToken
{
/// <summary>
/// The type of OAuth token
/// </summary>
public string TokenType { get; set; }
/// <summary>
/// The secret OAuth access token. Use this to authenticate Octokit.net's client.
/// </summary>
public string AccessToken { get; set; }
/// <summary>
/// The list of scopes the token includes.
/// </summary>
public IReadOnlyCollection<string> Scope { get; set; }
internal string DebuggerDisplay
{
get
{
return String.Format(CultureInfo.InvariantCulture, "TokenType: {0}, AccessToken: {1}, Scopes: {2}",
TokenType,
AccessToken,
Scope);
}
}
}
}
| using System.Collections.Generic;
namespace Octokit
{
public class OauthToken
{
public string TokenType { get; set; }
public string AccessToken { get; set; }
public IReadOnlyCollection<string> Scope { get; set; }
}
}
| mit | C# |
564dea58b893507d222eb2815883b9f01615b180 | Add missing words | alfhenrik/octokit.net,dampir/octokit.net,octokit-net-test-org/octokit.net,gdziadkiewicz/octokit.net,devkhan/octokit.net,shiftkey-tester/octokit.net,thedillonb/octokit.net,Sarmad93/octokit.net,SmithAndr/octokit.net,SamTheDev/octokit.net,chunkychode/octokit.net,khellang/octokit.net,editor-tools/octokit.net,M-Zuber/octokit.net,devkhan/octokit.net,octokit/octokit.net,TattsGroup/octokit.net,SamTheDev/octokit.net,shiftkey/octokit.net,alfhenrik/octokit.net,shiftkey/octokit.net,M-Zuber/octokit.net,shiftkey-tester/octokit.net,gdziadkiewicz/octokit.net,adamralph/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,octokit-net-test-org/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,shana/octokit.net,eriawan/octokit.net,octokit/octokit.net,rlugojr/octokit.net,TattsGroup/octokit.net,shana/octokit.net,SmithAndr/octokit.net,khellang/octokit.net,editor-tools/octokit.net,eriawan/octokit.net,ivandrofly/octokit.net,rlugojr/octokit.net,chunkychode/octokit.net,thedillonb/octokit.net,Sarmad93/octokit.net,hahmed/octokit.net,hahmed/octokit.net,ivandrofly/octokit.net,dampir/octokit.net | Octokit/Models/Response/PagesBuild.cs | Octokit/Models/Response/PagesBuild.cs | using System;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
/// <summary>
/// Metadata of a Github Pages build.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class PagesBuild
{
public PagesBuild() { }
public PagesBuild(string url, PagesBuildStatus status, ApiError error, User pusher, Commit commit, TimeSpan duration, DateTime createdAt, DateTime updatedAt)
{
Url = url;
Status = status;
Error = error;
Pusher = pusher;
Commit = commit;
Duration = duration;
CreatedAt = createdAt;
UpdatedAt = updatedAt;
}
/// <summary>
/// The pages's API URL.
/// </summary>
public string Url { get; protected set; }
/// <summary>
/// The status of the build.
/// </summary>
public PagesBuildStatus Status { get; protected set; }
/// <summary>
/// Error details - if there was one.
/// </summary>
public ApiError Error { get; protected set; }
/// <summary>
/// The user whose commit intiated the build.
/// </summary>
public User Pusher { get; protected set; }
/// <summary>
/// Commit SHA.
/// </summary>
public Commit Commit { get; protected set; }
/// <summary>
/// Duration of the build
/// </summary>
public TimeSpan Duration { get; protected set; }
public DateTime CreatedAt { get; protected set; }
public DateTime UpdatedAt { get; protected set; }
internal string DebuggerDisplay
{
get
{
return string.Format(CultureInfo.InvariantCulture, "Pusher: {0}, Status: {1}, Duration: {2}", Pusher.Name, Status.ToString(), Duration.TotalMilliseconds);
}
}
}
}
| using System;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
/// <summary>
/// Metadata of a Github Pages build.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class PagesBuild
{
public PagesBuild() { }
public PagesBuild(string url, PagesBuildStatus status, ApiError error, User pusher, Commit commit, TimeSpan duration, DateTime createdAt, DateTime updatedAt)
{
Url = url;
Status = status;
Error = error;
Pusher = pusher;
Commit = commit;
Duration = duration;
CreatedAt = createdAt;
UpdatedAt = updatedAt;
}
/// <summary>
/// The pages's API URL.
/// </summary>
public string Url { get; protected set; }
/// <summary>
/// The status of the build.
/// </summary>
public PagesBuildStatus Status { get; protected set; }
/// <summary>
///
/// </summary>
public ApiError Error { get; protected set; }
/// <summary>
/// The user whose commit intiated the build.
/// </summary>
public User Pusher { get; protected set; }
/// <summary>
/// Commit SHA.
/// </summary>
public Commit Commit { get; protected set; }
/// <summary>
/// Duration of the build
/// </summary>
public TimeSpan Duration { get; protected set; }
public DateTime CreatedAt { get; protected set; }
public DateTime UpdatedAt { get; protected set; }
internal string DebuggerDisplay
{
get
{
return string.Format(CultureInfo.InvariantCulture, "Pusher: {0}, Status: {1}, Duration: {2}", Pusher.Name, Status.ToString(), Duration.TotalMilliseconds);
}
}
}
}
| mit | C# |
1cd661f07121ed358fda429e11b9593aff01a610 | Make comparison case insensitive | episerver/AlloyDemoKit,episerver/AlloyDemoKit,episerver/AlloyDemoKit | src/AlloyDemoKit/Business/VisitorGroupUIStyling/OverrideVisitorGroupCss.cs | src/AlloyDemoKit/Business/VisitorGroupUIStyling/OverrideVisitorGroupCss.cs | using System;
using System.Web.Mvc;
namespace AlloyDemoKit.Business.VisitorGroupUIStyling
{
public class OverrideVisitorGroupCssAttribute : OutputProcessorActionFilterAttribute
{
protected override string Process(string data)
{
return data
.Replace("</head", "<link href=\"/Static/css/VisitorGroupUIOverrides.css\" rel=\"stylesheet\"></link></head");
}
protected override bool ShouldProcess(ResultExecutedContext filterContext)
{
var result = filterContext.Result as ViewResultBase;
var view = result?.View as WebFormView;
return view != null
&& (view.ViewPath.Equals("/EPiServer/CMS/Views/VisitorGroups/Index.aspx", StringComparison.InvariantCultureIgnoreCase) || view.ViewPath.Equals("/EPiServer/CMS/Views/VisitorGroups/Edit.aspx", StringComparison.InvariantCultureIgnoreCase));
}
}
} | using System.Web.Mvc;
namespace AlloyDemoKit.Business.VisitorGroupUIStyling
{
public class OverrideVisitorGroupCssAttribute : OutputProcessorActionFilterAttribute
{
protected override string Process(string data)
{
return data
.Replace("</head", "<link href=\"/Static/css/VisitorGroupUIOverrides.css\" rel=\"stylesheet\"></link></head");
}
protected override bool ShouldProcess(ResultExecutedContext filterContext)
{
var result = filterContext.Result as ViewResultBase;
var view = result?.View as WebFormView;
return view != null
&& (view.ViewPath.Equals("/EPiServer/CMS/Views/VisitorGroups/Index.aspx") || view.ViewPath.Equals("/EPiServer/CMS/Views/VisitorGroups/Edit.aspx"));
}
}
} | apache-2.0 | C# |
b2c2810509cb43591af0803d7f7a8c15c374c027 | Fix tests | mavasani/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,diryboy/roslyn,mavasani/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,dotnet/roslyn,dotnet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,bartdesmet/roslyn,mavasani/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn | src/EditorFeatures/CSharpTest/EmbeddedLanguages/JsonStringDetectorTests.cs | src/EditorFeatures/CSharpTest/EmbeddedLanguages/JsonStringDetectorTests.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.Tasks;
using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EmbeddedLanguages
{
using VerifyCS = CSharpCodeFixVerifier<
CSharpJsonDetectionAnalyzer,
CSharpJsonDetectionCodeFixProvider>;
public class JsonStringDetectorTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsDetectJsonString)]
public async Task TestStrict()
{
await new VerifyCS.Test
{
TestCode =
@"
class C
{
void Goo()
{
var j = [|""{ \""a\"": 0 }""|];
}
}",
FixedCode =
@"
class C
{
void Goo()
{
var j = /*lang=json,strict*/ ""{ \""a\"": 0 }"";
}
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsDetectJsonString)]
public async Task TestNonStrict()
{
await new VerifyCS.Test
{
TestCode =
@"
class C
{
void Goo()
{
var j = [|""{ 'a': 00 }""|];
}
}",
FixedCode =
@"
class C
{
void Goo()
{
var j = /*lang=json*/ ""{ 'a': 00 }"";
}
}",
}.RunAsync();
}
}
}
| // 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.Tasks;
using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EmbeddedLanguages
{
using VerifyCS = CSharpCodeFixVerifier<
CSharpJsonDetectionAnalyzer,
CSharpJsonDetectionCodeFixProvider>;
public class JsonStringDetectorTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsDetectJsonString)]
public async Task TestStrict()
{
await new VerifyCS.Test
{
TestCode =
@"
class C
{
void Goo()
{
var j = [||]""{ \""a\"": 0 }"";
}
}",
FixedCode =
@"
class C
{
void Goo()
{
var j = /*lang=json,strict*/ ""{ \""a\"": 0 }"";
}
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsDetectJsonString)]
public async Task TestNonStrict()
{
await new VerifyCS.Test
{
TestCode =
@"
class C
{
void Goo()
{
var j = [||]""{ 'a': 00 }"";
}
}",
FixedCode =
@"
class C
{
void Goo()
{
var j = /*lang=json*/ ""{ 'a': 00 }"";
}
}",
}.RunAsync();
}
}
}
| mit | C# |
01e72aaed4df32986262da65dd7c2d7194ca6831 | Fix data bar for min/max | igitur/ClosedXML,ClosedXML/ClosedXML,jongleur1983/ClosedXML,JavierJJJ/ClosedXML,b0bi79/ClosedXML | ClosedXML/Excel/ConditionalFormats/Save/XLCFDataBarConverter.cs | ClosedXML/Excel/ConditionalFormats/Save/XLCFDataBarConverter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
namespace ClosedXML.Excel
{
internal class XLCFDataBarConverter : IXLCFConverter
{
public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context)
{
var conditionalFormattingRule = new ConditionalFormattingRule { Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority };
var dataBar = new DataBar { ShowValue = !cf.ShowBarOnly };
var conditionalFormatValueObject1 = new ConditionalFormatValueObject { Type = cf.ContentTypes[1].ToOpenXml() };
if (cf.Values.Any() && cf.Values[1]?.Value != null) conditionalFormatValueObject1.Val = cf.Values[1].Value;
var conditionalFormatValueObject2 = new ConditionalFormatValueObject { Type = cf.ContentTypes[2].ToOpenXml() };
if (cf.Values.Count >= 2 && cf.Values[2]?.Value != null) conditionalFormatValueObject2.Val = cf.Values[2].Value;
var color = new Color();
switch (cf.Colors[1].ColorType)
{
case XLColorType.Color:
color.Rgb = cf.Colors[1].Color.ToHex();
break;
case XLColorType.Theme:
color.Theme = System.Convert.ToUInt32(cf.Colors[1].ThemeColor);
break;
case XLColorType.Indexed:
color.Indexed = System.Convert.ToUInt32(cf.Colors[1].Indexed);
break;
}
dataBar.Append(conditionalFormatValueObject1);
dataBar.Append(conditionalFormatValueObject2);
dataBar.Append(color);
conditionalFormattingRule.Append(dataBar);
return conditionalFormattingRule;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
namespace ClosedXML.Excel
{
internal class XLCFDataBarConverter:IXLCFConverter
{
public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context)
{
var conditionalFormattingRule = new ConditionalFormattingRule { Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority };
var dataBar = new DataBar {ShowValue = !cf.ShowBarOnly};
var conditionalFormatValueObject1 = new ConditionalFormatValueObject { Type = cf.ContentTypes[1].ToOpenXml()};
if (cf.Values.Count >= 1) conditionalFormatValueObject1.Val = cf.Values[1].Value;
var conditionalFormatValueObject2 = new ConditionalFormatValueObject { Type = cf.ContentTypes[2].ToOpenXml()};
if (cf.Values.Count >= 2) conditionalFormatValueObject2.Val = cf.Values[2].Value;
var color = new Color { Rgb = cf.Colors[1].Color.ToHex() };
dataBar.Append(conditionalFormatValueObject1);
dataBar.Append(conditionalFormatValueObject2);
dataBar.Append(color);
conditionalFormattingRule.Append(dataBar);
return conditionalFormattingRule;
}
}
}
| mit | C# |
789eeeaeaa97949f40d90bb68f012c518b9d5933 | Update BindableBase | Kingloo/Rdr | RdrLib/Model/BindableBase.cs | RdrLib/Model/BindableBase.cs | using System;
using System.ComponentModel;
namespace RdrLib.Model
{
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, string propertyName)
{
if (String.IsNullOrWhiteSpace(propertyName))
{
throw new ArgumentNullException(nameof(propertyName));
}
if (Equals(storage, value))
{
return false;
}
storage = value;
RaisePropertyChanged(propertyName);
return true;
}
#pragma warning disable CA1030
protected virtual void RaisePropertyChanged(string propertyName)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
#pragma warning restore CA1030
}
}
| using System.ComponentModel;
namespace RdrLib.Model
{
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, string propertyName)
{
if (Equals(storage, value))
{
return false;
}
storage = value;
RaisePropertyChanged(propertyName);
return true;
}
protected virtual void RaisePropertyChanged(string propertyName)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
| unlicense | C# |
6116ef35b1fd54b9a21643128f8bb8ba07f38760 | Remove redundant code. bugid: 912 | JasonBock/csla,JasonBock/csla,ronnymgm/csla-light,jonnybee/csla,rockfordlhotka/csla,BrettJaner/csla,BrettJaner/csla,JasonBock/csla,MarimerLLC/csla,MarimerLLC/csla,jonnybee/csla,rockfordlhotka/csla,ronnymgm/csla-light,ronnymgm/csla-light,BrettJaner/csla,jonnybee/csla,MarimerLLC/csla,rockfordlhotka/csla | Samples/NET/cs/ProjectTracker/Mvc3UI/Views/Project/Index.cshtml | Samples/NET/cs/ProjectTracker/Mvc3UI/Views/Project/Index.cshtml | @using Csla.Web.Mvc
@using ProjectTracker.Library
@model IEnumerable<ProjectTracker.Library.ProjectInfo>
@{
ViewBag.Title = "Project list";
}
<h2>@ViewBag.Message</h2>
<p>
@Html.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit), Html.ActionLink("Create New", "Create"), string.Empty)
</p>
<table>
<tr>
<th></th>
<th>
Name
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectEdit), Html.ActionLink("Edit", "Edit", new { id = item.Id }), "Edit") |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectEdit), Html.ActionLink("Delete", "Delete", new { id = item.Id }), "Delete")
</td>
<td>
@item.Name
</td>
</tr>
}
</table>
| @using Csla.Web.Mvc
@using ProjectTracker.Library
@model IEnumerable<ProjectTracker.Library.ProjectInfo>
@{
ViewBag.Title = "Project list";
}
<h2>@ViewBag.Message</h2>
<p>
@Html.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit), Html.ActionLink("Create New", "Create"), string.Empty)
@if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit)))
{
@Html.ActionLink("Create New", "Create")
}
</p>
<table>
<tr>
<th></th>
<th>
Name
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectEdit), Html.ActionLink("Edit", "Edit", new { id = item.Id }), "Edit") |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectEdit), Html.ActionLink("Delete", "Delete", new { id = item.Id }), "Delete")
</td>
<td>
@item.Name
</td>
</tr>
}
</table>
| mit | C# |
593327a74eb1fdf6d77f2edbecbfc6d38e85ab29 | Add [Serializable] attribute | dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute | Source/NSubstitute/Exceptions/CannotCreateEventArgsException.cs | Source/NSubstitute/Exceptions/CannotCreateEventArgsException.cs | using System;
using System.Runtime.Serialization;
namespace NSubstitute.Exceptions
{
[Serializable]
public class CannotCreateEventArgsException : SubstituteException
{
public CannotCreateEventArgsException() { }
public CannotCreateEventArgsException(string message) : base(message) { }
public CannotCreateEventArgsException(string message, Exception innerException) : base(message, innerException) { }
protected CannotCreateEventArgsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
| using System;
using System.Runtime.Serialization;
namespace NSubstitute.Exceptions
{
public class CannotCreateEventArgsException : SubstituteException
{
public CannotCreateEventArgsException() { }
public CannotCreateEventArgsException(string message) : base(message) { }
public CannotCreateEventArgsException(string message, Exception innerException) : base(message, innerException) { }
protected CannotCreateEventArgsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
} | bsd-3-clause | C# |
e0b6fa516acb6ae1327826d3cf731667a58d7b70 | Remove unused imports. | Nezaboodka/Nevod.TextParsing,Nezaboodka/Nevod.TextParsing | WordExtraction/Demo.cs | WordExtraction/Demo.cs | using System;
namespace WordExtraction
{
class Demo
{
private const string UNICODE_DEMO = "The quick(\"brown\") fox can't jump 32.3 feet, right?";
static void Main(string[] args)
{
foreach (var word in WordExtractor.GetWords(UNICODE_DEMO))
{
Console.WriteLine(word);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WordExtraction
{
class Demo
{
private const string UNICODE_DEMO = "The quick(\"brown\") fox can't jump 32.3 feet, right?";
static void Main(string[] args)
{
foreach (var word in WordExtractor.GetWords(UNICODE_DEMO))
{
Console.WriteLine(word);
}
}
}
}
| mit | C# |
f80076e20702d4b3afbb223522b89dfef123808a | Fix for github issue #237 UWP, Desktop Back button not showing https://github.com/xamarin/Xamarin.Auth/issues/237 | xamarin/Xamarin.Auth,xamarin/Xamarin.Auth,xamarin/Xamarin.Auth | source/Xamarin.Auth.UniversalWindowsPlatform/Presenters/OAuthPlatformPresenter.UniversalWindowsPlatform.cs | source/Xamarin.Auth.UniversalWindowsPlatform/Presenters/OAuthPlatformPresenter.UniversalWindowsPlatform.cs | namespace Xamarin.Auth.Presenters.UWP
{
public class PlatformOAuthLoginPresenter
{
private readonly bool _hasHardwareButton;
private Frame _rootFrame;
private Authenticator _authenticator;
public PlatformOAuthLoginPresenter()
{
_hasHardwareButton = ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons");
}
public void Login(Authenticator authenticator)
{
_authenticator = authenticator;
authenticator.Completed += AuthenticatorCompleted;
System.Type pageType = authenticator.GetUI();
_rootFrame = Window.Current.Content as Frame;
_rootFrame.Navigate(pageType, authenticator);
if (!_hasHardwareButton && _authenticator.AllowCancel)
{
var navManager = SystemNavigationManager.GetForCurrentView();
navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
navManager.BackRequested += CustomPlatformOAuthLoginPresenter_BackRequested;
}
return;
authenticator.Completed += AuthenticatorCompleted;
System.Type page_type = authenticator.GetUI();
Windows.UI.Xaml.Controls.Frame root_frame = null;
root_frame = Windows.UI.Xaml.Window.Current.Content as Windows.UI.Xaml.Controls.Frame;
root_frame.Navigate(page_type, authenticator);
return;
}
private void CustomPlatformOAuthLoginPresenter_BackRequested(object sender, BackRequestedEventArgs e)
{
if (_rootFrame.CanGoBack)
{
_rootFrame.GoBack();
_authenticator.OnCancelled();
}
return;
}
protected void AuthenticatorCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
if (!_hasHardwareButton && _authenticator.AllowCancel)
{
SystemNavigationManager.GetForCurrentView().BackRequested -= CustomPlatformOAuthLoginPresenter_BackRequested;
}
((Authenticator)sender).Completed -= AuthenticatorCompleted;
return;
}
}
} | namespace Xamarin.Auth.Presenters.UWP
{
public class PlatformOAuthLoginPresenter
{
public void Login(Authenticator authenticator)
{
authenticator.Completed += AuthenticatorCompleted;
System.Type page_type = authenticator.GetUI();
Windows.UI.Xaml.Controls.Frame root_frame = null;
root_frame = Windows.UI.Xaml.Window.Current.Content as Windows.UI.Xaml.Controls.Frame;
root_frame.Navigate(page_type, authenticator);
return;
}
void AuthenticatorCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
//rootViewController.DismissViewController(true, null);
((Authenticator)sender).Completed -= AuthenticatorCompleted;
}
}
} | apache-2.0 | C# |
a3195d2b726ef72da2fb52f96d7ba6ae422c428b | Remove obsolete internals visible to | mrward/monodevelop-nuget-extensions,mrward/monodevelop-nuget-extensions | src/MonoDevelop.PackageManagement.Extensions/Properties/AssemblyInfo.cs | src/MonoDevelop.PackageManagement.Extensions/Properties/AssemblyInfo.cs | //
// AssemblyInfo.cs
//
// Author:
// Matt Ward <matt.ward@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("MonoDevelop.PackageManagement.Extensions")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Xamarin Inc. (http://xamarin.com)")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("0.17")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| //
// AssemblyInfo.cs
//
// Author:
// Matt Ward <matt.ward@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("MonoDevelop.PackageManagement.Extensions")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Xamarin Inc. (http://xamarin.com)")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("0.17")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
[assembly: InternalsVisibleTo ("MonoDevelop.PackageManagement.Cmdlets, PublicKey=002400000c800000940000000602000000240000525341310004000001000100e1290d741888d13312c0cd1f72bb843236573c80158a286f11bb98de5ee8acc3142c9c97b472684e521ae45125d7414558f2e70ac56504f3e8fe80830da2cdb1cda8504e8d196150d05a214609234694ec0ebf4b37fc7537e09d877c3e65000f7467fa3adb6e62c82b10ada1af4a83651556c7d949959817fed97480839dd39b")]
| mit | C# |
9184ee20bd6d7a5ee5694b8a6029ad301debc80f | Remove unused code | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts.Web/Controllers/CookieConsentController.cs | src/SFA.DAS.EmployerAccounts.Web/Controllers/CookieConsentController.cs | using System.Web.Mvc;
using SFA.DAS.Authentication;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.EmployerAccounts.Web.ViewModels;
namespace SFA.DAS.EmployerAccounts.Web.Controllers
{
public class CookieConsentController : BaseController
{
public CookieConsentController(
IAuthenticationService owinWrapper,
IMultiVariantTestingService multiVariantTestingService,
ICookieStorageService<FlashMessageViewModel> flashMessage
) : base(owinWrapper, multiVariantTestingService, flashMessage)
{
}
[HttpGet]
[Route("accounts/{HashedAccountId}/cookieConsent", Order = 0)]
[Route("cookieConsent", Order = 1)]
public ActionResult Settings()
{
return View();
}
[HttpGet]
[Route("accounts/{HashedAccountId}/cookieConsent/details", Order = 0)]
[Route("cookieConsent/details", Order = 1)]
public ActionResult Details()
{
return View();
}
}
} | using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using SFA.DAS.Authentication;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.EmployerAccounts.Web.ViewModels;
namespace SFA.DAS.EmployerAccounts.Web.Controllers
{
public class CookieConsentController : BaseController
{
public CookieConsentController(
IAuthenticationService owinWrapper,
IMultiVariantTestingService multiVariantTestingService,
ICookieStorageService<FlashMessageViewModel> flashMessage
) : base(owinWrapper, multiVariantTestingService, flashMessage)
{
}
[HttpGet]
[Route("accounts/{HashedAccountId}/cookieConsent", Order = 0)]
[Route("cookieConsent", Order = 1)]
public ActionResult Settings(bool saved = false)
{
return View(new { Saved = saved });
}
[HttpGet]
[Route("accounts/{HashedAccountId}/cookieConsent/details", Order = 0)]
[Route("cookieConsent/details", Order = 1)]
public ActionResult Details()
{
return View();
}
}
} | mit | C# |
08705a7250605a79fbc9a6fd1aa35df7144e2a13 | Format SerializableDictionary according to our coding style | github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs | src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs | using System;
using System.Collections.Generic;
using UnityEngine;
namespace GitHub.Unity
{
//http://answers.unity3d.com/answers/809221/view.html
[Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
[SerializeField] private List<TKey> keys = new List<TKey>();
[SerializeField] private List<TValue> values = new List<TValue>();
// save the dictionary to lists
public void OnBeforeSerialize()
{
keys.Clear();
values.Clear();
foreach (var pair in this)
{
keys.Add(pair.Key);
values.Add(pair.Value);
}
}
// load dictionary from lists
public void OnAfterDeserialize()
{
Clear();
if (keys.Count != values.Count)
{
throw new Exception(
string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable.",
keys.Count, values.Count));
}
for (var i = 0; i < keys.Count; i++)
{
Add(keys[i], values[i]);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace GitHub.Unity
{
//http://answers.unity3d.com/answers/809221/view.html
[Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
[SerializeField]
private List<TKey> keys = new List<TKey>();
[SerializeField]
private List<TValue> values = new List<TValue>();
// save the dictionary to lists
public void OnBeforeSerialize()
{
keys.Clear();
values.Clear();
foreach (KeyValuePair<TKey, TValue> pair in this)
{
keys.Add(pair.Key);
values.Add(pair.Value);
}
}
// load dictionary from lists
public void OnAfterDeserialize()
{
this.Clear();
if (keys.Count != values.Count)
throw new Exception(string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable.", keys.Count, values.Count));
for (int i = 0; i < keys.Count; i++)
this.Add(keys[i], values[i]);
}
}
} | mit | C# |
572d250eb15d4e6ff47b8fb50a4495fddbcc3dea | add missing serializable attrib to test exception | ajayanandgit/common-logging,net-commons/common-logging,Moily/common-logging,meixger/common-logging,net-commons/common-logging,xlgwr/common-logging,tablesmit/common-logging | test/Common.Logging.Tests/Logging/LoggingExceptionWithIndexerBugTest.cs | test/Common.Logging.Tests/Logging/LoggingExceptionWithIndexerBugTest.cs | #region License
/*
* Copyright © 2002-2007 the original author or authors.
*
* 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.Reflection;
using System.Runtime.Serialization;
using NUnit.Framework;
namespace Common.Logging
{
/// <summary>
/// Exception with indexer property should be logged without <see cref="TargetParameterCountException"/> error
/// </summary>
/// <author>artem1</author>
/// <version>$Id:$</version>
public class LoggingExceptionWithIndexerBugTest
{
/// <summary>
/// This bug was found by me in Npgsql driver for PostgreSQL (NpgsqlException)
/// </summary>
[Test]
public void ErrorNotThrownWhenLoggedExceptionHasIndexerProperty()
{
ILog log = LogManager.GetCurrentClassLogger();
ExceptionWithIndexerException exception = new ExceptionWithIndexerException();
Assert.That(() => log.Error("error catched", exception), Throws.Nothing);
}
[Serializable]
public class ExceptionWithIndexerException : Exception
{
public ExceptionWithIndexerException()
{
}
public ExceptionWithIndexerException(string message) : base(message)
{
}
public ExceptionWithIndexerException(string message, Exception innerException) : base(message, innerException)
{
}
protected ExceptionWithIndexerException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public string this[string key]
{
get { return null; }
}
}
}
} | #region License
/*
* Copyright © 2002-2007 the original author or authors.
*
* 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.Reflection;
using System.Runtime.Serialization;
using NUnit.Framework;
namespace Common.Logging
{
/// <summary>
/// Exception with indexer property should be logged without <see cref="TargetParameterCountException"/> error
/// </summary>
/// <author>artem1</author>
/// <version>$Id:$</version>
public class LoggingExceptionWithIndexerBugTest
{
/// <summary>
/// This bug was found by me in Npgsql driver for PostgreSQL (NpgsqlException)
/// </summary>
[Test]
public void ErrorNotThrownWhenLoggedExceptionHasIndexerProperty()
{
ILog log = LogManager.GetCurrentClassLogger();
ExceptionWithIndexerException exception = new ExceptionWithIndexerException();
Assert.That(() => log.Error("error catched", exception), Throws.Nothing);
}
public class ExceptionWithIndexerException : Exception
{
public ExceptionWithIndexerException()
{
}
public ExceptionWithIndexerException(string message) : base(message)
{
}
public ExceptionWithIndexerException(string message, Exception innerException) : base(message, innerException)
{
}
protected ExceptionWithIndexerException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public string this[string key]
{
get { return null; }
}
}
}
} | apache-2.0 | C# |
af0fc4853034b3d6fcdd9d02b99bff68f2f7f00e | update SP | TonyNug/CGPSI,TonyNug/CGPSI,TonyNug/CGPSI | CGPSI/CGPSI.AbsenceManagement/CGPSI.AbsenceManagement/Controllers/AbsenceManagement/AbsenceDataController.cs | CGPSI/CGPSI.AbsenceManagement/CGPSI.AbsenceManagement/Controllers/AbsenceManagement/AbsenceDataController.cs | using CGPSI.AbsenceManagement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CGPSI.AbsenceManagement.Controllers.AbsenceManagement
{
public class AbsenceDataController : Controller
{
// GET: AbsenceData
public ActionResult Index()
{
return View();
}
public ActionResult Get()//(DateTime start,DateTime end)//(string take, string page, string skip, string pageSize, List<GridSort> sort, GridFilter filter)
{
//string filters = KendoHelper.GenerateFilters(take, page, skip, pageSize, sort, filter);
var result=new CGPSI_AbsenceDBEntities().SP_GetDataAbsenceOfCurrentMonth().ToList();
var data = new
{
Result = result
.Select(a => new
{
StartTime = a.StartTime.Value.ToString(@"hh\:mm\:ss"),
EndTime = a.EndTime.Value.ToString(@"hh\:mm\:ss"),
FirstName = a.FirstName,
Department = a.Department,
NIK = a.NIK,
Dates = a.Dates,
TimeIN = (a.TimeIN != null ? a.TimeIN.Value.ToString(@"hh\:mm\:ss") : ""),
TimeOUT = (a.TimeOUT != null ? a.TimeOUT.Value.ToString(@"hh\:mm\:ss") : ""),
actualDayname = a.DayName,
ShiftName = a.ShiftName,
AbsenceStatus = a.AbsenceStatus
}),
//CResult = new CGPSI_AbsenceDBEntities().ViewAbsenceSummaries.Count()
};
return Json(data);
//return Json(null);
}
}
} | using CGPSI.AbsenceManagement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CGPSI.AbsenceManagement.Controllers.AbsenceManagement
{
public class AbsenceDataController : Controller
{
// GET: AbsenceData
public ActionResult Index()
{
return View();
}
public ActionResult Get()//(DateTime start,DateTime end)//(string take, string page, string skip, string pageSize, List<GridSort> sort, GridFilter filter)
{
//string filters = KendoHelper.GenerateFilters(take, page, skip, pageSize, sort, filter);
var result=new CGPSI_AbsenceDBEntities().SP_GetDataAbsenceByDate().ToList();
var data = new
{
Result = result
.Select(a => new
{
StartTime = a.StartTime.Value.ToString(@"hh\:mm\:ss"),
EndTime = a.EndTime.Value.ToString(@"hh\:mm\:ss"),
FirstName = a.FirstName,
Department = a.Department,
NIK = a.NIK,
Dates = a.Dates,
TimeIN = (a.TimeIN != null ? a.TimeIN.Value.ToString(@"hh\:mm\:ss") : ""),
TimeOUT = (a.TimeOUT != null ? a.TimeOUT.Value.ToString(@"hh\:mm\:ss") : ""),
actualDayname = a.DayName,
ShiftName = a.ShiftName,
AbsenceStatus = a.AbsenceStatus
}),
//CResult = new CGPSI_AbsenceDBEntities().ViewAbsenceSummaries.Count()
};
return Json(data);
//return Json(null);
}
}
} | mit | C# |
1f11609e9fd14194b3a24be0245dceac3284b6da | Edit comments | andypaul/monotouch-samples,a9upam/monotouch-samples,nervevau2/monotouch-samples,nelzomal/monotouch-samples,robinlaide/monotouch-samples,albertoms/monotouch-samples,nervevau2/monotouch-samples,sakthivelnagarajan/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,W3SS/monotouch-samples,hongnguyenpro/monotouch-samples,nelzomal/monotouch-samples,andypaul/monotouch-samples,haithemaraissia/monotouch-samples,haithemaraissia/monotouch-samples,haithemaraissia/monotouch-samples,markradacz/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,W3SS/monotouch-samples,kingyond/monotouch-samples,a9upam/monotouch-samples,markradacz/monotouch-samples,YOTOV-LIMITED/monotouch-samples,iFreedive/monotouch-samples,hongnguyenpro/monotouch-samples,sakthivelnagarajan/monotouch-samples,nelzomal/monotouch-samples,albertoms/monotouch-samples,davidrynn/monotouch-samples,peteryule/monotouch-samples,hongnguyenpro/monotouch-samples,labdogg1003/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples,xamarin/monotouch-samples,davidrynn/monotouch-samples,kingyond/monotouch-samples,iFreedive/monotouch-samples,davidrynn/monotouch-samples,xamarin/monotouch-samples,albertoms/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,a9upam/monotouch-samples,nervevau2/monotouch-samples,andypaul/monotouch-samples,kingyond/monotouch-samples,sakthivelnagarajan/monotouch-samples,a9upam/monotouch-samples,sakthivelnagarajan/monotouch-samples,haithemaraissia/monotouch-samples,xamarin/monotouch-samples,peteryule/monotouch-samples,andypaul/monotouch-samples,robinlaide/monotouch-samples,YOTOV-LIMITED/monotouch-samples,markradacz/monotouch-samples,robinlaide/monotouch-samples,nelzomal/monotouch-samples,W3SS/monotouch-samples,peteryule/monotouch-samples,davidrynn/monotouch-samples,hongnguyenpro/monotouch-samples | CoreAnimation/Screens/iPad/LayerAnimation/ImplicitAnimationScreen.xib.cs | CoreAnimation/Screens/iPad/LayerAnimation/ImplicitAnimationScreen.xib.cs | using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreAnimation;
using System.Drawing;
namespace Example_CoreAnimation.Screens.iPad.LayerAnimation
{
public partial class ImplicitAnimationScreen : UIViewController, IDetailView
{
public event EventHandler ContentsButtonClicked;
protected CALayer imgLayer;
#region Constructors
// The IntPtr and initWithCoder constructors are required for controllers that need
// to be able to be created from a xib rather than from managed code
public ImplicitAnimationScreen (IntPtr handle) : base (handle)
{
Initialize ();
}
[Export ("initWithCoder:")]
public ImplicitAnimationScreen (NSCoder coder) : base (coder)
{
Initialize ();
}
public ImplicitAnimationScreen () : base ("ImplicitAnimationScreen", null)
{
Initialize ();
}
void Initialize ()
{
Console.WriteLine ("Creating Layer");
// create our layer and set it's frame
imgLayer = CreateLayerFromImage ();
imgLayer.Frame = new RectangleF (200, 70, 114, 114);
// add the layer to the layer tree so that it's visible
View.Layer.AddSublayer (imgLayer);
}
#endregion
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
btnContents.TouchUpInside += (sender, e) => {
if (ContentsButtonClicked != null)
ContentsButtonClicked (sender, e);
};
// anonymous delegate that runs when the btnAnimate button is clicked
btnAnimate.TouchUpInside += (s, e) => {
if (imgLayer.Frame.Y == 70) {
imgLayer.Frame = new RectangleF (new PointF (200, 270), imgLayer.Frame.Size);
imgLayer.Opacity = 0.2f;
} else {
imgLayer.Frame = new RectangleF (new PointF (200, 70), imgLayer.Frame.Size);
imgLayer.Opacity = 1.0f;
}
};
}
// Ways to create a CALayer
// Method 1: create a layer from an image
protected CALayer CreateLayerFromImage ()
{
var layer = new CALayer ();
layer.Contents = UIImage.FromBundle ("icon-114.png").CGImage;
return layer;
}
// Method 2: create a layer and assign a custom delegate that performs the drawing
protected CALayer CreateLayerWithDelegate ()
{
var layer = new CALayer ();
layer.Delegate = new LayerDelegate ();
return layer;
}
public class LayerDelegate : CALayerDelegate
{
public override void DrawLayer (CALayer layer, MonoTouch.CoreGraphics.CGContext context)
{
// implement your drawing
}
}
// Method 3: Create a custom CALayer and override the appropriate methods
public class MyCustomLayer : CALayer
{
public override void DrawInContext (MonoTouch.CoreGraphics.CGContext ctx)
{
base.DrawInContext (ctx);
// implement your drawing
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreAnimation;
using System.Drawing;
namespace Example_CoreAnimation.Screens.iPad.LayerAnimation
{
public partial class ImplicitAnimationScreen : UIViewController, IDetailView
{
public event EventHandler ContentsButtonClicked;
protected CALayer imgLayer;
#region Constructors
// The IntPtr and initWithCoder constructors are required for controllers that need
// to be able to be created from a xib rather than from managed code
public ImplicitAnimationScreen (IntPtr handle) : base (handle)
{
Initialize ();
}
[Export ("initWithCoder:")]
public ImplicitAnimationScreen (NSCoder coder) : base (coder)
{
Initialize ();
}
public ImplicitAnimationScreen () : base ("ImplicitAnimationScreen", null)
{
Initialize ();
}
void Initialize ()
{
Console.WriteLine ("Creating Layer");
// create our layer and set it's frame
imgLayer = CreateLayerFromImage ();
imgLayer.Frame = new RectangleF (200, 70, 114, 114);
// add the layer to the layer tree so that it's visible
View.Layer.AddSublayer (imgLayer);
}
#endregion
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
btnContents.TouchUpInside += (sender, e) => {
if (ContentsButtonClicked != null)
ContentsButtonClicked (sender, e);
};
// anonymous delegate that runs when the btnAnimate button is clicked
btnAnimate.TouchUpInside += (s, e) => {
if (imgLayer.Frame.Y == 70) {
imgLayer.Frame = new RectangleF (new PointF (200, 270), imgLayer.Frame.Size);
imgLayer.Opacity = 0.2f;
} else {
imgLayer.Frame = new RectangleF (new PointF (200, 70), imgLayer.Frame.Size);
imgLayer.Opacity = 1.0f;
}
};
}
//==== Ways to create a CALayer
//==== Method 1: create a layer from an image
protected CALayer CreateLayerFromImage ()
{
var layer = new CALayer ();
layer.Contents = UIImage.FromBundle ("icon-114.png").CGImage;
return layer;
}
//==== Method 2: create a layer and assign a custom delegate that performs the drawing
protected CALayer CreateLayerWithDelegate ()
{
var layer = new CALayer ();
layer.Delegate = new LayerDelegate ();
return layer;
}
public class LayerDelegate : CALayerDelegate
{
public override void DrawLayer (CALayer layer, MonoTouch.CoreGraphics.CGContext context)
{
// implement your drawing
}
}
//===== Method 3: Create a custom CALayer and override the appropriate methods
public class MyCustomLayer : CALayer
{
public override void DrawInContext (MonoTouch.CoreGraphics.CGContext ctx)
{
base.DrawInContext (ctx);
// implement your drawing
}
}
}
}
| mit | C# |
1719602113a06202f8978dd7baf757d8f9604c1b | make test runtime independant | gluck/cecil,jbevain/cecil,xen2/cecil,fnajera-rac-de/cecil,mono/cecil,furesoft/cecil,joj/cecil,sailro/cecil,ttRevan/cecil,kzu/cecil,SiliconStudio/Mono.Cecil,cgourlay/cecil,saynomoo/cecil | rocks/Test/Mono.Cecil.Tests/SecurityDeclarationRocksTests.cs | rocks/Test/Mono.Cecil.Tests/SecurityDeclarationRocksTests.cs | using System.Security.Permissions;
using NUnit.Framework;
using Mono.Cecil.Rocks;
namespace Mono.Cecil.Tests {
[TestFixture]
public class SecurityDeclarationRocksTests : BaseTestFixture {
[TestModule ("decsec-xml.dll")]
public void ToPermissionSetFromPermissionSetAttribute (ModuleDefinition module)
{
var type = module.GetType ("SubLibrary");
Assert.IsTrue (type.HasSecurityDeclarations);
Assert.AreEqual (1, type.SecurityDeclarations.Count);
var declaration = type.SecurityDeclarations [0];
var permission_set = declaration.ToPermissionSet ();
Assert.IsNotNull (permission_set);
string permission_set_value = "<PermissionSet class=\"System.Security.PermissionSe"
+ "t\"\r\nversion=\"1\">\r\n<IPermission class=\"{0}\"\r\nversion=\"1\"\r\nFla"
+ "gs=\"UnmanagedCode\"/>\r\n</PermissionSet>\r\n";
permission_set_value = string.Format (permission_set_value, typeof (SecurityPermission).AssemblyQualifiedName);
Assert.AreEqual (Normalize (permission_set_value), Normalize (permission_set.ToXml ().ToString ()));
}
[TestModule ("decsec-att.dll")]
public void ToPermissionSetFromSecurityAttribute (ModuleDefinition module)
{
var type = module.GetType ("SubLibrary");
Assert.IsTrue (type.HasSecurityDeclarations);
Assert.AreEqual (1, type.SecurityDeclarations.Count);
var declaration = type.SecurityDeclarations [0];
var permission_set = declaration.ToPermissionSet ();
Assert.IsNotNull (permission_set);
string permission_set_value = "<PermissionSet class=\"System.Security.PermissionSe"
+ "t\"\r\nversion=\"1\">\r\n<IPermission class=\"{0}\"\r\nversion=\"1\"\r\nFla"
+ "gs=\"UnmanagedCode\"/>\r\n</PermissionSet>\r\n";
permission_set_value = string.Format (permission_set_value, typeof (SecurityPermission).AssemblyQualifiedName);
Assert.AreEqual (Normalize (permission_set_value), Normalize (permission_set.ToXml ().ToString ()));
}
static string Normalize (string s)
{
return s.Replace ("\n", "").Replace ("\r", "");
}
}
}
| using NUnit.Framework;
using Mono.Cecil.Rocks;
namespace Mono.Cecil.Tests {
[TestFixture]
public class SecurityDeclarationRocksTests : BaseTestFixture {
[TestModule ("decsec-xml.dll")]
public void ToPermissionSetFromPermissionSetAttribute (ModuleDefinition module)
{
var type = module.GetType ("SubLibrary");
Assert.IsTrue (type.HasSecurityDeclarations);
Assert.AreEqual (1, type.SecurityDeclarations.Count);
var declaration = type.SecurityDeclarations [0];
var permission_set = declaration.ToPermissionSet ();
Assert.IsNotNull (permission_set);
const string permission_set_value = "<PermissionSet class=\"System.Security.PermissionSe"
+ "t\"\r\nversion=\"1\">\r\n<IPermission class=\"System.Security.Permis"
+ "sions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture"
+ "=neutral, PublicKeyToken=b77a5c561934e089\"\r\nversion=\"1\"\r\nFla"
+ "gs=\"UnmanagedCode\"/>\r\n</PermissionSet>\r\n";
Assert.AreEqual (Normalize (permission_set_value), Normalize (permission_set.ToXml ().ToString ()));
}
[TestModule ("decsec-att.dll")]
public void ToPermissionSetFromSecurityAttribute (ModuleDefinition module)
{
var type = module.GetType ("SubLibrary");
Assert.IsTrue (type.HasSecurityDeclarations);
Assert.AreEqual (1, type.SecurityDeclarations.Count);
var declaration = type.SecurityDeclarations [0];
var permission_set = declaration.ToPermissionSet ();
Assert.IsNotNull (permission_set);
const string permission_set_value = "<PermissionSet class=\"System.Security.PermissionSe"
+ "t\"\r\nversion=\"1\">\r\n<IPermission class=\"System.Security.Permis"
+ "sions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture"
+ "=neutral, PublicKeyToken=b77a5c561934e089\"\r\nversion=\"1\"\r\nFla"
+ "gs=\"UnmanagedCode\"/>\r\n</PermissionSet>\r\n";
Assert.AreEqual (Normalize (permission_set_value), Normalize (permission_set.ToXml ().ToString ()));
}
static string Normalize (string s)
{
return s.Replace ("\n", "").Replace ("\r", "");
}
}
}
| mit | C# |
effe33d4a73620d5347cbaf91d3db668395eed18 | Fix newConnection window is sometimes not displayed | Yonom/CupCake | CupCake.Client/Dispatch.cs | CupCake.Client/Dispatch.cs | using System;
using System.Windows;
namespace CupCake.Client
{
public static class Dispatch
{
public static void Invoke(Action callback)
{
Application.Current.Dispatcher.Invoke(callback);
}
}
} | using System;
using System.Windows;
namespace CupCake.Client
{
public static class Dispatch
{
public static void Invoke(Action callback)
{
Application.Current.Dispatcher.BeginInvoke(callback);
}
}
} | mit | C# |
8aebfe4cd1a3767cde99bac93a7f3355216a7c07 | add comment | dotnet/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,mavasani/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,KevinRansom/roslyn,diryboy/roslyn,mavasani/roslyn,mavasani/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,eriawan/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,sharwell/roslyn,KevinRansom/roslyn,wvdd007/roslyn,weltkante/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn | src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.BidirectionalSymbolSet.cs | src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.BidirectionalSymbolSet.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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// Symbol set used when <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> is <see
/// langword="false"/>.
/// </summary>
private sealed class BidirectionalSymbolSet : SymbolSet
{
/// <summary>
/// When we're cascading in both direction, we can just keep all symbols in a single set. We'll always be
/// examining all of them to go in both up and down directions in every project we process. Any time we
/// add a new symbol to it we'll continue to cascade in both directions looking for more.
/// </summary>
private readonly HashSet<ISymbol> _allSymbols = new();
public BidirectionalSymbolSet(FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, HashSet<ISymbol> upSymbols)
: base(engine)
{
_allSymbols.AddRange(initialSymbols);
_allSymbols.AddRange(upSymbols);
}
public override ImmutableArray<ISymbol> GetAllSymbols()
=> _allSymbols.ToImmutableArray();
public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Start searching using the existing set of symbols found at the start (or anything found below that).
var workQueue = new Stack<ISymbol>();
PushAll(workQueue, _allSymbols);
var projects = ImmutableHashSet.Create(project);
while (workQueue.Count > 0)
{
var current = workQueue.Pop();
// For each symbol we're examining try to walk both up and down from it to see if we discover any
// new symbols in this project. As long as we keep finding symbols, we'll keep searching.
await AddDownSymbolsAsync(current, _allSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false);
await AddUpSymbolsAsync(this.Engine, current, _allSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false);
}
}
}
}
}
| // 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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// Symbol set used when <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> is <see
/// langword="false"/>.
/// </summary>
private sealed class BidirectionalSymbolSet : SymbolSet
{
private readonly HashSet<ISymbol> _allSymbols = new();
public BidirectionalSymbolSet(FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, HashSet<ISymbol> upSymbols)
: base(engine)
{
_allSymbols.AddRange(initialSymbols);
_allSymbols.AddRange(upSymbols);
}
public override ImmutableArray<ISymbol> GetAllSymbols()
=> _allSymbols.ToImmutableArray();
public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Start searching using the existing set of symbols found at the start (or anything found below that).
var workQueue = new Stack<ISymbol>();
PushAll(workQueue, _allSymbols);
var projects = ImmutableHashSet.Create(project);
while (workQueue.Count > 0)
{
var current = workQueue.Pop();
// For each symbol we're examining try to walk both up and down from it to see if we discover any
// new symbols in this project. As long as we keep finding symbols, we'll keep searching.
await AddDownSymbolsAsync(current, _allSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false);
await AddUpSymbolsAsync(this.Engine, current, _allSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false);
}
}
}
}
}
| mit | C# |
65c9827d9c6f4760259ff15e77eb4e454629c9f1 | Fix broken build | StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop | src/BloomTests/TestDoubles/CollectionTab/FakeLibraryModel.cs | src/BloomTests/TestDoubles/CollectionTab/FakeLibraryModel.cs | using Bloom;
using Bloom.Book;
using Bloom.Collection;
using Bloom.CollectionTab;
using Bloom.TeamCollection;
using SIL.TestUtilities;
using BloomTests.TestDoubles.Book;
namespace BloomTests.TestDoubles.CollectionTab
{
// A simplified implementation of LibraryModel that cuts some corners in order to ease setup.
// Tries to provide enough functionality to allow construction of LibraryListView without exceptions, to be able to return/load a collection, and instntiate a dummy SourceCollectionsList which has a dummy templates collection
class FakeLibraryModel : LibraryModel
{
public readonly string TestFolderPath;
public FakeLibraryModel(TemporaryFolder testFolder)
: base(testFolder.Path, new CollectionSettings(), new BookSelection(), GetDefaultSourceCollectionsList(),
BookCollectionFactory, null, new CreateFromSourceBookCommand(), new FakeBookServer(), new CurrentEditableCollectionSelection(), null, new TeamCollectionManager(testFolder.FolderPath))
{
TestFolderPath = testFolder.Path;
}
protected static SourceCollectionsList GetDefaultSourceCollectionsList()
{
var parentFolder = new TemporaryFolder("Parent");
var templateCollectionFolder = new TemporaryFolder(parentFolder, "Templates");
return new SourceCollectionsList(null, null, null, new string[] { parentFolder.Path });
}
public static BookCollection BookCollectionFactory(string path, BookCollection.CollectionType collectionType)
{
return new BookCollection(path, collectionType, null);
}
}
}
| using Bloom;
using Bloom.Book;
using Bloom.Collection;
using Bloom.CollectionTab;
using SIL.TestUtilities;
using BloomTests.TestDoubles.Book;
namespace BloomTests.TestDoubles.CollectionTab
{
// A simplified implementation of LibraryModel that cuts some corners in order to ease setup.
// Tries to provide enough functionality to allow construction of LibraryListView without exceptions, to be able to return/load a collection, and instntiate a dummy SourceCollectionsList which has a dummy templates collection
class FakeLibraryModel : LibraryModel
{
public readonly string TestFolderPath;
public FakeLibraryModel(TemporaryFolder testFolder)
: base(testFolder.Path, new CollectionSettings(), new BookSelection(), GetDefaultSourceCollectionsList(),
BookCollectionFactory, null, new CreateFromSourceBookCommand(), new FakeBookServer(), new CurrentEditableCollectionSelection(), null, null)
{
TestFolderPath = testFolder.Path;
}
protected static SourceCollectionsList GetDefaultSourceCollectionsList()
{
var parentFolder = new TemporaryFolder("Parent");
var templateCollectionFolder = new TemporaryFolder(parentFolder, "Templates");
return new SourceCollectionsList(null, null, null, new string[] { parentFolder.Path });
}
public static BookCollection BookCollectionFactory(string path, BookCollection.CollectionType collectionType)
{
return new BookCollection(path, collectionType, null);
}
}
}
| mit | C# |
8a23e40466f6844ee6ffa2b3c443f889e90d68fc | Refactor DotNetToTypeScriptType::Mapping | another-guy/CSharpToTypeScript,another-guy/CSharpToTypeScript | Core/DotNetToTypeScriptType.cs | Core/DotNetToTypeScriptType.cs | using System;
using System.Collections.Generic;
namespace TsModelGen.Core
{
public static class DotNetToTypeScriptType
{
public static Dictionary<string, string> Mapping => MappingLazy.Value;
private static readonly Lazy<Dictionary<string, string>> MappingLazy =
new Lazy<Dictionary<string, string>>(
// Simple cases:
// * object -> any
// * primitive types to their TS direct translations
() => new Dictionary<string, string>
{
{NameOf<object>(), "any"},
{NameOf<short>(), "number"},
{NameOf<int>(), "number"},
{NameOf<long>(), "number"},
{NameOf<ushort>(), "number"},
{NameOf<uint>(), "number"},
{NameOf<ulong>(), "number"},
{NameOf<byte>(), "number"},
{NameOf<sbyte>(), "number"},
{NameOf<float>(), "number"},
{NameOf<double>(), "number"},
{NameOf<decimal>(), "number"},
{NameOf<bool>(), "boolean"},
{NameOf<string>(), "string"},
{NameOf<DateTime>(), "boolean"}
// { char -> ??? },
// { TimeSpan -> ??? },
});
private static string NameOf<T>()
{
return typeof(T).FullName;
}
}
} | using System;
using System.Collections.Generic;
namespace TsModelGen.Core
{
public static class DotNetToTypeScriptType
{
public static Dictionary<string, string> Mapping => MappingLazy.Value;
private static readonly Lazy<Dictionary<string, string>> MappingLazy =
new Lazy<Dictionary<string, string>>(
// Simple cases:
// * object -> any
// * primitive types to their TS direct translations
() => new Dictionary<string, string>
{
{typeof(object).FullName, "any"},
{typeof(short).FullName, "number"},
{typeof(int).FullName, "number"},
{typeof(long).FullName, "number"},
{typeof(ushort).FullName, "number"},
{typeof(uint).FullName, "number"},
{typeof(ulong).FullName, "number"},
{typeof(byte).FullName, "number"},
{typeof(sbyte).FullName, "number"},
{typeof(float).FullName, "number"},
{typeof(double).FullName, "number"},
{typeof(decimal).FullName, "number"},
{typeof(bool).FullName, "boolean"},
{typeof(string).FullName, "string"},
{typeof(DateTime).FullName, "boolean"}
// { typeof(char).FullName, "any" },
// { typeof(TimeSpan).FullName, "boolean" },
});
}
} | mit | C# |
651cf1595248f5e66005bb515053734f961f65be | Make constructor of abstract class protected | picklesdoc/pickles,magicmonty/pickles,ludwigjossieaux/pickles,ludwigjossieaux/pickles,dirkrombauts/pickles,magicmonty/pickles,ludwigjossieaux/pickles,magicmonty/pickles,magicmonty/pickles,dirkrombauts/pickles,picklesdoc/pickles,dirkrombauts/pickles,picklesdoc/pickles,picklesdoc/pickles,dirkrombauts/pickles | src/Pickles/Pickles.TestFrameworks/XUnit/XUnitResultsBase.cs | src/Pickles/Pickles.TestFrameworks/XUnit/XUnitResultsBase.cs | using System.Linq;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.TestFrameworks.XUnit
{
public abstract class XUnitResultsBase<TSingleResult> : MultipleTestResults
where TSingleResult : XUnitSingleResultsBase
{
protected XUnitResultsBase(IConfiguration configuration, ISingleResultLoader singleResultLoader, XUnitExampleSignatureBuilder exampleSignatureBuilder)
: base(true, configuration, singleResultLoader)
{
this.SetExampleSignatureBuilder(exampleSignatureBuilder);
}
public void SetExampleSignatureBuilder(XUnitExampleSignatureBuilder exampleSignatureBuilder)
{
foreach (var testResult in TestResults.OfType<TSingleResult>())
{
testResult.ExampleSignatureBuilder = exampleSignatureBuilder;
}
}
public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments)
{
var results = TestResults.OfType<TSingleResult>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray();
return EvaluateTestResults(results);
}
}
} | using System.Linq;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.TestFrameworks.XUnit
{
public abstract class XUnitResultsBase<TSingleResult> : MultipleTestResults
where TSingleResult : XUnitSingleResultsBase
{
public XUnitResultsBase(IConfiguration configuration, ISingleResultLoader singleResultLoader, XUnitExampleSignatureBuilder exampleSignatureBuilder)
: base(true, configuration, singleResultLoader)
{
this.SetExampleSignatureBuilder(exampleSignatureBuilder);
}
public void SetExampleSignatureBuilder(XUnitExampleSignatureBuilder exampleSignatureBuilder)
{
foreach (var testResult in TestResults.OfType<TSingleResult>())
{
testResult.ExampleSignatureBuilder = exampleSignatureBuilder;
}
}
public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments)
{
var results = TestResults.OfType<TSingleResult>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray();
return EvaluateTestResults(results);
}
}
} | apache-2.0 | C# |
53b681aa2b63be4d89c731f6cd7af6f14e47b3ca | Revert "pad check" | serilog/serilog-sinks-console,serilog/serilog-sinks-console | src/Serilog.Sinks.Console/Sinks/SystemConsole/Rendering/Padding.cs | src/Serilog.Sinks.Console/Sinks/SystemConsole/Rendering/Padding.cs | // Copyright 2013-2017 Serilog Contributors
//
// 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.IO;
using Serilog.Parsing;
namespace Serilog.Sinks.SystemConsole.Rendering
{
static class Padding
{
static readonly char[] PaddingChars = new string(' ', 80).ToCharArray();
/// <summary>
/// Writes the provided value to the output, applying direction-based padding when <paramref name="alignment"/> is provided.
/// </summary>
public static void Apply(TextWriter output, string value, Alignment? alignment)
{
if (!alignment.HasValue || value.Length >= alignment.Value.Width)
{
output.Write(value);
return;
}
var pad = alignment.Value.Width - value.Length;
if (alignment.Value.Direction == AlignmentDirection.Left)
output.Write(value);
if (pad <= PaddingChars.Length)
{
output.Write(PaddingChars, 0, pad);
}
else
{
output.Write(new string(' ', pad));
}
if (alignment.Value.Direction == AlignmentDirection.Right)
output.Write(value);
}
}
} | // Copyright 2013-2017 Serilog Contributors
//
// 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.IO;
using Serilog.Parsing;
namespace Serilog.Sinks.SystemConsole.Rendering
{
static class Padding
{
static readonly char[] PaddingChars = new string(' ', 80).ToCharArray();
/// <summary>
/// Writes the provided value to the output, applying direction-based padding when <paramref name="alignment"/> is provided.
/// </summary>
public static void Apply(TextWriter output, string value, Alignment? alignment)
{
if (!alignment.HasValue || value.Length >= alignment.Value.Width)
{
output.Write(value);
return;
}
if (alignment.Value.Direction == AlignmentDirection.Left)
output.Write(value);
var pad = alignment.Value.Width - value.Length;
if (pad > 0)
{
if (pad <= PaddingChars.Length)
{
output.Write(PaddingChars, 0, pad);
}
else
{
output.Write(new string(' ', pad));
}
}
if (alignment.Value.Direction == AlignmentDirection.Right)
output.Write(value);
}
}
} | apache-2.0 | C# |
f7604ddc70664a3984172c04fff07e97ca3d6ec7 | Use unchecked math. | bartdesmet/roslyn,weltkante/roslyn,jamesqo/roslyn,wvdd007/roslyn,AmadeusW/roslyn,heejaechang/roslyn,swaroop-sridhar/roslyn,bkoelman/roslyn,davkean/roslyn,ErikSchierboom/roslyn,DustinCampbell/roslyn,mgoertz-msft/roslyn,reaction1989/roslyn,VSadov/roslyn,heejaechang/roslyn,jmarolf/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,OmarTawfik/roslyn,paulvanbrenk/roslyn,nguerrera/roslyn,xasx/roslyn,KirillOsenkov/roslyn,agocke/roslyn,stephentoub/roslyn,VSadov/roslyn,CyrusNajmabadi/roslyn,tmeschter/roslyn,jasonmalinowski/roslyn,bkoelman/roslyn,KirillOsenkov/roslyn,cston/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,paulvanbrenk/roslyn,panopticoncentral/roslyn,swaroop-sridhar/roslyn,dpoeschl/roslyn,MichalStrehovsky/roslyn,jmarolf/roslyn,weltkante/roslyn,aelij/roslyn,jamesqo/roslyn,nguerrera/roslyn,genlu/roslyn,mgoertz-msft/roslyn,tmat/roslyn,agocke/roslyn,DustinCampbell/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,eriawan/roslyn,MichalStrehovsky/roslyn,OmarTawfik/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,physhi/roslyn,abock/roslyn,cston/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,dotnet/roslyn,davkean/roslyn,cston/roslyn,dpoeschl/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tannergooding/roslyn,physhi/roslyn,heejaechang/roslyn,paulvanbrenk/roslyn,jcouv/roslyn,MichalStrehovsky/roslyn,dotnet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,panopticoncentral/roslyn,abock/roslyn,abock/roslyn,ErikSchierboom/roslyn,gafter/roslyn,gafter/roslyn,swaroop-sridhar/roslyn,OmarTawfik/roslyn,reaction1989/roslyn,agocke/roslyn,tmat/roslyn,DustinCampbell/roslyn,xasx/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,jmarolf/roslyn,panopticoncentral/roslyn,aelij/roslyn,tannergooding/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,KevinRansom/roslyn,jamesqo/roslyn,KevinRansom/roslyn,dpoeschl/roslyn,VSadov/roslyn,AlekseyTs/roslyn,xasx/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,diryboy/roslyn,tmeschter/roslyn,genlu/roslyn,jcouv/roslyn,tmeschter/roslyn,diryboy/roslyn,wvdd007/roslyn,gafter/roslyn,sharwell/roslyn,mavasani/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,genlu/roslyn,davkean/roslyn,wvdd007/roslyn,jcouv/roslyn,mavasani/roslyn,dotnet/roslyn,bkoelman/roslyn,mavasani/roslyn,sharwell/roslyn,tannergooding/roslyn,weltkante/roslyn,stephentoub/roslyn,physhi/roslyn,eriawan/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,eriawan/roslyn,stephentoub/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn | src/Workspaces/Core/Portable/RegularExpressions/RegexDiagnostic.cs | src/Workspaces/Core/Portable/RegularExpressions/RegexDiagnostic.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.RegularExpressions
{
/// <summary>
/// Represents an error in a regular expression. The error contains the message to show a user
/// (which should be as close as possible to the error that the .Net regex library would produce),
/// as well as the span of the error. This span is in actual user character coordinates. For
/// example, if the user has the string "...\\p{0}..." then the span of the error would be for
/// the range of characters for '\\p{0}' (even though the regex engine would only see the \\ translated
/// as a virtual char to the single \ character.
/// </summary>
internal struct RegexDiagnostic : IEquatable<RegexDiagnostic>
{
public readonly string Message;
public readonly TextSpan Span;
public RegexDiagnostic(string message, TextSpan span)
{
Debug.Assert(message != null);
Message = message;
Span = span;
}
public override bool Equals(object obj)
=> obj is RegexDiagnostic rd && Equals(rd);
public bool Equals(RegexDiagnostic other)
=> Message == other.Message &&
Span.Equals(other.Span);
public override int GetHashCode()
{
unchecked
{
var hashCode = -954867195;
hashCode = hashCode * -1521134295 + base.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Message);
hashCode = hashCode * -1521134295 + EqualityComparer<TextSpan>.Default.GetHashCode(Span);
return hashCode;
}
}
public static bool operator ==(RegexDiagnostic diagnostic1, RegexDiagnostic diagnostic2)
=> diagnostic1.Equals(diagnostic2);
public static bool operator !=(RegexDiagnostic diagnostic1, RegexDiagnostic diagnostic2)
=> !(diagnostic1 == diagnostic2);
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.RegularExpressions
{
/// <summary>
/// Represents an error in a regular expression. The error contains the message to show a user
/// (which should be as close as possible to the error that the .Net regex library would produce),
/// as well as the span of the error. This span is in actual user character coordinates. For
/// example, if the user has the string "...\\p{0}..." then the span of the error would be for
/// the range of characters for '\\p{0}' (even though the regex engine would only see the \\ translated
/// as a virtual char to the single \ character.
/// </summary>
internal struct RegexDiagnostic : IEquatable<RegexDiagnostic>
{
public readonly string Message;
public readonly TextSpan Span;
public RegexDiagnostic(string message, TextSpan span)
{
Debug.Assert(message != null);
Message = message;
Span = span;
}
public override bool Equals(object obj)
=> obj is RegexDiagnostic rd && Equals(rd);
public bool Equals(RegexDiagnostic other)
=> Message == other.Message &&
Span.Equals(other.Span);
public override int GetHashCode()
{
var hashCode = -954867195;
hashCode = hashCode * -1521134295 + base.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Message);
hashCode = hashCode * -1521134295 + EqualityComparer<TextSpan>.Default.GetHashCode(Span);
return hashCode;
}
public static bool operator ==(RegexDiagnostic diagnostic1, RegexDiagnostic diagnostic2)
=> diagnostic1.Equals(diagnostic2);
public static bool operator !=(RegexDiagnostic diagnostic1, RegexDiagnostic diagnostic2)
=> !(diagnostic1 == diagnostic2);
}
}
| mit | C# |
989d4d9b098c8730f90871ffa073e757b14f8ffe | remove redundant configuration | aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples | MySqlDemo/aspnet-core/src/Acme.MySqlDemo.EntityFrameworkCore/EntityFrameworkCore/MySqlDemoDbContextConfigurer.cs | MySqlDemo/aspnet-core/src/Acme.MySqlDemo.EntityFrameworkCore/EntityFrameworkCore/MySqlDemoDbContextConfigurer.cs | using System.Data.Common;
using Microsoft.EntityFrameworkCore;
namespace Acme.MySqlDemo.EntityFrameworkCore
{
public static class MySqlDemoDbContextConfigurer
{
public static void Configure(DbContextOptionsBuilder<MySqlDemoDbContext> builder, string connectionString)
{
builder.UseMySql(connectionString);
}
public static void Configure(DbContextOptionsBuilder<MySqlDemoDbContext> builder, DbConnection connection)
{
builder.UseMySql(connection);
}
}
}
| using System.Data.Common;
using Microsoft.EntityFrameworkCore;
namespace Acme.MySqlDemo.EntityFrameworkCore
{
public static class MySqlDemoDbContextConfigurer
{
public static void Configure(DbContextOptionsBuilder<MySqlDemoDbContext> builder, string connectionString)
{
builder.UseMySql(connectionString, mySqlOptionsAction =>
{
mySqlOptionsAction.MigrationsAssembly(typeof(MySqlDemoDbContextConfigurer).Assembly.GetName().Name);
});
}
public static void Configure(DbContextOptionsBuilder<MySqlDemoDbContext> builder, DbConnection connection)
{
builder.UseMySql(connection, mySqlOptionsAction =>
{
mySqlOptionsAction.MigrationsAssembly(typeof(MySqlDemoDbContextConfigurer).Assembly.GetName().Name);
});
}
}
}
| mit | C# |
ae03ef07875752960de705094946409e0b9cf655 | Allow audio device selection in settings | osu-RP/osu-RP,peppy/osu,ZLima12/osu,smoogipoo/osu,Drezi126/osu,default0/osu,naoey/osu,ppy/osu,Nabile-Rahmani/osu,NotKyon/lolisu,NeoAdonis/osu,EVAST9919/osu,naoey/osu,nyaamara/osu,ZLima12/osu,UselessToucan/osu,UselessToucan/osu,RedNesto/osu,smoogipoo/osu,johnneijzen/osu,DrabWeb/osu,tacchinotacchi/osu,2yangk23/osu,peppy/osu,peppy/osu,Damnae/osu,theguii/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,Frontear/osuKyzer,NeoAdonis/osu,ppy/osu,johnneijzen/osu,ppy/osu,EVAST9919/osu,DrabWeb/osu,UselessToucan/osu,2yangk23/osu,naoey/osu,peppy/osu-new,DrabWeb/osu | osu.Game/Overlays/Options/Sections/Audio/AudioDevicesOptions.cs | osu.Game/Overlays/Options/Sections/Audio/AudioDevicesOptions.cs | //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Graphics;
using System.Collections.Generic;
using System.Linq;
namespace osu.Game.Overlays.Options.Sections.Audio
{
public class AudioDevicesOptions : OptionsSubsection
{
protected override string Header => "Devices";
private AudioManager audio;
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
this.audio = audio;
}
protected override void LoadComplete()
{
base.LoadComplete();
var deviceItems = new List<KeyValuePair<string, string>>();
deviceItems.Add(new KeyValuePair<string, string>("Standard", ""));
deviceItems.AddRange(audio.GetDeviceNames().Select(d => new KeyValuePair<string, string>(d, d)));
Children = new Drawable[]
{
new OptionDropDown<string>()
{
Items = deviceItems,
Bindable = audio.AudioDevice
},
};
}
}
} | //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
namespace osu.Game.Overlays.Options.Sections.Audio
{
public class AudioDevicesOptions : OptionsSubsection
{
protected override string Header => "Devices";
public AudioDevicesOptions()
{
Children = new[]
{
new OptionLabel { Text = "Output device: TODO dropdown" }
};
}
}
} | mit | C# |
fd28b58b12e580c3509c3e8ccb26a82205f99b54 | Fix linking of follow camera to hero | puzzud/Flipper | Assets/Scripts/FollowCamera.cs | Assets/Scripts/FollowCamera.cs | using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour {
public GameObject global;
public GameObject objectToFollow;
// Use this for initialization
void Start () {
if (global == null)
{
return;
}
Global g = global.GetComponent<Global>();
if (g == null)
{
return;
}
objectToFollow = g.hero;
}
// Update is called once per frame (use LateUpdate for cameras)
void LateUpdate () {
if (objectToFollow != null)
{
transform.LookAt(objectToFollow.transform);
}
else
{
Global g = global.GetComponent<Global>();
if (g == null)
{
return;
}
objectToFollow = g.hero;
}
}
}
| using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour {
public GameObject global;
public GameObject objectToFollow;
// Use this for initialization
void Start () {
if (global == null)
{
return;
}
Global g = global.GetComponent<Global>();
if (g == null)
{
return;
}
objectToFollow = g.hero;
}
// Update is called once per frame (use LateUpdate for cameras)
void LateUpdate () {
transform.LookAt(objectToFollow.transform);
}
}
| mit | C# |
39aac9b761b42618a6dd7babf9b83cc3a530ead7 | Update Tests.cs | ic16b055/oom | tasks/Task3/Task3/Tests.cs | tasks/Task3/Task3/Tests.cs | using System;
using Task3;
namespace Tests
{
[TestFixture]
public class ComputerTests
{
[Test]
public void CanCreatComputer()
{
var x = new Computer("Asus", "Zenbook UX330UA", 7, 1200);
Assert.IsTrue(x.Company == "Asus");
Assert.IsTrue(x.Model == "Zenbook UX330UA");
Assert.IsTrue(x.Pieces == 7);
Assert.IsTrue(x.Price == 1200);
}
[Test]
public void CannotCreateCompanyWithEmptyTitle()
{
var x = new Computer(null, "xxx", 0, 0);
}
[Test]
public void CannotCreateModelWithEmptyTitle()
{
var x = new Computer("xxx", null, 0, 0);
}
[Test]
public void CannotCreatePiecesGreatherThan99()
{
var x = new Computer("xxx", "xxx", 100, 0);
}
[Test]
public void CannotCreatePriceNotInRange()
{
var lowestPrice = new Computer("xxx", "xxx", 0, -5);
var highestPrice = new Computer("xxx", "xxx", 0, 100000);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Task3;
namespace Tests
{
[TestFixture]
public class ComputerTests
{
[Test]
public void CanCreatComputer()
{
var x = new Computer("Asus", "Zenbook UX330UA", 7, 1200);
Assert.IsTrue(x.Company == "Asus");
Assert.IsTrue(x.Model == "Zenbook UX330UA");
Assert.IsTrue(x.Pieces == 7);
Assert.IsTrue(x.Price == 1200);
}
[Test]
public void CannotCreateCompanyWithEmptyTitle()
{
var x = new Computer(null, "xxx", 0, 0);
}
[Test]
public void CannotCreateModelWithEmptyTitle()
{
var x = new Computer("xxx", null, 0, 0);
}
[Test]
public void CannotCreatePiecesGreatherThan99()
{
var x = new Computer("xxx", "xxx", 100, 0);
}
[Test]
public void CannotCreatePriceNotInRange()
{
var lowestPrice = new Computer("xxx", "xxx", 0, -5);
var highestPrice = new Computer("xxx", "xxx", 0, 100000);
}
}
}
| mit | C# |
c18538d38247032109d6fa74d8803efa8cf759ad | Optimise Eager ORM implementation | hgcummings/DataAccessExamples,hgcummings/DataAccessExamples | DataAccessExamples.Core/Services/EagerOrmDepartmentService.cs | DataAccessExamples.Core/Services/EagerOrmDepartmentService.cs | using System;
using System.Data.Entity;
using System.Linq;
using DataAccessExamples.Core.Data;
using DataAccessExamples.Core.ViewModels;
namespace DataAccessExamples.Core.Services
{
public class EagerOrmDepartmentService : IDepartmentService
{
private readonly EmployeesContext context;
public EagerOrmDepartmentService(EmployeesContext context)
{
this.context = context;
}
public DepartmentList ListDepartments()
{
return new DepartmentList {
Departments = context.Departments.OrderBy(d => d.Code).Select(d => new DepartmentSummary
{
Code = d.Code,
Name = d.Name
})
};
}
public DepartmentList ListAverageSalaryPerDepartment()
{
return new DepartmentList
{
Departments = context.Departments
.Include(d => d.DepartmentEmployees.Select(e => e.Employee.Salaries))
.Select(d => new DepartmentSalary
{
Code = d.Code,
Name = d.Name,
AverageSalary =
(int) d.DepartmentEmployees.SelectMany(
e => e.Employee.Salaries
.Where(s => s != null)
.Where(s => s.ToDate > DateTime.Now)
.Take(1))
.Average(s => s.Amount)
})
.OrderByDescending(d => d.AverageSalary)
};
}
}
}
| using System;
using System.Data.Entity;
using System.Linq;
using DataAccessExamples.Core.Data;
using DataAccessExamples.Core.ViewModels;
namespace DataAccessExamples.Core.Services
{
public class EagerOrmDepartmentService : IDepartmentService
{
private readonly EmployeesContext context;
public EagerOrmDepartmentService(EmployeesContext context)
{
this.context = context;
}
public DepartmentList ListDepartments()
{
return new DepartmentList {
Departments = context.Departments.OrderBy(d => d.Code).Select(d => new DepartmentSummary
{
Code = d.Code,
Name = d.Name
})
};
}
public DepartmentList ListAverageSalaryPerDepartment()
{
return new DepartmentList
{
Departments = context.Departments
.Include(d => d.DepartmentEmployees.Select(e => e.Employee.Salaries))
.AsEnumerable().Select(d => new DepartmentSalary
{
Code = d.Code,
Name = d.Name,
AverageSalary =
(int) d.DepartmentEmployees.Select(
e => e.Employee.Salaries.LastOrDefault(s => s.ToDate > DateTime.Now))
.Where(s => s != null)
.Average(s => s.Amount)
})
};
}
}
}
| cc0-1.0 | C# |
1093cf6410bfbb3516c9ff9d0c1c0cbb355875a6 | Simplify code. | cston/roslyn,jmarolf/roslyn,lorcanmooney/roslyn,agocke/roslyn,pdelvo/roslyn,jcouv/roslyn,sharwell/roslyn,abock/roslyn,bartdesmet/roslyn,pdelvo/roslyn,panopticoncentral/roslyn,bkoelman/roslyn,khyperia/roslyn,kelltrick/roslyn,jamesqo/roslyn,wvdd007/roslyn,reaction1989/roslyn,pdelvo/roslyn,physhi/roslyn,aelij/roslyn,mavasani/roslyn,weltkante/roslyn,ErikSchierboom/roslyn,bkoelman/roslyn,jamesqo/roslyn,yeaicc/roslyn,tannergooding/roslyn,eriawan/roslyn,swaroop-sridhar/roslyn,paulvanbrenk/roslyn,tmat/roslyn,tvand7093/roslyn,Hosch250/roslyn,davkean/roslyn,kelltrick/roslyn,amcasey/roslyn,dpoeschl/roslyn,AmadeusW/roslyn,AnthonyDGreen/roslyn,jkotas/roslyn,davkean/roslyn,KevinRansom/roslyn,physhi/roslyn,dotnet/roslyn,diryboy/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,xasx/roslyn,tmeschter/roslyn,ErikSchierboom/roslyn,amcasey/roslyn,Giftednewt/roslyn,MichalStrehovsky/roslyn,mattwar/roslyn,kelltrick/roslyn,VSadov/roslyn,eriawan/roslyn,panopticoncentral/roslyn,genlu/roslyn,sharwell/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,MattWindsor91/roslyn,paulvanbrenk/roslyn,tannergooding/roslyn,nguerrera/roslyn,bbarry/roslyn,jasonmalinowski/roslyn,reaction1989/roslyn,stephentoub/roslyn,tannergooding/roslyn,AmadeusW/roslyn,bkoelman/roslyn,jkotas/roslyn,nguerrera/roslyn,zooba/roslyn,orthoxerox/roslyn,dpoeschl/roslyn,jasonmalinowski/roslyn,bbarry/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,robinsedlaczek/roslyn,diryboy/roslyn,MichalStrehovsky/roslyn,jeffanders/roslyn,weltkante/roslyn,paulvanbrenk/roslyn,akrisiun/roslyn,OmarTawfik/roslyn,tmeschter/roslyn,mmitche/roslyn,KevinRansom/roslyn,zooba/roslyn,jamesqo/roslyn,CaptainHayashi/roslyn,lorcanmooney/roslyn,orthoxerox/roslyn,heejaechang/roslyn,tvand7093/roslyn,gafter/roslyn,stephentoub/roslyn,yeaicc/roslyn,sharwell/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,khyperia/roslyn,swaroop-sridhar/roslyn,KirillOsenkov/roslyn,jeffanders/roslyn,aelij/roslyn,tvand7093/roslyn,VSadov/roslyn,AlekseyTs/roslyn,TyOverby/roslyn,swaroop-sridhar/roslyn,bbarry/roslyn,abock/roslyn,Giftednewt/roslyn,diryboy/roslyn,cston/roslyn,jcouv/roslyn,jcouv/roslyn,Giftednewt/roslyn,bartdesmet/roslyn,physhi/roslyn,xasx/roslyn,Hosch250/roslyn,genlu/roslyn,weltkante/roslyn,drognanar/roslyn,mavasani/roslyn,jkotas/roslyn,mattwar/roslyn,TyOverby/roslyn,amcasey/roslyn,reaction1989/roslyn,akrisiun/roslyn,drognanar/roslyn,DustinCampbell/roslyn,tmeschter/roslyn,jmarolf/roslyn,agocke/roslyn,abock/roslyn,panopticoncentral/roslyn,MattWindsor91/roslyn,akrisiun/roslyn,tmat/roslyn,MichalStrehovsky/roslyn,brettfo/roslyn,OmarTawfik/roslyn,davkean/roslyn,srivatsn/roslyn,DustinCampbell/roslyn,robinsedlaczek/roslyn,mattscheffer/roslyn,MattWindsor91/roslyn,shyamnamboodiripad/roslyn,cston/roslyn,orthoxerox/roslyn,lorcanmooney/roslyn,tmat/roslyn,yeaicc/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,TyOverby/roslyn,genlu/roslyn,robinsedlaczek/roslyn,khyperia/roslyn,jeffanders/roslyn,nguerrera/roslyn,MattWindsor91/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,AnthonyDGreen/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,AdamSpeight2008/roslyn-AdamSpeight2008,drognanar/roslyn,CaptainHayashi/roslyn,aelij/roslyn,mmitche/roslyn,CaptainHayashi/roslyn,brettfo/roslyn,mattwar/roslyn,agocke/roslyn,srivatsn/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,gafter/roslyn,dotnet/roslyn,heejaechang/roslyn,Hosch250/roslyn,dpoeschl/roslyn,mattscheffer/roslyn,stephentoub/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,KirillOsenkov/roslyn,mmitche/roslyn,VSadov/roslyn,AnthonyDGreen/roslyn,xasx/roslyn,wvdd007/roslyn,zooba/roslyn,gafter/roslyn,jmarolf/roslyn,dotnet/roslyn,srivatsn/roslyn,OmarTawfik/roslyn,mattscheffer/roslyn | src/Features/Core/Portable/Diagnostics/Analyzers/NamingStyles/NamingStylePreferencesInfo.cs | src/Features/Core/Portable/Diagnostics/Analyzers/NamingStyles/NamingStylePreferencesInfo.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;
using System.Linq;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal class NamingStylePreferencesInfo
{
public ImmutableArray<NamingRule> NamingRules { get; }
public NamingStylePreferencesInfo(ImmutableArray<NamingRule> namingRules)
{
NamingRules = namingRules;
}
internal bool TryGetApplicableRule(ISymbol symbol, out NamingRule applicableRule)
{
if (NamingRules == null)
{
applicableRule = null;
return false;
}
if (!IsSymbolNameAnalyzable(symbol))
{
applicableRule = null;
return false;
}
foreach (var namingRule in NamingRules)
{
if (namingRule.AppliesTo(symbol))
{
applicableRule = namingRule;
return true;
}
}
applicableRule = null;
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;
using System.Linq;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal class NamingStylePreferencesInfo
{
public ImmutableArray<NamingRule> NamingRules { get; }
public NamingStylePreferencesInfo(ImmutableArray<NamingRule> namingRules)
{
NamingRules = namingRules;
}
internal bool TryGetApplicableRule(ISymbol symbol, out NamingRule applicableRule)
{
if (NamingRules == null)
{
applicableRule = null;
return false;
}
if (!IsSymbolNameAnalyzable(symbol))
{
applicableRule = null;
return false;
}
foreach (var namingRule in NamingRules)
{
if (namingRule.AppliesTo(symbol))
{
applicableRule = namingRule;
return true;
}
}
applicableRule = null;
return false;
}
private bool IsSymbolNameAnalyzable(ISymbol symbol)
{
if (symbol.Kind == SymbolKind.Method)
{
var methodSymbol = symbol as IMethodSymbol;
if (methodSymbol != null && methodSymbol.MethodKind != MethodKind.Ordinary)
{
return false;
}
}
if (symbol.Kind == SymbolKind.Property)
{
var propertySymbol = symbol as IPropertySymbol;
if (propertySymbol != null && propertySymbol.IsIndexer)
{
return false;
}
}
return true;
}
}
} | mit | C# |
2c1231a1d54b36b4e928f1d1543a01a0a6476e77 | Add OptimizationCount to UserData. | nfleet/.net-sdk | NFleetSDK/Data/UserData.cs | NFleetSDK/Data/UserData.cs | using System.Collections.Generic;
using System.Runtime.Serialization;
namespace NFleet.Data
{
[DataContract]
public class UserData : IResponseData
{
[IgnoreDataMember]
public int VersionNumber { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public int ProblemLimit { get; set; }
[DataMember]
public int VehicleLimit { get; set; }
[DataMember]
public int TaskLimit { get; set; }
[DataMember]
public int OptimizationQueueLimit { get; set; }
[DataMember]
public int OptimizationCount { get; set; }
#region Implementation of IResponseData
[DataMember]
public List<Link> Meta { get; set; }
#endregion
}
}
| using System.Collections.Generic;
using System.Runtime.Serialization;
namespace NFleet.Data
{
[DataContract]
public class UserData : IResponseData
{
[IgnoreDataMember]
public int VersionNumber { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public int ProblemLimit { get; set; }
[DataMember]
public int VehicleLimit { get; set; }
[DataMember]
public int TaskLimit { get; set; }
[DataMember]
public int OptimizationQueueLimit { get; set; }
#region Implementation of IResponseData
[DataMember]
public List<Link> Meta { get; set; }
#endregion
}
}
| mit | C# |
a2fff765f42127b1bbc7a2b853da5c516f127687 | Fix missing quote | peterblazejewicz/aspnet-5-bootstrap-4,peterblazejewicz/aspnet-5-bootstrap-4 | WebApplication/Views/Account/ExternalLoginConfirmation.cshtml | WebApplication/Views/Account/ExternalLoginConfirmation.cshtml | @model ExternalLoginConfirmationViewModel
@{
ViewData["Title"] = "Register";
}
<h2>@ViewData["Title"].</h2>
<h3>Associate your @ViewData["LoginProvider"] account.</h3>
<form asp-controller="Account" asp-action="ExternalLoginConfirmation" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal" role="form">
<h4>Association Form</h4>
<hr />
<div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
<p class="text-info">
You've successfully authenticated with <strong>@ViewData["LoginProvider"]</strong>.
Please enter a user name for this site below and click the Register button to finish
logging in.
</p>
<div class="form-group">
<label asp-for="Email" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
</form>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
| @model ExternalLoginConfirmationViewModel
@{
ViewData["Title"] = "Register";
}
<h2>@ViewData["Title"].</h2>
<h3>Associate your @ViewData["LoginProvider"] account.</h3>
<form asp-controller="Account" asp-action="ExternalLoginConfirmation" asp-route-returnurl="@ViewData["ReturnUrl"] method="post" class="form-horizontal" role="form">
<h4>Association Form</h4>
<hr />
<div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
<p class="text-info">
You've successfully authenticated with <strong>@ViewData["LoginProvider"]</strong>.
Please enter a user name for this site below and click the Register button to finish
logging in.
</p>
<div class="form-group">
<label asp-for="Email" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
</form>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
| mit | C# |
c65dd781d622cc3e719ea6bf44ea5d38fb173e8b | Add shortcut for SortedList to not require explicitly creating a comparer class. | DrabWeb/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,naoey/osu-framework,smoogipooo/osu-framework,default0/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,RedNesto/osu-framework,ZLima12/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,default0/osu-framework,peppy/osu-framework,ppy/osu-framework,naoey/osu-framework,paparony03/osu-framework,RedNesto/osu-framework,ppy/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,Tom94/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework | osu.Framework/Lists/SortedList.cs | osu.Framework/Lists/SortedList.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
namespace osu.Framework.Lists
{
public class SortedList<T> : List<T>
{
public IComparer<T> Comparer { get; }
public SortedList(Func<T,T,int> comparer)
{
Comparer = new ComparisonComparer<T>(comparer);
}
public SortedList(IComparer<T> comparer)
{
Comparer = comparer;
}
public new int Add(T value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
int index = getAdditionIndex(value);
Insert(index, value);
return index;
}
public new int IndexOf(T value)
{
return BinarySearch(value, Comparer);
}
/// <summary>
/// Gets the first index of the element larger than value.
/// </summary>
/// <param name="value">The value to search for.</param>
/// <returns>The index of the first element larger than value.</returns>
private int getAdditionIndex(T value)
{
int index = BinarySearch(value, Comparer);
if (index < 0)
index = ~index;
// Binary search is not guaranteed to give the last index
// when duplicates are involved, so let's move towards it
for (; index < Count; index++)
{
if (Comparer.Compare(this[index], value) != 0)
break;
}
return index;
}
private class ComparisonComparer<TComparison> : IComparer<TComparison>
{
private readonly Comparison<TComparison> comparison;
public ComparisonComparer(Func<TComparison, TComparison, int> compare)
{
if (compare == null)
{
throw new ArgumentNullException(nameof(compare));
}
comparison = new Comparison<TComparison>(compare);
}
public int Compare(TComparison x, TComparison y)
{
return comparison(x, y);
}
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
namespace osu.Framework.Lists
{
public class SortedList<T> : List<T>
{
public IComparer<T> Comparer { get; }
public SortedList(IComparer<T> comparer)
{
Comparer = comparer;
}
public new int Add(T value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
int index = getAdditionIndex(value);
Insert(index, value);
return index;
}
public new int IndexOf(T value)
{
return BinarySearch(value, Comparer);
}
/// <summary>
/// Gets the first index of the element larger than value.
/// </summary>
/// <param name="value">The value to search for.</param>
/// <returns>The index of the first element larger than value.</returns>
private int getAdditionIndex(T value)
{
int index = BinarySearch(value, Comparer);
if (index < 0)
index = ~index;
// Binary search is not guaranteed to give the last index
// when duplicates are involved, so let's move towards it
for (; index < Count; index++)
{
if (Comparer.Compare(this[index], value) != 0)
break;
}
return index;
}
}
}
| mit | C# |
7459b8938e79937db59667be265c41b7f159da3e | Make LocalisableString a struct | peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework | osu.Framework/Localisation/LocalisableString.cs | osu.Framework/Localisation/LocalisableString.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using JetBrains.Annotations;
using osu.Framework.Configuration;
namespace osu.Framework.Localisation
{
/// <summary>
/// A class representing text that can be localised and formatted.
/// </summary>
public struct LocalisableString : IEquatable<LocalisableString>
{
/// <summary>
/// The text to be used for localisation and/or formatting.
/// </summary>
public Bindable<string> Text { get; }
/// <summary>
/// Whether <see cref="Text"/> should be localised.
/// </summary>
public Bindable<bool> Localised { get; }
/// <summary>
/// The arguments to format <see cref="Text"/> with.
/// </summary>
public Bindable<object[]> Args { get; }
/// <summary>
/// Creates a new <see cref="LocalisableString"/>.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="localised">Whether the text should be localised.</param>
/// <param name="args">The arguments to format the text with.</param>
public LocalisableString(string text, bool localised = true, params object[] args)
{
Text = new Bindable<string>(text ?? string.Empty);
Localised = new Bindable<bool>(localised);
Args = new Bindable<object[]>(args);
}
/// <summary>
/// Creates a new <see cref="LocalisableString"/>. This localises by default.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="args">The arguments to format the text with.</param>
public LocalisableString(string text, params object[] args)
: this(text, true, args)
{
}
{
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using JetBrains.Annotations;
using osu.Framework.Configuration;
namespace osu.Framework.Localisation
{
/// <summary>
/// A class representing text that can be localised and formatted.
/// </summary>
public class LocalisableString
{
/// <summary>
/// The text to be used for localisation and/or formatting.
/// </summary>
public Bindable<string> Text { get; } = new Bindable<string>();
/// <summary>
/// Whether <see cref="Text"/> should be localised.
/// </summary>
public Bindable<bool> Localised { get; } = new Bindable<bool>();
/// <summary>
/// The arguments to format <see cref="Text"/> with.
/// </summary>
public Bindable<object[]> Args { get; } = new Bindable<object[]>();
/// <summary>
/// Creates a new <see cref="LocalisableString"/>. This localises by default.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="args">The arguments to format the text with.</param>
public LocalisableString([NotNull] string text, params object[] args)
{
Text.Value = text;
Localised.Value = true;
Args.Value = args;
}
/// <summary>
/// Creates a new <see cref="LocalisableString"/>.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="localised">Whether the text should be localised.</param>
/// <param name="args">The arguments to format the text with.</param>
public LocalisableString([NotNull] string text, bool localised = true, params object[] args)
{
Text.Value = text;
Localised.Value = localised;
Args.Value = args;
}
}
}
| mit | C# |
f9c369b23cff9b0bdc1b8b7907ed74d8919bf123 | Fix toolbar music button tooltip overflowing off-screen | ppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu | osu.Game/Overlays/Toolbar/ToolbarMusicButton.cs | osu.Game/Overlays/Toolbar/ToolbarMusicButton.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.Framework.Graphics.Sprites;
using osu.Game.Input.Bindings;
namespace osu.Game.Overlays.Toolbar
{
public class ToolbarMusicButton : ToolbarOverlayToggleButton
{
protected override Anchor TooltipAnchor => Anchor.TopRight;
public ToolbarMusicButton()
{
Icon = FontAwesome.Solid.Music;
TooltipMain = "Now playing";
TooltipSub = "Manage the currently playing track";
Hotkey = GlobalAction.ToggleNowPlaying;
}
[BackgroundDependencyLoader(true)]
private void load(NowPlayingOverlay music)
{
StateContainer = music;
}
}
}
| // 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.Sprites;
using osu.Game.Input.Bindings;
namespace osu.Game.Overlays.Toolbar
{
public class ToolbarMusicButton : ToolbarOverlayToggleButton
{
public ToolbarMusicButton()
{
Icon = FontAwesome.Solid.Music;
TooltipMain = "Now playing";
TooltipSub = "Manage the currently playing track";
Hotkey = GlobalAction.ToggleNowPlaying;
}
[BackgroundDependencyLoader(true)]
private void load(NowPlayingOverlay music)
{
StateContainer = music;
}
}
}
| mit | C# |
cb2e7cd7a7b727ea06335de655004b9ea4c74688 | Handle callback directly if resolve bundle is empty | Miruken-DotNet/Miruken | Source/Miruken/Callback/Resolving.cs | Source/Miruken/Callback/Resolving.cs | namespace Miruken.Callback
{
using System;
public class Resolving : Inquiry, IResolveCallback
{
private bool _handled;
public Resolving(object key, object callback)
: base(key, true)
{
if (callback == null)
throw new ArgumentNullException(nameof(callback));
Callback = callback;
}
public object Callback { get; }
object IResolveCallback.GetResolveCallback()
{
return this;
}
protected override bool IsSatisfied(
object resolution, bool greedy, IHandler composer)
{
if (_handled && !greedy) return true;
return _handled = Handler.Dispatch(
resolution, Callback, ref greedy, composer)
|| _handled;
}
public static object GetDefaultResolvingCallback(object callback)
{
var dispatch = callback as IDispatchCallback;
var policy = dispatch?.Policy ?? HandlesAttribute.Policy;
var handlers = policy.GetHandlers(callback);
var bundle = new Bundle(false);
foreach (var handler in handlers)
bundle.Add(h => h.Handle(new Resolving(handler, callback)));
if (bundle.IsEmpty)
bundle.Add(h => h.Handle(callback));
return bundle;
}
}
}
| namespace Miruken.Callback
{
using System;
public class Resolving : Inquiry, IResolveCallback
{
private bool _handled;
public Resolving(object key, object callback)
: base(key, true)
{
if (callback == null)
throw new ArgumentNullException(nameof(callback));
Callback = callback;
}
public object Callback { get; }
object IResolveCallback.GetResolveCallback()
{
return this;
}
protected override bool IsSatisfied(
object resolution, bool greedy, IHandler composer)
{
if (_handled && !greedy) return true;
return _handled =
Handler.Dispatch(resolution, Callback, ref greedy, composer)
|| _handled;
}
public static object GetDefaultResolvingCallback(object callback)
{
var dispatch = callback as IDispatchCallback;
var policy = dispatch?.Policy ?? HandlesAttribute.Policy;
var handlers = policy.GetHandlers(callback);
var bundle = new Bundle(false);
foreach (var handler in handlers)
bundle.Add(h => h.Handle(new Resolving(handler, callback)));
bundle.Add(h => h.Handle(callback));
return bundle;
}
}
}
| mit | C# |
60a38436c14938abd39b4b00e790f3b2f1ae7b6c | Disable lifetime validation on JWTs. | PietroProperties/holms.platformclient.net | csharp/HOLMS.Platform/HOLMS.Platform/Support/Security/ValidatedJWToken.cs | csharp/HOLMS.Platform/HOLMS.Platform/Support/Security/ValidatedJWToken.cs | using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security;
using HOLMS.Types.IAM;
using Microsoft.IdentityModel.Tokens;
namespace HOLMS.Support.Security {
public class ValidatedJWToken {
public string RawTokenData { get; protected set; }
public AuthenticatedClientClaims ACC { get; protected set; }
protected ValidatedJWToken() { }
private ValidatedJWToken(JwtSecurityToken t) {
RawTokenData = t.RawData;
var claims = t.Claims.ToDictionary(x => x.Type);
if (!claims.ContainsKey(JWToken.ClientIdKey) || !claims.ContainsKey(JWToken.TenancyIdKey) ||
!claims.ContainsKey(JWToken.UserIdKey)) {
throw new Exception("Missing keys in token");
}
ACC = new AuthenticatedClientClaims {
Client = new ClientInstanceIndicator(Guid.Parse(claims[JWToken.ClientIdKey].Value)),
Tenancy = new TenancyIndicator(Guid.Parse(claims[JWToken.TenancyIdKey].Value)),
User = new StaffMemberIndicator(Guid.Parse(claims[JWToken.UserIdKey].Value)),
};
}
public static ValidatedJWToken CreateWithValidation(string rawData, SecurityKey key) {
var tokenValidationParameters = new TokenValidationParameters() {
ValidAudiences = new [] { JWToken.Audience },
ValidIssuers = new [] { JWToken.Issuer },
IssuerSigningKey = key,
ValidateLifetime = false,
};
var tokenHandler = new JwtSecurityTokenHandler();
SecurityToken validatedToken;
tokenHandler.ValidateToken(rawData, tokenValidationParameters, out validatedToken);
var tok = tokenHandler.ReadToken(rawData) as JwtSecurityToken;
var expirationClaim = tok.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Exp);
if (expirationClaim != null) {
if (tok.ValidTo < DateTime.Now) {
throw new SecurityException("Presented token is expired");
}
}
return new ValidatedJWToken(tok);
}
}
}
| using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security;
using HOLMS.Types.IAM;
using Microsoft.IdentityModel.Tokens;
namespace HOLMS.Support.Security {
public class ValidatedJWToken {
public string RawTokenData { get; protected set; }
public AuthenticatedClientClaims ACC { get; protected set; }
protected ValidatedJWToken() { }
private ValidatedJWToken(JwtSecurityToken t) {
RawTokenData = t.RawData;
var claims = t.Claims.ToDictionary(x => x.Type);
if (!claims.ContainsKey(JWToken.ClientIdKey) || !claims.ContainsKey(JWToken.TenancyIdKey) ||
!claims.ContainsKey(JWToken.UserIdKey)) {
throw new Exception("Missing keys in token");
}
ACC = new AuthenticatedClientClaims {
Client = new ClientInstanceIndicator(Guid.Parse(claims[JWToken.ClientIdKey].Value)),
Tenancy = new TenancyIndicator(Guid.Parse(claims[JWToken.TenancyIdKey].Value)),
User = new StaffMemberIndicator(Guid.Parse(claims[JWToken.UserIdKey].Value)),
};
}
public static ValidatedJWToken CreateWithValidation(string rawData, SecurityKey key) {
var tokenValidationParameters = new TokenValidationParameters() {
ValidAudiences = new [] { JWToken.Audience },
ValidIssuers = new [] { JWToken.Issuer },
IssuerSigningKey = key,
};
var tokenHandler = new JwtSecurityTokenHandler();
SecurityToken validatedToken;
tokenHandler.ValidateToken(rawData, tokenValidationParameters, out validatedToken);
var tok = tokenHandler.ReadToken(rawData) as JwtSecurityToken;
var expirationClaim = tok.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Exp);
if (expirationClaim != null) {
if (tok.ValidTo < DateTime.Now) {
throw new SecurityException("Presented token is expired");
}
}
return new ValidatedJWToken(tok);
}
}
}
| mit | C# |
66d40e9aa0f438eab531a8542a7efed3a759f5a8 | remove using UnityEditor | mattak/Unidux | Assets/Unidux/UniduxSubscribeComponent.cs | Assets/Unidux/UniduxSubscribeComponent.cs | using UnityEngine;
namespace Unidux
{
public static class MonoBehaviourExt
{
public static void AddTo<T>(
this GameObject gameObject,
Store<T> store,
Render<T> render)
where T : StateBase, new()
{
GetOrAddUniduxSubscriber<UniduxSubscriber>(gameObject).AddRenderTo(store, render);
}
public static void AddTo<T, A>(
this GameObject gameObject,
Store<T> store,
Reducer<T, A> reducer)
where T : StateBase, new()
{
GetOrAddUniduxSubscriber<UniduxSubscriber>(gameObject).AddReducerTo(store, reducer);
}
public static void AddSustainTo<T>(
this GameObject gameObject,
Store<T> store,
Render<T> render)
where T : StateBase, new()
{
GetOrAddUniduxSubscriber<UniduxSustainSubscriber>(gameObject).AddRenderTo(store, render);
}
public static void AddSustainTo<T, A>(
this GameObject gameObject,
Store<T> store,
Reducer<T, A> reducer)
where T : StateBase, new()
{
GetOrAddUniduxSubscriber<UniduxSustainSubscriber>(gameObject).AddReducerTo(store, reducer);
}
private static T GetOrAddUniduxSubscriber<T>(GameObject gameObject) where T : UniduxSubscriberBase
{
var component = gameObject.GetComponent<T>();
if (component == null)
{
gameObject.AddComponent<T>();
component = gameObject.GetComponent<T>();
}
return component;
}
}
}
| using UnityEditor;
using UnityEngine;
namespace Unidux
{
public static class MonoBehaviourExt
{
public static void AddTo<T>(
this GameObject gameObject,
Store<T> store,
Render<T> render)
where T : StateBase, new()
{
GetOrAddUniduxSubscriber<UniduxSubscriber>(gameObject).AddRenderTo(store, render);
}
public static void AddTo<T, A>(
this GameObject gameObject,
Store<T> store,
Reducer<T, A> reducer)
where T : StateBase, new()
{
GetOrAddUniduxSubscriber<UniduxSubscriber>(gameObject).AddReducerTo(store, reducer);
}
public static void AddSustainTo<T>(
this GameObject gameObject,
Store<T> store,
Render<T> render)
where T : StateBase, new()
{
GetOrAddUniduxSubscriber<UniduxSustainSubscriber>(gameObject).AddRenderTo(store, render);
}
public static void AddSustainTo<T, A>(
this GameObject gameObject,
Store<T> store,
Reducer<T, A> reducer)
where T : StateBase, new()
{
GetOrAddUniduxSubscriber<UniduxSustainSubscriber>(gameObject).AddReducerTo(store, reducer);
}
private static T GetOrAddUniduxSubscriber<T>(GameObject gameObject) where T : UniduxSubscriberBase
{
var component = gameObject.GetComponent<T>();
if (component == null)
{
gameObject.AddComponent<T>();
component = gameObject.GetComponent<T>();
}
return component;
}
}
}
| mit | C# |
8cd22c83fe72545dbca476e2d6d127ff445bb14b | Improve dictionary merge | vbliznikov/colabedit,vbliznikov/colabedit,vbliznikov/colabedit,vbliznikov/colabedit | src/vcs-lib/VersionControl/Operations/DictionaryMergeHandler.cs | src/vcs-lib/VersionControl/Operations/DictionaryMergeHandler.cs | using System;
using System.Linq;
using System.Collections.Generic;
namespace CollabEdit.VersionControl.Operations
{
public class DictionaryMergeHandler<TKey, TValue> : IMergeHandler<IDictionary<TKey, TValue>>
{
public IDictionary<TKey, TValue> Merge(IDictionary<TKey, TValue> origin, IDictionary<TKey, TValue> left,
IDictionary<TKey, TValue> right, ConflictResolutionOptions options)
{
// Empty dictionaries left and right
if (left.Count == 0 && right.Count == 0)
return left;
var mergedDictionary = new Dictionary<TKey, TValue>();
var lEditScript = KeysEditScript<TKey>.From(origin.Keys, left.Keys);
var rEditScript = KeysEditScript<TKey>.From(origin.Keys, right.Keys);
var resultScript = lEditScript.Merge(rEditScript);
// Chack that the key was changed either left or right, otherwise apply ConflictResolutinOptions
foreach (TKey key in resultScript.CommonKeys)
{
var originValue = origin[key];
var leftValue = left[key];
var rightValue = right[key];
var mergedValue = MergeUtils.Merge<TValue>(originValue, leftValue, rightValue, options);
mergedDictionary.Add(key, mergedValue);
}
var commonInsertedKeys = lEditScript.InsertedKeys.Intersect(rEditScript.InsertedKeys);
// Check that the same values was inserted, otherwise apply ConflictResolutionOptions
foreach (TKey key in commonInsertedKeys)
{
var leftValue = left[key];
var rightValue = right[key];
var mergedValue = MergeUtils.Merge<TValue>(leftValue, rightValue, options);
mergedDictionary.Add(key, mergedValue);
}
var delConflictLeft = rEditScript.DeletedKeys.Intersect(lEditScript.CommonKeys)
.Where(key => !EqualityComparer<TKey>.Equals(origin[key], left[key]));
var delConflictRight = lEditScript.DeletedKeys.Intersect(rEditScript.CommonKeys)
.Where(key => !EqualityComparer<TKey>.Equals(origin[key], right[key]));
switch (options)
{
case ConflictResolutionOptions.TakeRight:
foreach (var key in delConflictRight)
mergedDictionary.Add(key, right[key]);
break;
case ConflictResolutionOptions.TakeLeft:
foreach (var key in delConflictLeft)
mergedDictionary.Add(key, left[key]);
break;
default:
throw new MergeOperationException(string.Format("The key[{0}] was deleted at right but was changed at left.", key));
}
return mergedDictionary;
}
}
} | using System;
using System.Linq;
using System.Collections.Generic;
namespace CollabEdit.VersionControl.Operations
{
public class DictionaryMergeHandler<TKey, TValue> : IMergeHandler<IDictionary<TKey, TValue>>
{
public IDictionary<TKey, TValue> Merge(IDictionary<TKey, TValue> origin, IDictionary<TKey, TValue> left, IDictionary<TKey, TValue> right)
{
// Empty dictionaries left and right
if (left.Count == 0 && right.Count == 0)
return left;
var mergedDictionary = new Dictionary<TKey, TValue>();
var lEditScript = KeysEditScript<TKey>.From(origin.Keys, left.Keys);
var rEditScript = KeysEditScript<TKey>.From(origin.Keys, right.Keys);
var resultScript = lEditScript.Merge(rEditScript);
foreach (TKey key in resultScript.CommonKeys)
{
var originValue = origin[key];
var leftValue = left[key];
var rightValue = right[key];
var mergedValue = MergeUtils.Merge<TValue>(originValue, leftValue, rightValue);
mergedDictionary.Add(key, mergedValue);
}
foreach (TKey key in resultScript.InsertedKeys)
{
var leftValue = left[key];
var rightValue = right[key];
var mergedValue = MergeUtils.Merge<TValue>(leftValue, rightValue);
mergedDictionary.Add(key, mergedValue);
}
return mergedDictionary;
}
}
} | mit | C# |
656374914bf23d61b78aa6d62c26ca98bc42a37c | Fix try one | MrLeebo/unitystation,Necromunger/unitystation,fomalsd/unitystation,MrLeebo/unitystation,MrLeebo/unitystation,fomalsd/unitystation,Lancemaker/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,MrLeebo/unitystation,Lancemaker/unitystation,MrLeebo/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,krille90/unitystation,Necromunger/unitystation,Necromunger/unitystation,MrLeebo/unitystation | UnityProject/Assets/Scripts/Editor/Objects/ObjectBehaviourEditor.cs | UnityProject/Assets/Scripts/Editor/Objects/ObjectBehaviourEditor.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(ObjectBehaviour))]
public class ObjectBehaviourEditor : Editor
{
public override void OnInspectorGUI()
{
ObjectBehaviour oTarget = (ObjectBehaviour)target;
serializedObject.Update();
var isPushable = serializedObject.FindProperty("isPushable");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(isPushable, true);
if (EditorGUI.EndChangeCheck())
serializedObject.ApplyModifiedProperties();
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(ObjectBehaviour))]
public class ObjectBehaviourEditor : Editor
{
public override void OnInspectorGUI()
{
ObjectBehaviour oTarget = (ObjectBehaviour)target;
serializedObject.Update();
SerializedProperty isPushable = serializedObject.FindProperty("isPushable");
EditorGUILayout.PropertyField(isPushable);
}
}
| agpl-3.0 | C# |
c3cb7083b92dde7c63427dc9f71b53dd0e7c2a80 | implement 10 object search clicked just in case | GROWrepo/Santa_Inc | Assets/script/monoBehavior/GameManager.cs | Assets/script/monoBehavior/GameManager.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
STATUS_GAME SG;
public GameObject selectedObject;
dialog current;
Ray2D clickRay;
//RaycastHit2D hit;
RaycastHit2D[] hits;
public ContactFilter2D filter;
// Use this for initialization
void Start () {
SG = STATUS_GAME.MENU;
current = null;
hits = new RaycastHit2D[10];
filter = new ContactFilter2D();
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
clickRay = new Ray2D(Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)), Vector2.zero);
Physics2D.Raycast(clickRay.origin, clickRay.direction, filter, hits);
/*hit = Physics2D.Raycast(clickRay.origin, clickRay.direction, filter, hits);
if (hit.collider != null)
{
//Debug.Log(hit.transform.gameObject);
//selectedObject = hits[0].transform.gameObject;
}*/
if(hits[0].collider != null)
{
Debug.Log(hits[0].transform.gameObject);
selectedObject = hits[0].transform.gameObject;
}
}
}
private void OnGUI()
{
}
private void setCurrent(dialog dialogs)
{
this.current = dialogs;
}
public STATUS_GAME getSG()
{
return this.SG;
}
void getHitObject(RaycastHit hit)
{
//this.hit = hit;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
STATUS_GAME SG;
public GameObject selectedObject;
dialog current;
Ray2D clickRay;
RaycastHit2D hit;
// Use this for initialization
void Start () {
SG = STATUS_GAME.MENU;
current = null;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
clickRay = new Ray2D(Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)), Vector2.zero);
hit = Physics2D.Raycast(clickRay.origin, clickRay.direction);
if(hit.collider != null)
{
Debug.Log(hit.transform.gameObject);
}
}
}
private void OnGUI()
{
}
private void setCurrent(dialog dialogs)
{
this.current = dialogs;
}
public STATUS_GAME getSG()
{
return this.SG;
}
void getHitObject(RaycastHit hit)
{
//this.hit = hit;
}
}
| mit | C# |
3a4f77af5952a4a47b422ba6705662dc0b2ebaa1 | Add the news letter subscription webhook filters | SevenSpikes/api-plugin-for-nopcommerce,SevenSpikes/api-plugin-for-nopcommerce | Nop.Plugin.Api/WebHooks/FilterProvider.cs | Nop.Plugin.Api/WebHooks/FilterProvider.cs | using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Nop.Plugin.Api.Constants;
namespace Nop.Plugin.Api.WebHooks
{
using Microsoft.AspNet.WebHooks;
public class FilterProvider : IWebHookFilterProvider
{
private readonly Collection<WebHookFilter> filters = new Collection<WebHookFilter>
{
new WebHookFilter { Name = WebHookNames.CustomersCreate, Description = "A customer has been registered."},
new WebHookFilter { Name = WebHookNames.CustomersUpdate, Description = "A customer has been updated."},
new WebHookFilter { Name = WebHookNames.CustomersDelete, Description = "A customer has been deleted."},
new WebHookFilter { Name = WebHookNames.ProductsCreate, Description = "A product has been created."},
new WebHookFilter { Name = WebHookNames.ProductsUpdate, Description = "A product has been updated."},
new WebHookFilter { Name = WebHookNames.ProductsDelete, Description = "A product has been deleted."},
new WebHookFilter { Name = WebHookNames.ProductsUnmap, Description = "A product has been unmapped from the store."},
new WebHookFilter { Name = WebHookNames.CategoriesCreate, Description = "A category has been created."},
new WebHookFilter { Name = WebHookNames.CategoriesUpdate, Description = "A category has been updated."},
new WebHookFilter { Name = WebHookNames.CategoriesDelete, Description = "A category has been deleted."},
new WebHookFilter { Name = WebHookNames.CategoriesUnmap, Description = "A category has been unmapped from the store."},
new WebHookFilter { Name = WebHookNames.OrdersCreate, Description = "An order has been created."},
new WebHookFilter { Name = WebHookNames.OrdersUpdate, Description = "An order has been updated."},
new WebHookFilter { Name = WebHookNames.OrdersDelete, Description = "An order has been deleted."},
new WebHookFilter { Name = WebHookNames.ProductCategoryMapsCreate, Description = "A product category map has been created."},
new WebHookFilter { Name = WebHookNames.ProductCategoryMapsUpdate, Description = "A product category map has been updated."},
new WebHookFilter { Name = WebHookNames.ProductCategoryMapsDelete, Description = "A product category map has been deleted."},
new WebHookFilter { Name = WebHookNames.StoresUpdate, Description = "A store has been updated."},
new WebHookFilter { Name = WebHookNames.LanguagesCreate, Description = "A language has been created."},
new WebHookFilter { Name = WebHookNames.LanguagesUpdate, Description = "A language has been updated."},
new WebHookFilter { Name = WebHookNames.LanguagesDelete, Description = "A language has been deleted."},
new WebHookFilter { Name = WebHookNames.NewsLetterSubscriptionCreate, Description = "A news letter subscription has been created."},
new WebHookFilter { Name = WebHookNames.NewsLetterSubscriptionUpdate, Description = "A news letter subscription has been updated."},
new WebHookFilter { Name = WebHookNames.NewsLetterSubscriptionDelete, Description = "A news letter subscription has been deleted."}
};
public Task<Collection<WebHookFilter>> GetFiltersAsync()
{
return Task.FromResult(this.filters);
}
}
}
| using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Nop.Plugin.Api.Constants;
namespace Nop.Plugin.Api.WebHooks
{
using Microsoft.AspNet.WebHooks;
public class FilterProvider : IWebHookFilterProvider
{
private readonly Collection<WebHookFilter> filters = new Collection<WebHookFilter>
{
new WebHookFilter { Name = WebHookNames.CustomersCreate, Description = "A customer has been registered."},
new WebHookFilter { Name = WebHookNames.CustomersUpdate, Description = "A customer has been updated."},
new WebHookFilter { Name = WebHookNames.CustomersDelete, Description = "A customer has been deleted."},
new WebHookFilter { Name = WebHookNames.ProductsCreate, Description = "A product has been created."},
new WebHookFilter { Name = WebHookNames.ProductsUpdate, Description = "A product has been updated."},
new WebHookFilter { Name = WebHookNames.ProductsDelete, Description = "A product has been deleted."},
new WebHookFilter { Name = WebHookNames.ProductsUnmap, Description = "A product has been unmapped from the store."},
new WebHookFilter { Name = WebHookNames.CategoriesCreate, Description = "A category has been created."},
new WebHookFilter { Name = WebHookNames.CategoriesUpdate, Description = "A category has been updated."},
new WebHookFilter { Name = WebHookNames.CategoriesDelete, Description = "A category has been deleted."},
new WebHookFilter { Name = WebHookNames.CategoriesUnmap, Description = "A category has been unmapped from the store."},
new WebHookFilter { Name = WebHookNames.OrdersCreate, Description = "An order has been created."},
new WebHookFilter { Name = WebHookNames.OrdersUpdate, Description = "An order has been updated."},
new WebHookFilter { Name = WebHookNames.OrdersDelete, Description = "An order has been deleted."},
new WebHookFilter { Name = WebHookNames.ProductCategoryMapsCreate, Description = "A product category map has been created."},
new WebHookFilter { Name = WebHookNames.ProductCategoryMapsUpdate, Description = "A product category map has been updated."},
new WebHookFilter { Name = WebHookNames.ProductCategoryMapsDelete, Description = "A product category map has been deleted."},
new WebHookFilter { Name = WebHookNames.StoresUpdate, Description = "A store has been updated."},
new WebHookFilter { Name = WebHookNames.LanguagesCreate, Description = "A language has been created."},
new WebHookFilter { Name = WebHookNames.LanguagesUpdate, Description = "A language has been updated."},
new WebHookFilter { Name = WebHookNames.LanguagesDelete, Description = "A language has been deleted."}
};
public Task<Collection<WebHookFilter>> GetFiltersAsync()
{
return Task.FromResult(this.filters);
}
}
}
| mit | C# |
278fc6f51918c222ea2380ef0e2dde2d434c4fd7 | Remove enum underlying type declaration | mstrother/BmpListener | BmpListener/Bmp/Bmp.cs | BmpListener/Bmp/Bmp.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BmpListener.Bmp
{
public enum MessageType
{
RouteMonitoring,
StatisticsReport,
PeerDown,
PeerUp,
Initiation,
Termination,
RouteMirroring
}
public enum PeerType
{
Global,
RD,
Local
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BmpListener.Bmp
{
public enum MessageType : byte
{
RouteMonitoring,
StatisticsReport,
PeerDown,
PeerUp,
Initiation,
Termination,
RouteMirroring
}
public enum PeerType : byte
{
Global,
RD,
Local
}
}
| mit | C# |
c8471cc619dff42ac28329719861e78b16151c75 | set no wrap for ExpressEntry date | annaked/ExpressEntryCalculator,annaked/ExpressEntryCalculator,annaked/ExpressEntryCalculator | ExpressEntryCalculator.Web/Views/Shared/ExpressEntryStats.cshtml | ExpressEntryCalculator.Web/Views/Shared/ExpressEntryStats.cshtml | @using Microsoft.Extensions.Options
@inject IOptions<ExpressEntryStats> expressEntryStatsAccessor
@{
var expressEntryStats = expressEntryStatsAccessor.Value;
}
<div class="alert alert-info" role="alert">
Last round of invitations to apply for permanent residence under the Express Entry was on <strong style="white-space: nowrap">@expressEntryStats.RoundDate.ToShortDateString()</strong>.
The lowest score to be invited was <strong>@expressEntryStats.LowestScore</strong>.
<a href="https://www.canada.ca/en/immigration-refugees-citizenship/services/immigrate-canada/express-entry/become-candidate/rounds-invitations.html" target="_blank" style="text-decoration:underline">Click here for more information</a>.
</div> | @using Microsoft.Extensions.Options
@inject IOptions<ExpressEntryStats> expressEntryStatsAccessor
@{
var expressEntryStats = expressEntryStatsAccessor.Value;
}
<div class="alert alert-info" role="alert">
Last round of invitations to apply for permanent residence under the Express Entry was on <strong>@expressEntryStats.RoundDate.ToShortDateString()</strong>.
The lowest score to be invited was <strong>@expressEntryStats.LowestScore</strong>.
<a href="https://www.canada.ca/en/immigration-refugees-citizenship/services/immigrate-canada/express-entry/become-candidate/rounds-invitations.html" target="_blank" style="text-decoration:underline">Click here for more information</a>.
</div> | mit | C# |
4f76b870e2bac88560159511c8b1335e9c774d70 | Use readonly on fields that should not be modified | VirusFree/SharpDX,manu-silicon/SharpDX,VirusFree/SharpDX,andrewst/SharpDX,sharpdx/SharpDX,shoelzer/SharpDX,fmarrabal/SharpDX,andrewst/SharpDX,PavelBrokhman/SharpDX,wyrover/SharpDX,mrvux/SharpDX,RobyDX/SharpDX,shoelzer/SharpDX,davidlee80/SharpDX-1,Ixonos-USA/SharpDX,shoelzer/SharpDX,Ixonos-USA/SharpDX,fmarrabal/SharpDX,shoelzer/SharpDX,dazerdude/SharpDX,PavelBrokhman/SharpDX,TechPriest/SharpDX,manu-silicon/SharpDX,weltkante/SharpDX,davidlee80/SharpDX-1,dazerdude/SharpDX,TechPriest/SharpDX,VirusFree/SharpDX,RobyDX/SharpDX,weltkante/SharpDX,weltkante/SharpDX,VirusFree/SharpDX,TigerKO/SharpDX,waltdestler/SharpDX,Ixonos-USA/SharpDX,dazerdude/SharpDX,PavelBrokhman/SharpDX,davidlee80/SharpDX-1,TechPriest/SharpDX,wyrover/SharpDX,mrvux/SharpDX,TigerKO/SharpDX,wyrover/SharpDX,manu-silicon/SharpDX,jwollen/SharpDX,wyrover/SharpDX,RobyDX/SharpDX,TigerKO/SharpDX,dazerdude/SharpDX,mrvux/SharpDX,manu-silicon/SharpDX,PavelBrokhman/SharpDX,jwollen/SharpDX,RobyDX/SharpDX,sharpdx/SharpDX,sharpdx/SharpDX,TigerKO/SharpDX,Ixonos-USA/SharpDX,shoelzer/SharpDX,waltdestler/SharpDX,waltdestler/SharpDX,TechPriest/SharpDX,fmarrabal/SharpDX,jwollen/SharpDX,davidlee80/SharpDX-1,jwollen/SharpDX,fmarrabal/SharpDX,weltkante/SharpDX,waltdestler/SharpDX,andrewst/SharpDX | Source/Toolkit/SharpDX.Toolkit.Graphics/InputSignatureManager.cs | Source/Toolkit/SharpDX.Toolkit.Graphics/InputSignatureManager.cs | // Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.Collections.Generic;
using SharpDX.Direct3D11;
namespace SharpDX.Toolkit.Graphics
{
internal struct InputLayoutPair
{
public InputLayoutPair(VertexInputLayout vertexInputLayout, InputLayout inputLayout)
{
VertexInputLayout = vertexInputLayout;
InputLayout = inputLayout;
}
public readonly VertexInputLayout VertexInputLayout;
public readonly InputLayout InputLayout;
}
internal class InputSignatureManager : Component
{
private readonly Direct3D11.Device device;
public readonly byte[] Bytecode;
private readonly Dictionary<VertexInputLayout, InputLayoutPair> Cache;
public InputSignatureManager(GraphicsDevice device, byte[] byteCode)
{
this.device = device;
Bytecode = byteCode;
Cache = new Dictionary<VertexInputLayout, InputLayoutPair>();
}
public void GetOrCreate(VertexInputLayout layout, out InputLayoutPair currentPassPreviousPair)
{
lock (Cache)
{
if (!Cache.TryGetValue(layout, out currentPassPreviousPair))
{
currentPassPreviousPair = new InputLayoutPair(layout, ToDispose(new InputLayout(device, Bytecode, layout.InputElements)));
Cache.Add(layout, currentPassPreviousPair);
}
}
}
}
} | // Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.Collections.Generic;
using SharpDX.Direct3D11;
namespace SharpDX.Toolkit.Graphics
{
internal struct InputLayoutPair
{
public VertexInputLayout VertexInputLayout;
public InputLayout InputLayout;
}
internal class InputSignatureManager : Component
{
private readonly Direct3D11.Device device;
public readonly byte[] Bytecode;
private readonly Dictionary<VertexInputLayout, InputLayoutPair> Cache;
public InputSignatureManager(GraphicsDevice device, byte[] byteCode)
{
this.device = device;
Bytecode = byteCode;
Cache = new Dictionary<VertexInputLayout, InputLayoutPair>();
}
public void GetOrCreate(VertexInputLayout layout, out InputLayoutPair currentPassPreviousPair)
{
lock (Cache)
{
if (!Cache.TryGetValue(layout, out currentPassPreviousPair))
{
currentPassPreviousPair.InputLayout = ToDispose(new InputLayout(device, Bytecode, layout.InputElements));
currentPassPreviousPair.VertexInputLayout = layout;
Cache.Add(layout, currentPassPreviousPair);
}
}
}
}
} | mit | C# |
3dc18852edc8030090dd6eac1734a6fe3e02077c | hide object members on resetable metrics | huoxudong125/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,etishor/Metrics.NET,mnadel/Metrics.NET,Recognos/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,Recognos/Metrics.NET,ntent-ad/Metrics.NET,etishor/Metrics.NET,mnadel/Metrics.NET,huoxudong125/Metrics.NET,DeonHeyns/Metrics.NET,DeonHeyns/Metrics.NET,cvent/Metrics.NET,alhardy/Metrics.NET,alhardy/Metrics.NET,ntent-ad/Metrics.NET,Liwoj/Metrics.NET | Src/Metrics/ResetableMetric.cs | Src/Metrics/ResetableMetric.cs |
namespace Metrics
{
/// <summary>
/// Indicates a metric's ability to be reset. Reseting a metric clear all currently collected data.
/// </summary>
public interface ResetableMetric : Utils.IHideObjectMembers
{
/// <summary>
/// Clear all currently collected data for this metric.
/// </summary>
void Reset();
}
}
|
namespace Metrics
{
/// <summary>
/// Indicates a metric's ability to be reset. Reseting a metric clear all currently collected data.
/// </summary>
public interface ResetableMetric
{
/// <summary>
/// Clear all currently collected data for this metric.
/// </summary>
void Reset();
}
}
| apache-2.0 | C# |
eed6684cccf058becf49e0eca53fa31b99d074a5 | bump to 1.5 | greggman/DeJson.NET | DeJson/AssemblyInfo.cs | DeJson/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("DeJson")]
[assembly: AssemblyDescription("JSON serializer/deserializer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Greggman")]
[assembly: AssemblyProduct("DeJson")]
[assembly: AssemblyCopyright("Gregg Tavares")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.5.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("DeJson")]
[assembly: AssemblyDescription("JSON serializer/deserializer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Greggman")]
[assembly: AssemblyProduct("DeJson")]
[assembly: AssemblyCopyright("Gregg Tavares")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.4.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| bsd-3-clause | C# |
81b230320aab229039ac8a112a65f3096e03dfc5 | Improve warnings | Vanaheimr/Styx | Styx/Illias/Logging/Warning.cs | Styx/Illias/Logging/Warning.cs | /*
* Copyright (c) 2014 Achim Friedland <achim.friedland@graphdefined.com>
* This file is part of eMI3 WWCP <http://www.github.com/eMI3/WWCP-Bindings>
*
* Licensed under the Affero GPL license, Version 3.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.gnu.org/licenses/agpl.html
*
* 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.
*/
#region Usings
using System;
using System.Xml.Linq;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
#endregion
namespace org.GraphDefined.Vanaheimr.Illias
{
public static class WarningsExtentions
{
public static Boolean IsNeitherNullNorEmpty(this Warning Warning)
=> Warning != null && Warning.Text.IsNeitherNullNorEmpty();
public static IList<Warning> AddAndReturnList(this IList<Warning> Warnings,
I18NString Text)
=> Warnings?.AddAndReturnList(Warning.Create(Text));
}
public class Warning
{
public I18NString Text { get; }
public Object Context { get; }
private Warning(I18NString Text,
Object Context = null)
{
this.Text = Text;
this.Context = Context;
}
public JObject ToJSON()
=> JSONObject.Create(
new JProperty("text", Text. ToJSON()),
Context != null
? new JProperty("context", Context.ToString())
: null);
public static Warning Create(I18NString Text,
Object Warning = null)
=> new Warning(Text,
Warning);
public override String ToString()
=> Text.FirstText();
}
}
| /*
* Copyright (c) 2014 Achim Friedland <achim.friedland@graphdefined.com>
* This file is part of eMI3 WWCP <http://www.github.com/eMI3/WWCP-Bindings>
*
* Licensed under the Affero GPL license, Version 3.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.gnu.org/licenses/agpl.html
*
* 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.
*/
#region Usings
using System;
using System.Xml.Linq;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
#endregion
namespace org.GraphDefined.Vanaheimr.Illias
{
public static class WarningsExtentions
{
public static Boolean IsNotNullOrEmpty(this Warning Warning)
=> Warning != null && Warning.Text.IsNotNullOrEmpty();
public static IList<Warning> AddAndReturnList(this IList<Warning> Warnings,
String Text)
=> Warnings?.AddAndReturnList(Warning.Create(Text));
}
public class Warning
{
public String Text { get; }
public Object Context { get; }
private Warning(String Text,
Object Context = null)
{
this.Text = Text?.Trim();
this.Context = Context;
}
public static Warning Create(String Text,
Object Warning = null)
=> new Warning(Text,
Warning);
public override String ToString()
=> Text;
}
}
| apache-2.0 | C# |
a3ff75f8e145092c08282a5c283368d55eac30b5 | Update XMLAsset.cs | Cryru/SoulEngine | Emotion/IO/XMLAsset.cs | Emotion/IO/XMLAsset.cs | #region Using
using System;
using System.IO;
using System.Xml.Serialization;
using Emotion.Common;
using Emotion.Common.Threading;
using Emotion.Game.Animation;
using Emotion.Graphics.Shading;
using Emotion.Standard.Logging;
#endregion
namespace Emotion.IO
{
/// <summary>
/// A file in XML structure.
/// </summary>
/// <typeparam name="T">The class to deserialize to.</typeparam>
public class XMLAsset<T> : Asset
{
/// <summary>
/// The contents of the file.
/// </summary>
public T Content { get; protected set; }
/// <summary>
/// The serializer used for the file.
/// </summary>
public static XmlSerializer Serializer = new XmlSerializer(typeof(T));
protected override void CreateInternal(byte[] data)
{
try
{
// Deserialize the xml type.
using var stream = new MemoryStream(data);
Content = (T)Serializer.Deserialize(stream);
}
catch(Exception ex)
{
Engine.Log.Error(new Exception($"Couldn't parse XML asset of type {GetType()}!", ex));
}
}
protected override void DisposeInternal()
{
}
/// <summary>
/// Convert an object to an xml string.
/// Used in creating XMLAssets.
/// </summary>
/// <param name="obj">The obj to convert.</param>
/// <returns>The object as an xml string.</returns>
public static string FromObject(T obj)
{
using var stream = new MemoryStream ();
Serializer.Serialize(stream, obj);
return System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
}
} | #region Using
using System;
using System.IO;
using System.Xml.Serialization;
using Emotion.Common;
using Emotion.Common.Threading;
using Emotion.Game.Animation;
using Emotion.Graphics.Shading;
using Emotion.Standard.Logging;
#endregion
namespace Emotion.IO
{
/// <summary>
/// A file in XML structure.
/// </summary>
/// <typeparam name="T">The class to deserialize to.</typeparam>
public class XMLAsset<T> : Asset
{
/// <summary>
/// The contents of the file.
/// </summary>
public T Content { get; protected set; }
/// <summary>
/// The serializer used for the file.
/// </summary>
public static XmlSerializer Serializer = new XmlSerializer(typeof(T));
protected override void CreateInternal(byte[] data)
{
try
{
// Deserialize the xml type.
using var stream = new MemoryStream(data);
Content = (T)Serializer.Deserialize(stream);
}
catch(Exception ex)
{
Engine.Log.Error(new Exception($"Couldn't parse XML asset of type {GetType()}!", ex));
}
}
protected override void DisposeInternal()
{
}
/// <summary>
/// Convert an object to an xml string.
/// Used in creating XMLAssets.
/// </summary>
/// <param name="obj">The obj to convert.</param>
/// <returns>The object as an xml string.</returns>
public static string FromObject(T obj)
{
using var stream = new StringWriter ();
Serializer.Serialize(stream, obj);
return stream.ToString();
}
}
} | mit | C# |
e21deda407e80e76e1c93c874e0177908a786490 | Refactor ValueClearBehaviorAttributeTests | atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata | test/Atata.Tests/Bahaviors/ValueClear/ValueClearBehaviorAttributeTests.cs | test/Atata.Tests/Bahaviors/ValueClear/ValueClearBehaviorAttributeTests.cs | using System.Collections.Generic;
using NUnit.Framework;
namespace Atata.Tests.Bahaviors
{
public class ValueClearBehaviorAttributeTests : UITestFixture
{
private static IEnumerable<TestCaseData> Source =>
new[]
{
new TestCaseData(new ClearsValueUsingClearMethodAttribute()),
new TestCaseData(new ClearsValueUsingCtrlADeleteKeysAttribute()),
new TestCaseData(new ClearsValueUsingHomeShiftEndDeleteKeysAttribute()),
new TestCaseData(new ClearsValueUsingShiftHomeDeleteKeysAttribute()),
new TestCaseData(new ClearsValueUsingScriptAttribute()),
new TestCaseData(new ClearsValueUsingClearMethodOrScriptAttribute())
};
[TestCaseSource(nameof(Source))]
public void Execute(ValueClearBehaviorAttribute behavior)
{
var sut = Go.To<InputPage>().TextInput;
sut.Set("abc");
sut.Metadata.Push(behavior);
sut.Clear();
sut.Should.BeNull();
}
}
}
| using NUnit.Framework;
using NUnit.Framework.Internal;
namespace Atata.Tests.Bahaviors
{
[TestFixture(typeof(ClearsValueUsingClearMethodAttribute))]
[TestFixture(typeof(ClearsValueUsingCtrlADeleteKeysAttribute))]
[TestFixture(typeof(ClearsValueUsingHomeShiftEndDeleteKeysAttribute))]
[TestFixture(typeof(ClearsValueUsingShiftHomeDeleteKeysAttribute))]
[TestFixture(typeof(ClearsValueUsingScriptAttribute))]
[TestFixture(typeof(ClearsValueUsingClearMethodOrScriptAttribute))]
public class ValueClearBehaviorAttributeTests<TBehaviorAttribute> : UITestFixture
where TBehaviorAttribute : ValueClearBehaviorAttribute, new()
{
[Test]
public void Execute()
{
var sut = Go.To<InputPage>().TextInput;
sut.Set("abc");
sut.Metadata.Push(new[] { new TBehaviorAttribute() });
sut.Clear();
sut.Should.BeNull();
}
}
}
| apache-2.0 | C# |
31d5fe7680ccd4bf2f06631360256716037735c4 | Optimize field names | SICU-Stress-Measurement-System/frontend-cs | StressMeasurementSystem/Models/Patient.cs | StressMeasurementSystem/Models/Patient.cs | namespace StressMeasurementSystem.Models
{
public class Patient
{
#region Structs
struct Name
{
public string Prefix { get; set; }
public string First { get; set; }
public string Middle { get; set; }
public string Last { get; set; }
public string Suffix { get; set; }
}
struct Organization
{
public string Company { get; set; }
public string JobTitle { get; set; }
}
struct PhoneNumber
{
internal enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other}
public string Number { get; set; }
public Type T { get; set; }
}
#endregion
#region Fields
private Name _name;
private int _age;
private Organization _organization;
private PhoneNumber _phoneNumber;
#endregion
}
} | namespace StressMeasurementSystem.Models
{
public class Patient
{
#region Structs
struct Name
{
public string Prefix { get; set; }
public string First { get; set; }
public string Middle { get; set; }
public string Last { get; set; }
public string Suffix { get; set; }
}
struct Organization
{
public string Company { get; set; }
public string JobTitle { get; set; }
}
struct PhoneNumber
{
internal enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other}
public string Number { get; set; }
public Type T { get; set; }
}
#endregion
#region Fields
private Name _name;
private int _age;
private Organization _org;
private PhoneNumber _phone;
#endregion
}
} | apache-2.0 | C# |
0bdd63927f662bfd061bf52b2860393d9996d3ea | fix line endings | residuum/xwt,mminns/xwt,mminns/xwt,lytico/xwt,antmicro/xwt,akrisiun/xwt,iainx/xwt,hamekoz/xwt,steffenWi/xwt,sevoku/xwt,directhex/xwt,hwthomas/xwt,mono/xwt,TheBrainTech/xwt,cra0zy/xwt | Xwt.WPF/Xwt.WPFBackend/Util.cs | Xwt.WPF/Xwt.WPFBackend/Util.cs | // Util.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Windows;
using System.Windows.Media;
using System;
namespace Xwt.WPFBackend
{
public static class Util
{
public static Size GetPixelRatios (this Visual self)
{
var source = PresentationSource.FromVisual (self);
if (source == null)
return new Size (1, 1);
Matrix m = source.CompositionTarget.TransformToDevice;
return new Size (m.M11, m.M22);
}
public static double GetScaleFactor (this Visual self)
{
PresentationSource source = PresentationSource.FromVisual (self);
if (source == null)
return 1;
Matrix m = source.CompositionTarget.TransformToDevice;
return m.M11;
}
public static HorizontalAlignment ToWpfHorizontalAlignment(Alignment alignment)
{
switch (alignment) {
case Alignment.Start:
return HorizontalAlignment.Left;
case Alignment.Center:
return HorizontalAlignment.Center;
case Alignment.End:
return HorizontalAlignment.Right;
}
throw new InvalidOperationException("Invalid alignment value: " + alignment);
}
}
} | // Util.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Windows;
using System.Windows.Media;
using System;
namespace Xwt.WPFBackend
{
public static class Util
{
public static Size GetPixelRatios (this Visual self)
{
var source = PresentationSource.FromVisual (self);
if (source == null)
return new Size (1, 1);
Matrix m = source.CompositionTarget.TransformToDevice;
return new Size (m.M11, m.M22);
}
public static double GetScaleFactor (this Visual self)
{
PresentationSource source = PresentationSource.FromVisual (self);
if (source == null)
return 1;
Matrix m = source.CompositionTarget.TransformToDevice;
return m.M11;
}
public static HorizontalAlignment ToWpfHorizontalAlignment(Alignment alignment)
{
switch (alignment) {
case Alignment.Start:
return HorizontalAlignment.Left;
case Alignment.Center:
return HorizontalAlignment.Center;
case Alignment.End:
return HorizontalAlignment.Right;
}
throw new InvalidOperationException("Invalid alignment value: " + alignment);
}
}
} | mit | C# |
a16848393fe9ed31935714bc4db9dea90ff3ba20 | fix codefactor | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/Dialogs/EnterPasswordViewModel.cs | WalletWasabi.Fluent/ViewModels/Dialogs/EnterPasswordViewModel.cs | using ReactiveUI;
using System.Reactive.Linq;
using System.Windows.Input;
using WalletWasabi.Gui.Validation;
using WalletWasabi.Models;
using WalletWasabi.Userfacing;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
public class EnterPasswordViewModel : DialogViewModelBase<string?>
{
private string? _password;
private string? _confirmPassword;
public EnterPasswordViewModel(string subtitle = "Type your super-secret password in the blanks below and click Continue")
{
Subtitle = subtitle;
// This means pressing continue will make the password empty string.
// pressing cancel will return null.
_password = "";
this.ValidateProperty(x => x.Password, ValidatePassword);
this.ValidateProperty(x => x.ConfirmPassword, ValidateConfirmPassword);
var continueCommandCanExecute = this.WhenAnyValue(
x => x.Password,
x => x.ConfirmPassword,
(password, confirmPassword) =>
{
// This will fire validations before return canExecute value.
this.RaisePropertyChanged(nameof(Password));
this.RaisePropertyChanged(nameof(ConfirmPassword));
return (string.IsNullOrEmpty(password) && string.IsNullOrEmpty(confirmPassword)) || (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(confirmPassword) && !Validations.Any);
})
.ObserveOn(RxApp.MainThreadScheduler);
ContinueCommand = ReactiveCommand.Create(() => Close(Password), continueCommandCanExecute);
CancelCommand = ReactiveCommand.Create(() => Close());
}
public string? Password
{
get => _password;
set => this.RaiseAndSetIfChanged(ref _password, value);
}
public string? ConfirmPassword
{
get => _confirmPassword;
set => this.RaiseAndSetIfChanged(ref _confirmPassword, value);
}
public ICommand ContinueCommand { get; }
public ICommand CancelCommand { get; }
public string Subtitle { get; }
protected override void OnDialogClosed()
{
Password = "";
ConfirmPassword = "";
}
private void ValidateConfirmPassword(IValidationErrors errors)
{
if (!string.IsNullOrEmpty(ConfirmPassword) && Password != ConfirmPassword)
{
errors.Add(ErrorSeverity.Error, PasswordHelper.MatchingMessage);
}
}
private void ValidatePassword(IValidationErrors errors)
{
if (PasswordHelper.IsTrimable(Password, out _))
{
errors.Add(ErrorSeverity.Error, PasswordHelper.WhitespaceMessage);
}
if (PasswordHelper.IsTooLong(Password, out _))
{
errors.Add(ErrorSeverity.Error, PasswordHelper.PasswordTooLongMessage);
}
}
}
}
| using ReactiveUI;
using System.Reactive.Linq;
using System.Windows.Input;
using WalletWasabi.Gui.Validation;
using WalletWasabi.Models;
using WalletWasabi.Userfacing;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
public class EnterPasswordViewModel : DialogViewModelBase<string?>
{
private string? _password;
private string? _confirmPassword;
public EnterPasswordViewModel(string subtitle = "Type your super-secret password in the blanks below and click Continue")
{
Subtitle = subtitle;
// This means pressing continue will make the password empty string.
// pressing cancel will return null.
_password = "";
this.ValidateProperty(x => x.Password, ValidatePassword);
this.ValidateProperty(x => x.ConfirmPassword, ValidateConfirmPassword);
var continueCommandCanExecute = this.WhenAnyValue(
x => x.Password,
x => x.ConfirmPassword,
(password, confirmPassword) =>
{
// This will fire validations before return canExecute value.
this.RaisePropertyChanged(nameof(Password));
this.RaisePropertyChanged(nameof(ConfirmPassword));
return (string.IsNullOrEmpty(password) && string.IsNullOrEmpty(confirmPassword)) || (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(confirmPassword) && !Validations.Any);
})
.ObserveOn(RxApp.MainThreadScheduler);
ContinueCommand = ReactiveCommand.Create(() => Close(Password), continueCommandCanExecute);
CancelCommand = ReactiveCommand.Create(() => Close());
}
public string? Password
{
get => _password;
set => this.RaiseAndSetIfChanged(ref _password, value);
}
public string? ConfirmPassword
{
get => _confirmPassword;
set => this.RaiseAndSetIfChanged(ref _confirmPassword, value);
}
public ICommand ContinueCommand { get; }
public ICommand CancelCommand { get; }
public string Subtitle { get; }
protected override void OnDialogClosed()
{
Password = "";
ConfirmPassword = "";
}
private void ValidateConfirmPassword(IValidationErrors errors)
{
if (!string.IsNullOrEmpty(ConfirmPassword) && Password != ConfirmPassword)
{
errors.Add(ErrorSeverity.Error, PasswordHelper.MatchingMessage);
}
}
private void ValidatePassword(IValidationErrors errors)
{
if (PasswordHelper.IsTrimable(Password, out _))
{
errors.Add(ErrorSeverity.Error, PasswordHelper.WhitespaceMessage);
}
if (PasswordHelper.IsTooLong(Password, out _))
{
errors.Add(ErrorSeverity.Error, PasswordHelper.PasswordTooLongMessage);
}
}
}
}
| mit | C# |
8d66f3508809fd26160b3c6b249a32a18fea8f4d | Disable console modification | DeathCradle/Open-Terraria-API,DeathCradle/Open-Terraria-API | OTAPI.Modifications/OTAPI.Modifications.Console/Modifications/WriteLine.cs | OTAPI.Modifications/OTAPI.Modifications.Console/Modifications/WriteLine.cs | using Mono.Cecil;
using OTAPI.Patcher.Engine.Extensions;
using OTAPI.Patcher.Engine.Modification;
using System;
using System.Linq;
namespace OTAPI.Patcher.Engine.Modifications.Patches
{
public class ConsoleWrites : ModificationBase
{
public override System.Collections.Generic.IEnumerable<string> AssemblyTargets => new[]
{
"TerrariaServer, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null"
};
public override string Description => "Hooking all Console.Write/Line calls...";
public override void Run()
{
return; // no one uses these afaik, and the write/line callbacks need to be 1:1, currently an object is receiving all overloads and thats not ideal
var redirectMethods = new[]
{
"Write",
"WriteLine"
};
SourceDefinition.MainModule.ForEachInstruction((method, instruction) =>
{
var mth = instruction.Operand as MethodReference;
if (mth != null && mth.DeclaringType.FullName == "System.Console")
{
if (redirectMethods.Contains(mth.Name))
{
var mthReference = this.Resolve(mth);
if (mthReference != null)
instruction.Operand = SourceDefinition.MainModule.Import(mthReference);
}
}
});
}
MethodReference Resolve(MethodReference method)
{
return this.Type<OTAPI.Callbacks.Terraria.Console>()
.Method(method.Name,
parameters: method.Parameters,
acceptParamObjectTypes: true
);
}
}
}
| using Mono.Cecil;
using OTAPI.Patcher.Engine.Extensions;
using OTAPI.Patcher.Engine.Modification;
using System;
using System.Linq;
namespace OTAPI.Patcher.Engine.Modifications.Patches
{
public class ConsoleWrites : ModificationBase
{
public override System.Collections.Generic.IEnumerable<string> AssemblyTargets => new[]
{
"TerrariaServer, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null"
};
public override string Description => "Hooking all Console.Write/Line calls...";
public override void Run()
{
var redirectMethods = new[]
{
"Write",
"WriteLine"
};
SourceDefinition.MainModule.ForEachInstruction((method, instruction) =>
{
var mth = instruction.Operand as MethodReference;
if (mth != null && mth.DeclaringType.FullName == "System.Console")
{
if (redirectMethods.Contains(mth.Name))
{
var mthReference = this.Resolve(mth);
if (mthReference != null)
instruction.Operand = SourceDefinition.MainModule.Import(mthReference);
}
}
});
}
MethodReference Resolve(MethodReference method)
{
return this.Type<OTAPI.Callbacks.Terraria.Console>()
.Method(method.Name,
parameters: method.Parameters,
acceptParamObjectTypes: true
);
}
}
}
| mit | C# |
e3bb82abc8c021cbdd690960093b69335ff2c4c8 | Update SA0001 unit test | DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.Test/SpecialRules/SA0001UnitTests.cs | StyleCop.Analyzers/StyleCop.Analyzers.Test/SpecialRules/SA0001UnitTests.cs | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.SpecialRules
{
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Analyzers.SpecialRules;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using TestHelper;
using Xunit;
/// <summary>
/// Unit tests for <see cref="SA0001XmlCommentAnalysisDisabled"/>.
/// </summary>
public class SA0001UnitTests : DiagnosticVerifier
{
private DocumentationMode documentationMode;
[Theory]
[InlineData(DocumentationMode.Parse)]
[InlineData(DocumentationMode.Diagnose)]
public async Task TestEnabledDocumentationModesAsync(DocumentationMode documentationMode)
{
var testCode = @"public class Foo
{
}
";
this.documentationMode = documentationMode;
await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[InlineData(DocumentationMode.None)]
public async Task TestDisabledDocumentationModesAsync(DocumentationMode documentationMode)
{
var testCode = @"public class Foo
{
}
";
// This diagnostic is reported without a location
DiagnosticResult expected = this.CSharpDiagnostic();
this.documentationMode = documentationMode;
await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
/// <inheritdoc/>
protected override IEnumerable<DiagnosticAnalyzer> GetCSharpDiagnosticAnalyzers()
{
yield return new SA0001XmlCommentAnalysisDisabled();
}
protected override Solution CreateSolution(ProjectId projectId, string language)
{
Solution solution = base.CreateSolution(projectId, language);
Project project = solution.GetProject(projectId);
return solution.WithProjectParseOptions(projectId, project.ParseOptions.WithDocumentationMode(this.documentationMode));
}
}
}
| // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.SpecialRules
{
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Analyzers.SpecialRules;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using TestHelper;
using Xunit;
/// <summary>
/// Unit tests for <see cref="SA0001XmlCommentAnalysisDisabled"/>.
/// </summary>
public class SA0001UnitTests : DiagnosticVerifier
{
private DocumentationMode documentationMode;
[Theory]
[InlineData(DocumentationMode.Parse)]
[InlineData(DocumentationMode.Diagnose)]
public async Task TestEnabledDocumentationModesAsync(DocumentationMode documentationMode)
{
var testCode = @"public class Foo
{
}
";
this.documentationMode = documentationMode;
await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[InlineData(DocumentationMode.None)]
public async Task TestDisabledDocumentationModesAsync(DocumentationMode documentationMode)
{
var testCode = @"public class Foo
{
}
";
DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(null, 0, 0);
this.documentationMode = documentationMode;
await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
/// <inheritdoc/>
protected override IEnumerable<DiagnosticAnalyzer> GetCSharpDiagnosticAnalyzers()
{
yield return new SA0001XmlCommentAnalysisDisabled();
}
protected override Solution CreateSolution(ProjectId projectId, string language)
{
Solution solution = base.CreateSolution(projectId, language);
Project project = solution.GetProject(projectId);
return solution.WithProjectParseOptions(projectId, project.ParseOptions.WithDocumentationMode(this.documentationMode));
}
}
}
| mit | C# |
d7b0aacc253b668a4c651ce19db579fcf4b59b6f | Remove a reference to Xwt.Gtk. | mono/guiunit | src/framework/GuiUnit/XwtMainLoopIntegration.cs | src/framework/GuiUnit/XwtMainLoopIntegration.cs | using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace GuiUnit
{
public class XwtMainLoopIntegration : IMainLoopIntegration
{
// List of Xwt backends we will try to use in order of priority
Tuple<string,string>[] backends = new[] {
Tuple.Create ("Xwt.WPF.dll", "Xwt.WPFBackend.WPFEngine, Xwt.WPF"),
Tuple.Create ("Xwt.XamMac.dll", "Xwt.Mac.MacEngine, Xwt.XamMac")
};
Type Application {
get; set;
}
public XwtMainLoopIntegration ()
{
Application = Type.GetType ("Xwt.Application, Xwt");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
Type assemblyType = typeof (Assembly);
PropertyInfo locationProperty = assemblyType.GetProperty ("Location");
if (locationProperty == null)
throw new NotSupportedException();
if (TestRunner.LoadFileMethod == null)
throw new NotSupportedException();
string assemblyDirectory = Path.GetDirectoryName ((string)locationProperty.GetValue (Application.Assembly, null));
// Firstly init Xwt
var initialized = false;
var initMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var initMethod = initMethods.First (m => m.Name == "Initialize" && m.GetParameters ().Length == 1 && m.GetParameters ()[0].ParameterType == typeof (string));
foreach (var impl in backends) {
var xwtImpl = Path.Combine (assemblyDirectory, impl.Item1);
if (File.Exists (xwtImpl)) {
TestRunner.LoadFileMethod.Invoke (null, new[] { xwtImpl });
initMethod.Invoke (null, new object[] { impl.Item2 });
initialized = true;
break;
}
}
if (!initialized)
initMethod.Invoke (null, new object[] { null });
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var application = Type.GetType ("Xwt.Application, Xwt");
var invokeOnMainThreadMethod = application.GetMethod ("Invoke", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (null, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (null, null);
}
public void Shutdown ()
{
Application.GetMethod ("Exit").Invoke (null, null);
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace GuiUnit
{
public class XwtMainLoopIntegration : IMainLoopIntegration
{
// List of Xwt backends we will try to use in order of priority
Tuple<string,string>[] backends = new[] {
Tuple.Create ("Xwt.Gtk.dll", "Xwt.GtkBackend.GtkEngine, Xwt.Gtk"),
Tuple.Create ("Xwt.WPF.dll", "Xwt.WPFBackend.WPFEngine, Xwt.WPF"),
Tuple.Create ("Xwt.XamMac.dll", "Xwt.Mac.MacEngine, Xwt.XamMac")
};
Type Application {
get; set;
}
public XwtMainLoopIntegration ()
{
Application = Type.GetType ("Xwt.Application, Xwt");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
Type assemblyType = typeof (Assembly);
PropertyInfo locationProperty = assemblyType.GetProperty ("Location");
if (locationProperty == null)
throw new NotSupportedException();
if (TestRunner.LoadFileMethod == null)
throw new NotSupportedException();
string assemblyDirectory = Path.GetDirectoryName ((string)locationProperty.GetValue (Application.Assembly, null));
// Firstly init Xwt
var initialized = false;
var initMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var initMethod = initMethods.First (m => m.Name == "Initialize" && m.GetParameters ().Length == 1 && m.GetParameters ()[0].ParameterType == typeof (string));
foreach (var impl in backends) {
var xwtImpl = Path.Combine (assemblyDirectory, impl.Item1);
if (File.Exists (xwtImpl)) {
TestRunner.LoadFileMethod.Invoke (null, new[] { xwtImpl });
initMethod.Invoke (null, new object[] { impl.Item2 });
initialized = true;
break;
}
}
if (!initialized)
initMethod.Invoke (null, new object[] { null });
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var application = Type.GetType ("Xwt.Application, Xwt");
var invokeOnMainThreadMethod = application.GetMethod ("Invoke", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (null, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (null, null);
}
public void Shutdown ()
{
Application.GetMethod ("Exit").Invoke (null, null);
}
}
}
| mit | C# |
c15b6de9d6fe34e92a565ca29e90a7a58a34745f | Test Refactor, EvaluateTests with Setup and Evaluate | ajlopez/ClojSharp | Src/ClojSharp.Core.Tests/EvaluateTests.cs | Src/ClojSharp.Core.Tests/EvaluateTests.cs | namespace ClojSharp.Core.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClojSharp.Core.Compiler;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class EvaluateTests
{
private Machine machine;
[TestInitialize]
public void Setup()
{
this.machine = new Machine();
}
[TestMethod]
public void EvaluateInteger()
{
Assert.AreEqual(123, this.Evaluate("123", null));
}
[TestMethod]
public void EvaluateSymbolInContext()
{
Context context = new Context();
context.SetValue("one", 1);
Assert.AreEqual(1, this.Evaluate("one", context));
}
private object Evaluate(string text, Context context)
{
Parser parser = new Parser(text);
var expr = parser.ParseExpression();
Assert.IsNull(parser.ParseExpression());
return this.machine.Evaluate(expr, context);
}
}
}
| namespace ClojSharp.Core.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClojSharp.Core.Compiler;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class EvaluateTests
{
[TestMethod]
public void EvaluateInteger()
{
Machine machine = new Machine();
Parser parser = new Parser("123");
var expr = parser.ParseExpression();
Assert.AreEqual(123, machine.Evaluate(expr, null));
}
[TestMethod]
public void EvaluateSymbolInContext()
{
Machine machine = new Machine();
Context context = new Context();
context.SetValue("one", 1);
Parser parser = new Parser("one");
var expr = parser.ParseExpression();
Assert.AreEqual(1, machine.Evaluate(expr, context));
}
}
}
| mit | C# |
b96dec7599f6f74f04d0a1ab4dcd0c9d9d1f30da | Remove redundant body tags | erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner | Zk/Views/Home/Index.cshtml | Zk/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home";
}
<h2>Welcome to ASP.NET MVC @ViewData["Version"] on @ViewData["Runtime"]!</h2> | @{
ViewBag.Title = "Home";
}
<body>
<h2>Welcome to ASP.NET MVC @ViewData["Version"] on @ViewData["Runtime"]!</h2>
</body> | mit | C# |
84218f70d5df991fdbbd9503370ac343c6adf29e | Make DateTimePrecisionTest more robust | karolz-ms/diagnostics-eventflow | test/Microsoft.Diagnostics.EventFlow.Core.Tests/DateTimePreciseTests.cs | test/Microsoft.Diagnostics.EventFlow.Core.Tests/DateTimePreciseTests.cs | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Microsoft.Diagnostics.EventFlow.Core.Tests
{
public class DateTimePreciseTests
{
const double MaxResolutionThresholdMS = 200.0;
private static double GetAverageResolution()
{
const int count = 1000;
var precisions = new List<double>(count);
for (var i = 0; i < count; ++i)
{
var res = GetResolution().TotalMilliseconds;
if (res > MaxResolutionThresholdMS)
{
// Not a valid sample--most likely the test process was suspended by the OS for extended period of time.
continue;
}
precisions.Add(res);
}
return precisions.Average();
}
private static TimeSpan GetResolution()
{
var t1 = DateTimePrecise.UtcNow;
DateTime t2;
while ((t2 = DateTimePrecise.UtcNow) == t1)
{
// Spin until the time changes
}
return t2 - t1;
}
[Fact]
public void DateTimeIsHighPrecision()
{
if (!(Environment.OSVersion.Platform == PlatformID.Win32NT
&& (Environment.OSVersion.Version.Major >= 10 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2))))
{
// We only use explicit high-precision timestamping on Windows, relying on .NET implementation defaults for other platforms
return;
}
// We should be able to use 0.001 here. It works from a command line application but not the test runner.
const double expectedMs = 1.1;
var actualMs = GetAverageResolution();
Assert.True(actualMs <= expectedMs, $"Expected a higher resolution than {expectedMs}ms but got {actualMs:0.000}ms");
}
}
}
| // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Microsoft.Diagnostics.EventFlow.Core.Tests
{
public class DateTimePreciseTests
{
private static double GetAverageResolution()
{
const int count = 1000;
var precisions = new List<double>(count);
for (var i = 0; i < count; ++i)
{
precisions.Add(GetResolution().TotalMilliseconds);
}
return precisions.Average();
}
private static TimeSpan GetResolution()
{
var t1 = DateTimePrecise.UtcNow;
DateTime t2;
while ((t2 = DateTimePrecise.UtcNow) == t1)
{
// Spin until the time changes
}
return t2 - t1;
}
[Fact]
public void DateTimeIsHighPrecision()
{
if (!(Environment.OSVersion.Platform == PlatformID.Win32NT
&& (Environment.OSVersion.Version.Major >= 10 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2))))
{
// We only use explicit high-precision timestamping on Windows, relying on .NET implementation defaults for other platforms
return;
}
// We should be able to use 0.001 here. It works from a command line application but not the test runner.
const double expectedMs = 1.1;
var actualMs = GetAverageResolution();
Assert.True(actualMs <= expectedMs, $"Expected a higher resolution than {expectedMs}ms but got {actualMs:0.000}ms");
}
}
}
| mit | C# |
6161928583171295b8ade6b7391ba65063190c5d | Cover Art idle => Banshee logo | arfbtwn/banshee,arfbtwn/banshee,arfbtwn/banshee,arfbtwn/banshee,arfbtwn/banshee,arfbtwn/banshee,arfbtwn/banshee,arfbtwn/banshee | src/Core/Banshee.ThickClient/Banshee.Gui.Widgets/CoverArtDisplay.cs | src/Core/Banshee.ThickClient/Banshee.Gui.Widgets/CoverArtDisplay.cs | //
// CoverArtdisplay.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Cairo;
using Hyena;
using Hyena.Gui;
using Hyena.Gui.Theatrics;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
namespace Banshee.Gui.Widgets
{
public class CoverArtDisplay : TrackInfoDisplay
{
protected override int ArtworkSizeRequest {
get { return Allocation.Width; }
}
protected override void RenderTrackInfo (Cairo.Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum)
{
}
protected override bool CanRenderIdle {
get { return true; }
}
protected override void RenderIdle (Cairo.Context cr)
{
ArtworkRenderer.RenderThumbnail (cr, null, false, 0, 0, ArtworkSizeRequest, ArtworkSizeRequest, false, 0, true, BackgroundColor);
}
}
}
| //
// CoverArtdisplay.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Cairo;
using Hyena;
using Hyena.Gui;
using Hyena.Gui.Theatrics;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
namespace Banshee.Gui.Widgets
{
public class CoverArtDisplay : TrackInfoDisplay
{
private ImageSurface idle_album;
public CoverArtDisplay ()
{
}
protected override void Dispose (bool disposing)
{
var disposable = idle_album as IDisposable;
if (disposable != null) {
disposable.Dispose ();
}
base.Dispose (disposing);
}
protected override int ArtworkSizeRequest {
get { return Allocation.Width; }
}
protected override void RenderTrackInfo (Cairo.Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum)
{
}
protected override bool CanRenderIdle {
get { return true; }
}
protected override void RenderIdle (Cairo.Context cr)
{
idle_album = idle_album ?? PixbufImageSurface.Create (Banshee.Gui.IconThemeUtils.LoadIcon (
ArtworkSizeRequest, MissingAudioIconName), true);
ArtworkRenderer.RenderThumbnail (cr, idle_album, false, 0, 0,
ArtworkSizeRequest, ArtworkSizeRequest,
false, 0, true, BackgroundColor);
}
}
}
| mit | C# |
1fe4dd9aa3aa88ffbab2f01274e14b6e0603cc26 | Add Microsoft-Windows-DotNETRuntime to the list of framework EventSources. (#31691) | ViktorHofer/corefx,wtgodbe/corefx,Jiayili1/corefx,mmitche/corefx,BrennanConroy/corefx,mmitche/corefx,ericstj/corefx,Jiayili1/corefx,ViktorHofer/corefx,shimingsg/corefx,mmitche/corefx,ptoonen/corefx,mmitche/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx,BrennanConroy/corefx,ptoonen/corefx,shimingsg/corefx,Jiayili1/corefx,ericstj/corefx,ptoonen/corefx,ericstj/corefx,mmitche/corefx,shimingsg/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,mmitche/corefx,ericstj/corefx,ViktorHofer/corefx,Jiayili1/corefx,ViktorHofer/corefx,ptoonen/corefx,shimingsg/corefx,BrennanConroy/corefx,ptoonen/corefx,ericstj/corefx,ericstj/corefx,wtgodbe/corefx,wtgodbe/corefx,Jiayili1/corefx,shimingsg/corefx,Jiayili1/corefx,Jiayili1/corefx,ericstj/corefx,wtgodbe/corefx,mmitche/corefx,ptoonen/corefx,ptoonen/corefx,wtgodbe/corefx,wtgodbe/corefx | src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestUtilities.cs | src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestUtilities.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.
#if USE_MDT_EVENTSOURCE
using Microsoft.Diagnostics.Tracing;
#else
using System.Diagnostics.Tracing;
#endif
using System.Diagnostics;
using Xunit;
using System;
namespace BasicEventSourceTests
{
internal class TestUtilities
{
// Specifies whether the process is elevated or not.
private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated());
internal static bool IsProcessElevated => s_isElevated.Value;
/// <summary>
/// Confirms that there are no EventSources running.
/// </summary>
/// <param name="message">Will be printed as part of the Assert</param>
public static void CheckNoEventSourcesRunning(string message = "")
{
var eventSources = EventSource.GetSources();
string eventSourceNames = "";
foreach (var eventSource in EventSource.GetSources())
{
// Exempt sources built in to the framework that might be used by types involved in the tests
if (eventSource.Name != "System.Threading.Tasks.TplEventSource" &&
eventSource.Name != "System.Diagnostics.Eventing.FrameworkEventSource" &&
eventSource.Name != "System.Buffers.ArrayPoolEventSource" &&
eventSource.Name != "System.Threading.SynchronizationEventSource" &&
eventSource.Name != "System.Runtime.InteropServices.InteropEventProvider" &&
eventSource.Name != "System.Reflection.Runtime.Tracing" &&
eventSource.Name != "Microsoft-Windows-DotNETRuntime"
)
{
eventSourceNames += eventSource.Name + " ";
}
}
Debug.WriteLine(message);
Assert.Equal("", eventSourceNames);
}
}
}
| // 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.
#if USE_MDT_EVENTSOURCE
using Microsoft.Diagnostics.Tracing;
#else
using System.Diagnostics.Tracing;
#endif
using System.Diagnostics;
using Xunit;
using System;
namespace BasicEventSourceTests
{
internal class TestUtilities
{
// Specifies whether the process is elevated or not.
private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated());
internal static bool IsProcessElevated => s_isElevated.Value;
/// <summary>
/// Confirms that there are no EventSources running.
/// </summary>
/// <param name="message">Will be printed as part of the Assert</param>
public static void CheckNoEventSourcesRunning(string message = "")
{
var eventSources = EventSource.GetSources();
string eventSourceNames = "";
foreach (var eventSource in EventSource.GetSources())
{
// Exempt sources built in to the framework that might be used by types involved in the tests
if (eventSource.Name != "System.Threading.Tasks.TplEventSource" &&
eventSource.Name != "System.Diagnostics.Eventing.FrameworkEventSource" &&
eventSource.Name != "System.Buffers.ArrayPoolEventSource" &&
eventSource.Name != "System.Threading.SynchronizationEventSource" &&
eventSource.Name != "System.Runtime.InteropServices.InteropEventProvider" &&
eventSource.Name != "System.Reflection.Runtime.Tracing"
)
{
eventSourceNames += eventSource.Name + " ";
}
}
Debug.WriteLine(message);
Assert.Equal("", eventSourceNames);
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.