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 |
---|---|---|---|---|---|---|---|---|
f22e30668d4f9288383b75f3751adfa0ad5763fb | Fix access to schedule api (#1022) | joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net | Joinrpg/Controllers/XGameApi/ProjectScheduleController.cs | Joinrpg/Controllers/XGameApi/ProjectScheduleController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using JoinRpg.Data.Interfaces;
using JoinRpg.Domain;
using JoinRpg.Domain.Schedules;
using JoinRpg.Helpers;
using Joinrpg.Markdown;
using JoinRpg.Web.Filter;
using JoinRpg.Web.Models.Schedules;
using JoinRpg.Web.XGameApi.Contract.Schedule;
using JoinRpg.WebPortal.Managers.Schedule;
namespace JoinRpg.Web.Controllers.XGameApi
{
[RoutePrefix("x-game-api/{projectId}/schedule")]
public class ProjectScheduleController : XGameApiController
{
private SchedulePageManager Manager { get; }
public ProjectScheduleController(IProjectRepository projectRepository, SchedulePageManager manager) : base(projectRepository)
{
Manager = manager;
}
[HttpGet]
[Route("all")]
public async Task<List<ProgramItemInfoApi>> GetSchedule([FromUri]
int projectId)
{
var check = await Manager.CheckScheduleConfiguration();
if (check.Contains(ScheduleConfigProblemsViewModel.NoAccess))
{
throw new HttpResponseException(HttpStatusCode.Forbidden);
}
if (check.Any())
{
throw new Exception($"Error {check.Select(x => x.ToString()).JoinStrings(" ,")}");
}
var project = await ProjectRepository.GetProjectWithFieldsAsync(projectId);
var characters = await ProjectRepository.GetCharacters(projectId);
var scheduleBuilder = new ScheduleBuilder(project, characters);
var result = scheduleBuilder.Build().AllItems.Select(slot =>
new ProgramItemInfoApi
{
Name = slot.ProgramItem.Name,
Authors = slot.ProgramItem.Authors.Select(author =>
new AuthorInfoApi {Name = author.GetDisplayName()}),
StartTime = slot.StartTime,
EndTime = slot.EndTime,
Rooms = slot.Rooms.Select(room => new RoomInfoApi {Name = room.Name}),
Description = slot.ProgramItem.Description.ToHtmlString().ToString()
}).ToList();
return result;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using JoinRpg.Data.Interfaces;
using JoinRpg.Domain;
using JoinRpg.Domain.Schedules;
using Joinrpg.Markdown;
using JoinRpg.Web.Filter;
using JoinRpg.Web.XGameApi.Contract.Schedule;
using JoinRpg.WebPortal.Managers.Schedule;
namespace JoinRpg.Web.Controllers.XGameApi
{
[RoutePrefix("x-game-api/{projectId}/schedule"), XGameMasterAuthorize()]
public class ProjectScheduleController : XGameApiController
{
private SchedulePageManager Manager { get; }
public ProjectScheduleController(IProjectRepository projectRepository, SchedulePageManager manager) : base(projectRepository)
{
Manager = manager;
}
[HttpGet]
[Route("all")]
public async Task<List<ProgramItemInfoApi>> GetSchedule([FromUri]
int projectId)
{
var check = await Manager.CheckScheduleConfiguration();
if (check.Any())
{
throw new Exception("Error");
}
var project = await ProjectRepository.GetProjectWithFieldsAsync(projectId);
var characters = await ProjectRepository.GetCharacters(projectId);
var scheduleBuilder = new ScheduleBuilder(project, characters);
var result = scheduleBuilder.Build().AllItems.Select(slot =>
new ProgramItemInfoApi
{
Name = slot.ProgramItem.Name,
Authors = slot.ProgramItem.Authors.Select(author =>
new AuthorInfoApi {Name = author.GetDisplayName()}),
StartTime = slot.StartTime,
EndTime = slot.EndTime,
Rooms = slot.Rooms.Select(room => new RoomInfoApi {Name = room.Name}),
Description = slot.ProgramItem.Description.ToHtmlString().ToString()
}).ToList();
return result;
}
}
}
| mit | C# |
0bf91405399bf41891c241fa72e5d23642d874e7 | Fix OnAfterMap | ernestoherrera/FluentSql | FluentSql/Mappers/EntityMap.cs | FluentSql/Mappers/EntityMap.cs | using FluentSql.DatabaseMappers.Common;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FluentSql.Mappers
{
public class EntityMap
{
public string Database { get; internal set; }
public string SchemaName { get; internal set; }
public string TableName { get; internal set; }
public string TableAlias { get; internal set; }
public List<PropertyMap> Properties { get; internal set; }
public Type EntityType { get; private set; }
public string Name { get; private set; }
public EntityMap(Type entityType)
{
if (entityType == null)
throw new ArgumentNullException("Entity type can not be null");
Properties = entityType.GetProperties().Select(p => new PropertyMap(p)).ToList();
Name = entityType.Name;
}
public EntityMap(Type entityType, Table table)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace FluentSql.Mappers
{
public class EntityMap
{
public string Database { get; internal set; }
public string SchemaName { get; internal set; }
public string TableName { get; internal set; }
public string TableAlias { get; internal set; }
public List<PropertyMap> Properties { get; internal set; }
public Type EntityType { get; private set; }
public string Name { get; private set; }
public EntityMap(Type entityType)
{
if (entityType == null)
{
Properties = new List<PropertyMap>();
Name = string.Empty;
return;
}
Properties = entityType.GetProperties().Select(p => new PropertyMap(p)).ToList();
Name = entityType.Name;
}
}
}
| apache-2.0 | C# |
5bc2351d28048b9574f6dc4813a50325083228fd | use inner exception | pardeike/Harmony | HarmonyTests/Patching/TargetMethod.cs | HarmonyTests/Patching/TargetMethod.cs | using HarmonyLib;
using HarmonyLibTests.Assets;
using NUnit.Framework;
using System;
namespace HarmonyLibTests
{
[TestFixture]
public class TargetMethod
{
[Test]
public void Test_TargetMethod_Returns_Null()
{
var patchClass = typeof(Class15Patch);
Assert.NotNull(patchClass);
var harmonyInstance = new Harmony("test");
Assert.NotNull(harmonyInstance);
var processor = harmonyInstance.CreateClassProcessor(patchClass);
Assert.NotNull(processor);
Exception exception = null;
try
{
Assert.NotNull(processor.Patch());
}
catch (Exception ex)
{
exception = ex;
}
Assert.NotNull(exception);
Assert.NotNull(exception.InnerException);
Assert.True(exception.InnerException.Message.Contains("returned an unexpected result: null"));
}
[Test]
public void Test_TargetMethod_Returns_Wrong_Type()
{
var patchClass = typeof(Class16Patch);
Assert.NotNull(patchClass);
var harmonyInstance = new Harmony("test");
Assert.NotNull(harmonyInstance);
var processor = harmonyInstance.CreateClassProcessor(patchClass);
Assert.NotNull(processor);
Exception exception = null;
try
{
Assert.NotNull(processor.Patch());
}
catch (Exception ex)
{
exception = ex;
}
Assert.NotNull(exception);
Assert.NotNull(exception.InnerException);
Assert.True(exception.InnerException.Message.Contains("has wrong return type"));
}
[Test]
public void Test_TargetMethods_Returns_Null()
{
var patchClass = typeof(Class17Patch);
Assert.NotNull(patchClass);
var harmonyInstance = new Harmony("test");
Assert.NotNull(harmonyInstance);
var processor = harmonyInstance.CreateClassProcessor(patchClass);
Assert.NotNull(processor);
Exception exception = null;
try
{
Assert.NotNull(processor.Patch());
}
catch (Exception ex)
{
exception = ex;
}
Assert.NotNull(exception);
Assert.NotNull(exception.InnerException);
Assert.True(exception.InnerException.Message.Contains("returned an unexpected result: some element was null"));
}
}
} | using HarmonyLib;
using HarmonyLibTests.Assets;
using NUnit.Framework;
using System;
namespace HarmonyLibTests
{
[TestFixture]
public class TargetMethod
{
[Test]
public void Test_TargetMethod_Returns_Null()
{
var patchClass = typeof(Class15Patch);
Assert.NotNull(patchClass);
var harmonyInstance = new Harmony("test");
Assert.NotNull(harmonyInstance);
var processor = harmonyInstance.CreateClassProcessor(patchClass);
Assert.NotNull(processor);
Exception exception = null;
try
{
Assert.NotNull(processor.Patch());
}
catch (Exception ex)
{
exception = ex;
}
Assert.NotNull(exception);
Assert.True(exception.Message.Contains("returned an unexpected result: null"));
}
[Test]
public void Test_TargetMethod_Returns_Wrong_Type()
{
var patchClass = typeof(Class16Patch);
Assert.NotNull(patchClass);
var harmonyInstance = new Harmony("test");
Assert.NotNull(harmonyInstance);
var processor = harmonyInstance.CreateClassProcessor(patchClass);
Assert.NotNull(processor);
Exception exception = null;
try
{
Assert.NotNull(processor.Patch());
}
catch (Exception ex)
{
exception = ex;
}
Assert.NotNull(exception);
Assert.True(exception.Message.Contains("has wrong return type"));
}
[Test]
public void Test_TargetMethods_Returns_Null()
{
var patchClass = typeof(Class17Patch);
Assert.NotNull(patchClass);
var harmonyInstance = new Harmony("test");
Assert.NotNull(harmonyInstance);
var processor = harmonyInstance.CreateClassProcessor(patchClass);
Assert.NotNull(processor);
Exception exception = null;
try
{
Assert.NotNull(processor.Patch());
}
catch (Exception ex)
{
exception = ex;
}
Assert.NotNull(exception);
Assert.True(exception.Message.Contains("returned an unexpected result: some element was null"));
}
}
} | mit | C# |
433b3862dec28e69660ce838a404d63ba80fc4b9 | Add USM ID API | wwwwwwzx/3DSRNGTool | 3DSRNGTool/Util/SFMTSeedAPI.cs | 3DSRNGTool/Util/SFMTSeedAPI.cs | using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
namespace Pk3DSRNGTool
{
public static class SFMTSeedAPI
{
public static List<Result> request(string needle, bool IsID, bool IsUltra)
{
Root root;
var url = IsUltra
? (IsID ? $"https://rng-api.poyo.club/usm/sfmt/seed/id?needle={needle}"
: $"https://rng-api.poyo.club/usm/sfmt/seed?needle={needle}" )
: (IsID ? $"http://49.212.217.137:19937/gen7/sfmt/seed/id?needle={needle}"
: $"http://49.212.217.137:19937/gen7/sfmt/seed?needle={needle}");
string jsonStr;
using (var webClient = new WebClient())
{
jsonStr = webClient.DownloadString(url);
}
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
{
var serializer = new DataContractJsonSerializer(typeof(Root));
root = (Root)serializer.ReadObject(ms);
}
return root?.results;
}
public class Root
{
public List<Result> results { get; set; }
}
public class Result
{
public byte add { get; set; }
public string seed { get; set; }
public string encoded_needle { get; set; }
public int step { get; set; }
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
namespace Pk3DSRNGTool
{
public static class SFMTSeedAPI
{
public static List<Result> request(string needle, bool IsID, bool IsUltra)
{
Root root;
var url = IsUltra ? $"https://rng-api.poyo.club/usm/sfmt/seed?needle={needle}" :
( IsID ? $"http://49.212.217.137:19937/gen7/sfmt/seed/id?needle={needle}"
: $"http://49.212.217.137:19937/gen7/sfmt/seed?needle={needle}");
string jsonStr;
using (var webClient = new WebClient())
{
jsonStr = webClient.DownloadString(url);
}
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
{
var serializer = new DataContractJsonSerializer(typeof(Root));
root = (Root)serializer.ReadObject(ms);
}
return root?.results;
}
public class Root
{
public List<Result> results { get; set; }
}
public class Result
{
public byte add { get; set; }
public string seed { get; set; }
public string encoded_needle { get; set; }
public int step { get; set; }
}
}
}
| mit | C# |
2d1527eff359b9377ec038667b4544d1436820bc | Bump version for release 1.0.16349-alpha2 | rlvandaveer/heliar-composition,rlvandaveer/heliar-composition,rlvandaveer/heliar-composition | src/Heliar.Composition.Web/Properties/AssemblyInfo.cs | src/Heliar.Composition.Web/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Heliar.Composition.Web")]
[assembly: AssemblyDescription("Provides shared types and core behavior, e.g. dependency resolver bootstrappers, composition scopes, to perform composition for web based projects")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("39a5ad59-0a65-4032-9b9c-1f0933410b4a")]
// 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.16349.2124")]
[assembly: AssemblyFileVersion("1.0.16349.2124")]
[assembly: AssemblyInformationalVersion("1.0.16349-alpha2")] | 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("Heliar.Composition.Web")]
[assembly: AssemblyDescription("Provides shared types and core behavior, e.g. dependency resolver bootstrappers, composition scopes, to perform composition for web based projects")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("39a5ad59-0a65-4032-9b9c-1f0933410b4a")]
// 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.16349.2022")]
[assembly: AssemblyFileVersion("1.0.16349.2022")]
[assembly: AssemblyInformationalVersion("1.0.16349-alpha1")] | mit | C# |
afd109e5c65b0ce3e646041ecc3debac98789128 | change access modifier ApiVersion setter | clD11/aspnet-owin-oauth | src/Owin.Security.HighQ/HighQAuthenticationOptions.cs | src/Owin.Security.HighQ/HighQAuthenticationOptions.cs | using Authentication.Web.OWIN.HighQ.Provider;
using Microsoft.Owin;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Security;
using System;
using System.Net.Http;
namespace Authentication.Web.OWIN.HighQ
{
public class HighQAuthenticationOptions : AuthenticationOptions
{
public HighQAuthenticationOptions() : base(Constants.DefaultAuthenticationType)
{
Description.Caption = Constants.DefaultAuthenticationType;
CallbackPath = new PathString("/signin-highq");
AuthenticationMode = AuthenticationMode.Passive;
BackchannelTimeout = TimeSpan.FromSeconds(60);
CookieManager = new CookieManager();
AuthorizationEndpoint = Constants.AuthorizationEndpoint;
TokenEndpoint = Constants.TokenEndpoint;
UserInformationEndpoint = Constants.UserInformationEndpoint;
}
public string ClientId { get; set; }
public string ClientSecret { get; set; }
// redirect_uri path in HighQ app registration default is /signin-highq
public PathString CallbackPath { get; set; }
public string SignInAsAuthenticationType { get; internal set; }
public IHighQAuthenticationProvider Provider { get; set; }
public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; }
public string Domain { get; set; }
public string InstanceName { get; set; }
public string RedirectUri { get; set; }
public string AuthorizationEndpoint { get; private set; }
public string TokenEndpoint { get; private set; }
public string UserInformationEndpoint { get; private set; }
public TimeSpan BackchannelTimeout { get; private set; }
public ICertificateValidator BackchannelCertificateValidator { get; set; }
public HttpMessageHandler BackchannelHttpHandler { get; set; }
public ICookieManager CookieManager { get; set; }
public string AccessType { get; set; }
public string ApiVersion { get; set; }
}
} | using Authentication.Web.OWIN.HighQ.Provider;
using Microsoft.Owin;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Security;
using System;
using System.Net.Http;
namespace Authentication.Web.OWIN.HighQ
{
public class HighQAuthenticationOptions : AuthenticationOptions
{
public HighQAuthenticationOptions() : base(Constants.DefaultAuthenticationType)
{
Description.Caption = Constants.DefaultAuthenticationType;
CallbackPath = new PathString("/signin-highq");
AuthenticationMode = AuthenticationMode.Passive;
BackchannelTimeout = TimeSpan.FromSeconds(60);
CookieManager = new CookieManager();
AuthorizationEndpoint = Constants.AuthorizationEndpoint;
TokenEndpoint = Constants.TokenEndpoint;
UserInformationEndpoint = Constants.UserInformationEndpoint;
}
public string ClientId { get; set; }
public string ClientSecret { get; set; }
// redirect_uri path in HighQ app registration default is /signin-highq
public PathString CallbackPath { get; set; }
public string SignInAsAuthenticationType { get; internal set; }
public IHighQAuthenticationProvider Provider { get; set; }
public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; }
public string Domain { get; set; }
public string InstanceName { get; set; }
public string RedirectUri { get; set; }
public string AuthorizationEndpoint { get; private set; }
public string TokenEndpoint { get; private set; }
public string UserInformationEndpoint { get; private set; }
public TimeSpan BackchannelTimeout { get; private set; }
public ICertificateValidator BackchannelCertificateValidator { get; set; }
public HttpMessageHandler BackchannelHttpHandler { get; set; }
public ICookieManager CookieManager { get; set; }
public string AccessType { get; set; }
public string ApiVersion { get; internal set; }
}
} | mit | C# |
c2f39df0bdcb4b713ab1ebb429d870f4d807ae5e | fix non-used fields | NServiceBusSqlPersistence/NServiceBus.SqlPersistence | src/SqlPersistence/SqlPersistenceSettingsAttribute.cs | src/SqlPersistence/SqlPersistenceSettingsAttribute.cs | using System;
namespace NServiceBus.Persistence.Sql
{
[AttributeUsage(AttributeTargets.Assembly)]
public class SqlPersistenceSettingsAttribute : Attribute
{
public bool MsSqlServerScripts { get; }
public bool MySqlScripts { get; }
public SqlPersistenceSettingsAttribute(
bool msSqlServerScripts = false,
bool mySqlScripts = false
)
{
MySqlScripts = mySqlScripts;
MsSqlServerScripts = msSqlServerScripts;
}
}
} | using System;
namespace NServiceBus.Persistence.Sql
{
[AttributeUsage(AttributeTargets.Assembly)]
public class SqlPersistenceSettingsAttribute : Attribute
{
public readonly bool MsSqlServerScripts;
public readonly bool MySqlScripts;
public SqlPersistenceSettingsAttribute(
bool msSqlServerScripts = false,
bool mySqlScripts = false
)
{
MySqlScripts = mySqlScripts;
MsSqlServerScripts = msSqlServerScripts;
}
}
} | mit | C# |
01d999245eeacaf3134f106cf5428cf0d32bd0a1 | Fix linebreak inside hyperlink | pellea/waslibs,janabimustafa/waslibs,wasteam/waslibs,janabimustafa/waslibs,wasteam/waslibs,janabimustafa/waslibs,pellea/waslibs,wasteam/waslibs,pellea/waslibs | src/AppStudio.Uwp/Controls/HtmlBlock/Writers/BrWriter.cs | src/AppStudio.Uwp/Controls/HtmlBlock/Writers/BrWriter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppStudio.Uwp.Html;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Documents;
namespace AppStudio.Uwp.Controls.Html.Writers
{
class BrWriter : HtmlWriter
{
public override string[] TargetTags
{
get { return new string[] { "br" }; }
}
public override DependencyObject GetControl(HtmlFragment fragment)
{
//LineBreak doesn't work with hyperlink
return new Run
{
Text = Environment.NewLine
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppStudio.Uwp.Html;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Documents;
namespace AppStudio.Uwp.Controls.Html.Writers
{
class BrWriter : HtmlWriter
{
public override string[] TargetTags
{
get { return new string[] { "br" }; }
}
public override DependencyObject GetControl(HtmlFragment fragment)
{
return new LineBreak();
}
}
}
| mit | C# |
19a46dab8146340d72939f12c51073d8030bccd5 | Fix for a bug in the class I just created. | MarkerMetro/MarkerMetro.Unity.WinLegacy,hungweng/MarkerMetro.Unity.WinLegacy | MarkerMetro.Unity.WinLegacyUnity/System/Timers/Timer.cs | MarkerMetro.Unity.WinLegacyUnity/System/Timers/Timer.cs | using System;
namespace MarkerMetro.Unity.WinLegacy.IO.Timers
{
public delegate void ElapsedEventHandler(Object sender, ElapsedEventArgs e);
public class Timer
{
public event ElapsedEventHandler Elapsed;
public Timer(double interval)
{
throw new System.NotImplementedException();
}
public void Start()
{
throw new System.NotImplementedException();
}
public void Stop()
{
throw new System.NotImplementedException();
}
}
public class ElapsedEventArgs : EventArgs
{
public DateTime SignalTime { get; private set; }
}
}
| using System;
namespace MarkerMetro.Unity.WinLegacy.IO.Timers
{
public delegate void ElapsedEventHandler(Object sender, ElapsedEventArgs e);
public class Timer
{
public event ElapsedEventHandler Elapsed;
public Timer(double interval)
{
throw new System.NotImplementedException();
}
public void Start()
{
throw new System.NotImplementedException();
}
public void Stop()
{
throw new System.NotImplementedException();
}
}
public class ElapsedEventArgs : EventArgs
{
public DateTime SignalTime { get; }
}
}
| mit | C# |
c5b333600d1810c23b9ad8c01271289eb9dbc7f0 | Fix build | sboulema/CodeNav,sboulema/CodeNav | CodeNav/Mappers/FieldMapper.cs | CodeNav/Mappers/FieldMapper.cs | using CodeNav.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Linq;
using VisualBasicSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax;
using VisualBasic = Microsoft.CodeAnalysis.VisualBasic;
namespace CodeNav.Mappers
{
public static class FieldMapper
{
public static CodeItem MapField(FieldDeclarationSyntax member,
CodeViewUserControl control, SemanticModel semanticModel)
{
if (member == null) return null;
return MapField(member, member.Declaration.Variables.First().Identifier, member.Modifiers, control, semanticModel);
}
public static CodeItem MapField(VisualBasicSyntax.FieldDeclarationSyntax member,
CodeViewUserControl control, SemanticModel semanticModel)
{
if (member == null) return null;
return MapField(member, member.Declarators.First().Names.First().Identifier, member.Modifiers, control, semanticModel);
}
private static CodeItem MapField(SyntaxNode member, SyntaxToken identifier, SyntaxTokenList modifiers,
CodeViewUserControl control, SemanticModel semanticModel)
{
if (member == null) return null;
var item = BaseMapper.MapBase<CodeItem>(member, identifier, modifiers, control, semanticModel);
item.Kind = IsConstant(modifiers)
? CodeItemKindEnum.Constant
: CodeItemKindEnum.Variable;
item.Moniker = IconMapper.MapMoniker(item.Kind, item.Access);
return item;
}
private static bool IsConstant(SyntaxTokenList modifiers)
{
return modifiers.Any(m => m.RawKind == (int)SyntaxKind.ConstKeyword ||
m.RawKind == (int)VisualBasic.SyntaxKind.ConstKeyword);
}
}
}
| using CodeNav.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Linq;
using VisualBasicSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax;
using VisualBasic = Microsoft.CodeAnalysis.VisualBasic;
namespace CodeNav.Mappers
{
public static class FieldMapper
{
public static CodeItem MapField(FieldDeclarationSyntax member,
CodeViewUserControl control, SemanticModel semanticModel)
{
if (member == null) return null;
var item = BaseMapper.MapBase<CodeItem>(member, member.Declaration.Variables.First().Identifier, member.Modifiers, control, semanticModel);
item.Kind = IsConstant(member.Modifiers)
? CodeItemKindEnum.Constant
: CodeItemKindEnum.Variable;
item.Moniker = IconMapper.MapMoniker(item.Kind, item.Access);
return item;
}
public static CodeItem MapField(VisualBasicSyntax.FieldDeclarationSyntax member,
CodeViewUserControl control, SemanticModel semanticModel)
{
if (member == null) return null;
var item = BaseMapper.MapBase<CodeItem>(member, member.Declarators.First().Names.First().Identifier, member.Modifiers, control, semanticModel);
item.Kind = IsConstant(member.Modifiers)
? CodeItemKindEnum.Constant
: CodeItemKindEnum.Variable;
item.Moniker = IconMapper.MapMoniker(item.Kind, item.Access);
return item;
}
private static bool IsConstant(SyntaxTokenList modifiers)
{
if (modifiers.First().Language == "Visual Basic")
{
return modifiers.Any(m => m.RawKind == (int)VisualBasic.SyntaxKind.ConstKeyword);
}
else
{
return modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword);
}
}
}
}
| mit | C# |
8264d1ea378d6738c6f53931e264276ef0700988 | fix test class name | neekgreen/PaginableCollections,neekgreen/PaginableCollections | src/PaginableCollections.Tests/EmptyPaginableTests.cs | src/PaginableCollections.Tests/EmptyPaginableTests.cs | namespace PaginableCollections.Tests
{
using System;
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
[TestFixture, Category("EmptyPaginable")]
public class EmptyPaginableTests
{
[Test]
public void ShouldEqualPageNumber()
{
var expectedPageNumber = 1;
var sut = Paginable.Empty<int>();
sut.PageNumber.ShouldBeEquivalentTo(expectedPageNumber);
}
[Test]
public void ShouldEqualItemCountPerPage()
{
var expectedItemCountPerPage = 0;
var sut = Paginable.Empty<int>();
sut.ItemCountPerPage.ShouldBeEquivalentTo(expectedItemCountPerPage);
}
[Test]
public void ShouldEqualTotalItemCount()
{
var expectedTotalItemCount = 0;
var sut = Paginable.Empty<int>();
sut.TotalItemCount.ShouldBeEquivalentTo(expectedTotalItemCount);
}
}
} | namespace PaginableCollections.Tests
{
using System;
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
[TestFixture, Category("EmptyPaginable")]
public class EmptyQueryablePaginableTests
{
[Test]
public void ShouldEqualPageNumber()
{
var expectedPageNumber = 1;
var sut = Paginable.Empty<int>();
sut.PageNumber.ShouldBeEquivalentTo(expectedPageNumber);
}
[Test]
public void ShouldEqualItemCountPerPage()
{
var expectedItemCountPerPage = 0;
var sut = Paginable.Empty<int>();
sut.ItemCountPerPage.ShouldBeEquivalentTo(expectedItemCountPerPage);
}
[Test]
public void ShouldEqualTotalItemCount()
{
var expectedTotalItemCount = 0;
var sut = Paginable.Empty<int>();
sut.TotalItemCount.ShouldBeEquivalentTo(expectedTotalItemCount);
}
}
} | mit | C# |
bf4d6180f877b1735c2bcce1098d39122111cd8e | Refactor private and public members. | kubkon/GameOfLifeApplication | GameOfLifeApplication/Form1.cs | GameOfLifeApplication/Form1.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GameOfLifeApplication
{
public partial class Form1 : Form
{
private World world;
private Image liveCellImg;
private Size cellSize;
private Image canvas;
private Graphics graphics;
public int maxIterations = 200;
public int rows = 20;
public int columns = 20;
public int initLiveCells = 150;
public Form1()
{
InitializeComponent();
// Load images representing live cell
liveCellImg = Image.FromFile(@"..\..\assets\live_cell.bmp");
// Specify cell size
cellSize = new Size(10, 10);
// Create master canvas
canvas = new Bitmap(rows * cellSize.Width, columns * cellSize.Height);
// Create new instance of the World
world = new World(rows, columns, initLiveCells);
}
private void drawWorld()
{
var child = Graphics.FromImage(canvas);
child.Clear(Color.White);
for (int i = 0; i < world.rows; i++)
{
for (int j = 0; j < world.columns; j++)
{
var location = new Point(i * cellSize.Width, j * cellSize.Height);
if (world.grid[i, j] == World.State.Live)
child.DrawImage(liveCellImg, new Rectangle(location, cellSize));
}
}
if (graphics == null)
graphics = simulationPreviewBox.CreateGraphics();
graphics.DrawImage(canvas, 0, 0);
}
private void runSimulationClick(object sender, EventArgs e)
{
world.Randomise();
for (int i = 0; i < maxIterations; i++)
{
drawWorld();
if (world.Evolve())
break;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GameOfLifeApplication
{
public partial class Form1 : Form
{
private World world = null;
private Image liveCellImg;
private Size cellSize;
private int maxIterations = 200;
private int rows = 20;
private int columns = 20;
private int initLiveCells = 150;
public Form1()
{
InitializeComponent();
// Load images representing live and dead cell
liveCellImg = Image.FromFile(@"..\..\assets\live_cell.bmp");
cellSize = new Size(10, 10);
// Create new instance of the World
world = new World(rows, columns, initLiveCells);
}
private void drawWorld()
{
var canvas = new Bitmap(rows * cellSize.Width, columns * cellSize.Height);
var child = Graphics.FromImage(canvas);
child.Clear(Color.White);
for (int i = 0; i < world.rows; i++)
{
for (int j = 0; j < world.columns; j++)
{
var location = new Point(i * cellSize.Width, j * cellSize.Height);
if (world.grid[i, j] == World.State.Live)
child.DrawImage(liveCellImg, new Rectangle(location, cellSize));
}
}
var master = simulationPreviewBox.CreateGraphics();
master.DrawImage(canvas, 0, 0);
}
private void runSimulationClick(object sender, EventArgs e)
{
world.Randomise();
for (int i = 0; i < maxIterations; i++)
{
drawWorld();
if (world.Evolve())
break;
}
}
}
}
| mit | C# |
8b2575f85e3aa5aa3f7450cb9fb01a65424181dc | Resolve #110 - Ignore failing test in Firefox | csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay | Tests/CSF.Screenplay.Web.Tests/Tasks/EnterTheDateTests.cs | Tests/CSF.Screenplay.Web.Tests/Tasks/EnterTheDateTests.cs | using CSF.Screenplay.Web.Builders;
using CSF.Screenplay.Web.Tests.Pages;
using FluentAssertions;
using CSF.Screenplay.NUnit;
using NUnit.Framework;
using static CSF.Screenplay.StepComposer;
using CSF.Screenplay.Web.Models;
using CSF.Screenplay.Actors;
using System;
namespace CSF.Screenplay.Web.Tests.Tasks
{
[TestFixture]
[Description("Entering dates")]
public class EnterTheDateTests
{
[Test,Screenplay]
[Description("Entering a date into an HTML 5 input field should work cross-browser")]
public void Enter_TheDate_puts_the_correct_value_into_the_control(IScreenplayScenario scenario)
{
IgnoreOn.Browsers("Clearing dates is now broken in Firefox. https://github.com/csf-dev/CSF.Screenplay/issues/109",
BrowserName.Firefox);
var joe = scenario.GetJoe();
var date = new DateTime(2012, 5, 6);
var expectedString = date.ToString("yyyy-MM-dd");
Given(joe).WasAbleTo(OpenTheirBrowserOn.ThePage<PageTwo>());
When(joe).AttemptsTo(Enter.TheDate(date).Into(PageTwo.DateInput));
Then(joe).ShouldSee(TheText.Of(PageTwo.DateOutput))
.Should()
.Be(expectedString, because: "the displayed date should match");
}
}
}
| using CSF.Screenplay.Web.Builders;
using CSF.Screenplay.Web.Tests.Pages;
using FluentAssertions;
using CSF.Screenplay.NUnit;
using NUnit.Framework;
using static CSF.Screenplay.StepComposer;
using CSF.Screenplay.Web.Models;
using CSF.Screenplay.Actors;
using System;
namespace CSF.Screenplay.Web.Tests.Tasks
{
[TestFixture]
[Description("Entering dates")]
public class EnterTheDateTests
{
[Test,Screenplay]
[Description("Entering a date into an HTML 5 input field should work cross-browser")]
public void Enter_TheDate_puts_the_correct_value_into_the_control(IScreenplayScenario scenario)
{
var joe = scenario.GetJoe();
var date = new DateTime(2012, 5, 6);
var expectedString = date.ToString("yyyy-MM-dd");
Given(joe).WasAbleTo(OpenTheirBrowserOn.ThePage<PageTwo>());
When(joe).AttemptsTo(Enter.TheDate(date).Into(PageTwo.DateInput));
Then(joe).ShouldSee(TheText.Of(PageTwo.DateOutput))
.Should()
.Be(expectedString, because: "the displayed date should match");
}
}
}
| mit | C# |
a2ca0788dbbde44c7e78c66d80074ab1aa8de63a | update demo. | shuxinqin/Chloe | src/ChloeDemo/MySqlConnectionFactory.cs | src/ChloeDemo/MySqlConnectionFactory.cs | using Chloe.Infrastructure;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChloeDemo
{
public class MySqlConnectionFactory : IDbConnectionFactory
{
string _connString = null;
public MySqlConnectionFactory(string connString)
{
this._connString = connString;
}
public IDbConnection CreateConnection()
{
IDbConnection conn = new MySqlConnection(this._connString);
return conn;
}
}
}
| using Chloe.Infrastructure;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChloeDemo
{
public class MySqlConnectionFactory : IDbConnectionFactory
{
string _connString = null;
public MySqlConnectionFactory(string connString)
{
this._connString = connString;
}
public IDbConnection CreateConnection()
{
IDbConnection conn = new MySqlConnection("Database='Chloe';Data Source=localhost;User ID=root;Password=sasa;CharSet=utf8;SslMode=None");
return conn;
}
}
}
| mit | C# |
92e2636bcdc3a63363fca9226f7166e731f6f8f8 | store value on candidate so it can be placed on output | agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov | WebAPI.Domain/ArcServerResponse/Geolocator/Candidate.cs | WebAPI.Domain/ArcServerResponse/Geolocator/Candidate.cs | using System.Globalization;
using Newtonsoft.Json;
namespace WebAPI.Domain.ArcServerResponse.Geolocator
{
public class Candidate
{
private string _address;
[JsonProperty(PropertyName = "address")]
public string Address
{
get { return _address; }
set
{
_address = value;
if (string.IsNullOrEmpty(_address)) return;
var parts = _address.Split(new[] {','});
if (parts.Length != 3) return;
AddressGrid = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(parts[1].Trim().ToLowerInvariant());
_address = string.Join(",", parts[0], parts[2]).Trim();
}
}
[JsonProperty(PropertyName = "location")]
public Location Location { get; set; }
[JsonProperty(PropertyName = "score")]
public double Score { get; set; }
public double ScoreDifference { get; set; }
[JsonProperty(PropertyName = "locator")]
public string Locator { get; set; }
[JsonProperty(PropertyName = "addressGrid")]
public string AddressGrid { get; set; }
[JsonIgnore]
public int Weight { get; set; }
public override string ToString()
{
return string.Format("address: {0}, location: {1}, score: {2}, locator: {3}", Address, Location, Score,
Locator);
}
public bool ShouldSerializeScoreDifference()
{
return false;
}
}
} | using System.Globalization;
using Newtonsoft.Json;
namespace WebAPI.Domain.ArcServerResponse.Geolocator
{
public class Candidate
{
private string _address;
[JsonProperty(PropertyName = "address")]
public string Address
{
get { return _address; }
set
{
_address = value;
if (string.IsNullOrEmpty(_address)) return;
var parts = _address.Split(new[] {','});
if (parts.Length != 3) return;
AddressGrid = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(parts[1].Trim().ToLowerInvariant());
_address = string.Join(",", parts[0], parts[2]).Trim();
}
}
[JsonProperty(PropertyName = "location")]
public Location Location { get; set; }
[JsonProperty(PropertyName = "score")]
public double Score { get; set; }
[JsonProperty(PropertyName = "locator")]
public string Locator { get; set; }
[JsonProperty(PropertyName = "addressGrid")]
public string AddressGrid { get; set; }
[JsonIgnore]
public int Weight { get; set; }
public override string ToString()
{
return string.Format("address: {0}, location: {1}, score: {2}, locator: {3}", Address, Location, Score,
Locator);
}
}
} | mit | C# |
f055d0e5e85c04299b71b22d78b7166abf3bfd97 | Add extension method for adding bundle to bundle collection. | mrydengren/templar,mrydengren/templar | src/Bundlr/BundleExtensions.cs | src/Bundlr/BundleExtensions.cs | using System.IO;
using System.Web.Optimization;
namespace Bundlr
{
public static class BundleExtensions
{
public static TBundle AddTo<TBundle>(this TBundle bundle, BundleCollection collection)
where TBundle : Bundle
{
collection.Add(bundle);
return bundle;
}
public static TBundle IncludePath<TBundle>(this TBundle bundle, string root, params string[] files)
where TBundle : Bundle
{
foreach (string file in files)
{
string path = Path.Combine(root, file);
bundle.Include(path);
}
return bundle;
}
}
} | using System.IO;
using System.Web.Optimization;
namespace Bundlr
{
public static class BundleExtensions
{
public static TBundle IncludePath<TBundle>(this TBundle bundle, string root, params string[] files)
where TBundle : Bundle
{
foreach (string file in files)
{
string path = Path.Combine(root, file);
bundle.Include(path);
}
return bundle;
}
}
} | mit | C# |
0689e8617ae1101f13d6f4daf9151c88be6c8e4d | adjust match types | bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core | src/Core/Enums/UriMatchType.cs | src/Core/Enums/UriMatchType.cs | namespace Bit.Core.Enums
{
public enum UriMatchType : byte
{
BaseDomain = 0,
FullHostname = 1,
StartsWith = 2,
Exact = 3,
RegularExpression = 4,
Never = 5
}
}
| namespace Bit.Core.Enums
{
public enum UriMatchType : byte
{
BaseDomain = 0,
FullHostname = 1,
FullUri = 2,
StartsWith = 3,
RegularExpression = 4
}
}
| agpl-3.0 | C# |
620f7c4cb13f48a74b263142e95c43510e2ca5a0 | Fix wrong scale | JLChnToZ/BMP-U | Assets/Scripts/CameraScaler.cs | Assets/Scripts/CameraScaler.cs | using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Camera))]
public class CameraScaler : MonoBehaviour {
Camera _camera;
new Camera camera {
get {
if(_camera == null)
_camera = GetComponent<Camera>();
return _camera;
}
}
public float referenceScale = 1;
public BMS.Visualization.BMSTextureDisplay[] displays;
void LateUpdate () {
CalculateMaxScale();
float scale = (float)Screen.height / Screen.width;
camera.orthographicSize = scale * referenceScale;
}
void CalculateMaxScale() {
if(displays == null || displays.Length < 1) return;
float maxScale = float.NegativeInfinity;
foreach(var display in displays) {
if(!display.isActiveAndEnabled) continue;
Vector2 scale = display.transform.localScale;
maxScale = Mathf.Max(maxScale, scale.x);
}
if(maxScale < 0) return;
referenceScale = maxScale / 2F;
}
}
| using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Camera))]
public class CameraScaler : MonoBehaviour {
Camera _camera;
new Camera camera {
get {
if(_camera == null)
_camera = GetComponent<Camera>();
return _camera;
}
}
public float referenceScale = 1;
public BMS.Visualization.BMSTextureDisplay[] displays;
void LateUpdate () {
CalculateMaxScale();
float scale = (float)Screen.height / Screen.width;
camera.orthographicSize = scale * referenceScale;
}
void CalculateMaxScale() {
if(displays == null || displays.Length < 1) return;
float maxScale = float.PositiveInfinity;
foreach(var display in displays) {
if(!display.isActiveAndEnabled) continue;
Vector2 scale = display.transform.localScale;
maxScale = Mathf.Min(maxScale, 1 / scale.x);
}
if(maxScale == float.PositiveInfinity) return;
referenceScale = maxScale / 2F;
}
}
| artistic-2.0 | C# |
743bf289e1d2992292f7e4a0e4f1430761793f97 | Remove a bundle directive which pointed to an empty folder (which blew up Azure) | bendetat/Listy-Azure,bendetat/Listy-Azure | src/Listy.Web/App_Start/BundleConfig.cs | src/Listy.Web/App_Start/BundleConfig.cs | using System.Web.Optimization;
namespace Listy.Web
{
public class BundleConfig
{
public class BootstrapResourcesTransform : IItemTransform
{
public string Process(string includedVirtualPath, string input)
{
return input.Replace(@"../fonts/", @"/Content/fonts/")
;
}
}
public static void Register(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/bundles/css")
.Include("~/Content/bootstrap.css", new BootstrapResourcesTransform())
.Include("~/Content/toastr.css"));
// Remember order is important!
bundles.Add(new ScriptBundle("~/bundles/js")
.Include("~/Scripts/jquery-2.0.3.js")
.Include("~/Scripts/jquery-ui-1.10.3.js")
.Include("~/Scripts/bootstrap.js")
.Include("~/Scripts/knockout-2.3.0.js")
.Include("~/Scripts/knockout.validation.js")
.Include("~/Scripts/toastr.js")
.Include("~/Scripts/knockout-sortable.js")
.IncludeDirectory("~/Scripts/extensions/", "*.js", true)
.IncludeDirectory("~/Scripts/site/", "*.js", true));
bundles.Add(new ScriptBundle("~/bundles/html5shiv")
.Include("~/Scripts/html5shiv.js")
.Include("~/Scripts/respond.min.js"));
}
}
} | using System.Web.Optimization;
namespace Listy.Web
{
public class BundleConfig
{
public class BootstrapResourcesTransform : IItemTransform
{
public string Process(string includedVirtualPath, string input)
{
return input.Replace(@"../fonts/", @"/Content/fonts/")
;
}
}
public static void Register(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/bundles/css")
.Include("~/Content/bootstrap.css", new BootstrapResourcesTransform())
.Include("~/Content/toastr.css")
.IncludeDirectory("~/Content/Css/site/", "*.css", true));
bundles.Add(new StyleBundle("~/bundles/css/"));
// Remember order is important!
bundles.Add(new ScriptBundle("~/bundles/js")
.Include("~/Scripts/jquery-2.0.3.js")
.Include("~/Scripts/jquery-ui-1.10.3.js")
.Include("~/Scripts/bootstrap.js")
.Include("~/Scripts/knockout-2.3.0.js")
.Include("~/Scripts/knockout.validation.js")
.Include("~/Scripts/toastr.js")
.Include("~/Scripts/knockout-sortable.js")
.IncludeDirectory("~/Scripts/extensions/", "*.js", true)
.IncludeDirectory("~/Scripts/site/", "*.js", true));
bundles.Add(new ScriptBundle("~/bundles/html5shiv")
.Include("~/Scripts/html5shiv.js")
.Include("~/Scripts/respond.min.js"));
}
}
} | apache-2.0 | C# |
d4525c3f4a1ceb97c3809cb7f30fb3e189da85ec | Fix init firebase parameter. | Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x | src/unity/Runtime/Services/Internal/FirebaseParameter.cs | src/unity/Runtime/Services/Internal/FirebaseParameter.cs | using System;
using System.Reflection;
namespace EE.Internal {
internal class FirebaseParameter {
private const string TypeName = "Firebase.Analytics.Parameter, Firebase.Analytics";
private static readonly Type _type = Type.GetType(TypeName);
private static readonly ConstructorInfo _constructor0 =
_type.GetConstructor(new[] {
typeof(string),
typeof(string)
});
private static readonly ConstructorInfo _constructor1 =
_type.GetConstructor(new[] {
typeof(string),
typeof(long)
});
private static readonly ConstructorInfo _constructor2 =
_type.GetConstructor(new[] {
typeof(string),
typeof(double)
});
public static Type InternalType { get; } = _type;
public object Internal { get; }
public FirebaseParameter(string name, string value) {
Internal = _constructor0.Invoke(new object[] {name, value});
}
public FirebaseParameter(string name, long value) {
Internal = _constructor1.Invoke(new object[] {name, value});
}
public FirebaseParameter(string name, double value) {
Internal = _constructor2.Invoke(new object[] {name, value});
}
}
} | using System;
namespace EE.Internal {
internal class FirebaseParameter {
private const string TypeName = "Firebase.Analytics.Parameter, Firebase.Analytics";
private static readonly Type _type = Type.GetType(TypeName);
private static readonly ObjectActivator<object> _constructor0 =
ObjectActivatorUtils.GetActivator<object>(
_type.GetConstructor(new[] {
typeof(string),
typeof(string)
}));
private static readonly ObjectActivator<object> _constructor1 =
ObjectActivatorUtils.GetActivator<object>(
_type.GetConstructor(new[] {
typeof(string),
typeof(long)
}));
private static readonly ObjectActivator<object> _constructor2 =
ObjectActivatorUtils.GetActivator<object>(
_type.GetConstructor(new[] {
typeof(string),
typeof(double)
}));
public static Type InternalType { get; } = _type;
public object Internal { get; }
public FirebaseParameter(string name, string value) {
Internal = _constructor0(name, value);
}
public FirebaseParameter(string name, long value) {
Internal = _constructor1(name, value);
}
public FirebaseParameter(string name, double value) {
Internal = _constructor2(name, value);
}
}
} | mit | C# |
d952af5f31912e5500b451ce6b40e841498f8c87 | Make tests runnable on mono | featuresnap/FAKE,philipcpresley/FAKE,pmcvtm/FAKE,ovu/FAKE,ilkerde/FAKE,modulexcite/FAKE,satsuper/FAKE,ctaggart/FAKE,dlsteuer/FAKE,tpetricek/FAKE,MichalDepta/FAKE,philipcpresley/FAKE,xavierzwirtz/FAKE,MiloszKrajewski/FAKE,NaseUkolyCZ/FAKE,gareth-evans/FAKE,rflechner/FAKE,neoeinstein/FAKE,ovu/FAKE,satsuper/FAKE,molinch/FAKE,brianary/FAKE,modulexcite/FAKE,xavierzwirtz/FAKE,leflings/FAKE,gareth-evans/FAKE,MichalDepta/FAKE,pmcvtm/FAKE,ovu/FAKE,beeker/FAKE,xavierzwirtz/FAKE,yonglehou/FAKE,ArturDorochowicz/FAKE,ctaggart/FAKE,Kazark/FAKE,MichalDepta/FAKE,JonCanning/FAKE,jayp33/FAKE,jayp33/FAKE,gareth-evans/FAKE,pacificIT/FAKE,MichalDepta/FAKE,wooga/FAKE,dlsteuer/FAKE,mfalda/FAKE,brianary/FAKE,beeker/FAKE,mat-mcloughlin/FAKE,RMCKirby/FAKE,daniel-chambers/FAKE,pmcvtm/FAKE,MiloszKrajewski/FAKE,mat-mcloughlin/FAKE,warnergodfrey/FAKE,mat-mcloughlin/FAKE,ctaggart/FAKE,dmorgan3405/FAKE,gareth-evans/FAKE,daniel-chambers/FAKE,xavierzwirtz/FAKE,mglodack/FAKE,MiloszKrajewski/FAKE,haithemaraissia/FAKE,molinch/FAKE,featuresnap/FAKE,jayp33/FAKE,neoeinstein/FAKE,dlsteuer/FAKE,beeker/FAKE,hitesh97/FAKE,ArturDorochowicz/FAKE,wooga/FAKE,yonglehou/FAKE,darrelmiller/FAKE,daniel-chambers/FAKE,haithemaraissia/FAKE,molinch/FAKE,ArturDorochowicz/FAKE,satsuper/FAKE,beeker/FAKE,mfalda/FAKE,ArturDorochowicz/FAKE,hitesh97/FAKE,hitesh97/FAKE,philipcpresley/FAKE,leflings/FAKE,warnergodfrey/FAKE,philipcpresley/FAKE,tpetricek/FAKE,Kazark/FAKE,RMCKirby/FAKE,tpetricek/FAKE,naveensrinivasan/FAKE,pacificIT/FAKE,NaseUkolyCZ/FAKE,darrelmiller/FAKE,modulexcite/FAKE,dlsteuer/FAKE,Kazark/FAKE,pacificIT/FAKE,pmcvtm/FAKE,RMCKirby/FAKE,leflings/FAKE,rflechner/FAKE,featuresnap/FAKE,jayp33/FAKE,NaseUkolyCZ/FAKE,mfalda/FAKE,wooga/FAKE,modulexcite/FAKE,leflings/FAKE,NaseUkolyCZ/FAKE,mfalda/FAKE,RMCKirby/FAKE,haithemaraissia/FAKE,warnergodfrey/FAKE,ovu/FAKE,naveensrinivasan/FAKE,mglodack/FAKE,mat-mcloughlin/FAKE,brianary/FAKE,ilkerde/FAKE,JonCanning/FAKE,featuresnap/FAKE,pacificIT/FAKE,haithemaraissia/FAKE,warnergodfrey/FAKE,naveensrinivasan/FAKE,neoeinstein/FAKE,Kazark/FAKE,naveensrinivasan/FAKE,JonCanning/FAKE,darrelmiller/FAKE,dmorgan3405/FAKE,JonCanning/FAKE,rflechner/FAKE,tpetricek/FAKE,molinch/FAKE,ilkerde/FAKE,ilkerde/FAKE,dmorgan3405/FAKE,neoeinstein/FAKE,yonglehou/FAKE,MiloszKrajewski/FAKE,rflechner/FAKE,dmorgan3405/FAKE,darrelmiller/FAKE,mglodack/FAKE,brianary/FAKE,satsuper/FAKE,yonglehou/FAKE,mglodack/FAKE,wooga/FAKE,ctaggart/FAKE,daniel-chambers/FAKE,hitesh97/FAKE | src/test/Test.FAKECore/FileHandling/SubfolderSpecs.cs | src/test/Test.FAKECore/FileHandling/SubfolderSpecs.cs | using System.IO;
using Fake;
using Machine.Specifications;
namespace Test.FAKECore.FileHandling
{
public class when_detecting_subfolders
{
It should_detect_same_dir = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:/sub"), new DirectoryInfo("C:/sub")).ShouldBeTrue();
It should_detect_same_dir_slashes = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:/sub/"), new DirectoryInfo("C:/sub")).ShouldBeTrue();
It should_detect_1_level = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:/sub"), new DirectoryInfo("C:/sub/sub1")).ShouldBeTrue();
It should_detect_2_levels = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:/sub"), new DirectoryInfo("C:/sub/sub1/sub2")).ShouldBeTrue();
It should_detect_if_not_sub = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:/sub"), new DirectoryInfo("C:/main/sub/sub2")).ShouldBeFalse();
}
public class when_detecting_files_in_folders
{
It should_detect_same_dir = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:/sub"), new FileInfo("C:/sub/file.txt")).ShouldBeTrue();
It should_detect_same_dir_slashes = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:/sub/"), new FileInfo("C:/sub/file.txt")).ShouldBeTrue();
It should_detect_1_level = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:/sub"), new FileInfo("C:/sub/sub1/file.txt")).ShouldBeTrue();
It should_detect_2_levels = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:/sub"), new FileInfo("C:/sub/sub1/sub2/file.txt")).ShouldBeTrue();
It should_detect_caseinsensitive = () =>
FileSystemHelper.isInFolder(new DirectoryInfo("C:/code/uen/data"), new FileInfo("C:/code/uen/Data/Demo/Prozessvorlagen/4000004.XML")).ShouldBeTrue();
It should_detect_if_not_sub = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:/sub"), new FileInfo("C:/main/sub/sub2/file.txt")).ShouldBeFalse();
}
} | using System.IO;
using Fake;
using Machine.Specifications;
namespace Test.FAKECore.FileHandling
{
public class when_detecting_subfolders
{
It should_detect_same_dir = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:\\sub"), new DirectoryInfo("C:\\sub")).ShouldBeTrue();
It should_detect_same_dir_slashes = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:\\sub\\"), new DirectoryInfo("C:/sub")).ShouldBeTrue();
It should_detect_1_level = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:/sub"), new DirectoryInfo("C:\\sub\\sub1")).ShouldBeTrue();
It should_detect_2_levels = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:/sub"), new DirectoryInfo("C:\\sub\\sub1\\sub2")).ShouldBeTrue();
It should_detect_if_not_sub = () => FileSystemHelper.isSubfolderOf(new DirectoryInfo("C:/sub"), new DirectoryInfo("C:\\main\\sub\\sub2")).ShouldBeFalse();
}
public class when_detecting_files_in_folders
{
It should_detect_same_dir = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:\\sub"), new FileInfo("C:\\sub\\file.txt")).ShouldBeTrue();
It should_detect_same_dir_slashes = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:\\sub\\"), new FileInfo("C:/sub/file.txt")).ShouldBeTrue();
It should_detect_1_level = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:/sub"), new FileInfo("C:\\sub\\sub1\\file.txt")).ShouldBeTrue();
It should_detect_2_levels = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:/sub"), new FileInfo("C:\\sub\\sub1\\sub2\\file.txt")).ShouldBeTrue();
It should_detect_caseinsensitive = () =>
FileSystemHelper.isInFolder(new DirectoryInfo("C:\\code\\uen\\data"), new FileInfo("C:\\code\\uen\\Data\\Demo\\Prozessvorlagen\\4000004.XML")).ShouldBeTrue();
It should_detect_if_not_sub = () => FileSystemHelper.isInFolder(new DirectoryInfo("C:/sub"), new FileInfo("C:\\main\\sub\\sub2\\file.txt")).ShouldBeFalse();
}
} | apache-2.0 | C# |
a50f75a7604345693c50684f1b5afb1f995f6523 | Disable test parallelization to fix issues with mongodb driver upsert in tests | jageall/IdentityServer.v3.MongoDb | Source/Core.MongoDb.Tests/Properties/AssemblyInfo.cs | Source/Core.MongoDb.Tests/Properties/AssemblyInfo.cs | /*
* Copyright 2014, 2015 James Geall
*
* 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.Reflection;
using System.Runtime.InteropServices;
using Xunit;
// 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("Core.MongoDb.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Core.MongoDb.Tests")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("47b451c8-a499-4353-a840-6443b821c9de")]
// 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")]
[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true)] | /*
* Copyright 2014, 2015 James Geall
*
* 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.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Core.MongoDb.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Core.MongoDb.Tests")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("47b451c8-a499-4353-a840-6443b821c9de")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | apache-2.0 | C# |
359bea1ba3367f5483a1286c507c38bd7d18f91d | Comment out unused code. | GridProtectionAlliance/openHistorian,GridProtectionAlliance/openHistorian,GridProtectionAlliance/openHistorian,GridProtectionAlliance/openHistorian,GridProtectionAlliance/openHistorian,GridProtectionAlliance/openHistorian | Source/Tools/openHistorianServiceHost/MainService.cs | Source/Tools/openHistorianServiceHost/MainService.cs | using System.ServiceProcess;
namespace openHistorianServiceHost
{
public partial class MainService : ServiceBase
{
public MainService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//args = args;
}
protected override void OnStop()
{
}
}
} | using System.ServiceProcess;
namespace openHistorianServiceHost
{
public partial class MainService : ServiceBase
{
public MainService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
args = args;
}
protected override void OnStop()
{
}
}
} | mit | C# |
f9bba734ab4cf3459d454f13acbdbc68bd90e555 | Remove unused staff | Verrickt/BsodSimulator | BsodSimulator/MainPage.xaml.cs | BsodSimulator/MainPage.xaml.cs | using BsodSimulator.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace BsodSimulator
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPageVM VM{ get; set; }
public MainPage()
{
this.NavigationCacheMode = NavigationCacheMode.Required;
this.InitializeComponent();
VM = new MainPageVM();
}
}
}
| using BsodSimulator.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace BsodSimulator
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPageVM VM{ get; set; }
public MainPage()
{
this.NavigationCacheMode = NavigationCacheMode.Required;
this.InitializeComponent();
VM = new MainPageVM();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(BsodPage), VM);
}
}
}
| mit | C# |
2eaff7346381d7ce0ddd40724aa404fb862605a1 | Update ViewModelPut.cs | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | Test/NakedObjects.Rest.Test.EndToEnd/ViewModelPut.cs | Test/NakedObjects.Rest.Test.EndToEnd/ViewModelPut.cs | // Copyright © Naked Objects Group Ltd ( http://www.nakedobjects.net).
// All Rights Reserved. This code released under the terms of the
// Microsoft Public License (MS-PL) ( http://opensource.org/licenses/ms-pl.html)
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
namespace RestfulObjects.Test.EndToEnd {
[TestClass]
public class ViewModelPut : ObjectAbstract {
#region Helpers
protected override string FilePrefix {
get { return "ViewModel-Put-"; }
}
private string key1 = "31459"; //An arbitrarily large Id
#endregion
[TestMethod]
public void MostSimple() {
var body = new JObject(new JProperty("Id", new JObject(new JProperty("value", 123))));
Object(Urls.VMMostSimple + key1, "MostSimpleViewModel", body.ToString(), Methods.Put, Codes.Forbidden);
}
[TestMethod]
public void WithReference() {
var simpleJ = new JObject(new JProperty("value", new JObject(new JProperty(JsonRep.Href, Urls.Objects + Urls.MostSimple1))));
var body = new JObject(
new JProperty("AReference", simpleJ),
new JProperty("ANullReference", simpleJ),
new JProperty("AChoicesReference", simpleJ),
new JProperty("AnEagerReference", simpleJ),
new JProperty("Id", new JObject(new JProperty("value", key1)))
);
Object(Urls.VMWithReference + "1--2--2--1", "WithReference", body.ToString(), Methods.Put, Codes.Forbidden);
}
}
} | // Copyright © Naked Objects Group Ltd ( http://www.nakedobjects.net).
// All Rights Reserved. This code released under the terms of the
// Microsoft Public License (MS-PL) ( http://opensource.org/licenses/ms-pl.html)
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
namespace RestfulObjects.Test.EndToEnd {
[TestClass]
public class ViewModelPut : ObjectAbstract {
#region Helpers
protected override string FilePrefix {
get { return "ViewModel-Put-"; }
}
private string key1 = "31459"; //An arbitrarily large Id
#endregion
[Ignore]
[TestMethod]
public void MostSimple() {
//Note: This is a slightly unusual situation, in that the act of putting a new
//value into the Id property of the view model effectively creates a different view model instance!
//so the 'self' link url has changed!
var body = new JObject(new JProperty("Id", new JObject(new JProperty("value", 123))));
Object(Urls.VMMostSimple + key1, "MostSimpleViewModel", body.ToString(), Methods.Put);
}
[Ignore]
[TestMethod]
public void WithReference() {
var simpleJ = new JObject(new JProperty("value", new JObject(new JProperty(JsonRep.Href, Urls.Objects + Urls.MostSimple1))));
var body = new JObject(
new JProperty("AReference", simpleJ),
new JProperty("ANullReference", simpleJ),
new JProperty("AChoicesReference", simpleJ),
new JProperty("AnEagerReference", simpleJ),
new JProperty("Id", new JObject(new JProperty("value", key1)))
);
Object(Urls.VMWithReference + "1--2--2--1", "WithReference", body.ToString(), Methods.Put);
}
}
} | apache-2.0 | C# |
2ec300af1e846a53b8fa5ae2d888aa57076df5f8 | Fix build.cake | diogodamiani/IdentityServer4.MongoDB,diogodamiani/IdentityServer4.MongoDB,diogodamiani/IdentityServer4.MongoDB | build.cake | build.cake | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor;
var packPath = Directory("./src/IdentityServer4.MongoDB");
var sourcePath = Directory("./src");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
var projects = GetFiles("./**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
// Runtime = IsRunningOnWindows() ? null : "unix-x64"
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
});
//Task("RunTests")
// .IsDependentOn("Restore")
// .IsDependentOn("Clean")
// .Does(() =>
//{
// var projects = GetFiles("./test/**/project.json");
//
// foreach(var project in projects)
// {
// var settings = new DotNetCoreTestSettings
// {
// Configuration = configuration
// };
//
// DotNetCoreTest(project.GetDirectory().FullPath, settings);
// }
//});
Task("Pack")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = buildArtifacts,
};
// add build suffix for CI builds
if(!isLocalBuild)
{
settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0');
}
DotNetCorePack(packPath, settings);
});
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
Task("Restore")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
Sources = new [] { "https://api.nuget.org/v3/index.json" }
};
DotNetCoreRestore(sourcePath, settings);
//DotNetCoreRestore(testsPath, settings);
});
Task("Default")
.IsDependentOn("Build")
//.IsDependentOn("RunTests")
.IsDependentOn("Pack");
RunTarget(target); | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor;
var packPath = Directory("./src/IdentityServer4.MongoDB");
var sourcePath = Directory("./src");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
var projects = GetFiles("./**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
// Runtime = IsRunningOnWindows() ? null : "unix-x64"
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
});
Task("RunTests")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreTestSettings
{
Configuration = configuration
};
DotNetCoreTest(project.GetDirectory().FullPath, settings);
}
});
Task("Pack")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = buildArtifacts,
};
// add build suffix for CI builds
if(!isLocalBuild)
{
settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0');
}
DotNetCorePack(packPath, settings);
});
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
Task("Restore")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
Sources = new [] { "https://api.nuget.org/v3/index.json" }
};
DotNetCoreRestore(sourcePath, settings);
DotNetCoreRestore(testsPath, settings);
});
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("RunTests")
.IsDependentOn("Pack");
RunTarget(target); | apache-2.0 | C# |
8accaa464222c463889a0d95ebb96ba04be366f1 | Update build script | thomaslevesque/Linq.Extras | build.cake | build.cake | using System.Xml.Linq;
var target = Argument<string>("target", "Default");
var configuration = Argument<string>("configuration", "Release");
var projectName = "Linq.Extras";
var libraryProject = $"{projectName}/{projectName}.csproj";
var testProject = $"{projectName}.Tests/{projectName}.Tests.csproj";
var outDir = $"{projectName}/bin/{configuration}";
Task("Clean")
.Does(() =>
{
CleanDirectory(outDir);
});
Task("Restore").Does(DotNetCoreRestore);
Task("JustBuild")
.Does(() =>
{
DotNetCoreBuild(".", new DotNetCoreBuildSettings { Configuration = configuration });
});
Task("JustTest")
.Does(() =>
{
DotNetCoreTest(testProject, new DotNetCoreTestSettings { Configuration = configuration });
});
Task("JustPack")
.Does(() =>
{
DotNetCorePack(libraryProject, new DotNetCorePackSettings { Configuration = configuration });
});
Task("JustPush")
.Does(() =>
{
var doc = XDocument.Load(libraryProject);
string version = doc.Root.Elements("PropertyGroup").Elements("Version").First().Value;
string package = $"{projectName}/bin/{configuration}/{projectName}.{version}.nupkg";
NuGetPush(package, new NuGetPushSettings());
});
Task("Doc")
.Does(() =>
{
CleanDirectory("Documentation/Help");
MSBuild("Documentation/Documentation.shfbproj");
});
// High level tasks
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.IsDependentOn("JustBuild");
Task("Test")
.IsDependentOn("Build")
.IsDependentOn("JustTest");
Task("Pack")
.IsDependentOn("Build")
.IsDependentOn("JustPack");
Task("Push")
.IsDependentOn("Pack")
.IsDependentOn("JustPush");
Task("Default")
.IsDependentOn("Test")
.IsDependentOn("Pack");
RunTarget(target);
| ///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument<string>("target", "Default");
var configuration = Argument<string>("configuration", "Release");
var projectName = "Linq.Extras";
///////////////////////////////////////////////////////////////////////////////
// TASK DEFINITIONS
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectory($"./{projectName}/bin/{configuration}");
});
Task("Restore")
.Does(() => DotNetCoreRestore());
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
DotNetCoreBuild(".", new DotNetCoreBuildSettings { Configuration = configuration });
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest(
$"{projectName}.Tests/{projectName}.Tests.csproj",
new DotNetCoreTestSettings { Configuration = configuration });
});
Task("Pack")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCorePack(projectName, new DotNetCorePackSettings { Configuration = configuration });
});
Task("Doc")
.Does(() =>
{
CleanDirectory("Documentation/Help");
MSBuild("Documentation/Documentation.shfbproj");
});
///////////////////////////////////////////////////////////////////////////////
// TARGETS
///////////////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Test")
.IsDependentOn("Pack");
///////////////////////////////////////////////////////////////////////////////
// EXECUTION
///////////////////////////////////////////////////////////////////////////////
RunTarget(target);
| apache-2.0 | C# |
3fb81ca6b166e9748ba66d700213e6c7a1a81887 | change task dependencies | Sphiecoh/MusicStore,Sphiecoh/MusicStore | build.cake | build.cake | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor;
var sourcePath = Directory("./src/NancyMusicStore");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Publish")
.IsDependentOn("RunTests")
.Does(() =>
{
var settings = new DotNetCorePublishSettings
{
// Framework = "netcoreapp1.0",
Configuration = "Release",
OutputDirectory = buildArtifacts
};
DotNetCorePublish("./src/*", settings);
});
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
var projects = GetFiles("./**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
// Runtime = IsRunningOnWindows() ? null : "unix-x64"
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
});
Task("RunTests")
.IsDependentOn("Build")
.Does(() =>
{
var projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreTestSettings
{
Configuration = configuration
};
DotNetCoreTest(project.GetDirectory().FullPath, settings);
}
});
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
Task("Restore")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
Sources = new [] { "https://api.nuget.org/v3/index.json" }
};
DotNetCoreRestore("./src", settings);
//DotNetCoreRestore(testsPath, settings);
});
Task("Default")
.IsDependentOn("Build");
RunTarget(target); | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor;
var sourcePath = Directory("./src/NancyMusicStore");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Publish")
.Does(() =>
{
var settings = new DotNetCorePublishSettings
{
// Framework = "netcoreapp1.0",
Configuration = "Release",
OutputDirectory = buildArtifacts
};
DotNetCorePublish("./src/*", settings);
});
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
var projects = GetFiles("./**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
// Runtime = IsRunningOnWindows() ? null : "unix-x64"
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
});
Task("RunTests")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreTestSettings
{
Configuration = configuration
};
DotNetCoreTest(project.GetDirectory().FullPath, settings);
}
});
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
Task("Restore")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
Sources = new [] { "https://api.nuget.org/v3/index.json" }
};
DotNetCoreRestore("./src", settings);
//DotNetCoreRestore(testsPath, settings);
});
Task("Default")
.IsDependentOn("Build");
RunTarget(target); | mit | C# |
c84def7f417e72af5657c0ce40d7ba48683d502e | fix version string | IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates | build.cake | build.cake | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var buildArtifacts = Directory("./artifacts/packages");
var packageVersion = "1.0.0";
///////////////////////////////////////////////////////////////////////////////
// Clean
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
///////////////////////////////////////////////////////////////////////////////
// Copy
///////////////////////////////////////////////////////////////////////////////
Task("Copy")
.IsDependentOn("Clean")
.Does(() =>
{
CreateDirectory("./feed/content");
var files = GetFiles("./src/**/*.*");
CopyFiles(files, "./feed/content", true);
});
///////////////////////////////////////////////////////////////////////////////
// Pack
///////////////////////////////////////////////////////////////////////////////
Task("Pack")
.IsDependentOn("Clean")
.IsDependentOn("Copy")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = packageVersion,
OutputDirectory = buildArtifacts
};
if (AppVeyor.IsRunningOnAppVeyor)
{
settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings);
});
Task("Default")
.IsDependentOn("Pack");
RunTarget(target); | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var buildArtifacts = Directory("./artifacts/packages");
var packageVersion = "1.0.0";
///////////////////////////////////////////////////////////////////////////////
// Clean
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
///////////////////////////////////////////////////////////////////////////////
// Copy
///////////////////////////////////////////////////////////////////////////////
Task("Copy")
.IsDependentOn("Clean")
.Does(() =>
{
CreateDirectory("./feed/content");
var files = GetFiles("./src/**/*.*");
CopyFiles(files, "./feed/content", true);
});
///////////////////////////////////////////////////////////////////////////////
// Pack
///////////////////////////////////////////////////////////////////////////////
Task("Pack")
.IsDependentOn("Clean")
.IsDependentOn("Copy")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = packageVersion,
OutputDirectory = buildArtifacts
};
if (AppVeyor.IsRunningOnAppVeyor)
{
settings.Version = packageVersion + "b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings);
});
Task("Default")
.IsDependentOn("Pack");
RunTarget(target); | apache-2.0 | C# |
b3636632ba87050ce706f98f836093a1c73171a6 | Create dummy level lazily. | orasimus/interwall | Source/Assets/Code/X.cs | Source/Assets/Code/X.cs | using UnityEngine;
using System.Collections;
public class X : MonoBehaviour
{
public static Level Level
{
get
{
return new Level()
{
Interval = "Sounds/ding",
CorrectSheet = "A",
WrongSheet = "C",
WrongSheet2 = "G"
};
}
}
void Start ()
{
}
}
| using UnityEngine;
using System.Collections;
public class X : MonoBehaviour
{
public static Level Level;
void Start ()
{
Level = new Level()
{
Interval = "Sounds/ding",
CorrectSheet = "A",
WrongSheet = "C",
WrongSheet2 = "G"
};
}
}
| mit | C# |
d9ea2d720deb961b1054418c437f0212573bdaea | Change namespace to match project | TrekBikes/Trek.BalihooApiClient | ConsoleApplication1/Program.cs | ConsoleApplication1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Trek.BalihooApiClient.Sample
{
class Program
{
static void Main()
{
// https://github.com/balihoo/local-connect-client
var client = new BalihooApiClient();
//client.GenerateClientApiKey("", "");
// Not sure where this list of location Ids are supposed to come from
var list = new List<int> { 85104, 1103020 };
var result = client.GetCampaigns(list);
var tactics = (from location in result
from campaign in location.Value
from tactic in campaign.Tactics
select tactic.Id).Distinct().ToList();
foreach (var tacticId in tactics)
{
var tacticMetrics = client.GetTacticMetrics(list, tacticId);
}
Console.ReadLine();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Trek.BalihooApiClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
// https://github.com/balihoo/local-connect-client
var client = new BalihooApiClient();
//client.GenerateClientApiKey("", "");
// Not sure where this list of location Ids are supposed to come from
var list = new List<int> { 85104, 1103020 };
var result = client.GetCampaigns(list);
var tactics = (from location in result
from campaign in location.Value
from tactic in campaign.Tactics
select tactic.Id).Distinct().ToList();
foreach (var tacticId in tactics)
{
var tacticMetrics = client.GetTacticMetrics(list, tacticId);
}
Console.ReadLine();
}
}
}
| mit | C# |
57dcebcd1181eea2ae67305dab42243f00b597de | Rename ConferenceDataModel.ConferenceTitle -> ConferenceDataModel.ConferenceTopic and ConferenceDataModel.ConferenceUserTitle -> ConferenceDataModel.ConferenceTopicCustom | InfiniteSoul/Azuria | Azuria/Api/v1/DataModels/Messenger/ConferenceDataModel.cs | Azuria/Api/v1/DataModels/Messenger/ConferenceDataModel.cs | using System;
using Azuria.Api.v1.Converters;
using Azuria.Api.v1.Converters.Messenger;
using Newtonsoft.Json;
namespace Azuria.Api.v1.DataModels.Messenger
{
/// <summary>
/// </summary>
public class ConferenceDataModel : DataModelBase
{
/// <summary>
/// </summary>
[JsonProperty("id")]
public int ConferenceId { get; set; }
/// <summary>
/// </summary>
[JsonProperty("image")]
[JsonConverter(typeof(ImageConverter))]
public Uri ConferenceImage { get; set; }
/// <summary>
/// </summary>
[JsonProperty("topic")]
public string ConferenceTopic { get; set; }
/// <summary>
/// </summary>
[JsonProperty("topic_custom")]
public string ConferenceTopicCustom { get; set; }
/// <summary>
/// </summary>
[JsonProperty("group")]
public bool IsConferenceGroup { get; set; }
/// <summary>
/// </summary>
[JsonProperty("read")]
public bool IsLastMessageRead { get; set; }
/// <summary>
/// </summary>
[JsonProperty("timestamp_end")]
[JsonConverter(typeof(UnixToDateTimeConverter))]
public DateTime LastMessageTimeStamp { get; set; }
/// <summary>
/// </summary>
[JsonProperty("read_mid")]
public int LastReadMessageId { get; set; }
/// <summary>
/// </summary>
[JsonProperty("count")]
public int ParticipantsCount { get; set; }
/// <summary>
/// </summary>
[JsonProperty("read_count")]
public int UnreadMessagesCount { get; set; }
}
} | using System;
using Azuria.Api.v1.Converters;
using Azuria.Api.v1.Converters.Messenger;
using Newtonsoft.Json;
namespace Azuria.Api.v1.DataModels.Messenger
{
/// <summary>
/// </summary>
public class ConferenceDataModel : DataModelBase
{
/// <summary>
/// </summary>
[JsonProperty("id")]
public int ConferenceId { get; set; }
/// <summary>
/// </summary>
[JsonProperty("image")]
[JsonConverter(typeof(ImageConverter))]
public Uri ConferenceImage { get; set; }
/// <summary>
/// </summary>
[JsonProperty("topic")]
public string ConferenceTitle { get; set; }
/// <summary>
/// </summary>
[JsonProperty("topic_custom")]
public string ConferenceUserTitle { get; set; }
/// <summary>
/// </summary>
[JsonProperty("group")]
public bool IsConferenceGroup { get; set; }
/// <summary>
/// </summary>
[JsonProperty("read")]
public bool IsLastMessageRead { get; set; }
/// <summary>
/// </summary>
[JsonProperty("timestamp_end")]
[JsonConverter(typeof(UnixToDateTimeConverter))]
public DateTime LastMessageTimeStamp { get; set; }
/// <summary>
/// </summary>
[JsonProperty("read_mid")]
public int LastReadMessageId { get; set; }
/// <summary>
/// </summary>
[JsonProperty("count")]
public int ParticipantsCount { get; set; }
/// <summary>
/// </summary>
[JsonProperty("read_count")]
public int UnreadMessagesCount { get; set; }
}
} | mit | C# |
945644c4aae6feffbb360be0fb81f7f9b707139d | Fix game menu spawn | Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare | Assets/Scripts/Menu/GameMenu.cs | Assets/Scripts/Menu/GameMenu.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Attach to every menu animator
public class GameMenu : MonoBehaviour
{
public static SubMenu subMenu = SubMenu.Splash;
//public static SubMenu subMenu = SubMenu.Title; //Debug purposes
public static bool shifting;
public static SubMenu shiftingFrom;
private static GameMenu shiftOrigin;
public enum SubMenu
{
Splash = 0,
Title = 1,
Settings = 2,
Gamemode = 3,
Practice = 4,
PracticeSelect = 5,
Credits = 6,
Quit = 7
}
void Awake()
{
Cursor.visible = true;
shifting = (subMenu == SubMenu.Splash);
correctSubMenu();
setSubMenu((int)subMenu);
MenuAnimationUpdater updater = GetComponent<MenuAnimationUpdater>();
if (updater != null)
updater.updateAnimatorValues();
}
void correctSubMenu()
{
if (subMenu == SubMenu.PracticeSelect)
subMenu = SubMenu.Practice;
}
public void shift(int subMenu)
{
if (shiftOrigin == null)
shiftOrigin = this;
shiftingFrom = GameMenu.subMenu;
setSubMenu(subMenu);
shifting = true;
}
public void endShift()
{
if (shiftOrigin != this) //Shift cannot be ended by the same menu that starts it, this prevents early endShifts in reversible shift animations
{
shifting = false;
shiftOrigin = null;
}
}
void setSubMenu(int subMenu)
{
GameMenu.subMenu = (SubMenu)subMenu;
}
void setShifting(bool shifting)
{
GameMenu.shifting = shifting;
}
private void OnDestroy()
{
shifting = false;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Attach to every menu animator
public class GameMenu : MonoBehaviour
{
public static SubMenu subMenu = SubMenu.Credits;
//public static SubMenu subMenu = SubMenu.Title; //Debug purposes
public static bool shifting;
public static SubMenu shiftingFrom;
private static GameMenu shiftOrigin;
public enum SubMenu
{
Splash = 0,
Title = 1,
Settings = 2,
Gamemode = 3,
Practice = 4,
PracticeSelect = 5,
Credits = 6,
Quit = 7
}
void Awake()
{
Cursor.visible = true;
shifting = (subMenu == SubMenu.Splash);
correctSubMenu();
setSubMenu((int)subMenu);
MenuAnimationUpdater updater = GetComponent<MenuAnimationUpdater>();
if (updater != null)
updater.updateAnimatorValues();
}
void correctSubMenu()
{
if (subMenu == SubMenu.PracticeSelect)
subMenu = SubMenu.Practice;
}
public void shift(int subMenu)
{
if (shiftOrigin == null)
shiftOrigin = this;
shiftingFrom = GameMenu.subMenu;
setSubMenu(subMenu);
shifting = true;
}
public void endShift()
{
if (shiftOrigin != this) //Shift cannot be ended by the same menu that starts it, this prevents early endShifts in reversible shift animations
{
shifting = false;
shiftOrigin = null;
}
}
void setSubMenu(int subMenu)
{
GameMenu.subMenu = (SubMenu)subMenu;
}
void setShifting(bool shifting)
{
GameMenu.shifting = shifting;
}
private void OnDestroy()
{
shifting = false;
}
}
| mit | C# |
84fd75d690cfbacf83f776d62168a81e950a3444 | Switch default submenu to Splash | NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,plrusek/NitoriWare,Barleytree/NitoriWare | Assets/Scripts/Menu/GameMenu.cs | Assets/Scripts/Menu/GameMenu.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Attach to every menu animator
public class GameMenu : MonoBehaviour
{
public static SubMenu subMenu = SubMenu.Splash;
//public static SubMenu subMenu = SubMenu.Title; //Debug purposes
public static bool shifting;
public static SubMenu shiftingFrom;
private static GameMenu shiftOrigin;
public enum SubMenu
{
Splash = 0,
Title = 1,
Settings = 2,
Gamemode = 3,
Practice = 4,
PracticeSelect = 5,
Credits = 6,
Quit = 7
}
void Awake()
{
Cursor.visible = true;
shifting = (subMenu == SubMenu.Splash);
correctSubMenu();
setSubMenu((int)subMenu);
MenuAnimationUpdater updater = GetComponent<MenuAnimationUpdater>();
if (updater != null)
updater.updateAnimatorValues();
}
void correctSubMenu()
{
if (subMenu == SubMenu.PracticeSelect)
subMenu = SubMenu.Practice;
}
public void shift(int subMenu)
{
if (shiftOrigin == null)
shiftOrigin = this;
shiftingFrom = GameMenu.subMenu;
setSubMenu(subMenu);
shifting = true;
}
public void endShift()
{
if (shiftOrigin != this) //Shift cannot be ended by the same menu that starts it, this prevents early endShifts in reversible shift animations
{
shifting = false;
shiftOrigin = null;
}
}
void setSubMenu(int subMenu)
{
GameMenu.subMenu = (SubMenu)subMenu;
}
void setShifting(bool shifting)
{
GameMenu.shifting = shifting;
}
private void OnDestroy()
{
shifting = false;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Attach to every menu animator
public class GameMenu : MonoBehaviour
{
//public static SubMenu subMenu = SubMenu.Splash;
public static SubMenu subMenu = SubMenu.Title; //Debug purposes
public static bool shifting;
public static SubMenu shiftingFrom;
private static GameMenu shiftOrigin;
public enum SubMenu
{
Splash = 0,
Title = 1,
Settings = 2,
Gamemode = 3,
Practice = 4,
PracticeSelect = 5,
Credits = 6,
Quit = 7
}
void Awake()
{
Cursor.visible = true;
shifting = (subMenu == SubMenu.Splash);
correctSubMenu();
setSubMenu((int)subMenu);
MenuAnimationUpdater updater = GetComponent<MenuAnimationUpdater>();
if (updater != null)
updater.updateAnimatorValues();
}
void correctSubMenu()
{
if (subMenu == SubMenu.PracticeSelect)
subMenu = SubMenu.Practice;
}
public void shift(int subMenu)
{
if (shiftOrigin == null)
shiftOrigin = this;
shiftingFrom = GameMenu.subMenu;
setSubMenu(subMenu);
shifting = true;
}
public void endShift()
{
if (shiftOrigin != this) //Shift cannot be ended by the same menu that starts it, this prevents early endShifts in reversible shift animations
{
shifting = false;
shiftOrigin = null;
}
}
void setSubMenu(int subMenu)
{
GameMenu.subMenu = (SubMenu)subMenu;
}
void setShifting(bool shifting)
{
GameMenu.shifting = shifting;
}
private void OnDestroy()
{
shifting = false;
}
}
| mit | C# |
be4e535e16958ffcbfa49132d06196d0451fcc82 | Add CommandHelpAttribute Description and Options | appharbor/appharbor-cli | src/AppHarbor/CommandHelpAttribute.cs | src/AppHarbor/CommandHelpAttribute.cs | using System;
namespace AppHarbor
{
public class CommandHelpAttribute : Attribute
{
public CommandHelpAttribute(string description, string options = "")
{
Description = description;
Options = options;
}
public string Description
{
get;
private set;
}
public string Options
{
get;
private set;
}
}
}
| using System;
namespace AppHarbor
{
public class CommandHelpAttribute : Attribute
{
}
}
| mit | C# |
854139ac3767256ca9ae7b6b13ffe87e98634c26 | Fix SimpleLogManager | atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata | src/Atata/Logging/SimpleLogManager.cs | src/Atata/Logging/SimpleLogManager.cs | using OpenQA.Selenium;
using System;
using System.Text;
namespace Atata
{
public class SimpleLogManager : LogManagerBase
{
private Action<string> writeLineAction;
public SimpleLogManager(Action<string> writeLineAction, IWebDriver driver = null, string screenshotsFolderPath = null)
: base(driver, screenshotsFolderPath)
{
if (writeLineAction == null)
throw new ArgumentNullException("writeLineAction");
this.writeLineAction = writeLineAction;
}
public override void Info(string message, params object[] args)
{
Log("INFO", message, args);
}
public override void Warn(string message, params object[] args)
{
Log("WARN", message, args);
}
public override void Error(string message, Exception excepton)
{
Log("ERROR", string.Format("{0} {1}", message, excepton));
}
private void Log(string logLevel, string message, params object[] args)
{
StringBuilder builder = new StringBuilder();
builder.
Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")).
Append(" ").
Append(logLevel).
Append(" ").
AppendFormat(message, args);
writeLineAction(builder.ToString());
}
}
}
| using OpenQA.Selenium;
using System;
using System.Text;
namespace Atata
{
public class SimpleLogManager : LogManagerBase
{
private Action<string> writeLineAction;
public SimpleLogManager(Action<string> writeLineAction, IWebDriver driver = null, string screenshotsFolderPath = null)
: base(driver, screenshotsFolderPath)
{
if (writeLineAction == null)
throw new ArgumentNullException("writeLineAction");
this.writeLineAction = writeLineAction;
}
public override void Info(string message, params object[] args)
{
Log("INFO", message, args);
}
public override void Warn(string message, params object[] args)
{
Log("WARN", message, args);
}
public override void Error(string message, Exception excepton)
{
Log("ERROR", string.Format("{0} {1}", message, excepton));
}
private void Log(string logLevel, string message, params object[] args)
{
StringBuilder builder = new StringBuilder();
builder.
Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")).
Append(" ").
Append(logLevel).
Append(" ").
Append(message);
writeLineAction(builder.ToString());
}
}
}
| apache-2.0 | C# |
ce81ef186d45fb98df6f16ea38458f42f1f0882c | Add OnValueChange event StatModifiers | jkpenner/RPGSystemTutorial | Assets/Scripts/RPGSystems/Modifiers/RPGStatModifier.cs | Assets/Scripts/RPGSystems/Modifiers/RPGStatModifier.cs | using UnityEngine;
using System.Collections;
using System;
/// <summary>
/// The base class for all RPGStatModifiers
/// </summary>
public abstract class RPGStatModifier {
/// <summary>
/// Variable used for the Value property
/// </summary>
private float _value = 0f;
/// <summary>
/// Event that triggers when the Stat Modifier's Value property changes
/// </summary>
public event EventHandler OnValueChange;
/// <summary>
/// The order in which the modifier is applied to the stat
/// </summary>
public abstract int Order { get; }
/// <summary>
/// The value of the modifier that is combined with other
/// modifiers of the same stat then is passed to ApplyModifier
/// method to determine the final modifier value to apply to the stat
///
/// Triggers the OnValueChange event
/// </summary>
public float Value {
get {
return _value;
}
set {
if (_value != value) {
_value = value;
if (OnValueChange != null) {
OnValueChange(this, null);
}
}
}
}
/// <summary>
/// Does the modifier's value stat with other modifiers of the
/// same type. If value is false, the value of the single modifier will be used
/// if the sum of stacking modifiers is not greater then the not statcking mod.
/// </summary>
public bool Stacks { get; set; }
/// <summary>
/// Default Constructer
/// </summary>
public RPGStatModifier() {
Value = 0;
Stacks = true;
}
/// <summary>
/// Constructs a Stat Modifier with the given value and stack set to true
/// </summary>
public RPGStatModifier(float value) {
Value = value;
Stacks = true;
}
/// <summary>
/// Constructs a Stat Modifier with the given value and stack value
/// </summary>
public RPGStatModifier(float value, bool stacks) {
Value = value;
Stacks = stacks;
}
/// <summary>
/// Calculates the amount to apply to the stat based off the
/// sum of all the stat modifier's value and the current value of
/// the stat.
/// </summary>
public abstract int ApplyModifier(int statValue, float modValue);
}
| using UnityEngine;
using System.Collections;
/// <summary>
/// The base class for all RPGStatModifiers
/// </summary>
public abstract class RPGStatModifier {
/// <summary>
/// The order in which the modifier is applied to the stat
/// </summary>
public abstract int Order { get; }
/// <summary>
/// The value of the modifier that is combined with other
/// modifiers of the same stat then is passed to ApplyModifier
/// method to determine the final modifier value to apply to the stat
/// </summary>
public float Value { get; set; }
/// <summary>
/// Does the modifier's value stat with other modifiers of the
/// same type. If value is false, the value of the single modifier will be used
/// if the sum of stacking modifiers is not greater then the not statcking mod.
/// </summary>
public bool Stacks { get; set; }
/// <summary>
/// Default Constructer
/// </summary>
public RPGStatModifier() {
Value = 0;
Stacks = true;
}
/// <summary>
/// Constructs a Stat Modifier with the given value and stack set to true
/// </summary>
public RPGStatModifier(float value) {
Value = value;
Stacks = true;
}
/// <summary>
/// Constructs a Stat Modifier with the given value and stack value
/// </summary>
public RPGStatModifier(float value, bool stacks) {
Value = value;
Stacks = stacks;
}
/// <summary>
/// Calculates the amount to apply to the stat based off the
/// sum of all the stat modifier's value and the current value of
/// the stat.
/// </summary>
public abstract int ApplyModifier(int statValue, float modValue);
}
| mit | C# |
9c641ae82c884143c4f4dc02ae6ed70d2daa3385 | add test | vinhch/MongoData | src/MongoData.ConsoleTests/Program.cs | src/MongoData.ConsoleTests/Program.cs | using System;
using Microsoft.Extensions.DependencyInjection;
namespace MongoData.ConsoleTests
{
public class Program
{
public static void Main(string[] args)
{
AppStartup.Run();
Console.WriteLine("Press any key to start...");
Console.ReadKey();
//run test here
var testDb = AppStartup.ServiceProvider.GetService<TestDb>();
testDb.Run();
Console.ReadLine();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MongoData.ConsoleTests
{
public class Program
{
public static void Main(string[] args)
{
}
}
}
| mit | C# |
8ed33bddd12bb84f745673d405238e1b98103789 | Clean up csproj | peppy/osu-framework,ppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,peppy/osu-framework,Tom94/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework | osu-framework-native/osu-framework-native/Program.cs | osu-framework-native/osu-framework-native/Program.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu_framework_native
{
public class Program
{
public static void Main(string[] args)
{
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu_framework_native
{
public class Program
{
public static void Main(string[] args)
{
return;
}
}
}
| mit | C# |
10edbffbcc57ae2166bb36315cef57ad1cd64c16 | Update UrlFormatter.cs | rolembergfilho/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,dfaruque/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity | Serenity.Script.Core/SlickGrid/Formatters/UrlFormatter.cs | Serenity.Script.Core/SlickGrid/Formatters/UrlFormatter.cs | namespace Serenity
{
public class UrlFormatter : ISlickFormatter
{
public string Format(SlickFormatterContext ctx)
{
var display = !string.IsNullOrEmpty(DisplayProperty) ?
ctx.Item[DisplayProperty] as string : ctx.Value;
var url = !string.IsNullOrEmpty(UrlProperty) ?
ctx.Item[UrlProperty] as string : ctx.Value;
return "<a href='" + url + "'>" +
display +
"</a>";
}
[Option]
public string DisplayProperty { get; set; }
[Option]
public string UrlProperty { get; set; }
}
}
| namespace Serenity
{
public class UrlFormatter : ISlickFormatter
{
public string Format(SlickFormatterContext ctx)
{
return "<a href='" + Q.HtmlEncode(ctx.Value) + "'>" +
Q.HtmlEncode(ctx.Value) +
"</a>";
}
}
} | mit | C# |
255b1e3b3b283d88c1bf9e8d208290a48b3c18d2 | comment for IPatternNode#Name | tmichel/thesis | Interfaces/DMT.Matcher.Data.Interfaces/IPatternNode.cs | Interfaces/DMT.Matcher.Data.Interfaces/IPatternNode.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DMT.Core.Interfaces;
namespace DMT.Matcher.Data.Interfaces
{
/// <summary>
/// A pettern node is a regular node, but it is not part of the model. Pattern nodes
/// are there to mark how the pattern looks like. And also used for storing already
/// matched nodes.
///
/// When requesting an other matcher instance to find a partial match, pattern nodes will
/// be sent over the network with their matched nodes.
/// </summary>
public interface IPatternNode : INode
{
/// <summary>
/// Gets the name of the pattern node.
/// </summary>
string Name { get; }
/// <summary>
/// Gets or sets the node, that has been matched for this
/// particular pattern node.
/// </summary>
INode MatchedNode { get; set; }
/// <summary>
/// Determines whether the pattern node has been matched to a model node or not.
/// </summary>
bool IsMatched { get; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DMT.Core.Interfaces;
namespace DMT.Matcher.Data.Interfaces
{
/// <summary>
/// A pettern node is a regular node, but it is not part of the model. Pattern nodes
/// are there to mark how the pattern looks like. And also used for storing already
/// matched nodes.
///
/// When requesting an other matcher instance to find a partial match, pattern nodes will
/// be sent over the network with their matched nodes.
/// </summary>
public interface IPatternNode : INode
{
string Name { get; }
/// <summary>
/// Gets or sets the node, that has been matched for this
/// particular pattern node.
/// </summary>
INode MatchedNode { get; set; }
/// <summary>
/// Determines whether the pattern node has been matched to a model node or not.
/// </summary>
bool IsMatched { get; }
}
}
| mit | C# |
aa9dd1f6b785d8790d39bdc4fc33d00a6918ed8f | Fix signalr JS link on monitor page | timgranstrom/JabbR,mzdv/JabbR,18098924759/JabbR,M-Zuber/JabbR,SonOfSam/JabbR,timgranstrom/JabbR,18098924759/JabbR,JabbR/JabbR,JabbR/JabbR,ajayanandgit/JabbR,ajayanandgit/JabbR,mzdv/JabbR,e10/JabbR,e10/JabbR,yadyn/JabbR,yadyn/JabbR,yadyn/JabbR,borisyankov/JabbR,M-Zuber/JabbR,borisyankov/JabbR,SonOfSam/JabbR,borisyankov/JabbR | JabbR/Views/Home/monitor.cshtml | JabbR/Views/Home/monitor.cshtml | @using SquishIt.Framework;
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<ul id="logs">
</ul>
@{
WriteLiteral(Bundle.JavaScript().ForceRelease()
.Add("~/Scripts/jquery-2.0.3.min.js")
.Add("~/Scripts/jquery-migrate-1.2.1.min.js")
.Add("~/Scripts/json2.min.js")
.Add("~/Scripts/jquery.signalR-2.2.0-pre-140709-b104.min.js")
.Render("~/Scripts/JabbR3_#.js"));
}
<script type="text/javascript" src="@Url.Content("~/signalr/hubs")"></script>
<script type="text/javascript">
$(function () {
function encodeHtml(html) {
// html still emits double quotes so we need to replace these entities to use them in attributes.
return $("<div/>").text(html).html().replace(/\"/g, """);
}
var monitor = $.connection.monitor;
$.connection.hub.logging = true;
monitor.client.logMessage = function (value) {
$('#logs').prepend('<li class="message">' + encodeHtml(value).replace('\n', '<br/>') + '</li>');
};
monitor.client.logError = function (value) {
$('#logs').prepend('<li class="error">' + encodeHtml(value) + '</li>');
};
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, 5000);
});
$.connection.hub.start();
});
</script>
</body>
</html>
| @using SquishIt.Framework;
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<ul id="logs">
</ul>
@{
WriteLiteral(Bundle.JavaScript().ForceRelease()
.Add("~/Scripts/jquery-2.0.3.min.js")
.Add("~/Scripts/jquery-migrate-1.2.1.min.js")
.Add("~/Scripts/json2.min.js")
.Add("~/Scripts/jquery.signalR-2.1.0-pre-140513-b35.min.js")
.Render("~/Scripts/JabbR3_#.js"));
}
<script type="text/javascript" src="@Url.Content("~/signalr/hubs")"></script>
<script type="text/javascript">
$(function () {
function encodeHtml(html) {
// html still emits double quotes so we need to replace these entities to use them in attributes.
return $("<div/>").text(html).html().replace(/\"/g, """);
}
var monitor = $.connection.monitor;
$.connection.hub.logging = true;
monitor.client.logMessage = function (value) {
$('#logs').prepend('<li class="message">' + encodeHtml(value).replace('\n', '<br/>') + '</li>');
};
monitor.client.logError = function (value) {
$('#logs').prepend('<li class="error">' + encodeHtml(value) + '</li>');
};
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, 5000);
});
$.connection.hub.start();
});
</script>
</body>
</html>
| mit | C# |
532fb5693519e4a39db926b8c876139c280e2900 | Fix plotfolder activeness | joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net | JoinRpg.DataModel/PlotFolder.cs | JoinRpg.DataModel/PlotFolder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using JoinRpg.Helpers;
namespace JoinRpg.DataModel
{
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global — required by LINQ
public class PlotFolder : IProjectEntity, IDeletableSubEntity
{
public int PlotFolderId { get; set; }
public int ProjectId { get; set; }
public virtual Project Project { get; set; }
int IOrderableEntity.Id => PlotFolderId;
//TODO: Decide if title should be for players or for masters or we need two titles
public string MasterTitle { get; set; }
public MarkdownString MasterSummary { get; set; } = new MarkdownString();
public virtual ICollection<PlotElement> Elements { get; set; }
public string TodoField { get; set; }
public DateTime CreatedDateTime { get; set; }
public DateTime ModifiedDateTime { get; set; }
public virtual ICollection<CharacterGroup> RelatedGroups { get; set; }
public bool IsActive { get; set; }
public bool Completed
=>
IsActive && string.IsNullOrWhiteSpace(TodoField) && Elements.All(e => e.IsCompleted || !e.IsActive) &&
Elements.Any(e => e.IsActive);
public bool InWork => IsActive && !Completed;
public bool CanBePermanentlyDeleted => !Elements.Any();
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using JoinRpg.Helpers;
namespace JoinRpg.DataModel
{
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global — required by LINQ
public class PlotFolder : IProjectEntity, IDeletableSubEntity
{
public int PlotFolderId { get; set; }
public int ProjectId { get; set; }
public virtual Project Project { get; set; }
int IOrderableEntity.Id => PlotFolderId;
//TODO: Decide if title should be for players or for masters or we need two titles
public string MasterTitle { get; set; }
public MarkdownString MasterSummary { get; set; } = new MarkdownString();
public virtual ICollection<PlotElement> Elements { get; set; }
public string TodoField { get; set; }
public DateTime CreatedDateTime { get; set; }
public DateTime ModifiedDateTime { get; set; }
public virtual ICollection<CharacterGroup> RelatedGroups { get; set; }
public bool IsActive { get; set; }
public bool Completed => IsActive && string.IsNullOrWhiteSpace(TodoField) && Elements.All(e => e.IsCompleted) && Elements.Any();
public bool InWork => IsActive && !Completed;
public bool CanBePermanentlyDeleted => !Elements.Any();
}
} | mit | C# |
05cb935a940315ad6ff3bfdbed05c010ee09388c | change WikiMarkdownImage to extend OsuMarkdownImage | peppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,ppy/osu,ppy/osu | osu.Game/Overlays/Wiki/Markdown/WikiMarkdownImage.cs | osu.Game/Overlays/Wiki/Markdown/WikiMarkdownImage.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Markdig.Syntax.Inlines;
using osu.Game.Graphics.Containers.Markdown;
namespace osu.Game.Overlays.Wiki.Markdown
{
public class WikiMarkdownImage : OsuMarkdownImage
{
public WikiMarkdownImage(LinkInline linkInline)
: base(linkInline)
{
}
protected override ImageContainer CreateImageContainer(string url)
{
// The idea is replace "https://website.url/wiki/{path-to-image}" to "https://website.url/wiki/images/{path-to-image}"
// "/wiki/images/*" is route to fetch wiki image from osu!web server (see: https://github.com/ppy/osu-web/blob/4205eb66a4da86bdee7835045e4bf28c35456e04/routes/web.php#L289)
url = url.Replace("/wiki/", "/wiki/images/");
return base.CreateImageContainer(url);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Markdig.Syntax.Inlines;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Framework.Graphics.Cursor;
namespace osu.Game.Overlays.Wiki.Markdown
{
public class WikiMarkdownImage : MarkdownImage, IHasTooltip
{
public string TooltipText { get; }
public WikiMarkdownImage(LinkInline linkInline)
: base(linkInline.Url)
{
TooltipText = linkInline.Title;
}
protected override ImageContainer CreateImageContainer(string url)
{
// The idea is replace "https://website.url/wiki/{path-to-image}" to "https://website.url/wiki/images/{path-to-image}"
// "/wiki/images/*" is route to fetch wiki image from osu!web server (see: https://github.com/ppy/osu-web/blob/4205eb66a4da86bdee7835045e4bf28c35456e04/routes/web.php#L289)
url = url.Replace("/wiki/", "/wiki/images/");
return base.CreateImageContainer(url);
}
}
}
| mit | C# |
01820d2a746c68e9120ac64bbcf2c1d5033f1ed1 | Update Regex | pontazaricardo/DBMS_Parser_Insert | main/dbms_gui_02/dbms_gui_02/Test_Functions/Program.cs | main/dbms_gui_02/dbms_gui_02/Test_Functions/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using dbms_objects_data;
namespace Test_Functions
{
class Program
{
static void Main(string[] args)
{
//TestDB();\
TestRegex();
}
static void TestDB()
{
string[] table01_columns = new string[] { "id", "name", "last name", "address" };
Type[] table01_types = new Type[] { typeof(int), typeof(string), typeof(string), typeof(string) };
List<string> values = new List<string>() { "1", "test", "lastnametest", "add1" };
List<string> values02 = new List<string>() { "2", "test02" };
List<string> values02_columns = new List<string>() { "id", "name" };
Table table_test01 = new Table();
bool isTableCreated_01 = table_test01.CreateTable(table01_columns, table01_types);
bool inserted = table_test01.Insert(values);
bool inserted02 = table_test01.Insert(values02, values02_columns);
Database db = Database.GetInstance;
bool isTableCreated_02 = db.Create("table01", table01_columns, table01_types);
bool insertTest_02 = db.Insert("table01", values);
bool insertTest_03 = db.Insert("table01", values02, values02_columns);
bool insertTest_04 = db.Insert("table02", values02, values02_columns);
}
static void TestRegex()
{
string pattern = @"(?i)INSERT INTO (\S+)\s*(\S+)? VALUES \((\S+)\)";
string input = @"INSERT INTO table_name VALUES (1)";
foreach (Match m in Regex.Matches(input, pattern))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dbms_objects_data;
namespace Test_Functions
{
class Program
{
static void Main(string[] args)
{
TestDB();
}
static void TestDB()
{
string[] table01_columns = new string[] { "id", "name", "last name", "address" };
Type[] table01_types = new Type[] { typeof(int), typeof(string), typeof(string), typeof(string) };
List<string> values = new List<string>() { "1", "test", "lastnametest", "add1" };
List<string> values02 = new List<string>() { "2", "test02" };
List<string> values02_columns = new List<string>() { "id", "name" };
Table table_test01 = new Table();
bool isTableCreated_01 = table_test01.CreateTable(table01_columns, table01_types);
bool inserted = table_test01.Insert(values);
bool inserted02 = table_test01.Insert(values02, values02_columns);
Database db = Database.GetInstance;
bool isTableCreated_02 = db.Create("table01", table01_columns, table01_types);
bool insertTest_02 = db.Insert("table01", values);
bool insertTest_03 = db.Insert("table01", values02, values02_columns);
bool insertTest_04 = db.Insert("table02", values02, values02_columns);
}
static void TestRegex()
{
}
}
}
| mpl-2.0 | C# |
7a727a3fd32a28b609d3e49b0a89482f6ea88ffe | Fix for #23, parsing decimals is different between Locales | vampireneo/SlackAPI,smanabat/SlackAPI,Jaykul/SlackAPI,Inumedia/SlackAPI | JavascriptDateTimeConverter.cs | JavascriptDateTimeConverter.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
class JavascriptDateTimeConverter : Newtonsoft.Json.JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
decimal value = decimal.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture);
DateTime res = new DateTime(621355968000000000 + (long)(value * 10000000m)).ToLocalTime();
System.Diagnostics.Debug.Assert(
Decimal.Equals(
Decimal.Parse(res.ToProperTimeStamp()),
Decimal.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture)),
"Precision loss :(");
return res;
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
//Not sure if this is correct :D
writer.WriteValue(((DateTime)value).Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
class JavascriptDateTimeConverter : Newtonsoft.Json.JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
decimal value = decimal.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture);
DateTime res = new DateTime(621355968000000000 + (long)(value * 10000000m)).ToLocalTime();
System.Diagnostics.Debug.Assert(Decimal.Equals(Decimal.Parse(res.ToProperTimeStamp()), Decimal.Parse(reader.Value.ToString())), "Precision loss :(");
return res;
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
//Not sure if this is correct :D
writer.WriteValue(((DateTime)value).Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
}
}
}
| mit | C# |
14ff22e962afad5cbf51de089364e72a131037f8 | Improve handling of the singleton pattern of UniqueInstance | Seddryck/NBi,Seddryck/NBi | NBi.Xml/InstanceSettlingXml.cs | NBi.Xml/InstanceSettlingXml.cs | using NBi.Xml.Settings;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace NBi.Xml
{
[XmlInclude(typeof(InstanceUnique))]
public class InstanceSettlingXml
{
[XmlElement("local-variable")]
public InstanceVariableXml Variable { get; set; }
[XmlElement("category")]
public List<string> Categories { get; set; } = new List<string>();
[XmlElement("trait")]
public List<TraitXml> Traits { get; set; } = new List<TraitXml>();
public static InstanceSettlingXml Unique { get; } = new InstanceUnique();
public class InstanceUnique : InstanceSettlingXml
{ }
}
}
| using NBi.Xml.Settings;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace NBi.Xml
{
[XmlInclude(typeof(InstanceUnique))]
public class InstanceSettlingXml
{
[XmlElement("local-variable")]
public InstanceVariableXml Variable { get; set; }
[XmlElement("category")]
public List<string> Categories { get; set; } = new List<string>();
[XmlElement("trait")]
public List<TraitXml> Traits { get; set; } = new List<TraitXml>();
private static InstanceSettlingXml _unique { get; set; }
public static InstanceSettlingXml Unique
{
get
{
_unique = _unique ?? new InstanceUnique();
return _unique;
}
}
public class InstanceUnique : InstanceSettlingXml
{ }
}
}
| apache-2.0 | C# |
8aaad2afc99ab9751622af3093ffc6d8630a0467 | Fix Capitalize for null and empty strings | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Utilities/String.Capitalize.cs | source/Nuke.Common/Utilities/String.Capitalize.cs | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System.Globalization;
using JetBrains.Annotations;
namespace Nuke.Common.Utilities
{
public static partial class StringExtensions
{
[Pure]
public static string Capitalize(this string text)
{
return !text.IsNullOrEmpty()
? text.Substring(startIndex: 0, length: 1).ToUpper(CultureInfo.InvariantCulture) +
text.Substring(startIndex: 1)
: text;
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System.Globalization;
using JetBrains.Annotations;
namespace Nuke.Common.Utilities
{
public static partial class StringExtensions
{
[Pure]
public static string Capitalize(this string text)
{
return text.Substring(startIndex: 0, length: 1).ToUpper(CultureInfo.InvariantCulture) +
text.Substring(startIndex: 1);
}
}
}
| mit | C# |
5ce7dfa09d60e9edd5b8907b4f7c18acb51f0821 | Test removing new lines for compare | CommonBuildToolset/CBT.Modules,jeffkl/CBT.Modules | src/MSBuildProjectBuilder.UnitTest/ProjectTest.cs | src/MSBuildProjectBuilder.UnitTest/ProjectTest.cs | using Microsoft.MSBuildProjectBuilder;
using NUnit.Framework;
using Shouldly;
namespace MSBuildProjectBuilder.UnitTest
{
[TestFixture]
public class ProjectTest
{
private ProjectBuilder _project;
[OneTimeSetUp]
public void TestInitialize()
{
_project = new ProjectBuilder();
}
[Test]
public void Create()
{
string expectedOutput =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
</Project>".Replace("\r\n", string.Empty).Replace("\n", string.Empty);
_project.Create();
_project.ProjectRoot.RawXml.Replace("\r\n", string.Empty).Replace("\n", string.Empty);.ShouldBe(expectedOutput);
expectedOutput =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""4.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" DefaultTargets=""TestDefaultTarget"" InitialTargets=""TestInitialTarget"" Label=""TestLabel"">
</Project>".Replace("\r\n", string.Empty).Replace("\n", string.Empty);
_project.Create("test.csproj", "4.0", "TestDefaultTarget", "TestInitialTarget", "TestLabel");
_project.ProjectRoot.RawXml.Replace("\r\n", string.Empty).Replace("\n", string.Empty);.ShouldBe(expectedOutput);
}
}
}
| using Microsoft.MSBuildProjectBuilder;
using NUnit.Framework;
using Shouldly;
namespace MSBuildProjectBuilder.UnitTest
{
[TestFixture]
public class ProjectTest
{
private ProjectBuilder _project;
[OneTimeSetUp]
public void TestInitialize()
{
_project = new ProjectBuilder();
}
[Test]
public void Create()
{
string expectedOutput =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
</Project>";
_project.Create();
_project.ProjectRoot.RawXml.Replace("\r\n", System.Environment.NewLine).ShouldBe(expectedOutput);
expectedOutput =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""4.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" DefaultTargets=""TestDefaultTarget"" InitialTargets=""TestInitialTarget"" Label=""TestLabel"">
</Project>";
_project.Create("test.csproj", "4.0", "TestDefaultTarget", "TestInitialTarget", "TestLabel");
_project.ProjectRoot.RawXml.Replace("\r\n", System.Environment.NewLine).ShouldBe(expectedOutput);
}
}
}
| mit | C# |
74ef373de7b4e1729a1ff99e872d9e029f2a735d | Fix broken metadata unit test | autofac/Autofac | test/Autofac.Test/Features/Metadata/StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied.cs | test/Autofac.Test/Features/Metadata/StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied.cs | using Autofac.Core;
using Autofac.Features.Metadata;
using Autofac.Test.Features.Metadata.TestTypes;
using Autofac.Util;
using Xunit;
namespace Autofac.Test.Features.Metadata
{
public class StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied
{
private readonly IContainer _container;
public StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied()
{
var builder = new ContainerBuilder();
builder.RegisterType<object>();
_container = builder.Build();
}
[Fact]
public void ResolvingStronglyTypedMetadataWithoutDefaultValueThrowsException()
{
var exception = Assert.Throws<DependencyResolutionException>(
() => _container.Resolve<Meta<object, MyMeta>>());
var propertyName = ReflectionExtensions.GetProperty<MyMeta, int>(x => x.TheInt).Name;
var message = string.Format(MetadataViewProviderResources.MissingMetadata, propertyName);
Assert.Equal(message, exception.InnerException.Message);
}
[Fact]
public void ResolvingStronglyTypedMetadataWithDefaultValueProvidesDefault()
{
var m = _container.Resolve<Meta<object, MyMetaWithDefault>>();
Assert.Equal(42, m.Metadata.TheInt);
}
}
} | using System;
using Autofac.Core;
using Autofac.Core.Registration;
using Autofac.Features.Metadata;
using Autofac.Test.Features.Metadata.TestTypes;
using Autofac.Util;
using Xunit;
namespace Autofac.Test.Features.Metadata
{
public class StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied
{
private IContainer _container;
public StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied()
{
var builder = new ContainerBuilder();
builder.RegisterType<object>();
_container = builder.Build();
}
[Fact]
public void ResolvingStronglyTypedMetadataWithoutDefaultValueThrowsException()
{
var exception = Assert.Throws<DependencyResolutionException>(
() => _container.Resolve<Meta<object, MyMeta>>());
var propertyName = ReflectionExtensions.GetProperty<MyMeta, int>(x => x.TheInt).Name;
var message = string.Format(MetadataViewProviderResources.MissingMetadata, propertyName);
Assert.Equal(message, exception.Message);
}
[Fact]
public void ResolvingStronglyTypedMetadataWithDefaultValueProvidesDefault()
{
var m = _container.Resolve<Meta<object, MyMetaWithDefault>>();
Assert.Equal(42, m.Metadata.TheInt);
}
}
} | mit | C# |
10b9d9f2e762c2df7410eeff8776159bb68d1f84 | Add subscription to the subscription item class | richardlawley/stripe.net,stripe/stripe-dotnet | src/Stripe.net/Entities/StripeSubscriptionItem.cs | src/Stripe.net/Entities/StripeSubscriptionItem.cs | using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeSubscriptionItem : StripeEntityWithId, ISupportMetadata
{
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("created")]
[JsonConverter(typeof(StripeDateTimeConverter))]
public DateTime Created { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("plan")]
public StripePlan Plan { get; set; }
[JsonProperty("quantity")]
public int Quantity { get; set; }
[JsonProperty("subscription")]
public string Subscription { get; set; }
}
}
| using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeSubscriptionItem : StripeEntityWithId, ISupportMetadata
{
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("created")]
[JsonConverter(typeof(StripeDateTimeConverter))]
public DateTime Created { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("plan")]
public StripePlan Plan { get; set; }
[JsonProperty("quantity")]
public int Quantity { get; set; }
}
}
| apache-2.0 | C# |
67e19661fd2284263841f6663a0e8a99b5ffb258 | Rearrange class order so form designer works | SimpleScale/SimpleScale,SimpleScale/SimpleScale | TestApp/Form1.cs | TestApp/Form1.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using SimpleScale.HeadNode;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var queueManager = new MemoryQueueManager<Member>();
var mapService = new MapService<Member>(queueManager, new ValueMemberMapJob());
queueManager.Add(GetJobs());
mapService.Start();
}
public List<Job<Member>> GetJobs()
{
var job1 = new Job<Member>(0, new Member{ Name = "Tom"});
var job2 = new Job<Member>(1, new Member{ Name = "Dick"});
var job3 = new Job<Member>(2, new Member{ Name = "Harry"});
return new List<Job<Member>>{
job1, job2, job3
};
}
}
public class Member {
public string Name;
}
public class ValueMemberMapJob : IMapJob<Member>
{
public void DoWork(Job<Member> job)
{
MessageBox.Show("Processing member " + job.Info.Name);
Thread.Sleep(1000);
MessageBox.Show("Member " + job.Info.Name + " processed");
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using SimpleScale.HeadNode;
namespace TestApp
{
public class Member {
public string Name;
}
public class ValueMemberMapJob : IMapJob<Member>
{
public void DoWork(Job<Member> job)
{
MessageBox.Show("Processing member " + job.Info.Name);
Thread.Sleep(1000);
MessageBox.Show("Member " + job.Info.Name + " processed");
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var queueManager = new MemoryQueueManager<Member>();
var mapService = new MapService<Member>(queueManager, new ValueMemberMapJob());
queueManager.Add(GetJobs());
mapService.Start();
}
public List<Job<Member>> GetJobs()
{
var job1 = new Job<Member>(0, new Member{ Name = "Tom"});
var job2 = new Job<Member>(1, new Member{ Name = "Dick"});
var job3 = new Job<Member>(2, new Member{ Name = "Harry"});
return new List<Job<Member>>{
job1, job2, job3
};
}
}
}
| mit | C# |
6c5b36f75711e4b2d7eb62d4b3b05e42f4501899 | Add new file UITests/Tests.cs | ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl | UITests/Tests.cs | UITests/Tests.cs | � using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Android;
using Xamarin.UITest.Queries;
namespace userAuth.cpl.UITests
{
[TestFixture]
public class Tests
{
AndroidApp app;
[SetUp]
public void BeforeEachTest ()
{
app = ConfigureApp.Android.StartApp ();
}
[Test]
public void WelcomeTextIsDisplayed ()
{
AppResult[] results = app.WaitForElement (c => c.Marked ("Welcome to Xamarin Forms!"));
app.Screenshot ("Welcome screen.");
Assert.IsTrue (results.Any ());
}
}
}
namespace userAuth.cpl.Droid
struct init_struct ()
{
forms = userAuth.Forms.ApplicationException.Android.Config
}
[TestFixtureSetUp]
public class preTest
{
AndroidDevice device;
[SetUpFixture]
public void AlternateBeforeTestParam ()
{
device = IDevice.AndroidConfig.TestDevice ();
}
[TestAction]
public void TestResultsAreDisplayed ()
{
ITestAction[] actions = device.DisplayCurrentElement (c => c.Marked ("Results of the Droid Test are:") + results);
device.ImageCap ("Test Results.");
Math.IsInstance (actions.String ());
}
}
}
namespace Test.userAuth.cpl.Droid
static void Launch(string[]EventArgs)
{
System.Console.WriteLine("Renter the frames to count");
Console.WriteLine("Enter any additional parameters");
Console.ReadLine();
}
struct command(start)
{
start: (ev:Sysyem.Path) "PathTo" = internal.interface(cmdLet)
path = scanner("&B", "%6");
[Builtin]
public class start
{
InitUI init;
(stable): from userAuth.FrameAnchor import into internal InitUI(on: op)
}
} | � using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Android;
using Xamarin.UITest.Queries;
namespace userAuth.cpl.UITests
{
[TestFixture]
public class Tests
{
AndroidApp app;
[SetUp]
public void BeforeEachTest ()
{
app = ConfigureApp.Android.StartApp ();
}
[Test]
public void WelcomeTextIsDisplayed ()
{
AppResult[] results = app.WaitForElement (c => c.Marked ("Welcome to Xamarin Forms!"));
app.Screenshot ("Welcome screen.");
Assert.IsTrue (results.Any ());
}
}
}
namespace userAuth.cpl.Droid
struct init_struct ()
{
forms = userAuth.Forms.ApplicationException.Android.Config
}
[TestFixtureSetUp]
public class preTest
{
AndroidDevice device;
[SetUpFixture]
public void AlternateBeforeTestParam ()
{
device = IDevice.AndroidConfig.TestDevice ();
}
[TestAction]
public void TestResultsAreDisplayed ()
{
ITestAction[] actions = device.DisplayCurrentElement (c => c.Marked ("Results of the Droid Test are:") + results);
device.ImageCap ("Test Results.");
Math.IsInstance (actions.String ());
}
}
}
namespace Test.userAuth.cpl.Droid
struct command(start)
{
start: (ev:Sysyem.Path) "PathTo" = internal.interface(cmdLet)
path = scanner("&B", "%6");
[Builtin]
public class start
{
InitUI init;
(stable): from userAuth.FrameAnchor import into internal InitUI(on: op)
}
} | mit | C# |
36d3f5dd46f9a389ba0442a5191405c510255e0f | Fix MUDOs. | jandppw/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code | dotnet/Util/SharePoint/trunk/src/I/RenameAllOccurences.cs | dotnet/Util/SharePoint/trunk/src/I/RenameAllOccurences.cs | namespace PPWCode.Util.SharePoint.I
{
public class RenameAllOccurences : ISharepointAction
{
public RenameAllOccurences(ISharePointClient iSharePointClient, string baseRelativeUrl, string oldFolderName, string newFolderName)
{
Sharepoint = iSharePointClient;
BaseRelativeUrl = baseRelativeUrl;
OldFolderName = oldFolderName;
NewFolderName = newFolderName;
}
public void Do()
{
Sharepoint.RenameAllOccurrencesOfFolder(BaseRelativeUrl, OldFolderName, NewFolderName);
}
public void Undo()
{
Sharepoint.RenameAllOccurrencesOfFolder(BaseRelativeUrl, NewFolderName, OldFolderName);
}
public ISharePointClient Sharepoint { get; set; }
public string BaseRelativeUrl { get; set; }
public string OldFolderName { get; set; }
public string NewFolderName { get; set; }
}
} | namespace PPWCode.Util.SharePoint.I
{
public class RenameAllOccurences : ISharepointAction
{
public RenameAllOccurences(ISharePointClient iSharePointClient, string baseRelativeUrl, string oldFolderName, string newFolderName)
{
Sharepoint = iSharePointClient;
BaseRelativeUrl = baseRelativeUrl;
OldFolderName = oldFolderName;
NewFolderName = newFolderName;
}
public void Do()
{
// MUDO: rename all occurrences
Sharepoint.RenameFolder(BaseRelativeUrl, OldFolderName, NewFolderName);
}
public void Undo()
{
// MUDO: rename all occurrences
Sharepoint.RenameFolder(BaseRelativeUrl, NewFolderName, OldFolderName);
}
public ISharePointClient Sharepoint { get; set; }
public string BaseRelativeUrl { get; set; }
public string OldFolderName { get; set; }
public string NewFolderName { get; set; }
}
} | apache-2.0 | C# |
555a627e4ad9a5fe1222c4e47de3cb710a9d1953 | Build and publish Rock.Encryption.XSerializer nuget package | RockFramework/Rock.Encryption | Rock.Encryption.XSerializer/Properties/AssemblyInfo.cs | Rock.Encryption.XSerializer/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("Rock.Encryption.XSerializer")]
[assembly: AssemblyDescription("Extension to Rock.Encryption - allows properties marked with the [Encrypt] attribute to be encrypted during an XSerializer serialization operation.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Encryption.XSerializer")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9e66b304-79a0-4eed-a5f3-adaf0e27844b")]
// 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.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0")]
[assembly: AssemblyInformationalVersion("0.9.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("Rock.Encryption.XSerializer")]
[assembly: AssemblyDescription("Extension to Rock.Encryption - allows properties marked with the [Encrypt] attribute to be encrypted during an XSerializer serialization operation.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Encryption.XSerializer")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9e66b304-79a0-4eed-a5f3-adaf0e27844b")]
// 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.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0")]
[assembly: AssemblyInformationalVersion("0.9.0-rc3")]
| mit | C# |
3ac85abd28d1aa235f102c97da3474e66435dd2e | Rewrite GenerateJsonPocket to complete output | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/ChessVariantsTraining/Extensions/ChessGameExtensions.cs | src/ChessVariantsTraining/Extensions/ChessGameExtensions.cs | using ChessDotNet;
using ChessDotNet.Variants.Crazyhouse;
using System.Collections.Generic;
namespace ChessVariantsTraining.Extensions
{
public static class ChessGameExtensions
{
public static Dictionary<string, int> GenerateJsonPocket(this ChessGame game)
{
CrazyhouseChessGame zhCurrent = game as CrazyhouseChessGame;
if (zhCurrent == null)
{
return null;
}
Dictionary<string, int> pocket = new Dictionary<string, int>()
{
{ "white-queen", 0 },
{ "white-rook", 0 },
{ "white-bishop", 0 },
{ "white-knight", 0 },
{ "white-pawn", 0 },
{ "black-queen", 0 },
{ "black-rook", 0 },
{ "black-bishop", 0 },
{ "black-knight", 0 },
{ "black-pawn", 0 }
};
foreach (Piece p in zhCurrent.WhitePocket)
{
string key = "white-" + p.GetType().Name.ToLowerInvariant();
pocket[key]++;
}
foreach (Piece p in zhCurrent.BlackPocket)
{
string key = "black-" + p.GetType().Name.ToLowerInvariant();
pocket[key]++;
}
return pocket;
}
}
}
| using ChessDotNet;
using ChessDotNet.Variants.Crazyhouse;
using System.Collections.Generic;
namespace ChessVariantsTraining.Extensions
{
public static class ChessGameExtensions
{
public static Dictionary<string, int> GenerateJsonPocket(this ChessGame game)
{
CrazyhouseChessGame zhCurrent = game as CrazyhouseChessGame;
if (zhCurrent == null)
{
return null;
}
Dictionary<string, int> pocket = new Dictionary<string, int>();
foreach (Piece p in zhCurrent.WhitePocket)
{
string key = "white-" + p.GetType().Name.ToLowerInvariant();
if (!pocket.ContainsKey(key))
{
pocket.Add(key, 1);
}
else
{
pocket[key]++;
}
}
foreach (Piece p in zhCurrent.BlackPocket)
{
string key = "black-" + p.GetType().Name.ToLowerInvariant();
if (!pocket.ContainsKey(key))
{
pocket.Add(key, 1);
}
else
{
pocket[key]++;
}
}
return pocket;
}
}
}
| agpl-3.0 | C# |
042a9f6d31eaf54879420d0d78b184740a108635 | Add Route | erangeljr/SportsStore | SportsStore/SportsStore.WebUI/App_Start/RouteConfig.cs | SportsStore/SportsStore.WebUI/App_Start/RouteConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SportsStore.WebUI
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: null,
url: "Page{page}",
defaults: new { Controller = "Product", action = "List"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SportsStore.WebUI
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }
);
}
}
}
| mit | C# |
df6db16275f8c3c1ac9bda85bfc5cfd921649391 | simplify DrawRect (and fix that rect was drawn slightly transparent as part of GUIStyle.Draw) | Unity-Technologies/CodeEditor,Unity-Technologies/CodeEditor | src/CodeEditor.Text.UI.Unity.Engine/GUIUtils.cs | src/CodeEditor.Text.UI.Unity.Engine/GUIUtils.cs | using UnityEngine;
namespace CodeEditor.Text.UI.Unity.Engine
{
public class GUIUtils
{
private static Texture2D _whiteTexture;
public static void DrawRect(Rect rect, Color color)
{
var backup = GUI.color;
GUI.color = new Color(color.r, color.g, color.b);
GUI.DrawTexture(rect, whiteTexture, ScaleMode.StretchToFill, false);
GUI.color = backup;
}
private static Texture2D whiteTexture
{
get
{
if (_whiteTexture != null)
return _whiteTexture;
_whiteTexture = new Texture2D(1, 1);
_whiteTexture.SetPixel(0, 0, Color.white);
_whiteTexture.hideFlags = HideFlags.HideAndDontSave;
return _whiteTexture;
}
}
}
}
| using UnityEngine;
namespace CodeEditor.Text.UI.Unity.Engine
{
public class GUIUtils
{
private static GUIStyle _style;
public static void DrawRect(Rect rect, Color color)
{
var backup = GUI.color;
GUI.color = color;
GUI.Label(rect, GUIContent.none, Style);
GUI.color = backup;
}
protected static GUIStyle Style
{
get
{
if (_style != null)
return _style;
_style = new GUIStyle();
_style.normal.background = DummyTexture();
_style.normal.textColor = Color.white;
return _style;
}
}
private static Texture2D DummyTexture()
{
var dummyTexture = new Texture2D(1, 1);
dummyTexture.SetPixel(0,0,Color.white);
dummyTexture.hideFlags = HideFlags.HideAndDontSave;
return dummyTexture;
}
}
}
| mit | C# |
b293f505a837656666d186fa022d36de579dd413 | Change main page text, remove comments. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Views/Home/Index.cshtml | src/CompetitionPlatform/Views/Home/Index.cshtml | @model CompetitionPlatform.Models.ProjectViewModels.ProjectListIndexViewModel
@{
ViewData["Title"] = "Projects";
}
<section class="section section--lead section--padding">
<div class="container container--extend">
<h1 class="text-center page__title">Lykke<span>Streams</span></h1>
<h3 class="page__subtitle mb0">Here Great Ideas Meet the Brightest Minds</h3>
</div>
</section>
<section class="section section--competition_list">
<div class="container container--extend">
<div class="section_header">
<h3 class="section_header__title">Current Projects</h3>
</div>
</div>
</section>
<section id="projectListResults" class="section section--competition_list">
@await Html.PartialAsync("ProjectListPartial", Model)
</section>
| @model CompetitionPlatform.Models.ProjectViewModels.ProjectListIndexViewModel
@{
ViewData["Title"] = "Projects";
}
<section class="section section--lead section--padding">
<div class="container container--extend">
<h1 class="text-center page__title">Lykke<span>Streams</span></h1>
<h3 class="page__subtitle mb0">Is Helping the Great Ideas to Meet the Bright Minds</h3>
</div>
</section>
<section class="section section--competition_list">
<div class="container container--extend">
<div class="section_header">
<h3 class="section_header__title">Current Projects</h3>
</div>
@*<div class="row">
<div class="col-sm-3">
<div class="select form-group" data-control="select">
<label for="projectCategoryFilter" class="select__label control-label">Category:</label>
<div class="select__value"><span class="_value">All</span></div>
<select id="projectCategoryFilter" name="projectCategoryFilter" class="form-control select__elem">
<option value="All">All</option>
@foreach (var category in Model.ProjectCategories)
{
<option value="@category">@category</option>
}
</select>
</div>
</div>
<div class="col-sm-3">
<div class="select form-group" data-control="select">
<label for="projectStatusFilter" class="select__label control-label">Status:</label>
<div class="select__value"><span class="_value">All</span></div>
<select id="projectStatusFilter" name="projectStatusFilter" class="form-control select__elem">
<option value="All">All</option>
@foreach (var status in Enum.GetValues(typeof(Status)))
{
<option value=@status>@status</option>
}
</select>
</div>
</div>
<div class="col-sm-3">
<div class="select form-group" data-control="select">
<label for="projectPrizeFilter" class="select__label control-label">Prize:</label>
<div class="select__value"><span class="_value">Ascending</span></div>
<select id="projectPrizeFilter" name="projectPrizeFilter" class="form-control select__elem">
<option value=Ascending>Ascending</option>
<option value=Descending>Descending</option>
</select>
</div>
</div>
<div class="pull-right hidden-xs hidden-sm">
<a type="button" class="btn btn-circle new-project-button" href="/Project/Create">+</a>
</div>
</div>*@
</div>
</section>
<section id="projectListResults" class="section section--competition_list">
@await Html.PartialAsync("ProjectListPartial", Model)
</section>
| mit | C# |
b48561fc78bd98169ed5a69ebb6dd492e3eb79d9 | Add ResolveKeyProperty extension methods for backwards compat | henkmollema/Dommel | src/Dommel/DommelMapper.IKeyPropertyResolver.cs | src/Dommel/DommelMapper.IKeyPropertyResolver.cs | using System;
using System.Linq;
using System.Reflection;
using static Dommel.DommelMapper;
namespace Dommel
{
public static partial class DommelMapper
{
/// <summary>
/// Defines methods for resolving the key property of entities.
/// Custom implementations can be registerd with <see cref="SetKeyPropertyResolver(IKeyPropertyResolver)"/>.
/// </summary>
public interface IKeyPropertyResolver
{
/// <summary>
/// Resolves the key properties for the specified type.
/// </summary>
/// <param name="type">The type to resolve the key properties for.</param>
/// <returns>A collection of <see cref="PropertyInfo"/> instances of the key properties of <paramref name="type"/>.</returns>
PropertyInfo[] ResolveKeyProperties(Type type);
/// <summary>
/// Resolves the key properties for the specified type.
/// </summary>
/// <param name="type">The type to resolve the key properties for.</param>
/// <param name="isIdentity">Indicates whether the key properties are identity properties.</param>
/// <returns>A collection of <see cref="PropertyInfo"/> instances of the key properties of <paramref name="type"/>.</returns>
PropertyInfo[] ResolveKeyProperties(Type type, out bool isIdentity);
}
}
/// <summary>
/// Extensions for <see cref="IKeyPropertyResolver"/>.
/// </summary>
public static class KeyPropertyResolverExtensions
{
/// <summary>
/// Resolves the single key property for the specified type.
/// </summary>
/// <param name="keyPropertyResolver">The <see cref="IKeyPropertyResolver"/>.</param>
/// <param name="type">The type to resolve the key property for.</param>
/// <returns>A <see cref="PropertyInfo"/> instance of the key property of <paramref name="type"/>.</returns>
public static PropertyInfo ResolveKeyProperty(this IKeyPropertyResolver keyPropertyResolver, Type type)
=> keyPropertyResolver.ResolveKeyProperties(type).FirstOrDefault();
/// <summary>
/// Resolves the single key property for the specified type.
/// </summary>
/// <param name="keyPropertyResolver">The <see cref="IKeyPropertyResolver"/>.</param>
/// <param name="type">The type to resolve the key property for.</param>
/// <param name="isIdentity">Indicates whether the key properties are identity properties.</param>
/// <returns>A <see cref="PropertyInfo"/> instance of the key property of <paramref name="type"/>.</returns>
public static PropertyInfo ResolveKeyProperty(this IKeyPropertyResolver keyPropertyResolver, Type type, out bool isIdentity) =>
keyPropertyResolver.ResolveKeyProperties(type, out isIdentity).FirstOrDefault();
}
}
| using System;
using System.Reflection;
namespace Dommel
{
public static partial class DommelMapper
{
/// <summary>
/// Defines methods for resolving the key property of entities.
/// Custom implementations can be registerd with <see cref="SetKeyPropertyResolver(IKeyPropertyResolver)"/>.
/// </summary>
public interface IKeyPropertyResolver
{
/// <summary>
/// Resolves the key properties for the specified type.
/// </summary>
/// <param name="type">The type to resolve the key properties for.</param>
/// <returns>A collection of <see cref="PropertyInfo"/> instances of the key properties of <paramref name="type"/>.</returns>
PropertyInfo[] ResolveKeyProperties(Type type);
/// <summary>
/// Resolves the key properties for the specified type.
/// </summary>
/// <param name="type">The type to resolve the key properties for.</param>
/// <param name="isIdentity">Indicates whether the key properties are identity properties.</param>
/// <returns>A collection of <see cref="PropertyInfo"/> instances of the key properties of <paramref name="type"/>.</returns>
PropertyInfo[] ResolveKeyProperties(Type type, out bool isIdentity);
}
}
}
| mit | C# |
976aac81f0d3791cd2406715c9e351c377d527a3 | fix non-async write in FixedAltitudeDemTileProvider | WorldWideTelescope/wwt-website,WorldWideTelescope/wwt-website,WorldWideTelescope/wwt-website | src/WWT.Providers/Providers/Fixedaltitudedemtileprovider.cs | src/WWT.Providers/Providers/Fixedaltitudedemtileprovider.cs | #nullable disable
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace WWT.Providers
{
[RequestEndpoint("/wwtweb/FixedAltitudeDemTile.aspx")]
public class FixedAltitudeDemTileProvider : RequestProvider
{
public override string ContentType => ContentTypes.OctetStream;
public override async Task RunAsync(IWwtContext context, CancellationToken token)
{
string query = context.Request.Params["Q"];
string[] values = query.Split(',');
//int level = Convert.ToInt32(values[0]);
//int tileX = Convert.ToInt32(values[1]);
//int tileY = Convert.ToInt32(values[2]);
string alt = context.Request.Params["alt"];
string proj = context.Request.Params["proj"];
float altitude = float.Parse(alt);
int demSize = 33 * 33;
if (proj.ToLower().StartsWith("t"))
{
demSize = 17 * 17;
}
var data = new byte[demSize * 4];
using var ms = new MemoryStream(data);
var bw = new BinaryWriter(ms);
for (int i = 0; i < demSize; i++)
{
bw.Write(altitude);
}
bw.Flush();
await context.Response.OutputStream.WriteAsync(data, 0, data.Length, token);
context.Response.End();
}
}
}
| #nullable disable
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace WWT.Providers
{
[RequestEndpoint("/wwtweb/FixedAltitudeDemTile.aspx")]
public class FixedAltitudeDemTileProvider : RequestProvider
{
public override string ContentType => ContentTypes.OctetStream;
public override Task RunAsync(IWwtContext context, CancellationToken token)
{
string query = context.Request.Params["Q"];
string[] values = query.Split(',');
//int level = Convert.ToInt32(values[0]);
//int tileX = Convert.ToInt32(values[1]);
//int tileY = Convert.ToInt32(values[2]);
string alt = context.Request.Params["alt"];
string proj = context.Request.Params["proj"];
float altitude = float.Parse(alt);
int demSize = 33 * 33;
if (proj.ToLower().StartsWith("t"))
{
demSize = 17 * 17;
}
BinaryWriter bw = new BinaryWriter(context.Response.OutputStream);
for (int i = 0; i < demSize; i++)
{
bw.Write(altitude);
}
bw = null;
context.Response.End();
return Task.CompletedTask;
}
}
}
| mit | C# |
8e3bd557048e764d7263272c9578e004d49ecd2c | Fix CircularContainer not always being circular | ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,default0/osu-framework,Tom94/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,default0/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,Nabile-Rahmani/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,peppy/osu-framework | osu.Framework/Graphics/Containers/CircularContainer.cs | osu.Framework/Graphics/Containers/CircularContainer.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A container which is rounded (via automatic corner-radius) on the shortest edge.
/// </summary>
public class CircularContainer : Container
{
public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true)
{
if ((invalidation & Invalidation.DrawSize) > 0)
CornerRadius = Math.Min(DrawSize.X, DrawSize.Y) / 2f;
return base.Invalidate(invalidation, source, shallPropagate);
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A container which is rounded (via automatic corner-radius) on the shortest edge.
/// </summary>
public class CircularContainer : Container
{
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
CornerRadius = Math.Min(DrawSize.X, DrawSize.Y) / 2f;
}
}
}
| mit | C# |
e09715d71efe23bdedf5a6b7718e6bdbe4ef2258 | Add ToString implementation to MultiplayerRoom for easier debug | NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu | osu.Game/Online/RealtimeMultiplayer/MultiplayerRoom.cs | osu.Game/Online/RealtimeMultiplayer/MultiplayerRoom.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// A multiplayer room.
/// </summary>
[Serializable]
public class MultiplayerRoom
{
/// <summary>
/// The ID of the room, used for database persistence.
/// </summary>
public readonly long RoomID;
/// <summary>
/// The current state of the room (ie. whether it is in progress or otherwise).
/// </summary>
public MultiplayerRoomState State { get; set; }
/// <summary>
/// All currently enforced game settings for this room.
/// </summary>
public MultiplayerRoomSettings Settings { get; set; } = new MultiplayerRoomSettings();
/// <summary>
/// All users currently in this room.
/// </summary>
public List<MultiplayerRoomUser> Users { get; set; } = new List<MultiplayerRoomUser>();
/// <summary>
/// The host of this room, in control of changing room settings.
/// </summary>
public MultiplayerRoomUser? Host { get; set; }
private object writeLock = new object();
public MultiplayerRoom(in long roomId)
{
RoomID = roomId;
}
/// <summary>
/// Request a lock on this room to perform a thread-safe update.
/// </summary>
public LockUntilDisposal LockForUpdate() => new LockUntilDisposal(writeLock);
public override string ToString() => $"RoomID:{RoomID} Host:{Host?.UserID} Users:{Users.Count} State:{State} Settings: [{Settings}]";
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// A multiplayer room.
/// </summary>
[Serializable]
public class MultiplayerRoom
{
/// <summary>
/// The ID of the room, used for database persistence.
/// </summary>
public readonly long RoomID;
/// <summary>
/// The current state of the room (ie. whether it is in progress or otherwise).
/// </summary>
public MultiplayerRoomState State { get; set; }
/// <summary>
/// All currently enforced game settings for this room.
/// </summary>
public MultiplayerRoomSettings Settings { get; set; } = new MultiplayerRoomSettings();
/// <summary>
/// All users currently in this room.
/// </summary>
public List<MultiplayerRoomUser> Users { get; set; } = new List<MultiplayerRoomUser>();
/// <summary>
/// The host of this room, in control of changing room settings.
/// </summary>
public MultiplayerRoomUser? Host { get; set; }
private object writeLock = new object();
public MultiplayerRoom(in long roomId)
{
RoomID = roomId;
}
/// <summary>
/// Request a lock on this room to perform a thread-safe update.
/// </summary>
public LockUntilDisposal LockForUpdate() => new LockUntilDisposal(writeLock);
}
}
| mit | C# |
47f524b375a12ee7beb5d8d4b62122b7905f17ae | use less memory | dethi/troma | src/TerrainAutomator/TerrainAutomator/ProcessImage.cs | src/TerrainAutomator/TerrainAutomator/ProcessImage.cs | using System.Drawing;
namespace TerrainAutomator
{
static class ProcessImage
{
public static Image CropImage(Image img, Rectangle cropArea)
{
return ((Bitmap)img).Clone(cropArea, img.PixelFormat);
}
public static Image resizeImage(Image img, Size newSize)
{
Bitmap b = new Bitmap(newSize.Width, newSize.Height);
Graphics g = Graphics.FromImage((Image)b);
g.DrawImage(img, 0, 0, newSize.Width, newSize.Height);
g.Dispose();
return (Image)b;
}
}
}
| using System.Drawing;
namespace TerrainAutomator
{
static class ProcessImage
{
public static Image CropImage(Image img, Rectangle cropArea)
{
Bitmap bmp = new Bitmap(img);
Bitmap bmpCrop = bmp.Clone(cropArea, bmp.PixelFormat);
return (Image)(bmpCrop);
}
public static Image resizeImage(Image img, Size newSize)
{
Bitmap b = new Bitmap(newSize.Width, newSize.Height);
Graphics g = Graphics.FromImage((Image)b);
g.DrawImage(img, 0, 0, newSize.Width, newSize.Height);
g.Dispose();
return (Image)b;
}
}
}
| mit | C# |
35e6f10a03fa9c3050b24f10f8450ad0c039441f | Set the assembly info | Nepochal/redshift-tray | redshift-tray/redshift-tray/Properties/AssemblyInfo.cs | redshift-tray/redshift-tray/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("Redshift Tray")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("mischolz.de")]
[assembly: AssemblyProduct("Redshift Tray")]
[assembly: AssemblyCopyright("Copyright © Michael Scholz 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
//Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie
//<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei
//in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch
//(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung
//des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile,
//sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher
//(wird verwendet, wenn eine Ressource auf der Seite
// oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.)
ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs
//(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem
// designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.)
)]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("redshift-tray")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("redshift-tray")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
//Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie
//<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei
//in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch
//(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung
//des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile,
//sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher
//(wird verwendet, wenn eine Ressource auf der Seite
// oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.)
ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs
//(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem
// designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.)
)]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
3639b6fb7c4c17b18d26b49f6613ffc076c408f3 | Add Server support to WaitForState. | DimensionDataResearch/cloudcontrol-client-core | src/DD.CloudControl.Client/CloudControlClient.WaitForStatus.cs | src/DD.CloudControl.Client/CloudControlClient.WaitForStatus.cs | using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace DD.CloudControl.Client
{
using Models;
using Models.Network;
using Models.Server;
/// <summary>
/// The CloudControl API client.
/// </summary>
public partial class CloudControlClient
{
/// <summary>
/// Wait for a resource to reach the specified state.
/// </summary>
/// <typeparam name="TResource">
/// The resource type.
/// </typeparam>
/// <param name="resourceId">
/// The resource Id.
/// </param>
/// <param name="targetState">
/// The resource state to wait for.
/// </param>
/// <param name="timeout">
/// The amount of time to wait for the resource to reach the target state.
/// </param>
/// <param name="cancellationToken">
/// An optional cancellation token that can be used to cancel the request.
/// </param>
/// <returns>
/// The resource (or <c>null</c> if the resource has been deleted).
/// </returns>
/// <exception cref="TimeoutException">
/// The timeout period elapsed before the resource reached the target state.
/// </exception>
/// <exception cref="CloudControlException">
/// The target resource was not found with the specified Id, and <paramref name="targetState"/> is not <see cref="ResourceState.Deleted"/>
/// </exception>
public async Task<TResource> WaitForState<TResource>(Guid resourceId, ResourceState targetState, TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
where TResource : Resource
{
Stopwatch stopwatch = Stopwatch.StartNew();
Func<Guid, CancellationToken, Task<Resource>> loader = CreateResourceLoader<TResource>();
Resource resource = await loader(resourceId, cancellationToken);
while (resource != null && resource.State != targetState)
{
if (stopwatch.Elapsed > timeout)
throw new TimeoutException($"Timed out after waiting {timeout.TotalSeconds} seconds for {typeof(TResource).Name} '{resourceId}' to reach state '{targetState}'.");
resource = await loader(resourceId, cancellationToken);
}
if (resource == null && targetState != ResourceState.Deleted)
throw new CloudControlException($"{typeof(TResource).Name} not found with Id '{resourceId}'.");
return (TResource)resource;
}
/// <summary>
/// Create a delegate that loads a resource of the specified type by Id.
/// </summary>
/// <typeparam name="TResource">
/// The resource type.
/// </typeparam>
/// <returns>
/// The loader delegate.
/// </returns>
Func<Guid, CancellationToken, Task<Resource>> CreateResourceLoader<TResource>()
where TResource : Resource
{
Type resourceType = typeof(TResource);
if (resourceType == typeof(NetworkDomain))
return async (resourceId, cancellationToken) => await GetNetworkDomain(resourceId, cancellationToken);
else if (resourceType == typeof(Vlan))
return async (resourceId, cancellationToken) => await GetVlan(resourceId, cancellationToken);
else if (resourceType == typeof(Server))
return async (resourceId, cancellationToken) => await GetServer(resourceId, cancellationToken);
else
throw new InvalidOperationException($"Unexpected resource type '{typeof(TResource)}'");
}
}
} | using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace DD.CloudControl.Client
{
using Models;
using Models.Network;
/// <summary>
/// The CloudControl API client.
/// </summary>
public partial class CloudControlClient
{
/// <summary>
/// Wait for a resource to reach the specified state.
/// </summary>
/// <typeparam name="TResource">
/// The resource type.
/// </typeparam>
/// <param name="resourceId">
/// The resource Id.
/// </param>
/// <param name="targetState">
/// The resource state to wait for.
/// </param>
/// <param name="timeout">
/// The amount of time to wait for the resource to reach the target state.
/// </param>
/// <param name="cancellationToken">
/// An optional cancellation token that can be used to cancel the request.
/// </param>
/// <returns>
/// The resource (or <c>null</c> if the resource has been deleted).
/// </returns>
/// <exception cref="TimeoutException">
/// The timeout period elapsed before the resource reached the target state.
/// </exception>
/// <exception cref="CloudControlException">
/// The target resource was not found with the specified Id, and <paramref name="targetState"/> is not <see cref="ResourceState.Deleted"/>
/// </exception>
public async Task<TResource> WaitForState<TResource>(Guid resourceId, ResourceState targetState, TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
where TResource : Resource
{
Stopwatch stopwatch = Stopwatch.StartNew();
Func<Guid, CancellationToken, Task<Resource>> loader = CreateResourceLoader<TResource>();
Resource resource = await loader(resourceId, cancellationToken);
while (resource != null && resource.State != targetState)
{
if (stopwatch.Elapsed > timeout)
throw new TimeoutException($"Timed out after waiting {timeout.TotalSeconds} seconds for {typeof(TResource).Name} '{resourceId}' to reach state '{targetState}'.");
resource = await loader(resourceId, cancellationToken);
}
if (resource == null && targetState != ResourceState.Deleted)
throw new CloudControlException($"{typeof(TResource).Name} not found with Id '{resourceId}'.");
return (TResource)resource;
}
/// <summary>
/// Create a delegate that loads a resource of the specified type by Id.
/// </summary>
/// <typeparam name="TResource">
/// The resource type.
/// </typeparam>
/// <returns>
/// The loader delegate.
/// </returns>
Func<Guid, CancellationToken, Task<Resource>> CreateResourceLoader<TResource>()
where TResource : Resource
{
Type resourceType = typeof(TResource);
if (resourceType == typeof(NetworkDomain))
return async (resourceId, cancellationToken) => await GetNetworkDomain(resourceId, cancellationToken);
else if (resourceType == typeof(Vlan))
return async (resourceId, cancellationToken) => await GetVlan(resourceId, cancellationToken);
else
throw new InvalidOperationException($"Unexpected resource type '{typeof(TResource)}'");
}
}
} | mit | C# |
2540e946c049b23bf59533982b9965c88358c2af | Fix typo for xml comments in GetMultipartBoundary method (#39266) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Http/Http.Extensions/src/HttpRequestMultipartExtensions.cs | src/Http/Http.Extensions/src/HttpRequestMultipartExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Http.Extensions;
/// <summary>
/// Extension methods for working with multipart form requests.
/// </summary>
public static class HttpRequestMultipartExtensions
{
/// <summary>
/// Gets the multipart boundary from the <c>Content-Type</c> header.
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/>.</param>
/// <returns>The multipart boundary.</returns>
public static string GetMultipartBoundary(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaType))
{
return string.Empty;
}
return HeaderUtilities.RemoveQuotes(mediaType.Boundary).ToString();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Http.Extensions;
/// <summary>
/// Extension methods for working with multipart form requests.
/// </summary>
public static class HttpRequestMultipartExtensions
{
/// <summary>
/// Gets the mutipart boundary from the <c>Content-Type</c> header.
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/>.</param>
/// <returns>The multipart boundary.</returns>
public static string GetMultipartBoundary(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaType))
{
return string.Empty;
}
return HeaderUtilities.RemoveQuotes(mediaType.Boundary).ToString();
}
}
| apache-2.0 | C# |
01c0b0e0dc2ce357be9430abd095176dec40fc68 | add store to timestamp field mapping | wawrzyn/elasticsearch-net,SeanKilleen/elasticsearch-net,robrich/elasticsearch-net,mac2000/elasticsearch-net,mac2000/elasticsearch-net,mac2000/elasticsearch-net,junlapong/elasticsearch-net,joehmchan/elasticsearch-net,LeoYao/elasticsearch-net,wawrzyn/elasticsearch-net,junlapong/elasticsearch-net,gayancc/elasticsearch-net,LeoYao/elasticsearch-net,robertlyson/elasticsearch-net,abibell/elasticsearch-net,wawrzyn/elasticsearch-net,abibell/elasticsearch-net,DavidSSL/elasticsearch-net,gayancc/elasticsearch-net,abibell/elasticsearch-net,DavidSSL/elasticsearch-net,robrich/elasticsearch-net,SeanKilleen/elasticsearch-net,junlapong/elasticsearch-net,robrich/elasticsearch-net,robertlyson/elasticsearch-net,DavidSSL/elasticsearch-net,SeanKilleen/elasticsearch-net,LeoYao/elasticsearch-net,gayancc/elasticsearch-net,joehmchan/elasticsearch-net,joehmchan/elasticsearch-net,robertlyson/elasticsearch-net | src/Nest/Domain/Mapping/SpecialFields/TimestampFieldMapping.cs | src/Nest/Domain/Mapping/SpecialFields/TimestampFieldMapping.cs | using System;
using Newtonsoft.Json;
using System.Linq.Expressions;
using Nest.Resolvers.Converters;
namespace Nest
{
[JsonConverter(typeof(ReadAsTypeConverter<TimestampFieldMapping>))]
public interface ITimestampFieldMapping : ISpecialField
{
[JsonProperty("enabled")]
bool Enabled { get; set; }
[JsonProperty("path")]
PropertyPathMarker Path { get; set; }
[JsonProperty("format")]
string Format { get; set; }
[JsonProperty("default")]
string Default { get; set; }
[JsonProperty("ignore_missing")]
bool? IgnoreMissing { get; set; }
[JsonProperty("store")]
bool Store { get; set; }
}
public class TimestampFieldMapping : ITimestampFieldMapping
{
public bool Enabled { get; set; }
public PropertyPathMarker Path { get; set; }
public string Format { get; set; }
public string Default { get; set; }
public bool? IgnoreMissing { get; set; }
public bool Store { get; set; }
}
public class TimestampFieldMappingDescriptor<T> : ITimestampFieldMapping
{
private ITimestampFieldMapping Self { get { return this; } }
bool ITimestampFieldMapping.Enabled { get; set;}
PropertyPathMarker ITimestampFieldMapping.Path { get; set;}
string ITimestampFieldMapping.Format { get; set; }
string ITimestampFieldMapping.Default { get; set; }
bool? ITimestampFieldMapping.IgnoreMissing { get; set; }
bool ITimestampFieldMapping.Store { get; set; }
public TimestampFieldMappingDescriptor<T> Enabled(bool enabled = true)
{
Self.Enabled = enabled;
return this;
}
public TimestampFieldMappingDescriptor<T> Store(bool store = false)
{
Self.Store = store;
return this;
}
public TimestampFieldMappingDescriptor<T> Path(string path)
{
Self.Path = path;
return this;
}
public TimestampFieldMappingDescriptor<T> Path(Expression<Func<T, object>> objectPath)
{
objectPath.ThrowIfNull("objectPath");
Self.Path = objectPath;
return this;
}
public TimestampFieldMappingDescriptor<T> Format(string format)
{
Self.Format = format;
return this;
}
public TimestampFieldMappingDescriptor<T> Default(string defaultValue)
{
Self.Default = defaultValue;
return this;
}
public TimestampFieldMappingDescriptor<T> IgnoreMissing(bool ignoreMissing = true)
{
Self.IgnoreMissing = ignoreMissing;
return this;
}
}
}
| using System;
using Newtonsoft.Json;
using System.Linq.Expressions;
using Nest.Resolvers.Converters;
namespace Nest
{
[JsonConverter(typeof(ReadAsTypeConverter<TimestampFieldMapping>))]
public interface ITimestampFieldMapping : ISpecialField
{
[JsonProperty("enabled")]
bool Enabled { get; set; }
[JsonProperty("path")]
PropertyPathMarker Path { get; set; }
[JsonProperty("format")]
string Format { get; set; }
[JsonProperty("default")]
string Default { get; set; }
[JsonProperty("ignore_missing")]
bool? IgnoreMissing { get; set; }
}
public class TimestampFieldMapping : ITimestampFieldMapping
{
public bool Enabled { get; set; }
public PropertyPathMarker Path { get; set; }
public string Format { get; set; }
public string Default { get; set; }
public bool? IgnoreMissing { get; set; }
}
public class TimestampFieldMappingDescriptor<T> : ITimestampFieldMapping
{
private ITimestampFieldMapping Self { get { return this; } }
bool ITimestampFieldMapping.Enabled { get; set;}
PropertyPathMarker ITimestampFieldMapping.Path { get; set;}
string ITimestampFieldMapping.Format { get; set; }
string ITimestampFieldMapping.Default { get; set; }
bool? ITimestampFieldMapping.IgnoreMissing { get; set; }
public TimestampFieldMappingDescriptor<T> Enabled(bool enabled = true)
{
Self.Enabled = enabled;
return this;
}
public TimestampFieldMappingDescriptor<T> Path(string path)
{
Self.Path = path;
return this;
}
public TimestampFieldMappingDescriptor<T> Path(Expression<Func<T, object>> objectPath)
{
objectPath.ThrowIfNull("objectPath");
Self.Path = objectPath;
return this;
}
public TimestampFieldMappingDescriptor<T> Format(string format)
{
Self.Format = format;
return this;
}
public TimestampFieldMappingDescriptor<T> Default(string defaultValue)
{
Self.Default = defaultValue;
return this;
}
public TimestampFieldMappingDescriptor<T> IgnoreMissing(bool ignoreMissing = true)
{
Self.IgnoreMissing = ignoreMissing;
return this;
}
}
} | apache-2.0 | C# |
22270ea833c3ffc5f35bea0d3fe3d502b2bf6405 | Revert "Adding assembly info attributes back to AssemblyInfo to see if patching will work." | caioproiete/Autofac.Wcf,autofac/Autofac.Wcf | src/Autofac.Integration.Wcf/Properties/AssemblyInfo.cs | src/Autofac.Integration.Wcf/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Wcf")]
[assembly: InternalsVisibleTo("Autofac.Integration.Wcf.Test, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyCopyright("Copyright © 2014 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac Inversion of Control container WCF application integration.")] | using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Wcf")]
[assembly: InternalsVisibleTo("Autofac.Integration.Wcf.Test, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyCopyright("Copyright © 2014 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac Inversion of Control container WCF application integration.")]
[assembly: AssemblyVersionAttribute("4.0.0.0")]
[assembly: AssemblyFileVersionAttribute("4.0.0.0")]
[assembly: AssemblyInformationalVersionAttribute("4.0.0.0")] | mit | C# |
5d9ff9150909217aa357e67ef8a84fc39e1210e4 | Use Traversal.Create to avoid double allocation of a step array. | ExRam/ExRam.Gremlinq | src/ExRam.Gremlinq.Core/Projections/ArrayProjection.cs | src/ExRam.Gremlinq.Core/Projections/ArrayProjection.cs | using ExRam.Gremlinq.Core.Steps;
namespace ExRam.Gremlinq.Core.Projections
{
public sealed class ArrayProjection : Projection
{
private readonly Projection _inner;
internal ArrayProjection(Projection inner)
{
_inner = inner;
}
public override Traversal ToTraversal(IGremlinQueryEnvironment environment)
{
var inner = _inner.ToTraversal(environment);
if (inner.Count > 0)
{
return new LocalStep(Traversal.Create(
inner.Count + 2,
inner,
static (steps, inner) =>
{
steps[0] = UnfoldStep.Instance;
steps[^1] = FoldStep.Instance;
inner
.AsSpan()
.CopyTo(steps[1..]);
}));
}
return Traversal.Empty;
}
public Projection Unfold() => _inner;
public override Projection Lower() => Empty;
}
}
| using System.Collections.Immutable;
using System.Linq;
using ExRam.Gremlinq.Core.Steps;
namespace ExRam.Gremlinq.Core.Projections
{
public sealed class ArrayProjection : Projection
{
private readonly Projection _inner;
internal ArrayProjection(Projection inner)
{
_inner = inner;
}
public override Traversal ToTraversal(IGremlinQueryEnvironment environment)
{
var inner = _inner.ToTraversal(environment);
if (inner.Count > 0)
{
return new LocalStep(inner
.Prepend(UnfoldStep.Instance)
.Append(FoldStep.Instance)
.ToTraversal());
}
return Traversal.Empty;
}
public Projection Unfold() => _inner;
public override Projection Lower() => Empty;
}
}
| mit | C# |
d747a7b6ebf2b89b52eea3bbc13e427951e6d231 | improve button look and feel on main page | pseale/monopoly-dotnet,pseale/monopoly-dotnet | src/MonopolyDotNet/MonopolyWeb/Views/Home/Index.cshtml | src/MonopolyDotNet/MonopolyWeb/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<div class="hero-unit" style="height: 400px; background-image: url('../img/Monopoly_board.jpg'); background-position: center center">
<div><a href="NewGame" class="btn btn-success btn-large">Start a new game <i class="icon-white icon-arrow-right"></i></a></div>
</div>
| @{
ViewBag.Title = "Home Page";
}
<div class="hero-unit" style="height: 400px; background-image: url('../img/Monopoly_board.jpg'); background-position: center center">
<div><a href="NewGame" class="btn btn-success btn-large" style="padding: 30px 20px 30px 20px">Start a new game <i class="icon-white icon-arrow-right"></i></a></div>
</div>
| mit | C# |
88b061bc4394425c297a5bc7d83ec9cb9e479235 | Fix UserPermissionsCacheRefresher - need to invalidate cache by prefix - key contains node ids as well | WebCentrum/Umbraco-CMS,WebCentrum/Umbraco-CMS,WebCentrum/Umbraco-CMS | src/Umbraco.Web/Cache/UserPermissionsCacheRefresher.cs | src/Umbraco.Web/Cache/UserPermissionsCacheRefresher.cs | using System;
using Umbraco.Core;
using Umbraco.Core.Cache;
namespace Umbraco.Web.Cache
{
/// <summary>
/// Used only to invalidate the user permissions cache
/// </summary>
/// <remarks>
/// The UserCacheRefresher will also clear a user's permissions cache, this refresher is for invalidating only permissions
/// for users/content, not the users themselves.
/// </remarks>
public sealed class UserPermissionsCacheRefresher : CacheRefresherBase<UserPermissionsCacheRefresher>
{
protected override UserPermissionsCacheRefresher Instance
{
get { return this; }
}
public override Guid UniqueIdentifier
{
get { return Guid.Parse(DistributedCache.UserPermissionsCacheRefresherId); }
}
public override string Name
{
get { return "User permissions cache refresher"; }
}
public override void RefreshAll()
{
ApplicationContext.Current.ApplicationCache.ClearCacheByKeySearch(CacheKeys.UserPermissionsCacheKey);
base.RefreshAll();
}
public override void Refresh(int id)
{
Remove(id);
base.Refresh(id);
}
public override void Remove(int id)
{
ApplicationContext.Current.ApplicationCache.ClearCacheByKeySearch(string.Format("{0}{1}", CacheKeys.UserPermissionsCacheKey, id));
base.Remove(id);
}
}
} | using System;
using Umbraco.Core;
using Umbraco.Core.Cache;
namespace Umbraco.Web.Cache
{
/// <summary>
/// Used only to invalidate the user permissions cache
/// </summary>
/// <remarks>
/// The UserCacheRefresher will also clear a user's permissions cache, this refresher is for invalidating only permissions
/// for users/content, not the users themselves.
/// </remarks>
public sealed class UserPermissionsCacheRefresher : CacheRefresherBase<UserPermissionsCacheRefresher>
{
protected override UserPermissionsCacheRefresher Instance
{
get { return this; }
}
public override Guid UniqueIdentifier
{
get { return Guid.Parse(DistributedCache.UserPermissionsCacheRefresherId); }
}
public override string Name
{
get { return "User permissions cache refresher"; }
}
public override void RefreshAll()
{
ApplicationContext.Current.ApplicationCache.ClearCacheByKeySearch(CacheKeys.UserPermissionsCacheKey);
base.RefreshAll();
}
public override void Refresh(int id)
{
Remove(id);
base.Refresh(id);
}
public override void Remove(int id)
{
ApplicationContext.Current.ApplicationCache.ClearCacheItem(string.Format("{0}{1}", CacheKeys.UserPermissionsCacheKey, id));
base.Remove(id);
}
}
} | mit | C# |
5252ddacdcc2cca4328fe00f5824c09b47d97bd0 | Create strategy's | sgrassie/gol | temporalcohesion.gol.console/Program.cs | temporalcohesion.gol.console/Program.cs | using System;
using System.Threading;
using Mono.Options;
using temporalcohesion.gol.core;
namespace temporalcohesion.gol.console
{
class Program
{
private static int _seed;
private static string _initialPattern;
private static int _xSize;
private static int _ySize;
private static int _generations;
static void Main(string[] args)
{
var optionSet = new OptionSet
{
{"s|seed=", "The random seed", (int v) => _seed = v},
{"p|pattern=", "A starting pattern, e.g. 'glider'", v=> _initialPattern = v},
{"x=", "The board x size", (int v) => _xSize= v},
{"y=", "The board y size", (int v) => _ySize= v},
{"g|generations=", "The number of generations", (int v) => _generations = v}
};
optionSet.Parse(args);
var gridStrategy = SelectStrategy();
var life = new Life(_xSize, _ySize, gridStrategy);
Console.Clear();
Console.WriteLine(life.ToString());
Console.WriteLine("0/{0}", _generations);
for (var i = 0; i < _generations; i++)
{
life.Tick();
Console.Clear();
Console.WriteLine(life.ToString());
Console.WriteLine();
Console.WriteLine("{0}/{1}", i+1, _generations);
Thread.Sleep(1000);
}
}
private static IGridPopulationStrategy SelectStrategy()
{
if(_seed > 0 && string.IsNullOrEmpty(_initialPattern)) return new DefaultGridPopulationStrategy(_seed);
switch (_initialPattern)
{
case "glider" : return new GliderPopulationStrategy();
case "tencellrow": return new TenCellRowPopulationStrategy();
}
return new DefaultGridPopulationStrategy(new Random(42).Next());
}
}
}
| using System;
using System.Threading;
using Mono.Options;
using temporalcohesion.gol.core;
namespace temporalcohesion.gol.console
{
class Program
{
private static int _seed;
private static string _initialPattern;
private static int _xSize;
private static int _ySize;
private static int _generations;
static void Main(string[] args)
{
var optionSet = new OptionSet
{
{"s|seed=", "The random seed", (int v) => _seed = v},
{"p|pattern=", "A starting pattern, e.g. 'glider'", v=> _initialPattern = v},
{"x=", "The board x size", (int v) => _xSize= v},
{"y=", "The board y size", (int v) => _ySize= v},
{"g|generations=", "The number of generations", (int v) => _generations = v}
};
optionSet.Parse(args);
var gridStrategy = SelectStrategy();
var life = new Life(_xSize, _ySize, gridStrategy);
for (var i = 0; i < _generations; i++)
{
life.Tick();
Console.Clear();
Console.WriteLine(life.ToString());
Console.WriteLine();
Console.WriteLine("{0}/{1}", i+1, _generations);
Thread.Sleep(1000);
}
}
private static IGridPopulationStrategy SelectStrategy()
{
if(_seed > 0 && string.IsNullOrEmpty(_initialPattern)) return new DefaultGridPopulationStrategy(_seed);
return new DefaultGridPopulationStrategy(new Random(42).Next());
}
}
}
| mit | C# |
64564690aec60023f89a1d64039ff683b9cd104e | Update xaml. | MichalStrehovsky/roslyn,OmarTawfik/roslyn,DustinCampbell/roslyn,AnthonyDGreen/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,diryboy/roslyn,khyperia/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,sharwell/roslyn,CaptainHayashi/roslyn,jamesqo/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,paulvanbrenk/roslyn,robinsedlaczek/roslyn,mattwar/roslyn,shyamnamboodiripad/roslyn,abock/roslyn,jcouv/roslyn,pdelvo/roslyn,mmitche/roslyn,lorcanmooney/roslyn,bkoelman/roslyn,aelij/roslyn,tannergooding/roslyn,agocke/roslyn,jasonmalinowski/roslyn,gafter/roslyn,mattscheffer/roslyn,aelij/roslyn,kelltrick/roslyn,tmat/roslyn,physhi/roslyn,yeaicc/roslyn,AArnott/roslyn,davkean/roslyn,abock/roslyn,KevinH-MS/roslyn,panopticoncentral/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,yeaicc/roslyn,a-ctor/roslyn,DustinCampbell/roslyn,zooba/roslyn,DustinCampbell/roslyn,AnthonyDGreen/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,TyOverby/roslyn,Hosch250/roslyn,nguerrera/roslyn,xasx/roslyn,srivatsn/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,tmat/roslyn,tmeschter/roslyn,vslsnap/roslyn,tvand7093/roslyn,stephentoub/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tvand7093/roslyn,brettfo/roslyn,dotnet/roslyn,VSadov/roslyn,stephentoub/roslyn,Hosch250/roslyn,KevinRansom/roslyn,xoofx/roslyn,brettfo/roslyn,weltkante/roslyn,TyOverby/roslyn,mmitche/roslyn,cston/roslyn,tmat/roslyn,a-ctor/roslyn,panopticoncentral/roslyn,vslsnap/roslyn,ErikSchierboom/roslyn,MichalStrehovsky/roslyn,ErikSchierboom/roslyn,akrisiun/roslyn,jkotas/roslyn,khyperia/roslyn,jkotas/roslyn,genlu/roslyn,tvand7093/roslyn,lorcanmooney/roslyn,VSadov/roslyn,diryboy/roslyn,zooba/roslyn,amcasey/roslyn,jkotas/roslyn,abock/roslyn,KirillOsenkov/roslyn,drognanar/roslyn,paulvanbrenk/roslyn,reaction1989/roslyn,AArnott/roslyn,paulvanbrenk/roslyn,jcouv/roslyn,pdelvo/roslyn,mgoertz-msft/roslyn,aelij/roslyn,Hosch250/roslyn,bbarry/roslyn,eriawan/roslyn,jcouv/roslyn,wvdd007/roslyn,orthoxerox/roslyn,AlekseyTs/roslyn,weltkante/roslyn,bartdesmet/roslyn,tmeschter/roslyn,AnthonyDGreen/roslyn,CaptainHayashi/roslyn,davkean/roslyn,jeffanders/roslyn,dpoeschl/roslyn,AmadeusW/roslyn,Giftednewt/roslyn,xoofx/roslyn,jamesqo/roslyn,eriawan/roslyn,jeffanders/roslyn,nguerrera/roslyn,AlekseyTs/roslyn,xasx/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,yeaicc/roslyn,akrisiun/roslyn,diryboy/roslyn,genlu/roslyn,robinsedlaczek/roslyn,srivatsn/roslyn,agocke/roslyn,KevinH-MS/roslyn,genlu/roslyn,AArnott/roslyn,xasx/roslyn,reaction1989/roslyn,drognanar/roslyn,KirillOsenkov/roslyn,lorcanmooney/roslyn,dotnet/roslyn,tannergooding/roslyn,kelltrick/roslyn,heejaechang/roslyn,vslsnap/roslyn,TyOverby/roslyn,heejaechang/roslyn,bkoelman/roslyn,KevinH-MS/roslyn,robinsedlaczek/roslyn,xoofx/roslyn,kelltrick/roslyn,nguerrera/roslyn,tannergooding/roslyn,mavasani/roslyn,akrisiun/roslyn,MattWindsor91/roslyn,cston/roslyn,physhi/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,srivatsn/roslyn,orthoxerox/roslyn,mattscheffer/roslyn,jmarolf/roslyn,swaroop-sridhar/roslyn,gafter/roslyn,swaroop-sridhar/roslyn,bbarry/roslyn,jmarolf/roslyn,mattscheffer/roslyn,brettfo/roslyn,panopticoncentral/roslyn,MattWindsor91/roslyn,KirillOsenkov/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,MattWindsor91/roslyn,mattwar/roslyn,MattWindsor91/roslyn,stephentoub/roslyn,bartdesmet/roslyn,CaptainHayashi/roslyn,jasonmalinowski/roslyn,jmarolf/roslyn,Giftednewt/roslyn,pdelvo/roslyn,KevinRansom/roslyn,agocke/roslyn,eriawan/roslyn,tmeschter/roslyn,VSadov/roslyn,bkoelman/roslyn,dpoeschl/roslyn,amcasey/roslyn,jeffanders/roslyn,khyperia/roslyn,Giftednewt/roslyn,amcasey/roslyn,sharwell/roslyn,cston/roslyn,davkean/roslyn,jamesqo/roslyn,mattwar/roslyn,mavasani/roslyn,weltkante/roslyn,wvdd007/roslyn,orthoxerox/roslyn,gafter/roslyn,a-ctor/roslyn,physhi/roslyn,OmarTawfik/roslyn,mmitche/roslyn,dpoeschl/roslyn,swaroop-sridhar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,shyamnamboodiripad/roslyn,bbarry/roslyn,AmadeusW/roslyn,MichalStrehovsky/roslyn,zooba/roslyn,drognanar/roslyn | src/VisualStudio/Xaml/Impl/Features/OrganizeImports/XamlRemoveUnnecessaryImportsService.cs | src/VisualStudio/Xaml/Impl/Features/OrganizeImports/XamlRemoveUnnecessaryImportsService.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Xaml.Features.OrganizeImports;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.RemoveUnnecessaryImports;
namespace Microsoft.CodeAnalysis.Editor.Xaml.OrganizeImports
{
[ExportLanguageService(typeof(IRemoveUnnecessaryImportsService), StringConstants.XamlLanguageName), Shared]
internal class XamlRemoveUnnecessaryImportsService : IRemoveUnnecessaryImportsService
{
private readonly IXamlRemoveUnnecessaryNamespacesService _removeService;
[ImportingConstructor]
public XamlRemoveUnnecessaryImportsService(IXamlRemoveUnnecessaryNamespacesService removeService)
{
_removeService = removeService;
}
public Task<Document> RemoveUnnecessaryImportsAsync(Document document, CancellationToken cancellationToken)
=> RemoveUnnecessaryImportsAsync(document, predicate: null, cancellationToken: cancellationToken);
public Task<Document> RemoveUnnecessaryImportsAsync(
Document document, Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken)
{
return _removeService.RemoveUnnecessaryNamespacesAsync(document, cancellationToken) ?? Task.FromResult(document);
}
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Xaml.Features.OrganizeImports;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.RemoveUnnecessaryImports;
namespace Microsoft.CodeAnalysis.Editor.Xaml.OrganizeImports
{
[ExportLanguageService(typeof(IRemoveUnnecessaryImportsService), StringConstants.XamlLanguageName), Shared]
internal class XamlRemoveUnnecessaryImportsService : IRemoveUnnecessaryImportsService
{
private readonly IXamlRemoveUnnecessaryNamespacesService _removeService;
[ImportingConstructor]
public XamlRemoveUnnecessaryImportsService(IXamlRemoveUnnecessaryNamespacesService removeService)
{
_removeService = removeService;
}
public Task<Document> RemoveUnnecessaryImportsAsync(Document document, CancellationToken cancellationToken)
{
return _removeService.RemoveUnnecessaryNamespacesAsync(document, cancellationToken) ?? Task.FromResult(document);
}
}
}
| mit | C# |
1538cf40de821076402669bcfd6a8c00972d2687 | allow casted IQuerable as IEnumerable to be projected | eriklieben/ErikLieben.Data | ErikLieben.Data/Projection/IQueryableExtensions.cs | ErikLieben.Data/Projection/IQueryableExtensions.cs | namespace ErikLieben.Data.Projection
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Provides projection mapping from an IQueryable source to a target type.
/// </summary>
public static class IQueryableExtensions
{
public static ProjectionExpression<TSource> Project<TSource>(this IQueryable<TSource> source)
{
return new ProjectionExpression<TSource>(source);
}
public static ProjectionExpression<TSource> Project<TSource>(this IEnumerable<TSource> source)
{
var result = source as IQueryable<TSource>;
if (result == null)
{
throw new ArgumentException("source is not IQueryable<TSource>");
}
return new ProjectionExpression<TSource>(result);
}
}
} | namespace ErikLieben.Data.Projection
{
using System.Linq;
/// <summary>
/// Provides projection mapping from an IQueryable source to a target type.
/// </summary>
public static class IQueryableExtensions
{
public static ProjectionExpression<TSource> Project<TSource>(this IQueryable<TSource> source)
{
return new ProjectionExpression<TSource>(source);
}
}
} | mit | C# |
c594dcef16d7afd4cb2a481da2a1f1c5d86b8e97 | fix bug with test | NickSerg/water-meter,NickSerg/water-meter,NickSerg/water-meter | WaterMeter/WM.AspNetMvc.Tests/Controllers/HomeControllerTest.cs | WaterMeter/WM.AspNetMvc.Tests/Controllers/HomeControllerTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WM.AspNetMvc;
using WM.AspNetMvc.Controllers;
namespace WM.AspNetMvc.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.About() as ViewResult;
// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}
[TestMethod]
public void Contact()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Contact() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WM.AspNetMvc;
using WM.AspNetMvc.Controllers;
namespace WM.AspNetMvc.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.About() as ViewResult;
// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}
[TestMethod]
public void Contact()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Contact() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
| apache-2.0 | C# |
82121eed9d5a38be939f82ec102f62f0164eb055 | Convert OkanshiTimer test to new stopwatch | mvno/Okanshi,mvno/Okanshi,mvno/Okanshi | tests/Okanshi.Tests/OkanshiTimerTest.cs | tests/Okanshi.Tests/OkanshiTimerTest.cs | using System;
using System.Threading;
using FluentAssertions;
using Xunit;
using NSubstitute;
namespace Okanshi.Test
{
public class OkanshiTimerTest
{
private readonly IStopwatch _stopwatch = Substitute.For<IStopwatch>();
private readonly OkanshiTimer _timer;
public OkanshiTimerTest() {
_timer = new OkanshiTimer(x => {}, () => _stopwatch);
}
[Fact]
public void Cannot_be_started_multiple_times()
{
_timer.Start();
_stopwatch.IsRunning.Returns(true);
Action start = () => _timer.Start();
start.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void Cannot_be_stopped_multiple_times()
{
_timer.Start();
_stopwatch.IsRunning.Returns(true);
_timer.Stop();
_stopwatch.IsRunning.Returns(false);
Action stop = () => _timer.Stop();
stop.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void Cannot_be_stopped_if_not_started()
{
Action stop = () => _timer.Stop();
stop.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void Cannot_be_started_if_already_used_once()
{
_timer.Start();
_stopwatch.IsRunning.Returns(true);
_timer.Stop();
_stopwatch.IsRunning.Returns(false);
Action start = () => _timer.Start();
start.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void Timer_calls_the_callback_with_elapsed_milliseconds()
{
var elapsedMilliseconds = 0L;
var timer = new OkanshiTimer(x => elapsedMilliseconds = x);
timer.Start();
Thread.Sleep(500);
timer.Stop();
elapsedMilliseconds.Should().BeInRange(400, 700);
}
}
} | using System;
using System.Threading;
using FluentAssertions;
using Xunit;
namespace Okanshi.Test
{
public class OkanshiTimerTest
{
private readonly OkanshiTimer _timer = new OkanshiTimer(x => { });
public OkanshiTimerTest() { }
[Fact]
public void Cannot_be_started_multiple_times()
{
_timer.Start();
Action start = () => _timer.Start();
start.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void Cannot_be_stopped_multiple_times()
{
_timer.Start();
_timer.Stop();
Action stop = () => _timer.Stop();
stop.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void Cannot_be_stopped_if_not_started()
{
Action stop = () => _timer.Stop();
stop.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void Cannot_be_started_if_already_used_once()
{
_timer.Start();
_timer.Stop();
Action start = () => _timer.Start();
start.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void Timer_calls_the_callback_with_elapsed_milliseconds()
{
var elapsedMilliseconds = 0L;
var timer = new OkanshiTimer(x => elapsedMilliseconds = x);
timer.Start();
Thread.Sleep(500);
timer.Stop();
elapsedMilliseconds.Should().BeInRange(400, 700);
}
}
} | mit | C# |
40ffd7866c33deeb528181435ac3534f6e639774 | Fix linking errors when compiled for arm | deruss/xamarin-paypal-ios-sdk | PayPalMobileForXamarin/libPayPalMobile.linkwith.cs | PayPalMobileForXamarin/libPayPalMobile.linkwith.cs | using System;
using MonoTouch.ObjCRuntime;
[assembly: LinkWith ("libPayPalMobile.a",
LinkTarget.ArmV7 | LinkTarget.ArmV7s | LinkTarget.Simulator,
ForceLoad = true,
Frameworks="AVFoundation CoreMedia CoreVideo SystemConfiguration Security MessageUI OpenGLES MobileCoreServices",
LinkerFlags="-lz -lxml2 -lc++ -lstdc++"
)]
| using System;
using MonoTouch.ObjCRuntime;
[assembly: LinkWith ("libPayPalMobile.a",
LinkTarget.ArmV7 | LinkTarget.ArmV7s | LinkTarget.Simulator,
ForceLoad = true,
Frameworks="AVFoundation CoreMedia CoreVideo SystemConfiguration Security MessageUI OpenGLES MobileCoreServices",
LinkerFlags="-lz -lxml2 -lc++"
)]
| bsd-2-clause | C# |
d60c56dfba0bc76b6f7c8a135567d629392b8b1b | Add tests for borders. | eylvisaker/AgateLib | AgateLib.Tests/UnitTests/UserInterface/Venus/AdapterTests.cs | AgateLib.Tests/UnitTests/UserInterface/Venus/AdapterTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AgateLib.Geometry;
using AgateLib.Resources;
using AgateLib.Resources.Managers;
using AgateLib.UnitTests.Resources;
using AgateLib.UserInterface.DataModel;
using AgateLib.UserInterface.Rendering;
using AgateLib.UserInterface.Venus;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AgateLib.UnitTests.UserInterface.Venus
{
[TestClass]
public class AdapterTests : AgateUnitTest
{
private AgateResourceManager resources;
private UserInterfaceResourceManager uiManager;
private VenusLayoutEngine layoutEngine;
private VenusWidgetAdapter adapter;
[TestInitialize]
public void Initialize()
{
ResourceManagerInitializer initializer = new ResourceManagerInitializer();
resources = initializer.Manager;
uiManager = (UserInterfaceResourceManager)resources.UserInterface;
layoutEngine = (VenusLayoutEngine)uiManager.LayoutEngine;
adapter = (VenusWidgetAdapter)uiManager.Adapter;
}
[TestMethod]
public void AdapterBackgroundProperties()
{
var facet = new ResourceManagerInitializer.TestFacet();
uiManager.InitializeFacet(facet);
var style = adapter.StyleOf(facet.WindowA);
Assert.AreEqual("ui_back_1.png", style.Background.Image);
Assert.AreEqual(Color.Blue, style.Background.Color);
Assert.AreEqual(BackgroundRepeat.None, style.Background.Repeat);
Assert.AreEqual(BackgroundClip.Content, style.Background.Clip);
Assert.AreEqual(new Point(4, 3), style.Background.Position);
}
[TestMethod]
public void AdapterBorderProperties()
{
const string image = "abc123.png";
LayoutBox borderSlice = new LayoutBox { Left = 2, Top = 3, Right = 4, Bottom = 5 };
var windowTheme = uiManager.Adapter.ThemeData.First().Value["window"];
windowTheme.Border = new WidgetBorderModel();
windowTheme.Border.Image = image;
windowTheme.Border.Slice = borderSlice;
var facet = new ResourceManagerInitializer.TestFacet();
uiManager.InitializeFacet(facet);
var style = adapter.StyleOf(facet.WindowA);
var border = style.Border;
Assert.AreEqual(image, style.Border.Image);
Assert.AreEqual(borderSlice, style.Border.ImageSlice);
Assert.AreEqual("ui_back_1.png", style.Border.Left.Width);
Assert.AreEqual("ui_back_1.png", style.Border.Left.Color);
Assert.AreEqual("ui_back_1.png", style.Border.Top.Width);
Assert.AreEqual("ui_back_1.png", style.Border.Top.Color);
Assert.AreEqual("ui_back_1.png", style.Border.Right.Width);
Assert.AreEqual("ui_back_1.png", style.Border.Right.Color);
Assert.AreEqual("ui_back_1.png", style.Border.Bottom.Width);
Assert.AreEqual("ui_back_1.png", style.Border.Bottom.Color);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AgateLib.Geometry;
using AgateLib.Resources;
using AgateLib.Resources.Managers;
using AgateLib.UnitTests.Resources;
using AgateLib.UserInterface.Rendering;
using AgateLib.UserInterface.Venus;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AgateLib.UnitTests.UserInterface.Venus
{
[TestClass]
public class AdapterTests : AgateUnitTest
{
private AgateResourceManager resources;
private UserInterfaceResourceManager uiManager;
private VenusLayoutEngine layoutEngine;
private VenusWidgetAdapter adapter;
[TestInitialize]
public void Initialize()
{
ResourceManagerInitializer initializer = new ResourceManagerInitializer();
resources = initializer.Manager;
uiManager = (UserInterfaceResourceManager)resources.UserInterface;
layoutEngine = (VenusLayoutEngine)uiManager.LayoutEngine;
adapter = (VenusWidgetAdapter)uiManager.Adapter;
}
[TestMethod]
public void AdapterBackgroundProperties()
{
var facet = new ResourceManagerInitializer.TestFacet();
uiManager.InitializeFacet(facet);
var style = adapter.StyleOf(facet.WindowA);
Assert.AreEqual("ui_back_1.png", style.Background.Image);
Assert.AreEqual(Color.Blue, style.Background.Color);
Assert.AreEqual(BackgroundRepeat.None, style.Background.Repeat);
Assert.AreEqual(BackgroundClip.Content, style.Background.Clip);
Assert.AreEqual(new Point(4, 3), style.Background.Position);
}
}
}
| mit | C# |
2b7169107c0db6a608a12bb9d150f65b0e7d2a39 | Rename method | Pliner/EasyLauncher | Source/EasyLauncher/Process.cs | Source/EasyLauncher/Process.cs | using System;
using System.Diagnostics;
using System.Management;
namespace EasyLauncher
{
public interface IProcess
{
string Name { get; }
bool IsStopped { get; }
void Kill();
event EventHandler OnExit;
}
public sealed class ProcessAdapter : IProcess
{
private readonly Process process;
public ProcessAdapter(Process process)
{
this.process = process;
}
public string Name { get; set; }
public bool IsStopped
{
get { return process.HasExited; }
}
public void Kill()
{
KillProcessTree(process.Id);
}
private static void KillProcessTree(int pid)
{
var processSearcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
foreach (var proccess in processSearcher.Get())
{
var managementObject = (ManagementObject) proccess;
KillProcessTree(Convert.ToInt32(managementObject["ProcessID"]));
}
try
{
var process = Process.GetProcessById(pid);
process.Kill();
}
catch
{
}
}
public event EventHandler OnExit
{
add { process.Exited += value; }
remove { process.Exited -= value; }
}
}
} | using System;
using System.Diagnostics;
using System.Management;
namespace EasyLauncher
{
public interface IProcess
{
string Name { get; }
bool IsStopped { get; }
void Kill();
event EventHandler OnExit;
}
public sealed class ProcessAdapter : IProcess
{
private readonly Process process;
public ProcessAdapter(Process process)
{
this.process = process;
}
public string Name { get; set; }
public bool IsStopped
{
get { return process.HasExited; }
}
public void Kill()
{
KillProcessAndChildren(process.Id);
}
private static void KillProcessAndChildren(int pid)
{
var processSearcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
foreach (var proccess in processSearcher.Get())
{
var managementObject = (ManagementObject) proccess;
KillProcessAndChildren(Convert.ToInt32(managementObject["ProcessID"]));
}
try
{
var process = Process.GetProcessById(pid);
process.Kill();
}
catch
{
}
}
public event EventHandler OnExit
{
add { process.Exited += value; }
remove { process.Exited -= value; }
}
}
} | mit | C# |
781c0bea9d5d0e515e859ae1eedec074d7a11ed2 | Add check for anonymous clients | bwatts/Totem,bwatts/Totem | Source/Totem/Runtime/Client.cs | Source/Totem/Runtime/Client.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
namespace Totem.Runtime
{
/// <summary>
/// A user or process establishing a security context with a runtime service
/// </summary>
public class Client
{
public Client()
{
Id = Id.Unassigned;
Principal = new ClaimsPrincipal();
}
public Client(Id id, ClaimsPrincipal principal)
{
Id = id;
Principal = principal;
}
public Id Id { get; }
public ClaimsPrincipal Principal { get; }
public bool IsAnonymous => !Principal.Identity?.IsAuthenticated ?? true;
public bool IsAuthenticated => Principal.Identity?.IsAuthenticated ?? false;
public string Name => Principal.Identity?.Name ?? "";
public override string ToString() => Name;
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
namespace Totem.Runtime
{
/// <summary>
/// A user or process establishing a security context with a runtime service
/// </summary>
public class Client
{
public Client()
{
Id = Id.Unassigned;
Principal = new ClaimsPrincipal();
}
public Client(Id id, ClaimsPrincipal principal)
{
Id = id;
Principal = principal;
}
public Id Id { get; }
public ClaimsPrincipal Principal { get; }
public bool IsAuthenticated => Principal.Identity?.IsAuthenticated ?? false;
public string Name => Principal.Identity?.Name ?? "";
public override string ToString() => Name;
}
} | mit | C# |
4461ebe616452fd23d69b12231cbcd9fedd468a4 | Fix formatting in ClipRect.cs. | eylvisaker/AgateLib | Tests/DisplayTests/ClipRect.cs | Tests/DisplayTests/ClipRect.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
namespace Tests.DisplayTests
{
class ClipRect : IAgateTest
{
#region IAgateTest Members
public string Name
{
get { return "Clip Rects"; }
}
public string Category
{
get { return "Display"; }
}
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup())
{
setup.AskUser = true;
setup.Initialize(true, false, false);
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateWindowed(
"Test clip rects", 640, 480);
Color[] colors = new Color[] {
Color.Red, Color.Orange, Color.Yellow, Color.YellowGreen, Color.Green, Color.Turquoise, Color.Blue, Color.Violet, Color.Wheat, Color.White};
Surface surf = new Surface("Data/wallpaper.png");
while (wind.IsClosed == false)
{
Display.BeginFrame();
Display.Clear();
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Display.SetClipRect(new Rectangle(5 + i * 32, 5 + j * 32, 30, 30));
surf.Draw();
}
}
int index = 0;
for (int i = 10; i < 100; i += 10)
{
Display.SetClipRect(new Rectangle(320 + i, i, 310 - i * 2, 310 - i * 2));
Display.FillRect(0, 0, 640, 480, colors[index]);
index++;
}
Display.EndFrame();
Core.KeepAlive();
}
}
}
#endregion
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
namespace Tests.DisplayTests
{
class ClipRect : IAgateTest
{
#region IAgateTest Members
public string Name
{
get { return "Clip Rects"; }
}
public string Category
{
get { return "Display"; }
}
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup())
{
setup.AskUser = true;
setup.Initialize(true, false, false);
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateWindowed(
"Test clip rects", 640, 480);
Color[] colors = new Color[] {
Color.Red, Color.Orange, Color.Yellow, Color.YellowGreen, Color.Green, Color.Turquoise, Color.Blue, Color.Violet, Color.Wheat, Color.White};
Surface surf = new Surface("Data/wallpaper.png");
while (wind.IsClosed == false)
{
Display.BeginFrame();
Display.Clear();
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Display.SetClipRect(new Rectangle(5 + i * 32, 5 + j * 32, 30, 30));
surf.Draw();
}
}
int index = 0;
for (int i = 10; i < 100; i += 10)
{
Display.SetClipRect(new Rectangle(320 + i, i, 310 - i * 2, 310 - i * 2));
Display.FillRect(0,0,640,480, colors[index]);
index++;
}
Display.EndFrame();
Core.KeepAlive();
}
}
}
#endregion
}
}
| mit | C# |
4d74afc5c37e7fa136c099557920354e4fd0059a | Fix missing ifdef | peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype | src/Glimpse.Agent.AspNet/_SystemWeb/GlimpseAgentModule.cs | src/Glimpse.Agent.AspNet/_SystemWeb/GlimpseAgentModule.cs | #if SystemWeb
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using SystemWebAdapter;
using Glimpse.Agent.Configuration;
using Glimpse.Agent.Inspectors;
using Glimpse.Initialization;
namespace Glimpse
{
public class GlimpseAgentModule : IHttpModule
{
private IInspectorRuntimeManager _inspectorRuntimeManager; // TODO: need to set
public void Init(HttpApplication httpApplication)
{
httpApplication.BeginRequest += (context, e) => BeginRequest(GetHttpContext(context));
httpApplication.PostReleaseRequestState += (context, e) => EndRequest(GetHttpContext(context));
}
private void BeginRequest(Microsoft.AspNet.Http.HttpContext context)
{
_inspectorRuntimeManager.BeginRequest(context);
}
private void EndRequest(Microsoft.AspNet.Http.HttpContext context)
{
_inspectorRuntimeManager.EndRequest(context);
}
private static Microsoft.AspNet.Http.HttpContext GetHttpContext(object sender)
{
var httpApplication = (HttpApplication)sender;
// convert SystemWeb HttpContext to DNX HttpContext
return httpApplication.Context.CreateContext();
}
public void Dispose()
{
}
}
}
#endif | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using SystemWebAdapter;
using Glimpse.Agent.Configuration;
using Glimpse.Agent.Inspectors;
using Glimpse.Initialization;
namespace Glimpse
{
public class GlimpseAgentModule : IHttpModule
{
private IInspectorRuntimeManager _inspectorRuntimeManager; // TODO: need to set
public void Init(HttpApplication httpApplication)
{
httpApplication.BeginRequest += (context, e) => BeginRequest(GetHttpContext(context));
httpApplication.PostReleaseRequestState += (context, e) => EndRequest(GetHttpContext(context));
}
private void BeginRequest(Microsoft.AspNet.Http.HttpContext context)
{
_inspectorRuntimeManager.BeginRequest(context);
}
private void EndRequest(Microsoft.AspNet.Http.HttpContext context)
{
_inspectorRuntimeManager.EndRequest(context);
}
private static Microsoft.AspNet.Http.HttpContext GetHttpContext(object sender)
{
var httpApplication = (HttpApplication)sender;
// convert SystemWeb HttpContext to DNX HttpContext
return httpApplication.Context.CreateContext();
}
public void Dispose()
{
}
}
}
| mit | C# |
72f9059f95e9ed334051ed68a8e5d31a9366e092 | Resolve Nunit run error: System.Security.VerificationException: Operation could destabilize the runtime | cityindex-attic/RESTful-Webservice-Schema,cityindex-attic/RESTful-Webservice-Schema,cityindex-attic/RESTful-Webservice-Schema | src/JsonSchemaGeneration.Tests/Properties/AssemblyInfo.cs | src/JsonSchemaGeneration.Tests/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// 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("JsonSchemaGeneration.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("JsonSchemaGeneration.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[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("01bdc6c0-3dc4-4c31-b0ee-576cf2a95e31")]
// 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")]
//Resolve Nunit run error: System.Security.VerificationException: Operation could destabilize the runtime
//http://stackoverflow.com/questions/378895/operation-could-destabilize-the-runtime
[assembly: AllowPartiallyTrustedCallers]
| 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("JsonSchemaGeneration.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("JsonSchemaGeneration.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[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("01bdc6c0-3dc4-4c31-b0ee-576cf2a95e31")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
c8a23379823fd6bbeea4274f37ac455e97b44904 | Fix CS | Lc5/CurrencyRates,Lc5/CurrencyRates,Lc5/CurrencyRates | CurrencyRates.NbpCurrencyRates/Service/Entity/NbpXml.cs | CurrencyRates.NbpCurrencyRates/Service/Entity/NbpXml.cs | namespace CurrencyRates.NbpCurrencyRates.Service.Entity
{
static class NbpXml
{
public const string AverageValue = "kurs_sredni";
public const string CurrencyCode = "kod_waluty";
public const string CurrencyName = "nazwa_waluty";
public const string Multiplier = "przelicznik";
public const string Position = "pozycja";
public const string PublicationDate = "data_publikacji";
public const string RateTable = "tabela_kursow";
public const string TableNumber = "numer_tabeli";
public const string Type = "typ";
public const string Uid = "uid";
}
}
| namespace CurrencyRates.NbpCurrencyRates.Service.Entity
{
static class NbpXml
{
public const string AverageValue = "kurs_sredni";
public const string CurrencyCode = "kod_waluty";
public const string CurrencyName = "nazwa_waluty";
public const string Multiplier = "przelicznik";
public const string PublicationDate = "data_publikacji";
public const string Position = "pozycja";
public const string RateTable = "tabela_kursow";
public const string TableNumber = "numer_tabeli";
public const string Type = "typ";
public const string Uid = "uid";
}
}
| mit | C# |
6c5d291b10806decdd8d70d8648012471cda47ca | Remove internal types from Logging and Abstractions (dotnet/extensions#513) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Shared/BenchmarkRunner/DefaultCoreValidationConfig.cs | src/Shared/BenchmarkRunner/DefaultCoreValidationConfig.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Toolchains.InProcess;
namespace BenchmarkDotNet.Attributes
{
internal class DefaultCoreValidationConfig : ManualConfig
{
public DefaultCoreValidationConfig()
{
Add(ConsoleLogger.Default);
Add(Job.Dry.With(InProcessToolchain.Instance));
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Reflection;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Toolchains.InProcess;
namespace BenchmarkDotNet.Attributes
{
internal class DefaultCoreValidationConfig : ManualConfig
{
public DefaultCoreValidationConfig()
{
Add(ConsoleLogger.Default);
Add(Job.Dry.With(InProcessToolchain.Instance));
}
}
}
| apache-2.0 | C# |
2ef53330fb8b19b5a150ec1b3a2b16f6896835a5 | Add newest verification level | AntiTcb/Discord.Net,Confruggy/Discord.Net,RogueException/Discord.Net | src/Discord.Net.Core/Entities/Guilds/VerificationLevel.cs | src/Discord.Net.Core/Entities/Guilds/VerificationLevel.cs | namespace Discord
{
public enum VerificationLevel
{
/// <summary> Users have no additional restrictions on sending messages to this guild. </summary>
None = 0,
/// <summary> Users must have a verified email on their account. </summary>
Low = 1,
/// <summary> Users must fulfill the requirements of Low, and be registered on Discord for at least 5 minutes. </summary>
Medium = 2,
/// <summary> Users must fulfill the requirements of Medium, and be a member of this guild for at least 10 minutes. </summary>
High = 3,
/// <summary> Users must fulfill the requirements of High, and must have a verified phone on their Discord account. </summary>
Extreme = 4
}
}
| namespace Discord
{
public enum VerificationLevel
{
/// <summary> Users have no additional restrictions on sending messages to this guild. </summary>
None = 0,
/// <summary> Users must have a verified email on their account. </summary>
Low = 1,
/// <summary> Users must fulfill the requirements of Low, and be registered on Discord for at least 5 minutes. </summary>
Medium = 2,
/// <summary> Users must fulfill the requirements of Medium, and be a member of this guild for at least 10 minutes. </summary>
High = 3
}
}
| mit | C# |
9cb7bd097f6fabddbeaad3890f9e677609198f03 | disable Inheritance proxyMode | AspectCore/Lite,AspectCore/AspectCore-Framework,AspectCore/Abstractions,AspectCore/AspectCore-Framework | src/AspectCore.Abstractions/Internal/ProxyGenerator.cs | src/AspectCore.Abstractions/Internal/ProxyGenerator.cs | using System;
using System.Reflection;
using AspectCore.Abstractions.Internal.Generator;
namespace AspectCore.Abstractions.Internal
{
public sealed class ProxyGenerator : IProxyGenerator
{
private readonly IAspectValidator aspectValidator;
public ProxyGenerator(IAspectValidator aspectValidator)
{
if (aspectValidator == null)
{
throw new ArgumentNullException(nameof(aspectValidator));
}
this.aspectValidator = aspectValidator;
}
public Type CreateClassProxyType(Type serviceType, Type implementationType, params Type[] interfaces)
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
if (!serviceType.GetTypeInfo().IsClass)
{
throw new ArgumentException($"Type '{serviceType}' should be class.", nameof(serviceType));
}
return new ClassProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator).CreateTypeInfo().AsType();
}
public Type CreateInterfaceProxyType(Type serviceType, Type implementationType, params Type[] interfaces)
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
return GetInterfaceProxyTypeGenerator(serviceType, implementationType).CreateTypeInfo().AsType();
}
private ProxyTypeGenerator GetInterfaceProxyTypeGenerator(Type serviceType, Type implementationType, params Type[] interfaces)
{
//var proxyStructureAttribute = serviceType.GetTypeInfo().GetCustomAttribute<ProxyStructureAttribute>();
//if (proxyStructureAttribute != null && proxyStructureAttribute.ProxyMode == ProxyMode.Inheritance)
//{
// return new InheritanceInterfaceProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator);
//}
return new InterfaceProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator);
}
}
}
| using System;
using System.Reflection;
using AspectCore.Abstractions.Internal.Generator;
namespace AspectCore.Abstractions.Internal
{
public sealed class ProxyGenerator : IProxyGenerator
{
private readonly IAspectValidator aspectValidator;
public ProxyGenerator(IAspectValidator aspectValidator)
{
if (aspectValidator == null)
{
throw new ArgumentNullException(nameof(aspectValidator));
}
this.aspectValidator = aspectValidator;
}
public Type CreateClassProxyType(Type serviceType, Type implementationType, params Type[] interfaces)
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
if (!serviceType.GetTypeInfo().IsClass)
{
throw new ArgumentException($"Type '{serviceType}' should be class.", nameof(serviceType));
}
return new ClassProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator).CreateTypeInfo().AsType();
}
public Type CreateInterfaceProxyType(Type serviceType, Type implementationType, params Type[] interfaces)
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
return GetInterfaceProxyTypeGenerator(serviceType, implementationType).CreateTypeInfo().AsType();
}
private ProxyTypeGenerator GetInterfaceProxyTypeGenerator(Type serviceType, Type implementationType, params Type[] interfaces)
{
var proxyStructureAttribute = serviceType.GetTypeInfo().GetCustomAttribute<ProxyStructureAttribute>();
if (proxyStructureAttribute != null && proxyStructureAttribute.ProxyMode == ProxyMode.Inheritance)
{
return new InheritanceInterfaceProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator);
}
return new InterfaceProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator);
}
}
}
| mit | C# |
acfe6750256ded98aea4a8828fc83eef700a4e5f | Remove MIT license header | fredatgithub/WinFormTemplate | WinFormTemplate/FormOptions.cs | WinFormTemplate/FormOptions.cs | using System;
using System.Windows.Forms;
namespace WinFormTemplate
{
internal partial class FormOptions : Form
{
private readonly ConfigurationOptions _configurationOptions2;
internal FormOptions(ConfigurationOptions configurationOptions)
{
if (configurationOptions == null)
{
//throw new ArgumentNullException(nameof(configurationOptions));
_configurationOptions2 = new ConfigurationOptions();
}
else
{
_configurationOptions2 = configurationOptions;
}
InitializeComponent();
checkBoxOption1.Checked = ConfigurationOptions2.Option1Name;
checkBoxOption2.Checked = ConfigurationOptions2.Option2Name;
}
internal ConfigurationOptions ConfigurationOptions2
{
get { return _configurationOptions2; }
}
private void buttonOptionsOK_Click(object sender, EventArgs e)
{
ConfigurationOptions2.Option1Name = checkBoxOption1.Checked;
ConfigurationOptions2.Option2Name = checkBoxOption2.Checked;
Close();
}
private void buttonOptionsCancel_Click(object sender, EventArgs e)
{
Close();
}
private void FormOptions_Load(object sender, EventArgs e)
{
// take care of language
//buttonOptionsCancel.Text = _languageDicoEn["Cancel"];
}
}
}
| /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
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.Windows.Forms;
namespace WinFormTemplate
{
internal partial class FormOptions : Form
{
private readonly ConfigurationOptions _configurationOptions2;
internal FormOptions(ConfigurationOptions configurationOptions)
{
if (configurationOptions == null)
{
//throw new ArgumentNullException(nameof(configurationOptions));
_configurationOptions2 = new ConfigurationOptions();
}
else
{
_configurationOptions2 = configurationOptions;
}
InitializeComponent();
checkBoxOption1.Checked = ConfigurationOptions2.Option1Name;
checkBoxOption2.Checked = ConfigurationOptions2.Option2Name;
}
internal ConfigurationOptions ConfigurationOptions2
{
get { return _configurationOptions2; }
}
private void buttonOptionsOK_Click(object sender, EventArgs e)
{
ConfigurationOptions2.Option1Name = checkBoxOption1.Checked;
ConfigurationOptions2.Option2Name = checkBoxOption2.Checked;
Close();
}
private void buttonOptionsCancel_Click(object sender, EventArgs e)
{
Close();
}
private void FormOptions_Load(object sender, EventArgs e)
{
// take care of language
//buttonOptionsCancel.Text = _languageDicoEn["Cancel"];
}
}
} | mit | C# |
29a28710f371587f8cf2ebbdd94f29fcd7ed2e1b | change Abstractions invokeAsync return type to Task<T> | AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Lite,AspectCore/Abstractions | src/AspectCore.Lite.Abstractions/IAspectActivator.cs | src/AspectCore.Lite.Abstractions/IAspectActivator.cs | using System;
using System.Reflection;
using System.Threading.Tasks;
namespace AspectCore.Lite.Abstractions
{
[NonAspect]
public interface IAspectActivator
{
void InitializeMetaData(Type serviceType, MethodInfo serviceMethod, MethodInfo targetMethod, MethodInfo proxyMethod);
T Invoke<T>(object targetInstance, object proxyInstance, params object[] paramters);
Task<T> InvokeAsync<T>(object targetInstance, object proxyInstance, params object[] paramters);
}
}
| using System;
using System.Reflection;
namespace AspectCore.Lite.Abstractions
{
[NonAspect]
public interface IAspectActivator
{
void InitializeMetaData(Type serviceType, MethodInfo serviceMethod, MethodInfo targetMethod, MethodInfo proxyMethod);
T Invoke<T>(object targetInstance, object proxyInstance, params object[] paramters);
T InvokeAsync<T>(object targetInstance, object proxyInstance, params object[] paramters);
}
}
| mit | C# |
3780b513b94b2b1a170cf44e36a5a8e9218485e4 | Change ResourceType | mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype | src/Glimpse.Server.Web/Resources/MetadataResource.cs | src/Glimpse.Server.Web/Resources/MetadataResource.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
namespace Glimpse.Server.Web.Resources
{
public class MetadataResource : IResource
{
private readonly IMetadataProvider _metadataProvider;
private readonly JsonSerializer _jsonSerializer;
private Metadata _metadata;
public MetadataResource(IMetadataProvider metadataProvider, JsonSerializer jsonSerializer)
{
_metadataProvider = metadataProvider;
_jsonSerializer = jsonSerializer;
}
public async Task Invoke(HttpContext context, IDictionary<string, string> parameters)
{
var metadata = GetMetadata();
var response = context.Response;
response.Headers[HeaderNames.ContentType] = "application/json";
await response.WriteAsync(_jsonSerializer.Serialize(metadata));
}
private Metadata GetMetadata()
{
if (_metadata != null)
return _metadata;
_metadata = _metadataProvider.BuildInstance();
return _metadata;
}
public string Name => "Metadata";
public ResourceParameters Parameters => new ResourceParameters(+ResourceParameter.Hash);
public ResourceType Type => ResourceType.Client;
}
}
| using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
namespace Glimpse.Server.Web.Resources
{
public class MetadataResource : IResource
{
private readonly IMetadataProvider _metadataProvider;
private readonly JsonSerializer _jsonSerializer;
private Metadata _metadata;
public MetadataResource(IMetadataProvider metadataProvider, JsonSerializer jsonSerializer)
{
_metadataProvider = metadataProvider;
_jsonSerializer = jsonSerializer;
}
public async Task Invoke(HttpContext context, IDictionary<string, string> parameters)
{
var metadata = GetMetadata();
var response = context.Response;
response.Headers[HeaderNames.ContentType] = "application/json";
await response.WriteAsync(_jsonSerializer.Serialize(metadata));
}
private Metadata GetMetadata()
{
if (_metadata != null)
return _metadata;
_metadata = _metadataProvider.BuildInstance();
return _metadata;
}
public string Name => "Metadata";
public ResourceParameters Parameters => new ResourceParameters(+ResourceParameter.Hash);
public ResourceType Type => ResourceType.Agent;
}
}
| mit | C# |
6c596b2515f606587faee51c9bc4f80eb2eb9425 | delete children first then the rest | livioc/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core | src/NHibernate.Test/NHSpecificTest/NH1845/Fixture.cs | src/NHibernate.Test/NHSpecificTest/NH1845/Fixture.cs | using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH1845
{
public class Fixture : TestCaseMappingByCode
{
protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Category>(rc =>
{
rc.Id(x => x.Id, map => map.Generator(Generators.Native));
rc.Property(x => x.Name);
rc.ManyToOne(x => x.Parent, map => map.Column("ParentId"));
rc.Bag(x => x.Subcategories, map =>
{
map.Access(Accessor.NoSetter);
map.Key(km => km.Column("ParentId"));
map.Cascade(Mapping.ByCode.Cascade.All.Include(Mapping.ByCode.Cascade.DeleteOrphans));
}, rel => rel.OneToMany());
});
var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
return mappings;
}
[Test]
public void LazyLoad_Initialize_AndEvict()
{
Category category = new Category("parent");
category.AddSubcategory(new Category("child"));
SaveCategory(category);
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
Category loaded = session.Load<Category>(category.Id);
NHibernateUtil.Initialize(loaded.Subcategories[0]);
session.Evict(loaded);
transaction.Commit();
Assert.AreEqual("child", loaded.Subcategories[0].Name, "cannot access child");
}
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
// first delete children
session.CreateQuery("delete from Category where Parent != null").ExecuteUpdate();
// then the rest
session.CreateQuery("delete from Category").ExecuteUpdate();
transaction.Commit();
}
}
private void SaveCategory(Category category)
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(category);
transaction.Commit();
}
}
}
} | using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH1845
{
public class Fixture: TestCaseMappingByCode
{
protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Category>(rc =>
{
rc.Id(x=> x.Id, map=> map.Generator(Generators.Native));
rc.Property(x=> x.Name);
rc.ManyToOne(x=> x.Parent, map=> map.Column("ParentId"));
rc.Bag(x => x.Subcategories, map =>
{
map.Access(Accessor.NoSetter);
map.Key(km=> km.Column("ParentId"));
map.Cascade(Mapping.ByCode.Cascade.All.Include(Mapping.ByCode.Cascade.DeleteOrphans));
}, rel => rel.OneToMany());
});
var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
return mappings;
}
[Test]
public void LazyLoad_Initialize_AndEvict()
{
Category category = new Category("parent");
category.AddSubcategory(new Category("child"));
SaveCategory(category);
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
Category loaded = session.Load<Category>(category.Id);
NHibernateUtil.Initialize(loaded.Subcategories[0]);
session.Evict(loaded);
transaction.Commit();
Assert.AreEqual("child", loaded.Subcategories[0].Name, "cannot access child");
}
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.CreateQuery("delete from Category").ExecuteUpdate();
transaction.Commit();
}
}
private void SaveCategory(Category category)
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(category);
transaction.Commit();
}
}
}
} | lgpl-2.1 | C# |
2220f7cd1ef10dccda2677ef0d7cb0fcde99dbdc | Fix for reading the BoltHost from the environment variables. | neo4j/neo4j-dotnet-driver,neo4j/neo4j-dotnet-driver | Neo4j.Driver/Neo4j.Driver.Tests.Integration/Internals/StandAlone/Neo4jDefaultInstallation.cs | Neo4j.Driver/Neo4j.Driver.Tests.Integration/Internals/StandAlone/Neo4jDefaultInstallation.cs | // Copyright (c) 2002-2020 "Neo4j,"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// 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 Neo4j.Driver.Internal;
using Neo4j.Driver;
using Neo4j.Driver.TestUtil;
namespace Neo4j.Driver.IntegrationTests.Internals
{
public class Neo4jDefaultInstallation
{
public static string User = "neo4j";
public static string Password = "neo4j";
public static string HttpUri = "http://127.0.0.1:7474";
public static string BoltUri { get { return BoltHost + ":" + BoltPort; } }
private static string BoltHost = "bolt://127.0.0.1";
private static string BoltPort = "7687";
static Neo4jDefaultInstallation()
{
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEST_NEO4J_USER"))) User = Environment.GetEnvironmentVariable("TEST_NEO4J_USER");
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEST_NEO4J_PASS"))) Password = Environment.GetEnvironmentVariable("TEST_NEO4J_PASS");
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEST_NEO4J_HOST"))) BoltHost = "bolt://" + Environment.GetEnvironmentVariable("TEST_NEO4J_HOST");
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEST_NEO4J_PORT"))) BoltPort = Environment.GetEnvironmentVariable("TEST_NEO4J_PORT");
}
public static IDriver NewBoltDriver(Uri boltUri, IAuthToken authToken)
{
ILogger logger;
var configuredLevelStr = Environment.GetEnvironmentVariable("NEOLOGLEVEL");
if (Enum.TryParse<ExtendedLogLevel>(configuredLevelStr ?? "", true, out var configuredLevel))
{
logger = new TestLogger(s => Console.WriteLine(s), configuredLevel);
}
else
{
logger = new TestLogger(s => System.Diagnostics.Debug.WriteLine(s), ExtendedLogLevel.Debug);
}
return GraphDatabase.Driver(boltUri, authToken, o => { o.WithLogger(logger); });
}
}
} | // Copyright (c) 2002-2020 "Neo4j,"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// 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 Neo4j.Driver.Internal;
using Neo4j.Driver;
using Neo4j.Driver.TestUtil;
namespace Neo4j.Driver.IntegrationTests.Internals
{
public class Neo4jDefaultInstallation
{
public static string User = "neo4j";
public static string Password = "neo4j";
public static string HttpUri = "http://127.0.0.1:7474";
public static string BoltUri { get { return BoltHost + ":" + BoltPort; } }
private static string BoltHost = "bolt://127.0.0.1";
private static string BoltPort = "7687";
static Neo4jDefaultInstallation()
{
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEST_NEO4J_USER"))) User = Environment.GetEnvironmentVariable("TEST_NEO4J_USER");
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEST_NEO4J_PASS"))) Password = Environment.GetEnvironmentVariable("TEST_NEO4J_PASS");
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEST_NEO4J_HOST"))) BoltHost = Environment.GetEnvironmentVariable("TEST_NEO4J_HOST");
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEST_NEO4J_PORT"))) BoltPort = Environment.GetEnvironmentVariable("TEST_NEO4J_PORT");
}
public static IDriver NewBoltDriver(Uri boltUri, IAuthToken authToken)
{
ILogger logger;
var configuredLevelStr = Environment.GetEnvironmentVariable("NEOLOGLEVEL");
if (Enum.TryParse<ExtendedLogLevel>(configuredLevelStr ?? "", true, out var configuredLevel))
{
logger = new TestLogger(s => Console.WriteLine(s), configuredLevel);
}
else
{
logger = new TestLogger(s => System.Diagnostics.Debug.WriteLine(s), ExtendedLogLevel.Debug);
}
return GraphDatabase.Driver(boltUri, authToken, o => { o.WithLogger(logger); });
}
}
} | apache-2.0 | C# |
9233c9dad26801d1d98b56f7bb7a8c0e2de361aa | Make integration tests explicit | micdenny/EasyNetQ.Management.Client,alexwiese/EasyNetQ.Management.Client,EasyNetQ/EasyNetQ.Management.Client,Pliner/EasyNetQ.Management.Client,EasyNetQ/EasyNetQ.Management.Client,chinaboard/EasyNetQ.Management.Client,LawrenceWard/EasyNetQ.Management.Client,micdenny/EasyNetQ.Management.Client,Pliner/EasyNetQ.Management.Client | Source/EasyNetQ.Management.Client.Tests/ScenarioTest.cs | Source/EasyNetQ.Management.Client.Tests/ScenarioTest.cs | // ReSharper disable InconsistentNaming
using System;
using EasyNetQ.Management.Client.Model;
using NUnit.Framework;
namespace EasyNetQ.Management.Client.Tests
{
[TestFixture]
[Explicit("Requires a RabbitMQ server on localhost to work")]
public class ScenarioTest
{
[SetUp]
public void SetUp()
{
}
/// <summary>
/// Demonstrate how to create a virtual host, add some users, set permissions
/// and create exchanges, queues and bindings.
/// </summary>
[Test]
public void Should_be_able_to_provision_a_virtual_host()
{
var initial = new ManagementClient("http://localhost", "guest", "guest");
// first create a new virtual host
var vhost = initial.CreateVirtualHost("my_virtual_host");
// next create a user for that virutal host
var user = initial.CreateUser(new UserInfo("mike", "topSecret"));
// give the new user all permissions on the virtual host
initial.CreatePermission(new PermissionInfo(user, vhost));
// now log in again as the new user
var management = new ManagementClient("http://localhost", user.name, "topSecret");
// test that everything's OK
management.IsAlive(vhost);
// create an exchange
var exchange = management.CreateExchange(new ExchangeInfo("my_exchagne", "direct"), vhost);
// create a queue
var queue = management.CreateQueue(new QueueInfo("my_queue"), vhost);
// bind the exchange to the queue
management.CreateBinding(exchange, queue, new BindingInfo("my_routing_key"));
// publish a test message
management.Publish(exchange, new PublishInfo("my_routing_key", "Hello World!"));
// get any messages on the queue
var messages = management.GetMessagesFromQueue(queue, new GetMessagesCriteria(1, false));
foreach (var message in messages)
{
Console.Out.WriteLine("message.payload = {0}", message.payload);
}
}
}
}
// ReSharper restore InconsistentNaming | // ReSharper disable InconsistentNaming
using System;
using EasyNetQ.Management.Client.Model;
using NUnit.Framework;
namespace EasyNetQ.Management.Client.Tests
{
[TestFixture]
public class ScenarioTest
{
[SetUp]
public void SetUp()
{
}
/// <summary>
/// Demonstrate how to create a virtual host, add some users, set permissions
/// and create exchanges, queues and bindings.
/// </summary>
[Test]
public void Should_be_able_to_provision_a_virtual_host()
{
var initial = new ManagementClient("http://localhost", "guest", "guest");
// first create a new virtual host
var vhost = initial.CreateVirtualHost("my_virtual_host");
// next create a user for that virutal host
var user = initial.CreateUser(new UserInfo("mike", "topSecret"));
// give the new user all permissions on the virtual host
initial.CreatePermission(new PermissionInfo(user, vhost));
// now log in again as the new user
var management = new ManagementClient("http://localhost", user.name, "topSecret");
// test that everything's OK
management.IsAlive(vhost);
// create an exchange
var exchange = management.CreateExchange(new ExchangeInfo("my_exchagne", "direct"), vhost);
// create a queue
var queue = management.CreateQueue(new QueueInfo("my_queue"), vhost);
// bind the exchange to the queue
management.CreateBinding(exchange, queue, new BindingInfo("my_routing_key"));
// publish a test message
management.Publish(exchange, new PublishInfo("my_routing_key", "Hello World!"));
// get any messages on the queue
var messages = management.GetMessagesFromQueue(queue, new GetMessagesCriteria(1, false));
foreach (var message in messages)
{
Console.Out.WriteLine("message.payload = {0}", message.payload);
}
}
}
}
// ReSharper restore InconsistentNaming | mit | C# |
ee682135893e78786005ccc66fe3af11df8e8e43 | Make ObservableSocket log using it's inherited type | danbarua/NEventSocket,pragmatrix/NEventSocket,pragmatrix/NEventSocket,danbarua/NEventSocket | test/NEventSocket.Tests/Sockets/OutboundSocketTests.cs | test/NEventSocket.Tests/Sockets/OutboundSocketTests.cs | namespace NEventSocket.Tests.Sockets
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using Common.Logging.Simple;
using Xunit;
public class OutboundSocketTests
{
public OutboundSocketTests()
{
LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(
LogLevel.All, true, true, true, "yyyy-MM-dd hh:mm:ss");
}
[Fact(Timeout = 1000)]
public async Task On_calling_connect_it_should_populate_the_channel_data()
{
using (var listener = new OutboundListener(8084))
{
listener.Start();
bool gotChannelData = false;
listener.Connections.Subscribe(
async (socket) =>
{
await socket.Connect();
gotChannelData = socket.ChannelData != null;
});
var fakeSocket = new FakeFreeSwitchOutbound(8084);
await fakeSocket.SendChannelDataEvent();
Thread.Sleep(100);
Assert.True(gotChannelData);
}
}
}
} | namespace NEventSocket.Tests.Sockets
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using Common.Logging.Simple;
using Xunit;
public class OutboundSocketTests
{
public OutboundSocketTests()
{
LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(
LogLevel.All, true, true, true, "yyyy-MM-dd hh:mm:ss");
}
[Fact]
public async Task On_calling_connect_it_should_populate_the_channel_data()
{
using (var listener = new OutboundListener(8084))
{
listener.Start();
bool wasConnected = false;
listener.Connections.Subscribe(
async (socket) =>
{
await socket.Connect();
wasConnected = socket.ChannelData != null;
await socket.SendCommandAsync("say hello!");
});
var fakeSocket = new FakeFreeSwitchOutbound(8084);
fakeSocket.MessagesReceived.Subscribe(x => Console.WriteLine(x));
await fakeSocket.SendChannelDataEvent();
Thread.Sleep(1000);
Assert.True(wasConnected);
}
}
}
} | mpl-2.0 | C# |
2786809fa2166172f3b9b84f41c708690b6ff10d | put AlwaysOnSampler in the tutorial (#1356) | open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet | docs/trace/getting-started/Program.cs | docs/trace/getting-started/Program.cs | // <copyright file="Program.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Trace;
public class Program
{
private static readonly ActivitySource MyActivitySource = new ActivitySource(
"MyCompany.MyProduct.MyLibrary");
public static void Main()
{
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.SetSampler(new AlwaysOnSampler())
.AddSource("MyCompany.MyProduct.MyLibrary")
.AddConsoleExporter()
.Build();
using (var activity = MyActivitySource.StartActivity("SayHello"))
{
activity?.SetTag("foo", 1);
activity?.SetTag("bar", "Hello, World!");
activity?.SetTag("baz", new int[] { 1, 2, 3 });
}
}
}
| // <copyright file="Program.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Trace;
public class Program
{
private static readonly ActivitySource MyActivitySource = new ActivitySource(
"MyCompany.MyProduct.MyLibrary");
public static void Main()
{
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("MyCompany.MyProduct.MyLibrary")
.AddConsoleExporter()
.Build();
using (var activity = MyActivitySource.StartActivity("SayHello"))
{
activity?.SetTag("foo", 1);
activity?.SetTag("bar", "Hello, World!");
activity?.SetTag("baz", new int[] { 1, 2, 3 });
}
}
}
| apache-2.0 | C# |
dedc668ce0871705fd6c86ec08033e5865748d92 | Add connection string test | TurnerSoftware/MongoFramework | tests/MongoFramework.Tests/MongoDbConnectionTests.cs | tests/MongoFramework.Tests/MongoDbConnectionTests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MongoFramework.Tests
{
[TestClass]
public class MongoDbConnectionTests
{
#if !NETCOREAPP2_0
[TestMethod]
public void ConnectionFromConfig()
{
var connection = MongoDbConnection.FromConfig("MongoFrameworkTests");
Assert.IsNotNull(connection);
}
[TestMethod]
public void InvalidConfigForConnection()
{
var connection = MongoDbConnection.FromConfig("ThisConfigNameDoesntExist");
Assert.IsNull(connection);
}
#endif
[TestMethod]
public void ConnectionFromConnectionString()
{
var connection = MongoDbConnection.FromConnectionString("mongodb://localhost:27017/MongoFrameworkTests");
Assert.IsNotNull(connection);
}
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void NullUrlThrowsException()
{
MongoDbConnection.FromUrl(null);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MongoFramework.Tests
{
[TestClass]
public class MongoDbConnectionTests
{
#if !NETCOREAPP2_0
[TestMethod]
public void ConnectionFromConfig()
{
var connection = MongoDbConnection.FromConfig("MongoFrameworkTests");
Assert.IsNotNull(connection);
}
[TestMethod]
public void InvalidConfigForConnection()
{
var connection = MongoDbConnection.FromConfig("ThisConfigNameDoesntExist");
Assert.IsNull(connection);
}
#endif
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void NullUrlThrowsException()
{
MongoDbConnection.FromUrl(null);
}
}
}
| mit | C# |
9823966f1bb423c92af481f24be40924eaefd6fa | Reorder parameters | appharbor/appharbor-cli | src/AppHarbor.Tests/Commands/LoginAuthCommandTest.cs | src/AppHarbor.Tests/Commands/LoginAuthCommandTest.cs | using System;
using System.IO;
using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class LoginAuthCommandTest
{
[Theory, AutoCommandData]
public void ShouldSetAppHarborTokenIfUserIsntLoggedIn([Frozen]Mock<TextWriter> writer, [Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock, Mock<LoginAuthCommand> loginCommand, string username, string password)
{
using (var reader = new StringReader(string.Format("{0}{2}{1}{2}", username, password, Environment.NewLine)))
{
Console.SetIn(reader);
accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns((string)null);
loginCommand.Setup(x => x.GetAccessToken(username, password)).Returns("foo");
loginCommand.Object.Execute(new string[] { });
writer.Verify(x => x.Write("Username: "), Times.Once());
writer.Verify(x => x.Write("Password: "), Times.Once());
writer.Verify(x => x.WriteLine("Successfully logged in as {0}", username), Times.Once());
accessTokenConfigurationMock.Verify(x => x.SetAccessToken("foo"), Times.Once());
}
}
[Theory, AutoCommandData]
public void ShouldThrowIfUserIsAlreadyLoggedIn([Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock, LoginAuthCommand loginCommand)
{
accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns("foo");
var exception = Assert.Throws<CommandException>(() => loginCommand.Execute(new string[] { }));
Assert.Equal("You're already logged in", exception.Message);
}
}
}
| using System;
using System.IO;
using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class LoginAuthCommandTest
{
[Theory, AutoCommandData]
public void ShouldSetAppHarborTokenIfUserIsntLoggedIn(string username, string password, [Frozen]Mock<TextWriter> writer, [Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock, Mock<LoginAuthCommand> loginCommand)
{
using (var reader = new StringReader(string.Format("{0}{2}{1}{2}", username, password, Environment.NewLine)))
{
Console.SetIn(reader);
accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns((string)null);
loginCommand.Setup(x => x.GetAccessToken(username, password)).Returns("foo");
loginCommand.Object.Execute(new string[] { });
writer.Verify(x => x.Write("Username: "), Times.Once());
writer.Verify(x => x.Write("Password: "), Times.Once());
writer.Verify(x => x.WriteLine("Successfully logged in as {0}", username), Times.Once());
accessTokenConfigurationMock.Verify(x => x.SetAccessToken("foo"), Times.Once());
}
}
[Theory, AutoCommandData]
public void ShouldThrowIfUserIsAlreadyLoggedIn([Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock, LoginAuthCommand loginCommand)
{
accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns("foo");
var exception = Assert.Throws<CommandException>(() => loginCommand.Execute(new string[] { }));
Assert.Equal("You're already logged in", exception.Message);
}
}
}
| mit | C# |
dbacb7a52aa18b3539063feacdbcfb8e082506a3 | Add a comment explaining why we're setting the FilePath and Region properties on the CallTreeNode class. | kschecht/sarif-sdk,kschecht/sarif-sdk,kschecht/sarif-sdk,kschecht/sarif-sdk,kschecht/sarif-sdk,kschecht/sarif-sdk,kschecht/sarif-sdk | src/Sarif.Viewer.VisualStudio/Models/CallTreeNode.cs | src/Sarif.Viewer.VisualStudio/Models/CallTreeNode.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Sarif;
using System;
using System.IO;
namespace Microsoft.Sarif.Viewer.Models
{
public class CallTreeNode : CodeLocationObject
{
private AnnotatedCodeLocation _location;
public AnnotatedCodeLocation Location
{
get
{
return this._location;
}
set
{
this._location = value;
if (value != null && value.PhysicalLocation != null)
{
// If the backing AnnotatedCodeLocation has a PhysicalLocation, set the
// FilePath and Region properties. The FilePath and Region properties
// are used to navigate to the source location and highlight the line.
Uri uri = value.PhysicalLocation.Uri;
if (uri != null)
{
string path = uri.IsAbsoluteUri ? uri.LocalPath : uri.ToString();
if (uri.IsAbsoluteUri && !Path.IsPathRooted(path))
{
path = uri.AbsoluteUri;
}
this.FilePath = path;
}
this.Region = value.PhysicalLocation.Region;
}
else
{
this.FilePath = null;
this.Region = null;
}
}
}
public List<CallTreeNode> Children { get; set; }
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Sarif;
using System;
using System.IO;
namespace Microsoft.Sarif.Viewer.Models
{
public class CallTreeNode : CodeLocationObject
{
private AnnotatedCodeLocation _location;
public AnnotatedCodeLocation Location
{
get
{
return this._location;
}
set
{
this._location = value;
if (value != null && value.PhysicalLocation != null)
{
Uri uri = value.PhysicalLocation.Uri;
if (uri != null)
{
string path = uri.IsAbsoluteUri ? uri.LocalPath : uri.ToString();
if (uri.IsAbsoluteUri && !Path.IsPathRooted(path))
{
path = uri.AbsoluteUri;
}
this.FilePath = path;
}
this.Region = value.PhysicalLocation.Region;
}
else
{
this.FilePath = null;
this.Region = null;
}
}
}
public List<CallTreeNode> Children { get; set; }
}
}
| mit | C# |
1eab4e179ddb5583ded246af115edafdc41b89c1 | Add sample action to test so hover effect is visible | johnneijzen/osu,peppy/osu,ZLima12/osu,2yangk23/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,johnneijzen/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,ZLima12/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu,2yangk23/osu | osu.Game.Tests/Visual/Online/TestSceneShowMoreButton.cs | osu.Game.Tests/Visual/Online/TestSceneShowMoreButton.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Overlays.Profile.Sections;
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneShowMoreButton : OsuTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(ShowMoreButton),
};
public TestSceneShowMoreButton()
{
ShowMoreButton button;
Add(button = new ShowMoreButton
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Action = () => { }
});
AddStep("switch loading state", () => button.IsLoading = !button.IsLoading);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Overlays.Profile.Sections;
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneShowMoreButton : OsuTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(ShowMoreButton),
};
public TestSceneShowMoreButton()
{
ShowMoreButton button;
Add(button = new ShowMoreButton
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
});
AddStep("switch loading state", () => button.IsLoading = !button.IsLoading);
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.