Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add XML documentation to extension method HttpRequestBase.GetOriginalUrl() and make the method public. | using System;
using System.Web;
namespace Canonicalize
{
internal static class HttpRequestBaseExtensions
{
public static Uri GetOriginalUrl(this HttpRequestBase request)
{
if (request.Url == null || request.Headers == null)
{
return request.Url;
}
var uriBuilder = new UriBuilder(request.Url);
var forwardedProtocol = request.Headers["X-Forwarded-Proto"];
if (forwardedProtocol != null)
{
uriBuilder.Scheme = forwardedProtocol;
}
var hostHeader = request.Headers["X-Forwarded-Host"] ?? request.Headers["Host"];
if (hostHeader != null)
{
var parsedHost = new Uri(uriBuilder.Scheme + Uri.SchemeDelimiter + hostHeader);
uriBuilder.Host = parsedHost.Host;
uriBuilder.Port = parsedHost.Port;
}
return uriBuilder.Uri;
}
}
}
| using System;
using System.Web;
namespace Canonicalize
{
/// <summary>
/// Adds extension methods on <see cref="HttpRequestBase"/>.
/// </summary>
public static class HttpRequestBaseExtensions
{
/// <summary>
/// Gets the original URL requested by the client, without artifacts from proxies or load balancers.
/// In particular HTTP headers Host, X-Forwarded-Host, X-Forwarded-Proto are applied on top of <see cref="HttpRequestBase.Url"/>.
/// </summary>
/// <param name="request">The request for which the original URL should be computed.</param>
/// <returns>The original URL requested by the client.</returns>
public static Uri GetOriginalUrl(this HttpRequestBase request)
{
if (request.Url == null || request.Headers == null)
{
return request.Url;
}
var uriBuilder = new UriBuilder(request.Url);
var forwardedProtocol = request.Headers["X-Forwarded-Proto"];
if (forwardedProtocol != null)
{
uriBuilder.Scheme = forwardedProtocol;
}
var hostHeader = request.Headers["X-Forwarded-Host"] ?? request.Headers["Host"];
if (hostHeader != null)
{
var parsedHost = new Uri(uriBuilder.Scheme + Uri.SchemeDelimiter + hostHeader);
uriBuilder.Host = parsedHost.Host;
uriBuilder.Port = parsedHost.Port;
}
return uriBuilder.Uri;
}
}
}
|
Add routing rules for profile | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace JabberBCIT {
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| using System.Web.Mvc;
using System.Web.Routing;
namespace JabberBCIT
{
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "EditProfile",
url: "Profile/Edit/{id}",
defaults: new { controller = "Manage", action = "Edit" }
);
routes.MapRoute(
name: "Profile",
url: "Profile/{id}",
defaults: new { controller = "Manage", action = "Index"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
|
Add tests for sameness in DateTimeFormatInfo | // 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 Xunit;
namespace System.Globalization.Tests
{
public class DateTimeFormatInfoReadOnly
{
public static IEnumerable<object[]> ReadOnly_TestData()
{
yield return new object[] { DateTimeFormatInfo.InvariantInfo, true };
yield return new object[] { new DateTimeFormatInfo(), false };
yield return new object[] { new CultureInfo("en-US").DateTimeFormat, false };
}
[Theory]
[MemberData(nameof(ReadOnly_TestData))]
public void ReadOnly(DateTimeFormatInfo format, bool expected)
{
Assert.Equal(expected, format.IsReadOnly);
DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format);
Assert.True(readOnlyFormat.IsReadOnly);
}
[Fact]
public void ReadOnly_Null_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("dtfi", () => DateTimeFormatInfo.ReadOnly(null)); // Dtfi is null
}
}
}
| // 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 Xunit;
namespace System.Globalization.Tests
{
public class DateTimeFormatInfoReadOnly
{
public static IEnumerable<object[]> ReadOnly_TestData()
{
yield return new object[] { DateTimeFormatInfo.InvariantInfo, true };
yield return new object[] { DateTimeFormatInfo.ReadOnly(new DateTimeFormatInfo()), true };
yield return new object[] { new DateTimeFormatInfo(), false };
yield return new object[] { new CultureInfo("en-US").DateTimeFormat, false };
}
[Theory]
[MemberData(nameof(ReadOnly_TestData))]
public void ReadOnly(DateTimeFormatInfo format, bool originalFormatIsReadOnly)
{
Assert.Equal(originalFormatIsReadOnly, format.IsReadOnly);
DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format);
if (originalFormatIsReadOnly)
{
Assert.Same(format, readOnlyFormat);
}
else
{
Assert.NotSame(format, readOnlyFormat);
}
Assert.True(readOnlyFormat.IsReadOnly);
}
[Fact]
public void ReadOnly_Null_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("dtfi", () => DateTimeFormatInfo.ReadOnly(null)); // Dtfi is null
}
}
}
|
Fix running test multiple times in same .NET runtime instance | using System;
using FullSerializer.Internal;
using NUnit.Framework;
using System.Collections.Generic;
namespace FullSerializer.Tests {
[fsObject(Converter = typeof(MyConverter))]
public class MyModel {
}
public class MyConverter : fsConverter {
public static bool DidSerialize = false;
public static bool DidDeserialize = false;
public override bool CanProcess(Type type) {
throw new NotSupportedException();
}
public override object CreateInstance(fsData data, Type storageType) {
return new MyModel();
}
public override fsFailure TrySerialize(object instance, out fsData serialized, Type storageType) {
DidSerialize = true;
serialized = new fsData();
return fsFailure.Success;
}
public override fsFailure TryDeserialize(fsData data, ref object instance, Type storageType) {
DidDeserialize = true;
return fsFailure.Success;
}
}
public class SpecifiedConverterTests {
[Test]
public void VerifyConversion() {
var serializer = new fsSerializer();
fsData result;
serializer.TrySerialize(new MyModel(), out result);
Assert.IsTrue(MyConverter.DidSerialize);
Assert.IsFalse(MyConverter.DidDeserialize);
MyConverter.DidSerialize = false;
object resultObj = null;
serializer.TryDeserialize(result, typeof (MyModel), ref resultObj);
Assert.IsFalse(MyConverter.DidSerialize);
Assert.IsTrue(MyConverter.DidDeserialize);
}
}
} | using System;
using FullSerializer.Internal;
using NUnit.Framework;
using System.Collections.Generic;
namespace FullSerializer.Tests {
[fsObject(Converter = typeof(MyConverter))]
public class MyModel {
}
public class MyConverter : fsConverter {
public static bool DidSerialize = false;
public static bool DidDeserialize = false;
public override bool CanProcess(Type type) {
throw new NotSupportedException();
}
public override object CreateInstance(fsData data, Type storageType) {
return new MyModel();
}
public override fsFailure TrySerialize(object instance, out fsData serialized, Type storageType) {
DidSerialize = true;
serialized = new fsData();
return fsFailure.Success;
}
public override fsFailure TryDeserialize(fsData data, ref object instance, Type storageType) {
DidDeserialize = true;
return fsFailure.Success;
}
}
public class SpecifiedConverterTests {
[Test]
public void VerifyConversion() {
MyConverter.DidDeserialize = false;
MyConverter.DidSerialize = false;
var serializer = new fsSerializer();
fsData result;
serializer.TrySerialize(new MyModel(), out result);
Assert.IsTrue(MyConverter.DidSerialize);
Assert.IsFalse(MyConverter.DidDeserialize);
MyConverter.DidSerialize = false;
object resultObj = null;
serializer.TryDeserialize(result, typeof (MyModel), ref resultObj);
Assert.IsFalse(MyConverter.DidSerialize);
Assert.IsTrue(MyConverter.DidDeserialize);
}
}
} |
Add Customer filter when listing CreditNote | namespace Stripe
{
using Newtonsoft.Json;
public class CreditNoteListOptions : ListOptions
{
/// <summary>
/// ID of the invoice.
/// </summary>
[JsonProperty("invoice")]
public string InvoiceId { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
public class CreditNoteListOptions : ListOptions
{
/// <summary>
/// ID of the customer.
/// </summary>
[JsonProperty("customer")]
public string CustomerId { get; set; }
/// <summary>
/// ID of the invoice.
/// </summary>
[JsonProperty("invoice")]
public string InvoiceId { get; set; }
}
}
|
Make string format optional if no trace listener is attached | using System;
namespace MQTTnet.Core.Diagnostics
{
public static class MqttTrace
{
public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;
public static void Verbose(string source, string message)
{
Publish(source, MqttTraceLevel.Verbose, null, message);
}
public static void Information(string source, string message)
{
Publish(source, MqttTraceLevel.Information, null, message);
}
public static void Warning(string source, string message)
{
Publish(source, MqttTraceLevel.Warning, null, message);
}
public static void Warning(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Warning, exception, message);
}
public static void Error(string source, string message)
{
Publish(source, MqttTraceLevel.Error, null, message);
}
public static void Error(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Error, exception, message);
}
private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message)
{
TraceMessagePublished?.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
}
}
}
| using System;
namespace MQTTnet.Core.Diagnostics
{
public static class MqttTrace
{
public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;
public static void Verbose(string source, string message)
{
Publish(source, MqttTraceLevel.Verbose, null, message);
}
public static void Information(string source, string message)
{
Publish(source, MqttTraceLevel.Information, null, message);
}
public static void Warning(string source, string message)
{
Publish(source, MqttTraceLevel.Warning, null, message);
}
public static void Warning(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Warning, exception, message);
}
public static void Error(string source, string message)
{
Publish(source, MqttTraceLevel.Error, null, message);
}
public static void Error(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Error, exception, message);
}
private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message)
{
var handler = TraceMessagePublished;
if (handler == null)
{
return;
}
message = string.Format(message, 1);
handler.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
}
}
}
|
Add rationale for exit status codes to comments. | using System;
namespace Sep.Git.Tfs
{
public static class GitTfsExitCodes
{
public const int OK = 0;
public const int Help = 1;
public const int InvalidArguments = 2;
public const int ForceRequired = 3;
public const int ExceptionThrown = Byte.MaxValue - 1;
}
}
| using System;
namespace Sep.Git.Tfs
{
/// <summary>
/// Collection of exit codes used by git-tfs.
/// </summary>
/// <remarks>
/// For consistency across all running environments, both various
/// Windows - shells (powershell.exe, cmd.exe) and UNIX - like environments
/// such as bash (MinGW), sh or zsh avoid using negative exit status codes
/// or codes 255 or higher.
///
/// Some running environments might either modulo exit codes with 256 or clamp
/// them to interval [0, 255].
///
/// For more information:
/// http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
/// http://tldp.org/LDP/abs/html/exitcodes.html
/// </remarks>
public static class GitTfsExitCodes
{
public const int OK = 0;
public const int Help = 1;
public const int InvalidArguments = 2;
public const int ForceRequired = 3;
public const int ExceptionThrown = Byte.MaxValue - 1;
}
}
|
Improve exception handling when function does not exist | using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CroquetAustralia.Domain.Data;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
namespace CroquetAustralia.DownloadTournamentEntries.ReadModels
{
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
public class FunctionReadModel
{
public FunctionReadModel(EntrySubmittedReadModel entrySubmitted, Tournament tournament, SubmitEntry.LineItem lineItem)
{
TournamentItem = tournament.Functions.First(f => f.Id == lineItem.Id);
EntrySubmitted = entrySubmitted;
LineItem = lineItem;
}
public EntrySubmittedReadModel EntrySubmitted { get; }
public SubmitEntry.LineItem LineItem { get; }
public TournamentItem TournamentItem { get; }
}
} | using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CroquetAustralia.Domain.Data;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
namespace CroquetAustralia.DownloadTournamentEntries.ReadModels
{
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
public class FunctionReadModel
{
public FunctionReadModel(EntrySubmittedReadModel entrySubmitted, Tournament tournament, SubmitEntry.LineItem lineItem)
{
TournamentItem = FindFirstFunction(tournament, lineItem);
EntrySubmitted = entrySubmitted;
LineItem = lineItem;
}
private static TournamentItem FindFirstFunction(Tournament tournament, SubmitEntry.LineItem lineItem)
{
try
{
return tournament.Functions.First(f => f.Id == lineItem.Id);
}
catch (Exception e)
{
throw new Exception($"Cannot find function '{lineItem.Id}' in tournament '{tournament.Title}'.", e);
}
}
public EntrySubmittedReadModel EntrySubmitted { get; }
public SubmitEntry.LineItem LineItem { get; }
public TournamentItem TournamentItem { get; }
}
} |
Update Ensure calls to use full path | using Microsoft.Extensions.Options;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.IO;
namespace Umbraco.Core.Runtime
{
public class CoreInitialComponent : IComponent
{
private readonly IIOHelper _ioHelper;
private readonly GlobalSettings _globalSettings;
public CoreInitialComponent(IIOHelper ioHelper, IOptions<GlobalSettings> globalSettings)
{
_ioHelper = ioHelper;
_globalSettings = globalSettings.Value;
}
public void Initialize()
{
// ensure we have some essential directories
// every other component can then initialize safely
_ioHelper.EnsurePathExists(Constants.SystemDirectories.Data);
_ioHelper.EnsurePathExists(_globalSettings.UmbracoMediaPath);
_ioHelper.EnsurePathExists(Constants.SystemDirectories.MvcViews);
_ioHelper.EnsurePathExists(Constants.SystemDirectories.PartialViews);
_ioHelper.EnsurePathExists(Constants.SystemDirectories.MacroPartials);
}
public void Terminate()
{ }
}
}
| using Microsoft.Extensions.Options;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
namespace Umbraco.Core.Runtime
{
public class CoreInitialComponent : IComponent
{
private readonly IIOHelper _ioHelper;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly GlobalSettings _globalSettings;
public CoreInitialComponent(IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, IOptions<GlobalSettings> globalSettings)
{
_ioHelper = ioHelper;
_hostingEnvironment = hostingEnvironment;
_globalSettings = globalSettings.Value;
}
public void Initialize()
{
// ensure we have some essential directories
// every other component can then initialize safely
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Data));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathWebRoot(_globalSettings.UmbracoMediaPath));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MvcViews));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.PartialViews));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MacroPartials));
}
public void Terminate()
{ }
}
}
|
Fix test, mine block with transaction | namespace BlockchainSharp.Tests.Processors
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BlockchainSharp.Stores;
using BlockchainSharp.Processors;
using BlockchainSharp.Tests.TestUtils;
using BlockchainSharp.Core;
[TestClass]
public class MinerProcessorTests
{
[TestMethod]
public void MineBlock()
{
TransactionPool transactionPool = new TransactionPool();
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(0, block.Transactions.Count);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
[TestMethod]
public void MineBlockWithTransaction()
{
TransactionPool transactionPool = new TransactionPool();
Transaction transaction = FactoryHelper.CreateTransaction(1000);
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(1, block.Transactions.Count);
Assert.AreSame(transaction, block.Transactions[0]);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
}
}
| namespace BlockchainSharp.Tests.Processors
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BlockchainSharp.Stores;
using BlockchainSharp.Processors;
using BlockchainSharp.Tests.TestUtils;
using BlockchainSharp.Core;
[TestClass]
public class MinerProcessorTests
{
[TestMethod]
public void MineBlock()
{
TransactionPool transactionPool = new TransactionPool();
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(0, block.Transactions.Count);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
[TestMethod]
public void MineBlockWithTransaction()
{
TransactionPool transactionPool = new TransactionPool();
Transaction transaction = FactoryHelper.CreateTransaction(1000);
transactionPool.AddTransaction(transaction);
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(1, block.Transactions.Count);
Assert.AreSame(transaction, block.Transactions[0]);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
}
}
|
Add a safety check for when Authors is null, which shouldn't happen in the first place. Work items: 1727, 1728 | using System;
using System.Collections.Generic;
using System.Windows.Data;
namespace NuGet.Dialog.PackageManagerUI
{
public class StringCollectionsToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(string))
{
string stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
else
{
IEnumerable<string> parts = (IEnumerable<string>)value;
return String.Join(", ", parts);
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Windows.Data;
namespace NuGet.Dialog.PackageManagerUI
{
public class StringCollectionsToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(string))
{
string stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
else if (value == null)
{
return String.Empty;
}
{
IEnumerable<string> parts = (IEnumerable<string>)value;
return String.Join(", ", parts);
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
Fix - Cambiata chiave degli eventi da id richiesta a codice | using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi;
using SO115App.API.Models.Servizi.CQRS.Queries.ListaEventi;
using SO115App.Models.Servizi.Infrastruttura.GetListaEventi;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Persistence.MongoDB.GestioneInterventi
{
public class GetListaEventiByCodiceRichiesta : IGetListaEventi
{
private readonly DbContext _dbContext;
public GetListaEventiByCodiceRichiesta(DbContext dbContext)
{
_dbContext = dbContext;
}
public List<Evento> Get(ListaEventiQuery query)
{
return (List<Evento>)_dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Eq(x => x.Id, query.IdRichiesta)).Single().Eventi;
}
}
}
| using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi;
using SO115App.API.Models.Servizi.CQRS.Queries.ListaEventi;
using SO115App.Models.Servizi.Infrastruttura.GetListaEventi;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Persistence.MongoDB.GestioneInterventi
{
public class GetListaEventiByCodiceRichiesta : IGetListaEventi
{
private readonly DbContext _dbContext;
public GetListaEventiByCodiceRichiesta(DbContext dbContext)
{
_dbContext = dbContext;
}
public List<Evento> Get(ListaEventiQuery query)
{
return (List<Evento>)_dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Eq(x => x.Codice, query.IdRichiesta)).Single().Eventi;
}
}
}
|
Revert "[DEVOPS-245] verify test failure" | using NUnit.Framework;
using System;
namespace Sailthru.Tests
{
[TestFixture()]
public class Test
{
[Test()]
public void TestCase()
{
Assert.Fail();
}
}
}
| using NUnit.Framework;
using System;
namespace Sailthru.Tests
{
[TestFixture()]
public class Test
{
[Test()]
public void TestCase()
{
}
}
}
|
Enable NH-315 fixture since it works now | using System;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH315
{
/// <summary>
/// Summary description for Fixture.
/// </summary>
[TestFixture]
[Ignore("Not working, see http://jira.nhibernate.org/browse/NH-315")]
public class Fixture : TestCase
{
protected override string MappingsAssembly
{
get { return "NHibernate.Test"; }
}
protected override System.Collections.IList Mappings
{
get
{
return new string[] { "NHSpecificTest.NH315.Mappings.hbm.xml" };
}
}
[Test]
public void SaveClient()
{
Client client = new Client();
Person person = new Person();
client.Contacts = new ClientPersons();
using( ISession s = OpenSession() )
{
s.Save( person );
client.Contacts.PersonId = person.Id;
client.Contacts.Person = person;
s.Save( client );
s.Flush();
}
using( ISession s = OpenSession() )
{
s.Delete( client );
s.Delete( person );
s.Flush();
}
}
}
}
| using System;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH315
{
/// <summary>
/// Summary description for Fixture.
/// </summary>
[TestFixture]
public class Fixture : BugTestCase
{
public override string BugNumber
{
get { return "NH315"; }
}
[Test]
public void SaveClient()
{
Client client = new Client();
Person person = new Person();
client.Contacts = new ClientPersons();
using( ISession s = OpenSession() )
{
s.Save( person );
client.Contacts.PersonId = person.Id;
client.Contacts.Person = person;
s.Save( client );
s.Flush();
}
using( ISession s = OpenSession() )
{
s.Delete( client );
s.Delete( person );
s.Flush();
}
}
}
}
|
Fix missed view model reference | using RealEstateAgencyFranchise.Database;
using Starcounter;
using System.Linq;
namespace RealEstateAgencyFranchise.Controllers
{
internal class OfficeController
{
public Json Get(ulong officeObjectNo)
{
return Db.Scope(() =>
{
var offices = Db.SQL<Office>(
"select o from Office o where o.ObjectNo = ?",
officeObjectNo);
if (offices == null || !offices.Any())
{
return new Response()
{
StatusCode = 404,
StatusDescription = "Office not found"
};
}
var office = offices.First;
var json = new OfficeListJson
{
Data = office
};
if (Session.Current == null)
{
Session.Current = new Session(SessionOptions.PatchVersioning);
}
json.Session = Session.Current;
return json;
});
}
}
}
| using RealEstateAgencyFranchise.Database;
using RealEstateAgencyFranchise.ViewModels;
using Starcounter;
using System.Linq;
namespace RealEstateAgencyFranchise.Controllers
{
internal class OfficeController
{
public Json Get(ulong officeObjectNo)
{
return Db.Scope(() =>
{
var offices = Db.SQL<Office>(
"select o from Office o where o.ObjectNo = ?",
officeObjectNo);
if (offices == null || !offices.Any())
{
return new Response()
{
StatusCode = 404,
StatusDescription = "Office not found"
};
}
var office = offices.First;
var json = new OfficeDetailsJson
{
Data = office
};
if (Session.Current == null)
{
Session.Current = new Session(SessionOptions.PatchVersioning);
}
json.Session = Session.Current;
return json;
});
}
}
}
|
Change time type to long | using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct ServerTimeMessage : INetSerializable
{
public int serverUnixTime;
public void Deserialize(NetDataReader reader)
{
serverUnixTime = reader.GetPackedInt();
}
public void Serialize(NetDataWriter writer)
{
writer.PutPackedInt(serverUnixTime);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct ServerTimeMessage : INetSerializable
{
public long serverUnixTime;
public void Deserialize(NetDataReader reader)
{
serverUnixTime = reader.GetPackedLong();
}
public void Serialize(NetDataWriter writer)
{
writer.PutPackedLong(serverUnixTime);
}
}
}
|
Fix `TemplateGame.iOS` failing to build | // 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 UIKit;
namespace TemplateGame.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
}
}
}
| // 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.iOS;
using UIKit;
namespace TemplateGame.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
}
}
}
|
Fix build failure from the merge to master. | using System;
using System.Globalization;
namespace Avalonia.Utilities
{
#if !BUILDTASK
public
#endif
static class StyleClassParser
{
public static ReadOnlySpan<char> ParseStyleClass(this ref CharacterReader r)
{
if (IsValidIdentifierStart(r.Peek))
{
return r.TakeWhile(c => IsValidIdentifierChar(c));
}
else
{
return ReadOnlySpan<char>.Empty;
}
}
private static bool IsValidIdentifierStart(char c)
{
return char.IsLetter(c) || c == '_';
}
private static bool IsValidIdentifierChar(char c)
{
if (IsValidIdentifierStart(c) || c == '-')
{
return true;
}
else
{
var cat = CharUnicodeInfo.GetUnicodeCategory(c);
return cat == UnicodeCategory.NonSpacingMark ||
cat == UnicodeCategory.SpacingCombiningMark ||
cat == UnicodeCategory.ConnectorPunctuation ||
cat == UnicodeCategory.Format ||
cat == UnicodeCategory.DecimalDigitNumber;
}
}
}
}
| using System;
using System.Globalization;
namespace Avalonia.Utilities
{
#if !BUILDTASK
public
#endif
static class StyleClassParser
{
public static ReadOnlySpan<char> ParseStyleClass(this ref CharacterReader r)
{
if (IsValidIdentifierStart(r.PeekOneOrThrow))
{
return r.TakeWhile(c => IsValidIdentifierChar(c));
}
else
{
return ReadOnlySpan<char>.Empty;
}
}
private static bool IsValidIdentifierStart(char c)
{
return char.IsLetter(c) || c == '_';
}
private static bool IsValidIdentifierChar(char c)
{
if (IsValidIdentifierStart(c) || c == '-')
{
return true;
}
else
{
var cat = CharUnicodeInfo.GetUnicodeCategory(c);
return cat == UnicodeCategory.NonSpacingMark ||
cat == UnicodeCategory.SpacingCombiningMark ||
cat == UnicodeCategory.ConnectorPunctuation ||
cat == UnicodeCategory.Format ||
cat == UnicodeCategory.DecimalDigitNumber;
}
}
}
}
|
Fix casting error in WhenAny shim | using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Windows;
namespace ReactiveUIMicro
{
public static class WhenAnyShim
{
public static IObservable<TVal> WhenAny<TSender, TTarget, TVal>(this TSender This, Expression<Func<TSender, TTarget>> property, Func<IObservedChange<TSender, TTarget>, TVal> selector)
where TSender : IReactiveNotifyPropertyChanged
{
var propName = Reflection.SimpleExpressionToPropertyName(property);
var getter = Reflection.GetValueFetcherForProperty<TSender>(propName);
return This.Changed
.Where(x => x.PropertyName == propName)
.Select(_ => new ObservedChange<TSender, TTarget>() {
Sender = This,
PropertyName = propName,
Value = (TTarget)getter(This),
})
.StartWith(new ObservedChange<TSender, TTarget>() { Sender = This, PropertyName = propName, Value = (TTarget)getter(This) })
.Select(selector);
}
}
} | using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Windows;
namespace ReactiveUIMicro
{
public static class WhenAnyShim
{
public static IObservable<TVal> WhenAny<TSender, TTarget, TVal>(this TSender This, Expression<Func<TSender, TTarget>> property, Func<IObservedChange<TSender, TTarget>, TVal> selector)
where TSender : IReactiveNotifyPropertyChanged
{
var propName = Reflection.SimpleExpressionToPropertyName(property);
var getter = Reflection.GetValueFetcherForProperty(This.GetType(), propName);
return This.Changed
.Where(x => x.PropertyName == propName)
.Select(_ => new ObservedChange<TSender, TTarget>() {
Sender = This,
PropertyName = propName,
Value = (TTarget)getter(This),
})
.StartWith(new ObservedChange<TSender, TTarget>() { Sender = This, PropertyName = propName, Value = (TTarget)getter(This) })
.Select(selector);
}
}
} |
Add support for nested properties access in GetElementAttribute command using dot separated syntax | namespace WindowsUniversalAppDriver.InnerServer.Commands
{
using System.Reflection;
using WindowsUniversalAppDriver.Common;
internal class GetElementAttributeCommand : CommandBase
{
#region Public Properties
public string ElementId { get; set; }
#endregion
#region Public Methods and Operators
public override string DoImpl()
{
var element = this.Automator.WebElements.GetRegisteredElement(this.ElementId);
object value;
var attributeName = (string)null;
if (this.Parameters.TryGetValue("NAME", out value))
{
attributeName = value.ToString();
}
if (attributeName == null)
{
return this.JsonResponse(ResponseStatus.Success, null);
}
var property = element.GetType().GetRuntimeProperty(attributeName);
if (property == null)
{
return this.JsonResponse(ResponseStatus.Success, null);
}
var attributeValue = property.GetValue(element, null).ToString();
return this.JsonResponse(ResponseStatus.Success, attributeValue);
}
#endregion
}
}
| namespace WindowsUniversalAppDriver.InnerServer.Commands
{
using System;
using System.Reflection;
using WindowsUniversalAppDriver.Common;
internal class GetElementAttributeCommand : CommandBase
{
#region Public Properties
public string ElementId { get; set; }
#endregion
#region Public Methods and Operators
public override string DoImpl()
{
var element = this.Automator.WebElements.GetRegisteredElement(this.ElementId);
object value;
string attributeName = null;
if (this.Parameters.TryGetValue("NAME", out value))
{
attributeName = value.ToString();
}
if (attributeName == null)
{
return this.JsonResponse(ResponseStatus.Success, null);
}
var properties = attributeName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
object propertyValueObject = element;
foreach (var property in properties)
{
propertyValueObject = GetProperty(propertyValueObject, property);
if (propertyValueObject == null)
{
break;
}
}
var propertyValue = propertyValueObject == null ? null : propertyValueObject.ToString();
return this.JsonResponse(ResponseStatus.Success, propertyValue);
}
private static object GetProperty(object obj, string propertyName)
{
var property = obj.GetType().GetRuntimeProperty(propertyName);
return property == null ? null : property.GetValue(obj, null);
}
#endregion
}
}
|
Remove stray space in 404 page | @using StackExchange.DataExplorer
@{this.SetPageTitle("Page not found - Stack Exchange Data Explorer");}
<div class="subheader">
<h2>Page Not Found</h2>
</div>
<div style="width:400px; float:left;">
<p>Sorry we could not find the page requested. However, we did find a picture of <a href="http://en.wikipedia.org/wiki/Edgar_F._Codd">Edgar F. Codd </a>, the inventor of the relational data model.</p>
<p>If you feel something is missing that should be here, <a href="http://meta.stackexchange.com/contact">contact us</a>.</p>
</div>
<img src="/Content/images/edgar.jpg" style="float:right;" />
<br class="clear" />
<p> </p> | @using StackExchange.DataExplorer
@{this.SetPageTitle("Page not found - Stack Exchange Data Explorer");}
<div class="subheader">
<h2>Page Not Found</h2>
</div>
<div style="width:400px; float:left;">
<p>Sorry we could not find the page requested. However, we did find a picture of <a href="http://en.wikipedia.org/wiki/Edgar_F._Codd">Edgar F. Codd</a>, the inventor of the relational data model.</p>
<p>If you feel something is missing that should be here, <a href="http://meta.stackexchange.com/contact">contact us</a>.</p>
</div>
<img src="/Content/images/edgar.jpg" style="float:right;" />
<br class="clear" />
<p> </p>
|
Set the last activity on creation so sql doesn't blow up. | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace JabbR.Models
{
public class ChatRoom
{
[Key]
public int Key { get; set; }
public DateTime LastActivity { get; set; }
public DateTime? LastNudged { get; set; }
public string Name { get; set; }
public virtual ChatUser Owner { get; set; }
public virtual ICollection<ChatMessage> Messages { get; set; }
public virtual ICollection<ChatUser> Users { get; set; }
public ChatRoom()
{
Messages = new HashSet<ChatMessage>();
Users = new HashSet<ChatUser>();
}
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace JabbR.Models
{
public class ChatRoom
{
[Key]
public int Key { get; set; }
public DateTime LastActivity { get; set; }
public DateTime? LastNudged { get; set; }
public string Name { get; set; }
public virtual ChatUser Owner { get; set; }
public virtual ICollection<ChatMessage> Messages { get; set; }
public virtual ICollection<ChatUser> Users { get; set; }
public ChatRoom()
{
LastActivity = DateTime.UtcNow;
Messages = new HashSet<ChatMessage>();
Users = new HashSet<ChatUser>();
}
}
} |
Fix refactor fail and add book reference | using System;
namespace BitCommitment
{
/// <summary>
/// A class to perform bit commitment. It does not care what the input is; it's just a
/// facility for exchanging bit commitment messages. Based on Bruce Schneier's RandBytes1-way
/// function method for committing bits
/// </summary>
public class BitCommitmentProvider
{
public byte[] AliceRandBytes1 { get; set; }
public byte[] AliceRandBytes2 { get; set; }
public byte[] AliceBytesToCommitBytesToCommit { get; set; }
public BitCommitmentProvider(byte[] randBytes1,
byte[] randBytes2,
byte[] bytesToCommit)
{
AliceRandBytes1 = randBytes1;
AliceRandBytes2 = randBytes2;
AliceBytesToCommitBytesToCommit = bytesToCommit;
}
public byte[] BitCommitMessage()
{
throw new NotImplementedException();
}
}
}
| using System;
namespace BitCommitment
{
/// <summary>
/// A class to perform bit commitment. It does not care what the input is; it's just a
/// facility for exchanging bit commitment messages. Based on Bruce Schneier's one-way
/// function method for committing bits. See p.87 of `Applied Cryptography`.
/// </summary>
public class BitCommitmentProvider
{
public byte[] AliceRandBytes1 { get; set; }
public byte[] AliceRandBytes2 { get; set; }
public byte[] AliceBytesToCommitBytesToCommit { get; set; }
public BitCommitmentProvider(byte[] randBytes1,
byte[] randBytes2,
byte[] bytesToCommit)
{
AliceRandBytes1 = randBytes1;
AliceRandBytes2 = randBytes2;
AliceBytesToCommitBytesToCommit = bytesToCommit;
}
public byte[] BitCommitMessage()
{
throw new NotImplementedException();
}
}
}
|
Change domain id to new naming format | using System.Collections.Generic;
using System.Linq;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;
namespace TeaCommerce.Umbraco.Configuration.Compatibility {
public static class Domain {
private const string CacheKey = "Domains";
public static umbraco.cms.businesslogic.web.Domain[] GetDomainsById( int nodeId ) {
List<umbraco.cms.businesslogic.web.Domain> domains = CacheService.Instance.GetCacheValue<List<umbraco.cms.businesslogic.web.Domain>>( CacheKey );
if ( domains == null ) {
domains = new List<umbraco.cms.businesslogic.web.Domain>();
List<dynamic> result = ApplicationContext.Current.DatabaseContext.Database.Fetch<dynamic>( "select id, domainName from umbracoDomains" );
foreach ( dynamic domain in result ) {
if ( domains.All( d => d.Name != domain.domainName ) ) {
domains.Add( new umbraco.cms.businesslogic.web.Domain( domain.domainId ) );
}
}
CacheService.Instance.SetCacheValue( CacheKey, domains );
}
return domains.Where( d => d.RootNodeId == nodeId ).ToArray();
}
public static void InvalidateCache() {
CacheService.Instance.Invalidate( CacheKey );
}
}
} | using System.Collections.Generic;
using System.Linq;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;
namespace TeaCommerce.Umbraco.Configuration.Compatibility {
public static class Domain {
private const string CacheKey = "Domains";
public static umbraco.cms.businesslogic.web.Domain[] GetDomainsById( int nodeId ) {
List<umbraco.cms.businesslogic.web.Domain> domains = CacheService.Instance.GetCacheValue<List<umbraco.cms.businesslogic.web.Domain>>( CacheKey );
if ( domains == null ) {
domains = new List<umbraco.cms.businesslogic.web.Domain>();
List<dynamic> result = ApplicationContext.Current.DatabaseContext.Database.Fetch<dynamic>( "select id, domainName from umbracoDomains" );
foreach ( dynamic domain in result ) {
if ( domains.All( d => d.Name != domain.domainName ) ) {
domains.Add( new umbraco.cms.businesslogic.web.Domain( domain.id ) );
}
}
CacheService.Instance.SetCacheValue( CacheKey, domains );
}
return domains.Where( d => d.RootNodeId == nodeId ).ToArray();
}
public static void InvalidateCache() {
CacheService.Instance.Invalidate( CacheKey );
}
}
} |
Edit assembly description to make xml compliant for nuspec output. | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Crosscutter")]
[assembly: AssemblyDescription(".NET extensions, safety & convenience methods for known types.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daryl Benzel")]
[assembly: AssemblyProduct("Crosscutter")]
[assembly: AssemblyCopyright("Copyright © Daryl Benzel 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bd03676e-4bbc-4e8e-9f00-a3e2ae2d2b9d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Crosscutter")]
[assembly: AssemblyDescription(".NET extensions, safety & convenience methods for known types.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daryl Benzel")]
[assembly: AssemblyProduct("Crosscutter")]
[assembly: AssemblyCopyright("Copyright © Daryl Benzel 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bd03676e-4bbc-4e8e-9f00-a3e2ae2d2b9d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0")]
|
Change FilterNumber to PhoneNumber so that it has the same name as the database field | using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Rellaid.Dto
{
[DataContract]
public class InboundQueueDistributorDto
{
[DataMember]
public string FilterNumber { get; set; }
[DataMember]
public int RungCount { get; set; }
}
}
| using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Rellaid.Dto
{
[DataContract]
public class InboundQueueDistributorDto
{
[DataMember]
public string PhoneNumber { get; set; }
[DataMember]
public int RungCount { get; set; }
}
}
|
Fix for NoVehicleUsage flag doing nothing | using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;
namespace RocketRegions.Model.Flag.Impl
{
public class NoVehiclesUsageFlag : BoolFlag
{
public override string Description => "Allow/Disallow usage of vehicles in region";
private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();
public override void UpdateState(List<UnturnedPlayer> players)
{
foreach (var player in players)
{
var id = PlayerUtil.GetId(player);
var veh = player.Player.movement.getVehicle();
var isInVeh = veh != null;
if (!_lastVehicleStates.ContainsKey(id))
_lastVehicleStates.Add(id, veh);
var wasDriving = _lastVehicleStates[id];
if (!isInVeh || wasDriving ||
!GetValueSafe(Region.GetGroup(player))) continue;
byte seat;
Vector3 point;
byte angle;
veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
}
}
public override void OnRegionEnter(UnturnedPlayer p)
{
//do nothing
}
public override void OnRegionLeave(UnturnedPlayer p)
{
//do nothing
}
}
} | using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;
namespace RocketRegions.Model.Flag.Impl
{
public class NoVehiclesUsageFlag : BoolFlag
{
public override string Description => "Allow/Disallow usage of vehicles in region";
private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();
public override void UpdateState(List<UnturnedPlayer> players)
{
foreach (var player in players)
{
var id = PlayerUtil.GetId(player);
var veh = player.Player.movement.getVehicle();
var isInVeh = veh != null;
if (!_lastVehicleStates.ContainsKey(id))
_lastVehicleStates.Add(id, veh);
var wasDriving = _lastVehicleStates[id];
if (!isInVeh || wasDriving ||
!GetValueSafe(Region.GetGroup(player))) continue;
byte seat;
Vector3 point;
byte angle;
veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
veh.removePlayer(seat, point, angle, true);
}
}
public override void OnRegionEnter(UnturnedPlayer p)
{
//do nothing
}
public override void OnRegionLeave(UnturnedPlayer p)
{
//do nothing
}
}
} |
Delete null check codes, it is not necessary because set owner object function bugs was solved. | using System.Collections.Generic;
using UnityEngine;
namespace LiteNetLibManager
{
public class DefaultInterestManager : BaseInterestManager
{
[Tooltip("Update every ? seconds")]
public float updateInterval = 1f;
private float updateCountDown = 0f;
private void Update()
{
if (!IsServer)
{
// Update at server only
return;
}
updateCountDown -= Time.unscaledDeltaTime;
if (updateCountDown <= 0f)
{
updateCountDown = updateInterval;
HashSet<uint> subscribings = new HashSet<uint>();
foreach (LiteNetLibPlayer player in Manager.GetPlayers())
{
if (!player.IsReady)
{
// Don't subscribe if player not ready
continue;
}
foreach (LiteNetLibIdentity playerObject in player.GetSpawnedObjects())
{
// Skip destroyed player object
if (playerObject == null)
continue;
// Update subscribing list, it will unsubscribe objects which is not in this list
subscribings.Clear();
foreach (LiteNetLibIdentity spawnedObject in Manager.Assets.GetSpawnedObjects())
{
if (ShouldSubscribe(playerObject, spawnedObject))
subscribings.Add(spawnedObject.ObjectId);
}
playerObject.UpdateSubscribings(subscribings);
}
}
}
}
}
}
| using System.Collections.Generic;
using UnityEngine;
namespace LiteNetLibManager
{
public class DefaultInterestManager : BaseInterestManager
{
[Tooltip("Update every ? seconds")]
public float updateInterval = 1f;
private float updateCountDown = 0f;
private void Update()
{
if (!IsServer)
{
// Update at server only
return;
}
updateCountDown -= Time.unscaledDeltaTime;
if (updateCountDown <= 0f)
{
updateCountDown = updateInterval;
HashSet<uint> subscribings = new HashSet<uint>();
foreach (LiteNetLibPlayer player in Manager.GetPlayers())
{
if (!player.IsReady)
{
// Don't subscribe if player not ready
continue;
}
foreach (LiteNetLibIdentity playerObject in player.GetSpawnedObjects())
{
// Update subscribing list, it will unsubscribe objects which is not in this list
subscribings.Clear();
foreach (LiteNetLibIdentity spawnedObject in Manager.Assets.GetSpawnedObjects())
{
if (ShouldSubscribe(playerObject, spawnedObject))
subscribings.Add(spawnedObject.ObjectId);
}
playerObject.UpdateSubscribings(subscribings);
}
}
}
}
}
}
|
Rename recommended mSpec convention to MspecExample for consistency | using Machine.Specifications;
namespace TestingFxTests
{
[Subject("Booleans")]
public class When_comparing_booleans
{
private static bool Subject;
private Establish context = () => Subject = false;
private Because of = () => Subject = true;
private It should_be_true = () => Subject.ShouldEqual(true);
}
} | using Machine.Specifications;
namespace TestingFxTests
{
[Subject("Mspec")]
public class MspecExample
{
private static bool Subject;
private Establish context = () => Subject = false;
private Because of = () => Subject = true;
private It should_be_true = () => Subject.ShouldEqual(true);
}
} |
Copy in Proxy code from ProxyMiddleware.cs, | using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Tiesmaster.Dcc
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(RunDccProxyAsync);
}
private static async Task RunDccProxyAsync(HttpContext context)
{
await context.Response.WriteAsync("Hello from DCC ;)");
}
}
} | using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Tiesmaster.Dcc
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(RunDccProxyAsync);
}
private static async Task RunDccProxyAsync(HttpContext context)
{
var requestMessage = new HttpRequestMessage();
var requestMethod = context.Request.Method;
if(!HttpMethods.IsGet(requestMethod) &&
!HttpMethods.IsHead(requestMethod) &&
!HttpMethods.IsDelete(requestMethod) &&
!HttpMethods.IsTrace(requestMethod))
{
var streamContent = new StreamContent(context.Request.Body);
requestMessage.Content = streamContent;
}
// Copy the request headers
foreach(var header in context.Request.Headers)
{
if(!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
{
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
}
}
requestMessage.Headers.Host = _options.Host + ":" + _options.Port;
var uriString = $"{_options.Scheme}://{_options.Host}:{_options.Port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
requestMessage.RequestUri = new Uri(uriString);
requestMessage.Method = new HttpMethod(context.Request.Method);
using(var responseMessage = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
context.Response.StatusCode = (int)responseMessage.StatusCode;
foreach(var header in responseMessage.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
foreach(var header in responseMessage.Content.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
// SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
context.Response.Headers.Remove("transfer-encoding");
await responseMessage.Content.CopyToAsync(context.Response.Body);
}
}
} |
Add one more discovery test | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel.Client;
using IdentityServer4.IntegrationTests.Clients;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace IdentityServer.IntegrationTests.Clients
{
public class DiscoveryClientTests
{
const string DiscoveryEndpoint = "https://server/.well-known/openid-configuration";
private readonly HttpClient _client;
private readonly HttpMessageHandler _handler;
public DiscoveryClientTests()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var server = new TestServer(builder);
_handler = server.CreateHandler();
_client = server.CreateClient();
}
[Fact]
public async Task Retrieving_discovery_document_should_succeed()
{
var client = new DiscoveryClient(DiscoveryEndpoint, _handler);
var doc = await client.GetAsync();
}
}
} | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using FluentAssertions;
using IdentityModel.Client;
using IdentityServer4.IntegrationTests.Clients;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace IdentityServer.IntegrationTests.Clients
{
public class DiscoveryClientTests
{
const string DiscoveryEndpoint = "https://server/.well-known/openid-configuration";
private readonly HttpClient _client;
private readonly HttpMessageHandler _handler;
public DiscoveryClientTests()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var server = new TestServer(builder);
_handler = server.CreateHandler();
_client = server.CreateClient();
}
[Fact]
public async Task Retrieving_discovery_document_should_succeed()
{
var client = new DiscoveryClient(DiscoveryEndpoint, _handler);
var doc = await client.GetAsync();
}
[Fact]
public async Task Discovery_document_should_have_expected_values()
{
var client = new DiscoveryClient(DiscoveryEndpoint, _handler);
var doc = await client.GetAsync();
// endpoints
doc.TokenEndpoint.Should().Be("https://server/connect/token");
doc.AuthorizationEndpoint.Should().Be("https://server/connect/authorize");
doc.IntrospectionEndpoint.Should().Be("https://server/connect/introspect");
doc.EndSessionEndpoint.Should().Be("https://server/connect/endsession");
// jwk
doc.Keys.Keys.Count.Should().Be(1);
doc.Keys.Keys.First().E.Should().NotBeNull();
doc.Keys.Keys.First().N.Should().NotBeNull();
}
}
} |
Change File Info repository save method, file info can now be updated. | using System.Threading.Tasks;
using AzureStorage.Tables;
using Microsoft.WindowsAzure.Storage.Table;
namespace CompetitionPlatform.Data.AzureRepositories.Project
{
public class ProjectFileInfoEntity : TableEntity, IProjectFileInfoData
{
public static string GeneratePartitionKey()
{
return "ProjectFileInfo";
}
public static string GenerateRowKey(string projectId)
{
return projectId;
}
public string ProjectId => RowKey;
public string FileName { get; set; }
public string ContentType { get; set; }
public static ProjectFileInfoEntity Create(IProjectFileInfoData src)
{
var result = new ProjectFileInfoEntity
{
PartitionKey = GeneratePartitionKey(),
RowKey = GenerateRowKey(src.ProjectId),
FileName = src.FileName,
ContentType = src.ContentType
};
return result;
}
}
public class ProjectFileInfoRepository : IProjectFileInfoRepository
{
private readonly IAzureTableStorage<ProjectFileInfoEntity> _projectFileInfoTableStorage;
public ProjectFileInfoRepository(IAzureTableStorage<ProjectFileInfoEntity> projectFileInfoTableStorage)
{
_projectFileInfoTableStorage = projectFileInfoTableStorage;
}
public async Task<IProjectFileInfoData> GetAsync(string projectId)
{
var partitionKey = ProjectFileInfoEntity.GeneratePartitionKey();
var rowKey = ProjectFileInfoEntity.GenerateRowKey(projectId);
return await _projectFileInfoTableStorage.GetDataAsync(partitionKey, rowKey);
}
public async Task SaveAsync(IProjectFileInfoData fileInfoData)
{
var newEntity = ProjectFileInfoEntity.Create(fileInfoData);
await _projectFileInfoTableStorage.InsertAsync(newEntity);
}
}
}
| using System.Threading.Tasks;
using AzureStorage.Tables;
using Microsoft.WindowsAzure.Storage.Table;
namespace CompetitionPlatform.Data.AzureRepositories.Project
{
public class ProjectFileInfoEntity : TableEntity, IProjectFileInfoData
{
public static string GeneratePartitionKey()
{
return "ProjectFileInfo";
}
public static string GenerateRowKey(string projectId)
{
return projectId;
}
public string ProjectId => RowKey;
public string FileName { get; set; }
public string ContentType { get; set; }
public static ProjectFileInfoEntity Create(IProjectFileInfoData src)
{
var result = new ProjectFileInfoEntity
{
PartitionKey = GeneratePartitionKey(),
RowKey = GenerateRowKey(src.ProjectId),
FileName = src.FileName,
ContentType = src.ContentType
};
return result;
}
}
public class ProjectFileInfoRepository : IProjectFileInfoRepository
{
private readonly IAzureTableStorage<ProjectFileInfoEntity> _projectFileInfoTableStorage;
public ProjectFileInfoRepository(IAzureTableStorage<ProjectFileInfoEntity> projectFileInfoTableStorage)
{
_projectFileInfoTableStorage = projectFileInfoTableStorage;
}
public async Task<IProjectFileInfoData> GetAsync(string projectId)
{
var partitionKey = ProjectFileInfoEntity.GeneratePartitionKey();
var rowKey = ProjectFileInfoEntity.GenerateRowKey(projectId);
return await _projectFileInfoTableStorage.GetDataAsync(partitionKey, rowKey);
}
public async Task SaveAsync(IProjectFileInfoData fileInfoData)
{
var newEntity = ProjectFileInfoEntity.Create(fileInfoData);
await _projectFileInfoTableStorage.InsertOrReplaceAsync(newEntity);
}
}
}
|
Change name of daabase for IoC | using NUnit.Framework;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
public class MyDatabaseSettings : IMyDatabaseSettings
{
public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\Tests.db;Version=3;New=True;BinaryGUID=False;";
}
}
| using NUnit.Framework;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
public class MyDatabaseSettings : IMyDatabaseSettings
{
public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\IoCTests.db;Version=3;New=True;BinaryGUID=False;";
}
}
|
Add useful overload for instruction remover | using Mono.Cecil;
using Mono.Cecil.Cil;
using System.Linq;
namespace Injector
{
public class InstructionRemover
{
public InstructionRemover(ModuleDefinition targetModule)
{
_targetModule = targetModule;
}
ModuleDefinition _targetModule;
public void ReplaceByNopAt(string typeName, string methodName, int instructionIndex)
{
var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
var methodBody = method.Body;
ReplaceByNop(methodBody, methodBody.Instructions[instructionIndex]);
}
public void ReplaceByNop(MethodBody methodBody, Instruction instruction)
{
methodBody.GetILProcessor().Replace(instruction, Instruction.Create(OpCodes.Nop));
}
public void ClearAllButLast(string typeName, string methodName)
{
var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
var methodBody = method.Body;
var methodILProcessor = methodBody.GetILProcessor();
for (int i = methodBody.Instructions.Count - 1; i > 0; i--)
{
methodILProcessor.Remove(methodBody.Instructions.First());
}
}
}
}
| using Mono.Cecil;
using Mono.Cecil.Cil;
using System.Linq;
namespace Injector
{
public class InstructionRemover
{
public InstructionRemover(ModuleDefinition targetModule)
{
_targetModule = targetModule;
}
ModuleDefinition _targetModule;
public void ReplaceByNopAt(string typeName, string methodName, int instructionIndex)
{
var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
var methodBody = method.Body;
ReplaceByNop(methodBody, methodBody.Instructions[instructionIndex]);
}
public void ReplaceByNop(MethodBody methodBody, Instruction instruction)
{
methodBody.GetILProcessor().Replace(instruction, Instruction.Create(OpCodes.Nop));
}
public void ClearAllButLast(string typeName, string methodName)
{
var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
var methodBody = method.Body;
ClearAllButLast(methodBody);
}
public void ClearAllButLast(MethodBody methodBody)
{
var methodILProcessor = methodBody.GetILProcessor();
for (int i = methodBody.Instructions.Count - 1; i > 0; i--)
{
methodILProcessor.Remove(methodBody.Instructions.First());
}
}
}
}
|
Fix connection bug for fresh environments | using Microsoft.Data.Tools.Schema.Sql.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
namespace Daves.DeepDataDuplicator.IntegrationTests
{
[TestClass]
public class SqlDatabaseSetup
{
public static readonly string ConnectionString;
static SqlDatabaseSetup()
{
using (var executionContext = SqlDatabaseTestClass.TestService.OpenExecutionContext())
{
ConnectionString = executionContext.Connection.ConnectionString;
}
}
[AssemblyInitialize]
public static void InitializeAssembly(TestContext testContext)
{
SqlDatabaseTestClass.TestService.DeployDatabaseProject();
using (var transaction = new TransactionScope())
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (IDbCommand command = connection.CreateCommand())
{
command.CommandText = DeepCopyGenerator.GenerateProcedure(
connection: connection,
rootTableName: "Nations");
command.ExecuteNonQuery();
}
}
transaction.Complete();
}
}
}
}
| using Microsoft.Data.Tools.Schema.Sql.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
namespace Daves.DeepDataDuplicator.IntegrationTests
{
[TestClass]
public class SqlDatabaseSetup
{
[AssemblyInitialize]
public static void InitializeAssembly(TestContext testContext)
{
SqlDatabaseTestClass.TestService.DeployDatabaseProject();
string connectionString;
using (var executionContext = SqlDatabaseTestClass.TestService.OpenExecutionContext())
{
connectionString = executionContext.Connection.ConnectionString;
}
using (var transaction = new TransactionScope())
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (IDbCommand command = connection.CreateCommand())
{
command.CommandText = DeepCopyGenerator.GenerateProcedure(
connection: connection,
rootTableName: "Nations");
command.ExecuteNonQuery();
}
}
transaction.Complete();
}
}
}
}
|
Update "Insert Include Field" example | using Aspose.Words.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aspose.Words.Examples.CSharp.Programming_Documents.Working_with_Fields
{
class InsertIncludeFieldWithoutDocumentBuilder
{
public static void Run()
{
// ExStart:InsertIncludeFieldWithoutDocumentBuilder
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this INCLUDETEXT field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an INCLUDETEXT field like this:
// { INCLUDETEXT "file path" }
// Create instance of FieldAsk class and lets build the above field code
FieldInclude fieldinclude = (FieldInclude)para.AppendField(FieldType.FieldInclude, false);
fieldinclude.BookmarkName = "bookmark";
fieldinclude.SourceFullName = dataDir + @"IncludeText.docx";
doc.FirstSection.Body.AppendChild(para);
// Finally update this TOA field
fieldinclude.Update();
dataDir = dataDir + "InsertIncludeFieldWithoutDocumentBuilder_out.doc";
doc.Save(dataDir);
// ExEnd:InsertIncludeFieldWithoutDocumentBuilder
Console.WriteLine("\nInclude field without using document builder inserted successfully.\nFile saved at " + dataDir);
}
}
}
| using Aspose.Words.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aspose.Words.Examples.CSharp.Programming_Documents.Working_with_Fields
{
class InsertIncludeFieldWithoutDocumentBuilder
{
public static void Run()
{
// ExStart:InsertIncludeFieldWithoutDocumentBuilder
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this INCLUDETEXT field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an INCLUDETEXT field like this:
// { INCLUDETEXT "file path" }
// Create instance of FieldAsk class and lets build the above field code
FieldInclude fieldinclude = (FieldInclude)para.AppendField(FieldType.FieldInclude, false);
fieldinclude.BookmarkName = "bookmark";
fieldinclude.SourceFullName = dataDir + @"IncludeText.docx";
doc.FirstSection.Body.AppendChild(para);
// Finally update this Include field
fieldinclude.Update();
dataDir = dataDir + "InsertIncludeFieldWithoutDocumentBuilder_out.doc";
doc.Save(dataDir);
// ExEnd:InsertIncludeFieldWithoutDocumentBuilder
Console.WriteLine("\nInclude field without using document builder inserted successfully.\nFile saved at " + dataDir);
}
}
}
|
Add the track number to the song | using System;
namespace Espera.Network
{
public class NetworkSong
{
public string Album { get; set; }
public string Artist { get; set; }
public TimeSpan Duration { get; set; }
public string Genre { get; set; }
public Guid Guid { get; set; }
public NetworkSongSource Source { get; set; }
public string Title { get; set; }
}
} | using System;
namespace Espera.Network
{
public class NetworkSong
{
public string Album { get; set; }
public string Artist { get; set; }
public TimeSpan Duration { get; set; }
public string Genre { get; set; }
public Guid Guid { get; set; }
public NetworkSongSource Source { get; set; }
public string Title { get; set; }
public int TrackNumber { get; set; }
}
} |
Add filter property to most played shows request. | namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base.Get;
using Enums;
using Objects.Basic;
using Objects.Get.Shows.Common;
using System.Collections.Generic;
internal class TraktShowsMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedShow>, TraktMostPlayedShow>
{
internal TraktShowsMostPlayedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; }
internal TraktPeriod? Period { get; set; }
protected override IDictionary<string, object> GetUriPathParameters()
{
var uriParams = base.GetUriPathParameters();
if (Period.HasValue && Period.Value != TraktPeriod.Unspecified)
uriParams.Add("period", Period.Value.AsString());
return uriParams;
}
protected override string UriTemplate => "shows/played{/period}{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
| namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base;
using Base.Get;
using Enums;
using Objects.Basic;
using Objects.Get.Shows.Common;
using System.Collections.Generic;
internal class TraktShowsMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedShow>, TraktMostPlayedShow>
{
internal TraktShowsMostPlayedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; }
internal TraktPeriod? Period { get; set; }
protected override IDictionary<string, object> GetUriPathParameters()
{
var uriParams = base.GetUriPathParameters();
if (Period.HasValue && Period.Value != TraktPeriod.Unspecified)
uriParams.Add("period", Period.Value.AsString());
return uriParams;
}
protected override string UriTemplate => "shows/played{/period}{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktShowFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
|
Remove editor completely when adding a fieldset to the layout editor. | using Orchard.Layouts.Helpers;
using Orchard.Layouts.Elements;
namespace Orchard.DynamicForms.Elements {
public class Fieldset : Container {
public override string Category {
get { return "Forms"; }
}
public string Legend {
get { return this.Retrieve(f => f.Legend); }
set { this.Store(f => f.Legend, value); }
}
public Form Form {
get {
var parent = Container;
while (parent != null) {
var form = parent as Form;
if (form != null)
return form;
parent = parent.Container;
}
return null;
}
}
}
} | using Orchard.Layouts.Helpers;
using Orchard.Layouts.Elements;
namespace Orchard.DynamicForms.Elements {
public class Fieldset : Container {
public override string Category {
get { return "Forms"; }
}
public override bool HasEditor {
get { return false; }
}
public string Legend {
get { return this.Retrieve(f => f.Legend); }
set { this.Store(f => f.Legend, value); }
}
public Form Form {
get {
var parent = Container;
while (parent != null) {
var form = parent as Form;
if (form != null)
return form;
parent = parent.Container;
}
return null;
}
}
}
} |
Convert scrap errors to warnings | using System;
using System.IO;
using System.Management.Automation;
namespace Microsoft.PowerShell.CrossCompatibility.Commands
{
internal static class CommandUtilities
{
private const string COMPATIBILITY_ERROR_ID = "CompatibilityAnalysisError";
public const string MODULE_PREFIX = "PSCompatibility";
public static void WriteExceptionAsError(
this Cmdlet cmdlet,
Exception exception,
string errorId = COMPATIBILITY_ERROR_ID,
ErrorCategory errorCategory = ErrorCategory.ReadError,
object targetObject = null)
{
cmdlet.WriteError(CreateCompatibilityErrorRecord(exception, errorId, errorCategory, targetObject));
}
public static string GetNormalizedAbsolutePath(this PSCmdlet cmdlet, string path)
{
if (Path.IsPathRooted(path))
{
return path;
}
return cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
}
private static ErrorRecord CreateCompatibilityErrorRecord(
Exception e,
string errorId = COMPATIBILITY_ERROR_ID,
ErrorCategory errorCategory = ErrorCategory.ReadError,
object targetObject = null)
{
return new ErrorRecord(
e,
errorId,
errorCategory,
targetObject);
}
}
} | using System;
using System.IO;
using System.Management.Automation;
namespace Microsoft.PowerShell.CrossCompatibility.Commands
{
internal static class CommandUtilities
{
private const string COMPATIBILITY_ERROR_ID = "CompatibilityAnalysisError";
public const string MODULE_PREFIX = "PSCompatibility";
public static void WriteExceptionAsWarning(
this Cmdlet cmdlet,
Exception exception,
string errorId = COMPATIBILITY_ERROR_ID,
ErrorCategory errorCategory = ErrorCategory.ReadError,
object targetObject = null)
{
cmdlet.WriteWarning(exception.ToString());
}
public static string GetNormalizedAbsolutePath(this PSCmdlet cmdlet, string path)
{
if (Path.IsPathRooted(path))
{
return path;
}
return cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
}
private static ErrorRecord CreateCompatibilityErrorRecord(
Exception e,
string errorId = COMPATIBILITY_ERROR_ID,
ErrorCategory errorCategory = ErrorCategory.ReadError,
object targetObject = null)
{
return new ErrorRecord(
e,
errorId,
errorCategory,
targetObject);
}
}
} |
Check associated object parameter for null. Throw ArgumentNullException if it is null | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Windows.UI.Xaml;
namespace Microsoft.Xaml.Interactivity
{
/// <summary>
/// A base class for behaviors, implementing the basic plumbing of IBehavior
/// </summary>
public abstract class Behavior : DependencyObject, IBehavior
{
public DependencyObject AssociatedObject { get; private set; }
public void Attach(DependencyObject associatedObject)
{
AssociatedObject = associatedObject;
OnAttached();
}
public void Detach()
{
OnDetaching();
}
protected virtual void OnAttached()
{
}
protected virtual void OnDetaching()
{
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Windows.UI.Xaml;
namespace Microsoft.Xaml.Interactivity
{
/// <summary>
/// A base class for behaviors, implementing the basic plumbing of IBehavior
/// </summary>
public abstract class Behavior : DependencyObject, IBehavior
{
public DependencyObject AssociatedObject { get; private set; }
public void Attach(DependencyObject associatedObject)
{
if (associatedObject == null) throw new ArgumentNullException(nameof(associatedObject));
AssociatedObject = associatedObject;
OnAttached();
}
public void Detach()
{
OnDetaching();
}
protected virtual void OnAttached()
{
}
protected virtual void OnDetaching()
{
}
}
}
|
Fix default value in settings window. | using Fiddler;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace VCSJones.FiddlerCert
{
public class SettingsModel : INotifyPropertyChanged
{
private bool _checkForUpdates;
private RelayCommand _saveCommand, _cancelCommand;
public Version LatestVersion => CertificateInspector.LatestVersion?.Item1;
public Version CurrentVersion => typeof(CertInspector).Assembly.GetName().Version;
public bool CheckForUpdates
{
get
{
return _checkForUpdates;
}
set
{
_checkForUpdates = value;
OnPropertyChanged();
}
}
public RelayCommand SaveCommand
{
get
{
return _saveCommand;
}
set
{
_saveCommand = value;
OnPropertyChanged();
}
}
public RelayCommand CancelCommand
{
get
{
return _cancelCommand;
}
set
{
_cancelCommand = value;
OnPropertyChanged();
}
}
public SettingsModel()
{
SaveCommand = new RelayCommand(_ =>
{
FiddlerApplication.Prefs.SetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, CheckForUpdates);
CloseRequest?.Invoke();
});
CancelCommand = new RelayCommand(_ =>
{
CloseRequest?.Invoke();
});
CheckForUpdates = FiddlerApplication.Prefs.GetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, CheckForUpdates);
}
public event PropertyChangedEventHandler PropertyChanged;
public event Action CloseRequest;
public void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| using Fiddler;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace VCSJones.FiddlerCert
{
public class SettingsModel : INotifyPropertyChanged
{
private bool _checkForUpdates;
private RelayCommand _saveCommand, _cancelCommand;
public Version LatestVersion => CertificateInspector.LatestVersion?.Item1;
public Version CurrentVersion => typeof(CertInspector).Assembly.GetName().Version;
public bool CheckForUpdates
{
get
{
return _checkForUpdates;
}
set
{
_checkForUpdates = value;
OnPropertyChanged();
}
}
public RelayCommand SaveCommand
{
get
{
return _saveCommand;
}
set
{
_saveCommand = value;
OnPropertyChanged();
}
}
public RelayCommand CancelCommand
{
get
{
return _cancelCommand;
}
set
{
_cancelCommand = value;
OnPropertyChanged();
}
}
public SettingsModel()
{
SaveCommand = new RelayCommand(_ =>
{
FiddlerApplication.Prefs.SetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, CheckForUpdates);
CloseRequest?.Invoke();
});
CancelCommand = new RelayCommand(_ =>
{
CloseRequest?.Invoke();
});
CheckForUpdates = FiddlerApplication.Prefs.GetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, false);
}
public event PropertyChangedEventHandler PropertyChanged;
public event Action CloseRequest;
public void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
Make addin version assembly to 0.1. | using Mono.Addins;
using Mono.Addins.Description;
[assembly: Addin(
Id = "jzeferino.XSAddin",
Namespace = "jzeferino.XSAddin",
Version = "0.0.1"
)]
[assembly: AddinName("jzeferino.XSAddin")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("This add-in let you create a Xamarin Cross Platform solution (Xamarin.Native) or (Xamarin.Forms)." +
"When creating the project the addin will show you a custom wizard wich the user can select the application name, the application identifier and if he wants, .gitignore, readme and cake." +
"It already creates some PCL projects to allow the shared code to be separated in different layers using MVVM pattern." +
"It also allows you to create some file templates.")]
[assembly: AddinAuthor("jzeferino")]
[assembly: AddinUrl("https://github.com/jzeferino/jzeferino.XSAddin")]
| using Mono.Addins;
using Mono.Addins.Description;
[assembly: Addin(
Id = "jzeferino.XSAddin",
Namespace = "jzeferino.XSAddin",
Version = "0.1"
)]
[assembly: AddinName("jzeferino.XSAddin")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("This add-in let you create a Xamarin Cross Platform solution (Xamarin.Native) or (Xamarin.Forms)." +
"When creating the project the addin will show you a custom wizard wich the user can select the application name, the application identifier and if he wants, .gitignore, readme and cake." +
"It already creates some PCL projects to allow the shared code to be separated in different layers using MVVM pattern." +
"It also allows you to create some file templates.")]
[assembly: AddinAuthor("jzeferino")]
[assembly: AddinUrl("https://github.com/jzeferino/jzeferino.XSAddin")]
|
Fix MemberwiseClone calls being generated for .GetEnumerator() on dictionary keys/values collections. | using System;
using System.Collections;
using System.Collections.Generic;
using JSIL.Meta;
using JSIL.Proxy;
namespace JSIL.Proxies {
[JSProxy(
new[] {
"System.Collections.ArrayList",
"System.Collections.Hashtable",
"System.Collections.Generic.List`1",
"System.Collections.Generic.Dictionary`2",
"System.Collections.Generic.Stack`1",
"System.Collections.Generic.Queue`1",
"System.Collections.Generic.HashSet`1",
},
memberPolicy: JSProxyMemberPolicy.ReplaceNone,
inheritable: false
)]
public abstract class CollectionProxy<T> : IEnumerable {
[JSIsPure]
[JSResultIsNew]
System.Collections.IEnumerator IEnumerable.GetEnumerator () {
throw new InvalidOperationException();
}
[JSIsPure]
[JSResultIsNew]
public AnyType GetEnumerator () {
throw new InvalidOperationException();
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using JSIL.Meta;
using JSIL.Proxy;
namespace JSIL.Proxies {
[JSProxy(
new[] {
"System.Collections.ArrayList",
"System.Collections.Hashtable",
"System.Collections.Generic.List`1",
"System.Collections.Generic.Dictionary`2",
"System.Collections.Generic.Stack`1",
"System.Collections.Generic.Queue`1",
"System.Collections.Generic.HashSet`1",
"System.Collections.Hashtable/KeyCollection",
"System.Collections.Hashtable/ValueCollection",
"System.Collections.Generic.Dictionary`2/KeyCollection",
"System.Collections.Generic.Dictionary`2/ValueCollection"
},
memberPolicy: JSProxyMemberPolicy.ReplaceNone,
inheritable: false
)]
public abstract class CollectionProxy<T> : IEnumerable {
[JSIsPure]
[JSResultIsNew]
System.Collections.IEnumerator IEnumerable.GetEnumerator () {
throw new InvalidOperationException();
}
[JSIsPure]
[JSResultIsNew]
public AnyType GetEnumerator () {
throw new InvalidOperationException();
}
}
}
|
Change artist in tags test | using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema.Tags;
namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
[TestFixture]
public class ArtistTagsTests
{
[Test]
public void Can_hit_endpoint()
{
ArtistTags tags = Api<ArtistTags>.Create
.WithParameter("artistId", "1")
.Please();
Assert.That(tags, Is.Not.Null);
Assert.That(tags.TagList.Count, Is.GreaterThan(0));
Assert.That(tags.TagList.FirstOrDefault().Id, Is.Not.Empty);
Assert.That(tags.TagList.Where(x => x.Id == "rock").FirstOrDefault().Text, Is.EqualTo("rock"));
}
[Test]
public void Can_hit_endpoint_with_paging()
{
ArtistTags artistBrowse = Api<ArtistTags>.Create
.WithParameter("artistId", "1")
.WithParameter("page", "2")
.WithParameter("pageSize", "1")
.Please();
Assert.That(artistBrowse, Is.Not.Null);
Assert.That(artistBrowse.Page, Is.EqualTo(2));
Assert.That(artistBrowse.PageSize, Is.EqualTo(1));
}
}
} | using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema.Tags;
namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
[TestFixture]
public class ArtistTagsTests
{
[Test]
public void Can_hit_endpoint()
{
ArtistTags tags = Api<ArtistTags>.Create
.WithParameter("artistId", "1")
.Please();
Assert.That(tags, Is.Not.Null);
Assert.That(tags.TagList.Count, Is.GreaterThan(0));
Assert.That(tags.TagList.FirstOrDefault().Id, Is.Not.Empty);
Assert.That(tags.TagList.Where(x => x.Id == "rock").FirstOrDefault().Text, Is.EqualTo("rock"));
}
[Test]
public void Can_hit_endpoint_with_paging()
{
ArtistTags artistBrowse = Api<ArtistTags>.Create
.WithParameter("artistId", "2")
.WithParameter("page", "2")
.WithParameter("pageSize", "1")
.Please();
Assert.That(artistBrowse, Is.Not.Null);
Assert.That(artistBrowse.Page, Is.EqualTo(2));
Assert.That(artistBrowse.PageSize, Is.EqualTo(1));
}
}
} |
Make beauty to extensions API | using Photosphere.Mapping.Static;
namespace Photosphere.Mapping.Extensions
{
public static class MappingObjectExtensions
{
/// <summary> Map from source to existent object target</summary>
public static void MapTo<TSource, TTarget>(this TSource source, TTarget target)
where TTarget : class, new()
{
StaticMapper<TSource, TTarget>.Map(source, target);
}
/// <summary> Map from source to new object of TTarget</summary>
public static TTarget Map<TSource, TTarget>(this TSource source)
where TTarget : class, new()
{
return StaticMapper<TSource, TTarget>.Map(source);
}
/// <summary> Map from object source to existent object target</summary>
public static void MapToObject(this object source, object target)
{
StaticMapper.Map(source, target);
}
/// <summary> Map from object source to new object of TTarget</summary>
public static TTarget MapObject<TTarget>(this object source)
where TTarget : new()
{
return StaticMapper.Map<TTarget>(source);
}
}
} | using Photosphere.Mapping.Static;
namespace Photosphere.Mapping.Extensions
{
public static class MappingObjectExtensions
{
/// <summary> Map from source to existent object target</summary>
public static void MapTo<TSource, TTarget>(this TSource source, TTarget target)
where TTarget : class, new()
{
StaticMapper<TSource, TTarget>.Map(source, target);
}
/// <summary> Map from object source to existent object target</summary>
public static void MapToObject(this object source, object target)
{
StaticMapper.Map(source, target);
}
/// <summary> Map from source to new object of TTarget</summary>
public static TTarget Map<TSource, TTarget>(this TSource source)
where TTarget : class, new()
{
return StaticMapper<TSource, TTarget>.Map(source);
}
/// <summary> Map from object source to new object of TTarget</summary>
public static TTarget MapObject<TTarget>(this object source)
where TTarget : new()
{
return StaticMapper.Map<TTarget>(source);
}
}
} |
Update the validation messages for uln and cost | using FluentValidation;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.Validation
{
public sealed class ApprenticeshipViewModelValidator : AbstractValidator<ApprenticeshipViewModel>
{
public ApprenticeshipViewModelValidator()
{
RuleFor(x => x.ULN).Matches("^$|^[1-9]{1}[0-9]{9}$").WithMessage("'ULN' is not in the correct format.");
RuleFor(x => x.Cost).Matches("^$|^[1-9]{1}[0-9]*$").WithMessage("Cost is not in the correct format");
}
}
} | using FluentValidation;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.Validation
{
public sealed class ApprenticeshipViewModelValidator : AbstractValidator<ApprenticeshipViewModel>
{
public ApprenticeshipViewModelValidator()
{
RuleFor(x => x.ULN).Matches("^$|^[1-9]{1}[0-9]{9}$").WithMessage("Please enter the unique learner number - this should be 10 digits long.");
RuleFor(x => x.Cost).Matches("^$|^[1-9]{1}[0-9]*$").WithMessage("Please enter the cost in whole pounds. For example, for £1500 you should enter 1500.");
}
}
} |
Add InsightsApiKey to conf file. | using System;
namespace Toggl.Phoebe
{
public static class Build
{
#warning Please fill in build settings and make git assume this file is unchanged.
#region Phoebe build config
public static readonly Uri ApiUrl = new Uri ("https://toggl.com/api/");
public static readonly Uri ReportsApiUrl = new Uri ("https://toggl.com/reports/api/");
public static readonly Uri PrivacyPolicyUrl = new Uri ("https://toggl.com/privacy");
public static readonly Uri TermsOfServiceUrl = new Uri ("https://toggl.com/terms");
public static readonly string GoogleAnalyticsId = "";
public static readonly int GoogleAnalyticsPlanIndex = 1;
public static readonly int GoogleAnalyticsExperimentIndex = 2;
#endregion
#region Joey build configuration
#if __ANDROID__
public static readonly string AppIdentifier = "TogglJoey";
public static readonly string GcmSenderId = "";
public static readonly string BugsnagApiKey = "";
public static readonly string GooglePlayUrl = "https://play.google.com/store/apps/details?id=com.toggl.timer";
#endif
#endregion
#region Ross build configuration
#if __IOS__
public static readonly string AppStoreUrl = "itms-apps://itunes.com/apps/toggl/toggltimer";
public static readonly string AppIdentifier = "TogglRoss";
public static readonly string BugsnagApiKey = "";
public static readonly string GoogleOAuthClientId = "";
#endif
#endregion
}
} | using System;
namespace Toggl.Phoebe
{
public static class Build
{
#warning Please fill in build settings and make git assume this file is unchanged.
#region Phoebe build config
public static readonly Uri ApiUrl = new Uri ("https://toggl.com/api/");
public static readonly Uri ReportsApiUrl = new Uri ("https://toggl.com/reports/api/");
public static readonly Uri PrivacyPolicyUrl = new Uri ("https://toggl.com/privacy");
public static readonly Uri TermsOfServiceUrl = new Uri ("https://toggl.com/terms");
public static readonly string GoogleAnalyticsId = "";
public static readonly int GoogleAnalyticsPlanIndex = 1;
public static readonly int GoogleAnalyticsExperimentIndex = 2;
#endregion
#region Joey build configuration
#if __ANDROID__
public static readonly string AppIdentifier = "TogglJoey";
public static readonly string GcmSenderId = "";
public static readonly string BugsnagApiKey = "";
public static readonly string XamInsightsApiKey = "";
public static readonly string GooglePlayUrl = "https://play.google.com/store/apps/details?id=com.toggl.timer";
#endif
#endregion
#region Ross build configuration
#if __IOS__
public static readonly string AppStoreUrl = "itms-apps://itunes.com/apps/toggl/toggltimer";
public static readonly string AppIdentifier = "TogglRoss";
public static readonly string BugsnagApiKey = "";
public static readonly string GoogleOAuthClientId = "";
#endif
#endregion
}
}
|
Add precision and scale to avatar zoom scale | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace GRA.Data.Model
{
public class AvatarLayer : Abstract.BaseDbEntity
{
[Required]
public int SiteId { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
public int Position { get; set; }
public bool CanBeEmpty { get; set; }
public int GroupId { get; set; }
public int SortOrder { get; set; }
public bool DefaultLayer { get; set; }
public bool ShowItemSelector { get; set; }
public bool ShowColorSelector { get; set; }
[MaxLength(255)]
public string Icon { get; set; }
public decimal ZoomScale { get; set; }
public int ZoomYOffset { get; set; }
public ICollection<AvatarColor> AvatarColors { get; set; }
public ICollection<AvatarItem> AvatarItems { get; set; }
}
}
| using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace GRA.Data.Model
{
public class AvatarLayer : Abstract.BaseDbEntity
{
[Required]
public int SiteId { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
public int Position { get; set; }
public bool CanBeEmpty { get; set; }
public int GroupId { get; set; }
public int SortOrder { get; set; }
public bool DefaultLayer { get; set; }
public bool ShowItemSelector { get; set; }
public bool ShowColorSelector { get; set; }
[MaxLength(255)]
public string Icon { get; set; }
[Column(TypeName = "decimal(4,2)")]
public decimal ZoomScale { get; set; }
public int ZoomYOffset { get; set; }
public ICollection<AvatarColor> AvatarColors { get; set; }
public ICollection<AvatarItem> AvatarItems { get; set; }
}
}
|
Test requires longer to run on slower aws build agents | using System;
using Amazon.SQS.Model;
using JustEat.Testing;
using NSubstitute;
using NUnit.Framework;
namespace AwsTools.UnitTests.SqsNotificationListener
{
public class WhenThereAreExceptionsInSqsCalling : BaseQueuePollingTest
{
private int _sqsCallCounter;
protected override void Given()
{
TestWaitTime = 50;
base.Given();
Sqs.ReceiveMessage(Arg.Any<ReceiveMessageRequest>())
.Returns(x => { throw new Exception(); })
.AndDoes(x => { _sqsCallCounter++; });
}
[Then]
public void QueueIsPolledMoreThanOnce()
{
Assert.Greater(_sqsCallCounter, 1);
}
}
} | using System;
using Amazon.SQS.Model;
using JustEat.Testing;
using NSubstitute;
using NUnit.Framework;
namespace AwsTools.UnitTests.SqsNotificationListener
{
public class WhenThereAreExceptionsInSqsCalling : BaseQueuePollingTest
{
private int _sqsCallCounter;
protected override void Given()
{
TestWaitTime = 1000;
base.Given();
Sqs.ReceiveMessage(Arg.Any<ReceiveMessageRequest>())
.Returns(x => { throw new Exception(); })
.AndDoes(x => { _sqsCallCounter++; });
}
[Then]
public void QueueIsPolledMoreThanOnce()
{
Assert.Greater(_sqsCallCounter, 1);
}
}
} |
Use lambda spec for method | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Localisation;
using static osu.Game.Users.User;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public class UserHistoryGraph : UserGraph<DateTime, long>
{
private readonly LocalisableString tooltipCounterName;
[CanBeNull]
public UserHistoryCount[] Values
{
set => Data = value?.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
}
public UserHistoryGraph(LocalisableString tooltipCounterName)
{
this.tooltipCounterName = tooltipCounterName;
}
protected override float GetDataPointHeight(long playCount) => playCount;
protected override UserGraphTooltipContent GetTooltipContent(DateTime date, long playCount)
{
return new UserGraphTooltipContent(
tooltipCounterName,
playCount.ToLocalisableString("N0"),
date.ToLocalisableString("MMMM yyyy"));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Localisation;
using static osu.Game.Users.User;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public class UserHistoryGraph : UserGraph<DateTime, long>
{
private readonly LocalisableString tooltipCounterName;
[CanBeNull]
public UserHistoryCount[] Values
{
set => Data = value?.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
}
public UserHistoryGraph(LocalisableString tooltipCounterName)
{
this.tooltipCounterName = tooltipCounterName;
}
protected override float GetDataPointHeight(long playCount) => playCount;
protected override UserGraphTooltipContent GetTooltipContent(DateTime date, long playCount) =>
new UserGraphTooltipContent(
tooltipCounterName,
playCount.ToLocalisableString("N0"),
date.ToLocalisableString("MMMM yyyy"));
}
}
|
Remove dot net core dependency | using Microsoft.AspNetCore.Mvc;
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class GetApprenticeshipRequest
{
[FromQuery]
public long? AccountId { get; set; }
[FromQuery]
public long? ProviderId { get; set; }
[FromQuery]
public int PageNumber { get; set; }
[FromQuery]
public int PageItemCount { get; set; }
[FromQuery]
public string SortField { get; set; }
[FromQuery]
public bool ReverseSort { get; set; }
}
} |
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class GetApprenticeshipRequest
{
public long? AccountId { get; set; }
public long? ProviderId { get; set; }
public int PageNumber { get; set; }
public int PageItemCount { get; set; }
public string SortField { get; set; }
public bool ReverseSort { get; set; }
}
} |
Move REcttransform scaler into mrtk namespace | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
/// <summary>
/// RectTransforms do not scale 3d objects (such as unit cubes) to fit within their bounds.
/// This helper class will apply a scale to fit a unit cube into the bounds specified by the RectTransform.
/// The Z component is scaled to the min of the X and Y components.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public class RectTransformCubeScaler : MonoBehaviour
{
private RectTransform rectTransform;
private Vector2 prevRectSize = default;
private void Start()
{
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
var size = rectTransform.rect.size;
if (prevRectSize != size)
{
prevRectSize = size;
this.transform.localScale = new Vector3(size.x, size.y, Mathf.Min(size.x, size.y));
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// RectTransforms do not scale 3d objects (such as unit cubes) to fit within their bounds.
/// This helper class will apply a scale to fit a unit cube into the bounds specified by the RectTransform.
/// The Z component is scaled to the min of the X and Y components.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public class RectTransformCubeScaler : MonoBehaviour
{
private RectTransform rectTransform;
private Vector2 prevRectSize = default;
private void Start()
{
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
var size = rectTransform.rect.size;
if (prevRectSize != size)
{
prevRectSize = size;
this.transform.localScale = new Vector3(size.x, size.y, Mathf.Min(size.x, size.y));
}
}
}
}
|
Fix bug with query after json ignoring user doc contact challenges. | using System;
using System.Linq;
using System.Threading.Tasks;
using ArangoDB.Client;
using EventSourced.Net.ReadModel.Users.Internal.Documents;
namespace EventSourced.Net.ReadModel.Users.Internal.Queries
{
public class UserDocumentByContactChallengeCorrelationId : IQuery<Task<UserDocument>>
{
public Guid CorrelationId { get; }
internal UserDocumentByContactChallengeCorrelationId(Guid correlationId) {
CorrelationId = correlationId;
}
}
public class HandleUserDocumentByContactChallengeCorrelationId : IHandleQuery<UserDocumentByContactChallengeCorrelationId, Task<UserDocument>>
{
private IArangoDatabase Db { get; }
public HandleUserDocumentByContactChallengeCorrelationId(IArangoDatabase db) {
Db = db;
}
public Task<UserDocument> Handle(UserDocumentByContactChallengeCorrelationId query) {
UserDocument user = Db.Query<UserDocument>()
.SingleOrDefault(x => AQL.In(query.CorrelationId, x.ContactChallenges.Select(y => y.CorrelationId)));
return Task.FromResult(user);
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using ArangoDB.Client;
using EventSourced.Net.ReadModel.Users.Internal.Documents;
namespace EventSourced.Net.ReadModel.Users.Internal.Queries
{
public class UserDocumentByContactChallengeCorrelationId : IQuery<Task<UserDocument>>
{
public Guid CorrelationId { get; }
internal UserDocumentByContactChallengeCorrelationId(Guid correlationId) {
CorrelationId = correlationId;
}
}
public class HandleUserDocumentByContactChallengeCorrelationId : IHandleQuery<UserDocumentByContactChallengeCorrelationId, Task<UserDocument>>
{
private IArangoDatabase Db { get; }
public HandleUserDocumentByContactChallengeCorrelationId(IArangoDatabase db) {
Db = db;
}
public Task<UserDocument> Handle(UserDocumentByContactChallengeCorrelationId query) {
UserDocument user = Db.Query<UserDocument>()
.SingleOrDefault(x =>
AQL.In(query.CorrelationId, x.ContactEmailChallenges.Select(y => y.CorrelationId)) ||
AQL.In(query.CorrelationId, x.ContactSmsChallenges.Select(y => y.CorrelationId)));
return Task.FromResult(user);
}
}
}
|
Add a missing event type | using Newtonsoft.Json;
namespace SyncTrayzor.Syncthing.ApiClient
{
[JsonConverter(typeof(DefaultingStringEnumConverter))]
public enum EventType
{
Unknown,
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
FolderErrors,
FolderScanProgress,
DevicePaused,
DeviceResumed,
LoginAttempt,
ListenAddressChanged,
RelayStateChanged,
ExternalPortMappingChanged,
}
}
| using Newtonsoft.Json;
namespace SyncTrayzor.Syncthing.ApiClient
{
[JsonConverter(typeof(DefaultingStringEnumConverter))]
public enum EventType
{
Unknown,
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
FolderErrors,
FolderScanProgress,
DevicePaused,
DeviceResumed,
LoginAttempt,
ListenAddressChanged,
RelayStateChanged,
ExternalPortMappingChanged,
ListenAddressesChanged,
}
}
|
Add limiter to JsonArrayField min and max properties | namespace Gigobyte.Mockaroo.Fields
{
public partial class JSONArrayField
{
public int Min { get; set; } = 1;
public int Max { get; set; } = 5;
public override string ToJson()
{
return $"{base.BaseJson()},\"minItems\":{Min},\"maxItems\":{Max}}}";
}
}
} | namespace Gigobyte.Mockaroo.Fields
{
public partial class JSONArrayField
{
public int Min
{
get { return _min; }
set { _min = value.Between(0, 100); }
}
public int Max
{
get { return _max; }
set { _max = value.Between(0, 100); }
}
public override string ToJson()
{
return $"{base.BaseJson()},\"minItems\":{Min},\"maxItems\":{Max}}}";
}
#region Private Members
private int _min = 1, _max = 5;
#endregion Private Members
}
} |
Add edit / remove buttons to each file on experience page | @model Badges.Models.Shared.ExperienceViewModel
<div id="work-container" class="container work">
<div class="row">
@foreach (var work in @Model.SupportingWorks)
{
@* <div class="col-md-4"> *@
<div class="@work.Type work-item-box">
@Html.Partial("_ViewWork", work)
<p>@work.Description</p>
</div>
@* </div> *@
}
</div>
</div>
| @model Badges.Models.Shared.ExperienceViewModel
<div id="work-container" class="container work">
<div class="row">
@foreach (var work in @Model.SupportingWorks)
{
@* <div class="col-md-4"> *@
<div class="@work.Type work-item-box">
@Html.Partial("_ViewWork", work)
<p>@work.Description<br />
<a href="#edit">
<i class="icon-edit"></i>
</a>
<a href="#delete">
<i class="icon-remove"></i>
</a>
</p>
<div></div>
</div>
@* </div> *@
}
</div>
</div>
|
Make Shuffle() returns IList to avoid delayed execution. | //
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace AIWolf.Lib
{
#if JHELP
/// <summary>
/// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
/// </summary>
#else
/// <summary>
/// Defines extension method to shuffle what implements IEnumerable interface.
/// </summary>
#endif
public static class ShuffleExtensions
{
#if JHELP
/// <summary>
/// IEnumerableをシャッフルしたものを返す
/// </summary>
/// <typeparam name="T">IEnumerableの要素の型</typeparam>
/// <param name="s">TのIEnumerable</param>
/// <returns>シャッフルされたIEnumerable</returns>
#else
/// <summary>
/// Returns shuffled IEnumerable of T.
/// </summary>
/// <typeparam name="T">Type of element of IEnumerable.</typeparam>
/// <param name="s">IEnumerable of T.</param>
/// <returns>Shuffled IEnumerable of T.</returns>
#endif
public static IOrderedEnumerable<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid());
}
}
| //
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace AIWolf.Lib
{
#if JHELP
/// <summary>
/// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
/// </summary>
#else
/// <summary>
/// Defines extension method to shuffle what implements IEnumerable interface.
/// </summary>
#endif
public static class ShuffleExtensions
{
#if JHELP
/// <summary>
/// IEnumerableをシャッフルしたIListを返す
/// </summary>
/// <typeparam name="T">IEnumerableの要素の型</typeparam>
/// <param name="s">TのIEnumerable</param>
/// <returns>シャッフルされたTのIList</returns>
#else
/// <summary>
/// Returns shuffled IList of T.
/// </summary>
/// <typeparam name="T">Type of element of IEnumerable.</typeparam>
/// <param name="s">IEnumerable of T.</param>
/// <returns>Shuffled IList of T.</returns>
#endif
public static IList<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid()).ToList();
}
}
|
Add comments for internal API. | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
namespace MsgPack.Serialization
{
/// <summary>
/// Define options of <see cref="SerializationMethodGeneratorManager"/>
/// </summary>
public enum SerializationMethodGeneratorOption
{
#if !SILVERLIGHT
/// <summary>
/// The generated method IL can be dumped to the current directory.
/// </summary>
CanDump,
/// <summary>
/// The entire generated method can be collected by GC when it is no longer used.
/// </summary>
CanCollect,
#endif
/// <summary>
/// Prefer performance. This options is default.
/// </summary>
Fast
}
}
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using System.ComponentModel;
namespace MsgPack.Serialization
{
/// <summary>
/// Define options of <see cref="SerializationMethodGeneratorManager"/>
/// </summary>
public enum SerializationMethodGeneratorOption
{
#if !SILVERLIGHT
/// <summary>
/// The generated method IL can be dumped to the current directory.
/// It is intended for the runtime, you cannot use this option.
/// </summary>
[EditorBrowsable( EditorBrowsableState.Never )]
CanDump,
/// <summary>
/// The entire generated method can be collected by GC when it is no longer used.
/// </summary>
CanCollect,
#endif
/// <summary>
/// Prefer performance. This options is default.
/// </summary>
Fast
}
}
|
Move all Eco setting types to the Eco namespace | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Eco;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Eco")]
[assembly: AssemblyDescription("Yet another configuration library for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Eco")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// SettingsComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bfdd8cf1-3e3b-4120-8d3a-68bd506ec4b3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly:SettingsAssembly("Eco.Elements")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Eco;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Eco")]
[assembly: AssemblyDescription("Yet another configuration library for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Eco")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// SettingsComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bfdd8cf1-3e3b-4120-8d3a-68bd506ec4b3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly:SettingsAssembly("Eco")]
|
Add support for Authenticated on 3DS Charges | namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity
{
[JsonProperty("succeeded")]
public bool Succeeded { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity
{
/// <summary>
/// Whether or not authentication was performed. 3D Secure will succeed without
/// authentication when the card is not enrolled.
/// </summary>
[JsonProperty("authenticated")]
public bool Authenticated { get; set; }
/// <summary>
/// Whether or not 3D Secure succeeded.
/// </summary>
[JsonProperty("succeeded")]
public bool Succeeded { get; set; }
/// <summary>
/// The version of 3D Secure that was used for this payment.
/// </summary>
[JsonProperty("version")]
public string Version { get; set; }
}
}
|
Update assembly copyright notice to 2017 | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Hangfire")]
[assembly: AssemblyCopyright("Copyright © 2013-2015 Sergey Odinokov, Adam Barclay")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
// Don't edit manually! Use `build.bat version` command instead!
[assembly: AssemblyVersion("0.1.0")]
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Hangfire")]
[assembly: AssemblyCopyright("Copyright © 2013-2017 Sergey Odinokov, Adam Barclay")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
// Don't edit manually! Use `build.bat version` command instead!
[assembly: AssemblyVersion("0.1.0")]
|
Add automatic placement for Prizes. | using UnityEngine;
using System.Collections;
using Matcha.Game.Tweens;
public class InteractiveEntity : MonoBehaviour
{
public enum EntityType { none, prize, weapon };
public EntityType entityType;
[HideInInspector]
public bool alreadyCollided = false;
public bool disableIfOffScreen = true;
public int worth;
void OnBecameInvisible()
{
if(disableIfOffScreen)
gameObject.SetActive(false);
}
void OnBecameVisible()
{
if(disableIfOffScreen)
gameObject.SetActive(true);
}
public void React()
{
alreadyCollided = true;
switch (entityType)
{
case EntityType.none:
break;
case EntityType.prize:
MTween.PickupPrize(gameObject);
break;
case EntityType.weapon:
MTween.PickupWeapon(gameObject);
break;
}
}
public void SelfDestruct(int inSeconds)
{
Destroy(gameObject, inSeconds);
}
}
| using UnityEngine;
using System;
using System.Collections;
using Matcha.Game.Tweens;
public class InteractiveEntity : MonoBehaviour
{
public enum EntityType { none, prize, weapon };
public EntityType entityType;
[HideInInspector]
public bool alreadyCollided = false;
public bool disableIfOffScreen = true;
public int worth;
void Start()
{
switch (entityType)
{
case EntityType.none:
break;
case EntityType.prize:
// still buggy
// needs to be more succint
transform.position = new Vector3(transform.position.x, (float)(Math.Ceiling(transform.position.y) - .623f), transform.position.z);
break;
case EntityType.weapon:
break;
}
}
void OnBecameInvisible()
{
if(disableIfOffScreen)
gameObject.SetActive(false);
}
void OnBecameVisible()
{
if(disableIfOffScreen)
gameObject.SetActive(true);
}
public void React()
{
alreadyCollided = true;
switch (entityType)
{
case EntityType.none:
break;
case EntityType.prize:
MTween.PickupPrize(gameObject);
break;
case EntityType.weapon:
MTween.PickupWeapon(gameObject);
break;
}
}
public void SelfDestruct(int inSeconds)
{
Destroy(gameObject, inSeconds);
}
}
|
Make sure a ball can't happen while a goal has already happened! | using System;
using Client.Common;
using Client.Game;
using UnityEngine;
namespace Client.Controllers
{
// Create a ball. Once there is a Goal, create a new
// ball at the given time frame.
public class BallController : MonoBehaviour
{
[SerializeField]
[Tooltip("The soccer ball prefab")]
private GameObject prefabBall;
private GameObject currentBall;
// --- Messages ---
private void Start()
{
if(prefabBall == null)
{
throw new Exception("Prefab should not be null!");
}
CreateBall();
var p1Goal = Goals.FindPlayerOneGoal().GetComponent<TriggerObservable>();
var p2Goal = Goals.FindPlayerTwoGoal().GetComponent<TriggerObservable>();
p1Goal.TriggerEnter += OnGoal;
p2Goal.TriggerEnter += OnGoal;
}
// --- Functions ---
// Create a ball. Removes the old one if there is one.
private void CreateBall()
{
if(currentBall != null)
{
Destroy(currentBall);
}
currentBall = Instantiate(prefabBall);
currentBall.name = Ball.Name;
}
private void OnGoal(Collider _)
{
Invoke("CreateBall", 5);
}
}
} | using System;
using Client.Common;
using Client.Game;
using UnityEngine;
namespace Client.Controllers
{
// Create a ball. Once there is a Goal, create a new
// ball at the given time frame.
public class BallController : MonoBehaviour
{
[SerializeField]
[Tooltip("The soccer ball prefab")]
private GameObject prefabBall;
private GameObject currentBall;
// property to ensure we don't try and create a ball while
// creating a ball
private bool isGoal;
// --- Messages ---
private void Start()
{
if(prefabBall == null)
{
throw new Exception("Prefab should not be null!");
}
isGoal = false;
var p1Goal = Goals.FindPlayerOneGoal().GetComponent<TriggerObservable>();
var p2Goal = Goals.FindPlayerTwoGoal().GetComponent<TriggerObservable>();
p1Goal.TriggerEnter += OnGoal;
p2Goal.TriggerEnter += OnGoal;
CreateBall();
}
// --- Functions ---
// Create a ball. Removes the old one if there is one.
private void OnGoal(Collider _)
{
if(!isGoal)
{
isGoal = true;
Invoke("CreateBall", 5);
}
}
private void CreateBall()
{
if(currentBall != null)
{
Destroy(currentBall);
}
currentBall = Instantiate(prefabBall);
currentBall.name = Ball.Name;
isGoal = false;
}
}
} |
Fix issues with wordwrap string extension method | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExoMail.Smtp.Extensions
{
public static class StringExtensions
{
public static Stream ToStream(this string str)
{
return new MemoryStream(Encoding.ASCII.GetBytes(str));
}
public static string WordWrap(this string str, int cols)
{
return WordWrap(str, cols, string.Empty);
}
public static string WordWrap(this string str, int cols, string indent)
{
string[] words = str.Split(' ');
var sb = new StringBuilder();
int colIndex = 0;
string space = string.Empty;
for (int i = 0; i < words.Count(); i++)
{
space = i == words.Count() ? string.Empty : " ";
colIndex += words[i].Length + space.Length;
if (colIndex <= cols)
{
sb.Append(string.Format("{0}{1}", words[i], space));
}
else
{
colIndex = 0;
sb.Append(string.Format("\r\n{0}{1}{2}", indent, words[i], space));
}
}
return sb.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExoMail.Smtp.Extensions
{
public static class StringExtensions
{
public static Stream ToStream(this string str)
{
return new MemoryStream(Encoding.ASCII.GetBytes(str));
}
public static string WordWrap(this string str, int cols)
{
return WordWrap(str, cols, string.Empty);
}
public static string WordWrap(this string str, int cols, string indent)
{
string[] words = str.Split(' ');
var sb = new StringBuilder();
int colIndex = 0;
string space = string.Empty;
string newLine = "\r\n";
for (int i = 0; i < words.Count(); i++)
{
space = i == (words.Count() - 1) ? newLine : " ";
colIndex += words[i].Length + space.Length + newLine.Length;
if (colIndex <= cols)
{
sb.AppendFormat("{0}{1}", words[i], space);
}
else
{
colIndex = 0;
sb.AppendFormat("\r\n{0}{1}{2}", indent, words[i], space);
}
if (words[i].Contains(';'))
{
colIndex = 0;
sb.Append(newLine);
sb.Append(indent);
}
}
return sb.ToString();
}
}
}
|
Set AssemblyVersion and AssemblyFileVersion to 1.0.0.0 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.*")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Add using for db context | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelAgency.Data;
using TravelAgency.Data.Migrations;
using TravelAgency.MongoDbExtractor;
namespace TravelAgency.Client
{
public class Startup
{
public static void Main()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<TravelAgencyDbContext, Configuration>());
var travelAgencyDbContext = new TravelAgencyDbContext();
var mongoExtractor = new MongoDbDataExtractor();
var dataImporter = new TravelAgenciesDataImporter(travelAgencyDbContext, mongoExtractor);
dataImporter.ImportData();
try
{
travelAgencyDbContext.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
throw;
}
//// Just for test - to see if something has been written to the Database
// Console.WriteLine(db.Destinations.Count());
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelAgency.Data;
using TravelAgency.Data.Migrations;
using TravelAgency.MongoDbExtractor;
namespace TravelAgency.Client
{
public class Startup
{
public static void Main()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<TravelAgencyDbContext, Configuration>());
using (var travelAgencyDbContext = new TravelAgencyDbContext())
{
var mongoExtractor = new MongoDbDataExtractor();
var dataImporter = new TravelAgenciesDataImporter(travelAgencyDbContext, mongoExtractor);
dataImporter.ImportData();
travelAgencyDbContext.SaveChanges();
}
//// Just for test - to see if something has been written to the Database
// Console.WriteLine(db.Destinations.Count());
}
}
}
|
Add Chroma keying to the background of the showcase video. | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Components;
namespace osu.Game.Tournament.Screens.Showcase
{
public class ShowcaseScreen : BeatmapInfoScreen
{
[BackgroundDependencyLoader]
private void load()
{
AddRangeInternal(new Drawable[] {
new TournamentLogo(),
new TourneyVideo("showcase")
{
Loop = true,
RelativeSizeAxes = Axes.Both,
}
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Components;
using osu.Framework.Graphics.Shapes;
using osuTK.Graphics;
namespace osu.Game.Tournament.Screens.Showcase
{
public class ShowcaseScreen : BeatmapInfoScreen, IProvideVideo
{
private Box chroma;
[BackgroundDependencyLoader]
private void load()
{
AddRangeInternal(new Drawable[] {
new TournamentLogo(),
new TourneyVideo("showcase")
{
Loop = true,
RelativeSizeAxes = Axes.Both,
},
chroma = new Box
{
// chroma key area for stable gameplay
Name = "chroma",
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Height = 695,
Width = 1366,
Colour = new Color4(0, 255, 0, 255),
}
});
}
}
}
|
Update usages to consume `IRulesetStore` | // 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.Game.Beatmaps;
using osu.Game.Rulesets;
namespace osu.Game.Scoring.Legacy
{
/// <summary>
/// A <see cref="LegacyScoreDecoder"/> which retrieves the applicable <see cref="Beatmap"/> and <see cref="Ruleset"/>
/// for the score from the database.
/// </summary>
public class DatabasedLegacyScoreDecoder : LegacyScoreDecoder
{
private readonly RulesetStore rulesets;
private readonly BeatmapManager beatmaps;
public DatabasedLegacyScoreDecoder(RulesetStore rulesets, BeatmapManager beatmaps)
{
this.rulesets = rulesets;
this.beatmaps = beatmaps;
}
protected override Ruleset GetRuleset(int rulesetId) => rulesets.GetRuleset(rulesetId).CreateInstance();
protected override WorkingBeatmap GetBeatmap(string md5Hash) => beatmaps.GetWorkingBeatmap(beatmaps.QueryBeatmap(b => !b.BeatmapSet.DeletePending && b.MD5Hash == md5Hash));
}
}
| // 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.Game.Beatmaps;
using osu.Game.Rulesets;
namespace osu.Game.Scoring.Legacy
{
/// <summary>
/// A <see cref="LegacyScoreDecoder"/> which retrieves the applicable <see cref="Beatmap"/> and <see cref="Ruleset"/>
/// for the score from the database.
/// </summary>
public class DatabasedLegacyScoreDecoder : LegacyScoreDecoder
{
private readonly IRulesetStore rulesets;
private readonly BeatmapManager beatmaps;
public DatabasedLegacyScoreDecoder(IRulesetStore rulesets, BeatmapManager beatmaps)
{
this.rulesets = rulesets;
this.beatmaps = beatmaps;
}
protected override Ruleset GetRuleset(int rulesetId) => rulesets.GetRuleset(rulesetId).CreateInstance();
protected override WorkingBeatmap GetBeatmap(string md5Hash) => beatmaps.GetWorkingBeatmap(beatmaps.QueryBeatmap(b => !b.BeatmapSet.DeletePending && b.MD5Hash == md5Hash));
}
}
|
Update spacing for project consistency | using System;
using System.Web;
namespace RollbarSharp
{
public class RollbarHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.Error += SendError;
}
public void Dispose()
{
}
private void SendError(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
new RollbarClient().SendException(application.Server.GetLastError().GetBaseException());
}
}
} | using System;
using System.Web;
namespace RollbarSharp
{
public class RollbarHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.Error += SendError;
}
public void Dispose()
{
}
private static void SendError(object sender, EventArgs e)
{
var application = (HttpApplication) sender;
new RollbarClient().SendException(application.Server.GetLastError().GetBaseException());
}
}
} |
Define and evaluate function, using defn defined in core.clj | namespace ClojSharp.Core.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClojSharp.Core.Forms;
using ClojSharp.Core.Language;
using ClojSharp.Core.SpecialForms;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
[DeploymentItem("Src", "Src")]
public class CoreTests
{
private Machine machine;
[TestInitialize]
public void Setup()
{
this.machine = new Machine();
this.machine.EvaluateFile("Src\\core.clj");
}
[TestMethod]
public void MachineHasMacros()
{
this.IsMacro("defmacro");
this.IsMacro("defn");
}
private void IsMacro(string name)
{
var result = this.machine.RootContext.GetValue(name);
Assert.IsNotNull(result, name);
Assert.IsInstanceOfType(result, typeof(IForm), name);
Assert.IsInstanceOfType(result, typeof(Macro), name);
}
}
}
| namespace ClojSharp.Core.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClojSharp.Core.Compiler;
using ClojSharp.Core.Forms;
using ClojSharp.Core.Language;
using ClojSharp.Core.SpecialForms;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
[DeploymentItem("Src", "Src")]
public class CoreTests
{
private Machine machine;
[TestInitialize]
public void Setup()
{
this.machine = new Machine();
this.machine.EvaluateFile("Src\\core.clj");
}
[TestMethod]
public void MachineHasMacros()
{
this.IsMacro("defmacro");
this.IsMacro("defn");
}
[TestMethod]
public void DefineAndEvaluateFunction()
{
this.Evaluate("(defn incr [x] (+ x 1))");
Assert.AreEqual(2, this.Evaluate("(incr 1)"));
}
private void IsMacro(string name)
{
var result = this.machine.RootContext.GetValue(name);
Assert.IsNotNull(result, name);
Assert.IsInstanceOfType(result, typeof(IForm), name);
Assert.IsInstanceOfType(result, typeof(Macro), name);
}
private object Evaluate(string text)
{
return this.Evaluate(text, this.machine.RootContext);
}
private object Evaluate(string text, IContext context)
{
Parser parser = new Parser(text);
var expr = parser.ParseExpression();
Assert.IsNull(parser.ParseExpression());
return Machine.Evaluate(expr, context);
}
}
}
|
Fix issue where RegisterScript did not load file in a IIS Virtual App environment | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.UI;
using System.Web.WebPages;
using DotNetNuke.Web.Client;
using DotNetNuke.Web.Client.ClientResourceManagement;
namespace Satrabel.OpenContent.Components
{
public abstract class OpenContentWebPage<TModel> : DotNetNuke.Web.Razor.DotNetNukeWebPage<TModel>
{
int JSOrder = (int)FileOrder.Js.DefaultPriority;
int CSSOrder = (int)FileOrder.Css.ModuleCss;
public void RegisterStyleSheet(string filePath)
{
if (!filePath.StartsWith("http") && !filePath.StartsWith("/"))
filePath = this.VirtualPath + filePath;
ClientResourceManager.RegisterStyleSheet((Page)HttpContext.Current.CurrentHandler, filePath, CSSOrder);
CSSOrder++;
}
public void RegisterScript(string filePath)
{
if (!filePath.StartsWith("http") && !filePath.StartsWith("/"))
filePath = this.VirtualPath + filePath;
ClientResourceManager.RegisterScript((Page)HttpContext.Current.CurrentHandler, filePath, JSOrder);
JSOrder++;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.UI;
using System.Web.WebPages;
using DotNetNuke.Web.Client;
using DotNetNuke.Web.Client.ClientResourceManagement;
namespace Satrabel.OpenContent.Components
{
public abstract class OpenContentWebPage<TModel> : DotNetNuke.Web.Razor.DotNetNukeWebPage<TModel>
{
int JSOrder = (int)FileOrder.Js.DefaultPriority;
int CSSOrder = (int)FileOrder.Css.ModuleCss;
public void RegisterStyleSheet(string filePath)
{
if (!filePath.StartsWith("http") && !filePath.Contains("/"))
{
filePath = VirtualPath + filePath;
}
if (!filePath.StartsWith("http"))
{
var file = new FileUri(filePath);
filePath = file.UrlFilePath;
}
ClientResourceManager.RegisterStyleSheet((Page)HttpContext.Current.CurrentHandler, filePath, CSSOrder);
CSSOrder++;
}
public void RegisterScript(string filePath)
{
if (!filePath.StartsWith("http") && !filePath.Contains("/"))
{
filePath = VirtualPath + filePath;
}
if (!filePath.StartsWith("http"))
{
var file = new FileUri(filePath);
filePath = file.UrlFilePath;
}
ClientResourceManager.RegisterScript((Page)HttpContext.Current.CurrentHandler, filePath, JSOrder);
JSOrder++;
}
}
} |
Remove display name for Negotiate and Ntlm | // 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.Collections.Generic;
using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.IISPlatformHandler
{
public class IISPlatformHandlerOptions
{
/// <summary>
/// If true the authentication middleware alter the request user coming in and respond to generic challenges.
/// If false the authentication middleware will only provide identity and respond to challenges when explicitly indicated
/// by the AuthenticationScheme.
/// </summary>
public bool AutomaticAuthentication { get; set; } = true;
/// <summary>
/// If true authentication middleware will try to authenticate using platform handler windows authentication
/// If false authentication middleware won't be added
/// </summary>
public bool FlowWindowsAuthentication { get; set; } = true;
/// <summary>
/// Additional information about the authentication type which is made available to the application.
/// </summary>
public IList<AuthenticationDescription> AuthenticationDescriptions { get; } = new List<AuthenticationDescription>()
{
new AuthenticationDescription()
{
AuthenticationScheme = IISPlatformHandlerDefaults.Negotiate,
DisplayName = IISPlatformHandlerDefaults.Negotiate
},
new AuthenticationDescription()
{
AuthenticationScheme = IISPlatformHandlerDefaults.Ntlm,
DisplayName = IISPlatformHandlerDefaults.Ntlm
}
};
}
} | // 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.Collections.Generic;
using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.IISPlatformHandler
{
public class IISPlatformHandlerOptions
{
/// <summary>
/// If true the authentication middleware alter the request user coming in and respond to generic challenges.
/// If false the authentication middleware will only provide identity and respond to challenges when explicitly indicated
/// by the AuthenticationScheme.
/// </summary>
public bool AutomaticAuthentication { get; set; } = true;
/// <summary>
/// If true authentication middleware will try to authenticate using platform handler windows authentication
/// If false authentication middleware won't be added
/// </summary>
public bool FlowWindowsAuthentication { get; set; } = true;
/// <summary>
/// Additional information about the authentication type which is made available to the application.
/// </summary>
public IList<AuthenticationDescription> AuthenticationDescriptions { get; } = new List<AuthenticationDescription>()
{
new AuthenticationDescription()
{
AuthenticationScheme = IISPlatformHandlerDefaults.Negotiate
},
new AuthenticationDescription()
{
AuthenticationScheme = IISPlatformHandlerDefaults.Ntlm
}
};
}
} |
Create server side API for single multiple answer question | using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
[HttpPost]
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
return Ok();
}
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
|
Fix database abstraction test to use correct table name, etc. | namespace StraightSql.Test
{
using System;
using System.Threading.Tasks;
using Xunit;
public class DatabaseAbstractionTest
{
[Fact]
public async Task DatabaseAbstractionTestAsync()
{
var queryDispatcher = new QueryDispatcher(new ConnectionFactory(ConnectionString.Default));
var database = new Database(queryDispatcher, TestReaderCollection.Default);
var setupQueries = new String[]
{
"DROP TABLE IF EXISTS database_abstraction_test;",
"CREATE TABLE database_abstraction_test (id INT NOT NULL, value TEXT NOT NULL);",
"INSERT INTO database_abstraction_test VALUES (1, 'James');",
"INSERT INTO database_abstraction_test VALUES (2, 'Madison');",
"INSERT INTO database_abstraction_test VALUES (3, 'University');"
};
foreach (var setupQuery in setupQueries)
await queryDispatcher.ExecuteAsync(new Query(setupQuery));
var item =
await database
.CreateQuery(@"
SELECT id, value
FROM contextualized_query_builder_query_test
WHERE value = :value;")
.SetParameter("value", "Hopkins")
.FirstAsync<TestItem>();
Assert.NotNull(item);
Assert.Equal(item.Id, 3);
Assert.Equal(item.Value, "Hopkins");
}
}
}
| namespace StraightSql.Test
{
using System;
using System.Threading.Tasks;
using Xunit;
public class DatabaseAbstractionTest
{
[Fact]
public async Task DatabaseAbstractionTestAsync()
{
var queryDispatcher = new QueryDispatcher(new ConnectionFactory(ConnectionString.Default));
var database = new Database(queryDispatcher, TestReaderCollection.Default);
var setupQueries = new String[]
{
"DROP TABLE IF EXISTS database_abstraction_test;",
"CREATE TABLE database_abstraction_test (id INT NOT NULL, value TEXT NOT NULL);",
"INSERT INTO database_abstraction_test VALUES (1, 'James');",
"INSERT INTO database_abstraction_test VALUES (2, 'Madison');",
"INSERT INTO database_abstraction_test VALUES (3, 'University');"
};
foreach (var setupQuery in setupQueries)
await queryDispatcher.ExecuteAsync(new Query(setupQuery));
var item =
await database
.CreateQuery(@"
SELECT id, value
FROM database_abstraction_test
WHERE id = :id;")
.SetParameter("id", 1)
.FirstAsync<TestItem>();
Assert.NotNull(item);
Assert.Equal(item.Id, 1);
Assert.Equal(item.Value, "James");
}
}
}
|
Add more precision to aspnet_start reported times. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace aspnet_start
{
public class Startup
{
public static IWebHost WebHost = null;
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
lifetime.ApplicationStarted.Register(OnAppStarted);
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
private void OnAppStarted()
{
Program._startupTimer.Stop();
Log($"Startup elapsed ms: {Program._startupTimer.ElapsedMilliseconds} ms");
WebHost.StopAsync(TimeSpan.FromSeconds(1));
}
private void Log(string s)
{
string time = DateTime.UtcNow.ToString();
Console.WriteLine($"[{time}] {s}");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace aspnet_start
{
public class Startup
{
public static IWebHost WebHost = null;
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
lifetime.ApplicationStarted.Register(OnAppStarted);
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
private void OnAppStarted()
{
Program._startupTimer.Stop();
Log($"Startup elapsed ms: {Program._startupTimer.Elapsed.TotalMilliseconds} ms");
WebHost.StopAsync(TimeSpan.FromSeconds(1));
}
private void Log(string s)
{
string time = DateTime.UtcNow.ToString();
Console.WriteLine($"[{time}] {s}");
}
}
}
|
Convert source to Hello World. | using System;
using System.Runtime.InteropServices;
namespace TimeToMain
{
public static class Program
{
[DllImport("libnative.so")]
private static extern void write_marker(string name);
public static void Main(string[] args)
{
write_marker("/function/main");
}
}
}
| using System;
using System.Runtime.InteropServices;
namespace TimeToMain
{
public static class Program
{
[DllImport("libnative.so")]
private static extern void write_marker(string name);
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
write_marker("/function/main");
}
}
}
|
Allow Models Builder to have correct type | using System;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
namespace Our.Umbraco.OpeningHours.Converters
{
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
public class OpeningHoursValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(PublishedPropertyType propertyType)
{
return propertyType.PropertyEditorAlias.InvariantEquals("OpeningHours");
}
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
try
{
return Model.OpeningHours.Deserialize(source as string);
}
catch (Exception e)
{
LogHelper.Error<OpeningHoursValueConverter>("Error converting value", e);
}
// Create default model
return new Model.OpeningHours();
}
}
} | using System;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Our.Umbraco.OpeningHours.Model;
namespace Our.Umbraco.OpeningHours.Converters
{
[PropertyValueType(typeof(OpeningHours))]
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
public class OpeningHoursValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(PublishedPropertyType propertyType)
{
return propertyType.PropertyEditorAlias.InvariantEquals("OpeningHours");
}
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
try
{
return Model.OpeningHours.Deserialize(source as string);
}
catch (Exception e)
{
LogHelper.Error<OpeningHoursValueConverter>("Error converting value", e);
}
// Create default model
return new Model.OpeningHours();
}
}
}
|
Fix AW error - creating new phone number | using NakedObjects;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AdventureWorksModel
{
public partial class PersonPhone {
#region Injected Services
public IDomainObjectContainer Container { set; protected get; }
#endregion
#region Title
public override string ToString() {
var t = Container.NewTitleBuilder();
t.Append(PhoneNumberType).Append(":", PhoneNumber);
return t.ToString();
}
#endregion
[NakedObjectsIgnore]
public virtual int BusinessEntityID { get; set; }
public virtual string PhoneNumber { get; set; }
[NakedObjectsIgnore]
public virtual int PhoneNumberTypeID { get; set; }
[ConcurrencyCheck]
public virtual DateTime ModifiedDate { get; set; }
[NakedObjectsIgnore]
public virtual Person Person { get; set; }
public virtual PhoneNumberType PhoneNumberType { get; set; }
}
}
| using NakedObjects;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AdventureWorksModel
{
public partial class PersonPhone {
#region Injected Services
public IDomainObjectContainer Container { set; protected get; }
#endregion
#region Lifecycle methods
public void Persisting()
{
ModifiedDate = DateTime.Now;
}
#endregion
#region Title
public override string ToString() {
var t = Container.NewTitleBuilder();
t.Append(PhoneNumberType).Append(":", PhoneNumber);
return t.ToString();
}
#endregion
[NakedObjectsIgnore]
public virtual int BusinessEntityID { get; set; }
public virtual string PhoneNumber { get; set; }
[NakedObjectsIgnore]
public virtual int PhoneNumberTypeID { get; set; }
[ConcurrencyCheck]
public virtual DateTime ModifiedDate { get; set; }
[NakedObjectsIgnore]
public virtual Person Person { get; set; }
public virtual PhoneNumberType PhoneNumberType { get; set; }
}
}
|
Fix osu!catch catcher not scaling down correctly | // 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.Containers;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
public class CatcherSprite : CompositeDrawable
{
public CatcherSprite()
{
Size = new Vector2(CatcherArea.CATCHER_SIZE);
// Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling.
OriginPosition = new Vector2(-0.02f, 0.06f) * CatcherArea.CATCHER_SIZE;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new SkinnableSprite("Gameplay/catch/fruit-catcher-idle")
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
};
}
}
}
| // 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.Containers;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
public class CatcherSprite : CompositeDrawable
{
public CatcherSprite()
{
Size = new Vector2(CatcherArea.CATCHER_SIZE);
// Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling.
OriginPosition = new Vector2(-0.02f, 0.06f) * CatcherArea.CATCHER_SIZE;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new SkinnableSprite("Gameplay/catch/fruit-catcher-idle", confineMode: ConfineMode.ScaleDownToFit)
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
};
}
}
}
|
Add "x-delayed-message" as valid exchange type | using System;
using System.Collections.Generic;
namespace EasyNetQ.Management.Client.Model
{
public class ExchangeInfo
{
public string Type { get; private set; }
public bool AutoDelete { get; private set; }
public bool Durable { get; private set; }
public bool Internal { get; private set; }
public Arguments Arguments { get; private set; }
private readonly string name;
private readonly ISet<string> exchangeTypes = new HashSet<string>
{
"direct", "topic", "fanout", "headers"
};
public ExchangeInfo(string name, string type) : this(name, type, false, true, false, new Arguments())
{
}
public ExchangeInfo(string name, string type, bool autoDelete, bool durable, bool @internal, Arguments arguments)
{
if(string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
if(type == null)
{
throw new ArgumentNullException("type");
}
if (!exchangeTypes.Contains(type))
{
throw new EasyNetQManagementException("Unknown exchange type '{0}', expected one of {1}",
type,
string.Join(", ", exchangeTypes));
}
this.name = name;
Type = type;
AutoDelete = autoDelete;
Durable = durable;
Internal = @internal;
Arguments = arguments;
}
public string GetName()
{
return name;
}
}
} | using System;
using System.Collections.Generic;
namespace EasyNetQ.Management.Client.Model
{
public class ExchangeInfo
{
public string Type { get; private set; }
public bool AutoDelete { get; private set; }
public bool Durable { get; private set; }
public bool Internal { get; private set; }
public Arguments Arguments { get; private set; }
private readonly string name;
private readonly ISet<string> exchangeTypes = new HashSet<string>
{
"direct", "topic", "fanout", "headers", "x-delayed-message"
};
public ExchangeInfo(string name, string type) : this(name, type, false, true, false, new Arguments())
{
}
public ExchangeInfo(string name, string type, bool autoDelete, bool durable, bool @internal, Arguments arguments)
{
if(string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
if(type == null)
{
throw new ArgumentNullException("type");
}
if (!exchangeTypes.Contains(type))
{
throw new EasyNetQManagementException("Unknown exchange type '{0}', expected one of {1}",
type,
string.Join(", ", exchangeTypes));
}
this.name = name;
Type = type;
AutoDelete = autoDelete;
Durable = durable;
Internal = @internal;
Arguments = arguments;
}
public string GetName()
{
return name;
}
}
}
|
Add an area for errors | using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
public class PublishWindow : EditorWindow
{
private const string PublishTitle = "Publish this repository to GitHub";
private string repoName = "";
private string repoDescription = "";
private int selectedOrg = 0;
private bool togglePrivate = false;
private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" };
static void Init()
{
PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
window.Show();
}
void OnGUI()
{
GUILayout.Label(PublishTitle, EditorStyles.boldLabel);
GUILayout.Space(5);
repoName = EditorGUILayout.TextField("Name", repoName);
repoDescription = EditorGUILayout.TextField("Description", repoDescription);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
}
GUILayout.EndHorizontal();
selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs);
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Create"))
{
Debug.Log("CREATING A REPO HAPPENS HERE!");
this.Close();
}
}
GUILayout.EndHorizontal();
}
}
}
| using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
public class PublishWindow : EditorWindow
{
private const string PublishTitle = "Publish this repository to GitHub";
private string repoName = "";
private string repoDescription = "";
private int selectedOrg = 0;
private bool togglePrivate = false;
// TODO: Replace me since this is just to test rendering errors
private bool error = true;
private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" };
static void Init()
{
PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
window.Show();
}
void OnGUI()
{
GUILayout.Label(PublishTitle, EditorStyles.boldLabel);
GUILayout.Space(5);
repoName = EditorGUILayout.TextField("Name", repoName);
repoDescription = EditorGUILayout.TextField("Description", repoDescription);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
}
GUILayout.EndHorizontal();
selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs);
GUILayout.Space(5);
if (error)
GUILayout.Label("There was an error", Styles.ErrorLabel);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Create"))
{
Debug.Log("CREATING A REPO HAPPENS HERE!");
this.Close();
}
}
GUILayout.EndHorizontal();
}
}
}
|
Bump up new version for assemblyinfor file | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Consumption Management Library")]
[assembly: AssemblyDescription("Provides management functionality for Microsoft Azure Consumption.")]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")] | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Consumption Management Library")]
[assembly: AssemblyDescription("Provides management functionality for Microsoft Azure Consumption.")]
[assembly: AssemblyVersion("3.0.1.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")] |
Fix incorrect version number displayed when deployed | #region
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
namespace DesktopWidgets.Classes
{
internal static class AssemblyInfo
{
public static Version Version { get; } = Assembly.GetExecutingAssembly().GetName().Version;
public static string Copyright { get; } = GetAssemblyAttribute<AssemblyCopyrightAttribute>(a => a.Copyright);
public static string Title { get; } = GetAssemblyAttribute<AssemblyTitleAttribute>(a => a.Title);
public static string Description { get; } =
GetAssemblyAttribute<AssemblyDescriptionAttribute>(a => a.Description);
public static string Guid { get; } = GetAssemblyAttribute<GuidAttribute>(a => a.Value);
private static string GetAssemblyAttribute<T>(Func<T, string> value)
where T : Attribute
{
var attribute = (T) Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof (T));
return value.Invoke(attribute);
}
}
} | #region
using System;
using System.Deployment.Application;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
namespace DesktopWidgets.Classes
{
internal static class AssemblyInfo
{
public static Version Version { get; } = (ApplicationDeployment.IsNetworkDeployed
? ApplicationDeployment.CurrentDeployment.CurrentVersion
: Assembly.GetExecutingAssembly().GetName().Version);
public static string Copyright { get; } = GetAssemblyAttribute<AssemblyCopyrightAttribute>(a => a.Copyright);
public static string Title { get; } = GetAssemblyAttribute<AssemblyTitleAttribute>(a => a.Title);
public static string Description { get; } =
GetAssemblyAttribute<AssemblyDescriptionAttribute>(a => a.Description);
public static string Guid { get; } = GetAssemblyAttribute<GuidAttribute>(a => a.Value);
private static string GetAssemblyAttribute<T>(Func<T, string> value)
where T : Attribute
{
var attribute = (T) Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof (T));
return value.Invoke(attribute);
}
}
} |
Update server side API for single multiple answer question | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
|
Fix formatting and add some constructor overloads | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Editor
{
internal struct CodeDefinitionWindowLocation
{
public string DisplayName { get; }
public string FilePath { get; }
public int Line { get; }
public int Character { get; }
public CodeDefinitionWindowLocation(string displayName, string filePath, int line, int character)
{
DisplayName = displayName;
FilePath = filePath;
Line = line;
Character = character;
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor
{
internal struct CodeDefinitionWindowLocation
{
public string DisplayName { get; }
public string FilePath { get; }
public int Line { get; }
public int Character { get; }
public CodeDefinitionWindowLocation(string displayName, string filePath, int line, int character)
{
DisplayName = displayName;
FilePath = filePath;
Line = line;
Character = character;
}
public CodeDefinitionWindowLocation(string displayName, string filePath, LinePositionSpan position)
: this (displayName, filePath, position.Start.Line, position.Start.Character)
{
}
public CodeDefinitionWindowLocation(string displayName, FileLinePositionSpan position)
: this (displayName, position.Path, position.Span)
{
}
}
}
|
Add more properties found in Twitter V2 Url | using Newtonsoft.Json;
namespace Tweetinvi.Models.V2
{
public class UrlV2
{
/// <summary>
/// The URL as displayed in the Twitter client.
/// </summary>
[JsonProperty("display_url")] public string DisplayUrl { get; set; }
/// <summary>
/// The end position (zero-based) of the recognized URL within the Tweet.
/// </summary>
[JsonProperty("end")] public int End { get; set; }
/// <summary>
/// The fully resolved URL.
/// </summary>
[JsonProperty("expanded_url")] public string ExpandedUrl { get; set; }
/// <summary>
/// The start position (zero-based) of the recognized URL within the Tweet.
/// </summary>
[JsonProperty("start")] public int Start { get; set; }
/// <summary>
/// The URL in the format tweeted by the user.
/// </summary>
[JsonProperty("url")] public string Url { get; set; }
/// <summary>
/// The full destination URL.
/// </summary>
[JsonProperty("unwound_url")] public string UnwoundUrl { get; set; }
}
public class UrlsV2
{
/// <summary>
/// Contains details about text recognized as a URL.
/// </summary>
[JsonProperty("urls")] public UrlV2[] Urls { get; set; }
}
} | using Newtonsoft.Json;
namespace Tweetinvi.Models.V2
{
public class UrlV2
{
/// <summary>
/// The URL as displayed in the Twitter client.
/// </summary>
[JsonProperty("display_url")] public string DisplayUrl { get; set; }
/// <summary>
/// The end position (zero-based) of the recognized URL within the Tweet.
/// </summary>
[JsonProperty("end")] public int End { get; set; }
/// <summary>
/// The fully resolved URL.
/// </summary>
[JsonProperty("expanded_url")] public string ExpandedUrl { get; set; }
/// <summary>
/// The start position (zero-based) of the recognized URL within the Tweet.
/// </summary>
[JsonProperty("start")] public int Start { get; set; }
/// <summary>
/// The URL in the format tweeted by the user.
/// </summary>
[JsonProperty("url")] public string Url { get; set; }
/// <summary>
/// The full destination URL.
/// </summary>
[JsonProperty("unwound_url")] public string UnwoundUrl { get; set; }
/// <summary>
/// Title of the URL
/// </summary>
[JsonProperty("title")] public string Title { get; set; }
/// <summary>
/// Description of the URL
/// </summary>
[JsonProperty("description")] public string Description { get; set; }
}
public class UrlsV2
{
/// <summary>
/// Contains details about text recognized as a URL.
/// </summary>
[JsonProperty("urls")] public UrlV2[] Urls { get; set; }
}
}
|
Use my enumerable in a loop | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
class Program
{
static void Main(string[] args)
{
// This doesn't change (yet):
foreach (var item in GeneratedStrings())
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<string> GeneratedStrings()
{
yield return "one";
yield return "two";
yield return "three";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
class Program
{
static void Main(string[] args)
{
// This doesn't change (yet):
foreach (var item in GeneratedStrings())
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<string> GeneratedStrings()
{
var i = 0;
while (i++ < 100)
yield return i.ToString();
}
}
}
|
Make sure window is visible. | //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - shell.cs
// Code for Revenge Of The Cats' Shell
//------------------------------------------------------------------------------
if(isObject(DefaultCursor))
{
DefaultCursor.delete();
new GuiCursor(DefaultCursor)
{
hotSpot = "1 1";
bitmapName = "./pixmaps/mg_arrow2";
};
}
function addWindow(%control)
{
if(Canvas.getContent() == Shell.getId())
Shell.add(%control);
else
ShellDlg.add(%control);
%control.onAddedAsWindow();
Canvas.repaint();
}
function removeWindow(%control)
{
%control.getParent().remove(%control);
%control.onRemovedAsWindow();
Canvas.repaint();
}
function ShellRoot::onMouseDown(%this,%modifier,%coord,%clickCount)
{
//
// display the root menu...
//
if( Shell.isMember(RootMenu) )
removeWindow(RootMenu);
else
{
RootMenu.position = %coord;
//addWindow(RootMenu);
//Canvas.repaint();
}
}
function ShellRoot::onMouseEnter(%this,%modifier,%coord,%clickCount)
{
//
}
| //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - shell.cs
// Code for Revenge Of The Cats' Shell
//------------------------------------------------------------------------------
if(isObject(DefaultCursor))
{
DefaultCursor.delete();
new GuiCursor(DefaultCursor)
{
hotSpot = "1 1";
bitmapName = "./pixmaps/mg_arrow2";
};
}
function addWindow(%control)
{
%parent = Shell;
if(Canvas.getContent() != Shell.getId())
%parent = ShellDlg;
%parent.add(%control);
%parent.pushToBack(%control);
%control.onAddedAsWindow();
Canvas.repaint();
}
function removeWindow(%control)
{
%control.getParent().remove(%control);
%control.onRemovedAsWindow();
Canvas.repaint();
}
function ShellRoot::onMouseDown(%this,%modifier,%coord,%clickCount)
{
//
// display the root menu...
//
if( Shell.isMember(RootMenu) )
removeWindow(RootMenu);
else
{
RootMenu.position = %coord;
//addWindow(RootMenu);
//Canvas.repaint();
}
}
function ShellRoot::onMouseEnter(%this,%modifier,%coord,%clickCount)
{
//
}
|
Add basic test for ParallelFireworkAlgorithm. | using FireworksNet.Algorithm;
using FireworksNet.Algorithm.Implementation;
using FireworksNet.Problems;
using FireworksNet.StopConditions;
using System;
using Xunit;
namespace FireworksNet.Tests.Algorithm
{
public class ParallelFireworkAlgorithmTests : AlgorithmTestDataSource
{
}
}
| using FireworksNet.Algorithm;
using FireworksNet.Algorithm.Implementation;
using FireworksNet.Problems;
using FireworksNet.StopConditions;
using System;
using Xunit;
namespace FireworksNet.Tests.Algorithm
{
public class ParallelFireworkAlgorithmTests : AlgorithmTestDataSource
{
[Theory]
[MemberData("DataForTestingCreationOfParallelFireworkAlgorithm")]
public void CreationParallelFireworkAlgorithm_PassEachParameterAsNullAndOtherIsCorrect_ArgumentNullExceptionThrown(
Problem problem, IStopCondition stopCondition, ParallelFireworksAlgorithmSettings settings, string expectedParamName)
{
ArgumentException exception = Assert.Throws<ArgumentNullException>(() => new ParallelFireworksAlgorithm(problem, stopCondition, settings));
Assert.Equal(expectedParamName, exception.ParamName);
}
}
}
|
Fix health not being calculated in osu! mode (regression). | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Osu.Judgements;
using osu.Game.Modes.Osu.Objects;
using osu.Game.Modes.Scoring;
using osu.Game.Modes.UI;
namespace osu.Game.Modes.Osu.Scoring
{
internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement>
{
public OsuScoreProcessor()
{
}
public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void Reset()
{
base.Reset();
Health.Value = 1;
Accuracy.Value = 1;
}
protected override void OnNewJudgement(OsuJudgement judgement)
{
int score = 0;
int maxScore = 0;
foreach (var j in Judgements)
{
score += j.ScoreValue;
maxScore += j.MaxScoreValue;
}
TotalScore.Value = score;
Accuracy.Value = (double)score / maxScore;
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Osu.Judgements;
using osu.Game.Modes.Osu.Objects;
using osu.Game.Modes.Scoring;
using osu.Game.Modes.UI;
namespace osu.Game.Modes.Osu.Scoring
{
internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement>
{
public OsuScoreProcessor()
{
}
public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void Reset()
{
base.Reset();
Health.Value = 1;
Accuracy.Value = 1;
}
protected override void OnNewJudgement(OsuJudgement judgement)
{
if (judgement != null)
{
switch (judgement.Result)
{
case HitResult.Hit:
Health.Value += 0.1f;
break;
case HitResult.Miss:
Health.Value -= 0.2f;
break;
}
}
int score = 0;
int maxScore = 0;
foreach (var j in Judgements)
{
score += j.ScoreValue;
maxScore += j.MaxScoreValue;
}
TotalScore.Value = score;
Accuracy.Value = (double)score / maxScore;
}
}
}
|
Add new overload to Compare method | namespace Gigobyte.Daterpillar.Management
{
public interface ISchemaComparer : System.IDisposable
{
SchemaDiscrepancy Compare(ISchemaAggregator source, ISchemaAggregator target);
}
} | using Gigobyte.Daterpillar.Transformation;
namespace Gigobyte.Daterpillar.Management
{
public interface ISchemaComparer : System.IDisposable
{
SchemaDiscrepancy Compare(Schema source, Schema target);
SchemaDiscrepancy Compare(ISchemaAggregator source, ISchemaAggregator target);
}
} |
Test that nameof nag is ignored in | namespace Gu.Analyzers.Test.GU0006UseNameofTests
{
using System.Threading.Tasks;
using NUnit.Framework;
internal class HappyPath : HappyPathVerifier<GU0006UseNameof>
{
[Test]
public async Task WhenThrowingArgumentException()
{
var testCode = @"
using System;
public class Foo
{
public void Meh(object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
}
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
[Test]
public async Task ArgumentOutOfRangeException()
{
var testCode = @"
using System;
public class Foo
{
public void Meh(StringComparison value)
{
switch (value)
{
default:
throw new ArgumentOutOfRangeException(nameof(value), value, null);
}
}
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
}
} | namespace Gu.Analyzers.Test.GU0006UseNameofTests
{
using System.Threading.Tasks;
using NUnit.Framework;
internal class HappyPath : HappyPathVerifier<GU0006UseNameof>
{
[Test]
public async Task WhenThrowingArgumentException()
{
var testCode = @"
using System;
public class Foo
{
public void Meh(object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
}
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
[Test]
public async Task ArgumentOutOfRangeException()
{
var testCode = @"
using System;
public class Foo
{
public void Meh(StringComparison value)
{
switch (value)
{
default:
throw new ArgumentOutOfRangeException(nameof(value), value, null);
}
}
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
[Test]
public async Task IgnoresDebuggerDisplay()
{
var testCode = @"
[System.Diagnostics.DebuggerDisplay(""{Name}"")]
public class Foo
{
public string Name { get; }
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
}
} |
Revert "give compilation error instead of warning or exception at runtime" | using System;
namespace BenchmarkDotNet.Diagnostics
{
[Obsolete("The \"GCDiagnoser\" has been renamed, please use the \"MemoryDiagnoser\" instead (it has the same functionality)", true)]
public class GCDiagnoser
{
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
namespace BenchmarkDotNet.Diagnostics.Windows
{
[Obsolete(message)]
public class GCDiagnoser : IDiagnoser, IColumnProvider
{
const string message = "The \"GCDiagnoser\" has been renamed, please us the \"MemoryDiagnoser\" instead (it has the same functionality)";
public IEnumerable<IColumn> GetColumns
{
get { throw new InvalidOperationException(message); }
}
public void AfterBenchmarkHasRun(Benchmark benchmark, Process process)
{
throw new InvalidOperationException(message);
}
public void DisplayResults(ILogger logger)
{
throw new InvalidOperationException(message);
}
public void ProcessStarted(Process process)
{
throw new InvalidOperationException(message);
}
public void ProcessStopped(Process process)
{
throw new InvalidOperationException(message);
}
public void Start(Benchmark benchmark)
{
throw new InvalidOperationException(message);
}
public void Stop(Benchmark benchmark, BenchmarkReport report)
{
throw new InvalidOperationException(message);
}
}
}
|
Install all indexes by scanning assembly | using System.ComponentModel.Composition.Hosting;
using Raven.Client;
using Raven.Client.Indexes;
namespace Snittlistan.Infrastructure.Indexes
{
public static class IndexCreator
{
public static void CreateIndexes(IDocumentStore store)
{
var typeCatalog = new TypeCatalog(typeof(Matches_PlayerStats), typeof(Match_ByDate));
IndexCreation.CreateIndexes(new CompositionContainer(typeCatalog), store);
}
}
} | using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using Raven.Client;
using Raven.Client.Indexes;
namespace Snittlistan.Infrastructure.Indexes
{
public static class IndexCreator
{
public static void CreateIndexes(IDocumentStore store)
{
var indexes = from type in Assembly.GetExecutingAssembly().GetTypes()
where
type.IsSubclassOf(typeof(AbstractIndexCreationTask))
select type;
var typeCatalog = new TypeCatalog(indexes.ToArray());
IndexCreation.CreateIndexes(new CompositionContainer(typeCatalog), store);
}
}
} |
Add explanatory text comment for person-prisoner example | namespace PersonPrisoner
{
class Program
{
static void Main(string[] args)
{
Person person = new Prisoner();
person.WalkEast(5);
}
}
}
| namespace PersonPrisoner
{
class Program
{
static void Main(string[] args)
{
Person person = new Prisoner();
person.WalkEast(5);
}
}
#region Explanation
// At a first glance, it would be pretty obvious to make the prisoner derive from person class.
// Just as obviously, this leads us into trouble, since a prisoner is not free to move an arbitrary distance
// in any direction, yet the contract of the Person class states that a Person can.
//So, in fact, the class Person could better be named FreePerson. If that were the case, then the idea that
//class Prisoner extends FreePerson is clearly wrong.
//By analogy, then, a Square is not an Rectangle, because it lacks the same degrees of freedom as an Rectangle.
//This strongly suggests that inheritance should never be used when the sub-class restricts the freedom
//implicit in the base class. It should only be used when the sub-class adds extra detail to the concept
//represented by the base class, for example, 'Monkey' is-an 'Animal'.
#endregion
}
|
Fix IsUpdatesChannel missing from ToApi() | using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Host.Models
{
/// <inheritdoc />
public sealed class ChatChannel : Api.Models.ChatChannel
{
/// <summary>
/// The row Id
/// </summary>
public long Id { get; set; }
/// <summary>
/// The <see cref="Api.Models.Internal.ChatBot.Id"/>
/// </summary>
public long ChatSettingsId { get; set; }
/// <summary>
/// The <see cref="Models.ChatBot"/>
/// </summary>
public ChatBot ChatSettings { get; set; }
/// <summary>
/// Convert the <see cref="ChatChannel"/> to it's API form
/// </summary>
/// <returns>A new <see cref="Api.Models.ChatChannel"/></returns>
public Api.Models.ChatChannel ToApi() => new Api.Models.ChatChannel
{
DiscordChannelId = DiscordChannelId,
IsAdminChannel = IsAdminChannel,
IsWatchdogChannel = IsWatchdogChannel,
IrcChannel = IrcChannel
};
}
}
| using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Host.Models
{
/// <inheritdoc />
public sealed class ChatChannel : Api.Models.ChatChannel
{
/// <summary>
/// The row Id
/// </summary>
public long Id { get; set; }
/// <summary>
/// The <see cref="Api.Models.Internal.ChatBot.Id"/>
/// </summary>
public long ChatSettingsId { get; set; }
/// <summary>
/// The <see cref="Models.ChatBot"/>
/// </summary>
public ChatBot ChatSettings { get; set; }
/// <summary>
/// Convert the <see cref="ChatChannel"/> to it's API form
/// </summary>
/// <returns>A new <see cref="Api.Models.ChatChannel"/></returns>
public Api.Models.ChatChannel ToApi() => new Api.Models.ChatChannel
{
DiscordChannelId = DiscordChannelId,
IsAdminChannel = IsAdminChannel,
IsWatchdogChannel = IsWatchdogChannel,
IsUpdatesChannel = IsUpdatesChannel,
IrcChannel = IrcChannel
};
}
}
|
Throw exceptions returned by service context. | using System;
using Castle.DynamicProxy;
using Dargon.Services.PortableObjects;
using Dargon.Services.Utilities;
namespace Dargon.Services.Client {
public class ServiceInvocationInterceptor : IInterceptor {
private readonly IServiceContext serviceContext;
public ServiceInvocationInterceptor(IServiceContext serviceContext) {
this.serviceContext = serviceContext;
}
public void Intercept(IInvocation invocation) {
var methodName = invocation.Method.Name;
var methodArguments = invocation.Arguments;
invocation.ReturnValue = serviceContext.Invoke(methodName, methodArguments);
}
}
} | using System;
using Castle.DynamicProxy;
using Dargon.Services.PortableObjects;
using Dargon.Services.Utilities;
namespace Dargon.Services.Client {
public class ServiceInvocationInterceptor : IInterceptor {
private readonly IServiceContext serviceContext;
public ServiceInvocationInterceptor(IServiceContext serviceContext) {
this.serviceContext = serviceContext;
}
public void Intercept(IInvocation invocation) {
var methodName = invocation.Method.Name;
var methodArguments = invocation.Arguments;
var result = serviceContext.Invoke(methodName, methodArguments);
var exception = result as Exception;
if (exception != null) {
throw exception;
} else {
invocation.ReturnValue = result;;
}
}
}
} |
Create application when executing create command | using System;
namespace AppHarbor.Commands
{
public class CreateCommand : ICommand
{
private readonly AppHarborApi _appHarborApi;
public CreateCommand(AppHarborApi appHarborApi)
{
_appHarborApi = appHarborApi;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
| using System;
namespace AppHarbor.Commands
{
public class CreateCommand : ICommand
{
private readonly AppHarborApi _appHarborApi;
public CreateCommand(AppHarborApi appHarborApi)
{
_appHarborApi = appHarborApi;
}
public void Execute(string[] arguments)
{
var result = _appHarborApi.CreateApplication(arguments[0], arguments[1]);
throw new NotImplementedException();
}
}
}
|
Add Audio properties to IAudiomanagement | namespace Vlc.DotNet.Core
{
public interface IAudioManagement
{
IAudioOutputsManagement Outputs { get; }
}
}
| namespace Vlc.DotNet.Core
{
public interface IAudioManagement
{
IAudioOutputsManagement Outputs { get; }
bool IsMute { get; set; }
void ToggleMute();
int Volume { get; set; }
ITracksManagement Tracks { get; }
int Channel { get; set; }
long Delay { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.