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 |
|---|---|---|---|---|---|---|---|---|
e23edf42fba406564f40a67916ed16ae2b448ef7 | fix build error | Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode | WorkWithTelemetryInDotNET/BillingService/OrderPlacedHandler.cs | WorkWithTelemetryInDotNET/BillingService/OrderPlacedHandler.cs | using JetBrains.Annotations;
using NServiceBus;
// using NServiceBus.Extensions.Diagnostics;
using Shared;
namespace BillingService;
[UsedImplicitly]
public partial class OrderPlacedHandler : IHandleMessages<OrderPlaced>
{
private readonly ILogger<OrderPlacedHandler> _logger;
public OrderPlacedHandler(ILogger<OrderPlacedHandler> logger)
{
_logger = logger;
}
[LoggerMessage(Level = LogLevel.Information, Message = "BillingService has received OrderPlaced, OrderId = {OrderId}")]
public static partial void LogOrderReceivedEvent(ILogger logger, string orderId);
public Task Handle(OrderPlaced message, IMessageHandlerContext context)
{
if (_logger.IsEnabled(LogLevel.Information))
{
LogOrderReceivedEvent(_logger, message.OrderId);
}
// var currentActivity = context.Extensions.Get<ICurrentActivity>();
// currentActivity.Current?.AddTag("payment.transaction.id", Guid.NewGuid().ToString());
return Task.CompletedTask;
}
} | using JetBrains.Annotations;
using NServiceBus;
using NServiceBus.Extensions.Diagnostics;
using Shared;
namespace BillingService;
[UsedImplicitly]
public partial class OrderPlacedHandler : IHandleMessages<OrderPlaced>
{
private readonly ILogger<OrderPlacedHandler> _logger;
public OrderPlacedHandler(ILogger<OrderPlacedHandler> logger)
{
_logger = logger;
}
[LoggerMessage(Level = LogLevel.Information, Message = "BillingService has received OrderPlaced, OrderId = {OrderId}")]
public static partial void LogOrderReceivedEvent(ILogger logger, string orderId);
public Task Handle(OrderPlaced message, IMessageHandlerContext context)
{
if (_logger.IsEnabled(LogLevel.Information))
{
LogOrderReceivedEvent(_logger, message.OrderId);
}
var currentActivity = context.Extensions.Get<ICurrentActivity>();
currentActivity.Current?.AddTag("payment.transaction.id", Guid.NewGuid().ToString());
return Task.CompletedTask;
}
} | mit | C# |
a66ef86ffb6b488662d6a87990d2cfeb61b1a856 | Fix page count | Krusen/ErgastApi.Net | src/ErgastiApi/Responses/ErgastResponse.cs | src/ErgastiApi/Responses/ErgastResponse.cs | using System;
using Newtonsoft.Json;
namespace ErgastApi.Responses
{
// TODO: Use internal/private constructors for all response types?
public abstract class ErgastResponse
{
public string Url { get; set; }
public int Limit { get; set; }
public int Offset { get; set; }
[JsonProperty("total")]
public int TotalResults { get; set; }
// TODO: Note that it can be inaccurate if limit/offset do not correlate
// TODO: Test with 0 values
public int Page => Offset / Limit + 1;
// TODO: Test with 0 values
public int TotalPages => (int) Math.Ceiling(TotalResults / (double)Limit);
// TODO: Test
public bool HasMorePages => TotalResults > Limit + Offset;
}
}
| using System;
namespace ErgastApi.Responses
{
// TODO: Use internal/private constructors for all response types?
public abstract class ErgastResponse
{
public string Url { get; set; }
public int Limit { get; set; }
public int Offset { get; set; }
public int Total { get; set; }
// TODO: Note that it can be inaccurate if limit/offset do not correlate
// TODO: Test with 0 values
public int Page => Offset / Limit;
// TODO: Test with 0 values
public int TotalPages => (int) Math.Ceiling(Total / (double)Limit);
// TODO: Test
public bool HasMorePages => Total > Limit + Offset;
}
}
| unlicense | C# |
eb03b0ee3a59f31f364ef904ed5c35ee67565ae1 | Fix whitespace in IMemberService. | GiveCampUK/GiveCRM,GiveCampUK/GiveCRM | src/GiveCRM.Web/Services/IMemberService.cs | src/GiveCRM.Web/Services/IMemberService.cs | using System.Collections.Generic;
using GiveCRM.Models;
namespace GiveCRM.Web.Services
{
public interface IMemberService
{
IEnumerable<Member> All();
Member Get(int id);
void Update(Member member);
void Insert(Member member);
void Delete(Member member);
void Save(Member member);
IEnumerable<Member> Search(string name, string postcode, string reference);
IEnumerable<Member> Search(string criteria);
IEnumerable<Member> FromCampaignRun(int campaignId);
}
} | using System.Collections.Generic;
using GiveCRM.Models;
namespace GiveCRM.Web.Services
{
public interface IMemberService
{
IEnumerable<Member> All();
Member Get(int id);
void Update(Member member);
void Insert(Member member);
void Delete(Member member);
void Save(Member member);
IEnumerable<Member> Search(string name, string postcode, string reference);
IEnumerable<Member> Search(string criteria);
IEnumerable<Member> FromCampaignRun(int campaignId);
}
} | mit | C# |
1eae934ac5f295180e392f144e662ff3cd194fc0 | update TotpHelperTest.cs | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | test/WeihanLi.Common.Test/HelpersTest/TotpHelperTest.cs | test/WeihanLi.Common.Test/HelpersTest/TotpHelperTest.cs | using System.Threading;
using WeihanLi.Common.Helpers;
using Xunit;
namespace WeihanLi.Common.Test.HelpersTest
{
public class TotpHelperTest
{
private readonly object _lock = new object();
private readonly string bizToken = "test_xxx";
[Fact]
public void Test()
{
lock (_lock)
{
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = null;
options.ExpiresIn = 600;
});
var code = TotpHelper.GenerateCode(bizToken);
Assert.NotEmpty(code);
Thread.Sleep(2000);
Assert.True(TotpHelper.VerifyCode(bizToken, code));
}
}
[Fact]
public void SaltTest()
{
lock (_lock)
{
TotpHelper.ConfigureTotpOptions(options => options.Salt = null);
var code = TotpHelper.GenerateCode(bizToken);
Assert.NotEmpty(code);
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = "amazing-dotnet";
options.ExpiresIn = 600;
});
Assert.False(TotpHelper.VerifyCode(bizToken, code));
var code1 = TotpHelper.GenerateCode(bizToken);
Assert.NotEmpty(code1);
Thread.Sleep(2000);
Assert.True(TotpHelper.VerifyCode(bizToken, code1));
}
}
}
}
| using System.Threading;
using WeihanLi.Common.Helpers;
using Xunit;
namespace WeihanLi.Common.Test.HelpersTest
{
public class TotpHelperTest
{
private readonly object _lock = new object();
private readonly string bizToken = "test_xxx";
[Fact]
public void Test()
{
lock (_lock)
{
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = null;
options.ExpiresIn = 600;
});
var code = TotpHelper.GenerateCode(bizToken);
Assert.NotEmpty(code);
Thread.Sleep(2000);
Assert.True(TotpHelper.VerifyCode(bizToken, code));
}
}
[Fact]
public void SaltTest()
{
lock (_lock)
{
TotpHelper.ConfigureTotpOptions(options => options.Salt = null);
var code = TotpHelper.GenerateCode(bizToken);
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = "amazing-dotnet";
options.ExpiresIn = 600;
});
var code1 = TotpHelper.GenerateCode(bizToken);
Assert.NotEmpty(code);
Thread.Sleep(2000);
Assert.False(TotpHelper.VerifyCode(bizToken, code));
Assert.NotEmpty(code1);
Assert.True(TotpHelper.VerifyCode(bizToken, code1));
}
}
}
}
| mit | C# |
ad6db7d37240d7433852137ed181e82c0de935eb | Replace test with test stub | SmartStepGroup/AgileCamp2015_Master,SmartStepGroup/AgileCamp2015_Master,SmartStepGroup/AgileCamp2015_Master | UnitTests/UnitTest1.cs | UnitTests/UnitTest1.cs | #region Usings
using NUnit.Framework;
using WebApplication.Controllers;
#endregion
namespace UnitTests
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var controller = new HabitController();
Assert.True(true);
}
}
} | #region Usings
using NUnit.Framework;
#endregion
namespace UnitTests
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
Assert.True(true);
}
}
} | mit | C# |
5758cb569fbca1f9eabea1d49ec56df3dba3535e | Add tests of string handling. | mysql-net/MySqlConnector,mysql-net/MySqlConnector | tests/MySqlConnector.Tests/StatementPreparerTests.cs | tests/MySqlConnector.Tests/StatementPreparerTests.cs | using System.Text;
using MySql.Data.MySqlClient;
using MySqlConnector.Core;
using MySqlConnector.Utilities;
using Xunit;
namespace MySqlConnector.Tests
{
public class StatementPreparerTests
{
[Theory]
[InlineData("SELECT Id\nFROM mytable\nWHERE column1 = 2\nAND column2 = @param")]
[InlineData("SELECT Id\nFROM mytable\nWHERE column1 = 2 -- mycomment\nAND column2 = @param")]
[InlineData("SELECT Id\nFROM mytable\nWHERE column1 = 2 -- mycomment\nAND column2 = @param")]
[InlineData("SELECT Id\nFROM mytable\nWHERE column1 = 2 -- mycomment\n AND column2 = @param")]
public void Bug429(string sql)
{
var parameters = new MySqlParameterCollection();
parameters.AddWithValue("@param", 123);
var parsedSql = GetParsedSql(sql, parameters);
Assert.Equal(sql.Replace("@param", "123"), parsedSql);
}
[Theory]
[InlineData(@"SELECT /* * / @param */ 1;")]
[InlineData("SELECT # @param \n1;")]
[InlineData("SELECT -- @param \n1;")]
public void ParametersIgnoredInComments(string sql)
{
Assert.Equal(sql, GetParsedSql(sql));
}
[Theory]
[InlineData("SELECT '@param';")]
[InlineData("SELECT \"@param\";")]
[InlineData("SELECT `@param`;")]
[InlineData("SELECT 'test\\'@param';")]
[InlineData("SELECT \"test\\\"@param\";")]
[InlineData("SELECT 'test''@param';")]
[InlineData("SELECT \"test\"\"@param\";")]
[InlineData("SELECT `test``@param`;")]
public void ParametersIgnoredInStrings(string sql)
{
Assert.Equal(sql, GetParsedSql(sql));
}
private static string GetParsedSql(string input, MySqlParameterCollection parameters = null) =>
Encoding.UTF8.GetString(new StatementPreparer(input, parameters ?? new MySqlParameterCollection(), StatementPreparerOptions.None).ParseAndBindParameters().Slice(1));
}
}
| using System.Text;
using MySql.Data.MySqlClient;
using MySqlConnector.Core;
using MySqlConnector.Utilities;
using Xunit;
namespace MySqlConnector.Tests
{
public class StatementPreparerTests
{
[Theory]
[InlineData("SELECT Id\nFROM mytable\nWHERE column1 = 2\nAND column2 = @param")]
[InlineData("SELECT Id\nFROM mytable\nWHERE column1 = 2 -- mycomment\nAND column2 = @param")]
[InlineData("SELECT Id\nFROM mytable\nWHERE column1 = 2 -- mycomment\nAND column2 = @param")]
[InlineData("SELECT Id\nFROM mytable\nWHERE column1 = 2 -- mycomment\n AND column2 = @param")]
public void Bug429(string sql)
{
var parameters = new MySqlParameterCollection();
parameters.AddWithValue("@param", 123);
var parsedSql = GetParsedSql(sql, parameters);
Assert.Equal(sql.Replace("@param", "123"), parsedSql);
}
[Theory]
[InlineData(@"SELECT /* * / @param */ 1;")]
[InlineData("SELECT # @param \n1;")]
[InlineData("SELECT -- @param \n1;")]
public void ParametersIgnoredInComments(string sql)
{
Assert.Equal(sql, GetParsedSql(sql));
}
private static string GetParsedSql(string input, MySqlParameterCollection parameters = null) =>
Encoding.UTF8.GetString(new StatementPreparer(input, parameters ?? new MySqlParameterCollection(), StatementPreparerOptions.None).ParseAndBindParameters().Slice(1));
}
}
| mit | C# |
0873924a6b4bd4318e67e0bb6d2a0dc88466b575 | Make a few methods public for testability Switch to more generic IMongoQuery | phoenixwebgroup/DotNetMongoMigrations,phoenixwebgroup/DotNetMongoMigrations | src/MongoMigrations/CollectionMigration.cs | src/MongoMigrations/CollectionMigration.cs | namespace MongoMigrations
{
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
public abstract class CollectionMigration : Migration
{
protected string CollectionName;
public CollectionMigration(MigrationVersion version, string collectionName) : base(version)
{
CollectionName = collectionName;
}
public virtual IMongoQuery Filter()
{
return null;
}
public override void Update()
{
var collection = GetCollection();
var documents = GetDocuments(collection);
UpdateDocuments(collection, documents);
}
public virtual void UpdateDocuments(MongoCollection<BsonDocument> collection, IEnumerable<BsonDocument> documents)
{
foreach (var document in documents)
{
try
{
UpdateDocument(collection, document);
}
catch (Exception exception)
{
OnErrorUpdatingDocument(document, exception);
}
}
}
protected virtual void OnErrorUpdatingDocument(BsonDocument document, Exception exception)
{
var message =
new
{
Message = "Failed to update document",
CollectionName,
Id = document.TryGetDocumentId(),
MigrationVersion = Version,
MigrationDescription = Description
};
throw new MigrationException(message.ToString(), exception);
}
public abstract void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document);
protected virtual MongoCollection<BsonDocument> GetCollection()
{
return Database.GetCollection(CollectionName);
}
protected virtual IEnumerable<BsonDocument> GetDocuments(MongoCollection<BsonDocument> collection)
{
var query = Filter();
return query != null
? collection.Find(query)
: collection.FindAll();
}
}
} | namespace MongoMigrations
{
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
public abstract class CollectionMigration : Migration
{
protected string CollectionName;
public CollectionMigration(MigrationVersion version, string collectionName) : base(version)
{
CollectionName = collectionName;
}
public virtual QueryDocument Filter()
{
return null;
}
public override void Update()
{
var collection = GetCollection();
var documents = GetDocuments(collection);
UpdateDocuments(collection, documents);
}
protected virtual void UpdateDocuments(MongoCollection<BsonDocument> collection, IEnumerable<BsonDocument> documents)
{
foreach (var document in documents)
{
try
{
UpdateDocument(collection, document);
}
catch (Exception exception)
{
OnErrorUpdatingDocument(document, exception);
}
}
}
protected virtual void OnErrorUpdatingDocument(BsonDocument document, Exception exception)
{
var message =
new
{
Message = "Failed to update document",
CollectionName,
Id = document.TryGetDocumentId(),
MigrationVersion = Version,
MigrationDescription = Description
};
throw new MigrationException(message.ToString(), exception);
}
protected abstract void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document);
protected virtual MongoCollection<BsonDocument> GetCollection()
{
return Database.GetCollection(CollectionName);
}
protected virtual IEnumerable<BsonDocument> GetDocuments(MongoCollection<BsonDocument> collection)
{
var query = Filter();
return query != null
? collection.Find(query)
: collection.FindAll();
}
}
} | mit | C# |
eb3c4d09c8897f5fe79696cfa1a002017f8f6f7b | Improve BulletController | emazzotta/unity-tower-defense | Assets/Scripts/BulletController.cs | Assets/Scripts/BulletController.cs | using UnityEngine;
using System.Collections;
public class BulletController : MonoBehaviour {
public float speed = 2f;
public Transform target;
public int damage = 1;
public float radius = 0;
void Update() {
Vector3 direction = target.position - this.transform.position;
float distanceCurrentFrame = speed * Time.deltaTime;
if(direction.magnitude <= distanceCurrentFrame) {
// We reached the node
DoBulletHit();
} else {
this.transform.Translate(direction.normalized * distanceCurrentFrame, Space.World);
Quaternion targetRotation = Quaternion.LookRotation(direction);
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, targetRotation, Time.deltaTime*speed);
}
}
void DoBulletHit() {
if(radius == 0) {
if (target != null) {
target.GetComponent<MetallKeferController>().TakeDamage(damage);
}
} else {
Collider[] collider = Physics.OverlapSphere(transform.position, radius);
foreach(Collider c in collider) {
MetallKeferController e = c.GetComponent<MetallKeferController>();
if(e != null) {
e.GetComponent<MetallKeferController>().TakeDamage(damage);
}
}
}
}
}
| using UnityEngine;
using System.Collections;
public class BulletController : MonoBehaviour {
public float speed = 5f;
public Transform target;
public float damage = 1f;
public float radius = 0;
void Start() {
}
void Update() {
if(target == null) {
Destroy(this);
return;
}
Vector3 direction = target.position - this.transform.localPosition;
float distanceCurrentFrame = speed * Time.deltaTime;
if(direction.magnitude <= distanceCurrentFrame) {
// We reached the node
DoBulletHit();
} else {
this.transform.Translate(direction.normalized * distanceCurrentFrame, Space.World);
Quaternion targetRotation = Quaternion.LookRotation(direction);
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, targetRotation, Time.deltaTime*5);
}
}
void DoBulletHit() {
if(radius == 0) {
target.GetComponent<MetallKeferController>().TakeDamage(damage);
} else {
Collider[] collider = Physics.OverlapSphere(transform.position, radius);
foreach(Collider c in collider) {
MetallKeferController e = c.GetComponent<MetallKeferController>();
if(e != null) {
e.GetComponent<MetallKeferController>().TakeDamage(damage);
}
}
}
Destroy(this);
}
}
| mit | C# |
8f3a3fb56ef8778627d267fe2c021110efd03a87 | Add mouse support | ChillyFlashER/OpenInput | src/OpenInput.Veldrid.SDL2/VeldridMouse.cs | src/OpenInput.Veldrid.SDL2/VeldridMouse.cs | namespace OpenInput
{
using OpenInput.Trackers;
using System.Collections.Generic;
using System.Linq;
using Veldrid;
public class VeldridMouse : VeldridDevice, IMouse
{
private readonly HashSet<MouseButton> pressedButtons = new HashSet<MouseButton>();
private MouseState currentState = new MouseState();
/// <inheritdoc />
public string Name => "Veldrid Mouse";
/// <inheritdoc />
public IMouseTracker CreateTracker() => new BasicMouseTracker(this);
/// <inheritdoc />
public MouseState GetCurrentState() => this.currentState;
/// <inheritdoc />
public void GetPosition(out int x, out int y)
{
x = this.currentState.X;
y = this.currentState.Y;
}
/// <inheritdoc />
public void SetPosition(int x, int y)
{
throw new System.NotImplementedException();
}
internal override void UpdateSnapshot(InputSnapshot snapshot)
{
foreach (var key in snapshot.MouseEvents)
{
if (key.Down)
{
this.pressedButtons.Add(key.MouseButton);
}
else
{
this.pressedButtons.Remove(key.MouseButton);
}
}
this.currentState = new MouseState(
(int)snapshot.MousePosition.X,
(int)snapshot.MousePosition.Y,
(int)snapshot.WheelDelta,
pressedButtons.Contains(MouseButton.Left),
pressedButtons.Contains(MouseButton.Middle),
pressedButtons.Contains(MouseButton.Right),
pressedButtons.Contains(MouseButton.Button1),
pressedButtons.Contains(MouseButton.Button2));
}
}
}
| namespace OpenInput
{
using OpenInput.Trackers;
using Veldrid;
public class VeldridMouse : VeldridDevice, IMouse
{
/// <inheritdoc />
public string Name => "Veldrid Mouse";
/// <inheritdoc />
public IMouseTracker CreateTracker() => new BasicMouseTracker(this);
/// <inheritdoc />
public MouseState GetCurrentState()
{
// FIXME:
return new MouseState();
}
/// <inheritdoc />
public void GetPosition(out int x, out int y)
{
throw new System.NotImplementedException();
}
/// <inheritdoc />
public void SetPosition(int x, int y)
{
throw new System.NotImplementedException();
}
internal override void UpdateSnapshot(InputSnapshot snapshot)
{
}
}
}
| mit | C# |
c69bde2ec1406c037457fe6966d4711be9d49b2d | Update AppModule.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D | src/Core2D/UI/Avalonia/Modules/AppModule.cs | src/Core2D/UI/Avalonia/Modules/AppModule.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Autofac;
using Core2D.Editor;
using Core2D.Interfaces;
using Core2D.UI.Avalonia.Editor;
using Core2D.UI.Avalonia.Importers;
namespace Core2D.UI.Avalonia.Modules
{
/// <summary>
/// Application components module.
/// </summary>
public class AppModule : Autofac.Module
{
/// <inheritdoc/>
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AvaloniaImageImporter>().As<IImageImporter>().InstancePerLifetimeScope();
builder.RegisterType<AvaloniaProjectEditorPlatform>().As<IProjectEditorPlatform>().InstancePerLifetimeScope();
builder.RegisterType<AvaloniaEditorCanvasPlatform>().As<IEditorCanvasPlatform>().InstancePerLifetimeScope();
builder.RegisterType<AvaloniaEditorLayoutPlatform>().As<IEditorLayoutPlatform>().InstancePerLifetimeScope();
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Autofac;
using Core2D.UI.Avalonia.Editor;
using Core2D.UI.Avalonia.Importers;
using Core2D.Editor;
using Core2D.Interfaces;
namespace Core2D.UI.Avalonia.Modules
{
/// <summary>
/// Application components module.
/// </summary>
public class AppModule : Autofac.Module
{
/// <inheritdoc/>
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AvaloniaImageImporter>().As<IImageImporter>().InstancePerLifetimeScope();
builder.RegisterType<AvaloniaProjectEditorPlatform>().As<IProjectEditorPlatform>().InstancePerLifetimeScope();
builder.RegisterType<AvaloniaEditorCanvasPlatform>().As<IEditorCanvasPlatform>().InstancePerLifetimeScope();
builder.RegisterType<AvaloniaEditorLayoutPlatform>().As<IEditorLayoutPlatform>().InstancePerLifetimeScope();
}
}
}
| mit | C# |
ab3c31c0ab18ac13ce1e73ec1f3e4333aa469b87 | Allow to create ecommon configuration twice. | tangxuehua/ecommon,Aaron-Liu/ecommon | src/ECommon/Configurations/Configuration.cs | src/ECommon/Configurations/Configuration.cs | using System;
using ECommon.Components;
using ECommon.IO;
using ECommon.Logging;
using ECommon.Scheduling;
using ECommon.Serializing;
using ECommon.Socketing.Framing;
namespace ECommon.Configurations
{
public class Configuration
{
/// <summary>Provides the singleton access instance.
/// </summary>
public static Configuration Instance { get; private set; }
private Configuration() { }
public static Configuration Create()
{
Instance = new Configuration();
return Instance;
}
public Configuration SetDefault<TService, TImplementer>(string serviceName = null, LifeStyle life = LifeStyle.Singleton)
where TService : class
where TImplementer : class, TService
{
ObjectContainer.Register<TService, TImplementer>(serviceName, life);
return this;
}
public Configuration SetDefault<TService, TImplementer>(TImplementer instance, string serviceName = null)
where TService : class
where TImplementer : class, TService
{
ObjectContainer.RegisterInstance<TService, TImplementer>(instance, serviceName);
return this;
}
public Configuration RegisterCommonComponents()
{
SetDefault<ILoggerFactory, EmptyLoggerFactory>();
SetDefault<IBinarySerializer, DefaultBinarySerializer>();
SetDefault<IJsonSerializer, NotImplementedJsonSerializer>();
SetDefault<IScheduleService, ScheduleService>(null, LifeStyle.Transient);
SetDefault<IMessageFramer, LengthPrefixMessageFramer>(null, LifeStyle.Transient);
SetDefault<IOHelper, IOHelper>();
return this;
}
public Configuration RegisterUnhandledExceptionHandler()
{
var logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
AppDomain.CurrentDomain.UnhandledException += (sender, e) => logger.ErrorFormat("Unhandled exception: {0}", e.ExceptionObject);
return this;
}
}
}
| using System;
using ECommon.Components;
using ECommon.IO;
using ECommon.Logging;
using ECommon.Scheduling;
using ECommon.Serializing;
using ECommon.Socketing.Framing;
namespace ECommon.Configurations
{
public class Configuration
{
/// <summary>Provides the singleton access instance.
/// </summary>
public static Configuration Instance { get; private set; }
private Configuration() { }
public static Configuration Create()
{
if (Instance != null)
{
throw new Exception("Could not create configuration instance twice.");
}
Instance = new Configuration();
return Instance;
}
public Configuration SetDefault<TService, TImplementer>(string serviceName = null, LifeStyle life = LifeStyle.Singleton)
where TService : class
where TImplementer : class, TService
{
ObjectContainer.Register<TService, TImplementer>(serviceName, life);
return this;
}
public Configuration SetDefault<TService, TImplementer>(TImplementer instance, string serviceName = null)
where TService : class
where TImplementer : class, TService
{
ObjectContainer.RegisterInstance<TService, TImplementer>(instance, serviceName);
return this;
}
public Configuration RegisterCommonComponents()
{
SetDefault<ILoggerFactory, EmptyLoggerFactory>();
SetDefault<IBinarySerializer, DefaultBinarySerializer>();
SetDefault<IJsonSerializer, NotImplementedJsonSerializer>();
SetDefault<IScheduleService, ScheduleService>(null, LifeStyle.Transient);
SetDefault<IMessageFramer, LengthPrefixMessageFramer>(null, LifeStyle.Transient);
SetDefault<IOHelper, IOHelper>();
return this;
}
public Configuration RegisterUnhandledExceptionHandler()
{
var logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
AppDomain.CurrentDomain.UnhandledException += (sender, e) => logger.ErrorFormat("Unhandled exception: {0}", e.ExceptionObject);
return this;
}
}
}
| mit | C# |
97135dabb826d850cc8053b8060fdce0f13c36fc | Add "References" as parent | michael-reichenauer/Dependinator | Dependinator/ModelParsing/Private/MonoCecilReflection/Private/ModuleParser.cs | Dependinator/ModelParsing/Private/MonoCecilReflection/Private/ModuleParser.cs | using System;
using System.Linq;
using Mono.Cecil;
namespace Dependinator.ModelParsing.Private.MonoCecilReflection.Private
{
internal class ModuleParser
{
private readonly string rootGroup;
private readonly LinkHandler linkHandler;
private readonly Sender sender;
private AssemblyDefinition assembly;
public ModuleParser(
string rootGroup,
LinkHandler linkHandler,
Sender sender)
{
this.rootGroup = rootGroup;
this.linkHandler = linkHandler;
this.sender = sender;
}
public void AddModule(AssemblyDefinition assemblyDefinition)
{
assembly = assemblyDefinition;
string parent = rootGroup;
string moduleName = Name.GetAssemblyName(assembly);
int index = moduleName.IndexOfTxt("*");
if (index > 0)
{
string groupName = moduleName.Substring(1, index - 1);
parent = parent == null ? groupName : $"{parent}.{groupName}";
}
parent = parent != null ? $"${parent?.Replace(".", ".$")}" : null;
ModelNode moduleNode = new ModelNode(moduleName, parent, JsonTypes.NodeType.NameSpace);
sender.SendNode(moduleNode);
}
public void AddModuleLinks()
{
if (assembly == null)
{
return;
}
string moduleName = Name.GetAssemblyName(assembly);
var references = assembly.MainModule.AssemblyReferences.
Where(reference => !IgnoredTypes.IsSystemIgnoredModuleName(reference.Name));
foreach (AssemblyNameReference reference in references)
{
string parent = "References";
string referenceName = Name.GetModuleName(reference.Name);
int index = referenceName.IndexOfTxt("*");
if (index > 0)
{
parent = $"References.{referenceName.Substring(1, index - 1)}";
}
parent = $"${parent?.Replace(".", ".$")}";
ModelNode referenceNode = new ModelNode(referenceName, parent, JsonTypes.NodeType.NameSpace);
sender.SendNode(referenceNode);
linkHandler.AddLinkToReference(
new Reference(moduleName, referenceName, JsonTypes.NodeType.NameSpace));
}
}
}
} | using System;
using System.Linq;
using Mono.Cecil;
namespace Dependinator.ModelParsing.Private.MonoCecilReflection.Private
{
internal class ModuleParser
{
private readonly string rootGroup;
private readonly LinkHandler linkHandler;
private readonly Sender sender;
private AssemblyDefinition assembly;
public ModuleParser(
string rootGroup,
LinkHandler linkHandler,
Sender sender)
{
this.rootGroup = rootGroup;
this.linkHandler = linkHandler;
this.sender = sender;
}
public void AddModule(AssemblyDefinition assemblyDefinition)
{
assembly = assemblyDefinition;
string parent = rootGroup;
string moduleName = Name.GetAssemblyName(assembly);
int index = moduleName.IndexOfTxt("*");
if (index > 0)
{
string groupName = moduleName.Substring(1, index - 1);
parent = parent == null ? groupName : $"{parent}.{groupName}";
}
parent = parent != null ? $"${parent?.Replace(".", ".$")}" : null;
ModelNode moduleNode = new ModelNode(moduleName, parent, JsonTypes.NodeType.NameSpace);
sender.SendNode(moduleNode);
}
public void AddModuleLinks()
{
if (assembly == null)
{
return;
}
string moduleName = Name.GetAssemblyName(assembly);
var references = assembly.MainModule.AssemblyReferences.
Where(reference => !IgnoredTypes.IsSystemIgnoredModuleName(reference.Name));
foreach (AssemblyNameReference reference in references)
{
string parent = null;
string referenceName = Name.GetModuleName(reference.Name);
int index = referenceName.IndexOfTxt("*");
if (index > 0)
{
parent = referenceName.Substring(1, index - 1);
}
parent = parent != null ? $"${parent?.Replace(".", ".$")}" : null;
ModelNode referenceNode = new ModelNode(referenceName, parent, JsonTypes.NodeType.NameSpace);
sender.SendNode(referenceNode);
linkHandler.AddLinkToReference(
new Reference(moduleName, referenceName, JsonTypes.NodeType.NameSpace));
}
}
}
} | mit | C# |
8e6cd9fa69690ca9506d97007e3005ee15655629 | handle legacy logouts | YAFNET/YAFNET,YAFNET/YAFNET,YAFNET/YAFNET,YAFNET/YAFNET | yafsrc/YetAnotherForum.NET/Pages/Account/Logout.ascx.cs | yafsrc/YetAnotherForum.NET/Pages/Account/Logout.ascx.cs | /* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Pages.Account
{
#region Using
using System;
using System.Web.Security;
using YAF.Core.BasePages;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.EventProxies;
using YAF.Types.Interfaces;
using YAF.Types.Interfaces.Events;
using YAF.Types.Interfaces.Identity;
using YAF.Utils;
#endregion
/// <summary>
/// The Logout function
/// </summary>
public partial class Logout : AccountPage
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref = "Logout" /> class.
/// </summary>
public Logout()
: base("LOGOUT")
{
this.PageContext.Globals.IsSuspendCheckEnabled = false;
}
#endregion
#region Methods
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
this.Get<IAspNetUsersHelper>().SignOut();
// Handle legacy ASP.NET Membership logout
FormsAuthentication.SignOut();
this.Get<IRaiseEvent>().Raise(new UserLogoutEvent(this.PageContext.PageUserID));
BuildLink.Redirect(ForumPages.Board);
}
#endregion
}
} | /* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Pages.Account
{
#region Using
using System;
using YAF.Core.BasePages;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.EventProxies;
using YAF.Types.Interfaces;
using YAF.Types.Interfaces.Events;
using YAF.Types.Interfaces.Identity;
using YAF.Utils;
#endregion
/// <summary>
/// The Logout function
/// </summary>
public partial class Logout : AccountPage
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref = "Logout" /> class.
/// </summary>
public Logout()
: base("LOGOUT")
{
this.PageContext.Globals.IsSuspendCheckEnabled = false;
}
#endregion
#region Methods
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
this.Get<IAspNetUsersHelper>().SignOut();
this.Get<IRaiseEvent>().Raise(new UserLogoutEvent(this.PageContext.PageUserID));
BuildLink.Redirect(ForumPages.Board);
}
#endregion
}
} | apache-2.0 | C# |
f92e364108b73b9e505407794e83050af7c0afb5 | Update Version : 1.7.171.0 URL Changes + Fix User Manager Delete | Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal | Master/Appleseed/Projects/Appleseed.Framework.Core/Properties/AssemblyInfo.cs | Master/Appleseed/Projects/Appleseed.Framework.Core/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Resources;
// 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("Appleseed.Framework.Core")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed Portal")]
[assembly: AssemblyCopyright("Copyright ANANT Corporation 2010-2017")]
[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( "acbff986-eea5-4c71-8bcd-c868dc78a20d" )]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.7.171.0")]
[assembly: AssemblyFileVersion("1.7.171.0")]
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the "project output directory". The location of the project output
// directory is dependent on whether you are working with a local or web project.
// For local projects, the project output directory is defined as
// <Project Directory>\obj\<Configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// For web projects, the project output directory is defined as
// %HOMEPATH%\VSWebCache\<Machine Name>\<Project Directory>\obj\<Configuration>.
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign( false )]
[assembly: AssemblyKeyFile( "" )]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Resources;
// 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("Appleseed.Framework.Core")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed Portal")]
[assembly: AssemblyCopyright("Copyright ANANT Corporation 2010-2017")]
[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( "acbff986-eea5-4c71-8bcd-c868dc78a20d" )]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.6.160.540")]
[assembly: AssemblyFileVersion("1.6.160.540")]
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the "project output directory". The location of the project output
// directory is dependent on whether you are working with a local or web project.
// For local projects, the project output directory is defined as
// <Project Directory>\obj\<Configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// For web projects, the project output directory is defined as
// %HOMEPATH%\VSWebCache\<Machine Name>\<Project Directory>\obj\<Configuration>.
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign( false )]
[assembly: AssemblyKeyFile( "" )]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| apache-2.0 | C# |
da1a836a0455b0baef625252200f07663d8930ee | Support ErrorMessage and Variables in ExternalTaskBpmnError | jlucansky/Camunda.Api.Client | Camunda.Api.Client/ExternalTask/ExternalTaskBpmnError.cs | Camunda.Api.Client/ExternalTask/ExternalTaskBpmnError.cs |
using System.Collections.Generic;
namespace Camunda.Api.Client.ExternalTask
{
public class ExternalTaskBpmnError
{
/// <summary>
/// The id of the worker that reports the failure. Must match the id of the worker who has most recently locked the task.
/// </summary>
public string WorkerId;
/// <summary>
/// A error code that indicates the predefined error. Is used to identify the BPMN error handler.
/// </summary>
public string ErrorCode;
/// <summary>
/// An error message that describes the error.
/// </summary>
public string ErrorMessage;
/// <summary>
/// Object containing variable key-value pairs.
/// </summary>
public Dictionary<string, VariableValue> Variables = new Dictionary<string, VariableValue>();
public override string ToString() => ErrorCode;
}
}
|
namespace Camunda.Api.Client.ExternalTask
{
public class ExternalTaskBpmnError
{
/// <summary>
/// The id of the worker that reports the failure. Must match the id of the worker who has most recently locked the task.
/// </summary>
public string WorkerId;
/// <summary>
/// A error code that indicates the predefined error. Is used to identify the BPMN error handler.
/// </summary>
public string ErrorCode;
public override string ToString() => ErrorCode;
}
}
| mit | C# |
9f2053e446d7883eb813486cb91d59f401e61984 | Update LocalDbTests.cs | mantzas/linear | src/Linear/Linear.SqlServer.Tests.Integration/LocalDbTests.cs | src/Linear/Linear.SqlServer.Tests.Integration/LocalDbTests.cs | using FluentAssertions;
using Xunit;
namespace Linear.SqlServer.Tests.Integration
{
public class LocalDbTests
{
[Fact]
public void LocalDb()
{
using (var localDb = new LocalDb("test"))
{
localDb.ConnectionStringName.Should().NotBeNullOrWhiteSpace();
}
}
}
}
| using FluentAssertions;
using Xunit;
namespace Linear.SqlServer.Tests.Integration
{
public class LocalDbTests
{
[Fact]
public void LocalDb()
{
using (var localDb = new LocalDb("test"))
{
localDb.ConnectionStringName.Should().NotBeNullOrWhiteSpace();
}
}
}
}
| apache-2.0 | C# |
54188aa5b9b6c0dd0a40edbd1627bffce4f2465d | Make sure there is only one MobileServiceClient | Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving | src/MobileApps/MyDriving/MyDriving.AzureClient/AzureClient.cs | src/MobileApps/MyDriving/MyDriving.AzureClient/AzureClient.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using Microsoft.WindowsAzure.MobileServices;
namespace MyDriving.AzureClient
{
public class AzureClient : IAzureClient
{
const string DefaultMobileServiceUrl = "https://mydriving.azurewebsites.net";
static IMobileServiceClient client;
public IMobileServiceClient Client => client ?? (client = CreateClient());
IMobileServiceClient CreateClient()
{
client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
{
SerializerSettings = new MobileServiceJsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
CamelCasePropertyNames = true
}
};
return client;
}
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using Microsoft.WindowsAzure.MobileServices;
namespace MyDriving.AzureClient
{
public class AzureClient : IAzureClient
{
const string DefaultMobileServiceUrl = "https://mydriving.azurewebsites.net";
IMobileServiceClient client;
string mobileServiceUrl;
public IMobileServiceClient Client => client ?? (client = CreateClient());
IMobileServiceClient CreateClient()
{
client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
{
SerializerSettings = new MobileServiceJsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
CamelCasePropertyNames = true
}
};
return client;
}
}
} | mit | C# |
0b850c65db8b8e690404377f046cf6c9e496c2f2 | refactor store operations | rmterra/NesZord | src/NesZord.Tests/Describe_microprocessor_store_operations.cs | src/NesZord.Tests/Describe_microprocessor_store_operations.cs | using NesZord.Core;
using NSpec;
using Ploeh.AutoFixture;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NesZord.Tests
{
public class Describe_microprocessor_store_operations : nspec
{
private static readonly Fixture fixture = new Fixture();
public void When_store_accumulator_with_absolute_addressing_mode()
{
Microprocessor processor = null;
before = () => { processor = new Microprocessor(); };
act = () =>
{
processor.Start(new byte[]
{
(byte)OpCode.ImmediateLoadAccumulator, fixture.Create<byte>(),
(byte)OpCode.AbsoluteStoreAccumulator, 0x00, 0x20
});
};
it["should increment 3 to program counter"] = () => { processor.ProgramCounter.should_be(5); };
it["should store the accumulator value in $0200"] = () =>
{
processor.ValueAt(0x20, 0x00).should_be(processor.Accumulator);
};
}
}
} | using NesZord.Core;
using NSpec;
using Ploeh.AutoFixture;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NesZord.Tests
{
public class Describe_microprocessor_store_operations : nspec
{
private static readonly Fixture fixture = new Fixture();
public void When_store_accumulator_with_absolute_addressing_mode()
{
Microprocessor processor = null;
before = () => { processor = new Microprocessor(); };
act = () =>
{
processor.Start(new byte[]
{
(byte)OpCode.ImmediateLoadAccumulator, fixture.Create<byte>(),
(byte)OpCode.AbsoluteStoreAccumulator, 0x00, 0x20
});
};
it["Should increment 3 to program counter"] = () => { processor.ProgramCounter.should_be(5); };
it["Should store the accumulator value in $0200"] = () =>
{
processor.ValueAt(0x20, 0x00).should_be(processor.Accumulator);
};
}
}
} | apache-2.0 | C# |
5f89e4ff2fa111d9e90dace0c6439fa5c00c0944 | Correct feature attribute to indicate dependency. | Lombiq/Helpful-Extensions,Lombiq/Helpful-Extensions | Lombiq.HelpfulExtensions/Extensions/SiteTexts/Startup.cs | Lombiq.HelpfulExtensions/Extensions/SiteTexts/Startup.cs | using Lombiq.HelpfulExtensions.Extensions.SiteTexts.Services;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;
namespace Lombiq.HelpfulExtensions.Extensions.SiteTexts;
[Feature(FeatureIds.SiteTexts)]
public class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDataMigration, Migrations>();
services.AddScoped<ISiteTextService, SiteTextService>();
}
}
[RequireFeatures("OrchardCore.ContentLocalization")]
public class ContentLocalizationStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.RemoveImplementations<ISiteTextService>();
services.AddScoped<ISiteTextService, ContentLocalizationSiteTextService>();
}
}
| using Lombiq.HelpfulExtensions.Extensions.SiteTexts.Services;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;
namespace Lombiq.HelpfulExtensions.Extensions.SiteTexts;
[Feature(FeatureIds.SiteTexts)]
public class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDataMigration, Migrations>();
services.AddScoped<ISiteTextService, SiteTextService>();
}
}
[Feature("OrchardCore.ContentLocalization")]
public class ContentLocalizationStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.RemoveImplementations<ISiteTextService>();
services.AddScoped<ISiteTextService, ContentLocalizationSiteTextService>();
}
}
| bsd-3-clause | C# |
49a40e9020cefaf2702a3afe79ef7a35fa4f6440 | Fix unit test | damiensawyer/cassette,honestegg/cassette,honestegg/cassette,andrewdavey/cassette,andrewdavey/cassette,damiensawyer/cassette,andrewdavey/cassette,honestegg/cassette,damiensawyer/cassette | src/Cassette.Spriting.UnitTests/ImageFileLoader.cs | src/Cassette.Spriting.UnitTests/ImageFileLoader.cs | using System.IO;
using Should;
using Xunit;
namespace Cassette.Spriting
{
public class ImageFileLoader_GetImageBytesTests
{
[Fact]
public void ReadsBytesFromFile()
{
var directory = new FakeFileSystem
{
{ "~/test.png", new byte[] { 1, 2, 3 } }
};
var loader = new ImageFileLoader(directory);
var output = loader.GetImageBytes("/cassette.axd/file/test-hash.png");
output.ShouldEqual(new byte[] { 1, 2, 3 });
}
[Fact]
public void ThrowsExceptionIfFileDoesntExist()
{
var directory = new FakeFileSystem();
var loader = new ImageFileLoader(directory);
var exception = Record.Exception(() => loader.GetImageBytes("/cassette.axd/file/test-hash.png"));
exception.ShouldBeType<FileNotFoundException>();
}
}
} | using System.IO;
using Should;
using Xunit;
namespace Cassette.Spriting
{
public class ImageFileLoader_GetImageBytesTests
{
[Fact]
public void ReadsBytesFromFile()
{
var directory = new FakeFileSystem
{
{ "~/test.png", new byte[] { 1, 2, 3 } }
};
var loader = new ImageFileLoader(directory);
var output = loader.GetImageBytes("test.png");
output.ShouldEqual(new byte[] { 1, 2, 3 });
}
[Fact]
public void ThrowsExceptionIfFileDoesntExist()
{
var directory = new FakeFileSystem();
var loader = new ImageFileLoader(directory);
var exception = Record.Exception(() => loader.GetImageBytes("test.png"));
exception.ShouldBeType<FileNotFoundException>();
}
}
} | mit | C# |
854beaab5f590f3a3e6fc0bd6f788c8fc2ed792e | Remove only remaining .NET desktop code | peppy/osu,NeoAdonis/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu,DrabWeb/osu,2yangk23/osu,peppy/osu,naoey/osu,naoey/osu,ZLima12/osu,EVAST9919/osu,naoey/osu,ZLima12/osu,smoogipoo/osu,johnneijzen/osu,UselessToucan/osu,DrabWeb/osu,DrabWeb/osu,UselessToucan/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,johnneijzen/osu,2yangk23/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,NeoAdonis/osu,ppy/osu | osu.Desktop/Program.cs | osu.Desktop/Program.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.IO;
using System.Linq;
using osu.Framework;
using osu.Framework.Platform;
using osu.Game.IPC;
namespace osu.Desktop
{
public static class Program
{
[STAThread]
public static int Main(string[] args)
{
// Back up the cwd before DesktopGameHost changes it
var cwd = Environment.CurrentDirectory;
using (DesktopGameHost host = Host.GetSuitableHost(@"osu", true))
{
if (!host.IsPrimaryInstance)
{
var importer = new ArchiveImportIPCChannel(host);
// Restore the cwd so relative paths given at the command line work correctly
Directory.SetCurrentDirectory(cwd);
foreach (var file in args)
{
Console.WriteLine(@"Importing {0}", file);
if (!importer.ImportAsync(Path.GetFullPath(file)).Wait(3000))
throw new TimeoutException(@"IPC took too long to send");
}
}
else
{
switch (args.FirstOrDefault() ?? string.Empty)
{
default:
host.Run(new OsuGameDesktop(args));
break;
}
}
return 0;
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.IO;
using System.Linq;
using osu.Framework;
using osu.Framework.Platform;
using osu.Game.IPC;
#if NET_FRAMEWORK
using System.Runtime;
#endif
namespace osu.Desktop
{
public static class Program
{
[STAThread]
public static int Main(string[] args)
{
useMultiCoreJit();
// Back up the cwd before DesktopGameHost changes it
var cwd = Environment.CurrentDirectory;
using (DesktopGameHost host = Host.GetSuitableHost(@"osu", true))
{
if (!host.IsPrimaryInstance)
{
var importer = new ArchiveImportIPCChannel(host);
// Restore the cwd so relative paths given at the command line work correctly
Directory.SetCurrentDirectory(cwd);
foreach (var file in args)
{
Console.WriteLine(@"Importing {0}", file);
if (!importer.ImportAsync(Path.GetFullPath(file)).Wait(3000))
throw new TimeoutException(@"IPC took too long to send");
}
}
else
{
switch (args.FirstOrDefault() ?? string.Empty)
{
default:
host.Run(new OsuGameDesktop(args));
break;
}
}
return 0;
}
}
private static void useMultiCoreJit()
{
#if NET_FRAMEWORK
var directory = Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Profiles"));
ProfileOptimization.SetProfileRoot(directory.FullName);
ProfileOptimization.StartProfile("Startup.Profile");
#endif
}
}
}
| mit | C# |
eb00e93b583bb30f695ef520eb2f4eda34654c86 | enable RestLogLogic for cleanup | MehdyKarimpour/extensions,AlejandroCano/extensions,signumsoftware/extensions,AlejandroCano/extensions,signumsoftware/extensions,signumsoftware/framework,MehdyKarimpour/extensions,signumsoftware/framework | Signum.Engine.Extensions/RestLog/RestLogLogic.cs | Signum.Engine.Extensions/RestLog/RestLogLogic.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Entities.Basics;
using Signum.Entities.RestLog;
namespace Signum.Engine.RestLog
{
public class RestLogLogic
{
public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<RestLogEntity>()
.WithQuery(dqm, e => new
{
Entity = e,
e.Id,
e.StartDate,
e.Duration,
e.Url,
e.User,
e.Exception,
});
}
ExceptionLogic.DeleteLogs += DeleteRestLogs;
}
private static void DeleteRestLogs(DeleteLogParametersEntity parameters)
{
Database.Query<RestLogEntity>().Where(a => a.StartDate < parameters.DateLimit).UnsafeDeleteChunks(parameters.ChunkSize,parameters.MaxChunks);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Entities.Basics;
using Signum.Entities.RestLog;
namespace Signum.Engine.RestLog
{
public class RestLogLogic
{
public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<RestLogEntity>()
.WithQuery(dqm, e => new
{
Entity = e,
e.Id,
e.StartDate,
e.Duration,
e.Url,
e.User,
e.Exception,
});
}
}
}
}
| mit | C# |
7ad556108ddaa39142f248f25408a6ed0f73a69c | add links for users and configs | confused/Portfolio,confused/Portfolio,confused/Portfolio | Source/Portfolio.Web/Views/Shared/_Layout.cshtml | Source/Portfolio.Web/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
<li>@Html.ActionLink("Users", "List", "Users")</li>
<li>@Html.ActionLink("Configs", "List", "Configs")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| apache-2.0 | C# |
f6d34ed80bd0d01e9aaf350c4e1e9d621d981a93 | Correct migrations | CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction | CollAction/Migrations/20180311221855_UpdateEndDates.cs | CollAction/Migrations/20180311221855_UpdateEndDates.cs | using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace CollAction.Migrations
{
public partial class UpdateEndDates : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("UPDATE public.\"Projects\" SET \"End\" = \"End\" + interval '23 hours 59 minutes 59 seconds' WHERE \"End\"::time <> interval '23 hours 59 minutes 59 seconds';");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("UPDATE public.\"Projects\" SET \"End\" = \"End\" - interval '23 hours 59 minutes 59 seconds' WHERE \"End\"::time = interval '23 hours 59 minutes 59 seconds';");
}
}
}
| using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace CollAction.Migrations
{
public partial class UpdateEndDates : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("UPDATE public.\"Projects\" SET \"End\" = \"End\" + interval '23 hours' + interval '59 minutes' + interval '59 seconds';");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("UPDATE public.\"Projects\" SET \"End\" = \"End\" - interval '23 hours' - interval '59 minutes' - interval '59 seconds';");
}
}
}
| agpl-3.0 | C# |
1e6709deb91336c8b71ec4721d7b57d72a63c22c | Fix failing test | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade.Test/Core/AddmlDatasetTestEngineTest.cs | src/Arkivverket.Arkade.Test/Core/AddmlDatasetTestEngineTest.cs | using System.IO;
using Arkivverket.Arkade.Core;
using Arkivverket.Arkade.Core.Addml;
using FluentAssertions;
using Xunit;
namespace Arkivverket.Arkade.Test.Core
{
public class AddmlDatasetTestEngineTest
{
[Fact]
public void ShouldReturnTestSuiteFromTests()
{
var addmlDefinition = new AddmlDefinition();
var testSession = new TestSession(new Archive(ArchiveType.Noark3, Uuid.Random(), new DirectoryInfo(@"c:\temp")));
var addmlDatasetTestEngine = new AddmlDatasetTestEngine(new FlatFileReaderFactory(), new AddmlProcessRunner());
TestSuite testSuite = addmlDatasetTestEngine.RunTests(addmlDefinition, testSession);
testSuite.Should().NotBeNull();
}
}
} | using Arkivverket.Arkade.Core;
using Arkivverket.Arkade.Core.Addml;
using FluentAssertions;
using Xunit;
namespace Arkivverket.Arkade.Test.Core
{
public class AddmlDatasetTestEngineTest
{
[Fact]
public void ShouldReturnTestSuiteFromTests()
{
var addmlDefinition = new AddmlDefinition();
var testSuite = new AddmlDatasetTestEngine(addmlDefinition).RunTests();
testSuite.Should().NotBeNull();
}
}
} | agpl-3.0 | C# |
af8b7a243b8f67742789ff344cbd7f88afc6d7b4 | Fix path, because NUnit does nto run from the current assembly dir | zhdusurfin/HttpMock,hibri/HttpMock | src/HttpMock.Integration.Tests/EndpointsReturningFilesTests.cs | src/HttpMock.Integration.Tests/EndpointsReturningFilesTests.cs | using System;
using System.IO;
using System.Net;
using NUnit.Framework;
namespace HttpMock.Integration.Tests
{
[TestFixture]
public class EndpointsReturningFilesTests
{
private const string FILE_NAME = "transcode-input.mp3";
private const string RES_TRANSCODE_INPUT_MP3 = "res\\"+FILE_NAME;
[Test]
public void A_Setting_return_file_return_the_correct_content_length() {
var stubHttp = HttpMockRepository.At("http://localhost.:9191");
var pathToFile = Path.Combine(TestContext.CurrentContext.TestDirectory, RES_TRANSCODE_INPUT_MP3);
stubHttp.Stub(x => x.Get("/afile"))
.ReturnFile(pathToFile)
.OK();
Console.WriteLine(stubHttp.WhatDoIHave());
var fileLength = new FileInfo(pathToFile).Length;
var webRequest = (HttpWebRequest) WebRequest.Create("http://localhost.:9191/afile");
using (var response = webRequest.GetResponse())
using(var responseStream = response.GetResponseStream())
{
var bytes = new byte[response.ContentLength];
responseStream.Read(bytes, 0, (int) response.ContentLength);
Assert.That(response.ContentLength, Is.EqualTo(fileLength));
}
}
}
} | using System;
using System.IO;
using System.Net;
using NUnit.Framework;
namespace HttpMock.Integration.Tests
{
[TestFixture]
public class EndpointsReturningFilesTests
{
private const string FILE_NAME = "transcode-input.mp3";
private const string RES_TRANSCODE_INPUT_MP3 = "./res/"+FILE_NAME;
[Test]
public void A_Setting_return_file_return_the_correct_content_length() {
var stubHttp = HttpMockRepository.At("http://localhost.:9191");
stubHttp.Stub(x => x.Get("/afile"))
.ReturnFile(RES_TRANSCODE_INPUT_MP3)
.OK();
Console.WriteLine(stubHttp.WhatDoIHave());
var fileLength = new FileInfo(RES_TRANSCODE_INPUT_MP3).Length;
var webRequest = (HttpWebRequest) WebRequest.Create("http://localhost.:9191/afile");
using (var response = webRequest.GetResponse())
using(var responseStream = response.GetResponseStream())
{
var bytes = new byte[response.ContentLength];
responseStream.Read(bytes, 0, (int) response.ContentLength);
Assert.That(response.ContentLength, Is.EqualTo(fileLength));
}
}
}
} | mit | C# |
8ce0e1343f08d42e196429744ba3a391eebdc534 | Fix authentication crash on edit | yanpearson/BeerCellier,yanpearson/BeerCellier | BeerCellier/Global.asax.cs | BeerCellier/Global.asax.cs | using System.Security.Claims;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace BeerCellier
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace BeerCellier
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| mit | C# |
28b48dda26cc27ae282a6e210afc03582800781c | Revert "Migrate Buddy to the new backend" | punker76/Espera,flagbug/Espera | Espera/Espera.Core/Analytics/BuddyAnalyticsEndpoint.cs | Espera/Espera.Core/Analytics/BuddyAnalyticsEndpoint.cs | using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Buddy;
namespace Espera.Core.Analytics
{
public class BuddyAnalyticsEndpoint : IAnalyticsEndpoint
{
private readonly BuddyClient client;
private AuthenticatedUser storedUser;
public BuddyAnalyticsEndpoint()
{
this.client = new BuddyClient("Espera", "EC60C045-B432-44A6-A4E0-15B4BF607105", autoRecordDeviceInfo: false);
}
public async Task AuthenticateUserAsync(string analyticsToken)
{
this.storedUser = await this.client.LoginAsync(analyticsToken);
}
public async Task<string> CreateUserAsync()
{
string throwAwayToken = Guid.NewGuid().ToString();
AuthenticatedUser user = await this.client.CreateUserAsync(throwAwayToken, throwAwayToken);
this.storedUser = user;
return user.Token;
}
public async Task RecordDeviceInformationAsync()
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
await this.client.Device.RecordInformationAsync(Environment.OSVersion.VersionString, "Desktop", this.storedUser, version);
await this.RecordLanguageAsync();
}
public Task RecordErrorAsync(string message, string logId, string stackTrace = null)
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
return this.client.Device.RecordCrashAsync(message, Environment.OSVersion.VersionString, "Desktop", this.storedUser, stackTrace, version, metadata: logId);
}
public Task RecordMetaDataAsync(string key, string value)
{
return this.storedUser.Metadata.SetAsync(key, value);
}
public async Task<string> SendBlobAsync(string name, string mimeType, Stream data)
{
Blob blob = await this.storedUser.Blobs.AddAsync(name, mimeType, String.Empty, 0, 0, data);
return blob.BlobID.ToString(CultureInfo.InvariantCulture);
}
public Task UpdateUserEmailAsync(string email)
{
AuthenticatedUser user = this.storedUser;
return user.UpdateAsync(user.Email, String.Empty, user.Gender, user.Age, email, // email is the only field we change here
user.Status, user.LocationFuzzing, user.CelebrityMode, user.ApplicationTag);
}
}
} | using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Buddy;
namespace Espera.Core.Analytics
{
public class BuddyAnalyticsEndpoint : IAnalyticsEndpoint
{
private readonly BuddyClient client;
private AuthenticatedUser storedUser;
public BuddyAnalyticsEndpoint()
{
this.client = new BuddyClient("bbbbbc.mhbbbxjLrKNl", "83585740-AE7A-4F68-828D-5E6A8825A0EE", autoRecordDeviceInfo: false);
}
public async Task AuthenticateUserAsync(string analyticsToken)
{
this.storedUser = await this.client.LoginAsync(analyticsToken);
}
public async Task<string> CreateUserAsync()
{
string throwAwayToken = Guid.NewGuid().ToString();
AuthenticatedUser user = await this.client.CreateUserAsync(throwAwayToken, throwAwayToken);
this.storedUser = user;
return user.Token;
}
public async Task RecordDeviceInformationAsync()
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
await this.client.Device.RecordInformationAsync(Environment.OSVersion.VersionString, "Desktop", this.storedUser, version);
await this.RecordLanguageAsync();
}
public Task RecordErrorAsync(string message, string logId, string stackTrace = null)
{
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
return this.client.Device.RecordCrashAsync(message, Environment.OSVersion.VersionString, "Desktop", this.storedUser, stackTrace, version, metadata: logId);
}
public Task RecordMetaDataAsync(string key, string value)
{
return this.storedUser.Metadata.SetAsync(key, value);
}
public async Task<string> SendBlobAsync(string name, string mimeType, Stream data)
{
Blob blob = await this.storedUser.Blobs.AddAsync(name, mimeType, String.Empty, 0, 0, data);
return blob.BlobID.ToString(CultureInfo.InvariantCulture);
}
public Task UpdateUserEmailAsync(string email)
{
AuthenticatedUser user = this.storedUser;
return user.UpdateAsync(user.Email, String.Empty, user.Gender, user.Age, email, // email is the only field we change here
user.Status, user.LocationFuzzing, user.CelebrityMode, user.ApplicationTag);
}
}
}
| mit | C# |
b014dcbe5228d8874e24c7f34244b4c9989a2ec0 | repare link to the showpage in poster name | ismaelbelghiti/Tigwi,ismaelbelghiti/Tigwi | Core/Tigwi.UI/Views/Shared/_ViewPost.cshtml | Core/Tigwi.UI/Views/Shared/_ViewPost.cshtml | @model Tigwi.UI.Models.IPostModel
<article class="message shown poster-@Model.Poster.Id">
<div class="row-fluid">
<img alt="Avatar of @Model.Poster.Name"
class="span2"
src="@Url.Content("~/Content/images/default_profile_1_bigger.png")"
style="border-radius: 20px;" />
<section class="span10">
<h5>@Html.ActionLink(Model.Poster.Name, "Show", "Account", new { accountName = Model.Poster.Name }, null)</h5>
<p>@Model.Content</p>
</section>
</div>
</article>
| @model Tigwi.UI.Models.IPostModel
<article class="message shown poster-@Model.Poster.Id">
<div class="row-fluid">
<img alt="Avatar of @Model.Poster.Name"
class="span2"
src="@Url.Content("~/Content/images/default_profile_1_bigger.png")"
style="border-radius: 20px;" />
<section class="span10">
<h5>@Html.ActionLink(Model.Poster.Name, "Show", "Account", new { searchString = Model.Poster.Name }, null)</h5>
<p>@Model.Content</p>
</section>
</div>
</article>
| bsd-3-clause | C# |
005673c441308b48f3d44ee2fcb25a5efb32db8a | Update PostHandleSymbols.cs | dimmpixeye/Unity3dTools | Editor/SceneProcessors/PostHandleSymbols.cs | Editor/SceneProcessors/PostHandleSymbols.cs | // Project : ecs
// Contacts : Pix - ask@pixeye.games
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Pixeye.Framework
{
/// <summary>
/// Adds the given define symbols to PlayerSettings define symbols.
/// Just add your own define symbols to the Symbols property at the below.
/// </summary>
[InitializeOnLoad]
public class PostHandleSymbols : Editor
{
/// <summary>
/// Add define symbols as soon as Unity gets done compiling.
/// </summary>
static PostHandleSymbols()
{
string definesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
var allDefines = definesString.Split(';').ToList();
var index = allDefines.FindIndex(d => d.Contains("ACTORS_TAGS"));
var str = string.Empty;
if (DataFramework.sizeTags == 24)
{
str = "ACTORS_TAGS_24";
}
else if (DataFramework.sizeTags == 12)
{
str = "ACTORS_TAGS_12";
}
else if (DataFramework.sizeTags == 6)
{
str = "ACTORS_TAGS_6";
}
else str = "ACTORS_TAGS_0";
if (index > -1)
{
allDefines[index] = str;
}
else allDefines.Add(str);
index = allDefines.FindIndex(d => d.Contains("ACTORS_TAGS_CHECKS"));
str = DataFramework.tagsCheck ? "ACTORS_TAGS_CHECKS" : string.Empty;
if (index > -1)
{
allDefines[index] = str;
}
else
{
allDefines.Add(str);
}
index = allDefines.FindIndex(d => d.Contains("ACTORS_COMPONENTS_STRUCTS"));
str = DataFramework.onStructs ? "ACTORS_COMPONENTS_STRUCTS" : string.Empty;
if (index > -1)
{
allDefines[index] = str;
}
else
{
allDefines.Add(str);
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(";", allDefines.ToArray()));
}
}
} | // Project : ecs
// Contacts : Pix - ask@pixeye.games
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Pixeye.Framework
{
/// <summary>
/// Adds the given define symbols to PlayerSettings define symbols.
/// Just add your own define symbols to the Symbols property at the below.
/// </summary>
[InitializeOnLoad]
public class PostHandleSymbols : Editor
{
/// <summary>
/// Add define symbols as soon as Unity gets done compiling.
/// </summary>
static PostHandleSymbols()
{
string definesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
var allDefines = definesString.Split(';').ToList();
var index = allDefines.FindIndex(d => d.Contains("ACTORS_TAGS"));
var str = string.Empty;
if (DataFramework.sizeTags == 24)
{
str = "ACTORS_TAGS_24";
}
else if (DataFramework.sizeTags == 12)
{
str = "ACTORS_TAGS_12";
}
else
{
str = "ACTORS_TAGS_6";
}
if (index > -1)
{
allDefines[index] = str;
}
else allDefines.Add(str);
index = allDefines.FindIndex(d => d.Contains("ACTORS_TAGS_CHECKS"));
str = DataFramework.tagsCheck ? "ACTORS_TAGS_CHECKS" : string.Empty;
if (index > -1)
{
allDefines[index] = str;
}
else
{
allDefines.Add(str);
}
index = allDefines.FindIndex(d => d.Contains("ACTORS_COMPONENTS_STRUCTS"));
str = DataFramework.onStructs ? "ACTORS_COMPONENTS_STRUCTS" : string.Empty;
if (index > -1)
{
allDefines[index] = str;
}
else
{
allDefines.Add(str);
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(";", allDefines.ToArray()));
}
}
} | mit | C# |
9d17a321655af57cdb187a11dd3002646996a893 | テスト リファクタリング | kawakawa/TDDBC20170701 | VendingMachine/VendingMachineTests/Step1Tests.cs | VendingMachine/VendingMachineTests/Step1Tests.cs | using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Money;
using VendingMachine;
using Money = Money.Money;
namespace VendingMachineTests
{
[TestClass]
public class Step1Tests
{
[TestMethod]
public void _10円玉を投入して投入金額合計が10円になる()
{
投入金額.投入金額Clear();
投入口.投入(MoneyKind.Yen10);
投入金額.Get合計金額().Is(10);
}
[TestMethod]
public void _50円玉を投入して投入金額が50円になる()
{
投入金額.投入金額Clear();
投入口.投入(MoneyKind.Yen50);
投入金額.Get合計金額().Is(50);
}
[TestMethod]
public void _10円玉を5回投入して投入金額が50円になる()
{
投入金額.投入金額Clear();
Enumerable.Range(1, 5).ToList()
.ForEach(i => 投入口.投入(MoneyKind.Yen10));
投入金額.Get合計金額().Is(50);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Money;
using VendingMachine;
using Money = Money.Money;
namespace VendingMachineTests
{
[TestClass]
public class Step1Tests
{
[TestMethod]
public void _10円玉を投入して投入金額合計が10円になる()
{
投入金額.投入金額Clear();
投入口.投入(MoneyKind.Yen10);
投入金額.Get合計金額().Is(10);
}
[TestMethod]
public void _50円玉を投入して投入金額が50円になる()
{
投入金額.投入金額Clear();
投入口.投入(MoneyKind.Yen50);
投入金額.Get合計金額().Is(50);
}
[TestMethod]
public void _10円玉を5回投入して投入金額が50円になる()
{
投入金額.投入金額Clear();
投入口.投入(MoneyKind.Yen10);
投入口.投入(MoneyKind.Yen10);
投入口.投入(MoneyKind.Yen10);
投入口.投入(MoneyKind.Yen10);
投入口.投入(MoneyKind.Yen10);
投入金額.Get合計金額().Is(50);
}
}
}
| mit | C# |
16c283f03e99835d287f390b6d61d9c2146e5820 | Add RelayCommand with generic parameter | Vanlalhriata/Vulcan.Wpf | Vulcan.Wpf/Vulcan.Wpf.Core/Utils/RelayCommand.cs | Vulcan.Wpf/Vulcan.Wpf.Core/Utils/RelayCommand.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Vulcan.Wpf.Core
{
public class RelayCommand : ICommand
{
private Action<object> executeMethod;
private Func<object, bool> canExecuteMethod;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<object> executeMethod, Func<object, bool> canExecuteMethod = null)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = canExecuteMethod;
}
public bool CanExecute(object parameter)
{
if (null == canExecuteMethod)
return true;
return canExecuteMethod(parameter);
}
public void Execute(object parameter)
{
executeMethod(parameter);
}
}
public class RelayCommand<T> : ICommand
{
private Action<T> executeMethod;
private Func<T, bool> canExecuteMethod;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod = null)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = canExecuteMethod;
}
public bool CanExecute(object parameter)
{
if (null == canExecuteMethod)
return true;
return canExecuteMethod((T)Convert.ChangeType(parameter, typeof(T)));
}
public void Execute(object parameter)
{
executeMethod((T)Convert.ChangeType(parameter, typeof(T)));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Vulcan.Wpf.Core
{
public class RelayCommand : ICommand
{
private Action<object> executeMethod;
private Func<object, bool> canExecuteMethod;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<object> executeMethod, Func<object, bool> canExecuteMethod = null)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = canExecuteMethod;
}
public bool CanExecute(object parameter)
{
if (null == canExecuteMethod)
return true;
return canExecuteMethod(parameter);
}
public void Execute(object parameter)
{
executeMethod(parameter);
}
}
}
| mit | C# |
99e869309a5e140cb30d3e3b4e9b3047d168da2a | Enable skipped ManagementPartner tests | ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell | src/ResourceManager/ManagementPartner/Commands.Partner.Test/ScenarioTests/ManagementPartnerTests.cs | src/ResourceManager/ManagementPartner/Commands.Partner.Test/ScenarioTests/ManagementPartnerTests.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.Azure.Commands.ManagementPartner;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Azure.Commands.ManagementPartner.Test.ScenarioTests
{
public class ManagementPartnerTests : RMTestBase
{
public XunitTracingInterceptor _logger;
public ManagementPartnerTests(Xunit.Abstractions.ITestOutputHelper output)
{
_logger = new XunitTracingInterceptor(output);
XunitTracingInterceptor.AddToContext(_logger);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetPartner()
{
TestController.NewInstance.RunPsTest(_logger, "Test-GetPartner");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetPartnerNoParnterId()
{
TestController.NewInstance.RunPsTest(_logger, "Test-GetPartnerNoPartnerId");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestNewParnter()
{
TestController.NewInstance.RunPsTest(_logger, "Test-NewPartner");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestUpdateParnter()
{
TestController.NewInstance.RunPsTest(_logger, "Test-UpdatePartner");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestRemoveParnter()
{
TestController.NewInstance.RunPsTest(_logger, "Test-RemovePartner");
}
}
}
| // ----------------------------------------------------------------------------------
//
// 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.Azure.Commands.ManagementPartner;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Azure.Commands.ManagementPartner.Test.ScenarioTests
{
public class ManagementPartnerTests : RMTestBase
{
public XunitTracingInterceptor _logger;
public ManagementPartnerTests(Xunit.Abstractions.ITestOutputHelper output)
{
_logger = new XunitTracingInterceptor(output);
XunitTracingInterceptor.AddToContext(_logger);
}
[Fact(Skip = "ManagementPartner tests need to be re-enabled, as outlined in issue https://github.com/Azure/azure-powershell/issues/6678")]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetPartner()
{
TestController.NewInstance.RunPsTest(_logger, "Test-GetPartner");
}
[Fact(Skip = "ManagementPartner tests need to be re-enabled, as outlined in issue https://github.com/Azure/azure-powershell/issues/6678")]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetPartnerNoParnterId()
{
TestController.NewInstance.RunPsTest(_logger, "Test-GetPartnerNoPartnerId");
}
[Fact(Skip = "ManagementPartner tests need to be re-enabled, as outlined in issue https://github.com/Azure/azure-powershell/issues/6678")]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestNewParnter()
{
TestController.NewInstance.RunPsTest(_logger, "Test-NewPartner");
}
[Fact(Skip = "ManagementPartner tests need to be re-enabled, as outlined in issue https://github.com/Azure/azure-powershell/issues/6678")]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestUpdateParnter()
{
TestController.NewInstance.RunPsTest(_logger, "Test-UpdatePartner");
}
[Fact(Skip = "ManagementPartner tests need to be re-enabled, as outlined in issue https://github.com/Azure/azure-powershell/issues/6678")]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestRemoveParnter()
{
TestController.NewInstance.RunPsTest(_logger, "Test-RemovePartner");
}
}
}
| apache-2.0 | C# |
19d3c3692b58bb29ef585b21fbba3b631f608bfe | Update WallGenerator.cs | Domiii/UnityLoopyLoops | Assets/Scripts/WallGenerator.cs | Assets/Scripts/WallGenerator.cs | using UnityEngine;
using System.Collections;
public class WallGenerator : MonoBehaviour {
public int nx = 10;
public int ny = 10;
public float Gap = 0.1f;
public MeshRenderer brickPrefab;
public void Generate() {
if (brickPrefab == null) {
Debug.LogError ("Missing Brick Prefab. Make sure to prepare and assign a prefab for the bricks!");
return;
}
// delete existing bricks first
Clear ();
// get brick size
var bounds = brickPrefab.bounds;
var brickW = bounds.extents.x * 2;
var brickH = bounds.extents.y * 2;
// build a bunch of bricks!
for (var j = 0; j < ny; ++j) {
for (var i = 0; i < nx; ++i) {
// create brick
var brick = Instantiate (brickPrefab, transform);
// set position
var x = i * (brickW + Gap) + Gap;
var y = j * (brickH + Gap) + Gap;
var pos = new Vector3 (x, y, 0);
brick.transform.localPosition = pos;
}
}
}
/// <summary>
/// Delete all children (bricks).
/// 把所有的小孩都 「清掉」.
/// </summary>
public void Clear() {
for (var i = transform.childCount-1; i >= 0; --i){
DestroyImmediate(transform.GetChild(0).gameObject);
}
}
}
| using UnityEngine;
using System.Collections;
public class WallGenerator : MonoBehaviour {
public int nx = 10;
public int ny = 10;
public float Gap = 0.1f;
public MeshRenderer brickPrefab;
// Use this for initialization
void Start () {
if (transform.childCount == 0) {
// create when starting, if no bricks have been added yet
Generate ();
}
}
public void Generate() {
if (brickPrefab == null) {
Debug.LogError ("Missing Brick Prefab. Make sure to prepare and assign a prefab for the bricks!");
return;
}
// delete existing bricks first
Clear ();
// get brick size
var bounds = brickPrefab.bounds;
var brickW = bounds.extents.x * 2;
var brickH = bounds.extents.y * 2;
// build a bunch of bricks!
for (var j = 0; j < ny; ++j) {
for (var i = 0; i < nx; ++i) {
// create brick
var brick = Instantiate (brickPrefab, transform);
// set position
var x = i * (brickW + Gap) + Gap;
var y = j * (brickH + Gap) + Gap;
var pos = new Vector3 (x, y, 0);
brick.transform.localPosition = pos;
}
}
}
/// <summary>
/// Delete all children (bricks).
/// 把所有的小孩都 「清掉」.
/// </summary>
public void Clear() {
for (var i = transform.childCount-1; i >= 0; --i){
DestroyImmediate(transform.GetChild(0).gameObject);
}
}
} | mit | C# |
03f9bcec0aaa40272226c03491755b0eb40b4566 | Update undocumented org.freedesktop.DBus members | tmds/Tmds.DBus | DBus.cs | DBus.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NDesk.DBus;
//namespace org.freedesktop.DBus
namespace org.freedesktop.DBus
{
/*
//what's this for?
public class DBusException : ApplicationException
{
}
*/
#if UNDOCUMENTED_IN_SPEC
//TODO: maybe this should be mapped to its CLR counterpart directly?
//not yet used
[Interface ("org.freedesktop.DBus.Error.InvalidArgs")]
public class InvalidArgsException : ApplicationException
{
}
#endif
[Flags]
public enum NameFlag : uint
{
None = 0,
AllowReplacement = 0x1,
ReplaceExisting = 0x2,
DoNotQueue = 0x4,
}
public enum NameReply : uint
{
PrimaryOwner = 1,
InQueue,
Exists,
AlreadyOwner,
}
public enum ReleaseNameReply : uint
{
Released = 1,
NonExistent,
NotOwner,
}
public enum StartReply : uint
{
//The service was successfully started.
Success = 1,
//A connection already owns the given name.
AlreadyRunning,
}
public delegate void NameOwnerChangedHandler (string name, string old_owner, string new_owner);
public delegate void NameAcquiredHandler (string name);
public delegate void NameLostHandler (string name);
[Interface ("org.freedesktop.DBus.Peer")]
public interface Peer
{
void Ping ();
[return: Argument ("machine_uuid")]
string GetMachineId ();
}
[Interface ("org.freedesktop.DBus.Introspectable")]
public interface Introspectable
{
[return: Argument ("data")]
string Introspect ();
}
[Interface ("org.freedesktop.DBus.Properties")]
public interface Properties
{
//TODO: some kind of indexer mapping?
//object this [string propname] {get; set;}
[return: Argument ("value")]
object Get (string @interface, string propname);
//void Get (string @interface, string propname, out object value);
void Set (string @interface, string propname, object value);
}
[Interface ("org.freedesktop.DBus")]
public interface IBus : Introspectable
{
NameReply RequestName (string name, NameFlag flags);
ReleaseNameReply ReleaseName (string name);
string Hello ();
string[] ListNames ();
string[] ListActivatableNames ();
bool NameHasOwner (string name);
event NameOwnerChangedHandler NameOwnerChanged;
event NameLostHandler NameLost;
event NameAcquiredHandler NameAcquired;
StartReply StartServiceByName (string name, uint flags);
string GetNameOwner (string name);
uint GetConnectionUnixUser (string connection_name);
void AddMatch (string rule);
void RemoveMatch (string rule);
#if UNDOCUMENTED_IN_SPEC
//undocumented in spec
string[] ListQueuedOwners (string name);
uint GetConnectionUnixProcessID (string connection_name);
byte[] GetConnectionSELinuxSecurityContext (string connection_name);
void ReloadConfig ();
#endif
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NDesk.DBus;
//namespace org.freedesktop.DBus
namespace org.freedesktop.DBus
{
/*
//what's this for?
public class DBusException : ApplicationException
{
}
*/
#if UNDOCUMENTED_IN_SPEC
//TODO: maybe this should be mapped to its CLR counterpart directly?
//not yet used
[Interface ("org.freedesktop.DBus.Error.InvalidArgs")]
public class InvalidArgsException : ApplicationException
{
}
#endif
[Flags]
public enum NameFlag : uint
{
None = 0,
AllowReplacement = 0x1,
ReplaceExisting = 0x2,
DoNotQueue = 0x4,
}
public enum NameReply : uint
{
PrimaryOwner = 1,
InQueue,
Exists,
AlreadyOwner,
}
public enum ReleaseNameReply : uint
{
Released = 1,
NonExistent,
NotOwner,
}
public enum StartReply : uint
{
//The service was successfully started.
Success = 1,
//A connection already owns the given name.
AlreadyRunning,
}
public delegate void NameOwnerChangedHandler (string name, string old_owner, string new_owner);
public delegate void NameAcquiredHandler (string name);
public delegate void NameLostHandler (string name);
[Interface ("org.freedesktop.DBus.Peer")]
public interface Peer
{
void Ping ();
[return: Argument ("machine_uuid")]
string GetMachineId ();
}
[Interface ("org.freedesktop.DBus.Introspectable")]
public interface Introspectable
{
[return: Argument ("data")]
string Introspect ();
}
[Interface ("org.freedesktop.DBus.Properties")]
public interface Properties
{
//TODO: some kind of indexer mapping?
//object this [string propname] {get; set;}
[return: Argument ("value")]
object Get (string @interface, string propname);
//void Get (string @interface, string propname, out object value);
void Set (string @interface, string propname, object value);
}
[Interface ("org.freedesktop.DBus")]
public interface IBus : Introspectable
{
NameReply RequestName (string name, NameFlag flags);
ReleaseNameReply ReleaseName (string name);
string Hello ();
string[] ListNames ();
string[] ListActivatableNames ();
bool NameHasOwner (string name);
event NameOwnerChangedHandler NameOwnerChanged;
event NameLostHandler NameLost;
event NameAcquiredHandler NameAcquired;
StartReply StartServiceByName (string name, uint flags);
string GetNameOwner (string name);
uint GetConnectionUnixUser (string connection_name);
void AddMatch (string rule);
void RemoveMatch (string rule);
#if UNDOCUMENTED_IN_SPEC
//undocumented in spec
//there are more of these
void ReloadConfig ();
#endif
}
}
| mit | C# |
6101f8f084fc5ccb1e0e50652efd6b8ad0f58f11 | Add License | chraft/c-raft | Chraft/World/NBT/TagNodeType.cs | Chraft/World/NBT/TagNodeType.cs | /* Minecraft NBT reader
*
* Copyright 2010-2011 Michael Ong, all rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System;
namespace Chraft.World.NBT
{
/// <summary>
/// Provides the basic TAG_TYPE for a node.
/// </summary>
public enum TagNodeType : int
{
/// <summary>
/// Empty tag
/// </summary>
TAG_END,
/// <summary>
/// Byte tag
/// </summary>
TAG_BYTE,
/// <summary>
/// Short integer tag
/// </summary>
TAG_SHORT,
/// <summary>
/// Normal integer tag
/// </summary>
TAG_INT,
/// <summary>
/// Large integer tag
/// </summary>
TAG_LONG,
/// <summary>
/// Single precision floating-point tag
/// </summary>
TAG_SINGLE,
/// <summary>
/// Double precision floating-point tag
/// </summary>
TAG_DOUBLE,
/// <summary>
/// Byte array tag
/// </summary>
TAG_BYTEA,
/// <summary>
/// String tag
/// </summary>
TAG_STRING,
/// <summary>
/// Unnamed, custom type array tag
/// </summary>
TAG_LIST,
/// <summary>
/// Named, custom type array tag
/// </summary>
TAG_COMPOUND,
}
}
| using System;
namespace Chraft.World.NBT
{
/// <summary>
/// Provides the basic TAG_TYPE for a node.
/// </summary>
public enum TagNodeType : int
{
/// <summary>
/// Empty tag
/// </summary>
TAG_END,
/// <summary>
/// Byte tag
/// </summary>
TAG_BYTE,
/// <summary>
/// Short integer tag
/// </summary>
TAG_SHORT,
/// <summary>
/// Normal integer tag
/// </summary>
TAG_INT,
/// <summary>
/// Large integer tag
/// </summary>
TAG_LONG,
/// <summary>
/// Single precision floating-point tag
/// </summary>
TAG_SINGLE,
/// <summary>
/// Double precision floating-point tag
/// </summary>
TAG_DOUBLE,
/// <summary>
/// Byte array tag
/// </summary>
TAG_BYTEA,
/// <summary>
/// String tag
/// </summary>
TAG_STRING,
/// <summary>
/// Unnamed, custom type array tag
/// </summary>
TAG_LIST,
/// <summary>
/// Named, custom type array tag
/// </summary>
TAG_COMPOUND,
}
}
| agpl-3.0 | C# |
2572fdd2a1ccd9c31b0b46a666680b24907a38c1 | Improve test coverage slightly | EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework | osu.Framework.Tests/Visual/Audio/TestSceneLoopingSample.cs | osu.Framework.Tests/Visual/Audio/TestSceneLoopingSample.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
namespace osu.Framework.Tests.Visual.Audio
{
public class TestSceneLoopingSample : FrameworkTestScene
{
private SampleChannel sampleChannel;
private ISampleStore samples;
[BackgroundDependencyLoader]
private void load(ISampleStore samples)
{
this.samples = samples;
}
[Test]
public void TestLoopingToggle()
{
AddStep("create sample", createSample);
AddAssert("not looping", () => !sampleChannel.Looping);
AddStep("enable looping", () => sampleChannel.Looping = true);
AddStep("play sample", () => sampleChannel.Play());
AddAssert("is playing", () => sampleChannel.Playing);
AddWaitStep("wait", 1);
AddAssert("is still playing", () => sampleChannel.Playing);
AddStep("disable looping", () => sampleChannel.Looping = false);
AddAssert("not playing", () => !sampleChannel.Playing);
}
[Test]
public void TestStopWhileLooping()
{
AddStep("create sample", createSample);
AddStep("enable looping", () => sampleChannel.Looping = true);
AddStep("play sample", () => sampleChannel.Play());
AddWaitStep("wait", 1);
AddAssert("is playing", () => sampleChannel.Playing);
AddStep("stop playing", () => sampleChannel.Stop());
AddAssert("not playing", () => !sampleChannel.Playing);
}
private void createSample()
{
sampleChannel?.Dispose();
sampleChannel = samples.Get("tone.wav");
// reduce volume of the tone due to how loud it normally is.
if (sampleChannel != null)
sampleChannel.Volume.Value = 0.05;
}
protected override void Dispose(bool isDisposing)
{
sampleChannel?.Dispose();
base.Dispose(isDisposing);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
namespace osu.Framework.Tests.Visual.Audio
{
public class TestSceneLoopingSample : FrameworkTestScene
{
private SampleChannel sampleChannel;
[BackgroundDependencyLoader]
private void load(ISampleStore samples)
{
sampleChannel = samples.Get("tone.wav");
// reduce volume of the tone due to how loud it normally is.
if (sampleChannel != null)
sampleChannel.Volume.Value = 0.05;
}
[Test]
public void TestLooping()
{
AddAssert("not looping", () => !sampleChannel.Looping);
AddStep("enable looping", () => sampleChannel.Looping = true);
AddStep("play sample", () => sampleChannel.Play());
AddAssert("is playing", () => sampleChannel.Playing);
AddWaitStep("wait", 1);
AddAssert("is still playing", () => sampleChannel.Playing);
AddStep("stop sample", () => sampleChannel.Stop());
AddAssert("not playing", () => !sampleChannel.Playing);
}
}
}
| mit | C# |
5f671bdf47252422a4103df97ad228ee6b1dc13a | add message | toannvqo/dnn_publish | Components/ProductController.cs | Components/ProductController.cs | using DotNetNuke.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Christoc.Modules.DNNModule1.Components
{
public class ProductController
{
public Product GetProduct(int productId)
{
Product p;
using (IDataContext ctx = DataContext.Instance())
{
Console.WriteLine("hello");
var rep = ctx.GetRepository<Product>();
p = rep.GetById(productId);
}
return p;
}
public IEnumerable<Product> getAll()
{
IEnumerable<Product> p;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
p = rep.Get();
}
return p;
}
public void CreateProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Insert(p);
}
}
public void DeleteProduct(int productId)
{
var p = GetProduct(productId);
DeleteProduct(p);
}
public void DeleteProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Delete(p);
}
}
public void UpdateProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Update(p);
}
}
}
} | using DotNetNuke.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Christoc.Modules.DNNModule1.Components
{
public class ProductController
{
public Product GetProduct(int productId)
{
Product p;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
p = rep.GetById(productId);
}
return p;
}
public IEnumerable<Product> getAll()
{
IEnumerable<Product> p;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
p = rep.Get();
}
return p;
}
public void CreateProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Insert(p);
}
}
public void DeleteProduct(int productId)
{
var p = GetProduct(productId);
DeleteProduct(p);
}
public void DeleteProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Delete(p);
}
}
public void UpdateProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Update(p);
}
}
}
} | mit | C# |
d728b324fc6d76058cb4aab2e4dc9ef3240131f0 | bump version | MetacoSA/NBitcoin.Indexer,NicolasDorier/NBitcoin.Indexer | NBitcoin.Indexer/Properties/AssemblyInfo.cs | NBitcoin.Indexer/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NBitcoin.Indexer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nicolas Dorier")]
[assembly: AssemblyProduct("NBitcoin.Indexer")]
[assembly: AssemblyCopyright("Copyright © AO-IS 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:InternalsVisibleTo("NBitcoin.Indexer.Tests")]
// 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("c2103e2f-76fe-4cd4-a129-edd06fa97913")]
// 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: AssemblyInformationalVersion("2.0.7.12")]
[assembly: AssemblyVersion("2.0.7.12")]
[assembly: AssemblyFileVersion("2.0.7.12")]
| 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("NBitcoin.Indexer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nicolas Dorier")]
[assembly: AssemblyProduct("NBitcoin.Indexer")]
[assembly: AssemblyCopyright("Copyright © AO-IS 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:InternalsVisibleTo("NBitcoin.Indexer.Tests")]
// 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("c2103e2f-76fe-4cd4-a129-edd06fa97913")]
// 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: AssemblyInformationalVersion("2.0.7.11")]
[assembly: AssemblyVersion("2.0.7.11")]
[assembly: AssemblyFileVersion("2.0.7.11")]
| mit | C# |
ddb57049eac6fe0a485b2f9a4d1d1ad55aa13e4c | Revert "不要な変数削除" | templa00/ScrollViewSample | Assets/Script/ScrollViewCtrl.cs | Assets/Script/ScrollViewCtrl.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// スクロールビューコントロール
/// </summary>
public class ScrollViewCtrl : MonoBehaviour
{
/// <summary>
/// コンテンツの短径の情報
/// </summary>
[SerializeField]
private RectTransform contentRect = null;
/// <summary>
/// ステージリスト
/// </summary>
[SerializeField]
private GameObject stageListObj = null;
/// <summary>
/// ボタンオブジェクト
/// </summary>
[SerializeField]
private GameObject baseBtnObj = null;
/// <summary>
/// 開始
/// </summary>
void Start ()
{
// ボタン生成
CreateButton(100);
}
/// <summary>
/// ボタン生成
/// </summary>
/// <param name="_num">個数</param>
private void CreateButton (int _num)
{
// ゲームオブジェクトとしてプレファブ(object)を読み込みます。
var obj = Instantiate(Resources.Load("Prefabs/Button")) as GameObject;
for (int i = 0; i < _num; i++)
{
// objをGameObjectとしてcopy_objに複製する。
var copy_obj = UnityEngine.Object.Instantiate(obj) as GameObject;
copy_obj.transform.parent = stageListObj.transform;
copy_obj.GetComponent<ButtonCtrl>().text.text = string.Format("ステージ {0}", i + 1);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// スクロールビューコントロール
/// </summary>
public class ScrollViewCtrl : MonoBehaviour
{
/// <summary>
/// ステージリスト
/// </summary>
[SerializeField]
private GameObject stageListObj = null;
/// <summary>
/// 開始
/// </summary>
void Start ()
{
// ボタン生成
CreateButton(100);
}
/// <summary>
/// ボタン生成
/// </summary>
/// <param name="_num">個数</param>
private void CreateButton (int _num)
{
// ゲームオブジェクトとしてプレファブ(object)を読み込みます。
var obj = Instantiate(Resources.Load("Prefabs/Button")) as GameObject;
for (int i = 0; i < _num; i++)
{
// objをGameObjectとしてcopy_objに複製する。
var copy_obj = UnityEngine.Object.Instantiate(obj) as GameObject;
copy_obj.transform.parent = stageListObj.transform;
copy_obj.GetComponent<ButtonCtrl>().text.text = string.Format("ステージ {0}", i + 1);
}
}
}
| mit | C# |
dc4853125724ea276fcc96b46d1b183a8acc83e8 | make parameter name consistent | ArsenShnurkov/BitSharp | BitSharp.Common/WorkerMethod.cs | BitSharp.Common/WorkerMethod.cs | using BitSharp.Common.ExtensionMethods;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BitSharp.Common
{
public class WorkerMethod : Worker
{
private readonly Action workAction;
public WorkerMethod(string name, Action workAction, bool initialNotify, TimeSpan minIdleTime, TimeSpan maxIdleTime)
: base(name, initialNotify, minIdleTime, maxIdleTime)
{
this.workAction = workAction;
}
protected override void WorkAction()
{
this.workAction();
}
}
}
| using BitSharp.Common.ExtensionMethods;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BitSharp.Common
{
public class WorkerMethod : Worker
{
private readonly Action workAction;
public WorkerMethod(string name, Action workAction, bool runOnStart, TimeSpan minIdleTime, TimeSpan maxIdleTime)
: base(name, runOnStart, minIdleTime, maxIdleTime)
{
this.workAction = workAction;
}
protected override void WorkAction()
{
this.workAction();
}
}
}
| unlicense | C# |
5337bdf7841cfe80e88436ec7657d3251e695512 | Remove unused references from example client | inter8ection/Obvs | Examples/Client/Program.cs | Examples/Client/Program.cs | using System;
using Obvs.Types;
using Obvs.ActiveMQ.Configuration;
using Obvs.Configuration;
using Obvs.Example.Messages;
using Obvs.Serialization.Json.Configuration;
namespace Obvs.Example.Client
{
internal static class Program
{
private static void Main(string[] args)
{
var brokerUri = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616";
var serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "Obvs.Service1";
Console.WriteLine($"Starting {serviceName}, connecting to broker {brokerUri}");
var serviceBus = ServiceBus.Configure()
.WithActiveMQEndpoints<IServiceMessage1>()
.Named(serviceName)
.UsingQueueFor<ICommand>()
.ConnectToBroker(brokerUri)
.WithCredentials("admin", "admin")
.SerializedAsJson()
.AsClient()
.CreateClient();
serviceBus.Events.Subscribe(ev => Console.WriteLine("Received event: " + ev));
Console.WriteLine("Type some text and hit <Enter> to send as command.");
while (true)
{
string data = Console.ReadLine();
serviceBus.SendAsync(new Command1 { Data = data });
}
}
}
}
| using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using Obvs.Types;
using Obvs.ActiveMQ.Configuration;
using Obvs.Configuration;
using Obvs.Example.Messages;
using Obvs.Serialization.Json.Configuration;
namespace Obvs.Example.Client
{
internal static class Program
{
private static void Main(string[] args)
{
var brokerUri = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616";
var serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "Obvs.Service1";
Console.WriteLine($"Starting {serviceName}, connecting to broker {brokerUri}");
var serviceBus = ServiceBus.Configure()
.WithActiveMQEndpoints<IServiceMessage1>()
.Named(serviceName)
.UsingQueueFor<ICommand>()
.ConnectToBroker(brokerUri)
.WithCredentials("admin", "admin")
.SerializedAsJson()
.AsClient()
.CreateClient();
serviceBus.Events.Subscribe(ev => Console.WriteLine("Received event: " + ev));
Console.WriteLine("Type some text and hit <Enter> to send as command.");
while (true)
{
string data = Console.ReadLine();
serviceBus.SendAsync(new Command1 { Data = data });
}
}
}
}
| mit | C# |
4882463b7e969af8475eb378a3b6af86144b7b31 | Increase version number | Teleopti/Rhino.ServiceBus.SqlQueues | Rhino.ServiceBus.SqlQueues/Properties/AssemblyInfo.cs | Rhino.ServiceBus.SqlQueues/Properties/AssemblyInfo.cs | 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("Sql Queues for Rhino Service Bus")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Teleopti")]
[assembly: AssemblyProduct("Rhino.ServiceBus.SqlQueues")]
[assembly: AssemblyCopyright("Copyright © Teleopti 2013")]
[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("47fecf89-9079-49b7-9b51-bfc263794bd6")]
// 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.1.4")]
[assembly: AssemblyFileVersion("1.0.1.4")]
[assembly: CLSCompliant(true)]
| 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("Sql Queues for Rhino Service Bus")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Teleopti")]
[assembly: AssemblyProduct("Rhino.ServiceBus.SqlQueues")]
[assembly: AssemblyCopyright("Copyright © Teleopti 2013")]
[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("47fecf89-9079-49b7-9b51-bfc263794bd6")]
// 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.1.3")]
[assembly: AssemblyFileVersion("1.0.1.3")]
[assembly: CLSCompliant(true)]
| mit | C# |
1d096a7fc519f96251bc005e9c2fc64202c524e6 | Fix spelling | AntiTcb/Discord.Net,Confruggy/Discord.Net,RogueException/Discord.Net | src/Discord.Net.Core/Entities/Emotes/Emoji.cs | src/Discord.Net.Core/Entities/Emotes/Emoji.cs | namespace Discord
{
/// <summary>
/// A unicode emoji
/// </summary>
public class Emoji : IEmote
{
// TODO: need to constrain this to unicode-only emojis somehow
/// <summary>
/// Creates a unicode emoji.
/// </summary>
/// <param name="unicode">The pure UTF-8 encoding of an emoji</param>
public Emoji(string unicode)
{
Name = unicode;
}
/// <summary>
/// The unicode representation of this emote.
/// </summary>
public string Name { get; }
}
}
| namespace Discord
{
/// <summary>
/// A unicode emoji
/// </summary>
public class Emoji : IEmote
{
// TODO: need to constrain this to unicode-only emojis somehow
/// <summary>
/// Creates a unciode emoji.
/// </summary>
/// <param name="unicode">The pure UTF-8 encoding of an emoji</param>
public Emoji(string unicode)
{
Name = unicode;
}
/// <summary>
/// The unicode representation of this emote.
/// </summary>
public string Name { get; }
}
}
| mit | C# |
827219643b95de087c18a276e8e941a69de973fc | correct how services are registered in di | AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us | src/Maw.Cache/IServiceCollectionExtensions.cs | src/Maw.Cache/IServiceCollectionExtensions.cs | using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using Maw.Cache.Abstractions;
using Maw.Cache.Blogs;
using Maw.Cache.Photos;
using Maw.Cache.Videos;
namespace Maw.Cache;
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddMawCacheServices(this IServiceCollection services, string redisConnectionString)
{
return services
.AddSingleton<IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(redisConnectionString))
.AddScoped(services => services.GetRequiredService<IConnectionMultiplexer>().GetDatabase())
.AddScoped<IBlogCache, BlogCache>()
.AddScoped<IPhotoCache, PhotoCache>()
.AddScoped<IVideoCache, VideoCache>();
}
}
| using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using Maw.Cache.Abstractions;
using Maw.Cache.Blogs;
using Maw.Cache.Photos;
using Maw.Cache.Videos;
namespace Maw.Cache;
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddMawCacheServices(this IServiceCollection services, string redisConnectionString)
{
return services
.AddSingleton<IConnectionMultiplexer, ConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(redisConnectionString))
.AddScoped(services => services.GetRequiredService<ConnectionMultiplexer>().GetDatabase())
.AddScoped<IBlogCache, BlogCache>()
.AddScoped<IPhotoCache, PhotoCache>()
.AddScoped<IVideoCache, VideoCache>();
}
}
| mit | C# |
31c425806825273ae715cbbd843566b0177eefe0 | Use ViewWillTransitionToSize to disable rotation animations | ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework | osu.Framework.iOS/GameAppDelegate.cs | osu.Framework.iOS/GameAppDelegate.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using UIKit;
using Foundation;
using System.Drawing;
using SixLabors.ImageSharp.PixelFormats;
using CoreGraphics;
namespace osu.Framework.iOS
{
public abstract class GameAppDelegate : UIApplicationDelegate
{
public override UIWindow Window { get; set; }
private iOSGameView gameView;
private iOSGameHost host;
protected abstract Game CreateGame();
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
aotImageSharp();
Window = new UIWindow(UIScreen.MainScreen.Bounds);
gameView = new iOSGameView(new RectangleF(0.0f, 0.0f, (float)Window.Frame.Size.Width, (float)Window.Frame.Size.Height));
GameViewController viewController = new GameViewController
{
View = gameView
};
Window.RootViewController = viewController;
Window.MakeKeyAndVisible();
gameView.Run();
host = new iOSGameHost(gameView);
host.Run(CreateGame());
return true;
}
private void aotImageSharp()
{
System.Runtime.CompilerServices.Unsafe.SizeOf<Rgba32>();
System.Runtime.CompilerServices.Unsafe.SizeOf<long>();
try
{
new SixLabors.ImageSharp.Formats.Png.PngDecoder().Decode<Rgba32>(SixLabors.ImageSharp.Configuration.Default, null);
} catch { }
}
}
internal class GameViewController : UIViewController
{
public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator)
{
coordinator.AnimateAlongsideTransition(_ => { }, _ => UIView.AnimationsEnabled = true);
UIView.AnimationsEnabled = false;
base.ViewWillTransitionToSize(toSize, coordinator);
var gameView = View as iOSGameView;
gameView?.RequestResizeFrameBuffer();
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using UIKit;
using Foundation;
using System.Drawing;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.iOS
{
public abstract class GameAppDelegate : UIApplicationDelegate
{
public override UIWindow Window { get; set; }
private iOSGameView gameView;
private iOSGameHost host;
protected abstract Game CreateGame();
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
aotImageSharp();
Window = new UIWindow(UIScreen.MainScreen.Bounds);
gameView = new iOSGameView(new RectangleF(0.0f, 0.0f, (float)Window.Frame.Size.Width, (float)Window.Frame.Size.Height));
GameViewController viewController = new GameViewController
{
View = gameView
};
Window.RootViewController = viewController;
Window.MakeKeyAndVisible();
gameView.Run();
host = new iOSGameHost(gameView);
host.Run(CreateGame());
return true;
}
private void aotImageSharp()
{
System.Runtime.CompilerServices.Unsafe.SizeOf<Rgba32>();
System.Runtime.CompilerServices.Unsafe.SizeOf<long>();
try
{
new SixLabors.ImageSharp.Formats.Png.PngDecoder().Decode<Rgba32>(SixLabors.ImageSharp.Configuration.Default, null);
} catch { }
}
}
internal class GameViewController : UIViewController
{
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
var gameView = View as iOSGameView;
gameView?.RequestResizeFrameBuffer();
}
}
}
| mit | C# |
46e08c4fd57cbbdc24384c6953271546025d0830 | use NRT | sharwell/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,weltkante/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,mavasani/roslyn,physhi/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,AmadeusW/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,bartdesmet/roslyn,dotnet/roslyn,mavasani/roslyn,diryboy/roslyn,physhi/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,dotnet/roslyn,diryboy/roslyn,weltkante/roslyn,wvdd007/roslyn,dotnet/roslyn,AmadeusW/roslyn,weltkante/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,AmadeusW/roslyn,eriawan/roslyn,KevinRansom/roslyn | src/Features/Core/Portable/ConvertTupleToStruct/IRemoteConvertTupleToStructCodeRefactoringService.cs | src/Features/Core/Portable/ConvertTupleToStruct/IRemoteConvertTupleToStructCodeRefactoringService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ConvertTupleToStruct
{
internal interface IRemoteConvertTupleToStructCodeRefactoringService
{
ValueTask<SerializableConvertTupleToStructResult> ConvertToStructAsync(
PinnedSolutionInfo solutionInfo,
DocumentId documentId,
TextSpan span,
Scope scope,
bool isRecord,
CancellationToken cancellationToken);
}
[DataContract]
internal readonly struct SerializableConvertTupleToStructResult
{
[DataMember(Order = 0)]
public readonly ImmutableArray<(DocumentId, ImmutableArray<TextChange>)> DocumentTextChanges;
[DataMember(Order = 1)]
public readonly (DocumentId, TextSpan) RenamedToken;
public SerializableConvertTupleToStructResult(
ImmutableArray<(DocumentId, ImmutableArray<TextChange>)> documentTextChanges,
(DocumentId, TextSpan) renamedToken)
{
DocumentTextChanges = documentTextChanges;
RenamedToken = renamedToken;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ConvertTupleToStruct
{
internal interface IRemoteConvertTupleToStructCodeRefactoringService
{
ValueTask<SerializableConvertTupleToStructResult> ConvertToStructAsync(
PinnedSolutionInfo solutionInfo,
DocumentId documentId,
TextSpan span,
Scope scope,
bool isRecord,
CancellationToken cancellationToken);
}
[DataContract]
internal readonly struct SerializableConvertTupleToStructResult
{
[DataMember(Order = 0)]
public readonly ImmutableArray<(DocumentId, ImmutableArray<TextChange>)> DocumentTextChanges;
[DataMember(Order = 1)]
public readonly (DocumentId, TextSpan) RenamedToken;
public SerializableConvertTupleToStructResult(
ImmutableArray<(DocumentId, ImmutableArray<TextChange>)> documentTextChanges,
(DocumentId, TextSpan) renamedToken)
{
DocumentTextChanges = documentTextChanges;
RenamedToken = renamedToken;
}
}
}
| mit | C# |
4dc961f44c6c7ea0d483b8711bdde4f3c87f669b | Update web page. | SpilledMilkCOM/DenDevDayEFCore,SpilledMilkCOM/DenDevDayEFCore | src/SM.DataModels.StuffDataModel.Web/Startup.cs | src/SM.DataModels.StuffDataModel.Web/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace SM.DataModels.StuffDataModel.Web
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddStuff();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Nothing interesting to see here...");
});
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace SM.DataModels.StuffDataModel.Web
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddStuff();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
| mit | C# |
7ca9f4776eaed9f7373a20a29881477e9e623718 | Update IsFalseStateTrigger.cs | onovotny/WindowsStateTriggers,ButchersBoy/WindowsStateTriggers,AlexBream/WindowsStateTriggers,karl-barkmann/WindowsStateTriggers,dinhchitrung/WindowsStateTriggers,ScottIsAFool/WindowsStateTriggers,dotMorten/WindowsStateTriggers,Viachaslau-Zinkevich/WindowsStateTriggers,robertos/WindowsStateTriggers | src/WindowsStateTriggers/IsFalseStateTrigger.cs | src/WindowsStateTriggers/IsFalseStateTrigger.cs | // Copyright (c) Morten Nielsen. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Windows.Foundation.Metadata;
using Windows.UI.Xaml;
namespace WindowsStateTriggers
{
/// <summary>
/// Enables a state if the value is false
/// </summary>
public class IsFalseStateTrigger : StateTriggerBase
{
public bool Value
{
get { return (bool)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(bool), typeof(IsFalseStateTrigger),
new PropertyMetadata(true, OnValuePropertyChanged));
private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var obj = (IsFalseStateTrigger)d;
var val = (bool)e.NewValue;
obj.SetTriggerValue(!val);
}
}
}
| using Windows.Foundation.Metadata;
using Windows.UI.Xaml;
namespace WindowsStateTriggers
{
/// <summary>
/// Enables a state if the value is false
/// </summary>
public class IsFalseStateTrigger : StateTriggerBase
{
public bool Value
{
get { return (bool)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(bool), typeof(IsFalseStateTrigger),
new PropertyMetadata(true, OnValuePropertyChanged));
private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var obj = (IsFalseStateTrigger)d;
var val = (bool)e.NewValue;
obj.SetTriggerValue(!val);
}
}
}
| mit | C# |
bfa5d41d89a64ec1a559cc4d5cc5975563d95335 | Fix one more case | ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu | osu.Game.Rulesets.Taiko/Skinning/Default/DefaultHitExplosion.cs | osu.Game.Rulesets.Taiko/Skinning/Default/DefaultHitExplosion.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.UI;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Taiko.Skinning.Default
{
internal class DefaultHitExplosion : CircularContainer, IAnimatableHitExplosion
{
private readonly HitResult result;
private Box? body;
[Resolved]
private OsuColour colours { get; set; } = null!;
public DefaultHitExplosion(HitResult result)
{
this.result = result;
}
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.Both;
BorderColour = Color4.White;
BorderThickness = 1;
Blending = BlendingParameters.Additive;
Alpha = 0.15f;
Masking = true;
if (!result.IsHit())
return;
InternalChildren = new[]
{
body = new Box
{
RelativeSizeAxes = Axes.Both,
}
};
updateColour();
}
private void updateColour(DrawableHitObject? judgedObject = null)
{
if (body == null)
return;
bool isRim = (judgedObject?.HitObject as Hit)?.Type == HitType.Rim;
body.Colour = isRim ? colours.BlueDarker : colours.PinkDarker;
}
public void Animate(DrawableHitObject drawableHitObject)
{
updateColour(drawableHitObject);
this.ScaleTo(3f, 1000, Easing.OutQuint);
this.FadeOut(500);
}
public void AnimateSecondHit()
{
}
}
}
| #nullable enable
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.UI;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Taiko.Skinning.Default
{
internal class DefaultHitExplosion : CircularContainer, IAnimatableHitExplosion
{
private readonly HitResult result;
private Box? body;
[Resolved]
private OsuColour colours { get; set; } = null!;
public DefaultHitExplosion(HitResult result)
{
this.result = result;
}
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.Both;
BorderColour = Color4.White;
BorderThickness = 1;
Blending = BlendingParameters.Additive;
Alpha = 0.15f;
Masking = true;
if (!result.IsHit())
return;
InternalChildren = new[]
{
body = new Box
{
RelativeSizeAxes = Axes.Both,
}
};
updateColour();
}
private void updateColour(DrawableHitObject? judgedObject = null)
{
if (body == null)
return;
bool isRim = (judgedObject?.HitObject as Hit)?.Type == HitType.Rim;
body.Colour = isRim ? colours.BlueDarker : colours.PinkDarker;
}
public void Animate(DrawableHitObject drawableHitObject)
{
updateColour(drawableHitObject);
this.ScaleTo(3f, 1000, Easing.OutQuint);
this.FadeOut(500);
}
public void AnimateSecondHit()
{
}
}
}
| mit | C# |
5cfb2c2ffe3e3bb111b11d344955710a1b13cb66 | Make VolumeControlReceptor handle global input | smoogipoo/osu,naoey/osu,2yangk23/osu,peppy/osu,naoey/osu,smoogipooo/osu,DrabWeb/osu,UselessToucan/osu,Frontear/osuKyzer,smoogipoo/osu,johnneijzen/osu,ppy/osu,ppy/osu,DrabWeb/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,2yangk23/osu,Nabile-Rahmani/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,ZLima12/osu,ppy/osu,ZLima12/osu,DrabWeb/osu,johnneijzen/osu,EVAST9919/osu,peppy/osu,naoey/osu,NeoAdonis/osu,peppy/osu | osu.Game/Graphics/UserInterface/Volume/VolumeControlReceptor.cs | osu.Game/Graphics/UserInterface/Volume/VolumeControlReceptor.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Game.Input.Bindings;
namespace osu.Game.Graphics.UserInterface.Volume
{
public class VolumeControlReceptor : Container, IKeyBindingHandler<GlobalAction>, IHandleGlobalInput
{
public Func<GlobalAction, bool> ActionRequested;
public bool OnPressed(GlobalAction action) => ActionRequested?.Invoke(action) ?? false;
public bool OnReleased(GlobalAction action) => false;
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Bindings;
using osu.Game.Input.Bindings;
namespace osu.Game.Graphics.UserInterface.Volume
{
public class VolumeControlReceptor : Container, IKeyBindingHandler<GlobalAction>
{
public Func<GlobalAction, bool> ActionRequested;
public bool OnPressed(GlobalAction action) => ActionRequested?.Invoke(action) ?? false;
public bool OnReleased(GlobalAction action) => false;
}
}
| mit | C# |
234c1f44059d6e548da99d5302ee6296dd03e930 | 添加NET451判断 | Kation/ComBoost,Kation/ComBoost,Kation/ComBoost,Kation/ComBoost | src/Wodsoft.ComBoost/DomainServiceAccessor.cs | src/Wodsoft.ComBoost/DomainServiceAccessor.cs | using System;
using System.Collections.Generic;
using System.Linq;
#if NET451
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
#endif
using System.Threading.Tasks;
namespace Wodsoft.ComBoost
{
public class DomainServiceAccessor : IDomainServiceAccessor
{
#if NET451
private static readonly string LogicalDataKey = "__DomainService_Current__" + AppDomain.CurrentDomain.Id;
public IDomainService DomainService
{
get
{
var handle = CallContext.LogicalGetData(LogicalDataKey) as ObjectHandle;
return handle?.Unwrap() as IDomainService;
}
set
{
CallContext.LogicalSetData(LogicalDataKey, new ObjectHandle(value));
}
}
#else
System.Threading.AsyncLocal<IDomainService> _Context = new System.Threading.AsyncLocal<IDomainService>();
public IDomainService DomainService
{
get { return _Context.Value; }
set { _Context.Value = value; }
}
#endif
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Threading.Tasks;
namespace Wodsoft.ComBoost
{
public class DomainServiceAccessor : IDomainServiceAccessor
{
#if NET451
private static readonly string LogicalDataKey = "__DomainService_Current__" + AppDomain.CurrentDomain.Id;
public IDomainService DomainService
{
get
{
var handle = CallContext.LogicalGetData(LogicalDataKey) as ObjectHandle;
return handle?.Unwrap() as IDomainService;
}
set
{
CallContext.LogicalSetData(LogicalDataKey, new ObjectHandle(value));
}
}
#else
System.Threading.AsyncLocal<IDomainService> _Context = new System.Threading.AsyncLocal<IDomainService>();
public IDomainService DomainService
{
get { return _Context.Value; }
set { _Context.Value = value; }
}
#endif
}
}
| mit | C# |
45c45af3e3941dd693f8cc0f5138333b937373a2 | Remove RuleTraitor unused imports (#2664) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/GameTicking/GameRules/RuleTraitor.cs | Content.Server/GameTicking/GameRules/RuleTraitor.cs | using Content.Server.Interfaces.Chat;
using Content.Server.Mobs.Roles.Traitor;
using Content.Server.Players;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Server.Interfaces.Player;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
namespace Content.Server.GameTicking.GameRules
{
public class RuleTraitor : GameRule
{
[Dependency] private readonly IChatManager _chatManager = default!;
public override void Added()
{
_chatManager.DispatchServerAnnouncement(Loc.GetString("Hello crew! Have a good shift!"));
bool Predicate(IPlayerSession session) => session.ContentData()?.Mind?.HasRole<TraitorRole>() ?? false;
EntitySystem.Get<AudioSystem>().PlayGlobal("/Audio/Misc/tatoralert.ogg", AudioParams.Default, Predicate);
}
}
}
| using System;
using System.Threading;
using Content.Server.Interfaces.Chat;
using Content.Server.Interfaces.GameTicking;
using Content.Server.Mobs.Roles.Traitor;
using Content.Server.Players;
using Content.Shared;
using Content.Shared.GameObjects.Components.Damage;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Server.Interfaces.Player;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.Configuration;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Timer = Robust.Shared.Timers.Timer;
namespace Content.Server.GameTicking.GameRules
{
public class RuleTraitor : GameRule
{
[Dependency] private readonly IChatManager _chatManager = default!;
public override void Added()
{
_chatManager.DispatchServerAnnouncement(Loc.GetString("Hello crew! Have a good shift!"));
bool Predicate(IPlayerSession session) => session.ContentData()?.Mind?.HasRole<TraitorRole>() ?? false;
EntitySystem.Get<AudioSystem>().PlayGlobal("/Audio/Misc/tatoralert.ogg", AudioParams.Default, Predicate);
}
}
}
| mit | C# |
0fee76c95c3bf1d7078d865b8bd22412f8ef21f1 | Fix merge error | johnneijzen/osu,ppy/osu,peppy/osu,naoey/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,DrabWeb/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,naoey/osu,DrabWeb/osu,johnneijzen/osu,UselessToucan/osu,naoey/osu,2yangk23/osu,peppy/osu-new,peppy/osu,EVAST9919/osu,DrabWeb/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,ZLima12/osu,peppy/osu,ppy/osu,NeoAdonis/osu,EVAST9919/osu | osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.cs | osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Rulesets.Osu.Difficulty.Preprocessing;
using osuTK;
namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
/// <summary>
/// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit.
/// </summary>
public class Speed : Skill
{
private const double min_angle_bonus = 1.0;
private const double max_angle_bonus = 1.25;
private const double angle_bonus_begin = 3 * Math.PI / 4;
private const double pi_over_4 = Math.PI / 4;
protected override double SkillMultiplier => 1400;
protected override double StrainDecayBase => 0.3;
private const double min_speed_bonus = 75; // ~200BPM
private const double max_speed_bonus = 45; // ~330BPM
private const double speed_balancing_factor = 40;
protected override double StrainValueOf(OsuDifficultyHitObject current)
{
double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance);
double deltaTime = Math.Max(max_speed_bonus, current.DeltaTime);
double speedBonus = 1.0;
if (deltaTime < min_speed_bonus)
speedBonus = 1 + Math.Pow((min_speed_bonus - deltaTime) / speed_balancing_factor, 2);
double angleBonus = 1.0;
if (current.Angle != null)
angleBonus = MathHelper.Clamp((angle_bonus_begin - current.Angle.Value) / pi_over_4 * 0.5 + 1.0, min_angle_bonus, max_angle_bonus);
return speedBonus * angleBonus * (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime;
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Rulesets.Osu.Difficulty.Preprocessing;
using osuTK;
namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
/// <summary>
/// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit.
/// </summary>
public class Speed : Skill
{
private const double min_angle_bonus = 1.0;
private const double max_angle_bonus = 1.25;
private const double angle_bonus_begin = 3 * Math.PI / 4;
private const double pi_over_4 = Math.PI / 4;
protected override double SkillMultiplier => 1400;
protected override double StrainDecayBase => 0.3;
private const double min_speed_bonus = 75; // ~200BPM
private const double max_speed_bonus = 45; // ~330BPM
private const double speed_balancing_factor = 40;
protected override double StrainValueOf(OsuDifficultyHitObject current)
{
double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance);
double deltaTime = Math.Max(max_speed_bonus, current.DeltaTime);
double speedBonus = 1.0;
if (deltaTime < min_speed_bonus)
speedBonus = 1 + Math.Pow((min_speed_bonus - deltaTime) / speed_balancing_factor, 2);
double angleBonus = 1.0;
if (current.Angle != null)
angleBonus = MathHelper.Clamp((angle_bonus_begin - current.Angle.Value) / pi_over_4 * 0.5 + 1.0, min_angle_bonus, max_angle_bonus);
return angleBonus * (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime;
}
}
}
| mit | C# |
171cb6438920f1bb9d41cee5c615241f3ab3a611 | Fix obfuscation attributes when merging assemblies | sharpdx/Toolkit,tomba/Toolkit,sharpdx/Toolkit | Source/SharedAssemblyInfo.cs | Source/SharedAssemblyInfo.cs | // Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly:AssemblyCompany("Alexandre Mutel")]
[assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:AssemblyVersion("2.5.1")]
[assembly:AssemblyFileVersion("2.5.1")]
[assembly: NeutralResourcesLanguage("en-us")]
#if DEBUG
[assembly:AssemblyConfiguration("Debug")]
#else
[assembly:AssemblyConfiguration("Release")]
#endif
[assembly:ComVisible(false)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when public and interface: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when struct: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.*: INotifyPropertyChanged heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: forced rename", Exclude = false)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: enum values pruning", Exclude = false)]
[assembly: Obfuscation(Feature = "legacy xml serialization heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "ignore InternalsVisibleToAttribute", Exclude = false)]
| // Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly:AssemblyCompany("Alexandre Mutel")]
[assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:AssemblyVersion("2.5.1")]
[assembly:AssemblyFileVersion("2.5.1")]
[assembly: NeutralResourcesLanguage("en-us")]
#if DEBUG
[assembly:AssemblyConfiguration("Debug")]
#else
[assembly:AssemblyConfiguration("Release")]
#endif
[assembly:ComVisible(false)]
| mit | C# |
bd174481a7ce4112b65f87b0d5f1c875f6582f66 | Set NUnit tests to run scripts under the current domain for access to the same console. | michaltakac/IronAHK,michaltakac/IronAHK,yatsek/IronAHK,yatsek/IronAHK,michaltakac/IronAHK,polyethene/IronAHK,michaltakac/IronAHK,polyethene/IronAHK,polyethene/IronAHK,yatsek/IronAHK,yatsek/IronAHK,michaltakac/IronAHK,polyethene/IronAHK,yatsek/IronAHK | Tests/Scripting/Scripting.cs | Tests/Scripting/Scripting.cs | using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using IronAHK.Scripting;
using NUnit.Framework;
namespace Tests
{
[TestFixture]
public partial class Scripting
{
[Test]
public void RunScripts()
{
string path = string.Format("..{0}..{0}Scripting{0}Code", Path.DirectorySeparatorChar.ToString());
foreach (string file in Directory.GetFiles(path, "*.ia"))
{
string name = Path.GetFileNameWithoutExtension(file);
var provider = new IACodeProvider();
var options = new CompilerParameters();
options.GenerateExecutable = true;
options.GenerateInMemory = false;
options.ReferencedAssemblies.Add(typeof(IronAHK.Rusty.Core).Namespace + ".dll");
options.OutputAssembly = Path.GetTempFileName() + ".exe";
provider.CompileAssemblyFromFile(options, file);
bool exists = File.Exists(options.OutputAssembly);
Assert.IsTrue(exists, name + " assembly");
if (exists)
{
var buffer = new StringBuilder();
var writer = new StringWriter(buffer);
Console.SetOut(writer);
AppDomain.CurrentDomain.ExecuteAssembly(options.OutputAssembly);
try { File.Delete(options.OutputAssembly); }
catch (UnauthorizedAccessException) { }
writer.Flush();
string output = buffer.ToString();
Assert.AreEqual("pass", output, name);
var stdout = new StreamWriter(Console.OpenStandardOutput());
stdout.AutoFlush = true;
Console.SetOut(stdout);
}
}
}
}
}
| using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using IronAHK.Scripting;
using NUnit.Framework;
namespace Tests
{
[TestFixture]
public partial class Scripting
{
[Test]
public void RunScripts()
{
string path = string.Format("..{0}..{0}Scripting{0}Code", Path.DirectorySeparatorChar.ToString());
foreach (string file in Directory.GetFiles(path, "*.ia"))
{
string name = Path.GetFileNameWithoutExtension(file);
var provider = new IACodeProvider();
var options = new CompilerParameters();
options.GenerateExecutable = true;
options.GenerateInMemory = false;
options.ReferencedAssemblies.Add(typeof(IronAHK.Rusty.Core).Namespace + ".dll");
options.OutputAssembly = Path.GetTempFileName() + ".exe";
provider.CompileAssemblyFromFile(options, file);
bool exists = File.Exists(options.OutputAssembly);
Assert.IsTrue(exists, name + " assembly");
if (exists)
{
AppDomain domain = AppDomain.CreateDomain(name);
var buffer = new StringBuilder();
var writer = new StringWriter(buffer);
Console.SetOut(writer);
domain.ExecuteAssembly(options.OutputAssembly);
AppDomain.Unload(domain);
string output = buffer.ToString();
Assert.AreEqual("pass", output, name);
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}
}
}
}
}
| bsd-2-clause | C# |
d76482edeb7cceac550b4e0bb042c3a3635d5301 | Use library (needed after VS update?) | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade.CLI.Tests/ProgramTests.cs | src/Arkivverket.Arkade.CLI.Tests/ProgramTests.cs | using System.IO;
using System.Linq;
using System.Reflection;
using Arkivverket.Arkade.Core.Base;
using Xunit;
using FluentAssertions;
using Microsoft.VisualStudio.TestPlatform.TestHost;
namespace Arkivverket.Arkade.CLI.Tests
{
public class ProgramTests
{
[Fact]
[Trait("Category", "Integration")]
public void TestReportAndPackageIsCreatedRunningN5Archive()
{
// Establish/clear needed paths:
string workingDirectoryPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string testDataDirectoryPath = Path.Combine(workingDirectoryPath, "TestData");
string metadataFilePath = Path.Combine(testDataDirectoryPath, "metadata.txt");
string archiveDirectoryPath = Path.Combine(testDataDirectoryPath, "N5-archive");
string outputDirectoryPath = Path.Combine(testDataDirectoryPath, "output");
// Clear needed paths:
File.Delete(metadataFilePath);
if (Directory.Exists(outputDirectoryPath))
Directory.Delete(outputDirectoryPath, true);
Directory.CreateDirectory(outputDirectoryPath);
// Run commands and store results:
Program.Main(new[]
{
"-g", metadataFilePath,
"-p", testDataDirectoryPath
});
bool metadataWasGenerated = File.Exists(metadataFilePath);
Program.Main(new[]
{
"-a", archiveDirectoryPath,
"-t", "noark5",
"-m", metadataFilePath,
"-p", testDataDirectoryPath,
"-o", outputDirectoryPath
});
FileSystemInfo[] outputDirectoryItems = new DirectoryInfo(outputDirectoryPath).GetFileSystemInfos();
bool testReportWasCreated = outputDirectoryItems.Any(item => item.Name.StartsWith("Arkaderapport"));
bool packageWasCreated = outputDirectoryItems.Any(item => item.Name.StartsWith("Arkadepakke"));
// Clean up:
File.Delete(metadataFilePath);
Directory.Delete(outputDirectoryPath, true);
ArkadeProcessingArea.Destroy();
// Control results:
metadataWasGenerated.Should().BeTrue();
testReportWasCreated.Should().BeTrue();
packageWasCreated.Should().BeTrue();
}
}
}
| using System.IO;
using System.Linq;
using System.Reflection;
using Arkivverket.Arkade.Core.Base;
using Xunit;
using FluentAssertions;
namespace Arkivverket.Arkade.CLI.Tests
{
public class ProgramTests
{
[Fact]
[Trait("Category", "Integration")]
public void TestReportAndPackageIsCreatedRunningN5Archive()
{
// Establish/clear needed paths:
string workingDirectoryPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string testDataDirectoryPath = Path.Combine(workingDirectoryPath, "TestData");
string metadataFilePath = Path.Combine(testDataDirectoryPath, "metadata.txt");
string archiveDirectoryPath = Path.Combine(testDataDirectoryPath, "N5-archive");
string outputDirectoryPath = Path.Combine(testDataDirectoryPath, "output");
// Clear needed paths:
File.Delete(metadataFilePath);
if (Directory.Exists(outputDirectoryPath))
Directory.Delete(outputDirectoryPath, true);
Directory.CreateDirectory(outputDirectoryPath);
// Run commands and store results:
Program.Main(new[]
{
"-g", metadataFilePath,
"-p", testDataDirectoryPath
});
bool metadataWasGenerated = File.Exists(metadataFilePath);
Program.Main(new[]
{
"-a", archiveDirectoryPath,
"-t", "noark5",
"-m", metadataFilePath,
"-p", testDataDirectoryPath,
"-o", outputDirectoryPath
});
FileSystemInfo[] outputDirectoryItems = new DirectoryInfo(outputDirectoryPath).GetFileSystemInfos();
bool testReportWasCreated = outputDirectoryItems.Any(item => item.Name.StartsWith("Arkaderapport"));
bool packageWasCreated = outputDirectoryItems.Any(item => item.Name.StartsWith("Arkadepakke"));
// Clean up:
File.Delete(metadataFilePath);
Directory.Delete(outputDirectoryPath, true);
ArkadeProcessingArea.Destroy();
// Control results:
metadataWasGenerated.Should().BeTrue();
testReportWasCreated.Should().BeTrue();
packageWasCreated.Should().BeTrue();
}
}
}
| agpl-3.0 | C# |
fcdc3ef6be44430fc2b52ef871b5196c38ff4184 | Make TaskCanceledException inherited from OperationCanceledException | OrangeCube/MinimumAsyncBridge,ppcuni/MinimumAsyncBridge,LeonAkasaka/MinimumAsyncBridge,munegon/MinimumAsyncBridge,ataihei/MinimumAsyncBridge,ufcpp/MinimumAsyncBridge | src/MinimumAsyncBridge/Threading/Tasks/TaskCanceledException.cs | src/MinimumAsyncBridge/Threading/Tasks/TaskCanceledException.cs | namespace System.Threading.Tasks
{
/// <summary>
/// Represents an exception used to communicate task cancellation.
/// </summary>
public class TaskCanceledException : OperationCanceledException
{
/// <summary>
/// Initializes a new instance of the TaskCanceledException class with a system-supplied message that describes the error.
/// </summary>
public TaskCanceledException() { }
/// <summary>
/// Initializes a new instance of the TaskCanceledException class with a specified message that describes the error.
/// </summary>
/// <param name="message"></param>
public TaskCanceledException(string message) : base(message) { }
/// <summary>
/// Initializes a new instance of the TaskCanceledException class with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TaskCanceledException(string message, Exception innerException) : base(message, innerException) { }
/// <summary>
/// Initializes a new instance of the TaskCanceledException class with a reference to the <see cref="Task"/> that has been canceled.
/// </summary>
/// <param name="task"></param>
public TaskCanceledException(Task task)
{
}
}
}
| namespace System.Threading.Tasks
{
/// <summary>
/// Represents an exception used to communicate task cancellation.
/// </summary>
public class TaskCanceledException : Exception
{
/// <summary>
/// Initializes a new instance of the TaskCanceledException class with a system-supplied message that describes the error.
/// </summary>
public TaskCanceledException() { }
/// <summary>
/// Initializes a new instance of the TaskCanceledException class with a specified message that describes the error.
/// </summary>
/// <param name="message"></param>
public TaskCanceledException(string message) : base(message) { }
/// <summary>
/// Initializes a new instance of the TaskCanceledException class with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TaskCanceledException(string message, Exception innerException) : base(message, innerException) { }
/// <summary>
/// Initializes a new instance of the TaskCanceledException class with a reference to the <see cref="Task"/> that has been canceled.
/// </summary>
/// <param name="task"></param>
public TaskCanceledException(Task task)
{
}
}
}
| mit | C# |
18ed0ad38982e7ea937105a599104bd3812ed174 | Fix typo | fuyuno/Norma | Norma.Gamma/Models/Slot.cs | Norma.Gamma/Models/Slot.cs | using System;
using Newtonsoft.Json;
using Norma.Gamma.Converters;
namespace Norma.Gamma.Models
{
public class Slot
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("startAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime StartAt { get; set; }
[JsonProperty("endAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime EndAt { get; set; }
[JsonProperty("programs")]
public Program[] Programs { get; set; }
[JsonProperty("tableStartAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime TableStartAt { get; set; }
[JsonProperty("tableEndAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime TableEndAt { get; set; }
[JsonProperty("highlight")]
public string Highlight { get; set; }
[JsonProperty("tableHighlight")]
public string TableHighlight { get; set; }
[JsonProperty("detailHighlight")]
public string DetailHighlight { get; set; }
[JsonProperty("displayProgramId")]
public string DisplayProgramId { get; set; }
[JsonProperty("mark")]
public Mark Mark { get; set; }
[JsonProperty("flags")]
public Flags Flags { get; set; }
[JsonProperty("channelId")]
public string ChannelId { get; set; }
[JsonProperty("timeshiftEndAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime TimeshiftEndAt { get; set; }
}
} | using System;
using Newtonsoft.Json;
using Norma.Gamma.Converters;
namespace Norma.Gamma.Models
{
public class Slot
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("startAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime StartAt { get; set; }
[JsonProperty("endAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime EndAt { get; set; }
[JsonProperty("program")]
public Program[] Programs { get; set; }
[JsonProperty("tableStartAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime TableStartAt { get; set; }
[JsonProperty("tableEndAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime TableEndAt { get; set; }
[JsonProperty("highlight")]
public string Highlight { get; set; }
[JsonProperty("tableHighlight")]
public string TableHighlight { get; set; }
[JsonProperty("detailHighlight")]
public string DetailHighlight { get; set; }
[JsonProperty("displayProgramId")]
public string DisplayProgramId { get; set; }
[JsonProperty("mark")]
public Mark Mark { get; set; }
[JsonProperty("flags")]
public Flags Flags { get; set; }
[JsonProperty("channelId")]
public string ChannelId { get; set; }
[JsonProperty("timeshiftEndAt")]
[JsonConverter(typeof(UnixTimeDateTimeConverter))]
public DateTime TimeshiftEndAt { get; set; }
}
} | mit | C# |
1ce7ef1bd292df31114a382ee7794880946b877a | fix shutdown luaenviroment | cyberegoorg/cetech,cyberegoorg/cetech,cyberegoorg/cetech,cyberegoorg/cetech | sources/CETech/Lua/LuaEnviroment.cs | sources/CETech/Lua/LuaEnviroment.cs | namespace CETech.Lua
{
/// <summary>
/// Main lua enviroment.
/// </summary>
public static partial class LuaEnviroment
{
/// <summary>
/// Init lua enviroment
/// </summary>
public static void Init()
{
InitImpl();
}
/// <summary>
/// Shutdown lua enviroment
/// </summary>
public static void Shutdown()
{
ShutdownImpl();
}
/// <summary>
/// Run script
/// </summary>
/// <param name="name">Script resource name</param>
public static void DoResource(long name)
{
DoResourceImpl(name);
}
/// <summary>
/// Init boot script
/// </summary>
/// <param name="name">Boot sript name</param>
public static void BootScriptInit(long name)
{
BootScriptInitImpl(name);
}
/// <summary>
/// Call boot script init fce.
/// </summary>
public static void BootScriptCallInit()
{
BootScriptCallInitImpl();
}
/// <summary>
/// Call boot script update
/// </summary>
/// <param name="dt">Deltatime</param>
public static void BootScriptCallUpdate(float dt)
{
BootScriptCallUpdateImpl(dt);
}
/// <summary>
/// Call boot script shutdown
/// </summary>
public static void BootScriptCallShutdown()
{
BootScriptCallShutdownImpl();
}
}
} | namespace CETech.Lua
{
/// <summary>
/// Main lua enviroment.
/// </summary>
public static partial class LuaEnviroment
{
/// <summary>
/// Init lua enviroment
/// </summary>
public static void Init()
{
InitImpl();
}
/// <summary>
/// Shutdown lua enviroment
/// </summary>
public static void Shutdown()
{
ShutdownImpl();
}
/// <summary>
/// Run script
/// </summary>
/// <param name="name">Script resource name</param>
public static void DoResource(long name)
{
DoResourceImpl(name);
}
/// <summary>
/// Init boot script
/// </summary>
/// <param name="name">Boot sript name</param>
public static void BootScriptInit(long name)
{
BootScriptInitImpl(name);
}
/// <summary>
/// Call boot script init fce.
/// </summary>
public static void BootScriptCallInit()
{
BootScriptCallInitImpl();
}
/// <summary>
/// Call boot script update
/// </summary>
/// <param name="dt">Deltatime</param>
public static void BootScriptCallUpdate(float dt)
{
BootScriptCallUpdateImpl(dt);
}
/// <summary>
/// Call boot script shutdown
/// </summary>
public static void BootScriptCallShutdown()
{
_enviromentScript.Call(_shutdownFce);
}
}
} | cc0-1.0 | C# |
0668e4541356a612f4d03faca985cd4e37156174 | Clean up server configuration. | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/MusicStore/Program.cs | src/MusicStore/Program.cs | using Microsoft.AspNetCore.Hosting;
using Microsoft.Net.Http.Server;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var builder = new WebHostBuilder()
.UseDefaultHostingConfiguration(args)
.UseIISIntegration()
.UseStartup("MusicStore");
// Switch beteween Kestrel and WebListener for different tests. Default to Kestrel for normal app execution.
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.WebListener", System.StringComparison.Ordinal))
{
if (string.Equals(builder.GetSetting("environment"), "NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener as follows.
// For IIS and IISExpress use inetmgr to setup NTLM authentication on the application or
// modify the applicationHost.config to enable NTLM.
builder.UseWebListener(options =>
{
options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM;
});
}
else
{
builder.UseWebListener();
}
}
else
{
builder.UseKestrel();
}
var host = builder.Build();
host.Run();
}
}
}
| using Microsoft.AspNetCore.Hosting;
using Microsoft.Net.Http.Server;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var builder = new WebHostBuilder()
// We set the server by name before default args so that command line arguments can override it.
// This is used to allow deployers to choose the server for testing.
.UseServer("Microsoft.AspNetCore.Server.Kestrel")
.UseDefaultHostingConfiguration(args)
.UseIISIntegration()
.UseStartup("MusicStore");
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.WebListener", System.StringComparison.Ordinal)
&& string.Equals(builder.GetSetting("environment"), "NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener like below.
// For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
// modify the applicationHost.config to enable NTLM.
builder.UseWebListener(options =>
{
options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM;
});
}
var host = builder.Build();
host.Run();
}
}
}
| apache-2.0 | C# |
583f7fcd534896bcd79dee08552d88bd1a070b41 | Switch to HTTPS. | loicteixeira/gj-unity-api | Assets/Plugins/GameJolt/Scripts/API/Constants.cs | Assets/Plugins/GameJolt/Scripts/API/Constants.cs | using UnityEngine;
using System.Collections;
namespace GameJolt.API
{
public static class Constants
{
public const string VERSION = "2.1.3";
public const string SETTINGS_ASSET_NAME = "GJAPISettings";
public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset";
public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/";
public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME;
public const string MANAGER_ASSET_NAME = "GameJoltAPI";
public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab";
public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/";
public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME;
public const string API_PROTOCOL = "https://";
public const string API_ROOT = "gamejolt.com/api/game/";
public const string API_VERSION = "1";
public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION;
public const string API_USERS_AUTH = "/users/auth";
public const string API_USERS_FETCH = "/users";
public const string API_SESSIONS_OPEN = "/sessions/open";
public const string API_SESSIONS_PING = "/sessions/ping";
public const string API_SESSIONS_CLOSE = "/sessions/close";
public const string API_SCORES_ADD = "/scores/add";
public const string API_SCORES_FETCH = "/scores";
public const string API_SCORES_TABLES_FETCH = "/scores/tables";
public const string API_TROPHIES_ADD = "/trophies/add-achieved";
public const string API_TROPHIES_FETCH = "/trophies";
public const string API_DATASTORE_SET = "/data-store/set";
public const string API_DATASTORE_UPDATE = "/data-store/update";
public const string API_DATASTORE_FETCH = "/data-store";
public const string API_DATASTORE_REMOVE = "/data-store/remove";
public const string API_DATASTORE_KEYS_FETCH = "/data-store/get-keys";
public const string IMAGE_RESOURCE_REL_PATH = "Images/";
public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar";
public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME;
public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification";
public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME;
public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy";
public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME;
}
}
| using UnityEngine;
using System.Collections;
namespace GameJolt.API
{
public static class Constants
{
public const string VERSION = "2.1.3";
public const string SETTINGS_ASSET_NAME = "GJAPISettings";
public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset";
public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/";
public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME;
public const string MANAGER_ASSET_NAME = "GameJoltAPI";
public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab";
public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/";
public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME;
public const string API_PROTOCOL = "http://";
public const string API_ROOT = "gamejolt.com/api/game/";
public const string API_VERSION = "1";
public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION;
public const string API_USERS_AUTH = "/users/auth";
public const string API_USERS_FETCH = "/users";
public const string API_SESSIONS_OPEN = "/sessions/open";
public const string API_SESSIONS_PING = "/sessions/ping";
public const string API_SESSIONS_CLOSE = "/sessions/close";
public const string API_SCORES_ADD = "/scores/add";
public const string API_SCORES_FETCH = "/scores";
public const string API_SCORES_TABLES_FETCH = "/scores/tables";
public const string API_TROPHIES_ADD = "/trophies/add-achieved";
public const string API_TROPHIES_FETCH = "/trophies";
public const string API_DATASTORE_SET = "/data-store/set";
public const string API_DATASTORE_UPDATE = "/data-store/update";
public const string API_DATASTORE_FETCH = "/data-store";
public const string API_DATASTORE_REMOVE = "/data-store/remove";
public const string API_DATASTORE_KEYS_FETCH = "/data-store/get-keys";
public const string IMAGE_RESOURCE_REL_PATH = "Images/";
public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar";
public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME;
public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification";
public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME;
public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy";
public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME;
}
}
| mit | C# |
b0229a2d86a4c4b35802d4281f98167883f40c69 | adjust version to 0.11.0 | McSherry/Zener | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("Zener")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Liam McSherry")]
[assembly: AssemblyProduct("Zener")]
[assembly: AssemblyCopyright("Copyright 2014-2015 © Liam McSherry")]
[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("eee2f3bf-8856-4d1c-a82d-7c3e0011e775")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")
[assembly: AssemblyVersion("0.11.0")]
[assembly: AssemblyFileVersion("0.11.0")]
[assembly: NeutralResourcesLanguageAttribute("en-GB")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("Zener")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Liam McSherry")]
[assembly: AssemblyProduct("Zener")]
[assembly: AssemblyCopyright("Copyright 2014-2015 © Liam McSherry")]
[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("eee2f3bf-8856-4d1c-a82d-7c3e0011e775")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")
[assembly: AssemblyVersion("0.10.0")]
[assembly: AssemblyFileVersion("0.10.0")]
[assembly: NeutralResourcesLanguageAttribute("en-GB")]
| bsd-3-clause | C# |
c71d1f2d74d2c791e46783e283daa104d52eea02 | Change SunshineFileSystem to save MOTMaster data directly to Box | ColdMatter/EDMSuite,ColdMatter/EDMSuite,ColdMatter/EDMSuite,ColdMatter/EDMSuite | DAQ/SunshineFileSystem.cs | DAQ/SunshineFileSystem.cs | using System;
namespace DAQ.Environment
{
public class SunshineFileSystem : DAQ.Environment.FileSystem
{
public SunshineFileSystem()
{
Paths.Add("settingsPath", "c:\\Control Programs\\Settings\\");
Paths.Add("scanMasterDataPath", "c:\\Data\\LCMCaF\\");
Paths.Add("mathPath", "c:/program files/wolfram research/mathematica/7.0/mathkernel.exe");
Paths.Add("fakeData", "c:\\Data\\examples\\");
// Paths.Add("decelerationUtilitiesPath", "d:\\Tools\\");
Paths.Add("vcoLockData", "c:\\Data\\VCO Lock\\");
Paths.Add("transferCavityData", "c:\\Data\\LCMCaF\\TCL\\");
Paths.Add("MOTMasterDataPath", "C:\\Users\\Cooler\\Box Sync\\CaF MOT\\MOTData\\MOTMasterData\\");
Paths.Add("scriptListPath", "C:\\Control Programs\\EDMSuite\\MoleculeMOTMasterScripts");
Paths.Add("daqDLLPath", "C:\\Control Programs\\EDMSuite\\DAQ\\bin\\CaF\\daq.dll");
Paths.Add("MOTMasterExePath", "C:\\Control Programs\\EDMSuite\\MOTMaster\\bin\\CaF\\");
Paths.Add("UntriggeredCameraAttributesPath", "c:\\Data\\Settings\\CameraAttributes\\SHCCameraAttributes.txt");
Paths.Add("CameraAttributesPath", "c:\\Data\\Settings\\CameraAttributes\\MOTMasterCameraAttributes.txt");
Paths.Add("ExternalFilesPath", "\\\\PH-RAINBOW1\\CameraImages\\");
Paths.Add("HardwareClassPath", "C:\\Control Programs\\EDMSuite\\DAQ\\MoleculeMOTHardware.cs");
DataSearchPaths.Add(Paths["scanMasterDataPath"]);
SortDataByDate = false;
}
}
}
| using System;
namespace DAQ.Environment
{
public class SunshineFileSystem : DAQ.Environment.FileSystem
{
public SunshineFileSystem()
{
Paths.Add("settingsPath", "c:\\Control Programs\\Settings\\");
Paths.Add("scanMasterDataPath", "c:\\Data\\LCMCaF\\");
Paths.Add("mathPath", "c:/program files/wolfram research/mathematica/7.0/mathkernel.exe");
Paths.Add("fakeData", "c:\\Data\\examples\\");
// Paths.Add("decelerationUtilitiesPath", "d:\\Tools\\");
Paths.Add("vcoLockData", "c:\\Data\\VCO Lock\\");
Paths.Add("transferCavityData", "c:\\Data\\LCMCaF\\TCL\\");
Paths.Add("MOTMasterDataPath", "c:\\Data\\MOTMasterData\\");
Paths.Add("scriptListPath", "C:\\Control Programs\\EDMSuite\\MoleculeMOTMasterScripts");
Paths.Add("daqDLLPath", "C:\\Control Programs\\EDMSuite\\DAQ\\bin\\CaF\\daq.dll");
Paths.Add("MOTMasterExePath", "C:\\Control Programs\\EDMSuite\\MOTMaster\\bin\\CaF\\");
Paths.Add("UntriggeredCameraAttributesPath", "c:\\Data\\Settings\\CameraAttributes\\SHCCameraAttributes.txt");
Paths.Add("CameraAttributesPath", "c:\\Data\\Settings\\CameraAttributes\\MOTMasterCameraAttributes.txt");
Paths.Add("ExternalFilesPath", "\\\\PH-RAINBOW1\\CameraImages\\");
Paths.Add("HardwareClassPath", "C:\\Control Programs\\EDMSuite\\DAQ\\MoleculeMOTHardware.cs");
DataSearchPaths.Add(Paths["scanMasterDataPath"]);
SortDataByDate = false;
}
}
}
| mit | C# |
7d2a017ac45dcafba574e292330580ccf363ed66 | Make sure the RealTimeMessagingService test actually runs. | CuriousCurmudgeon/taut | Taut.Test/RealTime/RealTimeMessagingServiceTests.cs | Taut.Test/RealTime/RealTimeMessagingServiceTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reactive.Threading.Tasks;
using System.Text;
using System.Threading.Tasks;
using Taut.RealTime;
namespace Taut.Test.RealTime
{
[TestClass]
public class RealTimeMessagingServiceTests : ApiServiceTestBase
{
private static RealTimeMessagingStartResponse OkRealTimeMessagingStartResponse;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
OkRealTimeMessagingStartResponse = JsonLoader.LoadJson<RealTimeMessagingStartResponse>(@"RealTime/Data/rtm_start.json");
}
#region Start
[TestMethod]
public async Task WhenStartIsCalled_ThenRtmStartIsIncludedInRequest()
{
await ShouldHaveCalledTestHelperAsync(OkRealTimeMessagingStartResponse,
async service => await service.Start().ToTask(),
"*rtm.start");
}
#endregion
#region Helpers
private async Task ShouldHaveCalledTestHelperAsync<T>(T response, Func<IRealTimeMessagingService, Task<T>> action,
string shouldHaveCalled)
{
// Arrange
var service = BuildRealTimeMessagingService();
HttpTest.RespondWithJson(response);
SetAuthorizedUserExpectations();
// Act
var result = await action.Invoke(service);
// Assert
HttpTest.ShouldHaveCalled(shouldHaveCalled)
.WithVerb(HttpMethod.Get)
.Times(1);
}
#region Test Helpers
private RealTimeMessagingService BuildRealTimeMessagingService()
{
return new RealTimeMessagingService(UserCredentialService.Object);
}
#endregion
#endregion
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reactive.Threading.Tasks;
using System.Text;
using System.Threading.Tasks;
using Taut.RealTime;
namespace Taut.Test.RealTime
{
public class RealTimeMessagingServiceTests : ApiServiceTestBase
{
private static RealTimeMessagingStartResponse OkRealTimeMessagingStartResponse;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
OkRealTimeMessagingStartResponse = JsonLoader.LoadJson<RealTimeMessagingStartResponse>(@"RealTime/Data/rtm_start.json");
}
#region Start
[TestMethod]
public async Task WhenStartIsCalled_ThenRtmStartIsIncludedInRequest()
{
await ShouldHaveCalledTestHelperAsync(OkRealTimeMessagingStartResponse,
async service => await service.Start().ToTask(),
"*rtm.start");
}
#endregion
#region Helpers
private async Task ShouldHaveCalledTestHelperAsync<T>(T response, Func<IRealTimeMessagingService, Task<T>> action,
string shouldHaveCalled)
{
// Arrange
var service = BuildRealTimeMessagingService();
HttpTest.RespondWithJson(response);
SetAuthorizedUserExpectations();
// Act
var result = await action.Invoke(service);
// Assert
HttpTest.ShouldHaveCalled(shouldHaveCalled)
.WithVerb(HttpMethod.Get)
.Times(1);
}
#region Test Helpers
private RealTimeMessagingService BuildRealTimeMessagingService()
{
return new RealTimeMessagingService(UserCredentialService.Object);
}
#endregion
#endregion
}
}
| mit | C# |
53e6a41eff53587dec6a3e3fe57de62b93a6c72e | Fix version number for the fake release | malcolmr/nodatime,malcolmr/nodatime,nodatime/nodatime,malcolmr/nodatime,jskeet/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,jskeet/nodatime,nodatime/nodatime,BenJenkinson/nodatime | src/NodaTime.Web/Models/FakeReleaseRepository.cs | src/NodaTime.Web/Models/FakeReleaseRepository.cs | // Copyright 2017 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System.Collections.Generic;
namespace NodaTime.Web.Models
{
/// <summary>
/// Fake implementation of IReleaseRepository used in cases of emergency...
/// </summary>
public class FakeReleaseRepository : IReleaseRepository
{
private static readonly IList<ReleaseDownload> releases = new[]
{
new ReleaseDownload(new StructuredVersion("2.4.4"), "NodaTime-2.4.4.zip",
"https://storage.cloud.google.com/nodatime/releases/NodaTime-2.4.4.zip",
"5a672e0910353eef53cd3b6a4ff08e1287ec6fe40faf96ca42e626b107c8f8d4",
new LocalDate(2018, 12, 31))
};
public ReleaseDownload LatestRelease => releases[0];
public IList<ReleaseDownload> GetReleases() => releases;
}
}
| // Copyright 2017 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System.Collections.Generic;
namespace NodaTime.Web.Models
{
/// <summary>
/// Fake implementation of IReleaseRepository used in cases of emergency...
/// </summary>
public class FakeReleaseRepository : IReleaseRepository
{
private static readonly IList<ReleaseDownload> releases = new[]
{
new ReleaseDownload(new StructuredVersion("2.4.3"), "NodaTime-2.4.4.zip",
"https://storage.cloud.google.com/nodatime/releases/NodaTime-2.4.4.zip",
"5a672e0910353eef53cd3b6a4ff08e1287ec6fe40faf96ca42e626b107c8f8d4",
new LocalDate(2018, 12, 31))
};
public ReleaseDownload LatestRelease => releases[0];
public IList<ReleaseDownload> GetReleases() => releases;
}
}
| apache-2.0 | C# |
b495c77a6435519a1298adc35617f7165090b871 | Set the driver property in TranslationUnitPass when adding new passes. | inordertotest/CppSharp,ktopouzi/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,mono/CppSharp,mono/CppSharp,mydogisbox/CppSharp,u255436/CppSharp,u255436/CppSharp,mydogisbox/CppSharp,imazen/CppSharp,mydogisbox/CppSharp,xistoso/CppSharp,Samana/CppSharp,nalkaro/CppSharp,zillemarco/CppSharp,Samana/CppSharp,ddobrev/CppSharp,mono/CppSharp,nalkaro/CppSharp,Samana/CppSharp,KonajuGames/CppSharp,nalkaro/CppSharp,ddobrev/CppSharp,txdv/CppSharp,mydogisbox/CppSharp,nalkaro/CppSharp,ddobrev/CppSharp,mydogisbox/CppSharp,zillemarco/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,SonyaSa/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,mono/CppSharp,txdv/CppSharp,txdv/CppSharp,mono/CppSharp,KonajuGames/CppSharp,imazen/CppSharp,imazen/CppSharp,imazen/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,mono/CppSharp,SonyaSa/CppSharp,Samana/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,SonyaSa/CppSharp,ktopouzi/CppSharp,SonyaSa/CppSharp,txdv/CppSharp,xistoso/CppSharp,xistoso/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,Samana/CppSharp,xistoso/CppSharp,imazen/CppSharp,xistoso/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,txdv/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,u255436/CppSharp,genuinelucifer/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,nalkaro/CppSharp,ktopouzi/CppSharp,genuinelucifer/CppSharp,KonajuGames/CppSharp,KonajuGames/CppSharp | src/Generator/Passes/PassBuilder.cs | src/Generator/Passes/PassBuilder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;
namespace CppSharp
{
/// <summary>
/// This class is used to build passes that will be run against the AST
/// that comes from C++.
/// </summary>
public class PassBuilder<T>
{
public List<T> Passes { get; private set; }
public Driver Driver { get; private set; }
public PassBuilder(Driver driver)
{
Passes = new List<T>();
Driver = driver;
}
/// <summary>
/// Adds a new pass to the builder.
/// </summary>
public void AddPass(T pass)
{
if (pass is TranslationUnitPass)
(pass as TranslationUnitPass).Driver = Driver;
Passes.Add(pass);
}
/// <summary>
/// Finds a previously-added pass of the given type.
/// </summary>
public U FindPass<U>() where U : TranslationUnitPass
{
return Passes.OfType<U>().Select(pass => pass as U).FirstOrDefault();
}
/// <summary>
/// Adds a new pass to the builder.
/// </summary>
public void RunPasses(Action<T> action)
{
foreach (var pass in Passes)
action(pass);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;
namespace CppSharp
{
/// <summary>
/// This class is used to build passes that will be run against the AST
/// that comes from C++.
/// </summary>
public class PassBuilder<T>
{
public List<T> Passes { get; private set; }
public Driver Driver { get; private set; }
public PassBuilder(Driver driver)
{
Passes = new List<T>();
Driver = driver;
}
/// <summary>
/// Adds a new pass to the builder.
/// </summary>
public void AddPass(T pass)
{
Passes.Add(pass);
}
/// <summary>
/// Finds a previously-added pass of the given type.
/// </summary>
public U FindPass<U>() where U : TranslationUnitPass
{
return Passes.OfType<U>().Select(pass => pass as U).FirstOrDefault();
}
/// <summary>
/// Adds a new pass to the builder.
/// </summary>
public void RunPasses(Action<T> action)
{
foreach (var pass in Passes)
action(pass);
}
}
}
| mit | C# |
b93fff590487d4931b6869625c38550ed97e9b01 | Change exception type. | wasabii/Cogito,wasabii/Cogito | Cogito.Fabric.Activities/ActivityActorInternalExtensions.cs | Cogito.Fabric.Activities/ActivityActorInternalExtensions.cs | using System;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Actors;
using Microsoft.ServiceFabric.Actors.Runtime;
namespace Cogito.Fabric.Activities
{
/// <summary>
/// Internal extensions against <see cref="IActivityActorInternal"/> interfaces.
/// </summary>
static class ActivityActorInternalExtensions
{
/// <summary>
/// Invokes the given action using an actor timer.
/// </summary>
/// <param name="actor"></param>
/// <param name="action"></param>
public static void ScheduleInvokeWithTimer(this IActivityActorInternal actor, Func<Task> action)
{
Contract.Requires<ArgumentNullException>(actor != null);
Contract.Requires<ArgumentNullException>(action != null);
// hoist timer so it can be unregistered
IActorTimer timer = null;
// schedule timer
timer = actor.RegisterTimer(
o => { actor.UnregisterTimer(timer); return action(); },
null,
TimeSpan.FromMilliseconds(1),
TimeSpan.FromMilliseconds(-1));
}
/// <summary>
/// Gets the actor reminder with the specified actor reminder name, or <c>null</c> if no such reminder exists.
/// </summary>
/// <param name="reminderName"></param>
/// <returns></returns>
public static IActorReminder TryGetReminder(this IActivityActorInternal actor, string reminderName)
{
Contract.Requires<ArgumentNullException>(actor != null);
Contract.Requires<ArgumentNullException>(reminderName != null);
try
{
return actor.GetReminder(reminderName);
}
catch (ReminderNotFoundException)
{
// ignore
}
return null;
}
}
}
| using System;
using System.Diagnostics.Contracts;
using System.Fabric;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Actors.Runtime;
namespace Cogito.Fabric.Activities
{
/// <summary>
/// Internal extensions against <see cref="IActivityActorInternal"/> interfaces.
/// </summary>
static class ActivityActorInternalExtensions
{
/// <summary>
/// Invokes the given action using an actor timer.
/// </summary>
/// <param name="actor"></param>
/// <param name="action"></param>
public static void ScheduleInvokeWithTimer(this IActivityActorInternal actor, Func<Task> action)
{
Contract.Requires<ArgumentNullException>(actor != null);
Contract.Requires<ArgumentNullException>(action != null);
// hoist timer so it can be unregistered
IActorTimer timer = null;
// schedule timer
timer = actor.RegisterTimer(
o => { actor.UnregisterTimer(timer); return action(); },
null,
TimeSpan.FromMilliseconds(1),
TimeSpan.FromMilliseconds(-1));
}
/// <summary>
/// Gets the actor reminder with the specified actor reminder name, or <c>null</c> if no such reminder exists.
/// </summary>
/// <param name="reminderName"></param>
/// <returns></returns>
public static IActorReminder TryGetReminder(this IActivityActorInternal actor, string reminderName)
{
Contract.Requires<ArgumentNullException>(actor != null);
Contract.Requires<ArgumentNullException>(reminderName != null);
try
{
return actor.GetReminder(reminderName);
}
catch (FabricException e) when (e.ErrorCode == FabricErrorCode.Unknown)
{
// ignore
}
return null;
}
}
}
| mit | C# |
9103e10e6d82f87d020319f154d1a3a5fc1add16 | Update 70.Autoproperties.cs | MarcosMeli/FileHelpers | FileHelpers.Examples/Examples/10.QuickStart/70.Autoproperties.cs | FileHelpers.Examples/Examples/10.QuickStart/70.Autoproperties.cs | using FileHelpers;
namespace ExamplesFx
{
//-> Name: Autoproperties
//-> Description: You can use autoproperties instead of fields:
public class AutopropertiesSample
: ExampleBase
{
//-> If you have a source file like this, separated by a "|":
//-> FileIn:Input.txt
/*10248|VINET|04071996|32.38
10249|TOMSP|05071996|11.61
10250|HANAS|08071996|65.83
10251|VICTE|08071996|41.34*/
//-> /FileIn
//-> You can use autoproperties but for the moment you can't use Converters:
//-> File:RecordClass.cs
[DelimitedRecord("|")]
public class Orders
{
public int OrderID { get; set; }
public string CustomerID { get; set; }
public string OrderDate { get; set; }
public string Freight { get; set; }
}
//-> /File
//-> Instantiate the FileHelperEngine and iterate over the records:
public override void Run()
{
//-> File:Example.cs
var engine = new FileHelperEngine<Orders>();
var records = engine.ReadFile("Input.txt");
foreach (var record in records)
{
Console.WriteLine(record.CustomerID);
Console.WriteLine(record.OrderDate);
Console.WriteLine(record.Freight);
}
//-> /File
}
}
}
| using FileHelpers;
namespace ExamplesFx
{
//-> Name: Autoproperties
//-> Description: You can use autoproperties instead of fields
public class AutopropertiesSample
: ExampleBase
{
//-> If you have a source file like this, separated by a |:
//-> FileIn:Input.txt
/*10248|VINET|04071996|32.38
10249|TOMSP|05071996|11.61
10250|HANAS|08071996|65.83
10251|VICTE|08071996|41.34*/
//-> /FileIn
//-> You can use autoproperties but for the moment you can't use Converters
//-> File:RecordClass.cs
[DelimitedRecord("|")]
public class Orders
{
public int OrderID { get; set; }
public string CustomerID { get; set; }
public string OrderDate { get; set; }
public string Freight { get; set; }
}
//-> /File
public override void Run()
{
//-> File:Example.cs
var engine = new FileHelperEngine<Orders>();
var records = engine.ReadFile("Input.txt");
foreach (var record in records)
{
Console.WriteLine(record.CustomerID);
Console.WriteLine(record.OrderDate);
Console.WriteLine(record.Freight);
}
//-> /File
}
}
} | mit | C# |
9a70a9475d00ab74f2e1f65306efea66adbce207 | Update AssignValidateDigitalSignatures.cs | asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Articles/AssignValidateDigitalSignatures.cs | Examples/CSharp/Articles/AssignValidateDigitalSignatures.cs | using System;
using System.IO;
using Aspose.Cells;
using System.Collections;
using System.Text;
using System.Threading;
using Aspose.Cells.Rendering;
using System.Security.Cryptography;
using System.Drawing;
using System.Diagnostics;
using Aspose.Cells.DigitalSignatures;
using System.Security.Cryptography.X509Certificates;
namespace Aspose.Cells.Examples.Articles
{
public class AssignValidateDigitalSignatures
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Program test = new MyTest();
//test.testSign();
//test.testvalidateSign();
Console.ReadLine();
//ExEnd:1
}
}
}
| using System;
using System.IO;
using Aspose.Cells;
using System.Collections;
using System.Text;
using System.Threading;
using Aspose.Cells.Rendering;
using System.Security.Cryptography;
using System.Drawing;
using System.Diagnostics;
using Aspose.Cells.DigitalSignatures;
using System.Security.Cryptography.X509Certificates;
namespace Aspose.Cells.Examples.Articles
{
public class AssignValidateDigitalSignatures
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Program test = new MyTest();
//test.testSign();
//test.testvalidateSign();
Console.ReadLine();
}
}
} | mit | C# |
2abf81e89ebc6209a9171d2d34d2791678b8fa01 | Change to WebApiConfig to test registration | stringbitking/JerryMouseChat,stringbitking/JerryMouseChat | JerryMouseChat/JerryChat.Services/App_Start/WebApiConfig.cs | JerryMouseChat/JerryChat.Services/App_Start/WebApiConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace JerryChat.Services
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var cors = new EnableCorsAttribute("http://localhost:53999", "*", "*");
config.EnableCors(cors);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace JerryChat.Services
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| mit | C# |
ddfb4194fae802b90c85709509192c62c5d69fe6 | Update ElementMethodsStream.cs | jeremytammik/RevitLookup | RevitLookup/Core/Streams/ElementMethodsStream.cs | RevitLookup/Core/Streams/ElementMethodsStream.cs | using System.Collections;
using System.Reflection;
using Autodesk.Revit.DB;
using RevitLookup.Core.CollectorExtensions;
using RevitLookup.Core.RevitTypes;
namespace RevitLookup.Core.Streams;
public class ElementMethodsStream : IElementStream
{
private readonly ArrayList _data;
private readonly DataFactory _methodDataFactory;
private readonly List<string> _seenMethods = new();
public ElementMethodsStream(Document document, ArrayList data, object element)
{
_data = data;
_methodDataFactory = new DataFactory(document, element);
}
public void Stream(Type type)
{
var methods = type
.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
.OrderBy(x => x.Name)
.ToList();
if (methods.Count > 0) _data.Add(new MemberSeparatorWithOffsetData("Methods"));
var currentTypeMethods = new List<string>();
foreach (var methodInfo in methods)
{
//if(IsMethodExcept(methodInfo)) continue;
if (_seenMethods.Contains(methodInfo.Name)) continue;
currentTypeMethods.Add(methodInfo.Name);
var methodData = GetMethodData(methodInfo);
if (methodData is not null) _data.Add(methodData);
}
_seenMethods.AddRange(currentTypeMethods);
}
private Data GetMethodData(MethodInfo methodInfo)
{
try
{
return _methodDataFactory.Create(methodInfo);
}
catch (Exception ex)
{
return new ExceptionData(methodInfo.Name, ex);
}
}
bool IsMethodExcept(MethodInfo methodInfo)
{
if (methodInfo.Name.Equals("SubmitPrint", StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
} | using System.Collections;
using System.Reflection;
using Autodesk.Revit.DB;
using RevitLookup.Core.CollectorExtensions;
using RevitLookup.Core.RevitTypes;
namespace RevitLookup.Core.Streams;
public class ElementMethodsStream : IElementStream
{
private readonly ArrayList _data;
private readonly DataFactory _methodDataFactory;
private readonly List<string> _seenMethods = new();
public ElementMethodsStream(Document document, ArrayList data, object element)
{
_data = data;
_methodDataFactory = new DataFactory(document, element);
}
public void Stream(Type type)
{
var methods = type
.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
.OrderBy(x => x.Name)
.ToList();
if (methods.Count > 0) _data.Add(new MemberSeparatorWithOffsetData("Methods"));
var currentTypeMethods = new List<string>();
foreach (var methodInfo in methods)
{
if (_seenMethods.Contains(methodInfo.Name)) continue;
currentTypeMethods.Add(methodInfo.Name);
var methodData = GetMethodData(methodInfo);
if (methodData is not null) _data.Add(methodData);
}
_seenMethods.AddRange(currentTypeMethods);
}
private Data GetMethodData(MethodInfo methodInfo)
{
try
{
return _methodDataFactory.Create(methodInfo);
}
catch (Exception ex)
{
return new ExceptionData(methodInfo.Name, ex);
}
}
} | mit | C# |
5f5e632f6c80a15a6552eb3cfd997d121e67c57b | Implement YoutrackCommand | n-develop/tickettimer | TicketTimer.Youtrack/Commands/YoutrackCommand.cs | TicketTimer.Youtrack/Commands/YoutrackCommand.cs | using ManyConsole;
using TicketTimer.Youtrack.Services;
namespace TicketTimer.Youtrack.Commands
{
public class YoutrackCommand : ConsoleCommand
{
private readonly YoutrackService _youtrackService;
public YoutrackCommand(YoutrackService youtrackService)
{
_youtrackService = youtrackService;
ConfigureCommand();
}
private void ConfigureCommand()
{
IsCommand("youtrack", "Log time for all saved YouTrack-tickets");
}
public override int Run(string[] remainingArguments)
{
_youtrackService.WriteEntireArchive();
return 0;
}
}
}
| using System;
using ManyConsole;
namespace TicketTimer.Youtrack.Commands
{
public class YoutrackCommand : ConsoleCommand
{
public YoutrackCommand()
{
}
public override int Run(string[] remainingArguments)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
db86483a41503e9a28d243b8902b291f14389bca | Rename prop | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University.Controls/ViewModels/AgplSignatureViewModel.cs | R7.University.Controls/ViewModels/AgplSignatureViewModel.cs | using System;
using System.Reflection;
using R7.University.Components;
namespace R7.University.Controls.ViewModels
{
public class AgplSignatureViewModel
{
public bool ShowRule { get; set; } = true;
public virtual Assembly BaseAssembly => UniversityAssembly.GetCoreAssembly ();
public virtual string Name => BaseAssembly.GetName ().Name;
public virtual Version Version => BaseAssembly.GetName ().Version;
public virtual string InformationalVersion =>
BaseAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute> ()?.InformationalVersion;
}
}
| //
// AgplSignatureViewModel.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2017 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Reflection;
using R7.University.Components;
namespace R7.University.Controls.ViewModels
{
public class AgplSignatureViewModel
{
public bool ShowRule { get; set; } = true;
public virtual Assembly CoreAssembly => UniversityAssembly.GetCoreAssembly ();
public virtual string Name => CoreAssembly.GetName ().Name;
public virtual Version Version => CoreAssembly.GetName ().Version;
public virtual string InformationalVersion =>
CoreAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute> ()?.InformationalVersion;
}
}
| agpl-3.0 | C# |
52b5965612a30c9acc108f18b291dca9da3bc746 | Increase nuget version to 2.0.0-beta02 | Jericho/CakeMail.RestClient | CakeMail.RestClient/Properties/AssemblyInfo.cs | CakeMail.RestClient/Properties/AssemblyInfo.cs | using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta02")] | using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta01")] | mit | C# |
25807433756790ed2f1135d962205a761f17af6a | 修改 Welcome action 可接收參數. | NemoChenTW/MvcMovie,NemoChenTW/MvcMovie,NemoChenTW/MvcMovie | src/MvcMovie/Controllers/HelloWorldController.cs | src/MvcMovie/Controllers/HelloWorldController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.WebEncoders;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
public string Index()
{
return "This is my default action...";
}
//
// GET: /HelloWorld/Welcome/
public string Welcome(string name, int numTimes = 1)
{
return HtmlEncoder.Default.HtmlEncode(
"Hello " + name + ", NumTimes is: " + numTimes);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
public string Index()
{
return "This is my default action...";
}
//
// GET: /HelloWorld/Welcome/
public string Welcome()
{
return "This is the Welcome action method...";
}
}
}
| apache-2.0 | C# |
fada75bf42ef8a014781ebbfb139bc1a29f689b5 | Update PathDrawNode.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Core2D/Modules/Renderer/Nodes/PathDrawNode.cs | src/Core2D/Modules/Renderer/Nodes/PathDrawNode.cs | #nullable disable
using Core2D.Model.Renderer;
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Shapes;
using Core2D.ViewModels.Style;
using AM = Avalonia.Media;
using AP = Avalonia.Platform;
namespace Core2D.Modules.Renderer.Nodes
{
internal class PathDrawNode : DrawNode, IPathDrawNode
{
public PathShapeViewModel Path { get; set; }
#if CUSTOM_DRAW
public AP.IGeometryImpl Geometry { get; set; }
#else
public AM.Geometry Geometry { get; set; }
#endif
public PathDrawNode(PathShapeViewModel path, ShapeStyleViewModel style)
{
Style = style;
Path = path;
UpdateGeometry();
}
public override void UpdateGeometry()
{
ScaleThickness = Path.State.HasFlag(ShapeStateFlags.Thickness);
ScaleSize = Path.State.HasFlag(ShapeStateFlags.Size);
#if CUSTOM_DRAW
Geometry = PathGeometryConverter.ToGeometryImpl(Path.Geometry, Path.IsFilled);
#else
Geometry = PathGeometryConverter.ToGeometry(Path.Geometry, Path.IsFilled);
#endif
Center = Geometry.Bounds.Center;
}
public override void OnDraw(object dc, double zoom)
{
#if CUSTOM_DRAW
var context = dc as AP.IDrawingContextImpl;
context.DrawGeometry(Path.IsFilled ? Fill : null, Path.IsStroked ? Stroke : null, Geometry);
#else
var context = dc as AM.DrawingContext;
context.DrawGeometry(Path.IsFilled ? Fill : null, Path.IsStroked ? Stroke : null, Geometry);
#endif
}
}
}
| #nullable disable
using Core2D.Model.Renderer;
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Shapes;
using Core2D.ViewModels.Style;
using AM = Avalonia.Media;
using AP = Avalonia.Platform;
namespace Core2D.Modules.Renderer.Nodes
{
internal class PathDrawNode : DrawNode, IPathDrawNode
{
public PathShapeViewModel Path { get; set; }
#if CUSTOM_DRAW
public AP.IGeometryImpl Geometry { get; set; }
#else
public AM.Geometry Geometry { get; set; }
#endif
public PathDrawNode(PathShapeViewModel path, ShapeStyleViewModel style)
{
Style = style;
Path = path;
UpdateGeometry();
}
public override void UpdateGeometry()
{
ScaleThickness = Path.State.HasFlag(ShapeStateFlags.Thickness);
ScaleSize = Path.State.HasFlag(ShapeStateFlags.Size);
#if CUSTOM_DRAW
Geometry = PathGeometryConverter.ToGeometryImpl(Path.Geometry);
#else
Geometry = PathGeometryConverter.ToGeometry(Path.Geometry);
#endif
Center = Geometry.Bounds.Center;
}
public override void OnDraw(object dc, double zoom)
{
#if CUSTOM_DRAW
var context = dc as AP.IDrawingContextImpl;
context.DrawGeometry(Path.IsFilled ? Fill : null, Path.IsStroked ? Stroke : null, Geometry);
#else
var context = dc as AM.DrawingContext;
context.DrawGeometry(Path.IsFilled ? Fill : null, Path.IsStroked ? Stroke : null, Geometry);
#endif
}
}
}
| mit | C# |
927c811aef5cffe58894357d1b4541753165e64b | Set version to 0.7.0 | hazzik/DelegateDecompiler,jaenyph/DelegateDecompiler,morgen2009/DelegateDecompiler | src/DelegateDecompiler/Properties/AssemblyInfo.cs | src/DelegateDecompiler/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DelegateDecompiler")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DelegateDecompiler")]
[assembly: AssemblyCopyright("Copyright © hazzik 2012")]
[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("cec0a257-502b-4718-91c3-9e67555c5e1b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.7.0.0")]
[assembly: AssemblyFileVersion("0.7.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DelegateDecompiler")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DelegateDecompiler")]
[assembly: AssemblyCopyright("Copyright © hazzik 2012")]
[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("cec0a257-502b-4718-91c3-9e67555c5e1b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.6.0.0")]
[assembly: AssemblyFileVersion("0.6.0.0")]
| mit | C# |
8730ac7b95dcbff45ec71c0c0f7dd6bf3bafa0a0 | remove unrefactored replace in explanation type | geeklearningio/gl-dotnet-domain | src/GeekLearning.Domain.AspnetCore/MaybeResult.cs | src/GeekLearning.Domain.AspnetCore/MaybeResult.cs | using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GeekLearning.Domain.AspnetCore
{
public class MaybeResult<T> : ObjectResult where T : class
{
private Maybe<T> maybe;
public MaybeResult(Maybe<T> maybe) : base(null)
{
this.maybe = maybe;
}
public Maybe<T> Maybe { get; set; }
public override Task ExecuteResultAsync(ActionContext context)
{
var resultMapper = context.HttpContext.RequestServices.GetRequiredService<Internal.MaybeResultMapper>();
var requestIdProvider = context.HttpContext.RequestServices.GetRequiredService<IRequestIdProvider>();
var options = context.HttpContext.RequestServices.GetRequiredService<IOptions<DomainOptions>>();
bool isDebugEnabled = options.Value.Debug;
var response = new Response<T>
{
Content = this.maybe.Value,
Status = new ReponseStatus
{
Code = resultMapper.GetResult(this.maybe.Explanations),
Reasons = (this.maybe.Explanations ?? Enumerable.Empty<Explanations.Explanation>())
.Select(reason => new ResponseExplanation
{
Message = reason.Message,
Type = reason.GetType().Name,
DebugData = isDebugEnabled ? reason.InternalMessage : null
}).ToArray(),
RequestId = requestIdProvider.RequestId
}
};
this.StatusCode = response.Status.Code;
this.Value = response;
return base.ExecuteResultAsync(context);
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GeekLearning.Domain.AspnetCore
{
public class MaybeResult<T> : ObjectResult where T : class
{
private Maybe<T> maybe;
public MaybeResult(Maybe<T> maybe) : base(null)
{
this.maybe = maybe;
}
public Maybe<T> Maybe { get; set; }
public override Task ExecuteResultAsync(ActionContext context)
{
var resultMapper = context.HttpContext.RequestServices.GetRequiredService<Internal.MaybeResultMapper>();
var requestIdProvider = context.HttpContext.RequestServices.GetRequiredService<IRequestIdProvider>();
var options = context.HttpContext.RequestServices.GetRequiredService<IOptions<DomainOptions>>();
bool isDebugEnabled = options.Value.Debug;
var response = new Response<T>
{
Content = this.maybe.Value,
Status = new ReponseStatus
{
Code = resultMapper.GetResult(this.maybe.Explanations),
Reasons = (this.maybe.Explanations ?? Enumerable.Empty<Explanations.Explanation>())
.Select(reason => new ResponseExplanation
{
Message = reason.Message,
Type = reason.GetType().Name.Replace("Reason", ""),
DebugData = isDebugEnabled ? reason.InternalMessage : null
}).ToArray(),
RequestId = requestIdProvider.RequestId
}
};
this.StatusCode = response.Status.Code;
this.Value = response;
return base.ExecuteResultAsync(context);
}
}
}
| mit | C# |
a44dc8b34bab91b00010ae7d6c61786a0b997599 | Refactor GetLexiconForTesting closer to real code | sillsdev/LfMerge,ermshiperete/LfMerge,ermshiperete/LfMerge,ermshiperete/LfMerge,sillsdev/LfMerge,sillsdev/LfMerge | src/LfMerge/Actions/UpdateFdoFromMongoDbAction.cs | src/LfMerge/Actions/UpdateFdoFromMongoDbAction.cs | // Copyright (c) 2015 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Linq;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
using LfMerge.LanguageForge.Config;
using LfMerge.LanguageForge.Model;
namespace LfMerge.Actions
{
public class UpdateFdoFromMongoDbAction: Action
{
protected override ProcessingState.SendReceiveStates StateForCurrentAction
{
get { return ProcessingState.SendReceiveStates.QUEUED; }
}
protected override void DoRun(ILfProject project)
{
ILfProjectConfig config = GetConfigForTesting(project);
if (config == null)
return;
IEnumerable<LfLexEntry> lexicon = GetLexiconForTesting(project, config);
foreach (LfLexEntry entry in lexicon)
{
if (entry.Lexeme != null && entry.Lexeme.Values != null)
Console.WriteLine(String.Join(", ", entry.Lexeme.Values.Select(x => (x.Value == null) ? "" : x.Value)));
if (entry.Senses != null) // Beware: the Senses field might not exist
{
foreach(LfSense sense in entry.Senses)
{
if (sense.PartOfSpeech != null)
{
if (sense.PartOfSpeech.Value != null)
Console.Write(" - " + sense.PartOfSpeech.Value);
}
Console.WriteLine();
}
}
}
}
private IEnumerable<LfLexEntry> GetLexiconForTesting(ILfProject project, ILfProjectConfig config)
{
var db = MongoConnection.Default.GetProjectDatabase(project);
var collection = db.GetCollection<LfLexEntry>("lexicon");
IAsyncCursor<LfLexEntry> result2 = collection.Find<LfLexEntry>(_ => true).ToCursorAsync().Result;
return result2.AsEnumerable();
}
private ILfProjectConfig GetConfigForTesting(ILfProject project)
{
MongoProjectRecord projectRecord = MongoProjectRecord.Create(project);
if (projectRecord == null)
{
Console.WriteLine("No project named {0}", project.LfProjectCode);
Console.WriteLine("If we are unit testing, this may not be an error");
return null;
}
ILfProjectConfig config = projectRecord.Config;
Console.WriteLine(config.GetType()); // Should be LfMerge.LanguageForge.Config.LfProjectConfig
Console.WriteLine(config.Entry.Type);
Console.WriteLine(String.Join(", ", config.Entry.FieldOrder));
Console.WriteLine(config.Entry.Fields["lexeme"].Type);
Console.WriteLine(config.Entry.Fields["lexeme"].GetType());
return config;
}
protected override ActionNames NextActionName
{
get { return ActionNames.None; }
}
}
}
| // Copyright (c) 2015 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Linq;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
using LfMerge.LanguageForge.Config;
using LfMerge.LanguageForge.Model;
namespace LfMerge.Actions
{
public class UpdateFdoFromMongoDbAction: Action
{
protected override ProcessingState.SendReceiveStates StateForCurrentAction
{
get { return ProcessingState.SendReceiveStates.QUEUED; }
}
protected override void DoRun(ILfProject project)
{
ILfProjectConfig config = GetConfigForTesting(project);
if (config == null)
return;
GetLexiconForTesting(project, config);
}
private void GetLexiconForTesting(ILfProject project, ILfProjectConfig config)
{
var db = MongoConnection.Default.GetProjectDatabase(project);
var collection = db.GetCollection<LfLexEntry>("lexicon");
// Can't use LINQ here as that requires Mongo server version 2.2 or higher
List<LfLexEntry> result = collection.Find<LfLexEntry>(_ => true).ToListAsync().Result;
foreach (LfLexEntry item in result)
{
Console.WriteLine(String.Join(", ", item.Lexeme.Values.Select(x => x.Value)));
}
// 56332f680f8709ed0fd92d6c is ObjectId for test data. TODO: Actually find by lexicon value
Console.WriteLine("Now trying an enumerable:");
IAsyncCursor<LfLexEntry> result2 = collection.Find<LfLexEntry>(_ => true).ToCursorAsync().Result;
foreach (LfLexEntry item in result2.AsEnumerable())
{
Console.WriteLine(String.Join(", ", item.Lexeme.Values.Select(x => x.Value)));
}
}
private ILfProjectConfig GetConfigForTesting(ILfProject project)
{
MongoProjectRecord projectRecord = MongoProjectRecord.Create(project);
if (projectRecord == null)
{
Console.WriteLine("No project named {0}", project.LfProjectCode);
Console.WriteLine("If we are unit testing, this may not be an error");
return null;
}
ILfProjectConfig config = projectRecord.Config;
Console.WriteLine(config.GetType()); // Should be LfMerge.LanguageForge.Config.LfProjectConfig
Console.WriteLine(config.Entry.Type);
Console.WriteLine(String.Join(", ", config.Entry.FieldOrder));
Console.WriteLine(config.Entry.Fields["lexeme"].Type);
Console.WriteLine(config.Entry.Fields["lexeme"].GetType());
return config;
}
protected override ActionNames NextActionName
{
get { return ActionNames.None; }
}
}
}
| mit | C# |
4015f02f217c25370c2839d77636a62f4250369d | Fix bad format string. | hoopsomuah/orleans,gabikliot/orleans,kowalot/orleans,cato541265/orleans,jokin/orleans,sebastianburckhardt/orleans,brhinescot/orleans,dVakulen/orleans,Liversage/orleans,carlos-sarmiento/orleans,benjaminpetit/orleans,Carlm-MS/orleans,jkonecki/orleans,ticup/orleans,bstauff/orleans,ElanHasson/orleans,jkonecki/orleans,tsibelman/orleans,galvesribeiro/orleans,Joshua-Ferguson/orleans,ashkan-saeedi-mazdeh/orleans,gigya/orleans,SoftWar1923/orleans,amccool/orleans,Liversage/orleans,cbredlow/orleans,kangkot/orleans,sergeybykov/orleans,dariobottazzi/orleans,jokin/orleans,dVakulen/orleans,pherbel/orleans,jthelin/orleans,rrector/orleans,sebastianburckhardt/orleans,dariobottazzi/orleans,waynemunro/orleans,jokin/orleans,Liversage/orleans,yevhen/orleans,amccool/orleans,kylemc/orleans,TedDBarr/orleans,gabikliot/orleans,ElanHasson/orleans,gigya/orleans,hoopsomuah/orleans,ashkan-saeedi-mazdeh/orleans,ibondy/orleans,NaseUkolyCZ/orleans,jason-bragg/orleans,brhinescot/orleans,kowalot/orleans,waynemunro/orleans,dVakulen/orleans,yevhen/orleans,TedDBarr/orleans,rrector/orleans,cato541265/orleans,veikkoeeva/orleans,LoveElectronics/orleans,MikeHardman/orleans,rore/orleans,centur/orleans,shayhatsor/orleans,Carlm-MS/orleans,ashkan-saeedi-mazdeh/orleans,shayhatsor/orleans,centur/orleans,LoveElectronics/orleans,MikeHardman/orleans,dotnet/orleans,garbervetsky/orleans,jdom/orleans,dotnet/orleans,ibondy/orleans,kylemc/orleans,NaseUkolyCZ/orleans,xclayl/orleans,bstauff/orleans,ReubenBond/orleans,rore/orleans,brhinescot/orleans,cbredlow/orleans,xclayl/orleans,galvesribeiro/orleans,carlos-sarmiento/orleans,shlomiw/orleans,SoftWar1923/orleans,sergeybykov/orleans,garbervetsky/orleans,jdom/orleans,ticup/orleans,tsibelman/orleans,kangkot/orleans,shlomiw/orleans,pherbel/orleans,Joshua-Ferguson/orleans,amccool/orleans | src/Orleans/Placement/StatelessWorkerPlacement.cs | src/Orleans/Placement/StatelessWorkerPlacement.cs | /*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Orleans.Runtime
{
[Serializable]
internal class StatelessWorkerPlacement : PlacementStrategy
{
private static int defaultMaxStatelessWorkers = Environment.ProcessorCount;
public int MaxLocal { get; private set; }
internal static void InitializeClass(int defMaxStatelessWorkers)
{
if (defMaxStatelessWorkers < 1)
throw new ArgumentOutOfRangeException("defMaxStatelessWorkers",
"defMaxStatelessWorkers must contain a value greater than zero.");
defaultMaxStatelessWorkers = defMaxStatelessWorkers;
}
internal StatelessWorkerPlacement(int maxLocal = -1)
{
// If maxLocal was not specified on the StatelessWorkerAttribute,
// we will use the defaultMaxStatelessWorkers, which is System.Environment.ProcessorCount.
MaxLocal = maxLocal > 0 ? maxLocal : defaultMaxStatelessWorkers;
}
public override string ToString()
{
return String.Format("StatelessWorkerPlacement(max={0})", MaxLocal);
}
public override bool Equals(object obj)
{
var other = obj as StatelessWorkerPlacement;
return other != null && MaxLocal == other.MaxLocal;
}
public override int GetHashCode()
{
return GetType().GetHashCode() ^ MaxLocal.GetHashCode();
}
}
}
| /*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Orleans.Runtime
{
[Serializable]
internal class StatelessWorkerPlacement : PlacementStrategy
{
private static int defaultMaxStatelessWorkers = Environment.ProcessorCount;
public int MaxLocal { get; private set; }
internal static void InitializeClass(int defMaxStatelessWorkers)
{
if (defMaxStatelessWorkers < 1)
throw new ArgumentOutOfRangeException("defMaxStatelessWorkers",
"defMaxStatelessWorkers must contain a value greater than zero.");
defaultMaxStatelessWorkers = defMaxStatelessWorkers;
}
internal StatelessWorkerPlacement(int maxLocal = -1)
{
// If maxLocal was not specified on the StatelessWorkerAttribute,
// we will use the defaultMaxStatelessWorkers, which is System.Environment.ProcessorCount.
MaxLocal = maxLocal > 0 ? maxLocal : defaultMaxStatelessWorkers;
}
public override string ToString()
{
return String.Format("StatelessWorkerPlacement(max={1})", MaxLocal);
}
public override bool Equals(object obj)
{
var other = obj as StatelessWorkerPlacement;
return other != null && MaxLocal == other.MaxLocal;
}
public override int GetHashCode()
{
return GetType().GetHashCode() ^ MaxLocal.GetHashCode();
}
}
}
| mit | C# |
43ecf253d6606bb329724d0df5bbb0e86b39423c | Make a method static because it can be | bungeemonkee/Configgy | Configgy/Coercion/ValueCoercerAttributeBase.cs | Configgy/Coercion/ValueCoercerAttributeBase.cs | using System;
using System.Reflection;
namespace Configgy.Coercion
{
/// <summary>
/// A base class for any coercer attributes.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public abstract class ValueCoercerAttributeBase : Attribute, IValueCoercer
{
private static readonly Type NullableType = typeof(Nullable<>);
/// <summary>
/// Coerce the raw string value into the expected result type.
/// </summary>
/// <typeparam name="T">The expected result type after coercion.</typeparam>
/// <param name="value">The raw string value to be coerced.</param>
/// <param name="valueName">The name of the value to be coerced.</param>
/// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
/// <param name="result">The coerced value.</param>
/// <returns>True if the value could be coerced, false otherwise.</returns>
public abstract bool Coerce<T>(string value, string valueName, PropertyInfo property, out T result);
protected static bool IsNullable<T>()
{
var type = typeof(T);
return type.IsClass || (type.IsGenericType && type.GetGenericTypeDefinition() == NullableType);
}
}
}
| using System;
using System.Reflection;
namespace Configgy.Coercion
{
/// <summary>
/// A base class for any coercer attributes.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public abstract class ValueCoercerAttributeBase : Attribute, IValueCoercer
{
private static readonly Type NullableType = typeof(Nullable<>);
/// <summary>
/// Coerce the raw string value into the expected result type.
/// </summary>
/// <typeparam name="T">The expected result type after coercion.</typeparam>
/// <param name="value">The raw string value to be coerced.</param>
/// <param name="valueName">The name of the value to be coerced.</param>
/// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
/// <param name="result">The coerced value.</param>
/// <returns>True if the value could be coerced, false otherwise.</returns>
public abstract bool Coerce<T>(string value, string valueName, PropertyInfo property, out T result);
protected bool IsNullable<T>()
{
var type = typeof(T);
return type.IsClass || (type.IsGenericType && type.GetGenericTypeDefinition() == NullableType);
}
}
}
| mit | C# |
92d558f3d06e8120146637bbb03d4cd0b6b95516 | Implement the string table. | KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog | src/StructuredLogger/Serialization/StringTable.cs | src/StructuredLogger/Serialization/StringTable.cs | using System.Collections.Generic;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class StringTable
{
private Dictionary<string, string> deduplicationMap = new Dictionary<string, string>();
public string Intern(string text)
{
string existing;
if (deduplicationMap.TryGetValue(text, out existing))
{
return existing;
}
deduplicationMap[text] = text;
return text;
}
}
}
| namespace Microsoft.Build.Logging.StructuredLogger
{
public class StringTable
{
public string Intern(string value)
{
return value;
}
}
}
| mit | C# |
39e901d7701eee0cb7e5309d2c073efd065ad888 | Update ifdefs | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MRTK/Examples/Demos/HandTracking/Scripts/LeapMotionOrientationDisplay.cs | Assets/MRTK/Examples/Demos/HandTracking/Scripts/LeapMotionOrientationDisplay.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
using Microsoft.MixedReality.Toolkit.Input;
using TMPro;
#if (LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE) || (LEAPMOTIONCORE_PRESENT && UNITY_WSA && UNITY_EDITOR)
using Microsoft.MixedReality.Toolkit.LeapMotion.Input;
#endif
namespace Microsoft.MixedReality.Toolkit.Examples
{
/// <summary>
/// Returns the orientation of Leap Motion Controller
/// </summary>
public class LeapMotionOrientationDisplay : MonoBehaviour
{
#if (LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE) || (LEAPMOTIONCORE_PRESENT && UNITY_WSA && UNITY_EDITOR)
[SerializeField]
private TextMeshProUGUI orientationText;
private LeapMotionDeviceManagerProfile managerProfile;
private void Start()
{
if (GetLeapManager())
{
orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString();
}
else
{
orientationText.text = "Orientation: Unavailable";
}
}
private LeapMotionDeviceManagerProfile GetLeapManager()
{
if (!MixedRealityToolkit.Instance.ActiveProfile)
{
return null;
}
foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations)
{
if (config.ComponentType == typeof(LeapMotionDeviceManager))
{
managerProfile = (LeapMotionDeviceManagerProfile)config.Profile;
return managerProfile;
}
}
return null;
}
#endif
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
using Microsoft.MixedReality.Toolkit.Input;
using TMPro;
#if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE
using Microsoft.MixedReality.Toolkit.LeapMotion.Input;
#endif
namespace Microsoft.MixedReality.Toolkit.Examples
{
/// <summary>
/// Returns the orientation of Leap Motion Controller
/// </summary>
public class LeapMotionOrientationDisplay : MonoBehaviour
{
#if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE
[SerializeField]
private TextMeshProUGUI orientationText;
private LeapMotionDeviceManagerProfile managerProfile;
private void Start()
{
if (GetLeapManager())
{
orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString();
}
else
{
orientationText.text = "Orientation: Unavailable";
}
}
private LeapMotionDeviceManagerProfile GetLeapManager()
{
if (!MixedRealityToolkit.Instance.ActiveProfile)
{
return null;
}
foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations)
{
if (config.ComponentType == typeof(LeapMotionDeviceManager))
{
managerProfile = (LeapMotionDeviceManagerProfile)config.Profile;
return managerProfile;
}
}
return null;
}
#endif
}
}
| mit | C# |
3fbd157c947dbd90cc912730bfc041596bbe901a | remove explicit issuer | chrisowhite/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,jbijlsma/IdentityServer4,chrisowhite/IdentityServer4,chrisowhite/IdentityServer4,IdentityServer/IdentityServer4,siyo-wang/IdentityServer4,siyo-wang/IdentityServer4,MienDev/IdentityServer4,siyo-wang/IdentityServer4 | src/Host/Startup.cs | src/Host/Startup.cs | using Host.Configuration;
using Host.Extensions;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using System.IO;
using System.Security.Cryptography.X509Certificates;
namespace Host
{
public class Startup
{
private readonly IApplicationEnvironment _environment;
public Startup(IApplicationEnvironment environment)
{
_environment = environment;
}
public void ConfigureServices(IServiceCollection services)
{
var cert = new X509Certificate2(Path.Combine(_environment.ApplicationBasePath, "idsrv3test.pfx"), "idsrv3test");
var builder = services.AddIdentityServer(options =>
{
options.SigningCertificate = cert;
});
builder.AddInMemoryClients(Clients.Get());
builder.AddInMemoryScopes(Scopes.Get());
builder.AddInMemoryUsers(Users.Get());
builder.AddCustomGrantValidator<CustomGrantValidator>();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Verbose);
loggerFactory.AddDebug(LogLevel.Verbose);
app.UseDeveloperExceptionPage();
app.UseIISPlatformHandler();
app.UseIdentityServer();
}
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
} | using Host.Configuration;
using Host.Extensions;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using System.IO;
using System.Security.Cryptography.X509Certificates;
namespace Host
{
public class Startup
{
private readonly IApplicationEnvironment _environment;
public Startup(IApplicationEnvironment environment)
{
_environment = environment;
}
public void ConfigureServices(IServiceCollection services)
{
var cert = new X509Certificate2(Path.Combine(_environment.ApplicationBasePath, "idsrv3test.pfx"), "idsrv3test");
var builder = services.AddIdentityServer(options =>
{
options.SigningCertificate = cert;
options.IssuerUri = "https://idsrv4";
options.DiscoveryOptions.CustomEntries.Add("foo", "bar");
});
builder.AddInMemoryClients(Clients.Get());
builder.AddInMemoryScopes(Scopes.Get());
builder.AddInMemoryUsers(Users.Get());
builder.AddCustomGrantValidator<CustomGrantValidator>();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Verbose);
loggerFactory.AddDebug(LogLevel.Verbose);
app.UseDeveloperExceptionPage();
app.UseIISPlatformHandler();
app.UseIdentityServer();
}
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
} | apache-2.0 | C# |
c18aec0b209d36e5da5c5c1fda2abde2bf08a917 | Update WavChannelMask.cs | wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter | WavFile/WavChannelMask.cs | WavFile/WavChannelMask.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace WavFile
{
#region References
using System;
#endregion
#region WavChannelMask
/// <summary>
/// Multi-channel WAV file mask
/// </summary>
public enum WavChannelMask
{
SPEAKER_FRONT_LEFT = 0x1,
SPEAKER_FRONT_RIGHT = 0x2,
SPEAKER_FRONT_CENTER = 0x4,
SPEAKER_LOW_FREQUENCY = 0x8,
SPEAKER_BACK_LEFT = 0x10,
SPEAKER_BACK_RIGHT = 0x20,
SPEAKER_FRONT_LEFT_OF_CENTER = 0x40,
SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80,
SPEAKER_BACK_CENTER = 0x100,
SPEAKER_SIDE_LEFT = 0x200,
SPEAKER_SIDE_RIGHT = 0x400,
SPEAKER_TOP_CENTER = 0x800,
SPEAKER_TOP_FRONT_LEFT = 0x1000,
SPEAKER_TOP_FRONT_CENTER = 0x2000,
SPEAKER_TOP_FRONT_RIGHT = 0x4000,
SPEAKER_TOP_BACK_LEFT = 0x8000,
SPEAKER_TOP_BACK_CENTER = 0x10000,
SPEAKER_TOP_BACK_RIGHT = 0x20000
}
#endregion
}
| /*
* WavFile
* Copyright © Wiesław Šoltés 2010-2012. All Rights Reserved
*/
namespace WavFile
{
#region References
using System;
#endregion
#region WavChannelMask
/// <summary>
/// Multi-channel WAV file mask
/// </summary>
public enum WavChannelMask
{
SPEAKER_FRONT_LEFT = 0x1,
SPEAKER_FRONT_RIGHT = 0x2,
SPEAKER_FRONT_CENTER = 0x4,
SPEAKER_LOW_FREQUENCY = 0x8,
SPEAKER_BACK_LEFT = 0x10,
SPEAKER_BACK_RIGHT = 0x20,
SPEAKER_FRONT_LEFT_OF_CENTER = 0x40,
SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80,
SPEAKER_BACK_CENTER = 0x100,
SPEAKER_SIDE_LEFT = 0x200,
SPEAKER_SIDE_RIGHT = 0x400,
SPEAKER_TOP_CENTER = 0x800,
SPEAKER_TOP_FRONT_LEFT = 0x1000,
SPEAKER_TOP_FRONT_CENTER = 0x2000,
SPEAKER_TOP_FRONT_RIGHT = 0x4000,
SPEAKER_TOP_BACK_LEFT = 0x8000,
SPEAKER_TOP_BACK_CENTER = 0x10000,
SPEAKER_TOP_BACK_RIGHT = 0x20000
}
#endregion
}
| mit | C# |
916cecbaa204c2fa8044f170ede4f606b7ac7c9e | Update parameter help text | allansson/Calamari,allansson/Calamari | source/Calamari/Commands/RunScriptCommand.cs | source/Calamari/Commands/RunScriptCommand.cs | using System.IO;
using Calamari.Commands.Support;
using Calamari.Deployment;
using Calamari.Integration.FileSystem;
using Calamari.Integration.Processes;
using Calamari.Integration.Scripting;
using Calamari.Integration.ServiceMessages;
using Octostache;
namespace Calamari.Commands
{
[Command("run-script", Description = "Invokes a PowerShell or ScriptCS script")]
public class RunScriptCommand : Command
{
private string variablesFile;
private string scriptFile;
private string sensitiveVariablesFile;
private string sensitiveVariablesPassword;
public RunScriptCommand()
{
Options.Add("variables=", "Path to a JSON file containing variables.", v => variablesFile = Path.GetFullPath(v));
Options.Add("script=", "Path to the script (PowerShell or ScriptCS) script to execute.", v => scriptFile = Path.GetFullPath(v));
Options.Add("sensitiveVariables=", "Password protected JSON file containing sensitive-variables.", v => sensitiveVariablesFile = v);
Options.Add("sensitiveVariablesPassword=", "Password used to decrypt sensitive-variables.", v => sensitiveVariablesPassword = v);
}
public override int Execute(string[] commandLineArguments)
{
Options.Parse(commandLineArguments);
var variables = new CalamariVariableDictionary(variablesFile, sensitiveVariablesFile, sensitiveVariablesPassword);
variables.EnrichWithEnvironmentVariables();
variables.LogVariables();
return InvokeScript(variables);
}
private int InvokeScript(CalamariVariableDictionary variables)
{
if (!File.Exists(scriptFile))
throw new CommandException("Could not find script file: " + scriptFile);
var scriptEngine = new CombinedScriptEngine();
var runner = new CommandLineRunner(
new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables)));
var result = scriptEngine.Execute(scriptFile, variables, runner);
return result.ExitCode;
}
}
}
| using System.IO;
using Calamari.Commands.Support;
using Calamari.Deployment;
using Calamari.Integration.FileSystem;
using Calamari.Integration.Processes;
using Calamari.Integration.Scripting;
using Calamari.Integration.ServiceMessages;
using Octostache;
namespace Calamari.Commands
{
[Command("run-script", Description = "Invokes a PowerShell or ScriptCS script")]
public class RunScriptCommand : Command
{
private string variablesFile;
private string scriptFile;
private string sensitiveVariablesFile;
private string sensitiveVariablesPassword;
public RunScriptCommand()
{
Options.Add("variables=", "Path to a JSON file containing variables.", v => variablesFile = Path.GetFullPath(v));
Options.Add("script=", "Path to the script (PowerShell or ScriptCS) script to execute.", v => scriptFile = Path.GetFullPath(v));
Options.Add("sensitiveVariables=", "Password protected JSON file containing sensitive-variables.", v => sensitiveVariablesFile = v);
Options.Add("sensitiveVariablesPassword=", "Password used to decrypt sensitive-variables (only applicable to offline-drop deployments).", v => sensitiveVariablesPassword = v);
}
public override int Execute(string[] commandLineArguments)
{
Options.Parse(commandLineArguments);
var variables = new CalamariVariableDictionary(variablesFile, sensitiveVariablesFile, sensitiveVariablesPassword);
variables.EnrichWithEnvironmentVariables();
variables.LogVariables();
return InvokeScript(variables);
}
private int InvokeScript(CalamariVariableDictionary variables)
{
if (!File.Exists(scriptFile))
throw new CommandException("Could not find script file: " + scriptFile);
var scriptEngine = new CombinedScriptEngine();
var runner = new CommandLineRunner(
new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables)));
var result = scriptEngine.Execute(scriptFile, variables, runner);
return result.ExitCode;
}
}
}
| apache-2.0 | C# |
2bb646adc4845c6166a8caca42dd91ccdec2bc62 | Update project settings | sakapon/Samples-2015 | BuildSample/EmptyConsole/Properties/AssemblyInfo.cs | BuildSample/EmptyConsole/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("EmptyConsole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EmptyConsole")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("0e18bacc-ad8f-443d-9376-d874391a5d1b")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("EmptyConsole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EmptyConsole")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("0e18bacc-ad8f-443d-9376-d874391a5d1b")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
5410efac835f6f5ed1f7dcdea2020caf930bc256 | Allow sessions to be created with a user-specified key. addressing #4 | 0xdeafcafe/luno-dotnet | src/LunoClient/Models/Session/CreateSession.cs | src/LunoClient/Models/Session/CreateSession.cs | using System;
using Newtonsoft.Json;
namespace Luno.Models.Session
{
public class CreateSession<T>
{
[JsonProperty("user_id", NullValueHandling = NullValueHandling.Ignore)]
public string UserId { get; set; }
[JsonProperty("ip")]
public string Ip { get; set; }
/// <summary>
/// Secure session key.
/// </summary>
/// <remarks>
/// Defaults to a 32-byte cryptographically secure hexadecimal string
/// </remarks>
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("expires")]
public DateTime? Expires { get; set; } = DateTime.UtcNow.AddDays(14);
[JsonProperty("user_agent")]
public string UserAgent { get; set; }
[JsonProperty("details", NullValueHandling = NullValueHandling.Ignore)]
public T Details { get; set; }
}
}
| using System;
using Newtonsoft.Json;
namespace Luno.Models.Session
{
public class CreateSession<T>
{
[JsonProperty("user_id", NullValueHandling = NullValueHandling.Ignore)]
public string UserId { get; set; }
[JsonProperty("ip")]
public string Ip { get; set; }
[JsonProperty("expires")]
public DateTime? Expires { get; set; } = DateTime.UtcNow.AddDays(14);
[JsonProperty("user_agent")]
public string UserAgent { get; set; }
[JsonProperty("details", NullValueHandling = NullValueHandling.Ignore)]
public T Details { get; set; }
}
}
| mit | C# |
8d5cddeda9874b46cbcffb9986862243a516204e | Use ExceptionDispatchInfo to rethrow test class constructor exceptions, now that all other such exception rethrows use ExceptionDispatchInfo. | fixie/fixie | src/Fixie/TestClass.cs | src/Fixie/TestClass.cs | namespace Fixie
{
using System;
using System.Reflection;
using System.Runtime.ExceptionServices;
using Internal;
/// <summary>
/// The context in which a test class is running.
/// </summary>
public class TestClass
{
readonly Action<Action<Case>> runCases;
readonly bool isStatic;
internal TestClass(Type type, Action<Action<Case>> runCases) : this(type, runCases, null) { }
internal TestClass(Type type, Action<Action<Case>> runCases, MethodInfo targetMethod)
{
this.runCases = runCases;
Type = type;
TargetMethod = targetMethod;
isStatic = Type.IsStatic();
}
/// <summary>
/// The test class to execute.
/// </summary>
public Type Type { get; }
/// <summary>
/// Gets the target MethodInfo identified by the
/// test runner as the sole method to be executed.
/// Null under normal test execution.
/// </summary>
public MethodInfo TargetMethod { get; }
/// <summary>
/// Constructs an instance of the test class type, using its default constructor.
/// If the class is static, no action is taken and null is returned.
/// </summary>
public object Construct()
{
if (isStatic)
return null;
try
{
return Activator.CreateInstance(Type);
}
catch (TargetInvocationException exception)
{
ExceptionDispatchInfo.Capture(exception.InnerException).Throw();
throw; //Unreachable.
}
}
public void RunCases(Action<Case> caseLifecycle)
{
runCases(caseLifecycle);
}
}
} | namespace Fixie
{
using System;
using System.Reflection;
using Internal;
/// <summary>
/// The context in which a test class is running.
/// </summary>
public class TestClass
{
readonly Action<Action<Case>> runCases;
readonly bool isStatic;
internal TestClass(Type type, Action<Action<Case>> runCases) : this(type, runCases, null) { }
internal TestClass(Type type, Action<Action<Case>> runCases, MethodInfo targetMethod)
{
this.runCases = runCases;
Type = type;
TargetMethod = targetMethod;
isStatic = Type.IsStatic();
}
/// <summary>
/// The test class to execute.
/// </summary>
public Type Type { get; }
/// <summary>
/// Gets the target MethodInfo identified by the
/// test runner as the sole method to be executed.
/// Null under normal test execution.
/// </summary>
public MethodInfo TargetMethod { get; }
/// <summary>
/// Constructs an instance of the test class type, using its default constructor.
/// If the class is static, no action is taken and null is returned.
/// </summary>
public object Construct()
{
if (isStatic)
return null;
try
{
return Activator.CreateInstance(Type);
}
catch (TargetInvocationException exception)
{
throw new PreservedException(exception.InnerException);
}
}
public void RunCases(Action<Case> caseLifecycle)
{
runCases(caseLifecycle);
}
}
} | mit | C# |
b0034355c0557cf21161a72d6a403d4a495707a7 | Add VTexExtraData COMPRESSED_MIP_SIZE | SteamDatabase/ValveResourceFormat | ValveResourceFormat/Resource/Enums/VTexExtraData.cs | ValveResourceFormat/Resource/Enums/VTexExtraData.cs | using System;
namespace ValveResourceFormat
{
public enum VTexExtraData
{
#pragma warning disable 1591
UNKNOWN = 0,
FALLBACK_BITS = 1,
SHEET = 2,
FILL_TO_POWER_OF_TWO = 3,
COMPRESSED_MIP_SIZE = 4,
#pragma warning restore 1591
}
}
| using System;
namespace ValveResourceFormat
{
public enum VTexExtraData
{
#pragma warning disable 1591
UNKNOWN = 0,
FALLBACK_BITS = 1,
SHEET = 2,
FILL_TO_POWER_OF_TWO = 3,
#pragma warning restore 1591
}
}
| mit | C# |
1c159f38d34863994587390879983538b78b5f81 | Change BuildAndOrExpr to use AndAlso & OrElse to make NHibernate Linq happy | Breeze/breeze.server.net,Breeze/breeze.server.net,Breeze/breeze.server.net,Breeze/breeze.server.net | AspNetCore-v3/Breeze.Core/Query/AndOrPredicate.cs | AspNetCore-v3/Breeze.Core/Query/AndOrPredicate.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Breeze.Core {
/**
* @author IdeaBlade
*
*/
public class AndOrPredicate : BasePredicate {
private List<BasePredicate> _predicates;
public AndOrPredicate(Operator op, params BasePredicate[] predicates) : this(op, predicates.ToList()) {
}
public AndOrPredicate(Operator op, IEnumerable<BasePredicate> predicates) : base(op) {
_predicates = predicates.ToList();
}
public IEnumerable<BasePredicate> Predicates {
get { return _predicates.AsReadOnly(); }
}
public override void Validate(Type entityType) {
_predicates.ForEach(p => p.Validate(entityType));
}
public override Expression ToExpression(ParameterExpression paramExpr) {
var exprs = _predicates.Select(p => p.ToExpression(paramExpr));
return BuildAndOrExpr(exprs, Operator);
}
private Expression BuildAndOrExpr(IEnumerable<Expression> exprs, Operator op) {
if (op == Operator.And) {
return exprs.Aggregate((result, expr) => Expression.AndAlso(result, expr));
} else if (op == Operator.Or) {
return exprs.Aggregate((result, expr) => Expression.OrElse(result, expr));
} else {
throw new Exception("Invalid AndOr operator " + op.Name);
}
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Breeze.Core {
/**
* @author IdeaBlade
*
*/
public class AndOrPredicate : BasePredicate {
private List<BasePredicate> _predicates;
public AndOrPredicate(Operator op, params BasePredicate[] predicates) : this(op, predicates.ToList()) {
}
public AndOrPredicate(Operator op, IEnumerable<BasePredicate> predicates) : base(op) {
_predicates = predicates.ToList();
}
public IEnumerable<BasePredicate> Predicates {
get { return _predicates.AsReadOnly(); }
}
public override void Validate(Type entityType) {
_predicates.ForEach(p => p.Validate(entityType));
}
public override Expression ToExpression(ParameterExpression paramExpr) {
var exprs = _predicates.Select(p => p.ToExpression(paramExpr));
return BuildAndOrExpr(exprs, Operator);
}
private Expression BuildAndOrExpr(IEnumerable<Expression> exprs, Operator op) {
if (op == Operator.And) {
return exprs.Aggregate((result, expr) => Expression.And(result, expr));
} else if (op == Operator.Or) {
return exprs.Aggregate((result, expr) => Expression.Or(result, expr));
} else {
throw new Exception("Invalid AndOr operator" + op.Name);
}
}
}
} | mit | C# |
921537f15254481600da59dfe5aee09ee04315d6 | Validate ReadOnlyCollection constructor inputs | cgourlay/cecil,joj/cecil,fnajera-rac-de/cecil,saynomoo/cecil,gluck/cecil,furesoft/cecil,sailro/cecil,SiliconStudio/Mono.Cecil,jbevain/cecil,mono/cecil,kzu/cecil,xen2/cecil,ttRevan/cecil | Mono.Collections.Generic/ReadOnlyCollection.cs | Mono.Collections.Generic/ReadOnlyCollection.cs | //
// ReadOnlyCollection.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
namespace Mono.Collections.Generic {
public sealed class ReadOnlyCollection<T> : Collection<T>, IList {
static ReadOnlyCollection<T> empty;
public static ReadOnlyCollection<T> Empty {
get { return empty ?? (empty = new ReadOnlyCollection<T> ()); }
}
bool IList.IsReadOnly {
get { return true; }
}
private ReadOnlyCollection ()
{
}
public ReadOnlyCollection (T [] array)
{
if (array == null)
throw new ArgumentNullException ();
this.items = array;
this.size = array.Length;
}
public ReadOnlyCollection (Collection<T> collection)
{
if (collection == null)
throw new ArgumentNullException ();
this.items = collection.items;
this.size = collection.size;
}
internal override void Grow (int desired)
{
throw new InvalidOperationException ();
}
protected override void OnAdd (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnClear ()
{
throw new InvalidOperationException ();
}
protected override void OnInsert (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnRemove (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnSet (T item, int index)
{
throw new InvalidOperationException ();
}
}
}
| //
// ReadOnlyCollection.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
namespace Mono.Collections.Generic {
public sealed class ReadOnlyCollection<T> : Collection<T>, IList {
static ReadOnlyCollection<T> empty;
public static ReadOnlyCollection<T> Empty {
get { return empty ?? (empty = new ReadOnlyCollection<T> ()); }
}
bool IList.IsReadOnly {
get { return true; }
}
private ReadOnlyCollection ()
{
}
public ReadOnlyCollection (T [] array)
{
this.items = array;
this.size = array.Length;
}
public ReadOnlyCollection (Collection<T> collection)
{
this.items = collection.items;
this.size = collection.size;
}
internal override void Grow (int desired)
{
throw new InvalidOperationException ();
}
protected override void OnAdd (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnClear ()
{
throw new InvalidOperationException ();
}
protected override void OnInsert (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnRemove (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnSet (T item, int index)
{
throw new InvalidOperationException ();
}
}
}
| mit | C# |
4883189bf0ae635aea43114fb22d53517a17d8ea | update main layout with app name | tblocksharer/tblocksharer,tblocksharer/tblocksharer | src/TBlockSharer/Views/Shared/_Layout.cshtml | src/TBlockSharer/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - TBlockSharer</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("TBlockSharer", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| agpl-3.0 | C# |
61ea3f2e6410980341803eb2c4548e917229ee3e | Remove unnecessary test step creating needless skins | UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu | osu.Game.Tests/Visual/Gameplay/TestSceneSkinEditor.cs | osu.Game.Tests/Visual/Gameplay/TestSceneSkinEditor.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Skinning.Editor;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSkinEditor : PlayerTestScene
{
private SkinEditor skinEditor;
[Resolved]
private SkinManager skinManager { get; set; }
[SetUpSteps]
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("reload skin editor", () =>
{
skinEditor?.Expire();
Player.ScaleTo(SkinEditorOverlay.VISIBLE_TARGET_SCALE);
LoadComponentAsync(skinEditor = new SkinEditor(Player), Add);
});
}
[Test]
public void TestToggleEditor()
{
AddToggleStep("toggle editor visibility", visible => skinEditor.ToggleVisibility());
}
protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Skinning.Editor;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSkinEditor : PlayerTestScene
{
private SkinEditor skinEditor;
[Resolved]
private SkinManager skinManager { get; set; }
[SetUpSteps]
public override void SetUpSteps()
{
AddStep("set empty legacy skin", () =>
{
var imported = skinManager.Import(new SkinInfo { Name = "test skin" }).Result;
skinManager.CurrentSkinInfo.Value = imported;
});
base.SetUpSteps();
AddStep("reload skin editor", () =>
{
skinEditor?.Expire();
Player.ScaleTo(SkinEditorOverlay.VISIBLE_TARGET_SCALE);
LoadComponentAsync(skinEditor = new SkinEditor(Player), Add);
});
}
[Test]
public void TestToggleEditor()
{
AddToggleStep("toggle editor visibility", visible => skinEditor.ToggleVisibility());
}
protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
}
}
| mit | C# |
663ffae42f9b8e97037e7f4c3ba06b8acb68d600 | Fix hit object selection blueprint potential null reference | UselessToucan/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu | osu.Game/Rulesets/Edit/HitObjectSelectionBlueprint.cs | osu.Game/Rulesets/Edit/HitObjectSelectionBlueprint.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Primitives;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osuTK;
namespace osu.Game.Rulesets.Edit
{
public abstract class HitObjectSelectionBlueprint : SelectionBlueprint<HitObject>
{
/// <summary>
/// The <see cref="DrawableHitObject"/> which this <see cref="HitObjectSelectionBlueprint"/> applies to.
/// </summary>
public DrawableHitObject DrawableObject { get; internal set; }
/// <summary>
/// Whether the blueprint should be shown even when the <see cref="DrawableObject"/> is not alive.
/// </summary>
protected virtual bool AlwaysShowWhenSelected => false;
protected override bool ShouldBeAlive => (DrawableObject?.IsAlive == true && DrawableObject.IsPresent) || (AlwaysShowWhenSelected && State == SelectionState.Selected);
protected HitObjectSelectionBlueprint(HitObject hitObject)
: base(hitObject)
{
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => DrawableObject.ReceivePositionalInputAt(screenSpacePos);
public override Vector2 ScreenSpaceSelectionPoint => DrawableObject.ScreenSpaceDrawQuad.Centre;
public override Quad SelectionQuad => DrawableObject.ScreenSpaceDrawQuad;
}
public abstract class HitObjectSelectionBlueprint<T> : HitObjectSelectionBlueprint
where T : HitObject
{
public T HitObject => (T)Item;
protected HitObjectSelectionBlueprint(T item)
: base(item)
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Primitives;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osuTK;
namespace osu.Game.Rulesets.Edit
{
public abstract class HitObjectSelectionBlueprint : SelectionBlueprint<HitObject>
{
/// <summary>
/// The <see cref="DrawableHitObject"/> which this <see cref="HitObjectSelectionBlueprint"/> applies to.
/// </summary>
public DrawableHitObject DrawableObject { get; internal set; }
/// <summary>
/// Whether the blueprint should be shown even when the <see cref="DrawableObject"/> is not alive.
/// </summary>
protected virtual bool AlwaysShowWhenSelected => false;
protected override bool ShouldBeAlive => (DrawableObject.IsAlive && DrawableObject.IsPresent) || (AlwaysShowWhenSelected && State == SelectionState.Selected);
protected HitObjectSelectionBlueprint(HitObject hitObject)
: base(hitObject)
{
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => DrawableObject.ReceivePositionalInputAt(screenSpacePos);
public override Vector2 ScreenSpaceSelectionPoint => DrawableObject.ScreenSpaceDrawQuad.Centre;
public override Quad SelectionQuad => DrawableObject.ScreenSpaceDrawQuad;
}
public abstract class HitObjectSelectionBlueprint<T> : HitObjectSelectionBlueprint
where T : HitObject
{
public T HitObject => (T)Item;
protected HitObjectSelectionBlueprint(T item)
: base(item)
{
}
}
}
| mit | C# |
0515e91b89998c8f01ca46a07ff08bdc4d82e425 | update assembly info | Blue0500/JoshuaKearney.Measurements | JoshuaKearney.Measurements/JoshuaKearney.Measurements/Properties/AssemblyInfo.cs | JoshuaKearney.Measurements/JoshuaKearney.Measurements/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
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("JoshuaKearney.Measurements")]
[assembly: AssemblyDescription("A simple liblrary for representing units in a type safe way")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Josh Kearney")]
[assembly: AssemblyProduct("JoshuaKearney.Measurements")]
[assembly: AssemblyCopyright("Copyright © 2016 Josh Kearney")]
[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.1.0")]
[assembly: AssemblyFileVersion("1.0.1.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("JoshuaKearney.Measurements")]
[assembly: AssemblyDescription("A simple liblrary for representing units in a type safe way")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Josh Kearney")]
[assembly: AssemblyProduct("JoshuaKearney.Measurements")]
[assembly: AssemblyCopyright("Copyright © 2016 Josh Kearney")]
[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# |
3c4579fa0b5bf4c9f79e16053d590f3996648830 | Enable FailingTest | AccelerateX-org/WiQuiz,AccelerateX-org/WiQuiz | Sources/WiQuest/WIQuest.Web.Tests/TestClass.cs | Sources/WiQuest/WIQuest.Web.Tests/TestClass.cs | using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using WIQuest.Web.Utils;
namespace WIQuest.Web.Tests
{
[TestFixture]
public class TestClass
{
[Test]
public void PassingTest()
{
Assert.AreEqual(4, Add(2, 2));
}
[Test]
public void FailingTest()
{
Assert.AreEqual(5, Add(2, 2));
}
[Test]
public void AmIReallyShufflingEveryday()
{
// Prepare Mock
var numbersToShuffle = new List<int>(Enumerable.Range(1, 75));
var numbersToCompare = new List<int>(Enumerable.Range(1, 75));
// Lists should be the same 1...75
Assert.True(numbersToCompare.Intersect(numbersToShuffle).SequenceEqual(numbersToShuffle));
// Using Method under Test
numbersToShuffle.Shuffle();
// List should now differ
Assert.False(numbersToCompare.Intersect(numbersToShuffle).SequenceEqual(numbersToShuffle));
}
static int Add(int x, int y)
{
return x + y;
}
}
} | using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using WIQuest.Web.Utils;
namespace WIQuest.Web.Tests
{
[TestFixture]
public class TestClass
{
[Test]
public void PassingTest()
{
Assert.AreEqual(4, Add(2, 2));
}
[Test]
[Ignore("Ignored")]
public void FailingTest()
{
Assert.AreEqual(5, Add(2, 2));
}
[Test]
public void AmIReallyShufflingEveryday()
{
// Prepare Mock
var numbersToShuffle = new List<int>(Enumerable.Range(1, 75));
var numbersToCompare = new List<int>(Enumerable.Range(1, 75));
// Lists should be the same 1...75
Assert.True(numbersToCompare.Intersect(numbersToShuffle).SequenceEqual(numbersToShuffle));
// Using Method under Test
numbersToShuffle.Shuffle();
// List should now differ
Assert.False(numbersToCompare.Intersect(numbersToShuffle).SequenceEqual(numbersToShuffle));
}
static int Add(int x, int y)
{
return x + y;
}
}
} | mit | C# |
6d4d39a0e3d025c7fea1b30cc6d9dcd933b3f0f5 | Revert vresion number for intermediate release | rajashekarusa/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core,phillipharding/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,phillipharding/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core | Core/OfficeDevPnP.Core/Properties/AssemblyInfo.cs | Core/OfficeDevPnP.Core/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
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("OfficeDevPnP.Core")]
#if SP2013
[assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint 2013")]
#elif SP2016
[assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint 2016")]
#else
[assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint Online")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OfficeDevPnP.Core")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
// 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("065331b6-0540-44e1-84d5-d38f09f17f9e")]
// 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:
// Convention:
// Major version = current version 2
// Minor version = Sequence...version 0 was with January release...so 1=Feb 2=Mar, 3=Apr, 4=May, 5=Jun, 6=Aug, 7=Sept,...
// Third part = version indenpendant showing the release month in YYMM
// Fourth part = 0 normally or a sequence number when we do an emergency release
[assembly: AssemblyVersion("2.5.1606.2")]
[assembly: AssemblyFileVersion("2.5.1606.2")]
[assembly: InternalsVisibleTo("OfficeDevPnP.Core.Tests")] | using System.Reflection;
using System.Resources;
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("OfficeDevPnP.Core")]
#if SP2013
[assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint 2013")]
#elif SP2016
[assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint 2016")]
#else
[assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint Online")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OfficeDevPnP.Core")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
// 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("065331b6-0540-44e1-84d5-d38f09f17f9e")]
// 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:
// Convention:
// Major version = current version 2
// Minor version = Sequence...version 0 was with January release...so 1=Feb 2=Mar, 3=Apr, 4=May, 5=Jun, 6=Aug, 7=Sept,...
// Third part = version indenpendant showing the release month in YYMM
// Fourth part = 0 normally or a sequence number when we do an emergency release
[assembly: AssemblyVersion("2.6.1608.0")]
[assembly: AssemblyFileVersion("2.6.1608.0")]
[assembly: InternalsVisibleTo("OfficeDevPnP.Core.Tests")] | mit | C# |
f6d3d5dd69f4ba7cbe9b96fcb0e85aa8b2757825 | update MeanAbsoluteDeviation to use a simple moving average for the mean calculation and update tests accordingly | racksen/Lean,JKarathiya/Lean,FrancisGauthier/Lean,Obawoba/Lean,Jay-Jay-D/LeanSTP,bizcad/LeanJJN,bizcad/Lean,JKarathiya/Lean,Obawoba/Lean,jameschch/Lean,AnObfuscator/Lean,devalkeralia/Lean,young-zhang/Lean,racksen/Lean,StefanoRaggi/Lean,AnObfuscator/Lean,Phoenix1271/Lean,Phoenix1271/Lean,Neoracle/Lean,AnshulYADAV007/Lean,squideyes/Lean,devalkeralia/Lean,a-hart/Lean,florentchandelier/Lean,rchien/Lean,andrewhart098/Lean,QuantConnect/Lean,redmeros/Lean,a-hart/Lean,jameschch/Lean,mabeale/Lean,exhau/Lean,Jay-Jay-D/LeanSTP,wowgeeker/Lean,bdilber/Lean,wowgeeker/Lean,StefanoRaggi/Lean,rchien/Lean,bdilber/Lean,bdilber/Lean,Phoenix1271/Lean,bizcad/LeanAbhi,andrewhart098/Lean,bizcad/LeanJJN,StefanoRaggi/Lean,squideyes/Lean,bizcad/Lean,bizcad/LeanITrend,AlexCatarino/Lean,desimonk/Lean,Mendelone/forex_trading,racksen/Lean,FrancisGauthier/Lean,young-zhang/Lean,squideyes/Lean,kaffeebrauer/Lean,iamkingmaker/Lean,bizcad/LeanAbhi,AlexCatarino/Lean,wowgeeker/Lean,bizcad/LeanAbhi,StefanoRaggi/Lean,desimonk/Lean,AlexCatarino/Lean,redmeros/Lean,JKarathiya/Lean,jameschch/Lean,tzaavi/Lean,Neoracle/Lean,bizcad/LeanITrend,Jay-Jay-D/LeanSTP,rchien/Lean,AnObfuscator/Lean,QuantConnect/Lean,exhau/Lean,jameschch/Lean,Neoracle/Lean,andrewhart098/Lean,florentchandelier/Lean,exhau/Lean,FrancisGauthier/Lean,bizcad/LeanAbhi,tzaavi/Lean,AnObfuscator/Lean,mabeale/Lean,tomhunter-gh/Lean,Jay-Jay-D/LeanSTP,Mendelone/forex_trading,tomhunter-gh/Lean,Neoracle/Lean,QuantConnect/Lean,dpavlenkov/Lean,iamkingmaker/Lean,AnshulYADAV007/Lean,bizcad/LeanITrend,dalebrubaker/Lean,kaffeebrauer/Lean,dpavlenkov/Lean,Mendelone/forex_trading,bdilber/Lean,young-zhang/Lean,wowgeeker/Lean,FrancisGauthier/Lean,AnshulYADAV007/Lean,JKarathiya/Lean,dpavlenkov/Lean,bizcad/LeanJJN,bizcad/LeanJJN,AnshulYADAV007/Lean,dalebrubaker/Lean,squideyes/Lean,racksen/Lean,mabeale/Lean,iamkingmaker/Lean,redmeros/Lean,Mendelone/forex_trading,bizcad/LeanITrend,AnshulYADAV007/Lean,QuantConnect/Lean,young-zhang/Lean,mabeale/Lean,dalebrubaker/Lean,bizcad/Lean,florentchandelier/Lean,rchien/Lean,dpavlenkov/Lean,tzaavi/Lean,tzaavi/Lean,devalkeralia/Lean,AlexCatarino/Lean,desimonk/Lean,Obawoba/Lean,kaffeebrauer/Lean,jameschch/Lean,florentchandelier/Lean,Obawoba/Lean,redmeros/Lean,dalebrubaker/Lean,Phoenix1271/Lean,bizcad/Lean,devalkeralia/Lean,tomhunter-gh/Lean,iamkingmaker/Lean,desimonk/Lean,andrewhart098/Lean,exhau/Lean,tomhunter-gh/Lean,kaffeebrauer/Lean,StefanoRaggi/Lean,Jay-Jay-D/LeanSTP,kaffeebrauer/Lean | Tests/Indicators/MeanAbsoluteDeviationTests.cs | Tests/Indicators/MeanAbsoluteDeviationTests.cs | /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 NUnit.Framework;
using QuantConnect.Indicators;
namespace QuantConnect.Tests.Indicators {
[TestFixture]
public class MeanAbsoluteDeviationTests {
[Test]
public void ComputesCorrectly() {
// Indicator output was compared against the octave code:
// mad = @(v) mean(abs(v - mean(v)));
var std = new MeanAbsoluteDeviation(3);
var reference = DateTime.MinValue;
std.Update(reference.AddDays(1), 1m);
Assert.AreEqual(0m, std.Current.Value);
std.Update(reference.AddDays(2), -1m);
Assert.AreEqual(1m, std.Current.Value);
std.Update(reference.AddDays(3), 1m);
Assert.AreEqual(0.888888888888889m, Decimal.Round(std.Current.Value, 15));
std.Update(reference.AddDays(4), -2m);
Assert.AreEqual(1.111111111111111m, Decimal.Round(std.Current.Value, 15));
std.Update(reference.AddDays(5), 3m);
Assert.AreEqual(1.777777777777778m, Decimal.Round(std.Current.Value, 15));
}
}
}
| /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 NUnit.Framework;
using QuantConnect.Indicators;
namespace QuantConnect.Tests.Indicators {
[TestFixture]
public class MeanAbsoluteDeviationTests {
[Test]
public void ComputesCorrectly() {
// Indicator output was compared against the octave code:
// mad = @(v) mean(abs(v - mean(v)));
var std = new MeanAbsoluteDeviation(3);
var reference = DateTime.MinValue;
std.Update(reference.AddDays(1), 1m);
Assert.AreEqual(0m, std.Current.Value);
std.Update(reference.AddDays(2), -1m);
Assert.AreEqual(1m, std.Current.Value);
std.Update(reference.AddDays(3), 1m);
Assert.AreEqual(0.888888888888889m, std.Current.Value);
std.Update(reference.AddDays(4), -2m);
Assert.AreEqual(1.11111111111111m, std.Current.Value);
std.Update(reference.AddDays(5), 3m);
Assert.AreEqual(1.77777777777778m, std.Current.Value);
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.