commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13 values | lang stringclasses 23 values |
|---|---|---|---|---|---|---|---|---|
89b32d1dfbff33300ac139bc2b47cb1e21c19d04 | Bump nuget version to 1.2.1. | FacilityApi/FacilityJavaScript,FacilityApi/FacilityJavaScript,FacilityApi/FacilityJavaScript | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.2.1.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| using System.Reflection;
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| mit | C# |
15858a9b19dca6e6d143f7201e241269c9ce84e2 | Add implementation for serializing TraktAuthorization. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Services/TraktSerializationService.cs | Source/Lib/TraktApiSharp/Services/TraktSerializationService.cs | namespace TraktApiSharp.Services
{
using Authentication;
using Extensions;
using System;
using Utils;
/// <summary>Provides helper methods for serializing and deserializing Trakt objects.</summary>
public static class TraktSerializationService
{
/// <summary>Serializes an <see cref="TraktAuthorization" /> instance to a Json string.</summary>
/// <param name="authorization">The authorization information, which should be serialized.</param>
/// <returns>A Json string, containing all properties of the given authorization.</returns>
/// <exception cref="ArgumentNullException">Thrown, if the given authorization is null.</exception>
public static string Serialize(TraktAuthorization authorization)
{
if (authorization == null)
throw new ArgumentNullException(nameof(authorization), "authorization must not be null");
var anonymousAuthorization = new
{
AccessToken = authorization.AccessToken,
RefreshToken = authorization.RefreshToken,
ExpiresIn = authorization.ExpiresIn,
Scope = authorization.AccessScope.ObjectName,
TokenType = authorization.TokenType.ObjectName,
CreatedAt = authorization.Created.ToTraktLongDateTimeString(),
IgnoreExpiration = authorization.IgnoreExpiration
};
return Json.Serialize(anonymousAuthorization);
}
public static TraktAuthorization Deserialize(string authorization)
{
return null;
}
}
}
| namespace TraktApiSharp.Services
{
using Authentication;
using System;
/// <summary>Provides helper methods for serializing and deserializing Trakt objects.</summary>
public static class TraktSerializationService
{
public static string Serialize(TraktAuthorization authorization)
{
if (authorization == null)
throw new ArgumentNullException(nameof(authorization), "authorization must not be null");
return string.Empty;
}
public static TraktAuthorization Deserialize(string authorization)
{
return null;
}
}
}
| mit | C# |
ea34fffe4fa3ee37715f06c9e24830d5954e1dfd | Update ExceptionlessMetricTelemeter.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Telemetry/ExceptionlessMetricTelemeter.cs | TIKSN.Core/Analytics/Telemetry/ExceptionlessMetricTelemeter.cs | using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Exceptionless;
namespace TIKSN.Analytics.Telemetry
{
public class ExceptionlessMetricTelemeter : ExceptionlessTelemeterBase, IMetricTelemeter
{
public Task TrackMetricAsync(string metricName, decimal metricValue)
{
try
{
ExceptionlessClient.Default.CreateFeatureUsage(metricName).SetValue(metricValue).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
return Task.CompletedTask;
}
}
}
| using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Exceptionless;
namespace TIKSN.Analytics.Telemetry
{
public class ExceptionlessMetricTelemeter : ExceptionlessTelemeterBase, IMetricTelemeter
{
public async Task TrackMetric(string metricName, decimal metricValue)
{
try
{
ExceptionlessClient.Default.CreateFeatureUsage(metricName).SetValue(metricValue).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
| mit | C# |
2458a2d8769c4d5b4831151099fa9b7d204592ea | Remove dead code, which I've commited accidentally | ivanz/CorrelatorSharp,CorrelatorSharp/CorrelatorSharp | Correlator/ActivityScope.cs | Correlator/ActivityScope.cs | using System;
namespace Correlator
{
public class ActivityScope : IDisposable
{
public static ActivityScope Current {
get { return ActivityTracker.Current; }
}
public ActivityScope(string name)
: this(name, Guid.NewGuid().ToString())
{
}
public ActivityScope(string name, string id, string parentId)
:this(name, id)
{
ParentId = parentId;
}
public ActivityScope(string name, string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentException($"{nameof(id)} is null or empty.", nameof(id));
Name = name;
Id = id;
ActivityTracker.Start(this);
}
public string Id { get; private set; }
public string ParentId { get; internal set; }
public string Name { get; set; }
public void Dispose()
{
ActivityTracker.End(this);
}
}
} | using System;
namespace Correlator
{
public class ActivityScope : IDisposable
{
public static ActivityScope Find(string id)
{
return ActivityTracker.Find(id);
}
public static ActivityScope Current {
get { return ActivityTracker.Current; }
}
public ActivityScope(string name)
: this(name, Guid.NewGuid().ToString())
{
}
public ActivityScope(string name, string id, string parentId)
:this(name, id)
{
ParentId = parentId;
}
public ActivityScope(string name, string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentException($"{nameof(id)} is null or empty.", nameof(id));
Name = name;
Id = id;
ActivityTracker.Start(this);
}
public string Id { get; private set; }
public string ParentId { get; internal set; }
public string Name { get; set; }
public void Dispose()
{
ActivityTracker.End(this);
}
}
} | mit | C# |
4584b7a30382bfa5c9e587c2ef640ba1d8e271c5 | Update CodeFixProvider.cs | filipw/RemoveRegionAnalyzerAndCodeFix | RemoveRegionAnalyzerAndCodeFix/RemoveRegionAnalyzerAndCodeFix/CodeFixProvider.cs | RemoveRegionAnalyzerAndCodeFix/RemoveRegionAnalyzerAndCodeFix/CodeFixProvider.cs | using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace RemoveRegionAnalyzerAndCodeFix
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RemoveRegionCodeFixProvider)), Shared]
public class RemoveRegionCodeFixProvider : CodeFixProvider
{
private const string title = "Get rid of the damn region";
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(RemoveRegionAnalyzer.DiagnosticId); }
}
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span, true, true);
var region = node as DirectiveTriviaSyntax;
if (region != null)
{
context.RegisterCodeFix(CodeAction.Create(title, c =>
{
Music.Play("Content\\msg.wav");
var newRoot = root.ReplaceNodes(region.GetRelatedDirectives(), (syntax, triviaSyntax) => SyntaxFactory.SkippedTokensTrivia());
var newDocument = context.Document.WithSyntaxRoot(newRoot.NormalizeWhitespace());
return Task.FromResult(newDocument);
} ), context.Diagnostics.First());
}
}
}
}
| using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace RemoveRegionAnalyzerAndCodeFix
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RemoveRegionCodeFixProvider)), Shared]
public class RemoveRegionCodeFixProvider : CodeFixProvider
{
private const string title = "Get rid of the damn region";
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(RemoveRegionAnalyzer.DiagnosticId); }
}
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var node = root.FindNode(diagnosticSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
DirectiveTriviaSyntax region = node as RegionDirectiveTriviaSyntax;
if (region == null)
{
region = node as EndRegionDirectiveTriviaSyntax;
}
if (region != null)
{
context.RegisterCodeFix(
CodeAction.Create(
title,
async c =>
{
Music.Play("Content\\msg.wav");
var oldRoot = await context.Document.GetSyntaxRootAsync(c);
var newRoot = oldRoot.ReplaceNodes(region.GetRelatedDirectives(), (trivia, syntaxTrivia) => SyntaxFactory.SkippedTokensTrivia());
var newDocument = context.Document.WithSyntaxRoot(newRoot.NormalizeWhitespace());
return newDocument;
}),
diagnostic);
}
}
}
} | mit | C# |
03c8d187b9d75e3ea93a91a010741246db54c4c3 | fix redirect unauthenticated attribute | ClearPeopleLtd/Habitat,GoranHalvarsson/Habitat,bhaveshmaniya/Habitat,zyq524/Habitat,nurunquebec/Habitat,nurunquebec/Habitat,ClearPeopleLtd/Habitat,bhaveshmaniya/Habitat,GoranHalvarsson/Habitat,zyq524/Habitat | src/Domain/Accounts/code/Attributes/RedirectUnauthenticatedAttribute.cs | src/Domain/Accounts/code/Attributes/RedirectUnauthenticatedAttribute.cs | namespace Habitat.Accounts.Attributes
{
using System;
using System.Web.Mvc;
using Habitat.Framework.SitecoreExtensions.Extensions;
using Sitecore;
public class RedirectUnauthenticatedAttribute: ActionFilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!Context.User.IsAuthenticated)
{
filterContext.Result = new RedirectResult(Context.Site.GetRootItem().Url());
}
}
}
} | namespace Habitat.Accounts.Attributes
{
using System;
using System.Web.Mvc;
using Habitat.Framework.SitecoreExtensions.Extensions;
using Sitecore;
public class RedirectUnauthenticatedAttribute: Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!Context.User.IsAuthenticated)
{
filterContext.Result = new RedirectResult(Context.Site.GetRootItem().Url());
}
}
}
} | apache-2.0 | C# |
a21be62f1cff70f799918e5692612f067ca50215 | Remove not needed IoC registrations | lion92pl/IIUWr,lion92pl/IIUWr | IIUWr/IIUWr/ConfigureIoC.cs | IIUWr/IIUWr/ConfigureIoC.cs | using IIUWr.Fereol.Common;
using IIUWr.Fereol.Interface;
using IIUWr.ViewModels.Fereol;
using LionCub.Patterns.DependencyInjection;
using System;
using HTMLParsing = IIUWr.Fereol.HTMLParsing;
namespace IIUWr
{
public static class ConfigureIoC
{
public static void All()
{
#if DEBUG
IoC.AsInstance(new Uri(@"http://192.168.1.150:8002/"));
#else
IoC.AsInstance(new Uri(@"https://zapisy.ii.uni.wroc.pl/"));
#endif
ViewModels();
Fereol.Common();
Fereol.HTMLParsing();
}
public static void ViewModels()
{
IoC.AsSingleton<SemestersViewModel>();
}
public static class Fereol
{
public static void Common()
{
IoC.AsSingleton<ICredentialsManager, CredentialsManager>();
IoC.AsSingleton<ISessionManager, CredentialsManager>();
}
public static void HTMLParsing()
{
IoC.AsSingleton<IConnection, HTMLParsing.Connection>();
IoC.AsSingleton<HTMLParsing.Interface.IHTTPConnection, HTMLParsing.Connection>();
IoC.AsSingleton<ICoursesService, HTMLParsing.CoursesService>();
}
}
}
}
| using IIUWr.Fereol.Common;
using IIUWr.Fereol.Interface;
using IIUWr.ViewModels.Fereol;
using LionCub.Patterns.DependencyInjection;
using System;
using HTMLParsing = IIUWr.Fereol.HTMLParsing;
namespace IIUWr
{
public static class ConfigureIoC
{
public static void All()
{
#if DEBUG
IoC.AsInstance(new Uri(@"http://192.168.1.150:8002/"));
#else
IoC.AsInstance(new Uri(@"https://zapisy.ii.uni.wroc.pl/"));
#endif
ViewModels();
Fereol.Common();
Fereol.HTMLParsing();
}
public static void ViewModels()
{
IoC.AsSingleton<SemestersViewModel>();
IoC.PerRequest<SemesterViewModel>();
IoC.PerRequest<CourseViewModel>();
IoC.PerRequest<TutorialViewModel>();
}
public static class Fereol
{
public static void Common()
{
IoC.AsSingleton<ICredentialsManager, CredentialsManager>();
IoC.AsSingleton<ISessionManager, CredentialsManager>();
}
public static void HTMLParsing()
{
IoC.AsSingleton<IConnection, HTMLParsing.Connection>();
IoC.AsSingleton<HTMLParsing.Interface.IHTTPConnection, HTMLParsing.Connection>();
IoC.AsSingleton<ICoursesService, HTMLParsing.CoursesService>();
}
}
}
}
| mit | C# |
3087df90e72e53958f334f8ed31094bab029e1f3 | fix failing fqdn detection unit tests now that we give precedence to publish_address | elastic/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,elastic/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net | src/Tests/Framework/VirtualClustering/MockResponses/SniffingResponse.cs | src/Tests/Framework/VirtualClustering/MockResponses/SniffingResponse.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Elasticsearch.Net;
namespace Tests.Framework.MockResponses
{
public static class SniffResponse
{
private static string ClusterName => "elasticsearch-test-cluster";
public static byte[] Create(IEnumerable<Node> nodes, string publishAddressOverride, bool randomFqdn = false)
{
var response = new
{
cluster_name = ClusterName,
nodes = SniffResponseNodes(nodes, publishAddressOverride, randomFqdn)
};
using (var ms = new MemoryStream())
{
new ElasticsearchDefaultSerializer().Serialize(response, ms);
return ms.ToArray();
}
}
private static IDictionary<string, object> SniffResponseNodes(IEnumerable<Node> nodes, string publishAddressOverride, bool randomFqdn) =>
(from node in nodes
let id = string.IsNullOrEmpty(node.Id) ? Guid.NewGuid().ToString("N").Substring(0, 8) : node.Id
let name = string.IsNullOrEmpty(node.Name) ? Guid.NewGuid().ToString("N").Substring(0, 8) : node.Name
select new { id, name, node })
.ToDictionary(kv => kv.id, kv => CreateNodeResponse(kv.node, kv.name, publishAddressOverride, randomFqdn));
private static Random Random = new Random(1337);
private static object CreateNodeResponse(Node node, string name, string publishAddressOverride, bool randomFqdn)
{
var fqdn = randomFqdn ? $"fqdn{node.Uri.Port}/" : "";
var publishAddress = !string.IsNullOrWhiteSpace(publishAddressOverride) ? publishAddressOverride : "127.0.0.1";
publishAddress += ":" + node.Uri.Port;
var nodeResponse = new
{
name = name,
transport_address = $"127.0.0.1:{node.Uri.Port + 1000}]",
host = Guid.NewGuid().ToString("N").Substring(0, 8),
ip = "127.0.0.1",
version = TestClient.Configuration.ElasticsearchVersion.Version,
build_hash = Guid.NewGuid().ToString("N").Substring(0, 8),
roles = new List<string>(),
http = node.HttpEnabled ? new
{
bound_address = new []
{
$"{fqdn}127.0.0.1:{node.Uri.Port}"
},
publish_address = $"{fqdn}${publishAddress}"
} : null,
settings = new Dictionary<string, object>
{
{ "cluster.name", ClusterName },
{ "node.name", name }
}
};
if (node.MasterEligible) nodeResponse.roles.Add("master");
if (node.HoldsData) nodeResponse.roles.Add("data");
if (!node.HttpEnabled)
nodeResponse.settings.Add("http.enabled", false);
return nodeResponse;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Elasticsearch.Net;
namespace Tests.Framework.MockResponses
{
public static class SniffResponse
{
private static string ClusterName => "elasticsearch-test-cluster";
public static byte[] Create(IEnumerable<Node> nodes, string publishAddressOverride, bool randomFqdn = false)
{
var response = new
{
cluster_name = ClusterName,
nodes = SniffResponseNodes(nodes, publishAddressOverride, randomFqdn)
};
using (var ms = new MemoryStream())
{
new ElasticsearchDefaultSerializer().Serialize(response, ms);
return ms.ToArray();
}
}
private static IDictionary<string, object> SniffResponseNodes(IEnumerable<Node> nodes, string publishAddressOverride, bool randomFqdn) =>
(from node in nodes
let id = string.IsNullOrEmpty(node.Id) ? Guid.NewGuid().ToString("N").Substring(0, 8) : node.Id
let name = string.IsNullOrEmpty(node.Name) ? Guid.NewGuid().ToString("N").Substring(0, 8) : node.Name
select new { id, name, node })
.ToDictionary(kv => kv.id, kv => CreateNodeResponse(kv.node, kv.name, publishAddressOverride, randomFqdn));
private static Random Random = new Random(1337);
private static object CreateNodeResponse(Node node, string name, string publishAddressOverride, bool randomFqdn)
{
var fqdn = randomFqdn ? $"fqdn{node.Uri.Port}/" : "";
var publishAddress = !string.IsNullOrWhiteSpace(publishAddressOverride) ? publishAddressOverride : "127.0.0.1";
publishAddress += ":" + node.Uri.Port;
var nodeResponse = new
{
name = name,
transport_address = $"127.0.0.1:{node.Uri.Port + 1000}]",
host = Guid.NewGuid().ToString("N").Substring(0, 8),
ip = "127.0.0.1",
version = TestClient.Configuration.ElasticsearchVersion.Version,
build_hash = Guid.NewGuid().ToString("N").Substring(0, 8),
roles = new List<string>(),
http = node.HttpEnabled ? new
{
bound_address = new []
{
$"{fqdn}127.0.0.1:{node.Uri.Port}"
},
publish_address = publishAddress
} : null,
settings = new Dictionary<string, object>
{
{ "cluster.name", ClusterName },
{ "node.name", name }
}
};
if (node.MasterEligible) nodeResponse.roles.Add("master");
if (node.HoldsData) nodeResponse.roles.Add("data");
if (!node.HttpEnabled)
nodeResponse.settings.Add("http.enabled", false);
return nodeResponse;
}
}
}
| apache-2.0 | C# |
81747f8a01d081757ac279fef09db6177d6db6c3 | Fix category for a test about tabular structure | Seddryck/NBi,Seddryck/NBi | NBi.Testing/Integration/Core/Structure/StructureDiscoveryFactoryProviderTest.cs | NBi.Testing/Integration/Core/Structure/StructureDiscoveryFactoryProviderTest.cs | using NBi.Core.Structure;
using NBi.Core.Structure.Olap;
using NBi.Core.Structure.Relational;
using NBi.Core.Structure.Tabular;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace NBi.Testing.Integration.Core.Structure
{
public class StructureDiscoveryFactoryProviderTest
{
private class FakeStructureDiscoveryFactoryProvider : StructureDiscoveryFactoryProvider
{
public new string InquireFurtherAnalysisService(string connectionString)
{
return base.InquireFurtherAnalysisService(connectionString);
}
}
[Test]
[Category("Olap")]
public void InquireFurtherAnalysisService_Multidimensional_ReturnCorrectServerMode()
{
var connectionString = ConnectionStringReader.GetAdomd();
var provider = new FakeStructureDiscoveryFactoryProvider();
var serverMode = provider.InquireFurtherAnalysisService(connectionString);
Assert.That(serverMode, Is.EqualTo("olap"));
}
[Test]
[Category("Olap")]
public void InquireFurtherAnalysisService_Tabular_ReturnCorrectServerMode()
{
var connectionString = ConnectionStringReader.GetAdomdTabular();
var provider = new FakeStructureDiscoveryFactoryProvider();
var serverMode = provider.InquireFurtherAnalysisService(connectionString);
Assert.That(serverMode, Is.EqualTo("tabular"));
}
}
}
| using NBi.Core.Structure;
using NBi.Core.Structure.Olap;
using NBi.Core.Structure.Relational;
using NBi.Core.Structure.Tabular;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace NBi.Testing.Integration.Core.Structure
{
public class StructureDiscoveryFactoryProviderTest
{
private class FakeStructureDiscoveryFactoryProvider : StructureDiscoveryFactoryProvider
{
public new string InquireFurtherAnalysisService(string connectionString)
{
return base.InquireFurtherAnalysisService(connectionString);
}
}
[Test]
[Category("Olap")]
public void InquireFurtherAnalysisService_Multidimensional_ReturnCorrectServerMode()
{
var connectionString = ConnectionStringReader.GetAdomd();
var provider = new FakeStructureDiscoveryFactoryProvider();
var serverMode = provider.InquireFurtherAnalysisService(connectionString);
Assert.That(serverMode, Is.EqualTo("olap"));
}
[Test]
[Category("Tabular")]
public void InquireFurtherAnalysisService_Tabular_ReturnCorrectServerMode()
{
var connectionString = ConnectionStringReader.GetAdomdTabular();
var provider = new FakeStructureDiscoveryFactoryProvider();
var serverMode = provider.InquireFurtherAnalysisService(connectionString);
Assert.That(serverMode, Is.EqualTo("tabular"));
}
}
}
| apache-2.0 | C# |
d70dc5c0f9c55fc3410ef14745dacfae645cc3c8 | Change user accounts view model to use the new viewmodel for displaying SuccessMessage | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerApprenticeshipsService.Web/Models/UserAccountsViewModel.cs | src/SFA.DAS.EmployerApprenticeshipsService.Web/Models/UserAccountsViewModel.cs | using SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account;
namespace SFA.DAS.EmployerApprenticeshipsService.Web.Models
{
public class UserAccountsViewModel
{
public Accounts Accounts;
public int Invitations;
public SuccessMessageViewModel SuccessMessage;
}
} | using SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account;
namespace SFA.DAS.EmployerApprenticeshipsService.Web.Models
{
public class UserAccountsViewModel
{
public Accounts Accounts;
public int Invitations;
public string SuccessMessage;
}
} | mit | C# |
ce51d60314f84dde61968333cca2c88811566c29 | test output in appveyor | andrewboudreau/Groceries.Boudreau.Cloud,andrewboudreau/Groceries.Boudreau.Cloud,andrewboudreau/Groceries.Boudreau.Cloud,andrewboudreau/Groceries.Boudreau.Cloud | test/Groceries.Boudreau.Cloud.Integration/EntityFramework/ShoppingListTests.cs | test/Groceries.Boudreau.Cloud.Integration/EntityFramework/ShoppingListTests.cs | using Groceries.Boudreau.Cloud.Database;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Groceries.Boudreau.Cloud.Integration.EntityFramework
{
public class ShoppingListTests
{
[Fact]
public async Task CreateShoppingListTest()
{
// Arrange
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer(Environment.GetEnvironmentVariable("DefaultConnection"));
Console.Out.WriteLine(Environment.GetEnvironmentVariable("DefaultConnection"));
var context = new ShoppingListContext(optionsBuilder.Options);
// Act
context.ShoppingItems.Add(new Domain.ShoppingItem() { Name = Guid.NewGuid().ToString() });
await context.SaveChangesAsync();
// Assert
Assert.True(true);
}
}
}
| using Groceries.Boudreau.Cloud.Database;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Groceries.Boudreau.Cloud.Integration.EntityFramework
{
public class ShoppingListTests
{
[Fact]
public async Task CreateShoppingListTest()
{
// Arrange
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer(Environment.GetEnvironmentVariable("DefaultConnection"));
var context = new ShoppingListContext(optionsBuilder.Options);
// Act
context.ShoppingItems.Add(new Domain.ShoppingItem() { Name = Guid.NewGuid().ToString() });
await context.SaveChangesAsync();
// Assert
Assert.True(true);
}
}
}
| mit | C# |
18ac74f9ebed763100cfe219ee979b51dd6761e9 | Tweak CopyResult | JohanLarsson/Gu.Inject | Gu.Inject.Benchmarks/Program.cs | Gu.Inject.Benchmarks/Program.cs | // ReSharper disable UnusedMember.Local
// ReSharper disable UnusedParameter.Local
// ReSharper disable PossibleNullReferenceException
namespace Gu.Inject.Benchmarks
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
public class Program
{
public static void Main()
{
foreach (var summary in RunSingle<Constructor>())
{
CopyResult(summary);
}
}
private static IEnumerable<Summary> RunAll()
{
var switcher = new BenchmarkSwitcher(typeof(Program).Assembly);
var summaries = switcher.Run(new[] { "*" });
return summaries;
}
private static IEnumerable<Summary> RunSingle<T>()
{
yield return BenchmarkRunner.Run<T>();
}
private static void CopyResult(Summary summary)
{
var sourceFileName = Directory.EnumerateFiles(summary.ResultsDirectoryPath, $"*{summary.Title}-report-github.md")
.Single();
var destinationFileName = Path.Combine(summary.ResultsDirectoryPath, "..\\..\\Benchmarks", summary.Title + ".md");
Console.WriteLine($"Copy: {sourceFileName} -> {destinationFileName}");
File.Copy(sourceFileName, destinationFileName, overwrite: true);
}
}
}
| // ReSharper disable UnusedMember.Local
// ReSharper disable UnusedParameter.Local
// ReSharper disable PossibleNullReferenceException
namespace Gu.Inject.Benchmarks
{
using System.Collections.Generic;
using System.IO;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
public class Program
{
private static readonly string DestinationDirectory = Path.Combine(new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Benchmarks");
public static void Main()
{
foreach (var summary in RunSingle<Constructor>())
{
CopyResult(summary.Title);
}
}
private static IEnumerable<Summary> RunAll()
{
////ClearAllResults();
var switcher = new BenchmarkSwitcher(typeof(Program).Assembly);
var summaries = switcher.Run(new[] { "*" });
return summaries;
}
private static IEnumerable<Summary> RunSingle<T>()
{
var summaries = new[] { BenchmarkRunner.Run<T>() };
return summaries;
}
private static void CopyResult(string name)
{
#if DEBUG
#else
var sourceFileName = Path.Combine(Directory.GetCurrentDirectory(), "BenchmarkDotNet.Artifacts", "results", name + "-report-github.md");
Directory.CreateDirectory(DestinationDirectory);
var destinationFileName = Path.Combine(DestinationDirectory, name + ".md");
File.Copy(sourceFileName, destinationFileName, overwrite: true);
#endif
}
private static void ClearAllResults()
{
if (Directory.Exists(DestinationDirectory))
{
foreach (var resultFile in Directory.EnumerateFiles(DestinationDirectory, "*.md"))
{
File.Delete(resultFile);
}
}
}
}
}
| mit | C# |
55523f6adc4c49476f1d942e3c4cf4502b8b567e | Mark assembly as version 1.3 | EamonNerbonne/ExpressionToCode,asd-and-Rizzo/ExpressionToCode | ExpressionToCodeLib/Properties/AssemblyInfo.cs | ExpressionToCodeLib/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ExpressionToCodeLib")]
[assembly: AssemblyDescription(@"Create readable C# assertions (or other code) from an expression tree; can annotate subexpressions with their runtime value. Integrates with xUnit.NET, NUnit and MSTest.")]
[assembly: AssemblyProduct("ExpressionToCodeLib")]
[assembly: AssemblyCompany("Eamon Nerbonne")]
[assembly: AssemblyCopyright("Copyright © Eamon Nerbonne")]
// 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("008ee713-7baa-491a-96f3-0a8ce3a473b1")]
// 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.3.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ExpressionToCodeLib")]
[assembly: AssemblyDescription(@"Create readable C# assertions (or other code) from an expression tree; can annotate subexpressions with their runtime value. Integrates with xUnit.NET, NUnit and MSTest.")]
[assembly: AssemblyProduct("ExpressionToCodeLib")]
[assembly: AssemblyCompany("Eamon Nerbonne")]
[assembly: AssemblyCopyright("Copyright © Eamon Nerbonne")]
// 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("008ee713-7baa-491a-96f3-0a8ce3a473b1")]
// 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.2.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
a6ad2c37541dfb8ed6f619182adfc1864f7081d9 | Make ManifestHelper for WP more robust | ChristopheLav/HockeySDK-Windows,bitstadium/HockeySDK-Windows,dkackman/HockeySDK-Windows | HockeySDK_WP8/ManifestHelper.cs | HockeySDK_WP8/ManifestHelper.cs | using Microsoft.Phone.Info;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Linq;
namespace HockeyApp
{
public class ManifestHelper
{
private static readonly ManifestHelper instance = new ManifestHelper();
static ManifestHelper() { }
private ManifestHelper() {
}
public static ManifestHelper Instance
{
get
{
return instance;
}
}
public static String GetAppVersion()
{
return Instance.GetValueFromManifest("Version");
}
public static String GetProductID()
{
return Instance.GetValueFromManifest("ProductID");
}
internal String GetValueFromManifest(String key)
{
try
{
XElement appxml = System.Xml.Linq.XElement.Load("WMAppManifest.xml");
var appElement = (from manifestData in appxml.Descendants("App") select manifestData).SingleOrDefault();
return appElement.Attribute(key).Value;
}
catch (Exception)
{
// Ignore all exceptions
}
return "";
}
}
}
| using Microsoft.Phone.Info;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace HockeyApp
{
public class ManifestHelper
{
private static readonly ManifestHelper instance = new ManifestHelper();
static ManifestHelper() { }
private ManifestHelper() {
}
public static ManifestHelper Instance
{
get
{
return instance;
}
}
// Idea based on http://bjorn.kuiper.nu/2011/10/01/wp7-notify-user-of-new-application-version/
public static String GetAppVersion()
{
return Instance.GetValueFromManifest("Version");
}
public static String GetProductID()
{
return Instance.GetValueFromManifest("ProductID");
}
internal String GetValueFromManifest(String key)
{
try
{
StreamReader reader = getManifestReader();
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
int begin = line.IndexOf(" " + key + "=\"", StringComparison.InvariantCulture);
if (begin >= 0)
{
int end = line.IndexOf("\"", begin + key.Length + 3, StringComparison.InvariantCulture);
if (end >= 0)
{
return line.Substring(begin + key.Length + 3, end - begin - key.Length - 3);
}
}
}
}
catch (Exception)
{
// Ignore all exceptions
}
return "";
}
internal static StreamReader getManifestReader()
{
Uri manifest = new Uri("WMAppManifest.xml", UriKind.Relative);
var stream = Application.GetResourceStream(manifest);
if (stream != null)
{
return new StreamReader(stream.Stream);
}
else
{
return null;
}
}
}
}
| mit | C# |
833ff7291694d15d153a90234b83d98092af1f7e | Fix to dispose when the specified object is Icon. | cube-soft/Cube.Core,cube-soft/Cube.Core | Libraries/Sources/Converters/ImageConverter.cs | Libraries/Sources/Converters/ImageConverter.cs | /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using Cube.Mixin.Drawing;
namespace Cube.Xui.Converters
{
/* --------------------------------------------------------------------- */
///
/// ImageConverter
///
/// <summary>
/// Provides functionality to convert from an Image object to
/// a BitmapImage object.
/// </summary>
///
/* --------------------------------------------------------------------- */
public class ImageConverter : SimplexConverter
{
/* ----------------------------------------------------------------- */
///
/// ImageValueConverter
///
/// <summary>
/// Initializes a new instance of the ImageConverter class.
/// </summary>
///
/* ----------------------------------------------------------------- */
public ImageConverter() : base(e =>
{
if (e is System.Drawing.Image i0) return i0.ToBitmapImage(false);
if (e is System.Drawing.Icon i1) return i1.ToBitmap().ToBitmapImage(true);
return null;
}) { }
}
}
| /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using Cube.Mixin.Drawing;
namespace Cube.Xui.Converters
{
/* --------------------------------------------------------------------- */
///
/// ImageConverter
///
/// <summary>
/// Provides functionality to convert from an Image object to
/// a BitmapImage object.
/// </summary>
///
/* --------------------------------------------------------------------- */
public class ImageConverter : SimplexConverter
{
/* ----------------------------------------------------------------- */
///
/// ImageValueConverter
///
/// <summary>
/// Initializes a new instance of the ImageConverter class.
/// </summary>
///
/* ----------------------------------------------------------------- */
public ImageConverter() : base(e =>
{
var src = e is System.Drawing.Image image ? image :
e is System.Drawing.Icon icon ? icon.ToBitmap() :
null;
return src.ToBitmapImage();
}) { }
}
}
| apache-2.0 | C# |
6cf1968a49c52936f9a9d3a37496bbcef1e96376 | Make MuffinClient.Start virtual | Yonom/MuffinFramework | MuffinFramework/MuffinClient.cs | MuffinFramework/MuffinClient.cs | using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using MuffinFramework.Muffin;
using MuffinFramework.Platform;
using MuffinFramework.Service;
namespace MuffinFramework
{
public class MuffinClient : IDisposable
{
private readonly object _lockObj = new object();
public bool IsStarted { get; private set; }
public AggregateCatalog Catalog { get; private set; }
public PlatformLoader PlatformLoader { get; private set; }
public ServiceLoader ServiceLoader { get; private set; }
public MuffinLoader MuffinLoader { get; private set; }
public MuffinClient()
{
this.Catalog = new AggregateCatalog();
this.Catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetCallingAssembly()));
this.PlatformLoader = new PlatformLoader();
this.ServiceLoader = new ServiceLoader();
this.MuffinLoader = new MuffinLoader();
}
public virtual void Start()
{
lock (this._lockObj)
{
if (this.IsStarted)
throw new InvalidOperationException("MuffinClient has already been started.");
this.IsStarted = true;
}
this.PlatformLoader.Enable(this.Catalog, new PlatformArgs(this.PlatformLoader));
this.ServiceLoader.Enable(this.Catalog, new ServiceArgs(this.PlatformLoader, this.ServiceLoader));
this.MuffinLoader.Enable(this.Catalog, new MuffinArgs(this.PlatformLoader, this.ServiceLoader, this.MuffinLoader));
}
public virtual void Dispose()
{
this.MuffinLoader.Dispose();
this.ServiceLoader.Dispose();
this.PlatformLoader.Dispose();
this.Catalog.Dispose();
}
}
} | using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using MuffinFramework.Muffin;
using MuffinFramework.Platform;
using MuffinFramework.Service;
namespace MuffinFramework
{
public class MuffinClient : IDisposable
{
private readonly object _lockObj = new object();
public bool IsStarted { get; private set; }
public AggregateCatalog Catalog { get; private set; }
public PlatformLoader PlatformLoader { get; private set; }
public ServiceLoader ServiceLoader { get; private set; }
public MuffinLoader MuffinLoader { get; private set; }
public MuffinClient()
{
this.Catalog = new AggregateCatalog();
this.Catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetCallingAssembly()));
this.PlatformLoader = new PlatformLoader();
this.ServiceLoader = new ServiceLoader();
this.MuffinLoader = new MuffinLoader();
}
public void Start()
{
lock (this._lockObj)
{
if (this.IsStarted)
throw new InvalidOperationException("MuffinClient has already been started.");
this.IsStarted = true;
}
this.PlatformLoader.Enable(this.Catalog, new PlatformArgs(this.PlatformLoader));
this.ServiceLoader.Enable(this.Catalog, new ServiceArgs(this.PlatformLoader, this.ServiceLoader));
this.MuffinLoader.Enable(this.Catalog, new MuffinArgs(this.PlatformLoader, this.ServiceLoader, this.MuffinLoader));
}
public virtual void Dispose()
{
this.MuffinLoader.Dispose();
this.ServiceLoader.Dispose();
this.PlatformLoader.Dispose();
this.Catalog.Dispose();
}
}
} | mit | C# |
3108bfd0500956740777db21190ee8bd9afa564e | Change the order Loaders are disposed | Yonom/MuffinFramework | MuffinFramework/MuffinClient.cs | MuffinFramework/MuffinClient.cs | using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using MuffinFramework.Muffin;
using MuffinFramework.Platform;
using MuffinFramework.Service;
namespace MuffinFramework
{
public class MuffinClient : IDisposable
{
private readonly object _lockObj = new object();
public bool IsStarted { get; private set; }
public AggregateCatalog Catalog { get; private set; }
public PlatformLoader PlatformLoader { get; private set; }
public ServiceLoader ServiceLoader { get; private set; }
public MuffinLoader MuffinLoader { get; private set; }
public MuffinClient()
{
Catalog = new AggregateCatalog();
Catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetCallingAssembly()));
PlatformLoader = new PlatformLoader();
ServiceLoader = new ServiceLoader();
MuffinLoader = new MuffinLoader();
}
public void Start()
{
lock (_lockObj)
{
if (IsStarted)
throw new InvalidOperationException("MuffinClient has already been started.");
IsStarted = true;
}
PlatformLoader.Enable(Catalog, new PlatformArgs(PlatformLoader));
ServiceLoader.Enable(Catalog, new ServiceArgs(PlatformLoader, ServiceLoader));
MuffinLoader.Enable(Catalog, new MuffinArgs(PlatformLoader, ServiceLoader, MuffinLoader));
}
public virtual void Dispose()
{
MuffinLoader.Dispose();
ServiceLoader.Dispose();
PlatformLoader.Dispose();
Catalog.Dispose();
}
}
} | using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using MuffinFramework.Muffin;
using MuffinFramework.Platform;
using MuffinFramework.Service;
namespace MuffinFramework
{
public class MuffinClient : IDisposable
{
private readonly object _lockObj = new object();
public bool IsStarted { get; private set; }
public AggregateCatalog Catalog { get; private set; }
public PlatformLoader PlatformLoader { get; private set; }
public ServiceLoader ServiceLoader { get; private set; }
public MuffinLoader MuffinLoader { get; private set; }
public MuffinClient()
{
Catalog = new AggregateCatalog();
Catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetCallingAssembly()));
PlatformLoader = new PlatformLoader();
ServiceLoader = new ServiceLoader();
MuffinLoader = new MuffinLoader();
}
public void Start()
{
lock (_lockObj)
{
if (IsStarted)
throw new InvalidOperationException("MuffinClient has already been started.");
IsStarted = true;
}
PlatformLoader.Enable(Catalog, new PlatformArgs(PlatformLoader));
ServiceLoader.Enable(Catalog, new ServiceArgs(PlatformLoader, ServiceLoader));
MuffinLoader.Enable(Catalog, new MuffinArgs(PlatformLoader, ServiceLoader, MuffinLoader));
}
public virtual void Dispose()
{
Catalog.Dispose();
PlatformLoader.Dispose();
ServiceLoader.Dispose();
MuffinLoader.Dispose();
}
}
} | mit | C# |
023e67da4fc8c0548a6f13fd50fb29314048d54d | Update TestMongoDatabaseProvider.cs | tiksn/TIKSN-Framework | TIKSN.Framework.IntegrationTests/Data/Mongo/TestMongoDatabaseProvider.cs | TIKSN.Framework.IntegrationTests/Data/Mongo/TestMongoDatabaseProvider.cs | using Microsoft.Extensions.Configuration;
using TIKSN.Data.Mongo;
namespace TIKSN.Framework.IntegrationTests.Data.Mongo
{
public class TestMongoDatabaseProvider : MongoDatabaseProviderBase
{
public TestMongoDatabaseProvider(
IMongoClientProvider mongoClientProvider,
IConfiguration configuration) : base(
mongoClientProvider,
configuration,
"Mongo")
{
}
}
}
| using Microsoft.Extensions.Configuration;
using TIKSN.Data.Mongo;
namespace TIKSN.Framework.IntegrationTests.Data.Mongo
{
public class TestMongoDatabaseProvider : MongoDatabaseProviderBase
{
public TestMongoDatabaseProvider(
IMongoClientProvider mongoClientProvider,
IConfiguration configuration) : base(
mongoClientProvider,
configuration,
"Mongo")
{
}
}
} | mit | C# |
4fc9ca3788050d5ec302ac0bf7b6e1d4df73dbec | Fix to the fix of the IUserInfoService. | TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim | OpenSim/Framework/Services/IUserInfoService.cs | OpenSim/Framework/Services/IUserInfoService.cs | using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Services.Interfaces
{
public class UserInfo
{
/// <summary>
/// The user that this info is for
/// </summary>
public string UserID;
public UUID SessionID;
/// <summary>
/// The region the user is currently active in
/// NOTE: In a grid situation, the agent can be active in more than one region
/// as they can be logged in more than once
/// </summary>
public UUID CurrentRegionID;
public Vector3 CurrentPosition;
public Vector3 CurrentLookAt;
/// <summary>
/// The home region of this user
/// </summary>
public UUID HomeRegionID;
public Vector3 HomePosition;
public Vector3 HomeLookAt;
/// <summary>
/// Whether this agent is currently online
/// </summary>
public bool IsOnline;
/// <summary>
/// The last login of the user
/// </summary>
public DateTime LastLogin;
/// <summary>
/// The last logout of the user
/// </summary>
public DateTime LastLogout;
/// <summary>
/// Any other assorted into about this user
/// </summary>
public OSDMap Info = new OSDMap();
}
public interface IAgentInfoService
{
/// <summary>
/// Get the user infos for the given user (all regions)
/// </summary>
/// <param name="userID"></param>
/// <param name="regionID"></param>
/// <returns></returns>
UserInfo GetUserInfo(string userID);
/// <summary>
/// Set the home position of the given user
/// </summary>
/// <param name="userID"></param>
/// <param name="homeID"></param>
/// <param name="homePosition"></param>
/// <param name="homeLookAt"></param>
/// <returns></returns>
bool SetHomePosition(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt);
/// <summary>
/// Set the last known position of the given user
/// </summary>
/// <param name="userID"></param>
/// <param name="regionID"></param>
/// <param name="lastPosition"></param>
/// <param name="lastLookAt"></param>
void SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt);
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Services.Interfaces
{
public class UserInfo
{
/// <summary>
/// The user that this info is for
/// </summary>
public string UserID;
public UUID SessionID;
/// <summary>
/// The region the user is currently active in
/// NOTE: In a grid situation, the agent can be active in more than one region
/// as they can be logged in more than once
/// </summary>
public UUID CurrentRegionID;
public Vector3 CurrentPosition;
public Vector3 CurrentLookAt;
/// <summary>
/// The home region of this user
/// </summary>
public UUID HomeRegionID;
public Vector3 HomePosition;
public Vector3 HomeLookAt;
/// <summary>
/// Whether this agent is currently online
/// </summary>
public bool IsOnline;
/// <summary>
/// The last login of the user
/// </summary>
public DateTime LastLogin;
/// <summary>
/// The last logout of the user
/// </summary>
public DateTime LastLogout;
/// <summary>
/// Any other assorted into about this user
/// </summary>
public OSDMap Info = new OSDMap();
}
public interface IAgentInfoService
{
/// <summary>
/// Get the user infos for the given user (all regions)
/// </summary>
/// <param name="userID"></param>
/// <param name="regionID"></param>
/// <returns></returns>
UserInfo[] GetUserInfo(string userID);
/// <summary>
/// Set the home position of the given user
/// </summary>
/// <param name="userID"></param>
/// <param name="homeID"></param>
/// <param name="homePosition"></param>
/// <param name="homeLookAt"></param>
/// <returns></returns>
bool SetHomePosition(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt);
/// <summary>
/// Set the last known position of the given user
/// </summary>
/// <param name="userID"></param>
/// <param name="regionID"></param>
/// <param name="lastPosition"></param>
/// <param name="lastLookAt"></param>
void SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt);
}
}
| bsd-3-clause | C# |
7ccee667fe55386ddad58cc1dcfd35cd47a4ac44 | Read playlist title from metadata json if available. | winnitron/WinnitronLauncher,winnitron/WinnitronLauncher | Assets/Scripts/System/Data/Playlist.cs | Assets/Scripts/System/Data/Playlist.cs | using UnityEngine;
using System.IO;
using System.Collections.Generic;
using System.Globalization;
using SimpleJSON;
[System.Serializable]
public class Playlist
{
public string name;
public string description;
public DirectoryInfo directory;
public List<Game> games;
/*
* Playlist Constructor
*
* Playlist only takes in the directory that the DataManager hands it
* and builds everything from there
*/
public Playlist(string directory) {
this.directory = new DirectoryInfo(directory);
this.games = new List<Game>();
SetName();
BuildGameList();
GM.logger.Info(null, "Playlist Built! : " + name);
}
public void SetName() {
string file = this.directory + "/winnitron_metadata.json";
if(System.IO.File.Exists(file)) {
string json = File.ReadAllText(file);
JSONNode data = JSONNode.Parse(json);
name = data["title"];
description = data["description"];
GM.logger.Debug("Setting playlist name from json: " + file);
} else {
name = this.directory.Name;
name = name.TrimStart('_');
name = name.Replace('_', ' ').Replace('-', ' ');
name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(name);
GM.logger.Debug("Playlist metadata file not found: " + file);
GM.logger.Debug("Setting playlist name from directory: " + name);
}
}
public void BuildGameList() {
foreach(var gameDir in directory.GetDirectories()) {
//Don't pick any directories that start with a dot
if(!gameDir.Name.Substring(0, 1).Equals(".")) {
Game newGame = new Game(gameDir.FullName);
games.Add(newGame);
}
}
}
}
| using UnityEngine;
using System.IO;
using System.Collections.Generic;
using System.Globalization;
[System.Serializable]
public class Playlist
{
public string name;
public DirectoryInfo directory;
public List<Game> games;
/*
* Playlist Constructor
*
* Playlist only takes in the directory that the DataManager hands it
* and builds everything from there
*/
public Playlist(string directory)
{
//Find out the name of the directory
this.directory = new DirectoryInfo(directory);
name = this.directory.Name;
GM.logger.Debug("Playlist: Name before fixes " + name);
name = name.TrimStart('_');
name = name.Replace('_', ' ').Replace('-', ' ');
//Replace the underscores for a cleaner name
name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(name);
GM.logger.Debug("Playlist: Name after fixes " + name);
//Init the games list
this.games = new List<Game>();
//Check for the Winnitron Metadata JSON, and use oldschool folder naming if it doesn't exist
if (System.IO.File.Exists (this.directory + "winnitron_metadata.json")) {
BuildPlaylistJSON ();
} else {
BuildPlaylist ();
}
}
//Where the magic happens
public void BuildPlaylist()
{
foreach (var gameDir in directory.GetDirectories())
{
//Don't pick any directories that start with a dot
if(!gameDir.Name.Substring(0, 1).Equals("."))
{
//Make a new game
Game newGame = new Game(gameDir.FullName);
//Add a game! Pass the Game constructor the directory where the game is contained
games.Add(newGame);
}
}
GM.logger.Info(null, "Playlist Built! : " + name);
}
public void BuildPlaylistJSON()
{
}
}
| mit | C# |
d5ed218488aac139909012bb0343a69edf357421 | Fix timeline sizes being updated potentially before the track has a length | ZLima12/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,DrabWeb/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu-new,smoogipoo/osu,Frontear/osuKyzer,UselessToucan/osu,smoogipoo/osu,naoey/osu,NeoAdonis/osu,naoey/osu,UselessToucan/osu,2yangk23/osu,Nabile-Rahmani/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,johnneijzen/osu,DrabWeb/osu,johnneijzen/osu,ZLima12/osu,ppy/osu,Drezi126/osu,EVAST9919/osu,naoey/osu,peppy/osu,ppy/osu | osu.Game/Screens/Edit/Components/Timelines/Summary/Parts/TimelinePart.cs | osu.Game/Screens/Edit/Components/Timelines/Summary/Parts/TimelinePart.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using OpenTK;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts
{
/// <summary>
/// Represents a part of the summary timeline..
/// </summary>
internal abstract class TimelinePart : CompositeDrawable
{
public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();
private readonly Container timeline;
protected TimelinePart()
{
AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both });
Beatmap.ValueChanged += b =>
{
updateRelativeChildSize();
LoadBeatmap(b);
};
}
private void updateRelativeChildSize()
{
if (!Beatmap.Value.TrackLoaded)
{
timeline.RelativeChildSize = Vector2.One;
return;
}
var track = Beatmap.Value.Track;
if (!track.IsLoaded)
{
// the track may not be loaded completely (only has a length once it is).
Schedule(updateRelativeChildSize);
return;
}
timeline.RelativeChildSize = new Vector2((float)Math.Max(1, track.Length), 1);
}
protected void Add(Drawable visualisation) => timeline.Add(visualisation);
protected virtual void LoadBeatmap(WorkingBeatmap beatmap)
{
timeline.Clear();
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using OpenTK;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts
{
/// <summary>
/// Represents a part of the summary timeline..
/// </summary>
internal abstract class TimelinePart : CompositeDrawable
{
public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();
private readonly Container timeline;
protected TimelinePart()
{
AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both });
Beatmap.ValueChanged += b =>
{
timeline.RelativeChildSize = new Vector2((float)Math.Max(1, b.Track.Length), 1);
LoadBeatmap(b);
};
}
protected void Add(Drawable visualisation) => timeline.Add(visualisation);
protected virtual void LoadBeatmap(WorkingBeatmap beatmap)
{
timeline.Clear();
}
}
}
| mit | C# |
f1150c95a2eabf43a5dcd3eec9cfae15d6433a10 | Use ObservableBase for StyleBinding. | susloparovdenis/Avalonia,Perspex/Perspex,OronDF343/Avalonia,punker76/Perspex,jazzay/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,sagamors/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,susloparovdenis/Avalonia,SuperJMN/Avalonia,DavidKarlas/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,MrDaedra/Avalonia,grokys/Perspex,ncarrillo/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,akrisiun/Perspex,SuperJMN/Avalonia,kekekeks/Perspex,bbqchickenrobot/Perspex,susloparovdenis/Perspex,SuperJMN/Avalonia,susloparovdenis/Perspex,MrDaedra/Avalonia,tshcherban/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,OronDF343/Avalonia,SuperJMN/Avalonia,danwalmsley/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,kekekeks/Perspex,jkoritzinsky/Avalonia | Perspex.Styling/StyleBinding.cs | Perspex.Styling/StyleBinding.cs | // -----------------------------------------------------------------------
// <copyright file="StyleBinding.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Perspex.Styling
{
using System;
using System.Reactive;
/// <summary>
/// Provides an observable for a style.
/// </summary>
/// <remarks>
/// This class takes an activator and a value. The activator is an observable which produces
/// a bool. When the activator produces true, this observable will produce <see cref="Value"/>.
/// When the activator produces false it will produce <see cref="PerspexProperty.UnsetValue"/>.
/// </remarks>
internal class StyleBinding : ObservableBase<object>, IDescription
{
/// <summary>
/// The activator.
/// </summary>
private IObservable<bool> activator;
/// <summary>
/// Initializes a new instance of the <see cref="StyleBinding"/> class.
/// </summary>
/// <param name="activator">The activator.</param>
/// <param name="activatedValue">The activated value.</param>
/// <param name="description">The binding description.</param>
public StyleBinding(
IObservable<bool> activator,
object activatedValue,
string description)
{
this.activator = activator;
this.ActivatedValue = activatedValue;
this.Description = description;
}
/// <summary>
/// Gets a description of the binding.
/// </summary>
public string Description
{
get;
private set;
}
/// <summary>
/// Gets the activated value.
/// </summary>
public object ActivatedValue
{
get;
private set;
}
/// <summary>
/// Notifies the provider that an observer is to receive notifications.
/// </summary>
/// <param name="observer">The observer.</param>
/// <returns>IDisposable object used to unsubscribe from the observable sequence.</returns>
protected override IDisposable SubscribeCore(IObserver<object> observer)
{
Contract.Requires<NullReferenceException>(observer != null);
return this.activator.Subscribe(
active => observer.OnNext(active ? this.ActivatedValue : PerspexProperty.UnsetValue),
observer.OnError,
observer.OnCompleted);
}
}
}
| // -----------------------------------------------------------------------
// <copyright file="StyleBinding.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Perspex.Styling
{
using System;
using System.Reactive.Subjects;
/// <summary>
/// Provides an observable for a style.
/// </summary>
/// <remarks>
/// This class takes an activator and a value. The activator is an observable which produces
/// a bool. When the activator produces true, this observable will produce <see cref="Value"/>.
/// When the activator produces false it will produce <see cref="PerspexProperty.UnsetValue"/>.
/// </remarks>
internal class StyleBinding : IObservable<object>, IObservableDescription
{
/// <summary>
/// The activator.
/// </summary>
private IObservable<bool> activator;
/// <summary>
/// Initializes a new instance of the <see cref="StyleBinding"/> class.
/// </summary>
/// <param name="activator">The activator.</param>
/// <param name="activatedValue">The activated value.</param>
/// <param name="description">The binding description.</param>
public StyleBinding(
IObservable<bool> activator,
object activatedValue,
string description)
{
this.activator = activator;
this.ActivatedValue = activatedValue;
this.Description = description;
}
/// <summary>
/// Gets a description of the binding.
/// </summary>
public string Description
{
get;
private set;
}
/// <summary>
/// Gets the activated value.
/// </summary>
public object ActivatedValue
{
get;
private set;
}
/// <summary>
/// Notifies the provider that an observer is to receive notifications.
/// </summary>
/// <param name="observer">The observer.</param>
/// <returns>IDisposable object used to unsubscribe from the observable sequence.</returns>
public IDisposable Subscribe(IObserver<object> observer)
{
Contract.Requires<NullReferenceException>(observer != null);
return this.activator.Subscribe(
active => observer.OnNext(active ? this.ActivatedValue : PerspexProperty.UnsetValue),
observer.OnError,
observer.OnCompleted);
}
}
}
| mit | C# |
f0dfa9f8f397269571b96d1165f03f36a555bc8e | Use the newest config file available (where the local username matches the filename) | peppy/osu-new,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu | osu.Game/IO/StableStorage.cs | osu.Game/IO/StableStorage.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using osu.Framework.Platform;
namespace osu.Game.IO
{
/// <summary>
/// A storage pointing to an osu-stable installation.
/// Provides methods for handling installations with a custom Song folder location.
/// </summary>
public class StableStorage : DesktopStorage
{
private const string stable_default_songs_path = "Songs";
private readonly DesktopGameHost host;
private readonly Lazy<string> songsPath;
public StableStorage(string path, DesktopGameHost host)
: base(path, host)
{
this.host = host;
songsPath = new Lazy<string>(locateSongsDirectory);
}
/// <summary>
/// Returns a <see cref="Storage"/> pointing to the osu-stable Songs directory.
/// </summary>
public Storage GetSongStorage() => new DesktopStorage(songsPath.Value, host);
private string locateSongsDirectory()
{
var songsDirectoryPath = Path.Combine(BasePath, stable_default_songs_path);
var configFile = GetFiles(".", $"osu!.{Environment.UserName}.cfg").SingleOrDefault();
if (configFile == null)
return songsDirectoryPath;
using (var stream = GetStream(configFile))
using (var textReader = new StreamReader(stream))
{
string line;
while ((line = textReader.ReadLine()) != null)
{
if (line.StartsWith("BeatmapDirectory", StringComparison.OrdinalIgnoreCase))
{
var directory = line.Split('=')[1].TrimStart();
if (Path.IsPathFullyQualified(directory))
songsDirectoryPath = directory;
break;
}
}
}
return songsDirectoryPath;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using osu.Framework.Platform;
namespace osu.Game.IO
{
/// <summary>
/// A storage pointing to an osu-stable installation.
/// Provides methods for handling installations with a custom Song folder location.
/// </summary>
public class StableStorage : DesktopStorage
{
private const string stable_default_songs_path = "Songs";
private readonly DesktopGameHost host;
private readonly Lazy<string> songsPath;
public StableStorage(string path, DesktopGameHost host)
: base(path, host)
{
this.host = host;
songsPath = new Lazy<string>(locateSongsDirectory);
}
/// <summary>
/// Returns a <see cref="Storage"/> pointing to the osu-stable Songs directory.
/// </summary>
public Storage GetSongStorage() => new DesktopStorage(songsPath.Value, host);
private string locateSongsDirectory()
{
var songsDirectoryPath = Path.Combine(BasePath, stable_default_songs_path);
// enumerate the user config files available in case the user migrated their files from another pc / operating system.
var foundConfigFiles = GetFiles(".", "osu!.*.cfg");
// if more than one config file is found, let's use the oldest one (where the username in the filename doesn't match the local username).
var configFile = foundConfigFiles.Count() > 1 ? foundConfigFiles.FirstOrDefault(filename => !filename[5..^4].Contains(Environment.UserName, StringComparison.Ordinal)) : foundConfigFiles.FirstOrDefault();
if (configFile == null)
return songsDirectoryPath;
using (var stream = GetStream(configFile))
using (var textReader = new StreamReader(stream))
{
string line;
while ((line = textReader.ReadLine()) != null)
{
if (line.StartsWith("BeatmapDirectory", StringComparison.OrdinalIgnoreCase))
{
var directory = line.Split('=')[1].TrimStart();
if (Path.IsPathFullyQualified(directory))
songsDirectoryPath = directory;
break;
}
}
}
return songsDirectoryPath;
}
}
}
| mit | C# |
f81b692493ef0918b8089f3e57359d53a8ed459d | Fix failing test due to project rename | billboga/dnxflash,billboga/dnxflash | test/DnxFlash.Test/MessageTest.cs | test/DnxFlash.Test/MessageTest.cs | using System;
using Xunit;
namespace DnxFlash.Test
{
public class MessageTest
{
private Message sut;
public class Constructor : MessageTest
{
[Fact]
public void Should_set_message()
{
sut = new Message("test message");
Assert.Equal("test message", sut.Text);
}
[Theory,
InlineData(null),
InlineData("")]
public void Should_throw_exception_if_message_is_not_valid(string text)
{
var exception = Assert.Throws<ArgumentNullException>(() => new Message(text));
Assert.Equal("text", exception.ParamName);
}
[Fact]
public void Should_set_title()
{
sut = new Message(
text: "test message",
title: "test");
Assert.Equal("test", sut.Title);
}
[Fact]
public void Should_set_type()
{
sut = new Message(
text: "test message",
type: "test");
Assert.Equal("test", sut.Type);
}
}
}
}
| using System;
using Xunit;
namespace DnxFlash.Test
{
public class MessageTest
{
private Message sut;
public class Constructor : MessageTest
{
[Fact]
public void Should_set_message()
{
sut = new Message("test message");
Assert.Equal("test message", sut.Text);
}
[Theory,
InlineData(null),
InlineData("")]
public void Should_throw_exception_if_message_is_not_valid(string message)
{
var exception = Assert.Throws<ArgumentNullException>(() => new Message(message));
Assert.Equal("message", exception.ParamName);
}
[Fact]
public void Should_set_title()
{
sut = new Message(
text: "test message",
title: "test");
Assert.Equal("test", sut.Title);
}
[Fact]
public void Should_set_type()
{
sut = new Message(
text: "test message",
type: "test");
Assert.Equal("test", sut.Type);
}
}
}
}
| mit | C# |
ecdf217d089e94f4d3951866a3eeff12d9073b28 | Make Helper calls threadsafe | Facepunch/Facepunch.Steamworks,Facepunch/Facepunch.Steamworks,Facepunch/Facepunch.Steamworks | Facepunch.Steamworks/Utility/Helpers.cs | Facepunch.Steamworks/Utility/Helpers.cs | using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
namespace Steamworks
{
internal static class Helpers
{
public const int MaxStringSize = 1024 * 32;
[ThreadStatic] private static IntPtr[] MemoryPool;
[ThreadStatic] private static int MemoryPoolIndex;
public static unsafe IntPtr TakeMemory()
{
if ( MemoryPool == null )
{
//
// The pool has 5 items. This should be safe because we shouldn't really
// ever be using more than 2 memory pools
//
MemoryPool = new IntPtr[5];
for ( int i = 0; i < MemoryPool.Length; i++ )
MemoryPool[i] = Marshal.AllocHGlobal( MaxStringSize );
}
MemoryPoolIndex++;
if ( MemoryPoolIndex >= MemoryPool.Length )
MemoryPoolIndex = 0;
var take = MemoryPool[MemoryPoolIndex];
((byte*)take)[0] = 0;
return take;
}
[ThreadStatic] private static byte[][] BufferPool;
[ThreadStatic] private static int BufferPoolIndex;
/// <summary>
/// Returns a buffer. This will get returned and reused later on.
/// </summary>
public static byte[] TakeBuffer( int minSize )
{
if ( BufferPool == null )
{
//
// The pool has 4 items.
//
BufferPool = new byte[4][];
for ( int i = 0; i < BufferPool.Length; i++ )
BufferPool[i] = new byte[ 1024 * 128 ];
}
BufferPoolIndex++;
if ( BufferPoolIndex >= BufferPool.Length )
BufferPoolIndex = 0;
if ( BufferPool[BufferPoolIndex].Length < minSize )
{
BufferPool[BufferPoolIndex] = new byte[minSize + 1024];
}
return BufferPool[BufferPoolIndex];
}
internal unsafe static string MemoryToString( IntPtr ptr )
{
var len = 0;
for( len = 0; len < MaxStringSize; len++ )
{
if ( ((byte*)ptr)[len] == 0 )
break;
}
if ( len == 0 )
return string.Empty;
return UTF8Encoding.UTF8.GetString( (byte*)ptr, len );
}
}
internal class MonoPInvokeCallbackAttribute : Attribute
{
public MonoPInvokeCallbackAttribute() { }
}
/// <summary>
/// Prevent unity from stripping shit we depend on
/// https://docs.unity3d.com/Manual/ManagedCodeStripping.html
/// </summary>
internal class PreserveAttribute : System.Attribute { }
}
| using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
namespace Steamworks
{
internal static class Helpers
{
public const int MaxStringSize = 1024 * 32;
private static IntPtr[] MemoryPool;
private static int MemoryPoolIndex;
public static unsafe IntPtr TakeMemory()
{
if ( MemoryPool == null )
{
//
// The pool has 5 items. This should be safe because we shouldn't really
// ever be using more than 2 memory pools
//
MemoryPool = new IntPtr[5];
for ( int i = 0; i < MemoryPool.Length; i++ )
MemoryPool[i] = Marshal.AllocHGlobal( MaxStringSize );
}
MemoryPoolIndex++;
if ( MemoryPoolIndex >= MemoryPool.Length )
MemoryPoolIndex = 0;
var take = MemoryPool[MemoryPoolIndex];
((byte*)take)[0] = 0;
return take;
}
private static byte[][] BufferPool;
private static int BufferPoolIndex;
/// <summary>
/// Returns a buffer. This will get returned and reused later on.
/// </summary>
public static byte[] TakeBuffer( int minSize )
{
if ( BufferPool == null )
{
//
// The pool has 8 items.
//
BufferPool = new byte[8][];
for ( int i = 0; i < BufferPool.Length; i++ )
BufferPool[i] = new byte[ 1024 * 128 ];
}
BufferPoolIndex++;
if ( BufferPoolIndex >= BufferPool.Length )
BufferPoolIndex = 0;
if ( BufferPool[BufferPoolIndex].Length < minSize )
{
BufferPool[BufferPoolIndex] = new byte[minSize + 1024];
}
return BufferPool[BufferPoolIndex];
}
internal unsafe static string MemoryToString( IntPtr ptr )
{
var len = 0;
for( len = 0; len < MaxStringSize; len++ )
{
if ( ((byte*)ptr)[len] == 0 )
break;
}
if ( len == 0 )
return string.Empty;
return UTF8Encoding.UTF8.GetString( (byte*)ptr, len );
}
}
internal class MonoPInvokeCallbackAttribute : Attribute
{
public MonoPInvokeCallbackAttribute() { }
}
/// <summary>
/// Prevent unity from stripping shit we depend on
/// https://docs.unity3d.com/Manual/ManagedCodeStripping.html
/// </summary>
internal class PreserveAttribute : System.Attribute { }
}
| mit | C# |
f7cd6e83aa81bc24ccce152e37028851e1af8ee0 | Adjust mania scoring to be 95% based on accuracy | smoogipooo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu | osu.Game.Rulesets.Mania/Scoring/ManiaScoreProcessor.cs | osu.Game.Rulesets.Mania/Scoring/ManiaScoreProcessor.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Scoring
{
internal class ManiaScoreProcessor : ScoreProcessor
{
protected override double DefaultAccuracyPortion => 0.95;
protected override double DefaultComboPortion => 0.05;
public override HitWindows CreateHitWindows() => new ManiaHitWindows();
}
}
| // 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.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Scoring
{
internal class ManiaScoreProcessor : ScoreProcessor
{
protected override double DefaultAccuracyPortion => 0.8;
protected override double DefaultComboPortion => 0.2;
public override HitWindows CreateHitWindows() => new ManiaHitWindows();
}
}
| mit | C# |
2b39857b8cec4b4a1d7777a7987bac9813f50d26 | Make mania 80% acc 20% combo | NeoAdonis/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,peppy/osu | osu.Game.Rulesets.Mania/Scoring/ManiaScoreProcessor.cs | osu.Game.Rulesets.Mania/Scoring/ManiaScoreProcessor.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Scoring
{
internal class ManiaScoreProcessor : ScoreProcessor
{
protected override double DefaultAccuracyPortion => 0.8;
protected override double DefaultComboPortion => 0.2;
public override HitWindows CreateHitWindows() => new ManiaHitWindows();
}
}
| // 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.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Scoring
{
internal class ManiaScoreProcessor : ScoreProcessor
{
public override HitWindows CreateHitWindows() => new ManiaHitWindows();
}
}
| mit | C# |
383afe04f35159262e34d437c7835e292d81125a | Remove not needed override | ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu | osu.Game/Overlays/Comments/CommentMarkdownContainer.cs | osu.Game/Overlays/Comments/CommentMarkdownContainer.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using Markdig.Syntax;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Game.Graphics.Containers.Markdown;
namespace osu.Game.Overlays.Comments
{
public class CommentMarkdownContainer : OsuMarkdownContainer
{
protected override MarkdownHeading CreateHeading(HeadingBlock headingBlock) => new CommentMarkdownHeading(headingBlock);
private class CommentMarkdownHeading : OsuMarkdownHeading
{
public CommentMarkdownHeading(HeadingBlock headingBlock)
: base(headingBlock)
{
}
protected override float GetFontSizeByLevel(int level)
{
float defaultFontSize = base.GetFontSizeByLevel(6);
switch (level)
{
case 1:
return 1.2f * defaultFontSize;
case 2:
return 1.1f * defaultFontSize;
default:
return defaultFontSize;
}
}
}
}
}
| // 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.
#nullable disable
using Markdig.Syntax;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Game.Graphics.Containers.Markdown;
namespace osu.Game.Overlays.Comments
{
public class CommentMarkdownContainer : OsuMarkdownContainer
{
public override MarkdownTextFlowContainer CreateTextFlow() => new OsuMarkdownTextFlowContainer();
protected override MarkdownHeading CreateHeading(HeadingBlock headingBlock) => new CommentMarkdownHeading(headingBlock);
private class CommentMarkdownHeading : OsuMarkdownHeading
{
public CommentMarkdownHeading(HeadingBlock headingBlock)
: base(headingBlock)
{
}
protected override float GetFontSizeByLevel(int level)
{
float defaultFontSize = base.GetFontSizeByLevel(6);
switch (level)
{
case 1:
return 1.2f * defaultFontSize;
case 2:
return 1.1f * defaultFontSize;
default:
return defaultFontSize;
}
}
}
}
}
| mit | C# |
f6272a1e6ddc2a37630e789d2c9a18f6a408086f | Add a fluent create method ast | akatakritos/SassSharp | SassSharp/Ast/SassSyntaxTree.cs | SassSharp/Ast/SassSyntaxTree.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SassSharp.Ast
{
public class SassSyntaxTree
{
public SassSyntaxTree(IEnumerable<Node> children)
{
this.Children = children;
}
public IEnumerable<Node> Children { get; private set; }
public static SassSyntaxTree Create(params Node[] nodes)
{
return new SassSyntaxTree(nodes);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SassSharp.Ast
{
public class SassSyntaxTree
{
public SassSyntaxTree(IEnumerable<Node> children)
{
this.Children = children;
}
public IEnumerable<Node> Children { get; private set; }
}
}
| mit | C# |
3797dbb67ebe0945c5801e93911fd2e919813b61 | Add description at top of new template | qinxgit/roslyn-analyzers,dotnet/roslyn-analyzers,genlu/roslyn-analyzers,srivatsn/roslyn-analyzers,tmeschter/roslyn-analyzers-1,natidea/roslyn-analyzers,modulexcite/roslyn-analyzers,dotnet/roslyn-analyzers,jaredpar/roslyn-analyzers,Anniepoh/roslyn-analyzers,jasonmalinowski/roslyn-analyzers,VitalyTVA/roslyn-analyzers,jinujoseph/roslyn-analyzers,bkoelman/roslyn-analyzers,jepetty/roslyn-analyzers,mavasani/roslyn-analyzers,pakdev/roslyn-analyzers,SpotLabsNET/roslyn-analyzers,mavasani/roslyn-analyzers,mattwar/roslyn-analyzers,heejaechang/roslyn-analyzers,pakdev/roslyn-analyzers | NewAnalyzerTemplate/NewAnalyzerTemplate/NewAnalyzerTemplate/DiagnosticAnalyzer.cs | NewAnalyzerTemplate/NewAnalyzerTemplate/NewAnalyzerTemplate/DiagnosticAnalyzer.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/*This tutorial is going to guide you to write a diagnostic analyzer that enforces the placement of one space between the if keyword of an if statement and the
open parenthesis of the condition.
For more information, please reference the ReadMe.
Before you begin, got to Tools->Extensions and Updates->Online, and install:
- .NET Compiler SDK
- Roslyn Syntax Visualizer
*/
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace NewAnalyzerTemplate
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
public override void Initialize(AnalysisContext context)
{
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace NewAnalyzerTemplate
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
public override void Initialize(AnalysisContext context)
{
}
}
}
| mit | C# |
39077266b365e3c2fd78bb52870ab4ad120b1f86 | Correct failing test | danielwertheim/mycouch,danielwertheim/mycouch | source/projects/MyCouch/Responses/Materializers/DocumentResponseMaterializer.cs | source/projects/MyCouch/Responses/Materializers/DocumentResponseMaterializer.cs | using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using EnsureThat;
using MyCouch.Extensions;
using MyCouch.Serialization;
using Newtonsoft.Json.Linq;
namespace MyCouch.Responses.Materializers
{
public class DocumentResponseMaterializer
{
protected readonly ISerializer Serializer;
public DocumentResponseMaterializer(ISerializer serializer)
{
Ensure.That(serializer, "serializer").IsNotNull();
Serializer = serializer;
}
public virtual async Task MaterializeAsync(DocumentResponse response, HttpResponseMessage httpResponse)
{
if (response.RequestMethod != HttpMethod.Get)
throw new ArgumentException(GetType().Name + " only supports materializing GET responses for raw documents.");
using (var content = await httpResponse.Content.ReadAsStreamAsync().ForAwait())
{
response.Content = content.ReadAsString();
var jt = JObject.Parse(response.Content);
response.Id = jt[JsonScheme._Id]?.Value<string>();
response.Rev = jt[JsonScheme._Rev]?.Value<string>();
response.Conflicts = jt[JsonScheme.Conflicts]?.Values<string>().ToArray();
SetMissingIdFromRequestUri(response, httpResponse.RequestMessage);
SetMissingRevFromResponseHeaders(response, httpResponse.Headers);
}
}
protected virtual void SetMissingIdFromRequestUri(DocumentResponse response, HttpRequestMessage request)
{
if (string.IsNullOrWhiteSpace(response.Id) && request.Method != HttpMethod.Post)
response.Id = request.ExtractIdFromUri(false);
}
protected virtual void SetMissingRevFromResponseHeaders(DocumentResponse response, HttpResponseHeaders responseHeaders)
{
if (string.IsNullOrWhiteSpace(response.Rev))
response.Rev = responseHeaders.GetETag();
}
}
} | using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using EnsureThat;
using MyCouch.Extensions;
using MyCouch.Serialization;
using Newtonsoft.Json.Linq;
namespace MyCouch.Responses.Materializers
{
public class DocumentResponseMaterializer
{
protected readonly ISerializer Serializer;
public DocumentResponseMaterializer(ISerializer serializer)
{
Ensure.That(serializer, "serializer").IsNotNull();
Serializer = serializer;
}
public virtual async Task MaterializeAsync(DocumentResponse response, HttpResponseMessage httpResponse)
{
if (response.RequestMethod != HttpMethod.Get)
throw new ArgumentException(GetType().Name + " only supports materializing GET responses for raw documents.");
using (var content = await httpResponse.Content.ReadAsStreamAsync().ForAwait())
{
response.Content = content.ReadAsString();
var jt = JObject.Parse(response.Content);
response.Id = jt.Value<string>(JsonScheme._Id);
response.Rev = jt.Value<string>(JsonScheme._Rev);
response.Conflicts = jt.Values<string>(JsonScheme.Conflicts)?.ToArray();
SetMissingIdFromRequestUri(response, httpResponse.RequestMessage);
SetMissingRevFromResponseHeaders(response, httpResponse.Headers);
}
}
protected virtual void SetMissingIdFromRequestUri(DocumentResponse response, HttpRequestMessage request)
{
if (string.IsNullOrWhiteSpace(response.Id) && request.Method != HttpMethod.Post)
response.Id = request.ExtractIdFromUri(false);
}
protected virtual void SetMissingRevFromResponseHeaders(DocumentResponse response, HttpResponseHeaders responseHeaders)
{
if (string.IsNullOrWhiteSpace(response.Rev))
response.Rev = responseHeaders.GetETag();
}
}
} | mit | C# |
e967ad34a3986ff0432b09f07b5c715961347f90 | correct the docs link | simplcommerce/SimplCommerce,simplcommerce/SimplCommerce,simplcommerce/SimplCommerce,simplcommerce/SimplCommerce | src/SimplCommerce.WebHost/Themes/SampleTheme/Areas/Core/Views/Home/Index.cshtml | src/SimplCommerce.WebHost/Themes/SampleTheme/Areas/Core/Views/Home/Index.cshtml | @model SimplCommerce.Module.Core.Areas.Core.ViewModels.HomeViewModel
@{
ViewData["Title"] = "Home Page";
}
<partial name="_WidgetInstances" model="Model.WidgetInstances.Where(x => x.WidgetZoneId == WidgetZoneIds.HomeFeatured)" />
<div>
<h2 class="page-header">Sample Theme</h2>
<p>It's very easy to find and install new themes or create your own theme. </p>
<p>Check out <a href="https://docs.simplcommerce.com/developer-guide/theme-development.html" target="_blank"> the doc here</a> for more details</p>
</div>
<partial name="_WidgetInstances" model="Model.WidgetInstances.Where(x => x.WidgetZoneId == WidgetZoneIds.HomeMainContent)" />
<partial name="_WidgetInstances" model="Model.WidgetInstances.Where(x => x.WidgetZoneId == WidgetZoneIds.HomeAfterMainContent)" />
| @model SimplCommerce.Module.Core.Areas.Core.ViewModels.HomeViewModel
@{
ViewData["Title"] = "Home Page";
}
<partial name="_WidgetInstances" model="Model.WidgetInstances.Where(x => x.WidgetZoneId == WidgetZoneIds.HomeFeatured)" />
<div>
<h2 class="page-header">Sample Theme</h2>
<p>It's very easy to find and install new themes or create your own theme. </p>
<p>Check out <a href="http://docs.simplcommerce.com/en/latest/theme-development/" target="_blank"> the doc here</a> for more details</p>
</div>
<partial name="_WidgetInstances" model="Model.WidgetInstances.Where(x => x.WidgetZoneId == WidgetZoneIds.HomeMainContent)" />
<partial name="_WidgetInstances" model="Model.WidgetInstances.Where(x => x.WidgetZoneId == WidgetZoneIds.HomeAfterMainContent)" />
| apache-2.0 | C# |
3f6fd655bcbd5f1232097b9ba87e0612df457597 | Update RTMarkerStream.cs | frstrtr/QTM-Unity-Realtime-Streaming | Streaming/RTMarkerStream.cs | Streaming/RTMarkerStream.cs | using UnityEngine;
using System.Collections.Generic;
//#IISCI
//Script for marker coordinates transfer to it's parent by marker name.
namespace QualisysRealTime.Unity
{
class RTMarkerTaker : MonoBehaviour
{
public string markerName = "Put QTM marker name here";
private List<LabeledMarker> markerData;
private RTClient rtClient;
private GameObject markerRoot;
private Vector3 markerPosition = new Vector3();
private bool streaming = false;
// Use this for initialization
void Start()
{
rtClient = RTClient.GetInstance();
markerRoot = gameObject;
}
// Update is called once per frame
void Update()
{
if (rtClient == null) rtClient = RTClient.GetInstance();
if (rtClient.GetStreamingStatus() && !streaming)
{
streaming = true;
}
if (!rtClient.GetStreamingStatus() && streaming)
{
streaming = false;
}
//Seeking fo desired marker name
markerData = rtClient.Markers;
if (markerData == null && markerData.Count == 0)
return;
for (int i = 0; i < markerData.Count; i++)
{
if (markerData[i].Label == markerName)
{
//Transfering marker position to parented object
markerPosition = markerData[i].Position;
transform.position = markerPosition;
}
}
}
}
}
| // Unity SDK for Qualisys Track Manager. Copyright 2015 Qualisys AB
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using QTMRealTimeSDK;
namespace QualisysRealTime.Unity
{
public class RTMarkerStream : MonoBehaviour
{
private List<LabeledMarker> markerData;
private RTClient rtClient;
private GameObject markerRoot;
private List<GameObject> markers;
public bool visibleMarkers = true;
public float markerScale = 0.01f;
private bool streaming = false;
// Use this for initialization
void Start()
{
rtClient = RTClient.GetInstance();
markers = new List<GameObject>();
markerRoot = this.gameObject;
}
private void InitiateMarkers()
{
foreach (var marker in markers)
{
UnityEngine.GameObject.Destroy(marker);
}
markers.Clear();
markerData = rtClient.Markers;
for (int i = 0; i < markerData.Count; i++)
{
GameObject newMarker = UnityEngine.GameObject.CreatePrimitive(PrimitiveType.Sphere);
newMarker.name = markerData[i].Label;
newMarker.transform.parent = markerRoot.transform;
newMarker.transform.localScale = Vector3.one * markerScale;
newMarker.SetActive(false);
markers.Add(newMarker);
}
}
// Update is called once per frame
void Update()
{
if (rtClient.GetStreamingStatus() && !streaming)
{
InitiateMarkers();
streaming = true;
}
if (!rtClient.GetStreamingStatus() && streaming)
{
streaming = false;
InitiateMarkers();
}
markerData = rtClient.Markers;
if (markerData == null && markerData.Count == 0)
return;
if (markers.Count != markerData.Count)
{
InitiateMarkers();
}
for (int i = 0; i < markerData.Count; i++)
{
if (markerData[i].Position.magnitude > 0)
{
markers[i].name = markerData[i].Label;
markers[i].GetComponent<Renderer>().material.color = markerData[i].Color;
markers[i].transform.localPosition = markerData[i].Position;
markers[i].SetActive(true);
markers[i].GetComponent<Renderer>().enabled = visibleMarkers;
markers[i].transform.localScale = Vector3.one * markerScale;
}
else
{
//hide markers if we cant find them.
markers[i].SetActive(false);
}
}
}
}
} | mit | C# |
8145de728f5f3bfb197b3725b246207e8cac6f29 | Use alternative source for images, CMC is blocking them. | funfair-tech/CoinBot | src/CoinBot.Clients/CoinMarketCap/CoinMarketCapCoin.cs | src/CoinBot.Clients/CoinMarketCap/CoinMarketCapCoin.cs | using System;
using CoinBot.Core;
using Newtonsoft.Json;
namespace CoinBot.Clients.CoinMarketCap
{
[JsonObject]
public class CoinMarketCapCoin : ICoinInfo
{
[JsonProperty("id")]
public string Id { get; set; }
public string ImageUrl => $"https://raw.githubusercontent.com/cjdowner/cryptocurrency-icons/master/128/color/{this.Symbol.ToLower()}.png";
public string Url => $"https://coinmarketcap.com/currencies/{this.Id}";
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
[JsonProperty("rank")]
public int? Rank { get; set; }
[JsonProperty("price_usd")]
public double? PriceUsd { get; set; }
[JsonProperty("price_btc")]
public decimal? PriceBtc { get; set; }
[JsonProperty("price_eth")]
public decimal? PriceEth { get; set; }
[JsonProperty("24h_volume_usd")]
public double? Volume { get; set; }
[JsonProperty("market_cap_usd")]
public double? MarketCap { get; set; }
[JsonProperty("available_supply")]
public decimal? AvailableSupply { get; set; }
[JsonProperty("total_supply")]
public decimal? TotalSupply { get; set; }
[JsonProperty("max_supply")]
public decimal? MaxSupply { get; set; }
[JsonProperty("percent_change_1h")]
public double? HourChange { get; set; }
[JsonProperty("percent_change_24h")]
public double? DayChange { get; set; }
[JsonProperty("percent_change_7d")]
public double? WeekChange { get; set; }
[JsonProperty("last_updated")]
[JsonConverter(typeof(UnixTimeConverter))]
public DateTime? LastUpdated { get; set; }
}
}
| using System;
using CoinBot.Core;
using Newtonsoft.Json;
namespace CoinBot.Clients.CoinMarketCap
{
[JsonObject]
public class CoinMarketCapCoin : ICoinInfo
{
[JsonProperty("id")]
public string Id { get; set; }
public string ImageUrl => $"https://files.coinmarketcap.com/static/img/coins/64x64/{this.Id}.png";
public string Url => $"https://coinmarketcap.com/currencies/{this.Id}";
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
[JsonProperty("rank")]
public int? Rank { get; set; }
[JsonProperty("price_usd")]
public double? PriceUsd { get; set; }
[JsonProperty("price_btc")]
public decimal? PriceBtc { get; set; }
[JsonProperty("price_eth")]
public decimal? PriceEth { get; set; }
[JsonProperty("24h_volume_usd")]
public double? Volume { get; set; }
[JsonProperty("market_cap_usd")]
public double? MarketCap { get; set; }
[JsonProperty("available_supply")]
public decimal? AvailableSupply { get; set; }
[JsonProperty("total_supply")]
public decimal? TotalSupply { get; set; }
[JsonProperty("max_supply")]
public decimal? MaxSupply { get; set; }
[JsonProperty("percent_change_1h")]
public double? HourChange { get; set; }
[JsonProperty("percent_change_24h")]
public double? DayChange { get; set; }
[JsonProperty("percent_change_7d")]
public double? WeekChange { get; set; }
[JsonProperty("last_updated")]
[JsonConverter(typeof(UnixTimeConverter))]
public DateTime? LastUpdated { get; set; }
}
}
| mit | C# |
4293119be0019f4373f92f9c591031e46504ab76 | make the changes in implementation responding to interface [#136060481] | revaturelabs/revashare-svc-webapi | revashare-svc-webapi/revashare-svc-webapi.Logic/DriverLogic.cs | revashare-svc-webapi/revashare-svc-webapi.Logic/DriverLogic.cs | using revashare_svc_webapi.Logic.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using revashare_svc_webapi.Logic.Mappers;
namespace revashare_svc_webapi.Logic {
public class DriverLogic : IDriverRepository {
private RevaShareDataServiceClient svc = new RevaShareDataServiceClient();
public bool UpdateVehicleInfo(VehicleDTO vehicle) {
try {
return svc.UpdateVehicle(VehicleMapper.mapToVehicleDAO(vehicle));
}
catch (Exception) {
return false;
}
}
public bool ReportRider(FlagDTO flag) {
try {
return true;
}
catch (Exception) {
return false;
}
}
public bool SetAvailability(RideDTO ride) {
try {
return true;
}
catch (Exception) {
return false;
}
}
public bool UpdateDriverProfile(UserDTO driver) {
try {
return true;
}
catch (Exception) {
return false;
}
}
public bool ScheduleRide(RideDTO ride) {
try {
return svc.AddRide(RideMapper.mapToRideDAO(ride));
}
catch (Exception) {
return false;
}
}
public bool CancelRide(RideDTO ride) {
try {
return svc.DeleteRide(RideMapper.mapToRideDAO(ride).RideID.ToString());
}
catch (Exception) {
return false;
}
}
}
}
| using revashare_svc_webapi.Logic.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using revashare_svc_webapi.Logic.Mappers;
namespace revashare_svc_webapi.Logic {
public class DriverLogic : IDriverRepository {
private RevaShareDataServiceClient svc = new RevaShareDataServiceClient();
public bool UpdateVehicleInfo(VehicleDTO vehicle) {
try {
return svc.UpdateVehicle(VehicleMapper.mapToVehicleDAO(vehicle));
}
catch (Exception) {
return false;
}
}
public bool ReportRider(FlagDTO flag) {
try {
return true;
}
catch (Exception) {
return false;
}
}
public bool SetAvailability() {
try {
return true;
}
catch (Exception) {
return false;
}
}
public bool ModifyDriverProfile(UserDTO driverToUpdate) {
try {
return true;
}
catch (Exception) {
return false;
}
}
public bool DeleteDriver(UserDTO driverToRemove) {
try {
return true;
}
catch (Exception) {
return false;
}
}
public bool ScheduleRide(RideDTO ride) {
try {
return svc.AddRide(RideMapper.mapToRideDAO(ride));
}
catch (Exception) {
return false;
}
}
public bool CancelRide(RideDTO ride) {
try {
return svc.DeleteRide(RideMapper.mapToRideDAO(ride).RideID.ToString());
}
catch (Exception) {
return false;
}
}
public bool AddVehicle(VehicleDTO vehicle) {
try {
return svc.AddVehicle(VehicleMapper.mapToVehicleDAO(vehicle));
}
catch (Exception) {
return false;
}
}
public bool InsertDriver(UserDTO driverToAdd) {
try {
return true;
}
catch (Exception) {
return false;
}
}
public List<UserDTO> RequestDrivers() {
try {
return new List<UserDTO>();
}
catch (Exception) {
return null;
}
}
}
}
| mit | C# |
69f4afba9cdca2ae0248ecd32f86da15f249e676 | Fix bug in notes api | bartsaintgermain/SharpAgileCRM | AgileAPI/Notes.cs | AgileAPI/Notes.cs | // <copyright file="Notes.cs" company="Quamotion">
// Copyright (c) Quamotion. All rights reserved.
// </copyright>
namespace AgileAPI
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using AgileAPI.Models;
using Newtonsoft.Json;
/// <summary>
/// This class provides support to handle with notes in the <c>CRM</c>
/// </summary>
public class Notes
{
/// <summary>
/// Creates a note in the <c>CRM</c>
/// </summary>
/// <param name="crm">
/// The <see cref="AgileCRM"/> instance to be used.
/// </param>
/// <param name="subject">
/// The subject of the note.
/// </param>
/// <param name="description">
/// The description of the note.
/// </param>
/// <param name="contactIds">
/// The related contact identifiers.
/// </param>
/// <returns>
/// The created note
/// </returns>
public static async Task<Note> CreateContactNoteAsync(AgileCRM crm, string subject, string description, List<long> contactIds)
{
var createNoteRequest = new CreateNoteRequest()
{
Subject = subject,
Description = description,
ContactIds = contactIds,
};
var response = await crm.RequestAsync($"notes", HttpMethod.Post, JsonConvert.SerializeObject(createNoteRequest)).ConfigureAwait(false);
return JsonConvert.DeserializeObject<Note>(response);
}
/// <summary>
/// Get all notes related to a contact.
/// </summary>
/// <param name="crm">
/// The <see cref="AgileCRM"/> instance to be used.
/// </param>
/// <param name="contactId">
/// The contact identifier for which to retrieve the note.
/// </param>
/// <returns>
/// The notes related to a contact.
/// </returns>
public static async Task<List<Note>> GetContactNotesAsync(AgileCRM crm, long contactId)
{
var response = await crm.RequestAsync($"contacts/{contactId}/notes", HttpMethod.Get, null).ConfigureAwait(false);
return JsonConvert.DeserializeObject<List<Note>>(response);
}
}
}
| // <copyright file="Notes.cs" company="Quamotion">
// Copyright (c) Quamotion. All rights reserved.
// </copyright>
namespace AgileAPI
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using AgileAPI.Models;
using Newtonsoft.Json;
/// <summary>
/// This class provides support to handle with notes in the <c>CRM</c>
/// </summary>
public class Notes
{
/// <summary>
/// Creates a note in the <c>CRM</c>
/// </summary>
/// <param name="crm">
/// The <see cref="AgileCRM"/> instance to be used.
/// </param>
/// <param name="subject">
/// The subject of the note.
/// </param>
/// <param name="description">
/// The description of the note.
/// </param>
/// <param name="contactIds">
/// The related contact identifiers.
/// </param>
/// <returns>
/// The created note
/// </returns>
public static async Task<Note> CreateContactNoteAsync(AgileCRM crm, string subject, string description, List<long> contactIds)
{
var createNoteRequest = new CreateNoteRequest()
{
Subject = subject,
Description = description,
ContactIds = contactIds,
};
var response = await crm.RequestAsync($"notes", HttpMethod.Post, null).ConfigureAwait(false);
return JsonConvert.DeserializeObject<Note>(response);
}
/// <summary>
/// Get all notes related to a contact.
/// </summary>
/// <param name="crm">
/// The <see cref="AgileCRM"/> instance to be used.
/// </param>
/// <param name="contactId">
/// The contact identifier for which to retrieve the note.
/// </param>
/// <returns>
/// The notes related to a contact.
/// </returns>
public static async Task<List<Note>> GetContactNotesAsync(AgileCRM crm, long contactId)
{
var response = await crm.RequestAsync($"contacts/{contactId}/notes", HttpMethod.Get, null).ConfigureAwait(false);
return JsonConvert.DeserializeObject<List<Note>>(response);
}
}
}
| mit | C# |
5f2f3bc625363f2a99daf1946519a152daa7353b | Fix for typo | mikamikem/Igor,mikamikem/Igor | Modules/Build/VR/Editor/IgorBuildVR.cs | Modules/Build/VR/Editor/IgorBuildVR.cs | using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System;
using System.Reflection;
using System.Xml.Serialization;
using System.Linq;
namespace Igor
{
public class IgorBuildVR : IgorModuleBase
{
public static string VRSupportedFlag = "vrsupported";
public static StepID SetVRStep = new StepID("Set VR Settings", 270);
public override string GetModuleName()
{
return "Build.VR";
}
public override void RegisterModule()
{
IgorCore.RegisterNewModule(this);
}
public override void ProcessArgs(IIgorStepHandler StepHandler)
{
StepHandler.RegisterJobStep(SetVRStep, this, SetVRSettings);
}
public override bool ShouldDrawInspectorForParams(string CurrentParams)
{
return true;
}
public override string DrawJobInspectorAndGetEnabledParams(string CurrentParams)
{
string EnabledParams = CurrentParams;
DrawBoolParam(ref EnabledParams, "VR Supported", VRSupportedFlag);
return EnabledParams;
}
public virtual bool SetVRSettings()
{
PlayerSettings.virtualRealitySupported = IgorJobConfig.IsBoolParamSet(VRSupportedFlag);
return true;
}
}
} | using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System;
using System.Reflection;
using System.Xml.Serialization;
using System.Linq;
namespace Igor
{
public class IgorBuildVR : IgorModuleBase
{
public static string VRSupportedFlag = "vrsupported";
public static StepID SetVRStep = new StepID("Set VR Settings", 270);
public override string GetModuleName()
{
return "Build.VR";
}
public override void RegisterModule()
{
IgorCore.RegisterNewModule(this);
}
public override void ProcessArgs(IIgorStepHandler StepHandler)
{
StepHandler.RegisterJobStep(SetVRStep, this, SetVRSettings);
}
public override bool ShouldDrawInspectorForParams(string CurrentParams)
{
return true;
}
public override string DrawJobInspectorAndGetEnabledParams(string CurrentParams)
{
string EnabledParams = CurrentParams;
DrawBoolParam(ref EnabledParams, "VR Supported", VRSupportedFlag);
return EnabledParams;
}
public virtual bool SetVRSettings()
{
PlayerSettings.virtualRealitySupported = IgorJobConfig.IsBoolParamSet(EnableVRFlag);
return true;
}
}
} | mit | C# |
5780454c3415d8555531a29be15f3ebe2431847f | Make the Cursor class's Bounds property publicly visible. This is needed because client code will need to know whether or not the cursor's bounds are intersecting an object, etc. | dneelyep/MonoGameUtils | MonoGameUtils/GameComponents/Cursor.cs | MonoGameUtils/GameComponents/Cursor.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace MonoGameUtils.GameComponents
{
/// <summary>
/// A simple cursor that will follow the user's mouse movements.
/// </summary>
public class Cursor : DrawableGameComponent
{
private Texture2D Texture { get; set; }
private Game game { get; set; }
// TODO Cursor width/height should be user-specifyable.
// TODO The user should have more options than just displaying a rectangle for the cursor.
private const int CURSOR_WIDTH = 10;
private const int CURSOR_HEIGHT = 10;
/// <summary>
/// The color of the Cursor.
/// </summary>
public Color Color { get; set; }
/// <summary>
/// The SpriteBatch to be used to draw this Cursor.
/// </summary>
private SpriteBatch spriteBatch { get; set; }
public Rectangle Bounds
{
get
{
return new Rectangle(Mouse.GetState().Position.X,
Mouse.GetState().Position.Y,
CURSOR_WIDTH,
CURSOR_HEIGHT);
}
}
public Cursor(Game game, SpriteBatch spriteBatch, Color color) : base(game)
{
this.game = game;
this.spriteBatch = spriteBatch;
this.Color = color;
}
public override void Initialize()
{
this.Texture = new Texture2D(game.GraphicsDevice, 1, 1);
this.Texture.SetData<Color>(new Color[] { Color.White });
base.Initialize();
}
public override void Draw(GameTime gameTime)
{
spriteBatch.Draw(Texture, Bounds, Color);
base.Draw(gameTime);
}
}
}
| using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace MonoGameUtils.GameComponents
{
/// <summary>
/// A simple cursor that will follow the user's mouse movements.
/// </summary>
public class Cursor : DrawableGameComponent
{
private Texture2D Texture { get; set; }
private Game game { get; set; }
// TODO Cursor width/height should be user-specifyable.
// TODO The user should have more options than just displaying a rectangle for the cursor.
private const int CURSOR_WIDTH = 10;
private const int CURSOR_HEIGHT = 10;
/// <summary>
/// The color of the Cursor.
/// </summary>
public Color Color { get; set; }
/// <summary>
/// The SpriteBatch to be used to draw this Cursor.
/// </summary>
private SpriteBatch spriteBatch { get; set; }
private Rectangle Bounds
{
get
{
return new Rectangle(Mouse.GetState().Position.X,
Mouse.GetState().Position.Y,
CURSOR_WIDTH,
CURSOR_HEIGHT);
}
}
public Cursor(Game game, SpriteBatch spriteBatch, Color color) : base(game)
{
this.game = game;
this.spriteBatch = spriteBatch;
this.Color = color;
}
public override void Initialize()
{
this.Texture = new Texture2D(game.GraphicsDevice, 1, 1);
this.Texture.SetData<Color>(new Color[] { Color.White });
base.Initialize();
}
public override void Draw(GameTime gameTime)
{
spriteBatch.Draw(Texture, Bounds, Color);
base.Draw(gameTime);
}
}
}
| mit | C# |
42d4ee8a57bcc596198ff4cd5f9f2290a596570c | add ApplicationBuilderExtensions tests | lvermeulen/Nanophone | test/Nanophone.AspNetCore.ApplicationServices.Tests/ApplicationBuilderExtensionsShould.cs | test/Nanophone.AspNetCore.ApplicationServices.Tests/ApplicationBuilderExtensionsShould.cs | using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Nanophone.Core;
using Nanophone.RegistryHost.InMemoryRegistry;
using Xunit;
namespace Nanophone.AspNetCore.ApplicationServices.Tests
{
public class ApplicationBuilderExtensionsShould
{
[Fact]
public Task AddRemoveTenantAndHealthCheck()
{
var registryHost = new InMemoryRegistryHost();
var hostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddNanophone(() => registryHost);
})
.Configure(async app =>
{
// add tenant
var registryInformation = app.AddTenant(nameof(ApplicationBuilderExtensionsShould), "1.0.0", new Uri("http://localhost:1234"));
Assert.NotNull(registryInformation);
var serviceRegistry = app.ApplicationServices.GetService<ServiceRegistry>();
Assert.NotNull(serviceRegistry);
var instances = await serviceRegistry.FindAllServicesAsync();
Assert.Equal(1, instances.Count);
// add health check
Assert.Null(app.AddHealthCheck(registryInformation, new Uri("http://localhost:4321")));
// remove health check
Assert.False(app.RemoveHealthCheck(null));
// remove tenant
Assert.True(app.RemoveTenant(registryInformation.Id));
instances = await serviceRegistry.FindAllServicesAsync();
Assert.Equal(0, instances.Count);
});
using (new TestServer(hostBuilder))
{
// ConfigureServices
// Configure
}
return Task.FromResult(0);
}
}
}
| using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Nanophone.Core;
using Nanophone.RegistryHost.InMemoryRegistry;
using Xunit;
namespace Nanophone.AspNetCore.ApplicationServices.Tests
{
public class ApplicationBuilderExtensionsShould
{
[Fact]
public Task AddTenant()
{
var registryHost = new InMemoryRegistryHost();
var hostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddNanophone(() => registryHost);
})
.Configure(async app =>
{
app.AddTenant(nameof(ApplicationBuilderExtensionsShould), "1.0.0", new Uri("http://localhost:1234"));
var serviceRegistry = app.ApplicationServices.GetService<ServiceRegistry>();
Assert.NotNull(serviceRegistry);
var instances = await serviceRegistry.FindAllServicesAsync();
Assert.Equal(1, instances.Count);
});
using (new TestServer(hostBuilder))
{
// ConfigureServices
// Configure
}
return Task.FromResult(0);
}
}
}
| mit | C# |
fc9dcf61f30cd8aafab8ade82f04440397a778e7 | add some xml comments to prevent IO exception | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | src/FilterLists.Api/Controllers/ListsController.cs | src/FilterLists.Api/Controllers/ListsController.cs | using FilterLists.Services.Contracts;
using Microsoft.AspNetCore.Mvc;
namespace FilterLists.Api.Controllers
{
//TODO: migrate controllers to separate projects by version, use dependency injection
//TODO: automate URL versioning
[Route("v1/[controller]")]
[Produces("application/json")]
public class ListsController : Controller
{
private readonly IListService listService;
public ListsController(IListService listService)
{
this.listService = listService;
}
/// <summary>
/// Get Lists
/// </summary>
/// <returns>All FilterLists</returns>
[HttpGet]
public IActionResult Get()
{
return Json(listService.GetAll());
}
}
} | using FilterLists.Services.Contracts;
using Microsoft.AspNetCore.Mvc;
namespace FilterLists.Api.Controllers
{
//TODO: migrate controllers to separate projects by version, use dependency injection
//TODO: automate URL versioning
[Route("v1/[controller]")]
[Produces("application/json")]
public class ListsController : Controller
{
private readonly IListService listService;
public ListsController(IListService listService)
{
this.listService = listService;
}
[HttpGet]
public IActionResult Get()
{
return Json(listService.GetAll());
}
}
} | mit | C# |
03a9474264e304eb071d1953326866280b674581 | fix preview 5 substring errors | SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake | src/Snowflake.Framework/Romfile/Tokenizer/StructuredFilenameTokenizer.cs | src/Snowflake.Framework/Romfile/Tokenizer/StructuredFilenameTokenizer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Snowflake.Romfile.Tokenizer
{
internal class StructuredFilenameTokenizer
{
private readonly string filename;
public StructuredFilenameTokenizer(string filename)
{
this.filename = filename;
}
public string GetTitle()
{
return Regex.Match(WithoutFileExtension(this.filename), @"(\([^]]*\))*(\[[^]]*\])*([\w\+\~\@\!\#\$\%\^\&\*\;\,\'\""\?\-\.\-\s]+)")
.Groups[3].Value.Trim();
}
private static string WithoutFileExtension(string rawTitle)
{
int index = rawTitle.LastIndexOf('.');
if (index < 0) return rawTitle;
string ext = rawTitle[index + 1..];
if (String.IsNullOrWhiteSpace(ext)) return rawTitle; // if whats after the period is whitespace
if (ext.StartsWith(' ')) return rawTitle; // if whats after the period is a space
if (!Regex.IsMatch(ext, "^[a-zA-Z0-9]*$")) return rawTitle; // if the extension is not alphanumeric
if (ext.Contains(' ')) return rawTitle; // if there is whitespace after the period
return rawTitle[0..index];
}
public IEnumerable<(string tokenValue, int tokenPosition)> GetParensTokens()
{
var tagData = Regex.Matches(this.filename, @"(\()([^)]+)(\))").ToList();
for (int i = 0; i < tagData.Count; i++)
{
yield return (tagData[i].Groups[2].Value, i);
}
}
public IEnumerable<(string tokenValue, int tokenPosition)> GetBracketTokens()
{
var tagData = Regex.Matches(this.filename, @"(\[)([^)]+)(\])").ToList();
for (int i = 0; i < tagData.Count; i++)
{
yield return (tagData[i].Groups[2].Value, i);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Snowflake.Romfile.Tokenizer
{
internal class StructuredFilenameTokenizer
{
private readonly string filename;
public StructuredFilenameTokenizer(string filename)
{
this.filename = filename;
}
public string GetTitle()
{
return Regex.Match(WithoutFileExtension(this.filename), @"(\([^]]*\))*(\[[^]]*\])*([\w\+\~\@\!\#\$\%\^\&\*\;\,\'\""\?\-\.\-\s]+)")
.Groups[3].Value.Trim();
}
private static string WithoutFileExtension(string rawTitle)
{
int index = rawTitle.LastIndexOf('.');
if (index < 0) return rawTitle;
string ext = rawTitle.Substring(index + 1..);
if (String.IsNullOrWhiteSpace(ext)) return rawTitle; // if whats after the period is whitespace
if (ext.StartsWith(' ')) return rawTitle; // if whats after the period is a space
if (!Regex.IsMatch(ext, "^[a-zA-Z0-9]*$")) return rawTitle; // if the extension is not alphanumeric
if (ext.Contains(' ')) return rawTitle; // if there is whitespace after the period
return rawTitle.Substring(0..index);
}
public IEnumerable<(string tokenValue, int tokenPosition)> GetParensTokens()
{
var tagData = Regex.Matches(this.filename, @"(\()([^)]+)(\))").ToList();
for (int i = 0; i < tagData.Count; i++)
{
yield return (tagData[i].Groups[2].Value, i);
}
}
public IEnumerable<(string tokenValue, int tokenPosition)> GetBracketTokens()
{
var tagData = Regex.Matches(this.filename, @"(\[)([^)]+)(\])").ToList();
for (int i = 0; i < tagData.Count; i++)
{
yield return (tagData[i].Groups[2].Value, i);
}
}
}
}
| mpl-2.0 | C# |
72fcb5c378a93a6e94fa4f46f6cbec16f7bb6e7b | fix a failing test | flickr-downloadr/flickr-downloadr,flickr-downloadr/flickr-downloadr,flickr-downloadr/flickr-downloadr,flickr-downloadr/flickr-downloadr,flickr-downloadr/flickr-downloadr | source/FloydPink.Flickr.Downloadr.UnitTests/ExtensionTests/JsonExtensionsTests.cs | source/FloydPink.Flickr.Downloadr.UnitTests/ExtensionTests/JsonExtensionsTests.cs | using FloydPink.Flickr.Downloadr.Model;
using FloydPink.Flickr.Downloadr.Repository.Extensions;
using NUnit.Framework;
namespace FloydPink.Flickr.Downloadr.UnitTests.ExtensionTests
{
[TestFixture]
public class JsonExtensionsTests
{
[Test]
public void WillConvertEmptyJsonStringToNewInstance()
{
string userAsJson = string.Empty;
var user = userAsJson.FromJson<User>();
Assert.IsNotNull(user);
Assert.AreEqual(string.Empty, user.Name);
Assert.AreEqual(string.Empty, user.Username);
Assert.AreEqual(string.Empty, user.UserNsId);
}
[Test]
public void WillConvertInstanceToJson()
{
var token = new Token("token", "secret");
string tokenJson = "{\"TokenString\":\"token\",\"Secret\":\"secret\"}";
Assert.AreEqual(tokenJson, token.ToJson());
}
[Test]
public void WillConvertJsonToInstance()
{
string tokenJson = "{\"TokenString\":\"token\",\"Secret\":\"secret\"}";
var token = tokenJson.FromJson<Token>();
Assert.AreEqual("token", token.TokenString);
Assert.AreEqual("secret", token.Secret);
}
[Test]
public void WillConvertJsonToUserInstance()
{
string userAsJson = "{\"Name\":\"name\",\"Username\":\"username\",\"UserNSId\":\"usernsid\"}";
var user = userAsJson.FromJson<User>();
Assert.AreEqual("name", user.Name);
Assert.AreEqual("username", user.Username);
Assert.AreEqual("usernsid", user.UserNsId);
}
[Test]
public void WillConvertUserInstanceToJson()
{
var user = new User("name", "username", "usernsid");
string userAsJson = "{\"Name\":\"name\",\"Username\":\"username\",\"UserNsId\":\"usernsid\",\"WelcomeMessage\":\"Welcome, name!\"}";
Assert.AreEqual(userAsJson, user.ToJson());
}
}
} | using FloydPink.Flickr.Downloadr.Model;
using FloydPink.Flickr.Downloadr.Repository.Extensions;
using NUnit.Framework;
namespace FloydPink.Flickr.Downloadr.UnitTests.ExtensionTests
{
[TestFixture]
public class JsonExtensionsTests
{
[Test]
public void WillConvertEmptyJsonStringToNewInstance()
{
string userAsJson = string.Empty;
var user = userAsJson.FromJson<User>();
Assert.IsNotNull(user);
Assert.AreEqual(string.Empty, user.Name);
Assert.AreEqual(string.Empty, user.Username);
Assert.AreEqual(string.Empty, user.UserNsId);
}
[Test]
public void WillConvertInstanceToJson()
{
var token = new Token("token", "secret");
string tokenJson = "{\"TokenString\":\"token\",\"Secret\":\"secret\"}";
Assert.AreEqual(tokenJson, token.ToJson());
}
[Test]
public void WillConvertJsonToInstance()
{
string tokenJson = "{\"TokenString\":\"token\",\"Secret\":\"secret\"}";
var token = tokenJson.FromJson<Token>();
Assert.AreEqual("token", token.TokenString);
Assert.AreEqual("secret", token.Secret);
}
[Test]
public void WillConvertJsonToUserInstance()
{
string userAsJson = "{\"Name\":\"name\",\"Username\":\"username\",\"UserNSId\":\"usernsid\"}";
var user = userAsJson.FromJson<User>();
Assert.AreEqual("name", user.Name);
Assert.AreEqual("username", user.Username);
Assert.AreEqual("usernsid", user.UserNsId);
}
[Test]
public void WillConvertUserInstanceToJson()
{
var user = new User("name", "username", "usernsid");
string userAsJson = "{\"Name\":\"name\",\"Username\":\"username\",\"UserNsId\":\"usernsid\"}";
Assert.AreEqual(userAsJson, user.ToJson());
}
}
} | mit | C# |
cfb2af90baf34d99dac21a8d5999c10470644ef5 | Enumerate child items in projects (Issue #11) | DanTup/TestAdapters,DanTup/TestAdapters | DanTup.TestAdapters/VsExtensions.cs | DanTup.TestAdapters/VsExtensions.cs | using System;
using System.Collections.Generic;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace DanTup.TestAdapters
{
/// <summary>
/// Extensions for getting Visual Studio projects, and their items; since the API for this is crufty.
/// </summary>
static class VsExtensions
{
public static IEnumerable<IVsHierarchy> GetProjects(this IVsSolution solutionService)
{
IEnumHierarchies projects;
var result = solutionService.GetProjectEnum((uint)__VSENUMPROJFLAGS.EPF_ALLINSOLUTION, Guid.Empty, out projects);
if (result == VSConstants.S_OK)
{
IVsHierarchy[] hierarchy = new IVsHierarchy[1] { null };
uint fetched = 0;
for (projects.Reset(); projects.Next(1, hierarchy, out fetched) == VSConstants.S_OK && fetched == 1; /*nothing*/)
{
yield return hierarchy[0];
}
}
}
public static IEnumerable<string> GetProjectItems(this IVsHierarchy project)
{
return project.GetProjectItems(VSConstants.VSITEMID_ROOT);
}
public static IEnumerable<string> GetProjectItems(this IVsHierarchy project, uint itemID)
{
object item;
// Get first item
project.GetProperty(itemID, (int)__VSHPROPID.VSHPROPID_FirstVisibleChild, out item);
while (item != null)
{
string canonicalName;
project.GetCanonicalName((uint)(int)item, out canonicalName);
if (!string.IsNullOrWhiteSpace(canonicalName))
yield return canonicalName;
// Call recursively for children
foreach (var child in project.GetProjectItems((uint)(int)item))
yield return child;
// Get next sibling
project.GetProperty((uint)(int)item, (int)__VSHPROPID.VSHPROPID_NextVisibleSibling, out item);
}
}
}
}
| using System;
using System.Collections.Generic;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace DanTup.TestAdapters
{
/// <summary>
/// Extensions for getting Visual Studio projects, and their items; since the API for this is crufty.
/// </summary>
static class VsExtensions
{
public static IEnumerable<IVsHierarchy> GetProjects(this IVsSolution solutionService)
{
IEnumHierarchies projects;
var result = solutionService.GetProjectEnum((uint)__VSENUMPROJFLAGS.EPF_ALLINSOLUTION, Guid.Empty, out projects);
if (result == VSConstants.S_OK)
{
IVsHierarchy[] hierarchy = new IVsHierarchy[1] { null };
uint fetched = 0;
for (projects.Reset(); projects.Next(1, hierarchy, out fetched) == VSConstants.S_OK && fetched == 1; /*nothing*/)
{
yield return hierarchy[0];
}
}
}
public static IEnumerable<string> GetProjectItems(this IVsHierarchy project)
{
object item;
// Get first item
project.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_FirstVisibleChild, out item);
while (item != null)
{
string canonicalName;
project.GetCanonicalName((uint)(int)item, out canonicalName);
if (!string.IsNullOrWhiteSpace(canonicalName))
yield return canonicalName;
// Get next sibling
project.GetProperty((uint)(int)item, (int)__VSHPROPID.VSHPROPID_NextVisibleSibling, out item);
}
}
}
}
| mit | C# |
f0a79b75e98419457f9b9591613d175f52cb0add | Add Spendable property to listunspent results | MetacoSA/NBitcoin,NicolasDorier/NBitcoin,stratisproject/NStratis,thepunctuatedhorizon/BrickCoinAlpha.0.0.1,MetacoSA/NBitcoin,lontivero/NBitcoin,dangershony/NStratis | NBitcoin/RPC/UnspentCoin.cs | NBitcoin/RPC/UnspentCoin.cs | using NBitcoin.DataEncoders;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.RPC
{
public class UnspentCoin
{
internal UnspentCoin(JObject unspent)
{
OutPoint = new OutPoint(uint256.Parse((string)unspent["txid"]), (uint)unspent["vout"]);
Address = Network.CreateFromBase58Data<BitcoinAddress>((string)unspent["address"]);
Account = (string)unspent["account"];
ScriptPubKey = new Script(Encoders.Hex.DecodeData((string)unspent["scriptPubKey"]));
var redeemScriptHex = (string)unspent["redeemScript"];
if (redeemScriptHex != null)
{
RedeemScript = new Script(Encoders.Hex.DecodeData(redeemScriptHex));
}
var amount = (decimal)unspent["amount"];
Amount = new Money((long)(amount * Money.COIN));
Confirmations = (uint)unspent["confirmations"];
// Added in Bitcoin Core 0.10.0
if (unspent["spendable"] != null)
{
IsSpendable = (bool)unspent["spendable"];
}
else
{
// Default to True for earlier versions, i.e. if not present
IsSpendable = true;
}
}
public OutPoint OutPoint
{
get;
private set;
}
public BitcoinAddress Address
{
get;
private set;
}
public string Account
{
get;
private set;
}
public Script ScriptPubKey
{
get;
private set;
}
public Script RedeemScript
{
get;
private set;
}
public uint Confirmations
{
get;
private set;
}
public Money Amount
{
get;
private set;
}
public Coin AsCoin()
{
return new Coin(OutPoint, new TxOut(Amount, ScriptPubKey));
}
public bool IsSpendable
{
get;
private set;
}
}
}
| using NBitcoin.DataEncoders;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.RPC
{
public class UnspentCoin
{
internal UnspentCoin(JObject unspent)
{
OutPoint = new OutPoint(uint256.Parse((string)unspent["txid"]), (uint)unspent["vout"]);
Address = Network.CreateFromBase58Data<BitcoinAddress>((string)unspent["address"]);
Account = (string)unspent["account"];
ScriptPubKey = new Script(Encoders.Hex.DecodeData((string)unspent["scriptPubKey"]));
var amount = (decimal)unspent["amount"];
Amount = new Money((long)(amount * Money.COIN));
Confirmations = (uint)unspent["confirmations"];
}
public OutPoint OutPoint
{
get;
private set;
}
public BitcoinAddress Address
{
get;
private set;
}
public string Account
{
get;
private set;
}
public Script ScriptPubKey
{
get;
private set;
}
public uint Confirmations
{
get;
private set;
}
public Money Amount
{
get;
private set;
}
public Coin AsCoin()
{
return new Coin(OutPoint, new TxOut(Amount, ScriptPubKey));
}
}
}
| mit | C# |
fe19b13bbd06b22e2ffd8d86c750b2825d926f80 | Add a algorithm usage comment | kornelijepetak/incident-cs | IncidentCS/Utils/UtilsRandomizer.cs | IncidentCS/Utils/UtilsRandomizer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace IncidentCS
{
public class UtilsRandomizer : IUtilsRandomizer
{
public virtual IRandomWheel<T> CreateWheel<T>(Dictionary<T, double> chances, bool saveChances = true)
{
return new RandomWheel<T>(chances, saveChances);
}
internal class RandomWheel<T> : IRandomWheel<T>
{
/// <summary>
/// Returns a random element from the wheel
/// </summary>
public T RandomElement
{
get
{
return getRandomElement(Incident.Primitive.DoubleUnit, 0, Count - 1);
}
}
/// <summary>
/// Returns a number of items in the wheel
/// </summary>
public int Count { get { return items.Length; } }
/// <summary>
/// Returns the chance assigned to the <paramref name="element"/>
/// </summary>
/// <param name="element"></param>
/// <returns>The chance assigned to the <paramref name="element"/></returns>
public double ChanceOf(T element)
{
if(dictionary == null)
throw new ArgumentException("To be able to get the chances later, set saveChances to true on Wheel construction.");
return dictionary[element];
}
private double[] chanceRanges;
private T[] items;
private Dictionary<T, double> dictionary;
internal RandomWheel(Dictionary<T, double> dictionary, bool saveChances)
{
if (saveChances)
{
this.dictionary = new Dictionary<T, double>(dictionary);
dictionary = this.dictionary;
}
chanceRanges = new double[dictionary.Count + 1];
items = new T[dictionary.Count];
double sum = dictionary.Values.Sum();
double cummulativeChance = 0;
int index = 0;
foreach (var item in dictionary)
{
items[index] = item.Key;
cummulativeChance += item.Value / sum;
chanceRanges[index + 1] = cummulativeChance;
index++;
}
}
private T getRandomElement(double val, int min, int max)
{
// Uses recursive binary-search to find the interval.
// ...
int mid = (min + max) / 2;
if (val < chanceRanges[mid])
return getRandomElement(val, min, mid - 1);
if (val > chanceRanges[mid + 1])
return getRandomElement(val, mid + 1, max);
return items[mid];
}
}
/// <summary>
/// Creates a string created by repeating a string.
/// </summary>
/// <param name="itemGenerator">A function that gives the original string</param>
/// <param name="count">Number of times to repeat</param>
/// <returns>A string created by repeating a string</returns>
public string Repeat(Func<string> itemGenerator, int count)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < count; i++)
result.Append(itemGenerator());
return result.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace IncidentCS
{
public class UtilsRandomizer : IUtilsRandomizer
{
public virtual IRandomWheel<T> CreateWheel<T>(Dictionary<T, double> chances, bool saveChances = true)
{
return new RandomWheel<T>(chances, saveChances);
}
internal class RandomWheel<T> : IRandomWheel<T>
{
/// <summary>
/// Returns a random element from the wheel
/// </summary>
public T RandomElement
{
get
{
return getRandomElement(Incident.Primitive.DoubleUnit, 0, Count - 1);
}
}
/// <summary>
/// Returns a number of items in the wheel
/// </summary>
public int Count { get { return items.Length; } }
/// <summary>
/// Returns the chance assigned to the <paramref name="element"/>
/// </summary>
/// <param name="element"></param>
/// <returns>The chance assigned to the <paramref name="element"/></returns>
public double ChanceOf(T element)
{
if(dictionary == null)
throw new ArgumentException("To be able to get the chances later, set saveChances to true on Wheel construction.");
return dictionary[element];
}
private double[] chanceRanges;
private T[] items;
private Dictionary<T, double> dictionary;
internal RandomWheel(Dictionary<T, double> dictionary, bool saveChances)
{
if (saveChances)
{
this.dictionary = new Dictionary<T, double>(dictionary);
dictionary = this.dictionary;
}
chanceRanges = new double[dictionary.Count + 1];
items = new T[dictionary.Count];
double sum = dictionary.Values.Sum();
double cummulativeChance = 0;
int index = 0;
foreach (var item in dictionary)
{
items[index] = item.Key;
cummulativeChance += item.Value / sum;
chanceRanges[index + 1] = cummulativeChance;
index++;
}
}
private T getRandomElement(double val, int min, int max)
{
int mid = (min + max) / 2;
if (val < chanceRanges[mid])
return getRandomElement(val, min, mid - 1);
if (val > chanceRanges[mid + 1])
return getRandomElement(val, mid + 1, max);
return items[mid];
}
}
/// <summary>
/// Creates a string created by repeating a string.
/// </summary>
/// <param name="itemGenerator">A function that gives the original string</param>
/// <param name="count">Number of times to repeat</param>
/// <returns>A string created by repeating a string</returns>
public string Repeat(Func<string> itemGenerator, int count)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < count; i++)
result.Append(itemGenerator());
return result.ToString();
}
}
}
| mit | C# |
eead7bcf7cd579b4e500588ceeba8f79b9909c22 | remove unreqired properties from table storage | narratr/story | Story.Ext/Handlers/StoryTableEntity.cs | Story.Ext/Handlers/StoryTableEntity.cs | using Microsoft.WindowsAzure.Storage.Table;
using Story.Core;
using Story.Core.Utils;
using System;
namespace Story.Ext.Handlers
{
public class StoryTableEntity : TableEntity
{
public static StoryTableEntity ToStoryTableEntity(IStory story)
{
if (story == null)
{
return null;
}
var storyTableEntity = new StoryTableEntity()
{
Name = story.Name,
Elapsed = story.Elapsed,
StartDateTime = story.StartDateTime,
InstanceId = story.InstanceId,
Json = story.Serialize()
};
storyTableEntity.UpdateKeys(story);
return storyTableEntity;
}
public string Name { get; set; }
public string InstanceId { get; set; }
public DateTime StartDateTime { get; set; }
public TimeSpan Elapsed { get; set; }
public string Json { get; set; }
private void UpdateKeys(IStory story)
{
PartitionKey = String.Format(story.StartDateTime.ToString("yyyyMMddHH"));
RowKey = story.StartDateTime.ToString("mmssffff") + story.InstanceId;
}
}
}
| using Microsoft.WindowsAzure.Storage.Table;
using Story.Core;
using Story.Core.Utils;
using System;
namespace Story.Ext.Handlers
{
public class StoryTableEntity : TableEntity
{
public static StoryTableEntity ToStoryTableEntity(IStory story)
{
if (story == null)
{
return null;
}
var storyTableEntity = new StoryTableEntity()
{
Name = story.Name,
Elapsed = story.Elapsed,
StartDateTime = story.StartDateTime,
InstanceId = story.InstanceId,
Json = story.Serialize()
};
storyTableEntity.UpdateKeys(story);
return storyTableEntity;
}
public string Name { get; set; }
public string InstanceId { get; set; }
public DateTime StartDateTime { get; set; }
public TimeSpan Elapsed { get; set; }
public string Data { get; set; }
public string Log { get; set; }
public string Json { get; set; }
private void UpdateKeys(IStory story)
{
PartitionKey = String.Format(story.StartDateTime.ToString("yyyyMMddHH"));
RowKey = story.StartDateTime.ToString("mmssffff") + story.InstanceId;
}
}
}
| mit | C# |
f7e5106175167c87426c7e7a4bacc7fcea91a1af | Update assemblyinfo & strong name version to 4.0.0.0 | 304NotModified/NLog.Web,NLog/NLog.Web | NLog.Web/Properties/AssemblyInfo.cs | NLog.Web/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
#if DNX
[assembly: AssemblyTitle("NLog.Web.ASPNET5")]
[assembly: AssemblyProduct("NLog.Web for ASP.NET Core")]
#else
[assembly: AssemblyTitle("NLog.Web")]
[assembly: AssemblyProduct("NLog.Web")]
#endif
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © NLog 2015-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("4.0.0.0")] //fixed
// 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("74d5915b-bea9-404c-b4d0-b663164def37")]
| 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.
#if DNX
[assembly: AssemblyTitle("NLog.Web.ASPNET5")]
[assembly: AssemblyProduct("NLog.Web for ASP.NET5")]
#else
[assembly: AssemblyTitle("NLog.Web")]
[assembly: AssemblyProduct("NLog.Web")]
#endif
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © NLog 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("74d5915b-bea9-404c-b4d0-b663164def37")]
| bsd-3-clause | C# |
c5c1a84fda1de1e5913ad8ae9282cd1036eeaffe | add mappingSet to MappingNode | GeertBellekens/UML-Tooling-Framework,GeertBellekens/UML-Tooling-Framework | MappingFramework/MappingNode.cs | MappingFramework/MappingNode.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UML = TSF.UmlToolingFramework.UML;
namespace MappingFramework
{
public interface MappingNode
{
string name { get; }
string displayName { get; }
ModelStructure structure { get; set; }
UML.Classes.Kernel.NamedElement source { get; set; }
UML.Classes.Kernel.NamedElement virtualOwner { get; set; }
bool isVirtual { get; }
IEnumerable<MappingNode> childNodes { get; }
IEnumerable<MappingNode> mappedChildNodes { get; }
IEnumerable<MappingNode> allChildNodes { get; }
bool showAll {get;set; }
bool isMapped { get;}
MappingNode parent { get; set; }
IEnumerable<Mapping> getMappings(MappingNode targetRootNode);
void addChildNode(MappingNode childNode);
IEnumerable<Mapping> mappings { get; }
void addMapping(Mapping mapping);
void removeMapping(Mapping mapping);
void setChildNodes();
Mapping mapTo(MappingNode targetNode);
bool isChildOf(MappingNode parentNode);
bool isChildOf(string uniqueID);
Mapping createEmptyMapping(MappingNode targetRootNode);
MappingNode findNode(List<string> mappingPathNames);
bool isReadOnly { get; }
MappingSet mappingSet { get; set;}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UML = TSF.UmlToolingFramework.UML;
namespace MappingFramework
{
public interface MappingNode
{
string name { get; }
string displayName { get; }
ModelStructure structure { get; set; }
UML.Classes.Kernel.NamedElement source { get; set; }
UML.Classes.Kernel.NamedElement virtualOwner { get; set; }
bool isVirtual { get; }
IEnumerable<MappingNode> childNodes { get; }
IEnumerable<MappingNode> mappedChildNodes { get; }
IEnumerable<MappingNode> allChildNodes { get; }
bool showAll {get;set; }
bool isMapped { get;}
MappingNode parent { get; set; }
IEnumerable<Mapping> getMappings(MappingNode targetRootNode);
void addChildNode(MappingNode childNode);
IEnumerable<Mapping> mappings { get; }
void addMapping(Mapping mapping);
void removeMapping(Mapping mapping);
void setChildNodes();
Mapping mapTo(MappingNode targetNode);
bool isChildOf(MappingNode parentNode);
bool isChildOf(string uniqueID);
Mapping createEmptyMapping(MappingNode targetRootNode);
MappingNode findNode(List<string> mappingPathNames);
bool isReadOnly { get; }
}
}
| bsd-2-clause | C# |
b482d34a05902d6a85f96fcdc3932c1c712f1de2 | add to the ArucoObjectController automatically at start. | enormand/aruco-unity,enormand/aruco-unity | src/aruco_unity_package/Assets/ArucoUnity/Scripts/Utility/ArucoObject.cs | src/aruco_unity_package/Assets/ArucoUnity/Scripts/Utility/ArucoObject.cs | using UnityEngine;
namespace ArucoUnity
{
/// \addtogroup aruco_unity_package
/// \{
namespace Utility
{
public abstract class ArucoObject : MonoBehaviour
{
// Editor fields
[SerializeField]
private ArucoObjectController arucoObjectController;
[SerializeField]
public int marginsSize;
[SerializeField]
public int markerBorderBits;
// Properties
public ArucoObjectController ArucoObjectController // TODO: multiple controllers?
{
get { return arucoObjectController; }
set
{
// Remove the previous controller
if (arucoObjectController != null)
{
arucoObjectController.Remove(this);
}
// Add the new controller
arucoObjectController = value;
if (arucoObjectController != null)
{
arucoObjectController.Add(this);
}
}
}
public int MarginsSize { get { return marginsSize; } set { marginsSize = value; } }
public int MarkerBorderBits { get { return markerBorderBits; } set { markerBorderBits = value; } }
/// <summary>
/// Hide at start, until it will be used by a <see cref="ArucoObjectController"/>.
/// </summary>
protected void Start()
{
gameObject.SetActive(false);
if (ArucoObjectController != null)
{
ArucoObjectController.Add(this);
}
}
}
}
/// \} aruco_unity_package
} | using UnityEngine;
namespace ArucoUnity
{
/// \addtogroup aruco_unity_package
/// \{
namespace Utility
{
public abstract class ArucoObject : MonoBehaviour
{
// Editor fields
[SerializeField]
private ArucoObjectController arucoObjectController;
[SerializeField]
public int marginsSize;
[SerializeField]
public int markerBorderBits;
// Properties
public ArucoObjectController ArucoObjectController // TODO: multiple controllers?
{
get { return arucoObjectController; }
set
{
// Remove the previous controller
if (arucoObjectController != null)
{
arucoObjectController.Remove(this);
}
// Add the new controller
arucoObjectController = value;
if (arucoObjectController != null)
{
ArucoObjectController.Add(this);
}
}
}
public int MarginsSize { get { return marginsSize; } set { marginsSize = value; } }
public int MarkerBorderBits { get { return markerBorderBits; } set { markerBorderBits = value; } }
/// <summary>
/// Hide at start, until it will be used by a <see cref="ArucoObjectController"/>.
/// </summary>
protected void Start()
{
gameObject.SetActive(false);
}
}
}
/// \} aruco_unity_package
} | bsd-3-clause | C# |
d9c5a69c3711cdf6b7accaca15575da3a77aae6a | Fix test in Release mode. | AvaloniaUI/Avalonia,SuperJMN/Avalonia,MrDaedra/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,susloparovdenis/Perspex,kekekeks/Perspex,OronDF343/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,OronDF343/Avalonia,grokys/Perspex,SuperJMN/Avalonia,susloparovdenis/Avalonia,susloparovdenis/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jazzay/Perspex,SuperJMN/Avalonia,kekekeks/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,punker76/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,akrisiun/Perspex,jkoritzinsky/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,susloparovdenis/Perspex,jkoritzinsky/Avalonia,grokys/Perspex | tests/Perspex.Markup.UnitTests/Binding/ExpressionObserverTests_PerspexProperty.cs | tests/Perspex.Markup.UnitTests/Binding/ExpressionObserverTests_PerspexProperty.cs | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using Perspex.Markup.Data;
using Xunit;
namespace Perspex.Markup.UnitTests.Binding
{
public class ExpressionObserverTests_PerspexProperty
{
public ExpressionObserverTests_PerspexProperty()
{
var foo = Class1.FooProperty;
}
[Fact]
public async void Should_Get_Simple_Property_Value()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Foo");
var result = await target.Take(1);
Assert.Equal("foo", result);
}
[Fact]
public void Should_Track_Simple_Property_Value()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Foo");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
data.SetValue(Class1.FooProperty, "bar");
Assert.Equal(new[] { "foo", "bar" }, result);
sub.Dispose();
}
private class Class1 : PerspexObject
{
public static readonly PerspexProperty<string> FooProperty =
PerspexProperty.Register<Class1, string>("Foo", defaultValue: "foo");
}
}
}
| // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using Perspex.Markup.Data;
using Xunit;
namespace Perspex.Markup.UnitTests.Binding
{
public class ExpressionObserverTests_PerspexProperty
{
[Fact]
public async void Should_Get_Simple_Property_Value()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Foo");
var result = await target.Take(1);
Assert.Equal("foo", result);
}
[Fact]
public void Should_Track_Simple_Property_Value()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Foo");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
data.SetValue(Class1.FooProperty, "bar");
Assert.Equal(new[] { "foo", "bar" }, result);
sub.Dispose();
}
private class Class1 : PerspexObject
{
public static readonly PerspexProperty<string> FooProperty =
PerspexProperty.Register<Class1, string>("Foo", defaultValue: "foo");
}
}
}
| mit | C# |
30c2ff4b2a1cf84da35a1c3e6557f3080fb4f5b4 | Update Version to 5.9 | lewischeng-ms/WebApi,lewischeng-ms/WebApi | OData/src/CommonAssemblyInfo.cs | OData/src/CommonAssemblyInfo.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.9.0.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.9.0.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.7.0.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.7.0.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif | mit | C# |
a2c93450a6aee17bf3de82109e83428b142a377c | Update ValuesOut.cs | EricZimmerman/RegistryPlugins | RegistryPlugin.Bam/ValuesOut.cs | RegistryPlugin.Bam/ValuesOut.cs | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.BamDam
{
public class ValuesOut:IValueOut
{
public ValuesOut(string program, DateTimeOffset executionTime)
{
Program = program;
ExecutionTime = executionTime;
}
public string Program { get; }
public DateTimeOffset ExecutionTime { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Program: {Program}";
public string BatchValueData2 =>$"Execution time: {ExecutionTime.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}";
public string BatchValueData3 { get; }
}
}
| using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.BamDam
{
public class ValuesOut:IValueOut
{
public ValuesOut(string program, DateTimeOffset executionTime)
{
Program = program;
ExecutionTime = executionTime;
}
public string Program { get; }
public DateTimeOffset ExecutionTime { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Program: {Program}";
public string BatchValueData2 =>$"Execution time: {ExecutionTime.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})";
public string BatchValueData3 { get; }
}
}
| mit | C# |
13a36dc014b7b601945913e0c29b9efd1f2b1cd3 | Set current dir as default dir for static files middleware configuration | bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework | Foundation/Server/Foundation.Api/Middlewares/StaticFilesMiddlewareConfiguration.cs | Foundation/Server/Foundation.Api/Middlewares/StaticFilesMiddlewareConfiguration.cs | using System;
using Foundation.Api.Contracts;
using Foundation.Core.Contracts;
using Foundation.Core.Models;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using NWebsec.Owin;
using Owin;
namespace Foundation.Api.Middlewares
{
public class StaticFilesMiddlewareConfiguration : IOwinMiddlewareConfiguration
{
private readonly IAppEnvironmentProvider _appEnvironmentProvider;
private readonly IPathProvider _pathProvider;
protected StaticFilesMiddlewareConfiguration()
{
}
public StaticFilesMiddlewareConfiguration(IAppEnvironmentProvider appEnvironmentProvider,
IPathProvider pathProvider)
{
if (appEnvironmentProvider == null)
throw new ArgumentNullException(nameof(appEnvironmentProvider));
if (pathProvider == null)
throw new ArgumentNullException(nameof(pathProvider));
_appEnvironmentProvider = appEnvironmentProvider;
_pathProvider = pathProvider;
}
public virtual void Configure(IAppBuilder owinApp)
{
AppEnvironment appEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();
string rootFolder = _pathProvider.MapPath(appEnvironment.GetConfig("StaticFilesRelativePath", "."));
PhysicalFileSystem fileSystem = new PhysicalFileSystem(rootFolder);
FileServerOptions options = new FileServerOptions
{
EnableDirectoryBrowsing = appEnvironment.DebugMode,
EnableDefaultFiles = false
};
options.DefaultFilesOptions.DefaultFileNames.Clear();
options.FileSystem = fileSystem;
string path = $@"/Files/V{appEnvironment.AppInfo.Version}";
owinApp.Map(path, innerApp =>
{
if (appEnvironment.DebugMode == true)
innerApp.Use<OwinNoCacheResponseMiddleware>();
else
innerApp.Use<OwinCacheResponseMiddleware>();
innerApp.UseXContentTypeOptions();
innerApp.UseXDownloadOptions();
innerApp.UseFileServer(options);
});
}
}
} | using System;
using Foundation.Api.Contracts;
using Foundation.Core.Contracts;
using Foundation.Core.Models;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using NWebsec.Owin;
using Owin;
namespace Foundation.Api.Middlewares
{
public class StaticFilesMiddlewareConfiguration : IOwinMiddlewareConfiguration
{
private readonly IAppEnvironmentProvider _appEnvironmentProvider;
private readonly IPathProvider _pathProvider;
protected StaticFilesMiddlewareConfiguration()
{
}
public StaticFilesMiddlewareConfiguration(IAppEnvironmentProvider appEnvironmentProvider,
IPathProvider pathProvider)
{
if (appEnvironmentProvider == null)
throw new ArgumentNullException(nameof(appEnvironmentProvider));
if (pathProvider == null)
throw new ArgumentNullException(nameof(pathProvider));
_appEnvironmentProvider = appEnvironmentProvider;
_pathProvider = pathProvider;
}
public virtual void Configure(IAppBuilder owinApp)
{
AppEnvironment appEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();
string rootFolder = _pathProvider.MapPath(appEnvironment.GetConfig<string>("StaticFilesRelativePath"));
PhysicalFileSystem fileSystem = new PhysicalFileSystem(rootFolder);
FileServerOptions options = new FileServerOptions
{
EnableDirectoryBrowsing = appEnvironment.DebugMode,
EnableDefaultFiles = false
};
options.DefaultFilesOptions.DefaultFileNames.Clear();
options.FileSystem = fileSystem;
string path = $@"/Files/V{appEnvironment.AppInfo.Version}";
owinApp.Map(path, innerApp =>
{
if (appEnvironment.DebugMode == true)
innerApp.Use<OwinNoCacheResponseMiddleware>();
else
innerApp.Use<OwinCacheResponseMiddleware>();
innerApp.UseXContentTypeOptions();
innerApp.UseXDownloadOptions();
innerApp.UseFileServer(options);
});
}
}
} | mit | C# |
dec9a135d8a8a4705f846bed5ed10808f7dc543a | Remove useless branch | hkdnet/Collection2Model | NemeValueCollectionMapper/Mapper.cs | NemeValueCollectionMapper/Mapper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Collection2Model.Mapper
{
public static class Mapper
{
public static T MappingFromNameValueCollection<T>(System.Collections.Specialized.NameValueCollection c)
where T : class, new()
{
var ret = new T();
var properties = typeof(T).GetProperties();
foreach (var p in properties)
{
var strVal = c[p.Name];
if (!p.CanWrite || strVal == null)
{
continue;
}
var val = Convert.ChangeType(strVal, p.PropertyType);
p.SetValue(ret, val, null);
}
return ret;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Collection2Model.Mapper
{
public static class Mapper
{
public static T MappingFromNameValueCollection<T>(System.Collections.Specialized.NameValueCollection c)
where T : class, new()
{
var ret = new T();
var properties = typeof(T).GetProperties();
foreach (var p in properties)
{
var strVal = c[p.Name];
if (!p.CanWrite || strVal == null)
{
continue;
}
if (p.PropertyType.FullName.Equals("System.String"))
{
p.SetValue(ret, strVal, null);
}
var val = Convert.ChangeType(strVal, p.PropertyType);
p.SetValue(ret, val, null);
}
return ret;
}
}
}
| mit | C# |
f37b002f37a946db3ee4d3bfc8f113370a561a8e | Update ZoomHelperTests.cs | wieslawsoltes/PanAndZoom,PanAndZoom/PanAndZoom,wieslawsoltes/MatrixPanAndZoomDemo,PanAndZoom/PanAndZoom,wieslawsoltes/PanAndZoom | tests/Avalonia.Controls.PanAndZoom.UnitTests/ZoomHelperTests.cs | tests/Avalonia.Controls.PanAndZoom.UnitTests/ZoomHelperTests.cs | using Xunit;
namespace Avalonia.Controls.PanAndZoom.UnitTests
{
public class ZoomHelperTests
{
private Matrix CreateMatrix(double scaleX = 1.0, double scaleY = 1.0, double offsetX = 0.0, double offsetY = 0.0)
{
return new Matrix(scaleX, 0, 0, scaleY, offsetX, offsetY);
}
[Fact]
public void CalculateScrollable_Default()
{
var bounds = new Rect(0, 0, 100, 100);
var matrix = CreateMatrix();
ZoomHelper.CalculateScrollable(bounds, matrix, out var extent, out var viewport, out var offset);
Assert.Equal(new Size(100, 100), extent);
Assert.Equal(new Size(100, 100), viewport);
Assert.Equal(new Vector(0, 0), offset);
}
[Fact]
public void CalculateScrollable_OffsetX_Negative()
{
var bounds = new Rect(0, 0, 100, 100);
var matrix = CreateMatrix(offsetX: -25);
ZoomHelper.CalculateScrollable(bounds, matrix, out var extent, out var viewport, out var offset);
Assert.Equal(new Size(125, 100), extent);
Assert.Equal(new Size(100, 100), viewport);
Assert.Equal(new Vector(100, 0), offset);
}
[Fact]
public void CalculateScrollable_OffsetX_Positive()
{
var bounds = new Rect(0, 0, 100, 100);
var matrix = CreateMatrix(offsetX: 25);
ZoomHelper.CalculateScrollable(bounds, matrix, out var extent, out var viewport, out var offset);
Assert.Equal(new Size(125, 100), extent);
Assert.Equal(new Size(100, 100), viewport);
Assert.Equal(new Vector(0, 0), offset);
}
[Fact]
public void CalculateScrollable_OffsetY_Negative()
{
var bounds = new Rect(0, 0, 100, 100);
var matrix = CreateMatrix(offsetY: -25);
ZoomHelper.CalculateScrollable(bounds, matrix, out var extent, out var viewport, out var offset);
Assert.Equal(new Size(100, 125), extent);
Assert.Equal(new Size(100, 100), viewport);
Assert.Equal(new Vector(0, 100), offset);
}
[Fact]
public void CalculateScrollable_OffsetY_Positive()
{
var bounds = new Rect(0, 0, 100, 100);
var matrix = CreateMatrix(offsetY: 25);
ZoomHelper.CalculateScrollable(bounds, matrix, out var extent, out var viewport, out var offset);
Assert.Equal(new Size(100, 125), extent);
Assert.Equal(new Size(100, 100), viewport);
Assert.Equal(new Vector(0, 0), offset);
}
}
}
| using Xunit;
namespace Avalonia.Controls.PanAndZoom.UnitTests
{
public class ZoomHelperTests
{
private Matrix CreateMatrix(double scaleX = 1.0, double scaleY = 1.0, double offsetX = 0.0, double offsetY = 0.0)
{
return new Matrix(scaleX, 0, 0, scaleY, offsetX, offsetY);
}
[Fact]
public void CalculateScrollable_Default()
{
var bounds = new Rect(0, 0, 100, 100);
var matrix = CreateMatrix();
ZoomHelper.CalculateScrollable(bounds, matrix, out var extent, out var viewport, out var offset);
Assert.Equal(new Size(100, 100), extent);
Assert.Equal(new Size(100, 100), viewport);
Assert.Equal(new Vector(0, 0), offset);
}
}
}
| mit | C# |
31fe3824cbcbefc28828b8e1b0f6c12bda8ffee6 | test commit | MassDebaters/DebateApp,MassDebaters/DebateApp,MassDebaters/DebateApp | DebateApp/DebateApp.Client/Startup.cs | DebateApp/DebateApp.Client/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
//thing
namespace DebateApp.Client
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DebateApp.Client
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| mit | C# |
3364176009a0b287db51846bbff08e29b63659ea | Update NewVhdVMTests.cs | AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell | src/ResourceManager/Compute/Commands.Compute.Test/ScenarioTests/NewVhdVMTests.cs | src/ResourceManager/Compute/Commands.Compute.Test/ScenarioTests/NewVhdVMTests.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
namespace Microsoft.Azure.Commands.Compute.Test.ScenarioTests
{
public class NewVhdVMTests
{
public NewVhdVMTests(Xunit.Abstractions.ITestOutputHelper output)
{
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
}
[Fact(Skip = "Skip until necessary fixes done: https://github.com/Azure/azure-powershell/issues/5692")]
[Trait(Category.AcceptanceType, Category.Flaky)]
public void TestWithValidVhdDiskFile()
{
ComputeTestController.NewInstance.RunPsTest("Test-NewAzureRmVhdVMWithValidDiskFile");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestWithInvalidVhdDiskFile()
{
ComputeTestController.NewInstance.RunPsTest("Test-NewAzureRmVhdVMWithInvalidDiskFile");
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
namespace Microsoft.Azure.Commands.Compute.Test.ScenarioTests
{
public class NewVhdVMTests
{
public NewVhdVMTests(Xunit.Abstractions.ITestOutputHelper output)
{
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
}
[Fact]
[Trait(Category.AcceptanceType, Category.Flaky)]
public void TestWithValidVhdDiskFile()
{
ComputeTestController.NewInstance.RunPsTest("Test-NewAzureRmVhdVMWithValidDiskFile");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestWithInvalidVhdDiskFile()
{
ComputeTestController.NewInstance.RunPsTest("Test-NewAzureRmVhdVMWithInvalidDiskFile");
}
}
}
| apache-2.0 | C# |
6e8bde2aeb59e2579a89ebe3486ae73ef72a41bb | Fix case in DatabaseFixture.ProviderName | fknx/linqpad-postgresql-driver | DynamicLinqPadPostgreSqlDriver.Tests/DynamicAssemblyGeneration/DatabaseFixture.cs | DynamicLinqPadPostgreSqlDriver.Tests/DynamicAssemblyGeneration/DatabaseFixture.cs | using System;
using System.Data;
using Dapper;
using Npgsql;
namespace DynamicLinqPadPostgreSqlDriver.Tests.DynamicAssemblyGeneration
{
public class DatabaseFixture : IDisposable
{
public const string ProviderName = "PostgreSQL";
public const string ConnectionString = "Server=localhost;Port=5433;Database=TestDb_DynamicAssemblyGeneration;User Id=postgres;Password=postgres;";
public IDbConnection DBConnection { get; }
public DatabaseFixture()
{
CreateDatabase();
DBConnection = new NpgsqlConnection(ConnectionString);
DBConnection.Open();
}
private static void CreateDatabase()
{
var cxBuilder = new NpgsqlConnectionStringBuilder(ConnectionString);
var database = cxBuilder.Database;
cxBuilder.Database = null;
var db = new NpgsqlConnection(cxBuilder.ToString());
db.Execute($"DROP DATABASE IF EXISTS \"{database}\"");
db.Execute($"CREATE DATABASE \"{database}\"");
}
public void Dispose()
{
DBConnection.Close();
}
}
}
| using System;
using System.Data;
using Dapper;
using Npgsql;
namespace DynamicLinqPadPostgreSqlDriver.Tests.DynamicAssemblyGeneration
{
public class DatabaseFixture : IDisposable
{
public const string ProviderName = "PostgreSql";
public const string ConnectionString = "Server=localhost;Port=5433;Database=TestDb_DynamicAssemblyGeneration;User Id=postgres;Password=postgres;";
public IDbConnection DBConnection { get; }
public DatabaseFixture()
{
CreateDatabase();
DBConnection = new NpgsqlConnection(ConnectionString);
DBConnection.Open();
}
private static void CreateDatabase()
{
var cxBuilder = new NpgsqlConnectionStringBuilder(ConnectionString);
var database = cxBuilder.Database;
cxBuilder.Database = null;
var db = new NpgsqlConnection(cxBuilder.ToString());
db.Execute($"DROP DATABASE IF EXISTS \"{database}\"");
db.Execute($"CREATE DATABASE \"{database}\"");
}
public void Dispose()
{
DBConnection.Close();
}
}
}
| mit | C# |
c390d47317c8d0bdac35b1a22d4c180ea79791bb | Add IsDevelopment and IsProduction extension methods | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Hosting.Abstractions/HostingEnvironmentExtensions.cs | src/Microsoft.AspNet.Hosting.Abstractions/HostingEnvironmentExtensions.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Hosting
{
public static class HostingEnvironmentExtensions
{
private const string DevelopmentEnvironmentName = "Development";
private const string ProductionEnvironmentName = "Production";
/// <summary>
/// Checks if the current hosting environment name is development.
/// </summary>
/// <param name="hostingEnvironment">An instance of <see cref="IHostingEnvironment"/> service.</param>
/// <returns>True if the environment name is Development, otherwise false.</returns>
public static bool IsDevelopment([NotNull]this IHostingEnvironment hostingEnvironment)
{
return hostingEnvironment.IsEnvironment(DevelopmentEnvironmentName);
}
/// <summary>
/// Checks if the current hosting environment name is Production.
/// </summary>
/// <param name="hostingEnvironment">An instance of <see cref="IHostingEnvironment"/> service.</param>
/// <returns>True if the environment name is Production, otherwise false.</returns>
public static bool IsProduction([NotNull]this IHostingEnvironment hostingEnvironment)
{
return hostingEnvironment.IsEnvironment(ProductionEnvironmentName);
}
/// <summary>
/// Compares the current hosting environment name against the specified value.
/// </summary>
/// <param name="hostingEnvironment">An instance of <see cref="IHostingEnvironment"/> service.</param>
/// <param name="environmentName">Environment name to validate against.</param>
/// <returns>True if the specified name is same as the current environment.</returns>
public static bool IsEnvironment(
[NotNull]this IHostingEnvironment hostingEnvironment,
string environmentName)
{
return string.Equals(
hostingEnvironment.EnvironmentName,
environmentName,
StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Gives the physical path corresponding to the given virtual path.
/// </summary>
/// <param name="hostingEnvironment">An instance of <see cref="IHostingEnvironment"/> service.</param>
/// <param name="virtualPath">Path relative to the root.</param>
/// <returns>Physical path corresponding to virtual path.</returns>
public static string MapPath(
[NotNull]this IHostingEnvironment hostingEnvironment,
string virtualPath)
{
if (virtualPath == null)
{
return hostingEnvironment.WebRootPath;
}
// On windows replace / with \.
virtualPath = virtualPath.Replace('/', Path.DirectorySeparatorChar);
return Path.Combine(hostingEnvironment.WebRootPath, virtualPath);
}
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Hosting
{
public static class HostingEnvironmentExtensions
{
/// <summary>
/// Compares the current hosting environment name against the specified value.
/// </summary>
/// <param name="hostingEnvironment">An instance of <see cref="IHostingEnvironment"/> service.</param>
/// <param name="environmentName">Environment name to validate against.</param>
/// <returns>True if the specified name is same as the current environment.</returns>
public static bool IsEnvironment(
[NotNull]this IHostingEnvironment hostingEnvironment,
string environmentName)
{
return string.Equals(
hostingEnvironment.EnvironmentName,
environmentName,
StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Gives the physical path corresponding to the given virtual path.
/// </summary>
/// <param name="hostingEnvironment">An instance of <see cref="IHostingEnvironment"/> service.</param>
/// <param name="virtualPath">Path relative to the root.</param>
/// <returns>Physical path corresponding to virtual path.</returns>
public static string MapPath(
[NotNull]this IHostingEnvironment hostingEnvironment,
string virtualPath)
{
if (virtualPath == null)
{
return hostingEnvironment.WebRootPath;
}
// On windows replace / with \.
virtualPath = virtualPath.Replace('/', Path.DirectorySeparatorChar);
return Path.Combine(hostingEnvironment.WebRootPath, virtualPath);
}
}
} | apache-2.0 | C# |
eca51930a990e4b0ee3fb889d047f5007bf9922c | Update AssemblyFileVersion | AzureRT/azure-powershell,ankurchoubeymsft/azure-powershell,juvchan/azure-powershell,Matt-Westphal/azure-powershell,CamSoper/azure-powershell,atpham256/azure-powershell,yoavrubin/azure-powershell,Matt-Westphal/azure-powershell,jtlibing/azure-powershell,dulems/azure-powershell,krkhan/azure-powershell,nemanja88/azure-powershell,juvchan/azure-powershell,hovsepm/azure-powershell,alfantp/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,alfantp/azure-powershell,haocs/azure-powershell,AzureRT/azure-powershell,nemanja88/azure-powershell,dulems/azure-powershell,hungmai-msft/azure-powershell,yoavrubin/azure-powershell,yantang-msft/azure-powershell,TaraMeyer/azure-powershell,jtlibing/azure-powershell,zhencui/azure-powershell,stankovski/azure-powershell,pankajsn/azure-powershell,CamSoper/azure-powershell,dulems/azure-powershell,akurmi/azure-powershell,seanbamsft/azure-powershell,TaraMeyer/azure-powershell,rohmano/azure-powershell,stankovski/azure-powershell,devigned/azure-powershell,DeepakRajendranMsft/azure-powershell,haocs/azure-powershell,AzureRT/azure-powershell,hungmai-msft/azure-powershell,jasper-schneider/azure-powershell,haocs/azure-powershell,hungmai-msft/azure-powershell,zhencui/azure-powershell,hovsepm/azure-powershell,AzureAutomationTeam/azure-powershell,akurmi/azure-powershell,nemanja88/azure-powershell,yantang-msft/azure-powershell,arcadiahlyy/azure-powershell,AzureAutomationTeam/azure-powershell,akurmi/azure-powershell,shuagarw/azure-powershell,naveedaz/azure-powershell,ankurchoubeymsft/azure-powershell,devigned/azure-powershell,seanbamsft/azure-powershell,yantang-msft/azure-powershell,jtlibing/azure-powershell,rohmano/azure-powershell,nemanja88/azure-powershell,atpham256/azure-powershell,CamSoper/azure-powershell,CamSoper/azure-powershell,yantang-msft/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,jasper-schneider/azure-powershell,hungmai-msft/azure-powershell,seanbamsft/azure-powershell,naveedaz/azure-powershell,Matt-Westphal/azure-powershell,nemanja88/azure-powershell,AzureRT/azure-powershell,atpham256/azure-powershell,alfantp/azure-powershell,TaraMeyer/azure-powershell,jtlibing/azure-powershell,ClogenyTechnologies/azure-powershell,pankajsn/azure-powershell,rohmano/azure-powershell,hovsepm/azure-powershell,juvchan/azure-powershell,rohmano/azure-powershell,yoavrubin/azure-powershell,ankurchoubeymsft/azure-powershell,yoavrubin/azure-powershell,alfantp/azure-powershell,atpham256/azure-powershell,Matt-Westphal/azure-powershell,zhencui/azure-powershell,yantang-msft/azure-powershell,haocs/azure-powershell,krkhan/azure-powershell,yoavrubin/azure-powershell,hovsepm/azure-powershell,dulems/azure-powershell,seanbamsft/azure-powershell,devigned/azure-powershell,akurmi/azure-powershell,zhencui/azure-powershell,juvchan/azure-powershell,ClogenyTechnologies/azure-powershell,alfantp/azure-powershell,stankovski/azure-powershell,arcadiahlyy/azure-powershell,TaraMeyer/azure-powershell,arcadiahlyy/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,shuagarw/azure-powershell,dulems/azure-powershell,ankurchoubeymsft/azure-powershell,devigned/azure-powershell,juvchan/azure-powershell,Matt-Westphal/azure-powershell,stankovski/azure-powershell,atpham256/azure-powershell,DeepakRajendranMsft/azure-powershell,arcadiahlyy/azure-powershell,krkhan/azure-powershell,stankovski/azure-powershell,shuagarw/azure-powershell,AzureRT/azure-powershell,jtlibing/azure-powershell,zhencui/azure-powershell,ClogenyTechnologies/azure-powershell,krkhan/azure-powershell,DeepakRajendranMsft/azure-powershell,seanbamsft/azure-powershell,AzureAutomationTeam/azure-powershell,rohmano/azure-powershell,hungmai-msft/azure-powershell,jasper-schneider/azure-powershell,DeepakRajendranMsft/azure-powershell,arcadiahlyy/azure-powershell,pankajsn/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,AzureRT/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,devigned/azure-powershell,DeepakRajendranMsft/azure-powershell,jasper-schneider/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,shuagarw/azure-powershell,pankajsn/azure-powershell,shuagarw/azure-powershell,naveedaz/azure-powershell,haocs/azure-powershell,TaraMeyer/azure-powershell,CamSoper/azure-powershell,seanbamsft/azure-powershell,hovsepm/azure-powershell,akurmi/azure-powershell,zhencui/azure-powershell,ClogenyTechnologies/azure-powershell,jasper-schneider/azure-powershell,pankajsn/azure-powershell,yantang-msft/azure-powershell,naveedaz/azure-powershell,ankurchoubeymsft/azure-powershell,krkhan/azure-powershell | src/ResourceManager/KeyVault/Commands.KeyVault/Properties/AssemblyInfo.cs | src/ResourceManager/KeyVault/Commands.KeyVault/Properties/AssemblyInfo.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.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("Microsoft Azure Powershell - Key Vault")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: Guid("2994548F-69B9-4DC2-8D19-52CC0C0C85BC")]
[assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyFileVersion("1.1.0")]
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.Azure.Commands.KeyVault.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Microsoft.Azure.Commands.KeyVault.Test")]
#endif
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.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("Microsoft Azure Powershell - Key Vault")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: Guid("2994548F-69B9-4DC2-8D19-52CC0C0C85BC")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyFileVersion)]
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.Azure.Commands.KeyVault.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Microsoft.Azure.Commands.KeyVault.Test")]
#endif
| apache-2.0 | C# |
f2abd6e507a3dad1e0a96b5ebe50cb8bd582f9f5 | Fix needy capacitor commands | samfun123/KtaneTwitchPlays | TwitchPlaysAssembly/Src/ComponentSolvers/Vanilla/NeedyDischargeComponentSolver.cs | TwitchPlaysAssembly/Src/ComponentSolvers/Vanilla/NeedyDischargeComponentSolver.cs | using System;
using System.Collections;
public class NeedyDischargeComponentSolver : ComponentSolver
{
public NeedyDischargeComponentSolver(TwitchModule module) :
base(module)
{
_dischargeButton = ((NeedyDischargeComponent) module.BombComponent).DischargeButton;
ModInfo = ComponentSolverFactory.GetModuleInfo("NeedyDischargeComponentSolver", "!{0} hold 7 [hold the lever for 7 seconds]", "Capacitor Discharge");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
string[] commandParts = inputCommand.Trim().Split(' ');
if (commandParts.Length != 2 || !commandParts[0].Equals("hold", StringComparison.InvariantCultureIgnoreCase))
yield break;
if (!float.TryParse(commandParts[1], out float holdTime)) yield break;
yield return "hold";
if (holdTime > 9) yield return "elevator music";
DoInteractionStart(_dischargeButton);
yield return new WaitForSecondsWithCancel(holdTime);
DoInteractionEnd(_dischargeButton);
}
private readonly SpringedSwitch _dischargeButton;
}
| using System;
using System.Collections;
public class NeedyDischargeComponentSolver : ComponentSolver
{
public NeedyDischargeComponentSolver(TwitchModule module) :
base(module)
{
_dischargeButton = ((NeedyDischargeComponent) module.BombComponent).DischargeButton;
ModInfo = ComponentSolverFactory.GetModuleInfo("NeedyDischargeComponentSolver", "!{0} hold 7 [hold the lever for 7 seconds]", "Capacitor Discharge");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
string[] commandParts = inputCommand.Trim().Split(' ');
if (commandParts.Length != 2 && !commandParts[0].Equals("hold", StringComparison.InvariantCultureIgnoreCase))
yield break;
if (!float.TryParse(commandParts[1], out float holdTime)) yield break;
yield return "hold";
if (holdTime > 9) yield return "elevator music";
DoInteractionStart(_dischargeButton);
yield return new WaitForSecondsWithCancel(holdTime);
DoInteractionEnd(_dischargeButton);
}
private readonly SpringedSwitch _dischargeButton;
}
| mit | C# |
53b2bf1be85b0a9d06204c6c9544a08fbdfd9655 | Return dialler session guid when subscribing | Paymentsense/Dapper.SimpleSave | PS.Mothership.Core/PS.Mothership.Core.Common/Contracts/IDiallerService.cs | PS.Mothership.Core/PS.Mothership.Core.Common/Contracts/IDiallerService.cs | using PS.Mothership.Core.Common.Rellaid.Dto;
using PS.Mothership.Core.Common.Template.Dial;
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace PS.Mothership.Core.Common.Contracts
{
[ServiceContract(Name = "DiallerService")]
public interface IDiallerService
{
[OperationContract]
ValidUserInfoDto ValidateUser(Guid mothershipSessionGuid);
[OperationContract]
Guid LogDiallerSessionSubscribe(Guid mothershipSessionGuid, DateTime startDateTime);
[OperationContract]
void LogDiallerSessionUnsubscribe(Guid mothershipSessionGuid, DateTime endDateTime, bool wasForcedLogout, LogoutReasonEnum logoutReason);
[OperationContract]
List<InboundQueueDetailsDto> GetInboundQueueDetails();
[OperationContract]
List<MissingCallRecordingsDto> GetMissingCallRecordings(DateTime dateStart, DateTime dateEnd);
[OperationContract]
void UpdateRecorderCallIdForCallGuid(Guid callGuid, long recorderCallId, Guid mothershipSessionGuid);
[OperationContract]
Dictionary<long, long> TryToFindDiallerDepartmentsByUserGuid(Guid userGuid);
[OperationContract]
List<CallStatsDto> GetCallTotalsForToday();
[OperationContract]
void InsertCallRecordingEvent(CallRecordingEventDto callRecordingEvent);
[OperationContract]
Guid LogDiallerModeChange(Guid mothershipSessionGuid, DateTime diallerStartTime, ModeEnum diallerMode);
[OperationContract]
void LogNewDiallerCall(NewDiallerCallDto diallerCall);
[OperationContract]
void LogFinalisedCall(FinalisedDiallerCallDto diallerCall);
}
}
| using PS.Mothership.Core.Common.Rellaid.Dto;
using PS.Mothership.Core.Common.Template.Dial;
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace PS.Mothership.Core.Common.Contracts
{
[ServiceContract(Name = "DiallerService")]
public interface IDiallerService
{
[OperationContract]
ValidUserInfoDto ValidateUser(Guid mothershipSessionGuid);
[OperationContract]
void LogDiallerSessionSubscribe(Guid mothershipSessionGuid, DateTime startDateTime);
[OperationContract]
void LogDiallerSessionUnsubscribe(Guid mothershipSessionGuid, DateTime endDateTime, bool wasForcedLogout, LogoutReasonEnum logoutReason);
[OperationContract]
List<InboundQueueDetailsDto> GetInboundQueueDetails();
[OperationContract]
List<MissingCallRecordingsDto> GetMissingCallRecordings(DateTime dateStart, DateTime dateEnd);
[OperationContract]
void UpdateRecorderCallIdForCallGuid(Guid callGuid, long recorderCallId, Guid mothershipSessionGuid);
[OperationContract]
Dictionary<long, long> TryToFindDiallerDepartmentsByUserGuid(Guid userGuid);
[OperationContract]
List<CallStatsDto> GetCallTotalsForToday();
[OperationContract]
void InsertCallRecordingEvent(CallRecordingEventDto callRecordingEvent);
[OperationContract]
Guid LogDiallerModeChange(Guid mothershipSessionGuid, DateTime diallerStartTime, ModeEnum diallerMode);
[OperationContract]
void LogNewDiallerCall(NewDiallerCallDto diallerCall);
[OperationContract]
void LogFinalisedCall(FinalisedDiallerCallDto diallerCall);
}
}
| mit | C# |
503f042858e5d814290be0ced46da61457ad8c8d | Fix critical bug about subscribe | leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net | JoinRpg.Domain/SubscribeExtensions.cs | JoinRpg.Domain/SubscribeExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers;
namespace JoinRpg.Domain
{
public static class SubscribeExtensions
{
public static IEnumerable<User> GetSubscriptions(this ForumThread claim, [CanBeNull] IEnumerable<User> extraRecepients, bool isVisibleToPlayer)
{
return
claim.Subscriptions //get subscriptions on forum
.Select(u => u.User) //Select users
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || !claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
}
public static IEnumerable<User> GetSubscriptions(
this Claim claim,
Func<UserSubscription, bool> predicate,
[CanBeNull] IEnumerable<User> extraRecepients,
bool isVisibleToPlayer)
{
return claim.GetTarget().GetGroupsPartOf() //Get all groups for claim
.SelectMany(g => g.Subscriptions) //get subscriptions on groups
.Union(claim.Subscriptions) //subscribtions on claim
.Union(claim.Character?.Subscriptions ?? new UserSubscription[] {}) //and on characters
.Where(predicate) //type of subscribe (on new comments, on new claims etc.)
.Select(u => u.User) //Select users
.Union(claim.ResponsibleMasterUser) //Responsible master is always subscribed on everything
.Union(claim.Player) //...and player himself also
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers;
namespace JoinRpg.Domain
{
public static class SubscribeExtensions
{
public static IEnumerable<User> GetSubscriptions(this ForumThread claim, [CanBeNull] IEnumerable<User> extraRecepients, bool isVisibleToPlayer)
{
return
claim.Subscriptions //get subscriptions on forum
.Select(u => u.User) //Select users
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || !claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
}
public static IEnumerable<User> GetSubscriptions(
this Claim claim,
Func<UserSubscription, bool> predicate,
[CanBeNull] IEnumerable<User> extraRecepients,
bool isVisibleToPlayer)
{
return claim.GetTarget().GetGroupsPartOf() //Get all groups for claim
.SelectMany(g => g.Subscriptions) //get subscriptions on groups
.Union(claim.Subscriptions) //subscribtions on claim
.Union(claim.Character?.Subscriptions ?? new UserSubscription[] {}) //and on characters
.Where(predicate) //type of subscribe (on new comments, on new claims etc.)
.Select(u => u.User) //Select users
.Union(claim.ResponsibleMasterUser) //Responsible master is always subscribed on everything
.Union(claim.Player) //...and player himself also
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || !claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
;
}
}
}
| mit | C# |
9d26e686ef418257b55a975e1a837855dbf71183 | Add DirectPay to ApplicationType | jzebedee/lcapi | LCAPI/LCAPI/Models/ApplicationType.cs | LCAPI/LCAPI/Models/ApplicationType.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LendingClub.Models
{
public enum ApplicationType
{
// Valid values are "INDIVIDUAL" or "JOINT"
None = 0,
Individual,
Joint,
DirectPay
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LendingClub.Models
{
public enum ApplicationType
{
// Valid values are "INDIVIDUAL" or "JOINT"
None = 0,
Individual,
Joint
}
}
| agpl-3.0 | C# |
704f4f8dd9d8108e166db9c69895c24232b798b9 | add code to where you can go to the details page of an opportunity that has been applied for to be able to review qualifications | CS297Sp16/LCC_Co-op_Site,CS297Sp16/LCC_Co-op_Site,CS297Sp16/LCC_Co-op_Site | Coop_Listing_Site/Coop_Listing_Site/Views/Coop/AppDetails.cshtml | Coop_Listing_Site/Coop_Listing_Site/Views/Coop/AppDetails.cshtml | @model Coop_Listing_Site.Models.Application
@{
ViewBag.Title = "Application Details";
}
<h2>Application Details</h2>
<div>
<h4>Opportunity</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Student.User.LastName)
</dt>
<dd>
@Html.DisplayFor(model => model.Student.User.LastName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Student.User.FirstName)
</dt>
<dd>
@Html.DisplayFor(model => model.Student.User.FirstName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Student.LNumber)
</dt>
<dd>
@Html.DisplayFor(model => model.Student.LNumber)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Message)
</dt>
<dd>
@Html.DisplayFor(model => model.Message)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Opportunity.CompanyName)
</dt>
<dd>
@Html.DisplayFor(model => model.Opportunity.CompanyName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Opportunity.CoopPositionTitle)
</dt>
<dd>
@*@Html.DisplayFor(model => model.Opportunity.CoopPositionTitle)*@
@Html.ActionLink(Model.Opportunity.CoopPositionTitle, "Details", new { id = Model.Opportunity.OpportunityID })
</dd>
<dt>
@Html.DisplayNameFor(model => model.Files)
</dt>
<dd>
@foreach(var file in Model.Files)
{
@Html.ActionLink(file.FileName, "GetFile", new { id = file.UserFileID})
<br />
}
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Back to List", "Applications") ||
@Html.ActionLink("Delete Application", "AppDelete", new { id = Model.ApplicationId })
</p> | @model Coop_Listing_Site.Models.Application
@{
ViewBag.Title = "Application Details";
}
<h2>Application Details</h2>
<div>
<h4>Opportunity</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Student.User.LastName)
</dt>
<dd>
@Html.DisplayFor(model => model.Student.User.LastName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Student.User.FirstName)
</dt>
<dd>
@Html.DisplayFor(model => model.Student.User.FirstName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Student.LNumber)
</dt>
<dd>
@Html.DisplayFor(model => model.Student.LNumber)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Message)
</dt>
<dd>
@Html.DisplayFor(model => model.Message)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Opportunity.CompanyName)
</dt>
<dd>
@Html.DisplayFor(model => model.Opportunity.CompanyName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Opportunity.CoopPositionTitle)
</dt>
<dd>
@Html.DisplayFor(model => model.Opportunity.CoopPositionTitle)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Files)
</dt>
<dd>
@foreach(var file in Model.Files)
{
@Html.ActionLink(file.FileName, "GetFile", new { id = file.UserFileID})
<br />
}
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Back to List", "Applications") ||
@Html.ActionLink("Delete Application", "AppDelete", new { id = Model.ApplicationId })
</p> | mit | C# |
658df31cb2387f82191c1b7357623e6a16b8d9b8 | Fix wrong timescale being forced on win/loss | NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare | Assets/Microgames/_Bosses/YoumuSlash/Scripts/YoumuSlashTimingEffectsController.cs | Assets/Microgames/_Bosses/YoumuSlash/Scripts/YoumuSlashTimingEffectsController.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class YoumuSlashTimingEffectsController : MonoBehaviour
{
[SerializeField]
private AudioSource musicSource;
[SerializeField]
private float pitchMult = 1f;
[SerializeField]
private float timeScaleMult = 1f;
[SerializeField]
private float volumeMult = 1f;
bool failed = false;
bool ended = false;
float initialTimeScale;
float initialVolume;
void Start ()
{
YoumuSlashPlayerController.onFail += onFail;
YoumuSlashPlayerController.onGameplayEnd += onGameplayEnd;
initialTimeScale = Time.timeScale;
initialVolume = musicSource.volume;
}
void onGameplayEnd()
{
ended = true;
}
void onFail()
{
failed = true;
}
private void LateUpdate()
{
if (MicrogameController.instance.getVictoryDetermined())
Time.timeScale = initialTimeScale;
else if (ended)
Time.timeScale = timeScaleMult * initialTimeScale;
if (failed)
musicSource.pitch = Time.timeScale * pitchMult;
musicSource.volume = volumeMult * initialVolume;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class YoumuSlashTimingEffectsController : MonoBehaviour
{
[SerializeField]
private AudioSource musicSource;
[SerializeField]
private float pitchMult = 1f;
[SerializeField]
private float timeScaleMult = 1f;
[SerializeField]
private float volumeMult = 1f;
bool failed = false;
bool ended = false;
float initialTimeScale;
float initialVolume;
void Start ()
{
YoumuSlashPlayerController.onFail += onFail;
YoumuSlashPlayerController.onGameplayEnd += onGameplayEnd;
initialTimeScale = Time.timeScale;
initialVolume = musicSource.volume;
}
void onGameplayEnd()
{
ended = true;
}
void onFail()
{
failed = true;
}
private void LateUpdate()
{
if (MicrogameController.instance.getVictoryDetermined())
Time.timeScale = initialVolume;
else if (ended)
Time.timeScale = timeScaleMult * initialTimeScale;
if (failed)
musicSource.pitch = Time.timeScale * pitchMult;
musicSource.volume = volumeMult * initialVolume;
}
}
| mit | C# |
558aef80a10d553ca29b1a3b1b108fdef6c90222 | Remove tests | jlewin/MatterControl,jlewin/MatterControl,CodeMangler/MatterControl,MatterHackers/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,CodeMangler/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,MatterHackers/MatterControl,mmoening/MatterControl,tellingmachine/MatterControl,jlewin/MatterControl,CodeMangler/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,rytz/MatterControl,jlewin/MatterControl,tellingmachine/MatterControl,rytz/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,MatterHackers/MatterControl,rytz/MatterControl | Tests/MatterControl.Tests/MatterControl/PrinterWhiteListTests.cs | Tests/MatterControl.Tests/MatterControl/PrinterWhiteListTests.cs | using MatterHackers.MatterControl;
using NUnit.Framework;
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Globalization;
using MatterHackers.MatterControl.SlicerConfiguration;
namespace MatterControl.Tests.MatterControl
{
[TestFixture]
class PrinterWhiteListTests
{
[Test, Category("PrinterWhiteListTests")]
public void DesktopCalibrationPartsInSettings()
{
string settingsJsonPath = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "StaticData", "OEMSettings", "Settings.json"));
if (File.Exists(settingsJsonPath))
{
string[] lines = File.ReadAllLines(settingsJsonPath);
bool hasCoin = lines.Where(l => l.Contains("\"MatterControl - Coin.stl\",")).Any();
bool hasTabletStand = lines.Where(l => l.Contains("\"MatterControl - Stand.stl\",")).Any();
Assert.IsTrue(hasCoin, "Expected coin file not found");
Assert.IsTrue(hasTabletStand, "Expected stand file not found");
}
}
[Test, Category("SamplePartsTests")]
public void DesktopCalibrationPartsExist()
{
string samplePartsPath = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "StaticData", "OEMSettings", "SampleParts"));
string[] files = Directory.GetFiles(samplePartsPath);
bool hasTabletStand = files.Where(l => l.Contains("MatterControl - Stand.stl")).Any();
bool hasCoin = files.Where(l => l.Contains("MatterControl - Coin.stl")).Any();
Assert.IsTrue(hasCoin, "Expected coin file not found");
Assert.IsTrue(hasTabletStand, "Expected stand file not found");
}
}
}
| using MatterHackers.MatterControl;
using NUnit.Framework;
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Globalization;
using MatterHackers.MatterControl.SlicerConfiguration;
namespace MatterControl.Tests.MatterControl
{
[TestFixture]
class PrinterWhiteListTests
{
[Test, Category("PrinterWhiteListTests")]
public void DesktopCalibrationPartsInSettings()
{
string settingsJsonPath = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "StaticData", "OEMSettings", "Settings.json"));
if (File.Exists(settingsJsonPath))
{
string[] lines = File.ReadAllLines(settingsJsonPath);
bool hasCoin = lines.Where(l => l.Contains("\"MatterControl - Coin.stl\",")).Any();
bool hasTabletStand = lines.Where(l => l.Contains("\"MatterControl - Stand.stl\",")).Any();
Assert.IsTrue(hasCoin, "Expected coin file not found");
Assert.IsTrue(hasTabletStand, "Expected stand file not found");
}
}
[Test, Category("SamplePartsTests")]
public void DesktopCalibrationPartsExist()
{
string samplePartsPath = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "StaticData", "OEMSettings", "SampleParts"));
string[] files = Directory.GetFiles(samplePartsPath);
bool hasTabletStand = files.Where(l => l.Contains("MatterControl - Stand.stl")).Any();
bool hasCoin = files.Where(l => l.Contains("MatterControl - Coin.stl")).Any();
Assert.IsTrue(hasCoin, "Expected coin file not found");
Assert.IsTrue(hasTabletStand, "Expected stand file not found");
}
[Test, Category("SamplePartsTests")]
public void AndroidCalibrationPartsInSettings()
{
string samplePartsPath = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "..", "MatterControlAndroid", "MatterControlAndroid", "DefaultOEMSettings", "Assets", "StaticData", "OEMSettings", "SampleParts"));
string[] files = Directory.GetFiles(samplePartsPath);
bool hasTabletStand = files.Where(l => l.Contains("MatterControl - Stand.stl")).Any();
bool hasCoin = files.Where(l => l.Contains("MatterControl - Coin.stl")).Any();
Assert.IsTrue(hasCoin, "Expected coin file not found");
Assert.IsTrue(hasTabletStand, "Expected stand file not found");
}
[Test, Category("SamplePartsTests")]
public void AndroidCalibrationPartsExist()
{
string samplePartsPath = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "..", "MatterControlAndroid", "MatterControlAndroid", "DefaultOEMSettings", "Assets", "StaticData", "OEMSettings", "Settings.json"));
string[] lines = File.ReadAllLines(samplePartsPath);
bool hasTabletStand = lines.Where(l => l.Contains("MatterControl - Stand.stl")).Any();
bool hasCoin = lines.Where(l => l.Contains("MatterControl - Coin.stl")).Any();
Assert.IsTrue(hasCoin, "Expected coin file not found");
Assert.IsTrue(hasTabletStand, "Expected stand file not found");
}
}
}
| bsd-2-clause | C# |
0ddb0b505c350072fc5e705f1c04c30db06a6d4c | Change type in error from of to or | USDXStartups/CalendarHelper | shared/AppSettingsHelper.csx | shared/AppSettingsHelper.csx | #load "LogHelper.csx"
using System.Configuration;
public static class AppSettingsHelper
{
public static string GetAppSetting(string SettingName, bool LogValue = true )
{
string SettingValue = "";
try
{
SettingValue = ConfigurationManager.AppSettings[SettingName].ToString();
if ((!String.IsNullOrEmpty(SettingValue)) && LogValue)
{
LogHelper.Info($"Retreived AppSetting {SettingName} with a value of {SettingValue}");
}
else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue)
{
LogHelper.Info($"Retreived AppSetting {SettingName} but logging value was turned off");
}
else if(!String.IsNullOrEmpty(SettingValue))
{
LogHelper.Info($"AppSetting {SettingName} was null or empty");
}
}
catch (ConfigurationErrorsException ex)
{
LogHelper.Error($"Unable to find AppSetting {SettingName} with exception of {ex.Message}");
}
catch (System.Exception ex)
{
LogHelper.Error($"Looking for AppSetting {SettingName} caused an exception of {ex.Message}");
}
return SettingValue;
}
} | #load "LogHelper.csx"
using System.Configuration;
public static class AppSettingsHelper
{
public static string GetAppSetting(string SettingName, bool LogValue = true )
{
string SettingValue = "";
try
{
SettingValue = ConfigurationManager.AppSettings[SettingName].ToString();
if ((!String.IsNullOrEmpty(SettingValue)) && LogValue)
{
LogHelper.Info($"Retreived AppSetting {SettingName} with a value of {SettingValue}");
}
else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue)
{
LogHelper.Info($"Retreived AppSetting {SettingName} but logging value was turned off");
}
else if(!String.IsNullOrEmpty(SettingValue))
{
LogHelper.Info($"AppSetting {SettingName} was null of empty");
}
}
catch (ConfigurationErrorsException ex)
{
LogHelper.Error($"Unable to find AppSetting {SettingName} with exception of {ex.Message}");
}
catch (System.Exception ex)
{
LogHelper.Error($"Looking for AppSetting {SettingName} caused an exception of {ex.Message}");
}
return SettingValue;
}
} | mit | C# |
6074bee744e8148d00481aac874827e3c644ff6d | clean up | dkataskin/bstrkr | bstrkr.mobile/bstrkr.mvvm/ViewModels/SelectRouteStopViewModel.cs | bstrkr.mobile/bstrkr.mvvm/ViewModels/SelectRouteStopViewModel.cs | using System;
namespace bstrkr.mvvm.viewmodels
{
public class SelectRouteStopViewModel : BusTrackerViewModelBase
{
}
} | using System;
namespace bstrkr.mvvm.viewmodels
{
public class SelectRouteStopViewModel : BusTrackerViewModelBase
{
public SelectRouteStopViewModel()
{
}
}
} | bsd-2-clause | C# |
5cce81a41f85a0f5de44da2b78ba3fc5a4bfc062 | Make BulletSpace bounds readonly (#5) | ForNeVeR/TankDriver | TankDriver.App/Logic/BulletSpace.cs | TankDriver.App/Logic/BulletSpace.cs | using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using TankDriver.Models;
namespace TankDriver.Logic
{
internal class BulletSpace
{
public List<Bullet> Bullets { get; }
private readonly Rectangle _bounds;
private TextureStorage _textureStorage;
public BulletSpace (Rectangle bounds)
{
Bullets = new List<Bullet> ();
_bounds = bounds;
}
public void AddBullet (double x, double y, double heading)
{
var bullet = new Bullet (x, y, heading);
bullet.GetModel ().LoadTextures (_textureStorage);
Bullets.Add (bullet);
}
public void LoadTexture(TextureStorage textureStorage)
{
_textureStorage = textureStorage;
}
public void Render(SpriteBatch spriteBatch)
{
foreach (var bullet in Bullets) {
bullet.GetModel ().Render (spriteBatch);
}
}
public void Update(TimeSpan timeDelta)
{
foreach (var bullet in Bullets) {
bullet.UpdatePosition (timeDelta);
}
Bullets.RemoveAll (delegate(Bullet bullet) {
return !_bounds.Contains((Vector2) bullet.Position);
});
}
}
}
| using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using TankDriver.Models;
namespace TankDriver.Logic
{
internal class BulletSpace
{
public List<Bullet> Bullets { get; }
private Rectangle _bounds;
private TextureStorage _textureStorage;
public BulletSpace (Rectangle bounds)
{
Bullets = new List<Bullet> ();
_bounds = bounds;
}
public void AddBullet (double x, double y, double heading)
{
var bullet = new Bullet (x, y, heading);
bullet.GetModel ().LoadTextures (_textureStorage);
Bullets.Add (bullet);
}
public void LoadTexture(TextureStorage textureStorage)
{
_textureStorage = textureStorage;
}
public void Render(SpriteBatch spriteBatch)
{
foreach (var bullet in Bullets) {
bullet.GetModel ().Render (spriteBatch);
}
}
public void Update(TimeSpan timeDelta)
{
foreach (var bullet in Bullets) {
bullet.UpdatePosition (timeDelta);
}
Bullets.RemoveAll (delegate(Bullet bullet) {
return !_bounds.Contains((Vector2) bullet.Position);
});
}
}
}
| mit | C# |
607f1df9aa73a7bfe6ab790d9658175094ea6bfc | Make ExcludeFromCodeCoverage conditional on DEBUG | weltkante/corefx,Priya91/corefx-1,weltkante/corefx,seanshpark/corefx,tijoytom/corefx,shmao/corefx,lggomez/corefx,nbarbettini/corefx,stone-li/corefx,Jiayili1/corefx,krk/corefx,alexperovich/corefx,gkhanna79/corefx,manu-silicon/corefx,the-dwyer/corefx,tstringer/corefx,dhoehna/corefx,manu-silicon/corefx,stone-li/corefx,nchikanov/corefx,DnlHarvey/corefx,MaggieTsang/corefx,josguil/corefx,the-dwyer/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,marksmeltzer/corefx,tijoytom/corefx,ravimeda/corefx,ravimeda/corefx,rahku/corefx,pallavit/corefx,rjxby/corefx,YoupHulsebos/corefx,billwert/corefx,pgavlin/corefx,ravimeda/corefx,benpye/corefx,janhenke/corefx,krk/corefx,jcme/corefx,cartermp/corefx,alexandrnikitin/corefx,seanshpark/corefx,stephenmichaelf/corefx,cydhaselton/corefx,benjamin-bader/corefx,rahku/corefx,rahku/corefx,benpye/corefx,YoupHulsebos/corefx,690486439/corefx,vidhya-bv/corefx-sorting,yizhang82/corefx,khdang/corefx,ptoonen/corefx,DnlHarvey/corefx,kkurni/corefx,stephenmichaelf/corefx,n1ghtmare/corefx,manu-silicon/corefx,yizhang82/corefx,shmao/corefx,alexandrnikitin/corefx,rubo/corefx,dhoehna/corefx,mafiya69/corefx,tijoytom/corefx,tijoytom/corefx,jhendrixMSFT/corefx,alexperovich/corefx,cydhaselton/corefx,axelheer/corefx,nbarbettini/corefx,MaggieTsang/corefx,mazong1123/corefx,DnlHarvey/corefx,nbarbettini/corefx,khdang/corefx,axelheer/corefx,seanshpark/corefx,jcme/corefx,Chrisboh/corefx,krk/corefx,alphonsekurian/corefx,yizhang82/corefx,mmitche/corefx,mellinoe/corefx,Ermiar/corefx,ptoonen/corefx,gkhanna79/corefx,alexperovich/corefx,ptoonen/corefx,cartermp/corefx,twsouthwick/corefx,josguil/corefx,elijah6/corefx,vidhya-bv/corefx-sorting,YoupHulsebos/corefx,BrennanConroy/corefx,wtgodbe/corefx,elijah6/corefx,manu-silicon/corefx,dhoehna/corefx,shmao/corefx,weltkante/corefx,PatrickMcDonald/corefx,nbarbettini/corefx,pallavit/corefx,SGuyGe/corefx,DnlHarvey/corefx,zhenlan/corefx,jlin177/corefx,alexperovich/corefx,marksmeltzer/corefx,weltkante/corefx,seanshpark/corefx,rubo/corefx,ellismg/corefx,mafiya69/corefx,MaggieTsang/corefx,pgavlin/corefx,pallavit/corefx,Priya91/corefx-1,ptoonen/corefx,wtgodbe/corefx,cydhaselton/corefx,Chrisboh/corefx,khdang/corefx,mellinoe/corefx,shahid-pk/corefx,mokchhya/corefx,ericstj/corefx,stone-li/corefx,gkhanna79/corefx,Petermarcu/corefx,nchikanov/corefx,ellismg/corefx,richlander/corefx,billwert/corefx,vidhya-bv/corefx-sorting,mazong1123/corefx,yizhang82/corefx,yizhang82/corefx,khdang/corefx,rjxby/corefx,n1ghtmare/corefx,JosephTremoulet/corefx,tstringer/corefx,MaggieTsang/corefx,parjong/corefx,mokchhya/corefx,JosephTremoulet/corefx,shahid-pk/corefx,Ermiar/corefx,seanshpark/corefx,n1ghtmare/corefx,ViktorHofer/corefx,Priya91/corefx-1,n1ghtmare/corefx,cydhaselton/corefx,the-dwyer/corefx,billwert/corefx,akivafr123/corefx,bitcrazed/corefx,tstringer/corefx,lggomez/corefx,SGuyGe/corefx,mmitche/corefx,Yanjing123/corefx,JosephTremoulet/corefx,adamralph/corefx,seanshpark/corefx,pallavit/corefx,rubo/corefx,mmitche/corefx,alexperovich/corefx,shahid-pk/corefx,690486439/corefx,the-dwyer/corefx,alexandrnikitin/corefx,kkurni/corefx,billwert/corefx,dotnet-bot/corefx,adamralph/corefx,wtgodbe/corefx,shahid-pk/corefx,parjong/corefx,pallavit/corefx,rjxby/corefx,billwert/corefx,parjong/corefx,zhenlan/corefx,jeremymeng/corefx,lggomez/corefx,Jiayili1/corefx,jeremymeng/corefx,janhenke/corefx,mokchhya/corefx,richlander/corefx,marksmeltzer/corefx,BrennanConroy/corefx,benjamin-bader/corefx,bitcrazed/corefx,axelheer/corefx,elijah6/corefx,gkhanna79/corefx,nbarbettini/corefx,mazong1123/corefx,josguil/corefx,fgreinacher/corefx,twsouthwick/corefx,axelheer/corefx,cartermp/corefx,benpye/corefx,stone-li/corefx,josguil/corefx,akivafr123/corefx,alphonsekurian/corefx,PatrickMcDonald/corefx,jcme/corefx,lggomez/corefx,wtgodbe/corefx,gregg-miskelly/corefx,nbarbettini/corefx,jlin177/corefx,Petermarcu/corefx,alexperovich/corefx,iamjasonp/corefx,elijah6/corefx,mellinoe/corefx,Petermarcu/corefx,manu-silicon/corefx,gregg-miskelly/corefx,zhenlan/corefx,Chrisboh/corefx,ericstj/corefx,gkhanna79/corefx,ViktorHofer/corefx,nchikanov/corefx,josguil/corefx,axelheer/corefx,richlander/corefx,fgreinacher/corefx,ericstj/corefx,mazong1123/corefx,kkurni/corefx,rjxby/corefx,nchikanov/corefx,twsouthwick/corefx,nchikanov/corefx,Priya91/corefx-1,the-dwyer/corefx,mmitche/corefx,gkhanna79/corefx,janhenke/corefx,DnlHarvey/corefx,jcme/corefx,alphonsekurian/corefx,ravimeda/corefx,shahid-pk/corefx,dotnet-bot/corefx,lggomez/corefx,cydhaselton/corefx,zhenlan/corefx,rubo/corefx,mazong1123/corefx,akivafr123/corefx,mmitche/corefx,the-dwyer/corefx,mellinoe/corefx,dhoehna/corefx,ViktorHofer/corefx,kkurni/corefx,Jiayili1/corefx,parjong/corefx,tijoytom/corefx,ptoonen/corefx,stephenmichaelf/corefx,jlin177/corefx,Ermiar/corefx,yizhang82/corefx,marksmeltzer/corefx,elijah6/corefx,ViktorHofer/corefx,krytarowski/corefx,Petermarcu/corefx,Jiayili1/corefx,DnlHarvey/corefx,jhendrixMSFT/corefx,mafiya69/corefx,zhenlan/corefx,benpye/corefx,benjamin-bader/corefx,dotnet-bot/corefx,jlin177/corefx,tstringer/corefx,shmao/corefx,jcme/corefx,ericstj/corefx,krytarowski/corefx,elijah6/corefx,shahid-pk/corefx,rjxby/corefx,iamjasonp/corefx,jhendrixMSFT/corefx,Ermiar/corefx,mokchhya/corefx,MaggieTsang/corefx,jlin177/corefx,BrennanConroy/corefx,jhendrixMSFT/corefx,iamjasonp/corefx,mmitche/corefx,ellismg/corefx,YoupHulsebos/corefx,MaggieTsang/corefx,mazong1123/corefx,benpye/corefx,gregg-miskelly/corefx,richlander/corefx,wtgodbe/corefx,pgavlin/corefx,dsplaisted/corefx,krytarowski/corefx,PatrickMcDonald/corefx,shmao/corefx,ericstj/corefx,manu-silicon/corefx,Yanjing123/corefx,krk/corefx,dsplaisted/corefx,janhenke/corefx,ViktorHofer/corefx,twsouthwick/corefx,billwert/corefx,JosephTremoulet/corefx,SGuyGe/corefx,benjamin-bader/corefx,nbarbettini/corefx,ravimeda/corefx,weltkante/corefx,stephenmichaelf/corefx,krk/corefx,stephenmichaelf/corefx,690486439/corefx,dotnet-bot/corefx,jeremymeng/corefx,gregg-miskelly/corefx,Ermiar/corefx,rjxby/corefx,elijah6/corefx,nchikanov/corefx,khdang/corefx,parjong/corefx,the-dwyer/corefx,Yanjing123/corefx,PatrickMcDonald/corefx,mellinoe/corefx,twsouthwick/corefx,twsouthwick/corefx,shmao/corefx,Jiayili1/corefx,Yanjing123/corefx,shimingsg/corefx,jlin177/corefx,alphonsekurian/corefx,jhendrixMSFT/corefx,stephenmichaelf/corefx,tstringer/corefx,dsplaisted/corefx,rahku/corefx,Petermarcu/corefx,ravimeda/corefx,parjong/corefx,Chrisboh/corefx,mafiya69/corefx,alexandrnikitin/corefx,rahku/corefx,akivafr123/corefx,Yanjing123/corefx,SGuyGe/corefx,axelheer/corefx,ellismg/corefx,zhenlan/corefx,dhoehna/corefx,richlander/corefx,lggomez/corefx,JosephTremoulet/corefx,PatrickMcDonald/corefx,alexandrnikitin/corefx,krytarowski/corefx,iamjasonp/corefx,jcme/corefx,shmao/corefx,nchikanov/corefx,jhendrixMSFT/corefx,alphonsekurian/corefx,tstringer/corefx,akivafr123/corefx,kkurni/corefx,mokchhya/corefx,ViktorHofer/corefx,ericstj/corefx,bitcrazed/corefx,jeremymeng/corefx,krk/corefx,mellinoe/corefx,MaggieTsang/corefx,Priya91/corefx-1,iamjasonp/corefx,ravimeda/corefx,mafiya69/corefx,marksmeltzer/corefx,shimingsg/corefx,Petermarcu/corefx,rahku/corefx,Ermiar/corefx,vidhya-bv/corefx-sorting,mmitche/corefx,iamjasonp/corefx,alphonsekurian/corefx,janhenke/corefx,benjamin-bader/corefx,khdang/corefx,wtgodbe/corefx,dhoehna/corefx,YoupHulsebos/corefx,krk/corefx,YoupHulsebos/corefx,weltkante/corefx,cartermp/corefx,JosephTremoulet/corefx,cartermp/corefx,jlin177/corefx,shimingsg/corefx,yizhang82/corefx,cydhaselton/corefx,billwert/corefx,benpye/corefx,jhendrixMSFT/corefx,pallavit/corefx,ellismg/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,Chrisboh/corefx,pgavlin/corefx,mafiya69/corefx,dhoehna/corefx,alexperovich/corefx,YoupHulsebos/corefx,DnlHarvey/corefx,Jiayili1/corefx,tijoytom/corefx,Chrisboh/corefx,SGuyGe/corefx,rahku/corefx,stone-li/corefx,mazong1123/corefx,vidhya-bv/corefx-sorting,690486439/corefx,tijoytom/corefx,janhenke/corefx,seanshpark/corefx,benjamin-bader/corefx,ellismg/corefx,alphonsekurian/corefx,dotnet-bot/corefx,rjxby/corefx,rubo/corefx,stephenmichaelf/corefx,Priya91/corefx-1,richlander/corefx,mokchhya/corefx,parjong/corefx,krytarowski/corefx,fgreinacher/corefx,bitcrazed/corefx,stone-li/corefx,cartermp/corefx,n1ghtmare/corefx,690486439/corefx,zhenlan/corefx,adamralph/corefx,ViktorHofer/corefx,lggomez/corefx,jeremymeng/corefx,bitcrazed/corefx,Petermarcu/corefx,krytarowski/corefx,kkurni/corefx,SGuyGe/corefx,Jiayili1/corefx,stone-li/corefx,krytarowski/corefx,gkhanna79/corefx,iamjasonp/corefx,weltkante/corefx,shimingsg/corefx,marksmeltzer/corefx,josguil/corefx,Ermiar/corefx,ericstj/corefx,fgreinacher/corefx,ptoonen/corefx,manu-silicon/corefx,richlander/corefx,cydhaselton/corefx,marksmeltzer/corefx,ptoonen/corefx,shimingsg/corefx,twsouthwick/corefx,dotnet-bot/corefx | src/Common/src/System/Diagnostics/CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs | src/Common/src/System/Diagnostics/CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Diagnostics.CodeAnalysis
{
[Conditional("DEBUG")] // don't bloat release assemblies
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)]
internal sealed class ExcludeFromCodeCoverageAttribute : Attribute
{
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)]
internal sealed class ExcludeFromCodeCoverageAttribute : Attribute
{
}
}
| mit | C# |
f259a23fa20570bec0d7f2d427fb6be818904ae9 | Bump v1.0.16 | karronoli/tiny-sato | TinySato/Properties/AssemblyInfo.cs | TinySato/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TinySato")]
[assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TinySato")]
[assembly: AssemblyCopyright("Copyright 2016 karronoli")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
[assembly: AssemblyVersion("1.0.16")]
[assembly: AssemblyFileVersion("1.0.16")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TinySato")]
[assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TinySato")]
[assembly: AssemblyCopyright("Copyright 2016 karronoli")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
[assembly: AssemblyVersion("1.0.15")]
[assembly: AssemblyFileVersion("1.0.15")]
| apache-2.0 | C# |
dedb40c7aaf173ac4af81d9b98a945a43443a0af | Move to version 1.1.0.0 | aloisdg/Gravimage | Gravimage/Properties/AssemblyInfo.cs | Gravimage/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Gravimage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Gravimage")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Gravimage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Gravimage")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
b22ae2426ebbda6306f3c8244ed86a6f31676c73 | Add StartsOn and EndsOn to ProjectOptions | ithielnor/harvest.net | Harvest.Net/Models/ProjectOptions.cs | Harvest.Net/Models/ProjectOptions.cs | using RestSharp.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Harvest.Net.Models
{
[SerializeAs(Name = "project")]
public class ProjectOptions
{
public long? ClientId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public bool? Active { get; set; }
public bool? Billable { get; set; }
public BillingMethod? BillBy { get; set; }
public decimal? HourlyRate { get; set; }
public decimal? Budget { get; set; }
public BudgetMethod? BudgetBy { get; set; }
public bool? NotifyWhenOverBudget { get; set; }
public decimal? OverBudgetNotificationPercentage { get; set; }
public bool? ShowBudgetToAll { get; set; }
public decimal? Estimate { get; set; }
public EstimateMethod? EstimateBy { get; set; }
public string Notes { get; set; }
public decimal? CostBudget { get; set; }
public bool? CostBudgetIncludeExpenses { get; set; }
public DateTime? StartsOn { get; set; }
public DateTime? EndsOn { get; set; }
}
}
| using RestSharp.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Harvest.Net.Models
{
[SerializeAs(Name = "project")]
public class ProjectOptions
{
public long? ClientId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public bool? Active { get; set; }
public bool? Billable { get; set; }
public BillingMethod? BillBy { get; set; }
public decimal? HourlyRate { get; set; }
public decimal? Budget { get; set; }
public BudgetMethod? BudgetBy { get; set; }
public bool? NotifyWhenOverBudget { get; set; }
public decimal? OverBudgetNotificationPercentage { get; set; }
public bool? ShowBudgetToAll { get; set; }
public decimal? Estimate { get; set; }
public EstimateMethod? EstimateBy { get; set; }
public string Notes { get; set; }
public decimal? CostBudget { get; set; }
public bool? CostBudgetIncludeExpenses { get; set; }
}
}
| mit | C# |
52ae8b398ade5f53a22cb60f6edf968c032de380 | add comment | kmarcell/ELTE-2015-Component-Team4 | Server/Program.cs | Server/Program.cs | using System;
using Server.Implementation;
namespace Server
{
class Program
{
static void Main()
{
// get the instance of the server manager and start
var manager = ServerManager.ServerManagerInstance;
manager.Start();
if (manager.Running)
{
Console.WriteLine("Server started with ip address: {0}, port number: {1}", manager.ServerIp, manager.ServerPort);
Console.WriteLine("Press enter to stop the server!");
Console.ReadKey();
}
Console.WriteLine("\nAttempting to stop, please wait, it will be closed immediately.");
manager.Stop();
}
}
}
| using System;
using Server.Implementation;
namespace Server
{
class Program
{
static void Main()
{
var manager = ServerManager.ServerManagerInstance;
manager.Start();
if (manager.Running)
{
Console.WriteLine("Server started with ip address: {0}, port number: {1}", manager.ServerIp, manager.ServerPort);
Console.WriteLine("Press enter to stop the server!");
Console.ReadKey();
}
Console.WriteLine("\nAttempting to stop, please wait, it will be closed immediately.");
manager.Stop();
}
}
}
| mit | C# |
212b307ba588d85b5c8da968eef8ed766fac22d0 | Update copyright data and assembly description. | jthelin/ServerHost,jthelin/ServerHost | ServerHost/Properties/AssemblyInfo.cs | ServerHost/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ServerHost")]
[assembly: AssemblyDescription("ServerHost - A .NET Server Hosting utility library, including in-process server host testing.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jorgen Thelin")]
[assembly: AssemblyProduct("ServerHost")]
[assembly: AssemblyCopyright("Copyright © Jorgen Thelin 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e9fff8d5-f4c0-483d-aee6-5ff82afd434f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ServerHost")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jorgen Thelin")]
[assembly: AssemblyProduct("ServerHost")]
[assembly: AssemblyCopyright("Copyright © Jorgen Thelin 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e9fff8d5-f4c0-483d-aee6-5ff82afd434f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
9a5edf04620d0a65b2899ce8a24e234dd72c68c7 | Update Program.cs | iamnotageek/GitTest1 | ConsoleApp1/ConsoleApp1/Program.cs | ConsoleApp1/ConsoleApp1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//Code was added in Github
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
05c360de21c9ba5ab50fb245392fa0bf516406b9 | fix typo | smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework | osu.Framework/Input/UserInputManager.cs | osu.Framework/Input/UserInputManager.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Platform;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Input
{
public class UserInputManager : PassThroughInputManager
{
protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers;
protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true;
protected internal override bool ShouldBeAlive => true;
protected internal UserInputManager()
{
// UserInputManager is at the very top of the draw hierarchy, so it has no parent updating its IsAlive state
IsAlive = true;
UseParentInput = false;
}
public override void HandleInputStateChange(InputStateChangeEvent inputStateChange)
{
switch (inputStateChange)
{
case MousePositionChangeEvent mousePositionChange:
var mouse = mousePositionChange.State.Mouse;
// confine cursor
if (Host.Window != null && Host.Window.CursorState.HasFlag(CursorState.Confined))
mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height));
break;
case ButtonStateChangeEvent<MouseButton> buttonChange:
if (buttonChange.Kind == ButtonStateChangeKind.Pressed && Host.Window?.CursorInWindow == false)
return;
break;
case MouseScrollChangeEvent _:
if (Host.Window?.CursorInWindow == false)
return;
break;
}
base.HandleInputStateChange(inputStateChange);
}
}
}
| // 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.Collections.Generic;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Platform;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Input
{
public class UserInputManager : PassThroughInputManager
{
protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers;
protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true;
protected internal override bool ShouldBeAlive => true;
protected internal UserInputManager()
{
// UserInputManager is at the very top of the draw hierarchy, so it has no parnt updating its IsAlive state
IsAlive = true;
UseParentInput = false;
}
public override void HandleInputStateChange(InputStateChangeEvent inputStateChange)
{
switch (inputStateChange)
{
case MousePositionChangeEvent mousePositionChange:
var mouse = mousePositionChange.State.Mouse;
// confine cursor
if (Host.Window != null && Host.Window.CursorState.HasFlag(CursorState.Confined))
mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height));
break;
case ButtonStateChangeEvent<MouseButton> buttonChange:
if (buttonChange.Kind == ButtonStateChangeKind.Pressed && Host.Window?.CursorInWindow == false)
return;
break;
case MouseScrollChangeEvent _:
if (Host.Window?.CursorInWindow == false)
return;
break;
}
base.HandleInputStateChange(inputStateChange);
}
}
}
| mit | C# |
1203a7153371ae2299842fc0eb40e9679e228b13 | Update MiniKanren.cs | wallymathieu/csharp_ukanren,wallymathieu/csharp_ukanren | lib/MiniKanren.cs | lib/MiniKanren.cs | using System;
namespace MicroKanren{
public class Cons<T1,T2>{
//attr_reader :car, :cdr
public T1 Car{get;private set;}
public T2 Cdr{get;private set;}
//# Returns a Cons cell (read: instance) that is also marked as such for
//# later identification.
public Cons(T1 car,T2 cdr){ //def initialize(car, cdr)
Car=car; Cdr = cdr;
}//end
//# Converts Lisp AST to a String. Algorithm is a recursive implementation of
//# http://www.mat.uc.pt/~pedro/cientificos/funcional/lisp/gcl_22.html#SEC1238.
/*def to_s(cons_in_cdr = false)
str = cons_in_cdr ? '' : '('
str += self.car.is_a?(Cons) ? self.car.to_s : atom_string(self.car)
str += case self.cdr
when Cons
' ' + self.cdr.to_s(true)
when NilClass
''
else
' . ' + atom_string(self.cdr)
end
cons_in_cdr ? str : str << ')'
end*/
/*def ==(other)
other.is_a?(Cons) ? self.car == other.car && self.cdr == other.cdr : false
end*/
//private
/*def atom_string(node)
case node
when NilClass, Array, String
node.inspect
else
node.to_s
end
end*/
}
}
| using System;
namespace MiniKanren{
}
| mit | C# |
d8fbaa693b14a7a0b931ae0523ab9c5ddda51687 | Update SetUpFixture | atata-framework/atata-webdriverextras,atata-framework/atata-webdriverextras | src/Atata.WebDriverExtras.Tests/SetUpFixture.cs | src/Atata.WebDriverExtras.Tests/SetUpFixture.cs | using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using NUnit.Framework;
using Retry;
namespace Atata.WebDriverExtras.Tests
{
[SetUpFixture]
public class SetUpFixture
{
private Process coreRunProcess;
[OneTimeSetUp]
public void GlobalSetUp()
{
try
{
PingTestApp();
}
catch
{
RunTestApp();
}
}
private static WebResponse PingTestApp() =>
WebRequest.CreateHttp(UITestFixture.BaseUrl).GetResponse();
private void RunTestApp()
{
coreRunProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/c dotnet run",
WorkingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\..\\Atata.WebDriverExtras.TestApp")
}
};
coreRunProcess.Start();
Thread.Sleep(5000);
RetryHelper.Instance.Try(() => PingTestApp()).
WithTryInterval(1000).
WithTimeLimit(40000).
UntilNoException();
}
[OneTimeTearDown]
public void GlobalTearDown()
{
coreRunProcess?.CloseMainWindow();
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using NUnit.Framework;
using Retry;
namespace Atata.WebDriverExtras.Tests
{
[SetUpFixture]
public class SetUpFixture
{
private Process coreRunProcess;
[OneTimeSetUp]
public void GlobalSetUp()
{
try
{
PingTestApp();
}
catch
{
RunTestApp();
}
}
private static WebResponse PingTestApp() =>
WebRequest.CreateHttp(UITestFixture.BaseUrl).GetResponse();
private void RunTestApp()
{
coreRunProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/c dotnet run",
WorkingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\Atata.WebDriverExtras.TestApp")
}
};
coreRunProcess.Start();
Thread.Sleep(5000);
RetryHelper.Instance.Try(() => PingTestApp()).
WithTryInterval(1000).
WithTimeLimit(40000).
UntilNoException();
}
[OneTimeTearDown]
public void GlobalTearDown()
{
coreRunProcess?.CloseMainWindow();
}
}
}
| apache-2.0 | C# |
72f39ed79461cc0616b9cdd78b864ba5cf9724d1 | Fix so that SPARQL query test works | kentcb/BrightstarDB,BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB,kentcb/BrightstarDB,dharmatech/BrightstarDB,dharmatech/BrightstarDB,dharmatech/BrightstarDB,kentcb/BrightstarDB,dharmatech/BrightstarDB,BrightstarDB/BrightstarDB,dharmatech/BrightstarDB,dharmatech/BrightstarDB,kentcb/BrightstarDB,BrightstarDB/BrightstarDB | src/benchmarking/BrightstarDB.PerformanceBenchmarks/Models/IFoafPerson.cs | src/benchmarking/BrightstarDB.PerformanceBenchmarks/Models/IFoafPerson.cs | using System;
using System.Collections.Generic;
using System.Text;
using BrightstarDB.EntityFramework;
namespace BrightstarDB.PerformanceBenchmarks.Models
{
[Entity("http://xmlns.com/foaf/0.1/Person")]
public interface IFoafPerson
{
[Identifier("http://www.brightstardb.com/people/")]
string Id { get; }
[PropertyType("http://xmlns.com/foaf/0.1/name")]
string Name { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/givenName")]
string GivenName { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/familyName")]
string FamilyName { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/age")]
int Age { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/organization")]
string Organisation { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/knows")]
ICollection<IFoafPerson> Knows { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using BrightstarDB.EntityFramework;
namespace BrightstarDB.PerformanceBenchmarks.Models
{
[Entity("http://xmlns.com/foaf/0.1/Person")]
public interface IFoafPerson
{
string Id { get; }
[PropertyType("http://xmlns.com/foaf/0.1/name")]
string Name { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/givenName")]
string GivenName { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/familyName")]
string FamilyName { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/age")]
int Age { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/organization")]
string Organisation { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/knows")]
ICollection<IFoafPerson> Knows { get; set; }
}
}
| mit | C# |
1a833e9d52e2ffb4512a06dd7bd4f93c8ab41192 | change URL | tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web | src/Tugberk.Web/Controllers/PortalController.cs | src/Tugberk.Web/Controllers/PortalController.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Tugberk.Web.Controllers
{
[Route("portal")]
public class PortalController : Controller
{
private readonly IImageStorage _imageStorage;
public PortalController(IImageStorage imageStorage)
{
_imageStorage = imageStorage ?? throw new System.ArgumentNullException(nameof(imageStorage));
}
public IActionResult Index() => View();
[HttpGet("posts/create")]
public IActionResult CreatePost() => View();
[HttpGet("posts/{postId}")]
public IActionResult EditPost(string postId) => View();
[ValidateAntiForgeryToken]
[HttpPost("images/upload")]
public async Task<IActionResult> UploadImage()
{
if(Request.Form.Files.Count < 1)
{
return BadRequest("Request contains no file to upload");
}
if(Request.Form.Files.Count > 1)
{
return BadRequest("More than one file to upload at the same time is not supported");
}
var firstFile = Request.Form.Files.First();
using(var stream = firstFile.OpenReadStream())
{
var result = await _imageStorage.SaveImage(stream, firstFile.FileName);
return Json(new
{
ImageUrl = result.Url
});
}
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Tugberk.Web.Controllers
{
[Route("portal")]
public class PortalController : Controller
{
private readonly IImageStorage _imageStorage;
public PortalController(IImageStorage imageStorage)
{
_imageStorage = imageStorage ?? throw new System.ArgumentNullException(nameof(imageStorage));
}
public IActionResult Index() => View();
[HttpGet("posts")]
public IActionResult CreatePost() => View();
[HttpGet("posts/{postId}")]
public IActionResult EditPost(string postId) => View();
[ValidateAntiForgeryToken]
[HttpPost("images/upload")]
public async Task<IActionResult> UploadImage()
{
if(Request.Form.Files.Count < 1)
{
return BadRequest("Request contains no file to upload");
}
if(Request.Form.Files.Count > 1)
{
return BadRequest("More than one file to upload at the same time is not supported");
}
var firstFile = Request.Form.Files.First();
using(var stream = firstFile.OpenReadStream())
{
var result = await _imageStorage.SaveImage(stream, firstFile.FileName);
return Json(new
{
ImageUrl = result.Url
});
}
}
}
}
| agpl-3.0 | C# |
f0f600cbf87b4523e0d4be3e8288e3cf3d773d6e | Fix big ArrayListAlgorithms-Exercises/06.Batteries/Batteries.cs | Peter-Georgiev/Programming.Fundamentals,Peter-Georgiev/Programming.Fundamentals | ArrayListAlgorithms-Exercises/06.Batteries/Batteries.cs | ArrayListAlgorithms-Exercises/06.Batteries/Batteries.cs | using System;
using System.Collections.Generic;
using System.Linq;
class Batteries
{
static void Main()
{
double[] capacities = ReadLine();
double[] usagePerHour = ReadLine();
int hour = int.Parse(Console.ReadLine());
PrintStatusBattery(GetStatusBattery(capacities, usagePerHour, hour));
}
static List<string> GetStatusBattery(double[] capacities, double[] usagePerHour, int hour)
{
List<string> statusBatt = new List<string>(capacities.Length);
double result = 0d;
for (int i = 0; i < capacities.Length; i++)
{
result = capacities[i] - (hour * usagePerHour[i]);
if (result > 0)
{
double percent = ((double)result / (double)capacities[i]) * 100d;
statusBatt.Add($"Battery {i + 1}: {result:F2} mAh ({percent:F2})%");
}
else
{
double howManyHours = Math.Ceiling(capacities[i] / usagePerHour[i]);
statusBatt.Add($"Battery {i + 1}: dead (lasted {howManyHours} hours)");
}
}
return statusBatt;
}
static void PrintStatusBattery(List<string> statusBattery)
{
statusBattery.ForEach(Console.WriteLine);
}
static double[] ReadLine()
{
double[] readLine = Console.ReadLine()
.Split(' ')
.Select(double.Parse)
.ToArray();
return readLine;
}
} | using System;
using System.Collections.Generic;
using System.Linq;
class Batteries
{
static void Main()
{
double[] capacities = ReadLine();
double[] usagePerHour = ReadLine();
int hour = int.Parse(Console.ReadLine());
PrintStatusBattery(GetStatusBattery(capacities, usagePerHour, hour));
}
static List<string> GetStatusBattery(double[] capacities, double[] usagePerHour, int hour)
{
List<string> statusBatt = new List<string>(capacities.Length);
double result = 0d;
for (int i = 0; i < capacities.Length; i++)
{
result = capacities[i] - (hour * usagePerHour[i]);
if (result > 0)
{
double percent = ((double)result / (double)capacities[i]) * 100d;
statusBatt.Add($"Battery {i + 1}: {result:F2} mAh ({percent:F2})%");
}
else
{
double howManyHours = Math.Ceiling(capacities[i] / usagePerHour[i]);
statusBatt.Add($"Battery {i + 1}: dead (lasted {howManyHours} hours)");
}
}
return statusBatt;
}
static void PrintStatusBattery(List<string> statusBattery)
{
statusBattery.ForEach(Console.WriteLine);
}
static double[] ReadLine()
{
double[] readLine = Console.ReadLine()
.Split(' ')
.Select(double.Parse)
.ToArray();
return readLine;
}
} | mit | C# |
5a7f2d5ed62735e6e4213281dd29c230d91f2cef | add onError callback | amiralles/abacus,amiralles/abacus | src/core/AbacusExtensions.cs | src/core/AbacusExtensions.cs | namespace Abacus {
using System;
using System.Collections;
using System.Data;
using static Interpreter;
using static Utils;
using static System.Convert;
public static class AbacusTableExtensions {
static Random Rnd = new Random();
static bool ToBool(object val) {
DbgPrint(val);
if (val is bool)
return (bool)val;
if (val == null)
return false;
if (val is IConvertible)
return ToBoolean(val);
return false;
}
public static DataTable Reduce(this DataTable tbl, string formula) =>
tbl.Reduce(formula, new string[0], new object[0]);
public static DataTable Reduce(this DataTable tbl,
string formula, Func<Exception, object> onError) =>
tbl.Reduce(formula, new string[0], new object[0], onError);
public static DataTable Reduce(this DataTable tbl,
string formula, string[] locNames, object[] locals) =>
tbl.Reduce(formula, locNames, locals, null);
public static DataTable Reduce(this DataTable tbl,
string formula, string[] locNames, object[] locals,
Func<Exception, object> onError) {
//TODO: Validate args.
var sess = new Session(Rnd.Next());
var names = new string[tbl.Columns.Count + locNames.Length];
var res = tbl.Clone();
// ===========================================================
// Merge local names.
// ===========================================================
var colslen = tbl.Columns.Count;
for (int i = 0; i < colslen; ++i)
names[i] = tbl.Columns[i].ColumnName.ToLower();
for (int i = 0; i < locNames.Length; ++i)
names[colslen + i] = locNames[i];
// ===========================================================
var locs = new object[locals.Length + tbl.Rows[0].ItemArray.Length];
foreach (DataRow row in tbl.Rows) {
// ========================================================
// Merge local values.
// ========================================================
int rowslen = row.ItemArray.Length;
for(int i = 0 ; i < rowslen; ++i)
locs[i] = row.ItemArray[i];
for (int i = 0; i < locals.Length; ++i)
locs[rowslen + i] = locals[i];
//==========================================================
try {
var r = Eval(formula, names, locs, ref sess, onError);
if(ToBool(r))
res.ImportRow(row);
}
catch(Exception ex) {
if (onError != null) {
onError(ex);
}
else {
throw;
}
}
}
return res;
}
}
}
| namespace Abacus {
using System;
using System.Collections;
using System.Data;
using static Interpreter;
using static Utils;
using static System.Convert;
public static class AbacusTableExtensions {
static Random Rnd = new Random();
static bool ToBool(object val) {
DbgPrint(val);
if (val is bool)
return (bool)val;
if (val is IConvertible)
return ToBoolean(val);
return false;
}
public static DataTable Reduce(this DataTable tbl, string formula) =>
tbl.Reduce(formula, new string[0], new object[0]);
public static DataTable Reduce(this DataTable tbl,
string formula, string[] locNames, object[] locals) {
//TODO: Validate args.
var sess = new Session(Rnd.Next());
var names = new string[tbl.Columns.Count + locNames.Length];
var res = tbl.Clone();
// ===========================================================
// Merge local names.
// ===========================================================
var colslen = tbl.Columns.Count;
for (int i = 0; i < colslen; ++i)
names[i] = tbl.Columns[i].ColumnName.ToLower();
for (int i = 0; i < locNames.Length; ++i)
names[colslen + i] = locNames[i];
// ===========================================================
var locs = new object[locals.Length + tbl.Rows[0].ItemArray.Length];
foreach (DataRow row in tbl.Rows) {
// ========================================================
// Merge local values.
// ========================================================
int rowslen = row.ItemArray.Length;
for(int i = 0 ; i < rowslen; ++i)
locs[i] = row.ItemArray[i];
for (int i = 0; i < locals.Length; ++i)
locs[rowslen + i] = locals[i];
//==========================================================
var r = Eval(formula, names, locs, ref sess);
if(ToBool(r))
res.ImportRow(row);
}
return res;
}
}
}
| mit | C# |
84989eee482c5389b5090586b022dfce5f1ead6b | include score | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Shared/DisplayTemplates/APFT.cshtml | Battery-Commander.Web/Views/Shared/DisplayTemplates/APFT.cshtml | @model APFT
@if (Model != null)
{
<div>
<a href="@Url.Action("Details", "APFT", new { Model.Id })">
@if (Model.IsPassing)
{
<span class="label label-success">Passing (@Model.TotalScore)</span>
}
else
{
<span class="label label-danger">Failure (@Model.TotalScore)</span>
}
</a>
</div>
} | @model APFT
@if (Model != null)
{
<div>
<a href="@Url.Action("Details", "APFT", new { Model.Id })">
@if (Model.IsPassing)
{
<span class="label label-success">Passing</span>
}
else
{
<span class="label label-danger">Failure</span>
}
</a>
</div>
} | mit | C# |
8b52ded42afe8c11d43579d0e4dfadf76412e18c | update jquery-mobile resource reference to 1.2 version | intellifactory/websharper.jquerymobile,intellifactory/websharper.jquerymobile | if-ws-jquerymobile/Resources.cs | if-ws-jquerymobile/Resources.cs | using System.Web.UI;
using IntelliFactory.WebSharper;
namespace IntelliFactory.WebSharper.JQuery.Mobile.Resources
{
[IntelliFactory.WebSharper.Core.Attributes.Require(typeof(IntelliFactory.WebSharper.JQuery.Resources.JQuery))]
public class JQueryMobile : IntelliFactory.WebSharper.Core.Resources.BaseResource
{
public JQueryMobile()
: base("http://code.jquery.com/mobile/1.2.0",
"/jquery.mobile-1.2.0.min.js",
"/jquery.mobile-1.2.0.min.css") { }
}
}
| using System.Web.UI;
using IntelliFactory.WebSharper;
namespace IntelliFactory.WebSharper.JQuery.Mobile.Resources
{
[IntelliFactory.WebSharper.Core.Attributes.Require(typeof(IntelliFactory.WebSharper.JQuery.Resources.JQuery))]
public class JQueryMobile : IntelliFactory.WebSharper.Core.Resources.BaseResource
{
public JQueryMobile() : base("http://code.jquery.com/mobile/1.1.1",
"/jquery.mobile-1.1.1.min.js",
"/jquery.mobile-1.1.1.min.css") {}
}
}
| apache-2.0 | C# |
ca7fab586d113977b1ea9823a8059d3db3dd1ca7 | Fix typo and remove unneeded comments | gregsochanik/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper | src/SevenDigital.Api.Wrapper/Requests/Serializing/FormUrlEncodedPayloadSerializer.cs | src/SevenDigital.Api.Wrapper/Requests/Serializing/FormUrlEncodedPayloadSerializer.cs | using System;
using System.Collections;
using System.Linq;
namespace SevenDigital.Api.Wrapper.Requests.Serializing
{
public class FormUrlEncodedPayloadSerializer : IPayloadSerializer
{
public PayloadFormat Handles
{
get { return PayloadFormat.FormUrlEncoded; }
}
public string ContentType
{
get { return "application/x-www-form-urlencoded"; }
}
public string Serialize<TPayload>(TPayload payload) where TPayload : class
{
return SerialiseWithReflection(payload);
}
/// <summary>
/// Code to "Serialize object into a query string with Reflection" by Ole Michelsen 2012
/// Will do most poco objects
/// http://ole.michelsen.dk/blog/serialize-object-into-a-query-string-with-reflection.html
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
private string SerialiseWithReflection(object request)
{
var allProperties = request.GetType().GetProperties()
.Where(x => x.CanRead)
.Where(x => x.GetValue(request, null) != null)
.ToDictionary(x => x.Name, x => x.GetValue(request, null));
var propertyNames = allProperties
.Where(x => !(x.Value is string) && x.Value is IEnumerable)
.Select(x => x.Key)
.ToList();
foreach (var key in propertyNames)
{
var valueType = allProperties[key].GetType();
var valueElemType = valueType.IsGenericType
? valueType.GetGenericArguments()[0]
: valueType.GetElementType();
if (valueElemType.IsPrimitive || valueElemType == typeof(string))
{
var enumerable = allProperties[key] as IEnumerable;
allProperties[key] = string.Join(",", enumerable.Cast<object>());
}
}
var pairs = allProperties.Select(x =>
string.Concat(
Uri.EscapeDataString(x.Key), "=",
Uri.EscapeDataString(x.Value.ToString())));
return string.Join("&", pairs);
}
}
} | using System;
using System.Collections;
using System.Linq;
namespace SevenDigital.Api.Wrapper.Requests.Serializing
{
public class FormUrlEncodedPayloadSerializer : IPayloadSerializer
{
public PayloadFormat Handles
{
get { return PayloadFormat.FormUrlEncoded; }
}
public string ContentType
{
get { return "application/x-www-form-urlencoded"; }
}
public string Serialize<TPayload>(TPayload payload) where TPayload : class
{
return SerialiseWithRefection(payload);
}
/// <summary>
/// Code to "Serialize object into a query string with Reflection" by Ole Michelsen 2012
/// Will do most poco objects
/// http://ole.michelsen.dk/blog/serialize-object-into-a-query-string-with-reflection.html
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
private string SerialiseWithRefection(object request)
{
// Get all properties on the object
var properties = request.GetType().GetProperties()
.Where(x => x.CanRead)
.Where(x => x.GetValue(request, null) != null)
.ToDictionary(x => x.Name, x => x.GetValue(request, null));
// Get names for all IEnumerable properties (excl. string)
var propertyNames = properties
.Where(x => !(x.Value is string) && x.Value is IEnumerable)
.Select(x => x.Key)
.ToList();
// Concat all IEnumerable properties into a comma separated string
foreach (var key in propertyNames)
{
var valueType = properties[key].GetType();
var valueElemType = valueType.IsGenericType
? valueType.GetGenericArguments()[0]
: valueType.GetElementType();
if (valueElemType.IsPrimitive || valueElemType == typeof(string))
{
var enumerable = properties[key] as IEnumerable;
properties[key] = string.Join(",", enumerable.Cast<object>());
}
}
// Concat all key/value pairs into a string separated by ampersand
var pairs = properties.Select(x =>
string.Concat(
Uri.EscapeDataString(x.Key), "=",
Uri.EscapeDataString(x.Value.ToString())));
return string.Join("&", pairs);
}
}
} | mit | C# |
5822e902f1a64db42373bf76b2123ed33dd524c9 | Implement MethodBase.GetCurrentMethod | gregkalapos/corert,botaberg/corert,gregkalapos/corert,krytarowski/corert,krytarowski/corert,yizhang82/corert,shrah/corert,gregkalapos/corert,botaberg/corert,krytarowski/corert,yizhang82/corert,yizhang82/corert,yizhang82/corert,tijoytom/corert,krytarowski/corert,botaberg/corert,tijoytom/corert,tijoytom/corert,shrah/corert,shrah/corert,gregkalapos/corert,botaberg/corert,shrah/corert,tijoytom/corert | src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/ReflectionHelpers.cs | src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/ReflectionHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using Internal.Runtime.Augments;
namespace Internal.Runtime.CompilerHelpers
{
/// <summary>
/// Set of helpers used to implement callsite-specific reflection intrinsics.
/// </summary>
internal static class ReflectionHelpers
{
// This entry is used to implement Type.GetType()'s ability to detect the calling assembly and use it as
// a default assembly name.
public static Type GetType(string typeName, string callingAssemblyName, bool throwOnError, bool ignoreCase)
{
return ExtensibleGetType(typeName, callingAssemblyName, null, null, throwOnError: throwOnError, ignoreCase: ignoreCase);
}
// This entry is used to implement Type.GetType()'s ability to detect the calling assembly and use it as
// a default assembly name.
public static Type ExtensibleGetType(string typeName, string callingAssemblyName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase)
{
return RuntimeAugments.Callbacks.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, callingAssemblyName);
}
// This supports Assembly.GetExecutingAssembly() intrinsic expansion in the compiler
[System.Runtime.CompilerServices.DependencyReductionRoot]
public static Assembly GetExecutingAssembly(RuntimeTypeHandle typeHandle)
{
return Type.GetTypeFromHandle(typeHandle).Assembly;
}
// This supports MethodBase.GetCurrentMethod() intrinsic expansion in the compiler
[System.Runtime.CompilerServices.DependencyReductionRoot]
public static MethodBase GetCurrentMethodNonGeneric(RuntimeMethodHandle methodHandle)
{
// The compiler should ideally provide us with a RuntimeMethodHandle for the uninstantiated thing,
// but the file format cannot express a RuntimeMethodHandle for a generic definition of a generic method.
return MethodBase.GetMethodFromHandle(methodHandle).MetadataDefinitionMethod;
}
// This supports MethodBase.GetCurrentMethod() intrinsic expansion in the compiler
[System.Runtime.CompilerServices.DependencyReductionRoot]
public static MethodBase GetCurrentMethodGeneric(RuntimeMethodHandle methodHandle, RuntimeTypeHandle typeHandle)
{
// The compiler should ideally provide us with a RuntimeMethodHandle for the uninstantiated thing,
// but the file format cannot express a RuntimeMethodHandle for a generic definition of a generic method.
return MethodBase.GetMethodFromHandle(methodHandle, typeHandle).MetadataDefinitionMethod;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using Internal.Runtime.Augments;
namespace Internal.Runtime.CompilerHelpers
{
/// <summary>
/// Set of helpers used to implement callsite-specific reflection intrinsics.
/// </summary>
internal static class ReflectionHelpers
{
// This entry is used to implement Type.GetType()'s ability to detect the calling assembly and use it as
// a default assembly name.
public static Type GetType(string typeName, string callingAssemblyName, bool throwOnError, bool ignoreCase)
{
return ExtensibleGetType(typeName, callingAssemblyName, null, null, throwOnError: throwOnError, ignoreCase: ignoreCase);
}
// This entry is used to implement Type.GetType()'s ability to detect the calling assembly and use it as
// a default assembly name.
public static Type ExtensibleGetType(string typeName, string callingAssemblyName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase)
{
return RuntimeAugments.Callbacks.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, callingAssemblyName);
}
// This supports Assembly.GetExecutingAssembly() intrinsic expansion in the compiler
[System.Runtime.CompilerServices.DependencyReductionRoot]
public static Assembly GetExecutingAssembly(RuntimeTypeHandle typeHandle)
{
return Type.GetTypeFromHandle(typeHandle).Assembly;
}
}
}
| mit | C# |
671d2828500283d273a5451b199eaed3845e1306 | Fix minor typo in documentation (#78) | danikf/tik4net | tik4net/ITikSentence.cs | tik4net/ITikSentence.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace tik4net
{
/// <summary>
/// Base of all sentences returned from mikrotik router as response to request.
/// </summary>
public interface ITikSentence
{
/// <summary>
/// All sentence words (properties). {fieldName, value}
/// </summary>
#if NET20 || NET35 || NET40
IDictionary<string, string> Words { get; }
#else
IReadOnlyDictionary<string, string> Words { get; }
#endif
/// <summary>
/// Tag of sentence (see asynchronous commands for details).
/// </summary>
/// <seealso cref="ITikConnection.CallCommandAsync(IEnumerable{string}, string, Action{ITikSentence})"/>
/// <seealso cref="ITikCommand.ExecuteAsync"/>
string Tag { get; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace tik4net
{
/// <summary>
/// Base of all sentences returned from mikrotik router as response to request.
/// </summary>
public interface ITikSentence
{
/// <summary>
/// All sentence words (properties). {fieldName, value}
/// </summary>
#if NET20 || NET35 || NET40
IDictionary<string, string> Words { get; }
#else
IReadOnlyDictionary<string, string> Words { get; }
#endif
/// <summary>
/// Tag of sentence (see asynchronous commands fro details).
/// </summary>
/// <seealso cref="ITikConnection.CallCommandAsync(IEnumerable{string}, string, Action{ITikSentence})"/>
/// <seealso cref="ITikCommand.ExecuteAsync"/>
string Tag { get; }
}
}
| apache-2.0 | C# |
cd0676e6418b48b6ccd65eabea9bc8513283d9de | Update Address.cs | eeaquino/DotNetShipping,kylewest/DotNetShipping | src/DotNetShipping/Address.cs | src/DotNetShipping/Address.cs | using System;
namespace DotNetShipping
{
/// <summary>
/// Summary description for Address.
/// </summary>
public class Address
{
#region .ctor
public Address(string city, string state, string postalCode, string countryCode) : this(null, null, null, city, state, postalCode, countryCode)
{
}
public Address(string line1, string line2, string line3, string city, string state, string postalCode, string countryCode)
{
Line1 = line1;
Line2 = line2;
Line3 = line3;
City = city;
State = state;
PostalCode = postalCode;
CountryCode = countryCode;
IsResidential = false;
}
#endregion
#region Properties
public string City { get; set; }
public string CountryCode { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string PostalCode { get; set; }
public string State { get; set; }
public bool IsResidential { get; set; }
#endregion
#region Methods
public bool IsUnitedStatesAddress()
{
return !string.IsNullOrEmpty(CountryCode) && string.Equals(CountryCode, "US", StringComparison.OrdinalIgnoreCase);
}
#endregion
}
}
| using System;
namespace DotNetShipping
{
/// <summary>
/// Summary description for Address.
/// </summary>
public class Address
{
#region .ctor
public Address(string city, string state, string postalCode, string countryCode) : this(null, null, null, city, state, postalCode, countryCode)
{
}
public Address(string line1, string line2, string line3, string city, string state, string postalCode, string countryCode)
{
Line1 = line1;
Line2 = line2;
Line3 = line3;
City = city;
State = state;
PostalCode = postalCode;
CountryCode = countryCode;
}
#endregion
#region Properties
public string City { get; set; }
public string CountryCode { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string PostalCode { get; set; }
public string State { get; set; }
#endregion
#region Methods
public bool IsUnitedStatesAddress()
{
return !string.IsNullOrEmpty(CountryCode) && string.Equals(CountryCode, "US", StringComparison.OrdinalIgnoreCase);
}
#endregion
}
} | mit | C# |
5a999ac5a06a3db3e3177ee3e9bd6bbf9c7d0eaa | Correct logging around TextRendering | BlythMeister/Ensconce,BlythMeister/Ensconce,15below/Ensconce,15below/Ensconce | src/Ensconce/TextRendering.cs | src/Ensconce/TextRendering.cs | using System;
using System.Collections.Generic;
using System.IO;
using FifteenBelow.Deployment.Update;
namespace Ensconce
{
internal static class TextRendering
{
private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(BuildTagDictionary);
public static IDictionary<string, object> TagDictionary { get { return LazyTags.Value; } }
internal static string Render(this string s)
{
return s.RenderTemplate(LazyTags.Value);
}
private static TagDictionary BuildTagDictionary()
{
Logging.Log("Building Tag Dictionary");
var instanceName = Environment.GetEnvironmentVariable("InstanceName");
Logging.Log("Building Tag Dictionary ({0})", instanceName);
var tags = new TagDictionary(instanceName);
Logging.Log("Built Tag Dictionary ({0})", instanceName);
Arguments.FixedPath = Arguments.FixedPath.RenderTemplate(tags);
if (File.Exists(Arguments.FixedPath))
{
Logging.Log("Loading xml config from file {0}", Path.GetFullPath(Arguments.FixedPath));
var configXml = Retry.Do(() => File.ReadAllText(Arguments.FixedPath), TimeSpan.FromSeconds(5));
Logging.Log("Re-Building Tag Dictionary (Using Config File)");
tags = new TagDictionary(instanceName, configXml);
Logging.Log("Built Tag Dictionary (Using Config File)");
}
else
{
Logging.Log("No structure file found at: {0}", Path.GetFullPath(Arguments.FixedPath));
}
return tags;
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using FifteenBelow.Deployment.Update;
namespace Ensconce
{
internal static class TextRendering
{
private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(BuildTagDictionary);
public static IDictionary<string, object> TagDictionary { get { return LazyTags.Value; } }
internal static string Render(this string s)
{
return s.RenderTemplate(LazyTags.Value);
}
private static TagDictionary BuildTagDictionary()
{
Logging.Log("Building Tag Dictionary");
var instanceName = Environment.GetEnvironmentVariable("InstanceName");
var tags = new TagDictionary(instanceName);
Logging.Log("Build Tag Dictionary (Pass 1)");
Arguments.FixedPath = Arguments.FixedPath.RenderTemplate(tags);
if (File.Exists(Arguments.FixedPath))
{
Logging.Log("Reloading tags using config file {0}", Path.GetFullPath(Arguments.FixedPath));
var configXml = Retry.Do(() => File.ReadAllText(Arguments.FixedPath), TimeSpan.FromSeconds(5));
Logging.Log("Re-Building Tag Dictionary (Using Config File)");
tags = new TagDictionary(instanceName, configXml);
Logging.Log("Build Tag Dictionary (Using Config File)");
}
else
{
Logging.Log("No structure file found at: {0}", Path.GetFullPath(Arguments.FixedPath));
}
return tags;
}
}
} | mit | C# |
95ca7f9a84b511c7412fbab4d78f40ea42a85cbe | Update MainWindow.xaml.cs | Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Core2D.UI/Views/MainWindow.xaml.cs | src/Core2D.UI/Views/MainWindow.xaml.cs | using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace Core2D.UI.Views
{
/// <summary>
/// Interaction logic for <see cref="MainWindow"/> xaml.
/// </summary>
public class MainWindow : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="MainWindow"/> class.
/// </summary>
public MainWindow()
{
InitializeComponent();
this.AttachDevTools();
//VisualRoot.Renderer.DrawDirtyRects = true;
//VisualRoot.Renderer.DrawFps = true;
//App.Selector.EnableThemes(this);
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace Core2D.UI.Views
{
/// <summary>
/// Interaction logic for <see cref="MainWindow"/> xaml.
/// </summary>
public class MainWindow : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="MainWindow"/> class.
/// </summary>
public MainWindow()
{
InitializeComponent();
this.AttachDevTools();
//VisualRoot.Renderer.DrawDirtyRects = true;
//VisualRoot.Renderer.DrawFps = true;
App.Selector.EnableThemes(this);
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| mit | C# |
d48b1bf720740012152b6a505c89018480d6dd39 | Update RobGibbens.cs | beraybentesen/planetxamarin,stvansolano/planetxamarin,beraybentesen/planetxamarin,beraybentesen/planetxamarin,planetxamarin/planetxamarin,stvansolano/planetxamarin,stvansolano/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/RobGibbens.cs | src/Firehose.Web/Authors/RobGibbens.cs | using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
public class RobGibbens : IWorkAtXamarinOrMicrosoft
{
public string FirstName => "Rob";
public string LastName => "Gibbens";
public string ShortBioOrTagLine => "is one of the Xamarin University instructors";
public string StateOrRegion => "Farmington, Michigan";
public string EmailAddress => "RobGibbens@arteksoftware.com";
public string TwitterHandle => "RobGibbens";
public string GravatarHash => "";
public string GitHubHandle => string.Empty;
public GeoPosition Position => new GeoPosition(42.4644800, -83.3763220);
public Uri WebSite => new Uri("http://arteksoftware.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("http://arteksoftware.com/rss/"); }
}
}
| using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
public class RobGibbens : IWorkAtXamarinOrMicrosoft
{
public string FirstName => "Rob";
public string LastName => "Gibbens";
public string ShortBioOrTagLine => "manager and trainer at Xamarin University";
public string StateOrRegion => "Farmington, Michigan";
public string EmailAddress => "RobGibbens@arteksoftware.com";
public string TwitterHandle => "RobGibbens";
public string GravatarHash => "";
public string GitHubHandle => string.Empty;
public GeoPosition Position => new GeoPosition(42.4644800, -83.3763220);
public Uri WebSite => new Uri("http://arteksoftware.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("http://arteksoftware.com/rss/"); }
}
} | mit | C# |
d88189e8da6899df9a26dd8c326aa750e99826dd | Update ISampleDataAccesssService.cs | SDolha/UnitOfWork-EntityFramework | UnitOfWorkEntityFramework/SampleApp.DataAccess/ISampleDataAccesssService.cs | UnitOfWorkEntityFramework/SampleApp.DataAccess/ISampleDataAccesssService.cs | using DataAccessPatterns.Contracts;
using System;
namespace SampleApp.DataAccess
{
public interface ISampleDataAccesssService : IDisposable
{
IUnitOfWork GetUnitOfWork();
IRepository<T> GetRepository<T>() where T : class;
IEmployeeRepository GetEmployeeRepository();
}
}
| using DataAccessPatterns.Contracts;
using System;
namespace SampleApp.DataAccess
{
public interface ISampleDataAccesssService : IDisposable
{
IEmployeeRepository GetEmployeeRepository();
IRepository<T> GetRepository<T>() where T : class;
IUnitOfWork GetUnitOfWork();
}
} | mit | C# |
ff039a3b4a367da9d8e12e17d92725f3093d57fe | fix XML header in response #386 | DigDes/SoapCore | src/SoapCore/CustomMessage.cs | src/SoapCore/CustomMessage.cs | using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
namespace SoapCore
{
public class CustomMessage : Message
{
private readonly Message _message;
public CustomMessage(Message message)
{
_message = message;
}
public override MessageHeaders Headers
{
get { return _message.Headers; }
}
public override MessageProperties Properties
{
get { return _message.Properties; }
}
public override MessageVersion Version
{
get { return _message.Version; }
}
protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
{
writer.WriteStartDocument();
if (_message.Version.Envelope == EnvelopeVersion.Soap11)
{
writer.WriteStartElement("s", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
}
else
{
writer.WriteStartElement("s", "Envelope", "http://www.w3.org/2003/05/soap-envelope");
}
writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
_message.WriteBodyContents(writer);
}
}
}
| using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
namespace SoapCore
{
public class CustomMessage : Message
{
private readonly Message _message;
public CustomMessage(Message message)
{
_message = message;
}
public override MessageHeaders Headers
{
get { return _message.Headers; }
}
public override MessageProperties Properties
{
get { return _message.Properties; }
}
public override MessageVersion Version
{
get { return _message.Version; }
}
protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
{
writer.WriteStartDocument();
if (_message.Version.Envelope == EnvelopeVersion.Soap11)
{
writer.WriteStartElement("s", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
}
else
{
writer.WriteStartElement("s", "Envelope", "http://www.w3.org/2003/05/soap-envelope");
}
writer.WriteAttributeString("xsd", "xmlns", "http://www.w3.org/2001/XMLSchema");
writer.WriteAttributeString("xsi", "xmlns", "http://www.w3.org/2001/XMLSchema-instance");
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
_message.WriteBodyContents(writer);
}
}
}
| mit | C# |
7fec4f4ac21394b2d4ebdce605d3bf10c4c8b1a0 | Update France.cs | sambeauvois/DayInfo,sambeauvois/DayInfo,sambeauvois/DayInfo,sambeauvois/DayInfo | DayInfo/Europe/France.cs | DayInfo/Europe/France.cs | using DayInfo.Internals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DayInfo.Europe
{
public class France : DayInfo
{
private static List<DayInfo> list;
public France()
: base("FR")
{
}
public override IEnumerable<DayInfo> All()
{
if (list == null)
{
list = new List<DayInfo>();
list.AddRange(new ChristianDayInfo().All());
list.AddRange(GetHollidays());
}
return list;
}
private IEnumerable<France> GetHollidays()
{
return new France[]
{
new France
{
DisplayName = "Nouvel an",
EnglishName = "New Year",
IsHolliday = true,
NativeName = "Nouvel an",
Definition = new DayDefinition(1, Months.January)
},
new France
{
DisplayName = "Fête du travail",
EnglishName = "Labour Day",
IsHolliday = true,
NativeName = "Fête du travail",
Definition = new DayDefinition(1, Months.May)
},
new France
{
DisplayName = "Fête nationale",
EnglishName = "National Day",
IsHolliday = true,
NativeName = "Fête nationale",
Definition = new DayDefinition(14, Months.July)
}
};
}
// fêtes http://icalendrier.fr/fetes/fete-des-meres/
}
}
| using DayInfo.Internals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DayInfo.Europe
{
public class France : DayInfo
{
private static List<DayInfo> list;
public France()
: base("FR")
{
}
public override IEnumerable<DayInfo> All()
{
if (list == null)
{
list = new List<DayInfo>();
list.AddRange(new ChristianDayInfo().All());
list.AddRange(GetHollidays());
}
return list;
}
private IEnumerable<France> GetHollidays()
{
return new France[]
{
new France
{
DisplayName = "Nouvel an",
EnglishName = "New Year",
IsHolliday = true,
NativeName = "Nouvel an",
Definition = new DayDefinition(1, Months.January)
},
new France
{
DisplayName = "Fête du travail",
EnglishName = "Labour Day",
IsHolliday = true,
NativeName = "Fête du travail",
Definition = new DayDefinition(1, Months.May)
},
new France
{
DisplayName = "Fête nationale",
EnglishName = "National Day",
IsHolliday = true,
NativeName = "Fête nationale",
Definition = new DayDefinition(14, Months.July)
}
};
}
}
}
| mit | C# |
ba1d373005dcb46c433f5003e6b07761c2c88678 | Remove unnecessary function | hukatama024e/MacroRecoderCsScript,hukatama024e/UserInputMacro | src/UserInputMacro/SendInputWrapper.cs | src/UserInputMacro/SendInputWrapper.cs | using System.Runtime.InteropServices;
using System.ComponentModel;
namespace UserInputMacro
{
public static class SendInputWrapper
{
private static readonly int FAIL_SENDINPUT = 0;
[ DllImport( "user32.dll", SetLastError = true ) ]
private static extern uint SendInput( uint inputNum, Input[] inputs, int inputStructSize );
public static void SendMouseInput( MouseInput[] mouseInput )
{
uint result;
Input[] input = new Input[ mouseInput.Length ];
for( int i = 0; i < mouseInput.Length; i++ ) {
input[ i ].type = InputType.Mouse;
input[ i ].inputInfo.mouseInput = mouseInput[ i ];
}
result = SendInput( ( uint ) input.Length, input, Marshal.SizeOf( input[ 0 ] ) );
if( result == FAIL_SENDINPUT ) {
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception( errorCode );
}
}
public static void SendKeyInput( KeyInput[] keyInput )
{
uint result;
Input[] input = new Input[ keyInput.Length ];
for( int i = 0; i < keyInput.Length; i++ ) {
input[ i ].type = InputType.Keyboard;
input[ i ].inputInfo.keyInput = keyInput[ i ];
}
result = SendInput( ( uint ) input.Length, input, Marshal.SizeOf( input[ 0 ] ) );
if( result == FAIL_SENDINPUT ) {
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception( errorCode );
}
}
}
}
| using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Windows.Input;
namespace UserInputMacro
{
public static class SendInputWrapper
{
private static readonly int FAIL_SENDINPUT = 0;
[ DllImport( "user32.dll", SetLastError = true ) ]
private static extern uint SendInput( uint inputNum, Input[] inputs, int inputStructSize );
public static void PressKey( Key key )
{
KeyInput[] keyInput = new KeyInput[ 1 ];
keyInput[ 0 ] = new KeyInput
{
virtualKey = ( ushort ) KeyInterop.VirtualKeyFromKey( key )
};
SendKeyInput( keyInput );
}
public static void SendMouseInput( MouseInput[] mouseInput )
{
uint result;
Input[] input = new Input[ mouseInput.Length ];
for( int i = 0; i < mouseInput.Length; i++ ) {
input[ i ].type = InputType.Mouse;
input[ i ].inputInfo.mouseInput = mouseInput[ i ];
}
result = SendInput( ( uint ) input.Length, input, Marshal.SizeOf( input[ 0 ] ) );
if( result == FAIL_SENDINPUT ) {
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception( errorCode );
}
}
public static void SendKeyInput( KeyInput[] keyInput )
{
uint result;
Input[] input = new Input[ keyInput.Length ];
for( int i = 0; i < keyInput.Length; i++ ) {
input[ i ].type = InputType.Keyboard;
input[ i ].inputInfo.keyInput = keyInput[ i ];
}
result = SendInput( ( uint ) input.Length, input, Marshal.SizeOf( input[ 0 ] ) );
if( result == FAIL_SENDINPUT ) {
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception( errorCode );
}
}
}
}
| mit | C# |
19a5f3c18365dad6f9e13578355d1281e0e95643 | fix group separator naming | volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity | src/Serenity.Net.Web/Common/ScriptCulture.cs | src/Serenity.Net.Web/Common/ScriptCulture.cs | using System.Globalization;
using System;
namespace Serenity
{
public class ScriptCulture
{
public ScriptCulture()
: this(CultureInfo.CurrentCulture)
{
}
public ScriptCulture(CultureInfo culture)
{
var order = DateHelper.DateElementOrderFor(culture.DateTimeFormat.ShortDatePattern);
DateOrder = DateHelper.DateOrderString(order);
DateFormat = DateHelper.DefaultDateFormat(order);
DateTimeFormat = DateHelper.DefaultDateTimeFormat(order);
DateSeparator = DateTime.MaxValue.ToString("yy/MM/dd", culture.DateTimeFormat)[2].ToString();
DecimalSeparator = culture.NumberFormat.NumberDecimalSeparator;
GroupSeparator = culture.NumberFormat.NumberGroupSeparator;
}
public string DateOrder { get; set; }
public string DateFormat { get; set; }
public string DateSeparator { get; set; }
public string DateTimeFormat { get; set; }
public string DecimalSeparator { get; set; }
public string GroupSeparator { get; set; }
}
} | using System.Globalization;
using System;
namespace Serenity
{
public class ScriptCulture
{
public ScriptCulture()
: this(CultureInfo.CurrentCulture)
{
}
public ScriptCulture(CultureInfo culture)
{
var order = DateHelper.DateElementOrderFor(culture.DateTimeFormat.ShortDatePattern);
DateOrder = DateHelper.DateOrderString(order);
DateFormat = DateHelper.DefaultDateFormat(order);
DateTimeFormat = DateHelper.DefaultDateTimeFormat(order);
DateSeparator = DateTime.MaxValue.ToString("yy/MM/dd", culture.DateTimeFormat)[2].ToString();
DecimalSeparator = culture.NumberFormat.NumberDecimalSeparator;
GroupSepearator = culture.NumberFormat.NumberGroupSeparator;
}
public string DateOrder { get; set; }
public string DateFormat { get; set; }
public string DateSeparator { get; set; }
public string DateTimeFormat { get; set; }
public string DecimalSeparator { get; set; }
public string GroupSepearator { get; set; }
}
} | mit | C# |
7777d554ff69cb9f08de67ea3ff5ebf41b3c1f39 | Add ResourceCompleter to DevTestLabs | devigned/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell | src/ResourceManager/DevTestLabs/Commands.DevTestLabs/Commands/DevTestLabsCmdletBase.cs | src/ResourceManager/DevTestLabs/Commands.DevTestLabs/Commands/DevTestLabsCmdletBase.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.DevTestLabs;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.DevTestLabs
{
public class DevTestLabsCmdletBase : AzureRMCmdlet
{
internal IDevTestLabsClient _dataServiceClient;
#region Input Parameter Definitions
/// <summary>
/// Lab name
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
HelpMessage =
"Specifies a name an existing DevTest lab."
)]
[ValidateNotNullOrEmpty]
public string LabName { get; set; }
/// <summary>
/// Resource group name
/// </summary>
[Parameter(Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Specifies the name of an existing resource group that contains the lab.")]
[ResourceGroupCompleter()]
[ValidateNotNullOrEmpty()]
public string ResourceGroupName { get; set; }
#endregion Input Parameter Definitions
internal IDevTestLabsClient DataServiceClient
{
get
{
if (_dataServiceClient == null)
{
_dataServiceClient = AzureSession.Instance.ClientFactory.CreateArmClient<DevTestLabsClient>(DefaultContext,
AzureEnvironment.Endpoint.ResourceManager);
_dataServiceClient.ResourceGroupName = ResourceGroupName;
}
return _dataServiceClient;
}
set
{
_dataServiceClient = value;
}
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Management.DevTestLabs;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.DevTestLabs
{
public class DevTestLabsCmdletBase : AzureRMCmdlet
{
internal IDevTestLabsClient _dataServiceClient;
#region Input Parameter Definitions
/// <summary>
/// Lab name
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
HelpMessage =
"Specifies a name an existing DevTest lab."
)]
[ValidateNotNullOrEmpty]
public string LabName { get; set; }
/// <summary>
/// Resource group name
/// </summary>
[Parameter(Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Specifies the name of an existing resource group that contains the lab.")]
[ValidateNotNullOrEmpty()]
public string ResourceGroupName { get; set; }
#endregion Input Parameter Definitions
internal IDevTestLabsClient DataServiceClient
{
get
{
if (_dataServiceClient == null)
{
_dataServiceClient = AzureSession.Instance.ClientFactory.CreateArmClient<DevTestLabsClient>(DefaultContext,
AzureEnvironment.Endpoint.ResourceManager);
_dataServiceClient.ResourceGroupName = ResourceGroupName;
}
return _dataServiceClient;
}
set
{
_dataServiceClient = value;
}
}
}
}
| apache-2.0 | C# |
c692351625f03e73da3da24e79bae47be2f951d5 | Add null option to select to indicate no search index is set in the admin UI (#10608) | xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2 | src/OrchardCore.Modules/OrchardCore.Lucene/Views/LuceneSettings.Edit.cshtml | src/OrchardCore.Modules/OrchardCore.Lucene/Views/LuceneSettings.Edit.cshtml | @model LuceneSettingsViewModel
@if (Model.SearchIndexes.Any())
{
<div class="form-group" asp-validation-class-for="SearchIndex">
<label asp-for="SearchIndex">@T["Default search index"]</label>
<select asp-for="SearchIndex" class="form-control">
<option value="" selected="@(Model.SearchIndex == null)">@T["Select a search index"]</option>
@foreach (var index in Model.SearchIndexes)
{
<option value="@index" selected="@(Model.SearchIndex == index)">@index</option>
}
</select>
<span asp-validation-for="SearchIndex"></span>
<span class="hint">@T["The default index to use for the search page."]</span>
</div>
}
else
{
<div class="alert alert-warning">@T["You need to create at least an index to set as the Search index."]</div>
}
<div class="form-group" asp-validation-class-for="SearchFields">
<label asp-for="SearchFields">@T["Default searched fields"]</label>
<input asp-for="SearchFields" class="form-control" />
<span asp-validation-for="SearchFields"></span>
<span class="hint">@T["A comma separated list of fields to use for search pages. The default value is <code>Content.ContentItem.FullText</code>."]</span>
</div>
<div class="form-group" asp-validation-class-for="AllowLuceneQueriesInSearch">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" asp-for="AllowLuceneQueriesInSearch" />
<label class="custom-control-label" asp-for="AllowLuceneQueriesInSearch">@T["Allow Lucene queries in search forms"]</label>
<span class="hint dashed">@T["Whether search queries should be allowed to use <a href=\"https://lucene.apache.org/core/2_9_4/queryparsersyntax.html\">Lucene query parser syntax</a>."] <a class="seedoc" href="http://www.lucenetutorial.com/lucene-query-syntax.html" target="_blank">@T["See documentation"]</a></span>
</div>
</div>
| @model LuceneSettingsViewModel
@if (Model.SearchIndexes.Any())
{
<div class="form-group" asp-validation-class-for="SearchIndex">
<label asp-for="SearchIndex">@T["Default search index"]</label>
<select asp-for="SearchIndex" class="form-control">
@foreach (var index in Model.SearchIndexes)
{
<option value="@index" selected="@(Model.SearchIndex == index)">@index</option>
}
</select>
<span asp-validation-for="SearchIndex"></span>
<span class="hint">@T["The default index to use for the search page."]</span>
</div>
}
else
{
<div class="alert alert-warning">@T["You need to create at least an index to set as the Search index."]</div>
}
<div class="form-group" asp-validation-class-for="SearchFields">
<label asp-for="SearchFields">@T["Default searched fields"]</label>
<input asp-for="SearchFields" class="form-control" />
<span asp-validation-for="SearchFields"></span>
<span class="hint">@T["A comma separated list of fields to use for search pages. The default value is <code>Content.ContentItem.FullText</code>."]</span>
</div>
<div class="form-group" asp-validation-class-for="AllowLuceneQueriesInSearch">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" asp-for="AllowLuceneQueriesInSearch" />
<label class="custom-control-label" asp-for="AllowLuceneQueriesInSearch">@T["Allow Lucene queries in search forms"]</label>
<span class="hint dashed">@T["Whether search queries should be allowed to use <a href=\"https://lucene.apache.org/core/2_9_4/queryparsersyntax.html\">Lucene query parser syntax</a>."] <a class="seedoc" href="http://www.lucenetutorial.com/lucene-query-syntax.html" target="_blank">@T["See documentation"]</a></span>
</div>
</div>
| bsd-3-clause | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.