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 |
---|---|---|---|---|---|---|---|---|
20d4492f2fd49f25b889124c006ca3bcd1896a58 | exclude soft-deleted FilterLists from API | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | server/src/FilterLists.Services/FilterList/FilterListService.cs | server/src/FilterLists.Services/FilterList/FilterListService.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FilterLists.Data;
using FilterLists.Services.FilterList.Models;
using Microsoft.EntityFrameworkCore;
namespace FilterLists.Services.FilterList
{
public class FilterListService : Service
{
public FilterListService(FilterListsDbContext dbContext, IConfigurationProvider mapConfig)
: base(dbContext, mapConfig)
{
}
public async Task<IEnumerable<FilterListDto>> GetAllAsync()
{
return await DbContext.FilterLists
.Where(fl => fl.IsDeleted != true)
.ProjectTo<FilterListDto>(MapConfig)
.ToListAsync();
}
public async Task<FilterListDto> GetByIdAsync(int id)
{
return await DbContext.FilterLists
.Where(fl => fl.IsDeleted != true)
.ProjectTo<FilterListDto>(MapConfig)
.FirstOrDefaultAsync(l => l.Id == id);
}
}
} | using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FilterLists.Data;
using FilterLists.Services.FilterList.Models;
using Microsoft.EntityFrameworkCore;
namespace FilterLists.Services.FilterList
{
public class FilterListService : Service
{
public FilterListService(FilterListsDbContext dbContext, IConfigurationProvider mapConfig)
: base(dbContext, mapConfig)
{
}
public async Task<IEnumerable<FilterListDto>> GetAllAsync() =>
await DbContext.FilterLists
.ProjectTo<FilterListDto>(MapConfig)
.ToListAsync();
public async Task<FilterListDto> GetByIdAsync(int id) =>
await DbContext.FilterLists
.ProjectTo<FilterListDto>(MapConfig)
.FirstOrDefaultAsync(l => l.Id == id);
}
} | mit | C# |
c25d95c154a506b9a14679a0484a2b7feb65055f | Support directories | gildorwang/video-fuzzer | VideoFuzzer/Program.cs | VideoFuzzer/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace VideoFuzzer
{
class Program
{
/// <summary>
/// Only process files that are bigger than 50MB.
/// </summary>
private const int MinFileSize = 50 * 1024 * 1024;
static void Main(string[] args)
{
if(!args.Any())
{
return;
}
try
{
var path = args[0];
if(File.Exists(path))
{
FuzzFile(path);
}
else if (Directory.Exists(path))
{
foreach (var filename in EnumerateFiles(path))
{
FuzzFile(filename);
}
}
}
catch(Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
private static IEnumerable<string> EnumerateFiles(string path)
{
return new DirectoryInfo(path)
.EnumerateFiles("*", SearchOption.AllDirectories)
.Where(info => info.Length > MinFileSize)
.Select(info => info.FullName);
}
private static void FuzzFile(string path)
{
using (var stream = File.Open(path, FileMode.Append, FileAccess.Write))
{
stream.Write(Enumerable.Repeat((byte) 0, 16).ToArray(), 0, 16);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace VideoFuzzer
{
class Program
{
static void Main(string[] args)
{
if(!args.Any())
{
return;
}
try
{
using(var stream = File.Open(args[0], FileMode.Append, FileAccess.Write))
{
stream.Write(Enumerable.Repeat((byte)0, 16).ToArray(), 0, 16);
}
}
catch(Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
}
}
| mit | C# |
752f68574b7b6d33af92b92bc52e227fe153e7e3 | Remove default OAuth1 CallbackUrl | junian/Xamarin.Social,moljac/Xamarin.Social,moljac/Xamarin.Social,aphex3k/Xamarin.Social,pacificIT/Xamarin.Social,xamarin/Xamarin.Social,junian/Xamarin.Social,aphex3k/Xamarin.Social,xamarin/Xamarin.Social,pacificIT/Xamarin.Social | src/Xamarin.Social/OAuth1Service.cs | src/Xamarin.Social/OAuth1Service.cs | //
// Copyright 2012, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Auth;
namespace Xamarin.Social
{
public abstract class OAuth1Service : Service
{
public string ConsumerKey { get; set; }
public string ConsumerSecret { get; set; }
public Uri RequestTokenUrl { get; protected set; }
public Uri AuthorizeUrl { get; protected set; }
public Uri AccessTokenUrl { get; protected set; }
public Uri CallbackUrl { get; set; }
public OAuth1Service (string serviceId, string title)
: base (serviceId, title)
{
}
protected override Authenticator GetAuthenticator ()
{
if (string.IsNullOrEmpty (ConsumerKey)) {
throw new InvalidOperationException ("Consumer Key not specified.");
}
if (string.IsNullOrEmpty (ConsumerSecret)) {
throw new InvalidOperationException ("Consumer Secret not specified.");
}
if (RequestTokenUrl == null) {
throw new InvalidOperationException ("Request URL not specified.");
}
if (AuthorizeUrl == null) {
throw new InvalidOperationException ("Authorize URL not specified.");
}
if (AccessTokenUrl == null) {
throw new InvalidOperationException ("Access Token URL not specified.");
}
if (CallbackUrl == null) {
throw new InvalidOperationException ("Callback URL not specified.");
}
return new OAuth1Authenticator (
consumerKey: ConsumerKey,
consumerSecret: ConsumerSecret,
requestTokenUrl: RequestTokenUrl,
authorizeUrl: AuthorizeUrl,
accessTokenUrl: AccessTokenUrl,
callbackUrl: CallbackUrl,
getUsernameAsync: GetUsernameAsync);
}
public override Request CreateRequest (string method, Uri url, IDictionary<string, string> parameters, Account account)
{
return new OAuth1Request (method, url, parameters, account);
}
static readonly string[] UsernameKeys = new string[] {
"username",
"user_name",
"screenname",
"screen_name",
"email",
"email_address",
};
protected virtual Task<string> GetUsernameAsync (IDictionary<string, string> accountProperties)
{
return Task.Factory.StartNew (delegate {
foreach (var k in UsernameKeys) {
if (accountProperties.ContainsKey (k)) {
return accountProperties[k];
}
}
throw new SocialException ("Could not determine username.");
});
}
}
}
| //
// Copyright 2012, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Auth;
namespace Xamarin.Social
{
public abstract class OAuth1Service : Service
{
public string ConsumerKey { get; set; }
public string ConsumerSecret { get; set; }
public Uri RequestTokenUrl { get; protected set; }
public Uri AuthorizeUrl { get; protected set; }
public Uri AccessTokenUrl { get; protected set; }
public Uri CallbackUrl { get; set; }
public OAuth1Service (string serviceId, string title)
: base (serviceId, title)
{
//
// This is a reliable URL to redirect to
//
CallbackUrl = new Uri ("http://www.facebook.com/connect/login_success.html");
}
protected override Authenticator GetAuthenticator ()
{
if (string.IsNullOrEmpty (ConsumerKey)) {
throw new InvalidOperationException ("Consumer Key not specified.");
}
if (string.IsNullOrEmpty (ConsumerSecret)) {
throw new InvalidOperationException ("Consumer Secret not specified.");
}
if (RequestTokenUrl == null) {
throw new InvalidOperationException ("Request URL not specified.");
}
if (AuthorizeUrl == null) {
throw new InvalidOperationException ("Authorize URL not specified.");
}
if (AccessTokenUrl == null) {
throw new InvalidOperationException ("Access Token URL not specified.");
}
if (CallbackUrl == null) {
throw new InvalidOperationException ("Callback URL not specified.");
}
return new OAuth1Authenticator (
consumerKey: ConsumerKey,
consumerSecret: ConsumerSecret,
requestTokenUrl: RequestTokenUrl,
authorizeUrl: AuthorizeUrl,
accessTokenUrl: AccessTokenUrl,
callbackUrl: CallbackUrl,
getUsernameAsync: GetUsernameAsync);
}
public override Request CreateRequest (string method, Uri url, IDictionary<string, string> parameters, Account account)
{
return new OAuth1Request (method, url, parameters, account);
}
static readonly string[] UsernameKeys = new string[] {
"username",
"user_name",
"screenname",
"screen_name",
"email",
"email_address",
};
protected virtual Task<string> GetUsernameAsync (IDictionary<string, string> accountProperties)
{
return Task.Factory.StartNew (delegate {
foreach (var k in UsernameKeys) {
if (accountProperties.ContainsKey (k)) {
return accountProperties[k];
}
}
throw new SocialException ("Could not determine username.");
});
}
}
}
| apache-2.0 | C# |
69a9e3a006fa6fc774ed63959a2cebc62fdd387c | add AsEnumerable | shockzinfinity/sapHowmuch.Base | sapHowmuch.Base/Extensions/SboUIExtensions.cs | sapHowmuch.Base/Extensions/SboUIExtensions.cs | using System.Collections.Generic;
namespace sapHowmuch.Base.Extensions
{
public static class SboUIExtensions
{
/// <summary>
/// Return IEnumerable for LINQ support
/// </summary>
/// <param name="dbDatasources"></param>
/// <returns></returns>
public static IEnumerable<SAPbouiCOM.DBDataSource> AsEnumerable(this SAPbouiCOM.DBDataSources dbDatasources)
{
foreach (SAPbouiCOM.DBDataSource item in dbDatasources)
{
yield return item;
}
}
/// <summary>
/// Return IEnumerable for LINQ support
/// </summary>
/// <param name="userDatasources"></param>
/// <returns></returns>
public static IEnumerable<SAPbouiCOM.UserDataSource> AsEnumerable(this SAPbouiCOM.UserDataSources userDatasources)
{
foreach (SAPbouiCOM.UserDataSource item in userDatasources)
{
yield return item;
}
}
/// <summary>
/// Return IEnumerable for LINQ support
/// </summary>
/// <param name="dataTables"></param>
/// <returns></returns>
public static IEnumerable<SAPbouiCOM.DataTable> AsEnumerable(this SAPbouiCOM.DataTables dataTables)
{
foreach (SAPbouiCOM.DataTable item in dataTables)
{
yield return item;
}
}
/// <summary>
/// Return IEnumerable for LINQ support
/// </summary>
/// <param name="menus"></param>
/// <returns></returns>
public static IEnumerable<SAPbouiCOM.MenuItem> AsEnumerable(this SAPbouiCOM.Menus menus)
{
foreach (SAPbouiCOM.MenuItem item in SapStream.UiApp.Menus)
{
yield return item;
}
}
}
} | using System.Collections.Generic;
namespace sapHowmuch.Base.Extensions
{
public static class SboUIExtensions
{
//public static SAPbouiCOM.DataTable GetDataTable(this SAPbouiCOM.Form form)
//{
// form.DataSources.DataTables.GetEnumerator
//}
public static IEnumerable<SAPbouiCOM.MenuItem> AsEnumerable(this SAPbouiCOM.Menus menus)
{
foreach (SAPbouiCOM.MenuItem item in SapStream.UiApp.Menus)
{
yield return item;
}
}
}
} | mit | C# |
20593cf68076ab85cc2bf58b057e93e13cca644a | fix prefix in build script | roflkins/IdentityModel.OidcClient2,IdentityModel/IdentityModel.OidcClient2,IdentityModel/IdentityModel.OidcClient,roflkins/IdentityModel.OidcClient2,IdentityModel/IdentityModel.OidcClient,IdentityModel/IdentityModel.OidcClient2 | 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/IdentityModel.OidcClient");
var sourcePath = Directory("./src");
var clientsPath = Directory("./clients");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
// build sources
var projects = GetFiles("./src/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
// build tests
projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
};
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 = "b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'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/IdentityModel.OidcClient");
var sourcePath = Directory("./src");
var clientsPath = Directory("./clients");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
// build sources
var projects = GetFiles("./src/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
// build tests
projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
};
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 = AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'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# |
f018a3b0b6a12b867cacc90e81151b89553f91c6 | remove litter | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EAS.Portal/DependencyResolution/ProviderServices.cs | src/SFA.DAS.EAS.Portal/DependencyResolution/ProviderServices.cs | using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SFA.DAS.EAS.Portal.Configuration;
using SFA.DAS.Providers.Api.Client;
namespace SFA.DAS.EAS.Portal.DependencyResolution
{
public static class ProviderServices
{
public static IServiceCollection AddProviderServices(this IServiceCollection services, HostBuilderContext hostBuilderContext)
{
var apiClientConfig = hostBuilderContext.Configuration.GetSection<ApprenticeshipInfoServiceApiConfiguration>(ConfigurationKeys.ApprenticeshipInfoServiceApi);
services.AddTransient<IProviderApiClient>(sp => new ProviderApiClient(apiClientConfig.BaseUrl));
return services;
}
}
} | using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SFA.DAS.EAS.Portal.Configuration;
using SFA.DAS.Providers.Api.Client;
namespace SFA.DAS.EAS.Portal.DependencyResolution
{
public static class ProviderServices
{
public static IServiceCollection AddProviderServices(this IServiceCollection services, HostBuilderContext hostBuilderContext)
{
var apiClientConfig = hostBuilderContext.Configuration.GetSection<ApprenticeshipInfoServiceApiConfiguration>(ConfigurationKeys.ApprenticeshipInfoServiceApi);
services.AddTransient<IProviderApiClient>(sp => new ProviderApiClient(apiClientConfig.BaseUrl));
// if we want to support config changes on the fly, we could create wrapper class that accepts IOptionsMonitor and picks out url
return services;
}
}
} | mit | C# |
93411463f182d623d9904aa002ccf7cba8759294 | Fix incorrect assumption that a workspace is a Visual Studio workspace | paulvanbrenk/roslyn,ErikSchierboom/roslyn,tmeschter/roslyn,weltkante/roslyn,genlu/roslyn,cston/roslyn,davkean/roslyn,abock/roslyn,KevinRansom/roslyn,tmeschter/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,OmarTawfik/roslyn,dotnet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,panopticoncentral/roslyn,brettfo/roslyn,bartdesmet/roslyn,DustinCampbell/roslyn,heejaechang/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,eriawan/roslyn,xasx/roslyn,agocke/roslyn,gafter/roslyn,dpoeschl/roslyn,DustinCampbell/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,jamesqo/roslyn,eriawan/roslyn,genlu/roslyn,paulvanbrenk/roslyn,bkoelman/roslyn,brettfo/roslyn,physhi/roslyn,sharwell/roslyn,wvdd007/roslyn,davkean/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,bkoelman/roslyn,jcouv/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,cston/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,gafter/roslyn,tmat/roslyn,bartdesmet/roslyn,dpoeschl/roslyn,panopticoncentral/roslyn,weltkante/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,stephentoub/roslyn,reaction1989/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,heejaechang/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ErikSchierboom/roslyn,tmat/roslyn,genlu/roslyn,bkoelman/roslyn,tannergooding/roslyn,MichalStrehovsky/roslyn,jmarolf/roslyn,diryboy/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,jamesqo/roslyn,tmat/roslyn,reaction1989/roslyn,tannergooding/roslyn,diryboy/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,gafter/roslyn,dotnet/roslyn,tannergooding/roslyn,dpoeschl/roslyn,diryboy/roslyn,physhi/roslyn,aelij/roslyn,jmarolf/roslyn,agocke/roslyn,sharwell/roslyn,abock/roslyn,ErikSchierboom/roslyn,VSadov/roslyn,tmeschter/roslyn,mavasani/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,xasx/roslyn,shyamnamboodiripad/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,jcouv/roslyn,aelij/roslyn,AmadeusW/roslyn,brettfo/roslyn,paulvanbrenk/roslyn,OmarTawfik/roslyn,jamesqo/roslyn,physhi/roslyn,agocke/roslyn,VSadov/roslyn,abock/roslyn,OmarTawfik/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,davkean/roslyn,VSadov/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,xasx/roslyn,wvdd007/roslyn,MichalStrehovsky/roslyn,cston/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,DustinCampbell/roslyn,KevinRansom/roslyn,jcouv/roslyn,jmarolf/roslyn | src/VisualStudio/Core/Def/Telemetry/ProjectTypeLookupService.cs | src/VisualStudio/Core/Def/Telemetry/ProjectTypeLookupService.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.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
[ExportWorkspaceService(typeof(IProjectTypeLookupService), ServiceLayer.Host), Shared]
internal class ProjectTypeLookupService : IProjectTypeLookupService
{
public string GetProjectType(Workspace workspace, ProjectId projectId)
{
if (!(workspace is VisualStudioWorkspace vsWorkspace) || projectId == null)
{
return string.Empty;
}
var aggregatableProject = vsWorkspace.GetHierarchy(projectId) as IVsAggregatableProject;
if (aggregatableProject == null)
{
return string.Empty;
}
if (ErrorHandler.Succeeded(aggregatableProject.GetAggregateProjectTypeGuids(out var projectType)))
{
return projectType;
}
return projectType ?? string.Empty;
}
}
}
| // 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
[ExportWorkspaceService(typeof(IProjectTypeLookupService), ServiceLayer.Host), Shared]
internal class ProjectTypeLookupService : IProjectTypeLookupService
{
public string GetProjectType(Workspace workspace, ProjectId projectId)
{
if (workspace == null || projectId == null)
{
return string.Empty;
}
var vsWorkspace = workspace as VisualStudioWorkspace;
var aggregatableProject = vsWorkspace.GetHierarchy(projectId) as IVsAggregatableProject;
if (aggregatableProject == null)
{
return string.Empty;
}
if (ErrorHandler.Succeeded(aggregatableProject.GetAggregateProjectTypeGuids(out var projectType)))
{
return projectType;
}
return projectType ?? string.Empty;
}
}
}
| mit | C# |
f9af6a180bc2f5c492b0da188a9be4aca0d726d2 | Fix when user sanity check happens in AuthenticationContext | Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server | src/Tgstation.Server.Host/Security/AuthenticationContext.cs | src/Tgstation.Server.Host/Security/AuthenticationContext.cs | using System;
using System.Linq;
using Tgstation.Server.Api.Rights;
using Tgstation.Server.Host.Models;
namespace Tgstation.Server.Host.Security
{
/// <summary>
/// Manages <see cref="Api.Models.User"/>s for a scope
/// </summary>
sealed class AuthenticationContext : IAuthenticationContext
{
/// <inheritdoc />
public User User { get; private set; }
/// <inheritdoc />
public InstanceUser InstanceUser { get; }
/// <inheritdoc />
public ISystemIdentity SystemIdentity { get; }
/// <summary>
/// Construct an empty <see cref="AuthenticationContext"/>
/// </summary>
public AuthenticationContext() { }
/// <summary>
/// Construct an <see cref="AuthenticationContext"/>
/// </summary>
/// <param name="systemIdentity">The value of <see cref="SystemIdentity"/></param>
/// <param name="user">The value of <see cref="User"/></param>
/// <param name="instanceUser">The value of <see cref="InstanceUser"/></param>
public AuthenticationContext(ISystemIdentity systemIdentity, User user, InstanceUser instanceUser)
{
User = user ?? throw new ArgumentNullException(nameof(user));
if (systemIdentity == null && User.SystemIdentifier != null)
throw new ArgumentNullException(nameof(systemIdentity));
InstanceUser = instanceUser;
SystemIdentity = systemIdentity;
}
/// <inheritdoc />
public void Dispose() => SystemIdentity?.Dispose();
/// <inheritdoc />
public ulong GetRight(RightsType rightsType)
{
var isInstance = RightsHelper.IsInstanceRight(rightsType);
if (User == null)
throw new InvalidOperationException("Authentication context has no user!");
if (isInstance && InstanceUser == null)
return 0;
var rightsEnum = RightsHelper.RightToType(rightsType);
// use the api versions because they're the ones that contain the actual properties
var typeToCheck = isInstance ? typeof(InstanceUser) : typeof(User);
var nullableType = typeof(Nullable<>);
var nullableRightsType = nullableType.MakeGenericType(rightsEnum);
var prop = typeToCheck.GetProperties().Where(x => x.PropertyType == nullableRightsType).First();
var right = prop.GetMethod.Invoke(isInstance ? (object)InstanceUser : User, Array.Empty<object>());
if (right == null)
throw new InvalidOperationException("A user right was null!");
return (ulong)right;
}
}
}
| using System;
using System.Linq;
using Tgstation.Server.Api.Rights;
using Tgstation.Server.Host.Models;
namespace Tgstation.Server.Host.Security
{
/// <summary>
/// Manages <see cref="Api.Models.User"/>s for a scope
/// </summary>
sealed class AuthenticationContext : IAuthenticationContext
{
/// <inheritdoc />
public User User
{
get
{
if (user == null)
throw new InvalidOperationException("AuthenticationContext has no user!");
return user;
}
}
/// <inheritdoc />
public InstanceUser InstanceUser { get; }
/// <inheritdoc />
public ISystemIdentity SystemIdentity { get; }
/// <summary>
/// Backing field for <see cref="User"/>
/// </summary>
readonly User user;
/// <summary>
/// Construct an empty <see cref="AuthenticationContext"/>
/// </summary>
public AuthenticationContext() { }
/// <summary>
/// Construct an <see cref="AuthenticationContext"/>
/// </summary>
/// <param name="systemIdentity">The value of <see cref="SystemIdentity"/></param>
/// <param name="user">The value of <see cref="User"/></param>
/// <param name="instanceUser">The value of <see cref="InstanceUser"/></param>
public AuthenticationContext(ISystemIdentity systemIdentity, User user, InstanceUser instanceUser)
{
this.user = user ?? throw new ArgumentNullException(nameof(user));
if (systemIdentity == null && User.SystemIdentifier != null)
throw new ArgumentNullException(nameof(systemIdentity));
InstanceUser = instanceUser;
SystemIdentity = systemIdentity;
}
/// <inheritdoc />
public void Dispose() => SystemIdentity?.Dispose();
/// <inheritdoc />
public ulong GetRight(RightsType rightsType)
{
var isInstance = RightsHelper.IsInstanceRight(rightsType);
//forces the null user check
var pullThis = User;
if (isInstance && InstanceUser == null)
return 0;
var rightsEnum = RightsHelper.RightToType(rightsType);
// use the api versions because they're the ones that contain the actual properties
var typeToCheck = isInstance ? typeof(InstanceUser) : typeof(User);
var nullableType = typeof(Nullable<>);
var nullableRightsType = nullableType.MakeGenericType(rightsEnum);
var prop = typeToCheck.GetProperties().Where(x => x.PropertyType == nullableRightsType).First();
var right = prop.GetMethod.Invoke(isInstance ? (object)InstanceUser : User, Array.Empty<object>());
if (right == null)
throw new InvalidOperationException("A user right was null!");
return (ulong)right;
}
}
}
| agpl-3.0 | C# |
b37197f66aa4ae86ee7fba0393b38a41e96c347f | Fix for U4-10821, render alt text attribute from grid image editor, or empty string if null (for screen readers) | abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,rasmuseeg/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,aaronpowell/Umbraco-CMS,marcemarc/Umbraco-CMS,lars-erik/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,lars-erik/Umbraco-CMS,WebCentrum/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,lars-erik/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,aaronpowell/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tompipe/Umbraco-CMS,arknu/Umbraco-CMS,NikRimington/Umbraco-CMS,base33/Umbraco-CMS,WebCentrum/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,base33/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,aaronpowell/Umbraco-CMS,tompipe/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,lars-erik/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,base33/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,dawoe/Umbraco-CMS,tompipe/Umbraco-CMS,marcemarc/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,WebCentrum/Umbraco-CMS | src/Umbraco.Web.UI/Views/Partials/Grid/Editors/Media.cshtml | src/Umbraco.Web.UI/Views/Partials/Grid/Editors/Media.cshtml | @model dynamic
@using Umbraco.Web.Templates
@if (Model.value != null)
{
var url = Model.value.image;
if(Model.editor.config != null && Model.editor.config.size != null){
url += "?width=" + Model.editor.config.size.width;
url += "&height=" + Model.editor.config.size.height;
if(Model.value.focalPoint != null){
url += "¢er=" + Model.value.focalPoint.top +"," + Model.value.focalPoint.left;
url += "&mode=crop";
}
}
var altText = Model.value.altText ?? String.Empty;
<img src="@url" alt="@altText">
if (Model.value.caption != null)
{
<p class="caption">@Model.value.caption</p>
}
}
| @model dynamic
@using Umbraco.Web.Templates
@if (Model.value != null)
{
var url = Model.value.image;
if(Model.editor.config != null && Model.editor.config.size != null){
url += "?width=" + Model.editor.config.size.width;
url += "&height=" + Model.editor.config.size.height;
if(Model.value.focalPoint != null){
url += "¢er=" + Model.value.focalPoint.top +"," + Model.value.focalPoint.left;
url += "&mode=crop";
}
}
<img src="@url" alt="@Model.value.caption">
if (Model.value.caption != null)
{
<p class="caption">@Model.value.caption</p>
}
}
| mit | C# |
f59271f3592c2bdd8e1e8a9ab7834d121cc77be8 | Handle content pages as well | MassivePixel/Sancho.XAMLParser | samples/TabletDesigner/TabletDesignerPage.xaml.cs | samples/TabletDesigner/TabletDesignerPage.xaml.cs | using System;
using Sancho.DOM.XamarinForms;
using Sancho.XAMLParser;
using TabletDesigner.Helpers;
using Xamarin.Forms;
namespace TabletDesigner
{
public interface ILogAccess
{
void Clear();
string Log { get; }
}
public partial class TabletDesignerPage : ContentPage
{
ILogAccess logAccess;
public TabletDesignerPage()
{
InitializeComponent();
logAccess = DependencyService.Get<ILogAccess>();
}
protected override void OnAppearing()
{
base.OnAppearing();
editor.Text = Settings.Xaml;
}
void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
{
try
{
Settings.Xaml = editor.Text;
logAccess.Clear();
var parser = new Parser();
var rootNode = parser.Parse(e.NewTextValue);
rootNode = new ContentNodeProcessor().Process(rootNode);
rootNode = new ExpandedPropertiesProcessor().Process(rootNode);
var dom = new XamlDOMCreator().CreateNode(rootNode);
if (dom is View)
Root.Content = (View)dom;
else if (dom is ContentPage)
Root.Content = ((ContentPage)dom).Content;
LoggerOutput.Text = logAccess.Log;
LoggerOutput.TextColor = Color.White;
}
catch (Exception ex)
{
LoggerOutput.Text = ex.ToString();
LoggerOutput.TextColor = Color.FromHex("#FF3030");
}
}
}
}
| using System;
using Sancho.DOM.XamarinForms;
using Sancho.XAMLParser;
using TabletDesigner.Helpers;
using Xamarin.Forms;
namespace TabletDesigner
{
public interface ILogAccess
{
void Clear();
string Log { get; }
}
public partial class TabletDesignerPage : ContentPage
{
ILogAccess logAccess;
public TabletDesignerPage()
{
InitializeComponent();
logAccess = DependencyService.Get<ILogAccess>();
}
protected override void OnAppearing()
{
base.OnAppearing();
editor.Text = Settings.Xaml;
}
void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
{
try
{
Settings.Xaml = editor.Text;
logAccess.Clear();
var parser = new Parser();
var rootNode = parser.Parse(e.NewTextValue);
rootNode = new ContentNodeProcessor().Process(rootNode);
rootNode = new ExpandedPropertiesProcessor().Process(rootNode);
var view = new XamlDOMCreator().CreateNode(rootNode) as View;
Root.Content = view;
LoggerOutput.Text = logAccess.Log;
LoggerOutput.TextColor = Color.White;
}
catch (Exception ex)
{
LoggerOutput.Text = ex.ToString();
LoggerOutput.TextColor = Color.FromHex("#FF3030");
}
}
}
}
| mit | C# |
de0e46eaa32e463083ee354c08f11a1d84921bb7 | Add GitRepository.IsOnMainBranch and IsOnMainOrMasterBranch | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Git/GitRepositoryExtensions.cs | source/Nuke.Common/Git/GitRepositoryExtensions.cs | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.Utilities;
namespace Nuke.Common.Git
{
public enum GitHubItemType
{
Automatic,
File,
Directory
}
[PublicAPI]
public static class GitRepositoryExtensions
{
public static bool IsOnMainOrMasterBranch(this GitRepository repository)
{
return repository.IsOnMainBranch() ||
repository.IsOnMasterBranch();
}
public static bool IsOnMasterBranch(this GitRepository repository)
{
return repository.Branch?.EqualsOrdinalIgnoreCase("master") ?? false;
}
public static bool IsOnMainBranch(this GitRepository repository)
{
return repository.Branch?.EqualsOrdinalIgnoreCase("main") ?? false;
}
public static bool IsOnDevelopBranch(this GitRepository repository)
{
return (repository.Branch?.EqualsOrdinalIgnoreCase("dev") ?? false) ||
(repository.Branch?.EqualsOrdinalIgnoreCase("develop") ?? false) ||
(repository.Branch?.EqualsOrdinalIgnoreCase("development") ?? false);
}
public static bool IsOnFeatureBranch(this GitRepository repository)
{
return repository.Branch?.StartsWithOrdinalIgnoreCase("feature/") ?? false;
}
// public static bool IsOnBugfixBranch(this GitRepository repository)
// {
// return repository.Branch?.StartsWithOrdinalIgnoreCase("feature/fix-") ?? false;
// }
public static bool IsOnReleaseBranch(this GitRepository repository)
{
return repository.Branch?.StartsWithOrdinalIgnoreCase("release/") ?? false;
}
public static bool IsOnHotfixBranch(this GitRepository repository)
{
return repository.Branch?.StartsWithOrdinalIgnoreCase("hotfix/") ?? false;
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.Utilities;
namespace Nuke.Common.Git
{
public enum GitHubItemType
{
Automatic,
File,
Directory
}
[PublicAPI]
public static class GitRepositoryExtensions
{
public static bool IsOnMasterBranch(this GitRepository repository)
{
return repository.Branch?.EqualsOrdinalIgnoreCase("master") ?? false;
}
public static bool IsOnDevelopBranch(this GitRepository repository)
{
return (repository.Branch?.EqualsOrdinalIgnoreCase("dev") ?? false) ||
(repository.Branch?.EqualsOrdinalIgnoreCase("develop") ?? false) ||
(repository.Branch?.EqualsOrdinalIgnoreCase("development") ?? false);
}
public static bool IsOnFeatureBranch(this GitRepository repository)
{
return repository.Branch?.StartsWithOrdinalIgnoreCase("feature/") ?? false;
}
// public static bool IsOnBugfixBranch(this GitRepository repository)
// {
// return repository.Branch?.StartsWithOrdinalIgnoreCase("feature/fix-") ?? false;
// }
public static bool IsOnReleaseBranch(this GitRepository repository)
{
return repository.Branch?.StartsWithOrdinalIgnoreCase("release/") ?? false;
}
public static bool IsOnHotfixBranch(this GitRepository repository)
{
return repository.Branch?.StartsWithOrdinalIgnoreCase("hotfix/") ?? false;
}
}
}
| mit | C# |
2eacb593df7263d9686f845b65ecb2bfdd3d283b | Remove unused using | fredatgithub/GitAutoUpdate | GitAutoUpdateGUI/Logger.cs | GitAutoUpdateGUI/Logger.cs | using System;
using System.Windows.Forms;
namespace GitAutoUpdateGUI
{
public static class Logger
{
public static string Message { get; set; }
public static DestinationLog Destination { get; set; }
private const string OneSpace = " ";
private const string Dash = "-";
private static readonly string Crlf = Environment.NewLine;
public static void Add(TextBoxBase textBox, string message)
{
textBox.Text += DateTime.Now + OneSpace + Dash + OneSpace + message + Crlf;
}
public static void Clear(TextBoxBase textBox)
{
textBox.Text = string.Empty;
}
}
public enum DestinationLog
{
LogFile,
LogTextBox
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GitAutoUpdateGUI
{
public static class Logger
{
public static string Message { get; set; }
public static DestinationLog Destination { get; set; }
private const string OneSpace = " ";
private const string Dash = "-";
private static readonly string Crlf = Environment.NewLine;
public static void Add(TextBoxBase textBox, string message)
{
textBox.Text += DateTime.Now + OneSpace + Dash + OneSpace + message + Crlf;
}
public static void Clear(TextBoxBase textBox)
{
textBox.Text = string.Empty;
}
}
public enum DestinationLog
{
LogFile,
LogTextBox
}
} | mit | C# |
78f2f09c264637170dd969004a4d5eadf1844b65 | Fix hoisting of null initializers | x335/JSIL,acourtney2015/JSIL,antiufo/JSIL,dmirmilshteyn/JSIL,sq/JSIL,volkd/JSIL,hach-que/JSIL,dmirmilshteyn/JSIL,FUSEEProjectTeam/JSIL,Trattpingvin/JSIL,FUSEEProjectTeam/JSIL,volkd/JSIL,FUSEEProjectTeam/JSIL,acourtney2015/JSIL,iskiselev/JSIL,Trattpingvin/JSIL,hach-que/JSIL,dmirmilshteyn/JSIL,x335/JSIL,antiufo/JSIL,Trattpingvin/JSIL,sander-git/JSIL,sq/JSIL,hach-que/JSIL,acourtney2015/JSIL,iskiselev/JSIL,hach-que/JSIL,TukekeSoft/JSIL,iskiselev/JSIL,iskiselev/JSIL,sq/JSIL,FUSEEProjectTeam/JSIL,acourtney2015/JSIL,x335/JSIL,antiufo/JSIL,acourtney2015/JSIL,mispy/JSIL,iskiselev/JSIL,sander-git/JSIL,mispy/JSIL,volkd/JSIL,sander-git/JSIL,mispy/JSIL,volkd/JSIL,sander-git/JSIL,TukekeSoft/JSIL,TukekeSoft/JSIL,Trattpingvin/JSIL,sander-git/JSIL,x335/JSIL,TukekeSoft/JSIL,sq/JSIL,hach-que/JSIL,volkd/JSIL,mispy/JSIL,FUSEEProjectTeam/JSIL,sq/JSIL,antiufo/JSIL,dmirmilshteyn/JSIL | JSIL/DeclarationHoister.cs | JSIL/DeclarationHoister.cs | using System;
using System.Collections.Generic;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Ast.Transforms;
using ICSharpCode.NRefactory.CSharp;
namespace JSIL {
public class DeclarationHoister : ContextTrackingVisitor<object> {
public readonly BlockStatement Output;
public VariableDeclarationStatement Statement = null;
public readonly HashSet<string> HoistedNames = new HashSet<string>();
public DeclarationHoister (DecompilerContext context, BlockStatement output)
: base(context) {
Output = output;
}
public override object VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement, object data) {
if (Statement == null) {
Statement = new VariableDeclarationStatement();
Output.Add(Statement);
}
foreach (var variable in variableDeclarationStatement.Variables) {
if (!HoistedNames.Contains(variable.Name)) {
Statement.Variables.Add(new VariableInitializer(
variable.Name
));
HoistedNames.Add(variable.Name);
}
}
var replacement = new BlockStatement();
foreach (var variable in variableDeclarationStatement.Variables) {
if (variable.IsNull)
continue;
if (variable.Initializer.IsNull)
continue;
replacement.Add(new ExpressionStatement(new AssignmentExpression {
Left = new IdentifierExpression(variable.Name),
Right = variable.Initializer.Clone()
}));
}
if (replacement.Statements.Count == 1) {
var firstChild = replacement.FirstChild;
firstChild.Remove();
variableDeclarationStatement.ReplaceWith(firstChild);
} else if (replacement.Statements.Count > 1) {
variableDeclarationStatement.ReplaceWith(replacement);
} else {
variableDeclarationStatement.Remove();
}
return null;
}
}
}
| using System;
using System.Collections.Generic;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Ast.Transforms;
using ICSharpCode.NRefactory.CSharp;
namespace JSIL {
public class DeclarationHoister : ContextTrackingVisitor<object> {
public readonly BlockStatement Output;
public VariableDeclarationStatement Statement = null;
public readonly HashSet<string> HoistedNames = new HashSet<string>();
public DeclarationHoister (DecompilerContext context, BlockStatement output)
: base(context) {
Output = output;
}
public override object VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement, object data) {
if (Statement == null) {
Statement = new VariableDeclarationStatement();
Output.Add(Statement);
}
foreach (var variable in variableDeclarationStatement.Variables) {
if (!HoistedNames.Contains(variable.Name)) {
Statement.Variables.Add(new VariableInitializer(
variable.Name
));
HoistedNames.Add(variable.Name);
}
}
var replacement = new BlockStatement();
foreach (var variable in variableDeclarationStatement.Variables) {
replacement.Add(new ExpressionStatement(new AssignmentExpression {
Left = new IdentifierExpression(variable.Name),
Right = variable.Initializer.Clone()
}));
}
if (replacement.Statements.Count == 1) {
var firstChild = replacement.FirstChild;
firstChild.Remove();
variableDeclarationStatement.ReplaceWith(firstChild);
} else if (replacement.Statements.Count > 1) {
variableDeclarationStatement.ReplaceWith(replacement);
}
return null;
}
}
}
| mit | C# |
d2bce825b30f6d6cd26f3f95fb29212e7e0d1e91 | Revert "Fixed a typo" | denikson/Mono.Cecil.Inject | Mono.Cecil.Inject/MethodDefinitionExtensions.cs | Mono.Cecil.Inject/MethodDefinitionExtensions.cs | using Mono.Cecil;
namespace Mono.Cecil.Inject
{
public static class MethodDefinitionExtensions
{
public static void InjectWith(this MethodDefinition method,
MethodDefinition injectionMethod,
int codeOffset,
int tag = 0,
InjectFlags flags = InjectFlags.None,
InjectDirection dir = InjectDirection.Before,
int[] localsID = null,
FieldDefinition[] typeFields = null)
{
InjectionDefinition id = new InjectionDefinition(method, injectionMethod, flags, localsID, typeFields);
id.Inject(0, tag, dir);
}
public static InjectionDefinition GetInjector(this MethodDefinition target,
TypeDefinition type,
string name,
InjectFlags flags = InjectFlags.None,
int[] localsID = null,
params FieldDefinition[] typeFields)
{
return type.GetInjectionMethod(name, target, flags, localsID, typeFields);
}
}
} | using Mono.Cecil;
namespace Mono.Cecil.Inject
{
public static class MethodDefinitionExtensions
{
public static void InjectWith(this MethodDefinition method,
MethodDefinition injectionMethod,
int codeOffset,
int tag = 0,
InjectFlags flags = InjectFlags.None,
InjectDirection dir = InjectDirection.Before,
int[] localsID = null,
FieldDefinition[] typeFields = null)
{
InjectionDefinition id = new InjectionDefinition(method, injectionMethod, flags, localsID, typeFields);
id.Inject(codeOffset, tag, dir);
}
public static InjectionDefinition GetInjector(this MethodDefinition target,
TypeDefinition type,
string name,
InjectFlags flags = InjectFlags.None,
int[] localsID = null,
params FieldDefinition[] typeFields)
{
return type.GetInjectionMethod(name, target, flags, localsID, typeFields);
}
}
} | mit | C# |
4725901a5abffec404bbf76fdaf9647a26a0a227 | extend dummy msgbox to accept parameter | maul-esel/CobaltAHK,maul-esel/CobaltAHK | CobaltAHK/ExpressionTree/Scope.cs | CobaltAHK/ExpressionTree/Scope.cs | using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace CobaltAHK.ExpressionTree
{
public class Scope
{
public Scope() : this(null) { }
public Scope(Scope parentScope) {
parent = parentScope;
#if DEBUG
var param = Expression.Parameter(typeof(string), "str");
var msgbox = Expression.Lambda<Action<string>>(
Expression.Call(typeof(IronAHK.Rusty.Core).GetMethod("MsgBox", new[] { typeof(string) }), param),
param
);
AddFunction("MsgBox", msgbox);
#endif
}
private readonly Scope parent;
public bool IsRoot { get { return parent == null; } }
private readonly IDictionary<string, LambdaExpression> functions = new Dictionary<string, LambdaExpression>();
public void AddFunction(string name, LambdaExpression func) {
functions[name.ToLower()] = func;
}
public LambdaExpression ResolveFunction(string name)
{
if (functions.ContainsKey(name.ToLower())) {
return functions[name.ToLower()];
} else if (parent != null) {
return parent.ResolveFunction(name);
}
throw new Exception(); // todo
}
private readonly IDictionary<string, ParameterExpression> variables = new Dictionary<string, ParameterExpression>();
public void AddVariable(string name, ParameterExpression variable)
{
variables.Add(name.ToLower(), variable);
}
public ParameterExpression ResolveVariable(string name)
{
if (!variables.ContainsKey(name.ToLower())) {
AddVariable(name, Expression.Parameter(typeof(object), name));
}
return variables[name.ToLower()];
}
// todo: RootScope() initialized with builtin functions and commands
}
}
| using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace CobaltAHK.ExpressionTree
{
public class Scope
{
public Scope() : this(null) { }
public Scope(Scope parentScope) {
parent = parentScope;
#if DEBUG
var msgbox = Expression.Lambda<Action>(
Expression.Block(
Expression.Call(typeof(IronAHK.Rusty.Core).GetMethod("MsgBox", new[] { typeof(string) }), Expression.Constant("MSGBOX dummy"))
)
);
AddFunction("MsgBox", msgbox);
#endif
}
private readonly Scope parent;
public bool IsRoot { get { return parent == null; } }
private readonly IDictionary<string, LambdaExpression> functions = new Dictionary<string, LambdaExpression>();
public void AddFunction(string name, LambdaExpression func) {
functions[name.ToLower()] = func;
}
public LambdaExpression ResolveFunction(string name)
{
if (functions.ContainsKey(name.ToLower())) {
return functions[name.ToLower()];
} else if (parent != null) {
return parent.ResolveFunction(name);
}
throw new Exception(); // todo
}
private readonly IDictionary<string, ParameterExpression> variables = new Dictionary<string, ParameterExpression>();
public void AddVariable(string name, ParameterExpression variable)
{
variables.Add(name.ToLower(), variable);
}
public ParameterExpression ResolveVariable(string name)
{
if (!variables.ContainsKey(name.ToLower())) {
AddVariable(name, Expression.Parameter(typeof(object), name));
}
return variables[name.ToLower()];
}
// todo: RootScope() initialized with builtin functions and commands
}
}
| mit | C# |
106f6728a6e824bbf745e750c4621270d647bdda | Fix test | noelbundick/ci-api | test/SampleHubFacts.cs | test/SampleHubFacts.cs | using API.Hubs;
using Xunit;
namespace API.Tests
{
public class SampleHubFacts
{
[Fact]
public void ItExists()
{
var hub = new SampleHub();
Assert.NotNull(hub);
}
[Fact]
public void PassingTest()
{
Assert.True(true);
}
[Fact]
public void AnotherPassingTest()
{
var x = 3;
var y = 5;
var z = x + y;
Assert.Equal(8, z);
}
[Fact]
public void TDDNewFeature()
{
Assert.True(true);
}
}
} | using API.Hubs;
using Xunit;
namespace API.Tests
{
public class SampleHubFacts
{
[Fact]
public void ItExists()
{
var hub = new SampleHub();
Assert.NotNull(hub);
}
[Fact]
public void PassingTest()
{
Assert.True(true);
}
[Fact]
public void AnotherPassingTest()
{
var x = 3;
var y = 5;
var z = x + y;
Assert.Equal(8, z);
}
[Fact]
public void TDDNewFeature()
{
Assert.True(false);
}
}
} | mit | C# |
8efbe4865c4bad2d2d574c344bc0c9d59fe6363e | Update Concentration.cs (#44) | BosslandGmbH/BuddyWing.DefaultCombat | trunk/DefaultCombat/Routines/Advanced/Sentinel/Concentration.cs | trunk/DefaultCombat/Routines/Advanced/Sentinel/Concentration.cs | // Copyright (C) 2011-2016 Bossland GmbH
// See the file LICENSE for the source code's detailed license
using Buddy.BehaviorTree;
using DefaultCombat.Core;
using DefaultCombat.Helpers;
namespace DefaultCombat.Routines
{
internal class Concentration : RotationBase
{
public override string Name
{
get { return "Sentinel Concentration"; }
}
public override Composite Buffs
{
get
{
return new PrioritySelector(
Spell.Buff("Force Might")
);
}
}
public override Composite Cooldowns
{
get
{
return new PrioritySelector(
Spell.Buff("Rebuke", ret => Me.HealthPercent <= 50),
Spell.Buff("Guarded by the Force", ret => Me.HealthPercent <= 10),
Spell.Buff("Saber Ward", ret => Me.HealthPercent <= 30)
);
}
}
public override Composite SingleTarget
{
get
{
return new PrioritySelector(
//Movement
CombatMovement.CloseDistance(Distance.Melee),
//Rotation
Spell.Cast("Force Leap"),
Spell.Cast("Dispatch", ret => Me.CurrentTarget.HealthPercent <= 30),
Spell.Cast("Force Sweep", ret => Me.HasBuff("Singularity") && Me.HasBuff("Felling Blow")),
Spell.Cast("Force Exhaustion"),
Spell.Cast("Zealous Leap", ret => Me.HasBuff("Singularity")),
Spell.Cast("Blade Storm", ret => Me.HasBuff("Battle Cry") || Me.Energy >= 5),
Spell.Cast("Dual Saber Throw"),
Spell.Cast("Blade Barrage"),
Spell.Cast("Force Stasis"),
Spell.Cast("Slash", ret => Me.HasBuff("Zen")),
Spell.Cast("Zealous Strike"),
Spell.Cast("Strike")
);
}
}
public override Composite AreaOfEffect
{
get
{
return new Decorator(ret => Targeting.ShouldPbaoe,
new PrioritySelector(
));
}
}
}
}
| // Copyright (C) 2011-2016 Bossland GmbH
// See the file LICENSE for the source code's detailed license
using Buddy.BehaviorTree;
using DefaultCombat.Core;
using DefaultCombat.Helpers;
namespace DefaultCombat.Routines
{
internal class Concentration : RotationBase
{
public override string Name
{
get { return "Sentinel Concentration"; }
}
public override Composite Buffs
{
get
{
return new PrioritySelector(
Spell.Buff("Shii-Cho Form"),
Spell.Buff("Force Might")
);
}
}
public override Composite Cooldowns
{
get
{
return new PrioritySelector(
Spell.Buff("Rebuke", ret => Me.HealthPercent <= 50),
Spell.Buff("Guarded by the Force", ret => Me.HealthPercent <= 10),
Spell.Buff("Saber Ward", ret => Me.HealthPercent <= 30)
);
}
}
public override Composite SingleTarget
{
get
{
return new PrioritySelector(
//Movement
CombatMovement.CloseDistance(Distance.Melee),
//Rotation
Spell.Cast("Force Leap"),
Spell.Cast("Dispatch", ret => Me.CurrentTarget.HealthPercent <= 30),
Spell.Cast("Force Sweep", ret => Me.HasBuff("Singularity") && Me.HasBuff("Felling Blow")),
Spell.Cast("Force Exhaustion"),
Spell.Cast("Zealous Leap", ret => Me.HasBuff("Singularity")),
Spell.Cast("Blade Storm", ret => Me.HasBuff("Battle Cry") || Me.Energy >= 5),
Spell.Cast("Dual Saber Throw"),
Spell.Cast("Blade Dance"),
Spell.Cast("Force Stasis"),
Spell.Cast("Slash", ret => Me.HasBuff("Zen")),
Spell.Cast("Zealous Strike"),
Spell.Cast("Strike")
);
}
}
public override Composite AreaOfEffect
{
get
{
return new Decorator(ret => Targeting.ShouldPbaoe,
new PrioritySelector(
));
}
}
}
} | apache-2.0 | C# |
456eae9fde45438e0a19c0baf47960a06af42248 | Clean up | alvivar/Hasten | Core/Motion2D/Motion2DWallJump.cs | Core/Motion2D/Motion2DWallJump.cs |
// Experimental wall Jump+Crawl component for Motion2D.
// Andrés Villalobos ^ [email protected] ^ twitter.com/matnesis
// 2015/08/17 12:12 AM
using UnityEngine;
[RequireComponent(typeof(Motion2D))]
public class Motion2DWallJump : MonoBehaviour
{
[Header("Config")]
public float wallSnapGravity;
[Header("Motion override")]
public Vector2 gravityOnWall;
public float forceLimitOnWall;
private Motion2D motion;
private Motion2DJump jump;
void Start()
{
motion = GetComponent<Motion2D>();
jump = GetComponent<Motion2DJump>();
}
void Update()
{
Vector2 nextGravity = gravityOnWall;
// Modify gravity towards the wall (left, right)
if (motion.wallsColliding.w == 1)
nextGravity.x = wallSnapGravity * -1;
if (motion.wallsColliding.y == 1)
nextGravity.x = wallSnapGravity;
// Left or right
if (motion.wallsColliding.y == 1 || motion.wallsColliding.w == 1)
{
// Config overrides
motion.gravityOverride = nextGravity;
motion.forceLimit = forceLimitOnWall;
}
else
{
// Normal config
motion.gravityOverride = Vector2.zero;
motion.forceLimit = 0;
}
}
}
|
// Experimental wall Jump+Crawl component for Motion2D.
// Andrés Villalobos ^ [email protected] ^ twitter.com/matnesis
// 2015/08/17 12:12 AM
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Motion2D))]
public class Motion2DWallJump : MonoBehaviour
{
[Header("Config")]
public float wallSnapGravity;
[Header("Motion override")]
public Vector2 gravityOnWall;
public float forceLimitOnWall;
private Motion2D motion;
private Motion2DJump jump;
void Start()
{
motion = GetComponent<Motion2D>();
jump = GetComponent<Motion2DJump>();
}
void Update()
{
// >
// BEHAVIOUR WHEN TOUCHING THE WALLS
//
Vector2 nextGravity = gravityOnWall;
// Modify gravity towards the wall (left, right)
if (motion.wallsColliding.w == 1)
nextGravity.x = wallSnapGravity * -1;
if (motion.wallsColliding.y == 1)
nextGravity.x = wallSnapGravity;
// Left or right
if (motion.wallsColliding.y == 1 || motion.wallsColliding.w == 1)
{
// Config overrides
motion.gravityOverride = nextGravity;
motion.forceLimit = forceLimitOnWall;
}
else
{
// Normal config
motion.gravityOverride = Vector2.zero;
motion.forceLimit = 0;
}
}
}
| mit | C# |
7a9dffa5867a3c106298379f066c0ee3c521607c | Fix ICommandSource comments | SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia | src/Avalonia.Input/ICommandSource.cs | src/Avalonia.Input/ICommandSource.cs | using System.Windows.Input;
#nullable enable
namespace Avalonia.Input
{
///<summary>
/// An interface for classes that know how to invoke a Command.
///</summary>
public interface ICommandSource
{
/// <summary>
/// The command that will be executed when the class is "invoked."
/// Classes that implement this interface should enable or disable based on the command's CanExecute return value.
/// The property may be implemented as read-write if desired.
/// </summary>
ICommand? Command { get; }
/// <summary>
/// The parameter that will be passed to the command when executing the command.
/// The property may be implemented as read-write if desired.
/// </summary>
object? CommandParameter { get; }
/// <summary>
/// Called for the CanExecuteChanged event when changes are detected.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
void CanExecuteChanged(object sender, System.EventArgs e);
/// <summary>
/// Gets a value indicating whether this control and all its parents are enabled.
/// </summary>
bool IsEffectivelyEnabled { get; }
}
}
| using System.Windows.Input;
#nullable enable
namespace Avalonia.Input
{
///<summary>
/// An interface for classes that know how to invoke a Command.
///</summary>
public interface ICommandSource
{
/// <summary>
/// The command that will be executed when the class is "invoked."
/// Classes that implement this interface should enable or disable based on the command's CanExecute return value.
/// The property may be implemented as read-write if desired.
/// </summary>
ICommand? Command { get; }
/// <summary>
/// The parameter that will be passed to the command when executing the command.
/// The property may be implemented as read-write if desired.
/// </summary>
object? CommandParameter { get; }
/// <summary>
/// Bor the behavior CanExecuteChanged
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void CanExecuteChanged(object sender, System.EventArgs e);
/// <summary>
/// Gets a value indicating whether this control and all its parents are enabled.
/// </summary>
bool IsEffectivelyEnabled { get; }
}
}
| mit | C# |
1330126d3f7acef84317d400f049185bbd469600 | fix spacing | nessos/Eff | src/Eff/Handlers/IEffectHandler.cs | src/Eff/Handlers/IEffectHandler.cs | using System.Threading.Tasks;
namespace Nessos.Effects.Handlers
{
/// <summary>
/// An abstraction for providing evaluation semantics for Eff computations.
/// </summary>
public interface IEffectHandler
{
/// <summary>
/// Provides handling logic for abstract Effect awaiters.
/// </summary>
/// <typeparam name="TResult">The result type of the abstract effect.</typeparam>
/// <param name="awaiter">The effect awaiter to be completed with a value.</param>
/// <returns>A task waiting on the asynchronous handler.</returns>
/// <remarks>
/// Typically a pattern match against subtypes of <see cref="Effect{TResult}"/>
/// that are recognized by the particular effect handler implementation.
/// </remarks>
ValueTask Handle<TResult>(EffectAwaiter<TResult> awaiter);
/// <summary>
/// Provides evaluation logic for Eff state machines.
/// </summary>
/// <typeparam name="TResult">The result type of the eff state machine.</typeparam>
/// <param name="stateMachine">The state machine to be evaluated.</param>
/// <returns>A task waiting on the asynchronous evaluation.</returns>
/// <remarks>
/// Typically defines an evaluation loop calling the <see cref="EffStateMachine{TResult}.MoveNext"/> method
/// and querying the <see cref="EffStateMachine{TResult}.Position"/> property.
/// On completion the state machine should be completed with either a result or exception.
/// </remarks>
ValueTask Handle<TResult>(EffStateMachine<TResult> stateMachine);
}
}
| using System.Threading.Tasks;
namespace Nessos.Effects.Handlers
{
/// <summary>
/// An abstraction for providing evaluation semantics for Eff computations.
/// </summary>
public interface IEffectHandler
{
/// <summary>
/// Provides handling logic for abstract Effect awaiters.
/// </summary>
/// <typeparam name="TResult">The result type of the abstract effect.</typeparam>
/// <param name="awaiter">The effect awaiter to be completed with a value.</param>
/// <returns>A task waiting on the asynchronous handler.</returns>
/// <remarks>
/// Typically a pattern match against subtypes of <see cref="Effect{TResult}"/>
/// that are recognized by the particular effect handler implementation.
/// </remarks>
ValueTask Handle<TResult>(EffectAwaiter<TResult> awaiter);
/// <summary>
/// Provides evaluation logic for Eff state machines.
/// </summary>
/// <typeparam name="TResult">The result type of the eff state machine.</typeparam>
/// <param name="stateMachine">The state machine to be evaluated.</param>
/// <returns>A task waiting on the asynchronous evaluation.</returns>
/// <remarks>
/// Typically defines an evaluation loop calling the <see cref="EffStateMachine{TResult}.MoveNext"/> method
/// and querying the <see cref="EffStateMachine{TResult}.Position"/> property.
/// On completion the state machine should be completed with either a result or exception.
/// </remarks>
ValueTask Handle<TResult>(EffStateMachine<TResult> stateMachine);
}
}
| mit | C# |
ab02419ae9a96b75e29e07b11bf252a2ebade2a3 | mark obsolete methods | aritchie/userdialogs | src/Acr.UserDialogs.Interface/IUserDialogs.cs | src/Acr.UserDialogs.Interface/IUserDialogs.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Splat;
namespace Acr.UserDialogs
{
public interface IUserDialogs
{
IDisposable Alert(string message, string title = null, string okText = null);
IDisposable Alert(AlertConfig config);
Task AlertAsync(string message, string title = null, string okText = null, CancellationToken? cancelToken = null);
Task AlertAsync(AlertConfig config, CancellationToken? cancelToken = null);
IDisposable ActionSheet(ActionSheetConfig config);
Task<string> ActionSheetAsync(string title, string cancel, string destructive, CancellationToken? cancelToken = null, params string[] buttons);
IDisposable Confirm(ConfirmConfig config);
Task<bool> ConfirmAsync(string message, string title = null, string okText = null, string cancelText = null, CancellationToken? cancelToken = null);
Task<bool> ConfirmAsync(ConfirmConfig config, CancellationToken? cancelToken = null);
IDisposable DatePrompt(DatePromptConfig config);
Task<DatePromptResult> DatePromptAsync(DatePromptConfig config, CancellationToken? cancelToken = null);
Task<DatePromptResult> DatePromptAsync(string title = null, DateTime? selectedDate = null, CancellationToken? cancelToken = null);
IDisposable TimePrompt(TimePromptConfig config);
Task<TimePromptResult> TimePromptAsync(TimePromptConfig config, CancellationToken? cancelToken = null);
Task<TimePromptResult> TimePromptAsync(string title = null, TimeSpan? selectedTime = null, CancellationToken? cancelToken = null);
IDisposable Prompt(PromptConfig config);
Task<PromptResult> PromptAsync(string message, string title = null, string okText = null, string cancelText = null, string placeholder = "", InputType inputType = InputType.Default, CancellationToken? cancelToken = null);
Task<PromptResult> PromptAsync(PromptConfig config, CancellationToken? cancelToken = null);
IDisposable Login(LoginConfig config);
Task<LoginResult> LoginAsync(string title = null, string message = null, CancellationToken? cancelToken = null);
Task<LoginResult> LoginAsync(LoginConfig config, CancellationToken? cancelToken = null);
IProgressDialog Progress(ProgressDialogConfig config);
IProgressDialog Loading(string title = null, Action onCancel = null, string cancelText = null, bool show = true, MaskType? maskType = null);
IProgressDialog Progress(string title = null, Action onCancel = null, string cancelText = null, bool show = true, MaskType? maskType = null);
void ShowLoading(string title = null, MaskType? maskType = null);
void HideLoading();
void ShowImage(IBitmap image, string message, int timeoutMillis = 2000);
[Obsolete("This method will be removed in a future version. Use ShowImage and supply your own image")]
void ShowSuccess(string message, int timeoutMillis = 2000);
[Obsolete("This method will be removed in a future version. Use ShowImage and supply your own image")]
void ShowError(string message, int timeoutMillis = 2000);
IDisposable Toast(string title, TimeSpan? dismissTimer = null);
IDisposable Toast(ToastConfig cfg);
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
using Splat;
namespace Acr.UserDialogs
{
public interface IUserDialogs
{
IDisposable Alert(string message, string title = null, string okText = null);
IDisposable Alert(AlertConfig config);
Task AlertAsync(string message, string title = null, string okText = null, CancellationToken? cancelToken = null);
Task AlertAsync(AlertConfig config, CancellationToken? cancelToken = null);
IDisposable ActionSheet(ActionSheetConfig config);
Task<string> ActionSheetAsync(string title, string cancel, string destructive, CancellationToken? cancelToken = null, params string[] buttons);
IDisposable Confirm(ConfirmConfig config);
Task<bool> ConfirmAsync(string message, string title = null, string okText = null, string cancelText = null, CancellationToken? cancelToken = null);
Task<bool> ConfirmAsync(ConfirmConfig config, CancellationToken? cancelToken = null);
IDisposable DatePrompt(DatePromptConfig config);
Task<DatePromptResult> DatePromptAsync(DatePromptConfig config, CancellationToken? cancelToken = null);
Task<DatePromptResult> DatePromptAsync(string title = null, DateTime? selectedDate = null, CancellationToken? cancelToken = null);
IDisposable TimePrompt(TimePromptConfig config);
Task<TimePromptResult> TimePromptAsync(TimePromptConfig config, CancellationToken? cancelToken = null);
Task<TimePromptResult> TimePromptAsync(string title = null, TimeSpan? selectedTime = null, CancellationToken? cancelToken = null);
IDisposable Prompt(PromptConfig config);
Task<PromptResult> PromptAsync(string message, string title = null, string okText = null, string cancelText = null, string placeholder = "", InputType inputType = InputType.Default, CancellationToken? cancelToken = null);
Task<PromptResult> PromptAsync(PromptConfig config, CancellationToken? cancelToken = null);
IDisposable Login(LoginConfig config);
Task<LoginResult> LoginAsync(string title = null, string message = null, CancellationToken? cancelToken = null);
Task<LoginResult> LoginAsync(LoginConfig config, CancellationToken? cancelToken = null);
IProgressDialog Progress(ProgressDialogConfig config);
IProgressDialog Loading(string title = null, Action onCancel = null, string cancelText = null, bool show = true, MaskType? maskType = null);
IProgressDialog Progress(string title = null, Action onCancel = null, string cancelText = null, bool show = true, MaskType? maskType = null);
void ShowLoading(string title = null, MaskType? maskType = null);
void HideLoading();
void ShowImage(IBitmap image, string message, int timeoutMillis = 2000);
void ShowSuccess(string message, int timeoutMillis = 2000);
void ShowError(string message, int timeoutMillis = 2000);
IDisposable Toast(string title, TimeSpan? dismissTimer = null);
IDisposable Toast(ToastConfig cfg);
}
} | mit | C# |
7ddbd3c71b05efb9f3c03c289a2629e746d5025e | Add ability to reset message counts. | FoundatioFx/Foundatio,exceptionless/Foundatio | src/Foundatio/Messaging/InMemoryMessageBus.cs | src/Foundatio/Messaging/InMemoryMessageBus.cs | using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Foundatio.Extensions;
using Foundatio.Logging;
namespace Foundatio.Messaging {
public class InMemoryMessageBus : MessageBusBase<InMemoryMessageBusOptions> {
private readonly ConcurrentDictionary<Type, long> _messageCounts = new ConcurrentDictionary<Type, long>();
private long _messagesSent;
[Obsolete("Use the options overload")]
public InMemoryMessageBus(ILoggerFactory loggerFactory = null) : this(new InMemoryMessageBusOptions { LoggerFactory = loggerFactory }) { }
public InMemoryMessageBus(InMemoryMessageBusOptions options) : base(options) { }
public long MessagesSent => _messagesSent;
public long GetMessagesSent(Type messageType) {
return _messageCounts.TryGetValue(messageType, out long count) ? count : 0;
}
public long GetMessagesSent<T>() {
return _messageCounts.TryGetValue(typeof(T), out long count) ? count : 0;
}
public void ResetMessagesSent() {
Interlocked.Exchange(ref _messagesSent, 0);
_messageCounts.Clear();
}
protected override Task PublishImplAsync(Type messageType, object message, TimeSpan? delay, CancellationToken cancellationToken) {
Interlocked.Increment(ref _messagesSent);
_messageCounts.AddOrUpdate(messageType, t => 1, (t, c) => c + 1);
if (_subscribers.IsEmpty)
return Task.CompletedTask;
if (delay.HasValue && delay.Value > TimeSpan.Zero) {
_logger.Trace("Schedule delayed message: {messageType} ({delay}ms)", messageType.FullName, delay.Value.TotalMilliseconds);
return AddDelayedMessageAsync(messageType, message, delay.Value);
}
var subscribers = _subscribers.Values.Where(s => s.IsAssignableFrom(messageType)).ToList();
if (subscribers.Count == 0) {
_logger.Trace(() => $"Done sending message to 0 subscribers for message type {messageType.Name}.");
return Task.CompletedTask;
}
_logger.Trace("Message Publish: {messageType}", messageType.FullName);
return SendMessageToSubscribersAsync(subscribers, messageType, message.Copy());
}
}
} | using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Foundatio.Extensions;
using Foundatio.Logging;
namespace Foundatio.Messaging {
public class InMemoryMessageBus : MessageBusBase<InMemoryMessageBusOptions> {
private readonly ConcurrentDictionary<Type, long> _messageCounts = new ConcurrentDictionary<Type, long>();
private long _messagesSent;
[Obsolete("Use the options overload")]
public InMemoryMessageBus(ILoggerFactory loggerFactory = null) : this(new InMemoryMessageBusOptions { LoggerFactory = loggerFactory }) { }
public InMemoryMessageBus(InMemoryMessageBusOptions options) : base(options) { }
public long MessagesSent => _messagesSent;
public long GetMessagesSent(Type messageType) {
return _messageCounts.TryGetValue(messageType, out long count) ? count : 0;
}
public long GetMessagesSent<T>() {
return _messageCounts.TryGetValue(typeof(T), out long count) ? count : 0;
}
protected override Task PublishImplAsync(Type messageType, object message, TimeSpan? delay, CancellationToken cancellationToken) {
Interlocked.Increment(ref _messagesSent);
_messageCounts.AddOrUpdate(messageType, t => 1, (t, c) => c + 1);
if (_subscribers.IsEmpty)
return Task.CompletedTask;
if (delay.HasValue && delay.Value > TimeSpan.Zero) {
_logger.Trace("Schedule delayed message: {messageType} ({delay}ms)", messageType.FullName, delay.Value.TotalMilliseconds);
return AddDelayedMessageAsync(messageType, message, delay.Value);
}
var subscribers = _subscribers.Values.Where(s => s.IsAssignableFrom(messageType)).ToList();
if (subscribers.Count == 0) {
_logger.Trace(() => $"Done sending message to 0 subscribers for message type {messageType.Name}.");
return Task.CompletedTask;
}
_logger.Trace("Message Publish: {messageType}", messageType.FullName);
return SendMessageToSubscribersAsync(subscribers, messageType, message.Copy());
}
}
} | apache-2.0 | C# |
f9a7306d8aa3c0f9c416ca0ac1c24c7b2060ab8a | Tweak precision | feliwir/openSage,feliwir/openSage | src/OpenSage.Game.Tests/Mathematics/AngleTests.cs | src/OpenSage.Game.Tests/Mathematics/AngleTests.cs | using System.Numerics;
using OpenSage.Mathematics;
using Xunit;
namespace OpenSage.Tests.Mathematics
{
public class AngleTests
{
private const int Precision = 4;
[Fact]
public void DegreesToRadiansTest()
{
Assert.Equal(MathUtility.ToRadians(90.0f), MathUtility.PiOver2, Precision);
}
[Fact]
public void RadiansToDegreesTest()
{
Assert.Equal(90.0f, MathUtility.ToDegrees(MathUtility.PiOver2), Precision);
}
[Theory]
[InlineData(0.0f, 1.0f, 90.0f)]
[InlineData(1.0f, 0.0f, 0.0f)]
[InlineData(0.0f, -1.0f, -90.0f)]
[InlineData(-1.0f, 0.0f, 180.0f)]
public void GetYawFromDirectionTest(float x, float y, float angle)
{
Assert.Equal(angle, MathUtility.ToDegrees(MathUtility.GetYawFromDirection(new Vector2(x, y))), Precision);
}
[Theory]
[InlineData(0.0f, 0.0f, 1.0f, 0.0f)]
[InlineData(0.0f, 1.0f, 0.0f, 90.0f)]
[InlineData(0.1f, 0.1f, 0.8f, 10.024973f)]
public void GetPitchFromDirectionTest(float x, float y, float z, float angle)
{
var vec = Vector3.Normalize(new Vector3(x, y, z));
Assert.Equal(angle, MathUtility.ToDegrees(MathUtility.GetPitchFromDirection(vec)), Precision);
}
[Theory]
[InlineData(90.0f, 180.0f, 90.0f)]
[InlineData(90.0f, -180.0f, 90.0f)]
[InlineData(90.0f, 0.0f, -90.0f)]
public void AngleDeltaTest(float alpha, float beta, float delta)
{
var alphaRad = MathUtility.ToRadians(alpha);
var betaRad = MathUtility.ToRadians(beta);
var deltaRad = MathUtility.ToRadians(delta);
Assert.Equal(deltaRad, MathUtility.CalculateAngleDelta(alphaRad, betaRad), Precision);
}
}
}
| using System.Numerics;
using OpenSage.Mathematics;
using Xunit;
namespace OpenSage.Tests.Mathematics
{
public class AngleTests
{
private const int Precision = 6;
[Fact]
public void DegreesToRadiansTest()
{
Assert.Equal(MathUtility.ToRadians(90.0f), MathUtility.PiOver2, Precision);
}
[Fact]
public void RadiansToDegreesTest()
{
Assert.Equal(90.0f, MathUtility.ToDegrees(MathUtility.PiOver2), Precision);
}
[Theory]
[InlineData(0.0f, 1.0f, 90.0f)]
[InlineData(1.0f, 0.0f, 0.0f)]
[InlineData(0.0f, -1.0f, -90.0f)]
[InlineData(-1.0f, 0.0f, 180.0f)]
public void GetYawFromDirectionTest(float x, float y, float angle)
{
Assert.Equal(angle, MathUtility.ToDegrees(MathUtility.GetYawFromDirection(new Vector2(x, y))), Precision);
}
[Theory]
[InlineData(0.0f, 0.0f, 1.0f, 0.0f)]
[InlineData(0.0f, 1.0f, 0.0f, 90.0f)]
[InlineData(0.1f, 0.1f, 0.8f, 10.024973f)]
public void GetPitchFromDirectionTest(float x, float y, float z, float angle)
{
var vec = Vector3.Normalize(new Vector3(x, y, z));
Assert.Equal(angle, MathUtility.ToDegrees(MathUtility.GetPitchFromDirection(vec)), Precision);
}
[Theory]
[InlineData(90.0f, 180.0f, 90.0f)]
[InlineData(90.0f, -180.0f, 90.0f)]
[InlineData(90.0f, 0.0f, -90.0f)]
public void AngleDeltaTest(float alpha, float beta, float delta)
{
var alphaRad = MathUtility.ToRadians(alpha);
var betaRad = MathUtility.ToRadians(beta);
var deltaRad = MathUtility.ToRadians(delta);
Assert.Equal(deltaRad, MathUtility.CalculateAngleDelta(alphaRad, betaRad), Precision);
}
}
}
| mit | C# |
f423dbbb1de22222abf01bdfdcd9f7fec5c20d8c | Fix codepath where the property is a value type but the weakreference has been collected. | wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,Perspex/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex | src/Avalonia.Base/Data/Core/SettableNode.cs | src/Avalonia.Base/Data/Core/SettableNode.cs | using Avalonia.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Avalonia.Data.Core
{
internal abstract class SettableNode : ExpressionNode
{
public bool SetTargetValue(object value, BindingPriority priority)
{
if (ShouldNotSet(value))
{
return true;
}
return SetTargetValueCore(value, priority);
}
private bool ShouldNotSet(object value)
{
if (PropertyType == null)
{
return false;
}
if (PropertyType.IsValueType)
{
return LastValue?.Target != null && LastValue.Target.Equals(value);
}
return LastValue != null && Object.ReferenceEquals(LastValue?.Target, value);
}
protected abstract bool SetTargetValueCore(object value, BindingPriority priority);
public abstract Type PropertyType { get; }
}
}
| using Avalonia.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Avalonia.Data.Core
{
internal abstract class SettableNode : ExpressionNode
{
public bool SetTargetValue(object value, BindingPriority priority)
{
if (ShouldNotSet(value))
{
return true;
}
return SetTargetValueCore(value, priority);
}
private bool ShouldNotSet(object value)
{
if (PropertyType == null)
{
return false;
}
if (PropertyType.IsValueType)
{
return LastValue?.Target.Equals(value) ?? false;
}
return LastValue != null && Object.ReferenceEquals(LastValue?.Target, value);
}
protected abstract bool SetTargetValueCore(object value, BindingPriority priority);
public abstract Type PropertyType { get; }
}
}
| mit | C# |
a049b568b961415714d653c6ab4c4e9fa196dada | Fix tests | JetBrains/teamcity-runas,JetBrains/teamcity-runas,JetBrains/teamcity-runas,JetBrains/teamcity-runas,JetBrains/teamcity-runas-plugin,JetBrains/teamcity-runas-plugin | runAs-tool-win32/JetBrains.runAs.IntegrationTests/Dsl/RunAsRunner.cs | runAs-tool-win32/JetBrains.runAs.IntegrationTests/Dsl/RunAsRunner.cs | namespace JetBrains.runAs.IntegrationTests.Dsl
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
internal class RunAsRunner
{
public TestSession Run(TestContext ctx)
{
var lines = new List<string>();
var cmdArgs = ctx.CommandLineSetup.Arguments.ToList();
cmdArgs.Insert(0, "-l:debug");
lines.AddRange(ctx.CommandLineSetup.EnvVariables.Select(envVar => $"@SET \"{envVar.Key}={envVar.Value}\""));
lines.Add($"@pushd \"{ctx.CurrentDirectory}\"");
lines.Add($"@\"{ctx.CommandLineSetup.ToolName}\" " + string.Join(" ", cmdArgs));
lines.Add("@set exitCode=%errorlevel%");
lines.Add("@popd");
lines.Add("@exit /b %exitCode%");
var cmd = Path.Combine(ctx.SandboxPath, "run.cmd");
File.WriteAllText(cmd, string.Join(Environment.NewLine, lines));
var output = new StringBuilder();
var errors = new StringBuilder();
var process = new Process();
process.StartInfo.FileName = cmd;
process.StartInfo.UseShellExecute = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
process.ErrorDataReceived += (sender, args) => { errors.AppendLine(args.Data); };
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
var outputStr = output.ToString();
var errorsStr = errors.ToString();
Console.WriteLine(outputStr);
return new TestSession(ctx, process.ExitCode, outputStr, errorsStr);
}
}
}
| namespace JetBrains.runAs.IntegrationTests.Dsl
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
internal class RunAsRunner
{
public TestSession Run(TestContext ctx)
{
var lines = new List<string>();
var cmdArgs = ctx.CommandLineSetup.Arguments.ToList();
// cmdArgs.Insert(0, "-l:debug");
lines.AddRange(ctx.CommandLineSetup.EnvVariables.Select(envVar => $"@SET \"{envVar.Key}={envVar.Value}\""));
lines.Add($"@pushd \"{ctx.CurrentDirectory}\"");
lines.Add($"@\"{ctx.CommandLineSetup.ToolName}\" " + string.Join(" ", cmdArgs));
lines.Add("@set exitCode=%errorlevel%");
lines.Add("@popd");
lines.Add("@exit /b %exitCode%");
var cmd = Path.Combine(ctx.SandboxPath, "run.cmd");
File.WriteAllText(cmd, string.Join(Environment.NewLine, lines));
var output = new StringBuilder();
var errors = new StringBuilder();
var process = new Process();
process.StartInfo.FileName = cmd;
process.StartInfo.UseShellExecute = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
process.ErrorDataReceived += (sender, args) => { errors.AppendLine(args.Data); };
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
var outputStr = output.ToString();
var errorsStr = errors.ToString();
Console.WriteLine(outputStr);
return new TestSession(ctx, process.ExitCode, outputStr, errorsStr);
}
}
}
| apache-2.0 | C# |
fee2f0d58872c0a0ab56e16322d7d0bd20015439 | Revert "fix(logging): 🐛 try yet another AppInsights config" | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | services/SharedKernel/FilterLists.SharedKernel.Logging/HostRunner.cs | services/SharedKernel/FilterLists.SharedKernel.Logging/HostRunner.cs | using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace FilterLists.SharedKernel.Logging
{
public static class HostRunner
{
public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default)
{
_ = host ?? throw new ArgumentNullException(nameof(host));
Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration
.WriteTo.Conditional(
_ => host.Services.GetService<IHostEnvironment>().IsProduction(),
c => c.ApplicationInsights(
TelemetryConfiguration.CreateDefault(),
TelemetryConverter.Traces))
.CreateLogger();
try
{
if (runPreHostAsync != null)
{
Log.Information("Initializing pre-host");
await runPreHostAsync();
}
Log.Information("Initializing host");
await host.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
throw;
}
finally
{
Log.CloseAndFlush();
}
}
}
}
| using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace FilterLists.SharedKernel.Logging
{
public static class HostRunner
{
public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default)
{
_ = host ?? throw new ArgumentNullException(nameof(host));
InitializeLogger(host);
try
{
if (runPreHostAsync != null)
{
Log.Information("Initializing pre-host");
await runPreHostAsync();
}
Log.Information("Initializing host");
await host.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
throw;
}
finally
{
Log.CloseAndFlush();
}
}
private static void InitializeLogger(IHost host)
{
var hostEnvironment = host.Services.GetRequiredService<IHostEnvironment>();
Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration
.ReadFrom.Configuration(host.Services.GetRequiredService<IConfiguration>())
.Enrich.WithProperty("Application", hostEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", hostEnvironment.EnvironmentName)
.WriteTo.Conditional(
_ => !hostEnvironment.IsProduction(),
sc => sc.Console().WriteTo.Debug())
.WriteTo.Conditional(
_ => hostEnvironment.IsProduction(),
sc => sc.ApplicationInsights(
host.Services.GetRequiredService<TelemetryConfiguration>(),
TelemetryConverter.Traces))
.CreateLogger();
}
}
}
| mit | C# |
2c783813bb3317c09f968193b0fa38298c7d0b8f | Improve argNpath test | Tragetaschen/dbus-sharp,mono/dbus-sharp,openmedicus/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp,mono/dbus-sharp,arfbtwn/dbus-sharp,arfbtwn/dbus-sharp | tests/MatchRuleTest.cs | tests/MatchRuleTest.cs | // Copyright 2009 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NUnit.Framework;
using NDesk.DBus;
namespace NDesk.DBus.Tests
{
[TestFixture]
public class MatchRuleTest
{
[Test]
public void Parse ()
{
string ruleText = @"member='Lala'";
MatchRule rule = MatchRule.Parse (ruleText);
Assert.AreEqual (null, rule.MessageType);
Assert.AreEqual (null, rule.Interface);
Assert.AreEqual ("Lala", rule.Member);
Assert.AreEqual (null, rule.Path);
Assert.AreEqual (null, rule.Sender);
Assert.AreEqual (null, rule.Destination);
Assert.AreEqual (0, rule.Args.Count);
Assert.AreEqual (ruleText, rule.ToString ());
}
[Test]
public void ParsePathArgs ()
{
string ruleText = @"arg0='La',arg1path='Foo'";
MatchRule rule = MatchRule.Parse (ruleText);
Assert.AreEqual (ruleText, rule.ToString ());
}
[Test]
[ExpectedException (typeof (Exception))]
public void ParseBadArgsMaxAllowed ()
{
string ruleText = @"arg64='Foo'";
MatchRule.Parse (ruleText);
}
// TODO: Should fail
/*
[Test]
public void ParseArgsPartiallyBad ()
{
string ruleText = @"arg0='A',arg4='Foo\'";
MatchRule.Parse (ruleText);
}
*/
// TODO: Should fail
/*
[Test]
//[ExpectedException]
public void ParseArgsRepeated ()
{
string ruleText = @"arg0='A',arg0='A'";
MatchRule.Parse (ruleText);
}
*/
[Test]
public void ParseArgsMaxAllowed ()
{
string ruleText = @"arg63='Foo'";
MatchRule.Parse (ruleText);
}
[Test]
public void ParseArgs ()
{
string ruleText = @"arg5='F,o\'o\\\'\\',arg8=''";
MatchRule rule = MatchRule.Parse (ruleText);
Assert.AreEqual (null, rule.MessageType);
Assert.AreEqual (null, rule.Interface);
Assert.AreEqual (null, rule.Member);
Assert.AreEqual (null, rule.Path);
Assert.AreEqual (null, rule.Sender);
Assert.AreEqual (null, rule.Destination);
Assert.AreEqual (2, rule.Args.Count);
Assert.AreEqual (@"F,o'o\'\", rule.Args[5]);
Assert.AreEqual (@"", rule.Args[8]);
Assert.AreEqual (ruleText, rule.ToString ());
}
}
}
| // Copyright 2009 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NUnit.Framework;
using NDesk.DBus;
namespace NDesk.DBus.Tests
{
[TestFixture]
public class MatchRuleTest
{
[Test]
public void Parse ()
{
string ruleText = @"member='Lala'";
MatchRule rule = MatchRule.Parse (ruleText);
Assert.AreEqual (null, rule.MessageType);
Assert.AreEqual (null, rule.Interface);
Assert.AreEqual ("Lala", rule.Member);
Assert.AreEqual (null, rule.Path);
Assert.AreEqual (null, rule.Sender);
Assert.AreEqual (null, rule.Destination);
Assert.AreEqual (0, rule.Args.Count);
Assert.AreEqual (ruleText, rule.ToString ());
}
[Test]
public void ParsePathArgs ()
{
string ruleText = @"arg0path='Foo'";
MatchRule.Parse (ruleText);
}
[Test]
[ExpectedException (typeof (Exception))]
public void ParseBadArgsMaxAllowed ()
{
string ruleText = @"arg64='Foo'";
MatchRule.Parse (ruleText);
}
// TODO: Should fail
/*
[Test]
public void ParseArgsPartiallyBad ()
{
string ruleText = @"arg0='A',arg4='Foo\'";
MatchRule.Parse (ruleText);
}
*/
// TODO: Should fail
/*
[Test]
//[ExpectedException]
public void ParseArgsRepeated ()
{
string ruleText = @"arg0='A',arg0='A'";
MatchRule.Parse (ruleText);
}
*/
[Test]
public void ParseArgsMaxAllowed ()
{
string ruleText = @"arg63='Foo'";
MatchRule.Parse (ruleText);
}
[Test]
public void ParseArgs ()
{
string ruleText = @"arg5='F,o\'o\\\'\\',arg8=''";
MatchRule rule = MatchRule.Parse (ruleText);
Assert.AreEqual (null, rule.MessageType);
Assert.AreEqual (null, rule.Interface);
Assert.AreEqual (null, rule.Member);
Assert.AreEqual (null, rule.Path);
Assert.AreEqual (null, rule.Sender);
Assert.AreEqual (null, rule.Destination);
Assert.AreEqual (2, rule.Args.Count);
Assert.AreEqual (@"F,o'o\'\", rule.Args[5]);
Assert.AreEqual (@"", rule.Args[8]);
Assert.AreEqual (ruleText, rule.ToString ());
}
}
}
| mit | C# |
58b3ac0d979022e016c03c93397e8196c5697e09 | Remove flags attribute as its not needed | dipeshc/BTDeploy | src/MonoTorrent/MonoTorrent.Common/Enums.cs | src/MonoTorrent/MonoTorrent.Common/Enums.cs | //
// Enums.cs
//
// Authors:
// Alan McGovern [email protected]
//
// Copyright (C) 2006 Alan McGovern
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace MonoTorrent.Common
{
public enum PeerStatus
{
Available,
Connecting,
Connected
}
public enum Direction
{
None,
Incoming,
Outgoing
}
public enum TorrentState
{
Stopped,
Paused,
Downloading,
Seeding,
Hashing,
Stopping
}
public enum Priority
{
DoNotDownload = 0,
Lowest = 1,
Low = 2,
Normal = 4,
High = 8,
Highest = 16,
Immediate = 32
}
public enum TrackerState
{
Unknown,
Announcing,
AnnouncingFailed,
AnnounceSuccessful,
Scraping,
ScrapingFailed,
ScrapeSuccessful
}
public enum TorrentEvent
{
None,
Started,
Stopped,
Completed
}
public enum PeerConnectionEvent
{
IncomingConnectionReceived,
OutgoingConnectionCreated,
Disconnected
}
public enum PieceEvent
{
BlockWriteQueued,
BlockNotRequested,
BlockWrittenToDisk,
HashPassed,
HashFailed
}
public enum PeerListType
{
NascentPeers,
CandidatePeers,
OptimisticUnchokeCandidatePeers
}
}
| //
// Enums.cs
//
// Authors:
// Alan McGovern [email protected]
//
// Copyright (C) 2006 Alan McGovern
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace MonoTorrent.Common
{
[Flags]
public enum PeerStatus
{
Available,
Connecting,
Connected
}
public enum Direction
{
None,
Incoming,
Outgoing
}
public enum TorrentState
{
Stopped,
Paused,
Downloading,
Seeding,
Hashing,
Stopping
}
public enum Priority
{
DoNotDownload = 0,
Lowest = 1,
Low = 2,
Normal = 4,
High = 8,
Highest = 16,
Immediate = 32
}
public enum TrackerState
{
Unknown,
Announcing,
AnnouncingFailed,
AnnounceSuccessful,
Scraping,
ScrapingFailed,
ScrapeSuccessful
}
public enum TorrentEvent
{
None,
Started,
Stopped,
Completed
}
public enum PeerConnectionEvent
{
IncomingConnectionReceived,
OutgoingConnectionCreated,
Disconnected
}
public enum PieceEvent
{
BlockWriteQueued,
BlockNotRequested,
BlockWrittenToDisk,
HashPassed,
HashFailed
}
public enum PeerListType
{
NascentPeers,
CandidatePeers,
OptimisticUnchokeCandidatePeers
}
}
| mit | C# |
c9520a51780baeb78608c9b321acd2b84c3e7893 | clean up | dkataskin/bstrkr | bstrkr.mobile/bstrkr.core/Collections/CollectionExtensions.cs | bstrkr.mobile/bstrkr.core/Collections/CollectionExtensions.cs | using System;
using System.Collections.Generic;
namespace bstrkr.core.collections
{
public static class CollectionExtensions
{
public static MergeStats Merge<T, TKey>(
this ICollection<T> collection,
IEnumerable<T> updates,
Func<T, TKey> keySelector,
Action<T, T> updateFactory) where T : class
{
return Merge(collection, updates, keySelector, item => item, updateFactory);
}
public static MergeStats Merge<T, TKey>(
this ICollection<T> collection,
IEnumerable<T> updates,
Func<T, TKey> keySelector,
Func<T, T> addFactory,
Action<T, T> updateFactory) where T : class
{
return Update(collection, updates, keySelector, keySelector, addFactory, updateFactory);
}
public static MergeStats Update<T, V, TKey>(
this ICollection<T> collection,
IEnumerable<V> updates,
Func<T, TKey> itemKeySelector,
Func<V, TKey> updateKeySelector,
Func<V, T> addFactory,
Action<T, V> updateFactory) where T : class
{
var newItems = 0;
var updatedItems = 0;
var deletedItems = 0;
if (updates == null)
{
deletedItems = collection.Count;
collection.Clear();
return new MergeStats(0, 0, deletedItems);
}
var sourceDict = new Dictionary<TKey, T>();
foreach (var item in collection)
{
sourceDict[itemKeySelector(item)] = item;
}
var updatesDict = new Dictionary<TKey, V>();
foreach (var item in updates)
{
updatesDict[updateKeySelector(item)] = item;
}
var removedKeys = new List<TKey>();
foreach (TKey key in sourceDict.Keys)
{
if (!updatesDict.ContainsKey(key))
{
removedKeys.Add(key);
deletedItems++;
}
}
foreach (var key in removedKeys)
{
collection.Remove(sourceDict[key] as T);
sourceDict.Remove(key);
}
foreach (var item in updates)
{
var key = updateKeySelector(item);
if (sourceDict.ContainsKey(key))
{
updateFactory(sourceDict[key] as T, item);
updatedItems++;
}
else
{
collection.Add(addFactory(item));
newItems++;
}
}
return new MergeStats(newItems, updatedItems, deletedItems);
}
public class MergeStats
{
public MergeStats(int newItems, int updatedItems, int deletedItems)
{
this.NewItems = newItems;
this.UpdatedItems = updatedItems;
this.DeletedItems = deletedItems;
}
public int NewItems { get; private set; }
public int UpdatedItems { get; private set; }
public int DeletedItems { get; private set; }
}
}
} | using System;
using System.Collections.Generic;
namespace Collections
{
public static class CollectionExtensions
{
public static MergeStats Merge<T, TKey>(
this ICollection<T> collection,
IEnumerable<T> updates,
Func<T, TKey> keySelector,
Action<T, T> updateFactory) where T : class
{
return Merge(collection, updates, keySelector, item => item, updateFactory);
}
public static MergeStats Merge<T, TKey>(
this ICollection<T> collection,
IEnumerable<T> updates,
Func<T, TKey> keySelector,
Func<T, T> addFactory,
Action<T, T> updateFactory) where T : class
{
return Update(collection, updates, keySelector, keySelector, addFactory, updateFactory);
}
public static MergeStats Update<T, V, TKey>(
this ICollection<T> collection,
IEnumerable<V> updates,
Func<T, TKey> itemKeySelector,
Func<V, TKey> updateKeySelector,
Func<V, T> addFactory,
Action<T, V> updateFactory) where T : class
{
var newItems = 0;
var updatedItems = 0;
var deletedItems = 0;
if (updates == null)
{
deletedItems = collection.Count;
collection.Clear();
return new MergeStats(0, 0, deletedItems);
}
var sourceDict = new Dictionary<TKey, T>();
foreach (var item in collection)
{
sourceDict[itemKeySelector(item)] = item;
}
var updatesDict = new Dictionary<TKey, V>();
foreach (var item in updates)
{
updatesDict[updateKeySelector(item)] = item;
}
var removedKeys = new List<TKey>();
foreach (TKey key in sourceDict.Keys)
{
if (!updatesDict.ContainsKey(key))
{
removedKeys.Add(key);
deletedItems++;
}
}
foreach (var key in removedKeys)
{
collection.Remove(sourceDict[key] as T);
sourceDict.Remove(key);
}
foreach (var item in updates)
{
var key = updateKeySelector(item);
if (sourceDict.ContainsKey(key))
{
updateFactory(sourceDict[key] as T, item);
updatedItems++;
}
else
{
collection.Add(addFactory(item));
newItems++;
}
}
return new MergeStats(newItems, updatedItems, deletedItems);
}
public class MergeStats
{
public MergeStats(int newItems, int updatedItems, int deletedItems)
{
this.NewItems = newItems;
this.UpdatedItems = updatedItems;
this.DeletedItems = deletedItems;
}
public int NewItems { get; private set; }
public int UpdatedItems { get; private set; }
public int DeletedItems { get; private set; }
}
}
} | bsd-2-clause | C# |
d3772bd1e5c4d5ae6aa3fe1386c88450e3d4a9f8 | Update AssemblyInfo.cs. | espresso3389/AdaptiveKeyboardConfig,rogercloud/AdaptiveKeyboardConfig | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Adaptive Keyboard Configuration Utility")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Adaptive Keyboard Configuration Utility")]
[assembly: AssemblyCopyright("Copyright © 2014 [email protected]")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Adaptive Keyboard Configuration Utility")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdaptiveKeyboardConfig")]
[assembly: AssemblyCopyright("Copyright © 2014 [email protected]")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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# |
65790131f01e7c54a510296856936b1c59285244 | sort out registration of marker interfaces within EmployerAccounts. | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts/DependencyResolution/HashingRegistry.cs | src/SFA.DAS.EmployerAccounts/DependencyResolution/HashingRegistry.cs | using System;
using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.MarkerInterfaces;
using SFA.DAS.HashingService;
using StructureMap;
namespace SFA.DAS.EmployerAccounts.DependencyResolution
{
public class HashingRegistry : Registry
{
public HashingRegistry()
{
For<IHashingService>()
.Use(c =>
new HashingService.HashingService(
c.GetInstance<EmployerAccountsConfiguration>().AllowedHashstringCharacters,
c.GetInstance<EmployerAccountsConfiguration>().Hashstring));
For<IPublicHashingService>()
.Use<MarkerInterfaceWrapper>()
.Ctor<IHashingService>()
.Is(c =>
new HashingService.HashingService(
c.GetInstance<EmployerAccountsConfiguration>().PublicAllowedHashstringCharacters,
c.GetInstance<EmployerAccountsConfiguration>().PublicHashstring)
);
For<IAccountLegalEntityPublicHashingService>()
.Use<MarkerInterfaceWrapper>()
.Ctor<IHashingService>()
.Is(c =>
new HashingService.HashingService(
c.GetInstance<EmployerAccountsConfiguration>() .PublicAllowedAccountLegalEntityHashstringCharacters,
c.GetInstance<EmployerAccountsConfiguration>().PublicAllowedAccountLegalEntityHashstringSalt));
}
}
public class MarkerInterfaceWrapper
: IAccountLegalEntityPublicHashingService,
IPublicHashingService
{
private IHashingService _hashingServiceWithCorrectValuesForMarkerInterface;
public MarkerInterfaceWrapper(IHashingService hashingServiceWithCorrectValuesForMarkerInterface)
{
_hashingServiceWithCorrectValuesForMarkerInterface = hashingServiceWithCorrectValuesForMarkerInterface;
}
public string HashValue(long id)
{
return _hashingServiceWithCorrectValuesForMarkerInterface.HashValue(id);
}
public string HashValue(Guid id)
{
return _hashingServiceWithCorrectValuesForMarkerInterface.HashValue(id);
}
public string HashValue(string id)
{
return _hashingServiceWithCorrectValuesForMarkerInterface.HashValue(id);
}
public long DecodeValue(string id)
{
return _hashingServiceWithCorrectValuesForMarkerInterface.DecodeValue(id);
}
public Guid DecodeValueToGuid(string id)
{
return _hashingServiceWithCorrectValuesForMarkerInterface.DecodeValueToGuid(id);
}
public string DecodeValueToString(string id)
{
return _hashingServiceWithCorrectValuesForMarkerInterface.DecodeValueToString(id);
}
}
} | using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.MarkerInterfaces;
using SFA.DAS.HashingService;
using StructureMap;
namespace SFA.DAS.EmployerAccounts.DependencyResolution
{
public class HashingRegistry : Registry
{
public HashingRegistry()
{
For<IHashingService>().Use(c => GetHashingService(c));
For<IPublicHashingService>().Use(c => GetPublicHashingService(c));
For<IAccountLegalEntityPublicHashingService>().Add(c => GetAccountLegalEntityPublicHashingService(c));
}
private IHashingService GetHashingService(IContext context)
{
var config = context.GetInstance<EmployerAccountsConfiguration>();
var hashingService = new HashingService.HashingService(config.AllowedHashstringCharacters, config.Hashstring);
return hashingService;
}
private IPublicHashingService GetPublicHashingService(IContext context)
{
var config = context.GetInstance<EmployerAccountsConfiguration>();
var publicHashingService = new HashingService.HashingService(config.PublicAllowedHashstringCharacters, config.PublicHashstring);
return publicHashingService as IPublicHashingService;
}
private IAccountLegalEntityPublicHashingService GetAccountLegalEntityPublicHashingService(IContext context)
{
var config = context.GetInstance<EmployerAccountsConfiguration>();
var accountLegalEntityPublicHashingService = new HashingService.HashingService(config.PublicAllowedAccountLegalEntityHashstringCharacters, config.PublicAllowedAccountLegalEntityHashstringSalt);
return accountLegalEntityPublicHashingService as IAccountLegalEntityPublicHashingService;
}
}
} | mit | C# |
3fe973a3a70a48f6dbd4f8986a82ddf749b57cf7 | Update AvaloniaImageImporter.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Editor/AvaloniaImageImporter.cs | src/Core2D/Editor/AvaloniaImageImporter.cs | #nullable enable
using System;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Core2D.Model;
using Core2D.ViewModels;
using Core2D.ViewModels.Editor;
using Core2D.Views;
namespace Core2D.Editor;
public class AvaloniaImageImporter : IImageImporter
{
private readonly IServiceProvider? _serviceProvider;
public AvaloniaImageImporter(IServiceProvider? serviceProvider)
{
_serviceProvider = serviceProvider;
}
private Window? GetWindow()
{
return _serviceProvider?.GetService<Window>();
}
public async Task<string> GetImageKeyAsync()
{
try
{
var dlg = new OpenFileDialog() { Title = "Open" };
dlg.Filters.Add(new FileDialogFilter() { Name = "All", Extensions = { "*" } });
var result = await dlg.ShowAsync(GetWindow());
var path = result?.FirstOrDefault();
if (path is { })
{
return _serviceProvider.GetService<ProjectEditorViewModel>().OnGetImageKey(path);
}
}
catch (Exception ex)
{
_serviceProvider.GetService<ILog>()?.LogException(ex);
}
return default;
}
}
| #nullable enable
using System;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Core2D.Model;
using Core2D.ViewModels;
using Core2D.ViewModels.Editor;
using Core2D.Views;
namespace Core2D.Editor;
public class AvaloniaImageImporter : IImageImporter
{
private readonly IServiceProvider? _serviceProvider;
public AvaloniaImageImporter(IServiceProvider? serviceProvider)
{
_serviceProvider = serviceProvider;
}
private MainWindow? GetWindow()
{
return _serviceProvider?.GetService<MainWindow>();
}
public async Task<string> GetImageKeyAsync()
{
try
{
var dlg = new OpenFileDialog() { Title = "Open" };
dlg.Filters.Add(new FileDialogFilter() { Name = "All", Extensions = { "*" } });
var result = await dlg.ShowAsync(GetWindow());
var path = result?.FirstOrDefault();
if (path is { })
{
return _serviceProvider.GetService<ProjectEditorViewModel>().OnGetImageKey(path);
}
}
catch (Exception ex)
{
_serviceProvider.GetService<ILog>()?.LogException(ex);
}
return default;
}
} | mit | C# |
dd755d6b0181d1413e3124b75aae432a8d98c527 | update Kevin Marquette bio information | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/KevinMarquette.cs | src/Firehose.Web/Authors/KevinMarquette.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class KevinMarquette : IAmAMicrosoftMVP
{
public string FirstName => "Kevin";
public string LastName => "Marquette";
public string ShortBioOrTagLine => "Sr. DevOps Engineer, 2018 PowerShell Community Hero, Microsoft MVP, and SoCal PowerShell UserGroup Organizer.";
public string StateOrRegion => "Orange County, USA";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "kevinmarquette";
public string GitHubHandle => "kevinmarquette";
public string GravatarHash => "d7d29e9573b5da44d9886df24fcc6142";
public GeoPosition Position => new GeoPosition(33.6800000,-117.7900000);
public Uri WebSite => new Uri("https://kevinmarquette.github.io");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://kevinmarquette.github.io/feed.xml"); } }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class KevinMarquette : IAmACommunityMember
{
public string FirstName => "Kevin";
public string LastName => "Marquette";
public string ShortBioOrTagLine => "Sr. DevOps Engineer. Powershell all the things!";
public string StateOrRegion => "Orange County, USA";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "kevinmarquette";
public string GitHubHandle => "kevinmarquette";
public string GravatarHash => "d7d29e9573b5da44d9886df24fcc6142";
public GeoPosition Position => new GeoPosition(33.6800000,-117.7900000);
public Uri WebSite => new Uri("https://kevinmarquette.github.io");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://kevinmarquette.github.io/feed.xml"); } }
}
}
| mit | C# |
4eb6026cc3a0b785bd77faa80a64e202a48d1491 | Fix import tag to have correct namespace | hzhgis/ss,HermanSchoenfeld/fluent-nhibernate,chester89/fluent-nhibernate,narnau/fluent-nhibernate,bogdan7/nhibernate,narnau/fluent-nhibernate,oceanho/fluent-nhibernate,lingxyd/fluent-nhibernate,hzhgis/ss,bogdan7/nhibernate,MiguelMadero/fluent-nhibernate,oceanho/fluent-nhibernate,hzhgis/ss,owerkop/fluent-nhibernate,lingxyd/fluent-nhibernate,MiguelMadero/fluent-nhibernate,chester89/fluent-nhibernate,bogdan7/nhibernate,HermanSchoenfeld/fluent-nhibernate,chester89/fluent-nhibernate,owerkop/fluent-nhibernate | src/FluentNHibernate/Mapping/ImportPart.cs | src/FluentNHibernate/Mapping/ImportPart.cs | using System;
using System.Xml;
namespace FluentNHibernate.Mapping
{
public class ImportPart : IMappingPart
{
private readonly Cache<string, string> attributes = new Cache<string, string>();
private readonly Type importType;
public ImportPart(Type importType)
{
this.importType = importType;
}
public void SetAttribute(string name, string value)
{
attributes.Store(name, value);
}
public void SetAttributes(Attributes attrs)
{
foreach (var key in attrs.Keys)
{
SetAttribute(key, attrs[key]);
}
}
public void Write(XmlElement classElement, IMappingVisitor visitor)
{
var importElement = classElement.AddElement("import")
.WithAtt("class", importType.AssemblyQualifiedName)
.WithAtt("xmlns", "urn:nhibernate-mapping-2.2");
attributes.ForEachPair((name, value) => importElement.WithAtt(name, value));
}
public void As(string alternativeName)
{
SetAttribute("rename", alternativeName);
}
public int Level
{
get { return 1; }
}
public PartPosition Position
{
get { return PartPosition.First; }
}
}
} | using System;
using System.Xml;
namespace FluentNHibernate.Mapping
{
public class ImportPart : IMappingPart
{
private readonly Cache<string, string> attributes = new Cache<string, string>();
private readonly Type importType;
public ImportPart(Type importType)
{
this.importType = importType;
}
public void SetAttribute(string name, string value)
{
attributes.Store(name, value);
}
public void SetAttributes(Attributes attrs)
{
foreach (var key in attrs.Keys)
{
SetAttribute(key, attrs[key]);
}
}
public void Write(XmlElement classElement, IMappingVisitor visitor)
{
var importElement = classElement.AddElement("import")
.WithAtt("class", importType.AssemblyQualifiedName);
attributes.ForEachPair((name, value) => importElement.WithAtt(name, value));
}
public void As(string alternativeName)
{
SetAttribute("rename", alternativeName);
}
public int Level
{
get { return 1; }
}
public PartPosition Position
{
get { return PartPosition.First; }
}
}
} | bsd-3-clause | C# |
089e13346f04c78158f8af37a4e69c377bf889ec | Fix possible null ref in ConsoleInitializer. | antiufo/NuGet2,RichiCoder1/nuget-chocolatey,dolkensp/node.net,jholovacs/NuGet,mrward/NuGet.V2,oliver-feng/nuget,mrward/NuGet.V2,alluran/node.net,jmezach/NuGet2,dolkensp/node.net,rikoe/nuget,mono/nuget,jmezach/NuGet2,pratikkagda/nuget,mrward/nuget,xoofx/NuGet,akrisiun/NuGet,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,antiufo/NuGet2,GearedToWar/NuGet2,chocolatey/nuget-chocolatey,oliver-feng/nuget,ctaggart/nuget,jholovacs/NuGet,GearedToWar/NuGet2,GearedToWar/NuGet2,mrward/NuGet.V2,chocolatey/nuget-chocolatey,mrward/NuGet.V2,GearedToWar/NuGet2,jholovacs/NuGet,dolkensp/node.net,pratikkagda/nuget,alluran/node.net,antiufo/NuGet2,jmezach/NuGet2,dolkensp/node.net,mono/nuget,pratikkagda/nuget,xoofx/NuGet,mrward/nuget,mono/nuget,chocolatey/nuget-chocolatey,zskullz/nuget,jmezach/NuGet2,OneGet/nuget,mrward/nuget,chocolatey/nuget-chocolatey,rikoe/nuget,oliver-feng/nuget,antiufo/NuGet2,OneGet/nuget,jholovacs/NuGet,mrward/nuget,mrward/nuget,indsoft/NuGet2,xoofx/NuGet,oliver-feng/nuget,pratikkagda/nuget,indsoft/NuGet2,indsoft/NuGet2,zskullz/nuget,mrward/NuGet.V2,xoofx/NuGet,GearedToWar/NuGet2,rikoe/nuget,oliver-feng/nuget,OneGet/nuget,indsoft/NuGet2,ctaggart/nuget,rikoe/nuget,mrward/NuGet.V2,ctaggart/nuget,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey,antiufo/NuGet2,akrisiun/NuGet,alluran/node.net,oliver-feng/nuget,mono/nuget,mrward/nuget,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,pratikkagda/nuget,GearedToWar/NuGet2,RichiCoder1/nuget-chocolatey,xoofx/NuGet,xoofx/NuGet,jholovacs/NuGet,zskullz/nuget,OneGet/nuget,indsoft/NuGet2,alluran/node.net,ctaggart/nuget,chocolatey/nuget-chocolatey,zskullz/nuget,pratikkagda/nuget,indsoft/NuGet2,jholovacs/NuGet,chocolatey/nuget-chocolatey,jmezach/NuGet2 | src/VsConsole/Console/ConsoleInitializer.cs | src/VsConsole/Console/ConsoleInitializer.cs | using System;
using System.ComponentModel.Composition;
using System.Security;
using System.Threading.Tasks;
using Microsoft.VisualStudio.ComponentModelHost;
using VsPackage = Microsoft.VisualStudio.Shell.Package;
namespace NuGetConsole
{
[Export(typeof(IConsoleInitializer))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class ConsoleInitializer : IConsoleInitializer
{
private readonly Lazy<Task<Action>> _initializeTask = new Lazy<Task<Action>>(GetInitializeTask);
public Task<Action> Initialize()
{
return _initializeTask.Value;
}
private static Task<Action> GetInitializeTask()
{
var componentModel = (IComponentModel)VsPackage.GetGlobalService(typeof(SComponentModel));
if (componentModel == null)
{
throw new InvalidOperationException();
}
try
{
// HACK: Short cut to set the Powershell execution policy for this process to RemoteSigned.
// This is so that we can initialize the PowerShell host and load our modules successfully.
Environment.SetEnvironmentVariable(
"PSExecutionPolicyPreference", "RemoteSigned", EnvironmentVariableTarget.Process);
}
catch (SecurityException)
{
// ignore if user doesn't have permission to add process-level environment variable,
// which is very rare.
}
var initializer = componentModel.GetService<IHostInitializer>();
return Task.Factory.StartNew((state) =>
{
var hostInitializer = (IHostInitializer)state;
if (hostInitializer != null)
{
hostInitializer.Start();
return new Action(hostInitializer.SetDefaultRunspace);
}
else
{
return delegate { };
}
},
initializer);
}
}
}
| using System;
using System.ComponentModel.Composition;
using System.Security;
using System.Threading.Tasks;
using Microsoft.VisualStudio.ComponentModelHost;
using VsPackage = Microsoft.VisualStudio.Shell.Package;
namespace NuGetConsole
{
[Export(typeof(IConsoleInitializer))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class ConsoleInitializer : IConsoleInitializer
{
private readonly Lazy<Task<Action>> _initializeTask = new Lazy<Task<Action>>(GetInitializeTask);
public Task<Action> Initialize()
{
return _initializeTask.Value;
}
private static Task<Action> GetInitializeTask()
{
var componentModel = (IComponentModel)VsPackage.GetGlobalService(typeof(SComponentModel));
if (componentModel == null)
{
throw new InvalidOperationException();
}
try
{
// HACK: Short cut to set the Powershell execution policy for this process to RemoteSigned.
// This is so that we can initialize the PowerShell host and load our modules successfully.
Environment.SetEnvironmentVariable(
"PSExecutionPolicyPreference", "RemoteSigned", EnvironmentVariableTarget.Process);
}
catch (SecurityException)
{
// ignore if user doesn't have permission to add process-level environment variable,
// which is very rare.
}
var initializer = componentModel.GetService<IHostInitializer>();
return Task.Factory.StartNew(() =>
{
initializer.Start();
return new Action(initializer.SetDefaultRunspace);
});
}
}
}
| apache-2.0 | C# |
f85a09203cac28e84f6d668f3fde94e96a5e0726 | Add 'in' | wvdd007/roslyn,eriawan/roslyn,mavasani/roslyn,AmadeusW/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,sharwell/roslyn,KevinRansom/roslyn,physhi/roslyn,dotnet/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,physhi/roslyn,wvdd007/roslyn,eriawan/roslyn,wvdd007/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,dotnet/roslyn,KevinRansom/roslyn,weltkante/roslyn,weltkante/roslyn,diryboy/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,physhi/roslyn | src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs | src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Globalization;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.PatternMatching
{
internal partial class PatternMatcher
{
private sealed partial class SimplePatternMatcher : PatternMatcher
{
private PatternSegment _fullPatternSegment;
public SimplePatternMatcher(
string pattern,
CultureInfo culture,
bool includeMatchedSpans,
bool allowFuzzyMatching)
: base(includeMatchedSpans, culture, allowFuzzyMatching)
{
pattern = pattern.Trim();
_fullPatternSegment = new PatternSegment(pattern, allowFuzzyMatching);
_invalidPattern = _fullPatternSegment.IsInvalid;
}
public override void Dispose()
{
base.Dispose();
_fullPatternSegment.Dispose();
}
/// <summary>
/// Determines if a given candidate string matches under a multiple word query text, as you
/// would find in features like Navigate To.
/// </summary>
/// <returns>If this was a match, a set of match types that occurred while matching the
/// patterns. If it was not a match, it returns null.</returns>
public override bool AddMatches(string candidate, ref TemporaryArray<PatternMatch> matches)
{
if (SkipMatch(candidate))
{
return false;
}
return MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: false) ||
MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: true);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Globalization;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.PatternMatching
{
internal partial class PatternMatcher
{
private sealed partial class SimplePatternMatcher : PatternMatcher
{
private PatternSegment _fullPatternSegment;
public SimplePatternMatcher(
string pattern,
CultureInfo culture,
bool includeMatchedSpans,
bool allowFuzzyMatching)
: base(includeMatchedSpans, culture, allowFuzzyMatching)
{
pattern = pattern.Trim();
_fullPatternSegment = new PatternSegment(pattern, allowFuzzyMatching);
_invalidPattern = _fullPatternSegment.IsInvalid;
}
public override void Dispose()
{
base.Dispose();
_fullPatternSegment.Dispose();
}
/// <summary>
/// Determines if a given candidate string matches under a multiple word query text, as you
/// would find in features like Navigate To.
/// </summary>
/// <returns>If this was a match, a set of match types that occurred while matching the
/// patterns. If it was not a match, it returns null.</returns>
public override bool AddMatches(string candidate, ref TemporaryArray<PatternMatch> matches)
{
if (SkipMatch(candidate))
{
return false;
}
return MatchPatternSegment(candidate, _fullPatternSegment, ref matches, fuzzyMatch: false) ||
MatchPatternSegment(candidate, _fullPatternSegment, ref matches, fuzzyMatch: true);
}
}
}
}
| mit | C# |
463b10fc66906632b3540cbfc112f134eee92b06 | Update TupleConstruction.cs | jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode | CSharp7/CSharp7/TupleConstruction.cs | CSharp7/CSharp7/TupleConstruction.cs | // Copyright 2016 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file.
#pragma warning disable CS0219 // Variable is assigned but its value is never used
using System;
namespace CSharp7
{
class TupleConstruction
{
static void Main()
{
var tuple1 = (1, 2);
Console.WriteLine(tuple1.Item1);
Console.WriteLine(tuple1.Item2);
var tuple2 = new ValueTuple<int, long>(1, 2);
Console.WriteLine(tuple2.Item1);
Console.WriteLine(tuple2.Item2);
var tuple3 = (a: 1, b: 2);
Console.WriteLine(tuple3.a);
Console.WriteLine(tuple3.b);
// Names specified by declaration
(long a, int b) tuple4 = (1, 2);
// No names in declaration, so names in construction are irrelevant
(int, int) tuple5 = (a: 1, b: 2);
}
}
}
| // Copyright 2016 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file.
#pragma warning disable CS0219 // Variable is assigned but its value is never used
using System;
namespace CSharp7
{
class TupleConstruction
{
static void Main()
{
var tuple1 = (1, 2);
Console.WriteLine(tuple1.Item1);
Console.WriteLine(tuple1.Item2);
var tuple2 = new ValueTuple<int, long>(1, 2);
Console.WriteLine(tuple2.Item1);
Console.WriteLine(tuple2.Item2);
var tuple3 = (a: 1, b: 2);
Console.WriteLine(tuple3.a);
Console.WriteLine(tuple3.b);
// Names specified by declaration
(long a, int b) tuple4 = (1, 2);
// No names in declaration, so names in construction are irrelevant
var tuple5 = (a: 1, b: 2);
}
}
}
| apache-2.0 | C# |
43ab2b916b5ba98e81cb5b75264faefb527ad301 | Fix for LZ4 not decompressing properly | aa2g/PPeX | PPeX/Compressors/Lz4Compressor.cs | PPeX/Compressors/Lz4Compressor.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PPeX.Compressors
{
public class Lz4Compressor : BaseCompressor
{
public override ArchiveChunkCompression Compression => ArchiveChunkCompression.LZ4;
protected bool highCompression;
public static int BlockSize = 4 * 1024 * 1024;
public Lz4Compressor(Stream stream, bool HighCompression) : base(stream, (uint)stream.Length)
{
highCompression = HighCompression;
}
public override uint CompressedSize { get; protected set; }
public override void WriteToStream(Stream stream)
{
long oldPos = stream.Position;
var flags = LZ4.LZ4StreamFlags.IsolateInnerStream;
if (highCompression)
flags |= LZ4.LZ4StreamFlags.HighCompression;
using (var lz4 = new LZ4.LZ4Stream(stream, LZ4.LZ4StreamMode.Compress, flags, BlockSize))
{
BaseStream.CopyTo(lz4);
lz4.Close();
}
CompressedSize = (uint)(stream.Position - oldPos);
}
}
public class Lz4Decompressor : IDecompressor
{
public ArchiveChunkCompression Compression => ArchiveChunkCompression.LZ4;
public Stream BaseStream { get; protected set; }
public Lz4Decompressor(Stream stream)
{
BaseStream = stream;
}
public Stream Decompress()
{
MemoryStream buffer = new MemoryStream();
using (var lz4 = new LZ4.LZ4Stream(BaseStream, LZ4.LZ4StreamMode.Decompress))
lz4.CopyTo(buffer);
buffer.Position = 0;
return buffer;
}
public void Dispose()
{
((IDisposable)BaseStream).Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PPeX.Compressors
{
public class Lz4Compressor : BaseCompressor
{
public override ArchiveChunkCompression Compression => ArchiveChunkCompression.LZ4;
protected bool highCompression;
public static int BlockSize = 4 * 1024 * 1024;
public Lz4Compressor(Stream stream, bool HighCompression) : base(stream, (uint)stream.Length)
{
highCompression = HighCompression;
}
public override uint CompressedSize { get; protected set; }
public override void WriteToStream(Stream stream)
{
long oldPos = stream.Position;
var flags = LZ4.LZ4StreamFlags.IsolateInnerStream;
if (highCompression)
flags |= LZ4.LZ4StreamFlags.HighCompression;
using (var lz4 = new LZ4.LZ4Stream(stream, LZ4.LZ4StreamMode.Compress, flags, BlockSize))
{
BaseStream.CopyTo(lz4);
lz4.Close();
}
CompressedSize = (uint)(stream.Position - oldPos);
}
}
public class Lz4Decompressor : IDecompressor
{
public ArchiveChunkCompression Compression => ArchiveChunkCompression.LZ4;
public Stream BaseStream { get; protected set; }
public Lz4Decompressor(Stream stream)
{
BaseStream = stream;
}
public Stream Decompress()
{
MemoryStream buffer = new MemoryStream();
using (var lz4 = new LZ4.LZ4Stream(BaseStream, LZ4.LZ4StreamMode.Decompress))
lz4.CopyTo(buffer);
return buffer;
}
public void Dispose()
{
((IDisposable)BaseStream).Dispose();
}
}
}
| mit | C# |
3403ce0f266fbe0cb0f84b085db5696785e58ec0 | Bump version to 15.0.1 | rlabrecque/Steamworks.NET,rlabrecque/Steamworks.NET,rlabrecque/Steamworks.NET,rlabrecque/Steamworks.NET | Plugins/Steamworks.NET/Version.cs | Plugins/Steamworks.NET/Version.cs | // This file is provided under The MIT License as part of Steamworks.NET.
// Copyright (c) 2013-2019 Riley Labrecque
// Please see the included LICENSE.txt for additional information.
// This file is automatically generated.
// Changes to this file will be reverted when you update Steamworks.NET
#if !(UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX || STEAMWORKS_WIN || STEAMWORKS_LIN_OSX)
#define DISABLESTEAMWORKS
#endif
#if !DISABLESTEAMWORKS
namespace Steamworks {
public static class Version {
public const string SteamworksNETVersion = "15.0.1";
public const string SteamworksSDKVersion = "1.51";
public const string SteamAPIDLLVersion = "06.28.18.86";
public const int SteamAPIDLLSize = 239904;
public const int SteamAPI64DLLSize = 265504;
}
}
#endif // !DISABLESTEAMWORKS
| // This file is provided under The MIT License as part of Steamworks.NET.
// Copyright (c) 2013-2019 Riley Labrecque
// Please see the included LICENSE.txt for additional information.
// This file is automatically generated.
// Changes to this file will be reverted when you update Steamworks.NET
#if !(UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX || STEAMWORKS_WIN || STEAMWORKS_LIN_OSX)
#define DISABLESTEAMWORKS
#endif
#if !DISABLESTEAMWORKS
namespace Steamworks {
public static class Version {
public const string SteamworksNETVersion = "15.0.0";
public const string SteamworksSDKVersion = "1.51";
public const string SteamAPIDLLVersion = "06.28.18.86";
public const int SteamAPIDLLSize = 239904;
public const int SteamAPI64DLLSize = 265504;
}
}
#endif // !DISABLESTEAMWORKS
| mit | C# |
4b5e57a4dcb6058077cc547940b874feceae8ea6 | Modify PropertyMetadata for correct overloading | emoacht/Monitorian | Source/Monitorian.Core/Views/Behaviors/FocusElementAction.cs | Source/Monitorian.Core/Views/Behaviors/FocusElementAction.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Xaml.Behaviors;
namespace Monitorian.Core.Views.Behaviors
{
public class FocusElementAction : TriggerAction<DependencyObject>
{
public UIElement TargetElement
{
get { return (UIElement)GetValue(TargetElementProperty); }
set { SetValue(TargetElementProperty, value); }
}
public static readonly DependencyProperty TargetElementProperty =
DependencyProperty.Register(
"TargetElement",
typeof(UIElement),
typeof(FocusElementAction),
new PropertyMetadata(default(UIElement)));
protected override void Invoke(object parameter)
{
if ((TargetElement is null) || !TargetElement.Focusable || TargetElement.IsFocused)
return;
TargetElement.Focus();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Xaml.Behaviors;
namespace Monitorian.Core.Views.Behaviors
{
public class FocusElementAction : TriggerAction<DependencyObject>
{
public UIElement TargetElement
{
get { return (UIElement)GetValue(TargetElementProperty); }
set { SetValue(TargetElementProperty, value); }
}
public static readonly DependencyProperty TargetElementProperty =
DependencyProperty.Register(
"TargetElement",
typeof(UIElement),
typeof(FocusElementAction),
new PropertyMetadata(null));
protected override void Invoke(object parameter)
{
if ((TargetElement is null) || !TargetElement.Focusable || TargetElement.IsFocused)
return;
TargetElement.Focus();
}
}
} | mit | C# |
da5d641a9ec7306de0f8147650dc8cac29366b62 | Disable UnityEvent workaround since it is broken in Full Inspector | jacobdufault/fullserializer,jacobdufault/fullserializer,jacobdufault/fullserializer | Assets/FullSerializer/Source/Converters/Unity/UnityEvent_Converter.cs | Assets/FullSerializer/Source/Converters/Unity/UnityEvent_Converter.cs | #if !NO_UNITY
using System;
using UnityEngine;
using UnityEngine.Events;
namespace FullSerializer {
partial class fsConverterRegistrar {
// Disable the converter for the time being. Unity's JsonUtility API cannot be called from
// within a C# ISerializationCallbackReceiver callback.
// public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter;
}
}
namespace FullSerializer.Internal.Converters {
// The standard FS reflection converter has started causing Unity to crash when processing
// UnityEvent. We can send the serialization through JsonUtility which appears to work correctly
// instead.
//
// We have to support legacy serialization formats so importing works as expected.
public class UnityEvent_Converter : fsConverter {
public override bool CanProcess(Type type) {
return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false;
}
public override bool RequestCycleSupport(Type storageType) {
return false;
}
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
Type objectType = (Type)instance;
fsResult result = fsResult.Success;
instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType);
return result;
}
public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
fsResult result = fsResult.Success;
serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance));
return result;
}
}
}
#endif | #if !NO_UNITY
using System;
using UnityEngine;
using UnityEngine.Events;
namespace FullSerializer {
partial class fsConverterRegistrar {
public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter;
}
}
namespace FullSerializer.Internal.Converters {
// The standard FS reflection converter has started causing Unity to crash when processing
// UnityEvent. We can send the serialization through JsonUtility which appears to work correctly
// instead.
//
// We have to support legacy serialization formats so importing works as expected.
public class UnityEvent_Converter : fsConverter {
public override bool CanProcess(Type type) {
return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false;
}
public override bool RequestCycleSupport(Type storageType) {
return false;
}
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
Type objectType = (Type)instance;
fsResult result = fsResult.Success;
instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType);
return result;
}
public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
fsResult result = fsResult.Success;
serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance));
return result;
}
}
}
#endif | mit | C# |
43972f5d20fe421f4e0a0e63c1c84dc20e726d80 | Add Parent field to EntityBase | grantcolley/authorisationmanager,grantcolley/authorisationmanager,grantcolley/authorisationmanager,grantcolley/authorisationmanager | UI/WPF/Model/EntityBase.cs | UI/WPF/Model/EntityBase.cs | using System.ComponentModel;
namespace DevelopmentInProgress.AuthorisationManager.WPF.Model
{
public abstract class EntityBase : INotifyPropertyChanged
{
private bool isVisible;
protected EntityBase()
{
IsVisible = true;
}
public event PropertyChangedEventHandler PropertyChanged;
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual string Code { get; set; }
public virtual string Description { get; set; }
public EntityBase Parent { get; set; }
public bool IsReadOnly { get; set; }
public bool IsVisible
{
get { return isVisible; }
set
{
if (isVisible != value)
{
isVisible = value;
OnPropertyChanged("IsVisible");
}
}
}
public bool CanModify
{
get { return !IsReadOnly; }
}
protected void OnPropertyChanged(string propertyName)
{
var propertyChangedHandler = PropertyChanged;
if (propertyChangedHandler != null)
{
propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| using System.ComponentModel;
namespace DevelopmentInProgress.AuthorisationManager.WPF.Model
{
public abstract class EntityBase : INotifyPropertyChanged
{
private bool isVisible;
protected EntityBase()
{
IsVisible = true;
}
public event PropertyChangedEventHandler PropertyChanged;
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual string Code { get; set; }
public virtual string Description { get; set; }
public bool IsReadOnly { get; set; }
public bool IsVisible
{
get { return isVisible; }
set
{
if (isVisible != value)
{
isVisible = value;
OnPropertyChanged("IsVisible");
}
}
}
public bool CanModify
{
get { return !IsReadOnly; }
}
protected void OnPropertyChanged(string propertyName)
{
var propertyChangedHandler = PropertyChanged;
if (propertyChangedHandler != null)
{
propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| apache-2.0 | C# |
f6c17a715f717808f81a32f3fb9730f4a42f0481 | Remove some unused methods from the Mac backend. | directhex/xwt,hamekoz/xwt,akrisiun/xwt,mono/xwt,residuum/xwt,iainx/xwt,cra0zy/xwt,mminns/xwt,steffenWi/xwt,sevoku/xwt,lytico/xwt,mminns/xwt,hwthomas/xwt,antmicro/xwt,TheBrainTech/xwt | Xwt.Mac/Xwt.Mac/WebViewBackend.cs | Xwt.Mac/Xwt.Mac/WebViewBackend.cs | //
// WebViewBackend.cs
//
// Author:
// Cody Russell <[email protected]>
//
// Copyright (c) 2014 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.WebKit;
using MonoMac.ObjCRuntime;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class WebViewBackend : ViewBackend<MonoMac.WebKit.WebView, IWebViewEventSink>, IWebViewBackend
{
public WebViewBackend ()
{
}
internal WebViewBackend (MacWebView macweb)
{
ViewObject = macweb;
}
#region IWebViewBackend implementation
public override void Initialize()
{
base.Initialize ();
ViewObject = new MacWebView ();
}
public string Url {
get { return Widget.MainFrameUrl; }
set {
Widget.MainFrameUrl = value;
}
}
#endregion
}
class MacWebView : MonoMac.WebKit.WebView, IViewObject
{
public ViewBackend Backend { get; set; }
public NSView View {
get { return this; }
}
}
}
| //
// WebViewBackend.cs
//
// Author:
// Cody Russell <[email protected]>
//
// Copyright (c) 2014 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.WebKit;
using MonoMac.ObjCRuntime;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class WebViewBackend : ViewBackend<MonoMac.WebKit.WebView, IWebViewEventSink>, IWebViewBackend
{
public WebViewBackend ()
{
}
internal WebViewBackend (MacWebView macweb)
{
ViewObject = macweb;
}
#region IWebViewBackend implementation
public override void Initialize()
{
base.Initialize ();
ViewObject = new MacWebView ();
}
public void EnableEvent (Xwt.Backends.WebViewEvent ev)
{
}
public void DisableEvent (Xwt.Backends.WebViewEvent ev)
{
}
public string Url {
get { return Widget.MainFrameUrl; }
set {
Widget.MainFrameUrl = value;
}
}
#endregion
}
class MacWebView : MonoMac.WebKit.WebView, IViewObject
{
public ViewBackend Backend { get; set; }
public NSView View {
get { return this; }
}
public void EnableEvent (Xwt.Backends.WebViewEvent ev)
{
}
public void DisableEvent (Xwt.Backends.WebViewEvent ev)
{
}
}
}
| mit | C# |
8b88c96cbfed2420c4a98be1cb7ec705e404d68c | Reset testing flag. | StevenThuriot/Nova,StevenThuriot/Nova | Nova/Library/ViewModel.Validation.cs | Nova/Library/ViewModel.Validation.cs | #region License
//
// Copyright 2013 Steven Thuriot
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using Nova.Validation;
namespace Nova.Library
{
public abstract partial class ViewModel<TView, TViewModel>
{
private bool _isValid = true;
private ReadOnlyErrorCollection _errorCollection;
/// <summary>
/// Gets the error collection.
/// </summary>
public ReadOnlyErrorCollection ErrorCollection
{
get { return _errorCollection; }
internal set
{
if (SetValue(ref _errorCollection, value))
{
IsValid = _errorCollection == null || _errorCollection.Count == 0;
}
}
}
/// <summary>
/// Gets a value indicating whether this instance is valid.
/// </summary>
/// <value>
/// <c>true</c> if this instance is valid; otherwise, <c>false</c>.
/// </value>
public bool IsValid
{
get { return _isValid; }
private set { SetValue(ref _isValid, value); }
}
}
}
| #region License
//
// Copyright 2013 Steven Thuriot
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using Nova.Validation;
namespace Nova.Library
{
public abstract partial class ViewModel<TView, TViewModel>
{
private bool _isValid = false;
private ReadOnlyErrorCollection _errorCollection;
/// <summary>
/// Gets the error collection.
/// </summary>
public ReadOnlyErrorCollection ErrorCollection
{
get { return _errorCollection; }
internal set
{
if (SetValue(ref _errorCollection, value))
{
IsValid = _errorCollection == null || _errorCollection.Count == 0;
}
}
}
/// <summary>
/// Gets a value indicating whether this instance is valid.
/// </summary>
/// <value>
/// <c>true</c> if this instance is valid; otherwise, <c>false</c>.
/// </value>
public bool IsValid
{
get { return _isValid; }
private set { SetValue(ref _isValid, value); }
}
}
}
| mit | C# |
e9b5f54128b8ced841062a40406a21946af888ec | Cover mapping fully for taiko mods | peppy/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new | osu.Game.Rulesets.Taiko.Tests/TaikoLegacyModConversionTest.cs | osu.Game.Rulesets.Taiko.Tests/TaikoLegacyModConversionTest.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 System;
using NUnit.Framework;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Taiko.Tests
{
[TestFixture]
public class TaikoLegacyModConversionTest : LegacyModConversionTest
{
private static readonly object[][] taiko_mod_mapping =
{
new object[] { LegacyMods.NoFail, new[] { typeof(TaikoModNoFail) } },
new object[] { LegacyMods.Easy, new[] { typeof(TaikoModEasy) } },
new object[] { LegacyMods.Hidden, new[] { typeof(TaikoModHidden) } },
new object[] { LegacyMods.HardRock, new[] { typeof(TaikoModHardRock) } },
new object[] { LegacyMods.SuddenDeath, new[] { typeof(TaikoModSuddenDeath) } },
new object[] { LegacyMods.DoubleTime, new[] { typeof(TaikoModDoubleTime) } },
new object[] { LegacyMods.Relax, new[] { typeof(TaikoModRelax) } },
new object[] { LegacyMods.HalfTime, new[] { typeof(TaikoModHalfTime) } },
new object[] { LegacyMods.Nightcore, new[] { typeof(TaikoModNightcore) } },
new object[] { LegacyMods.Flashlight, new[] { typeof(TaikoModFlashlight) } },
new object[] { LegacyMods.Autoplay, new[] { typeof(TaikoModAutoplay) } },
new object[] { LegacyMods.Perfect, new[] { typeof(TaikoModPerfect) } },
new object[] { LegacyMods.Random, new[] { typeof(TaikoModRandom) } },
new object[] { LegacyMods.Cinema, new[] { typeof(TaikoModCinema) } },
new object[] { LegacyMods.HardRock | LegacyMods.DoubleTime, new[] { typeof(TaikoModHardRock), typeof(TaikoModDoubleTime) } }
};
[TestCaseSource(nameof(taiko_mod_mapping))]
[TestCase(LegacyMods.Cinema | LegacyMods.Autoplay, new[] { typeof(TaikoModCinema) })]
[TestCase(LegacyMods.Nightcore | LegacyMods.DoubleTime, new[] { typeof(TaikoModNightcore) })]
[TestCase(LegacyMods.Perfect | LegacyMods.SuddenDeath, new[] { typeof(TaikoModPerfect) })]
public new void TestFromLegacy(LegacyMods legacyMods, Type[] expectedMods) => base.TestFromLegacy(legacyMods, expectedMods);
[TestCaseSource(nameof(taiko_mod_mapping))]
public new void TestToLegacy(LegacyMods legacyMods, Type[] givenMods) => base.TestToLegacy(legacyMods, givenMods);
protected override Ruleset CreateRuleset() => new TaikoRuleset();
}
}
| // 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 System;
using NUnit.Framework;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Taiko.Tests
{
[TestFixture]
public class TaikoLegacyModConversionTest : LegacyModConversionTest
{
[TestCase(LegacyMods.Easy, new[] { typeof(TaikoModEasy) })]
[TestCase(LegacyMods.HardRock | LegacyMods.DoubleTime, new[] { typeof(TaikoModHardRock), typeof(TaikoModDoubleTime) })]
[TestCase(LegacyMods.DoubleTime, new[] { typeof(TaikoModDoubleTime) })]
[TestCase(LegacyMods.Nightcore, new[] { typeof(TaikoModNightcore) })]
[TestCase(LegacyMods.Nightcore | LegacyMods.DoubleTime, new[] { typeof(TaikoModNightcore) })]
[TestCase(LegacyMods.Flashlight | LegacyMods.Nightcore | LegacyMods.DoubleTime, new[] { typeof(TaikoModFlashlight), typeof(TaikoModNightcore) })]
[TestCase(LegacyMods.Perfect, new[] { typeof(TaikoModPerfect) })]
[TestCase(LegacyMods.SuddenDeath, new[] { typeof(TaikoModSuddenDeath) })]
[TestCase(LegacyMods.Perfect | LegacyMods.SuddenDeath, new[] { typeof(TaikoModPerfect) })]
[TestCase(LegacyMods.Perfect | LegacyMods.SuddenDeath | LegacyMods.DoubleTime, new[] { typeof(TaikoModDoubleTime), typeof(TaikoModPerfect) })]
public new void TestFromLegacy(LegacyMods legacyMods, Type[] expectedMods) => base.TestFromLegacy(legacyMods, expectedMods);
protected override Ruleset CreateRuleset() => new TaikoRuleset();
}
}
| mit | C# |
6bc83afc5fab06bb424573246571f9395b0eb6d5 | Add xml comment | damianh/SqlStreamStore,damianh/Cedar.EventStore,SQLStreamStore/SQLStreamStore,SQLStreamStore/SQLStreamStore | src/SqlStreamStore.MsSql/CheckSchemaResult.cs | src/SqlStreamStore.MsSql/CheckSchemaResult.cs | namespace SqlStreamStore
{
/// <summary>
/// Represents the result of a schema check.
/// </summary>
public class CheckSchemaResult
{
/// <summary>
/// The version of the schema checked.
/// </summary>
public int CurrentVersion { get; }
/// <summary>
/// The expected version for this version of MsSqlStreamStore to be compatible with.
/// </summary>
public int ExpectedVersion { get; }
/// <summary>
/// Initializes a new instance of <see cref="CheckSchemaResult"/>
/// </summary>
/// <param name="currentVersion">The current version of the schema.</param>
/// <param name="expectedVersion">The expected version of the schema.</param>
public CheckSchemaResult(int currentVersion, int expectedVersion)
{
CurrentVersion = currentVersion;
ExpectedVersion = expectedVersion;
}
/// <summary>
/// Checks to see if the schema version matches.
/// </summary>
/// <returns>True if the version match, otherwise False.</returns>
public bool IsMatch()
{
return CurrentVersion == ExpectedVersion;
}
}
} | namespace SqlStreamStore
{
/// <summary>
/// Represents the result of a schema check.
/// </summary>
public class CheckSchemaResult
{
/// <summary>
/// The version of the schema checked.
/// </summary>
public int CurrentVersion { get; }
/// <summary>
/// The expected version for this version of MsSqlStreamStore to be compatible with.
/// </summary>
public int ExpectedVersion { get; }
public CheckSchemaResult(int currentVersion, int expectedVersion)
{
CurrentVersion = currentVersion;
ExpectedVersion = expectedVersion;
}
/// <summary>
/// Checks to see if the schema version matches.
/// </summary>
/// <returns>True if the version match, otherwise False.</returns>
public bool IsMatch()
{
return CurrentVersion == ExpectedVersion;
}
}
} | mit | C# |
6896a68f2c177e8c9d052bab2e15830c539b757b | Include first & last names for recipients | bcemmett/SurveyMonkeyApi-v3 | SurveyMonkey/Containers/Recipient.cs | SurveyMonkey/Containers/Recipient.cs | using System.Collections.Generic;
using Newtonsoft.Json;
using SurveyMonkey.Enums;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class Recipient : IPageableContainer
{
public long? Id { get; set; }
public long? SurveyId { get; set; }
internal string Href { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public RecipientSurveyResponseStatus? SurveyResponseStatus { get; set; }
public MessageStatus? MailStatus { get; set; }
public Dictionary<string, string> CustomFields { get; set; }
public string SurveyLink { get; set; }
public string RemoveLink { get; set; }
public Dictionary<string, string> ExtraFields { get; set; }
}
} | using System.Collections.Generic;
using Newtonsoft.Json;
using SurveyMonkey.Enums;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class Recipient : IPageableContainer
{
public long? Id { get; set; }
public long? SurveyId { get; set; }
internal string Href { get; set; }
public string Email { get; set; }
public RecipientSurveyResponseStatus? SurveyResponseStatus { get; set; }
public MessageStatus? MailStatus { get; set; }
public Dictionary<string, string> CustomFields { get; set; }
public string SurveyLink { get; set; }
public string RemoveLink { get; set; }
public Dictionary<string, string> ExtraFields { get; set; }
}
} | mit | C# |
e35c7e8bbaee0582330d4534312fcf7f14e58bc0 | Update TMDbClientTrending.cs | LordMike/TMDbLib | TMDbLib/Client/TMDbClientTrending.cs | TMDbLib/Client/TMDbClientTrending.cs | using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.Trending;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<SearchContainer<SearchMovie>> GetTrendingMoviesAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/movie/{time_window}");
req.AddUrlSegment("time_window", timeWindow.GetDescription());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchMovie> resp = await req.GetOfT<SearchContainer<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchTv>> GetTrendingTvAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/tv/{time_window}");
req.AddUrlSegment("time_window", timeWindow.GetDescription());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchTv> resp = await req.GetOfT<SearchContainer<SearchTv>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchPerson>> GetTrendingPeopleAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/person/{time_window}");
req.AddUrlSegment("time_window", timeWindow.GetDescription());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchPerson> resp = await req.GetOfT<SearchContainer<SearchPerson>>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}
| using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.Trending;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<SearchContainer<SearchMovie>> GetTrendingMoviesAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/movie/{time_window}");
req.AddUrlSegment("time_window", timeWindow.ToString().ToLower());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchMovie> resp = await req.GetOfT<SearchContainer<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchTv>> GetTrendingTvAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/tv/{time_window}");
req.AddUrlSegment("time_window", timeWindow.ToString());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchTv> resp = await req.GetOfT<SearchContainer<SearchTv>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchPerson>> GetTrendingPeopleAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/person/{time_window}");
req.AddUrlSegment("time_window", timeWindow.ToString());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchPerson> resp = await req.GetOfT<SearchContainer<SearchPerson>>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}
| mit | C# |
5c1f87a719d3c06d0bef766bc57be3ffe03a6b13 | Make brstm instead of dsp. Encode adpcm channels in parallel | Thealexbarney/VGAudio,Thealexbarney/VGAudio,Thealexbarney/LibDspAdpcm,Thealexbarney/LibDspAdpcm | DspAdpcm/DspAdpcm.Cli/DspAdpcmCli.cs | DspAdpcm/DspAdpcm.Cli/DspAdpcmCli.cs | using System;
using System.Diagnostics;
using System.IO;
using DspAdpcm.Encode.Adpcm;
using DspAdpcm.Encode.Adpcm.Formats;
using DspAdpcm.Encode.Pcm;
using DspAdpcm.Encode.Pcm.Formats;
namespace DspAdpcm.Cli
{
public static class DspAdpcmCli
{
public static int Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: dspadpcm <wavIn> <brstmOut>\n");
return 0;
}
IPcmStream wave;
try
{
using (var file = new FileStream(args[0], FileMode.Open))
{
wave = new Wave(file).AudioStream;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return -1;
}
Stopwatch watch = new Stopwatch();
watch.Start();
IAdpcmStream adpcm = Encode.Adpcm.Encode.PcmToAdpcmParallel(wave);
watch.Stop();
Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n");
Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}");
Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per milisecond.");
var brstm = new Brstm(adpcm);
using (var stream = File.Open(args[1], FileMode.Create))
foreach (var b in brstm.GetFile())
stream.WriteByte(b);
return 0;
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using DspAdpcm.Encode.Adpcm;
using DspAdpcm.Encode.Adpcm.Formats;
using DspAdpcm.Encode.Pcm;
using DspAdpcm.Encode.Pcm.Formats;
namespace DspAdpcm.Cli
{
public static class DspAdpcmCli
{
public static int Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: dspenc <wavin> <dspout>\n");
return 0;
}
IPcmStream wave;
try
{
using (var file = new FileStream(args[0], FileMode.Open))
{
wave = new Wave(file).AudioStream;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return -1;
}
Stopwatch watch = new Stopwatch();
watch.Start();
IAdpcmStream adpcm = Encode.Adpcm.Encode.PcmToAdpcm(wave);
watch.Stop();
Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n");
Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}");
Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per milisecond.");
var dsp = new Dsp(adpcm);
using (var stream = File.Open(args[1], FileMode.Create))
foreach (var b in dsp.GetFile())
stream.WriteByte(b);
return 0;
}
}
}
| mit | C# |
d61d002677f9c7715936142bd024ffb08c9437bf | Remove useless instance of JsonSerializerSettings | dgarage/NBXplorer,dgarage/NBXplorer | NBXplorer.Client/NBXplorerNetwork.cs | NBXplorer.Client/NBXplorerNetwork.cs | using NBitcoin;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace NBXplorer
{
public class NBXplorerNetwork
{
public NBXplorerNetwork(INetworkSet networkSet, NBitcoin.NetworkType networkType)
{
NBitcoinNetwork = networkSet.GetNetwork(networkType);
CryptoCode = networkSet.CryptoCode;
DefaultSettings = NBXplorerDefaultSettings.GetDefaultSettings(networkType);
}
public Network NBitcoinNetwork
{
get;
private set;
}
public int MinRPCVersion
{
get;
internal set;
}
public string CryptoCode
{
get;
private set;
}
public NBXplorerDefaultSettings DefaultSettings
{
get;
private set;
}
public DerivationStrategy.DerivationStrategyFactory DerivationStrategyFactory
{
get;
internal set;
}
public bool SupportCookieAuthentication
{
get;
internal set;
} = true;
private Serializer _Serializer;
public Serializer Serializer
{
get
{
_Serializer = _Serializer ?? new Serializer(NBitcoinNetwork);
return _Serializer;
}
}
public JsonSerializerSettings JsonSerializerSettings
{
get
{
return Serializer.Settings;
}
}
public TimeSpan ChainLoadingTimeout
{
get;
set;
} = TimeSpan.FromMinutes(15);
/// <summary>
/// Minimum blocks to keep if pruning is activated
/// </summary>
public int MinBlocksToKeep
{
get; set;
} = 288;
public override string ToString()
{
return CryptoCode.ToString();
}
}
}
| using NBitcoin;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace NBXplorer
{
public class NBXplorerNetwork
{
public NBXplorerNetwork(INetworkSet networkSet, NBitcoin.NetworkType networkType)
{
NBitcoinNetwork = networkSet.GetNetwork(networkType);
CryptoCode = networkSet.CryptoCode;
DefaultSettings = NBXplorerDefaultSettings.GetDefaultSettings(networkType);
}
public Network NBitcoinNetwork
{
get;
private set;
}
public int MinRPCVersion
{
get;
internal set;
}
public string CryptoCode
{
get;
private set;
}
public NBXplorerDefaultSettings DefaultSettings
{
get;
private set;
}
public DerivationStrategy.DerivationStrategyFactory DerivationStrategyFactory
{
get;
internal set;
}
public bool SupportCookieAuthentication
{
get;
internal set;
} = true;
private Serializer _Serializer;
public Serializer Serializer
{
get
{
_Serializer = _Serializer ?? new Serializer(NBitcoinNetwork);
return _Serializer;
}
}
private JsonSerializerSettings _JsonSerializerSettings;
public JsonSerializerSettings JsonSerializerSettings
{
get
{
if (_JsonSerializerSettings == null)
{
var json = new JsonSerializerSettings();
Serializer.ConfigureSerializer(json);
_JsonSerializerSettings = json;
}
return _JsonSerializerSettings;
}
}
public TimeSpan ChainLoadingTimeout
{
get;
set;
} = TimeSpan.FromMinutes(15);
/// <summary>
/// Minimum blocks to keep if pruning is activated
/// </summary>
public int MinBlocksToKeep
{
get; set;
} = 288;
public override string ToString()
{
return CryptoCode.ToString();
}
}
}
| mit | C# |
ecd08e31a09543317e4a71220b4d45cb61beccef | Fix Key Converter | Valetude/Valetude.Rollbar | Rollbar.Net/ArbitraryKeyConverter.cs | Rollbar.Net/ArbitraryKeyConverter.cs | using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Rollbar {
public class ArbitraryKeyConverter : JsonConverter<HasArbitraryKeys> {
public override void WriteJson(JsonWriter writer, HasArbitraryKeys value, JsonSerializer serializer) {
JObject.FromObject(value.Denormalize(), serializer).WriteTo(writer);
}
public override HasArbitraryKeys ReadJson(JsonReader reader, HasArbitraryKeys existingValue, JsonSerializer serializer) {
IDictionary<string, JToken> obj = JObject.Load(reader);
existingValue.WithKeys(obj.ToDictionary(x => x.Key, x => x.Value as object));
existingValue.Normalize();
return existingValue;
}
}
} | using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Rollbar {
public class ArbitraryKeyConverter : JsonConverter<HasArbitraryKeys> {
public override void WriteJson(JsonWriter writer, HasArbitraryKeys value, JsonSerializer serializer) {
writer.WriteValue(value.Denormalize());
}
public override HasArbitraryKeys ReadJson(JsonReader reader, HasArbitraryKeys existingValue, JsonSerializer serializer) {
IDictionary<string, JToken> obj = JObject.Load(reader);
existingValue.WithKeys(obj.ToDictionary(x => x.Key, x => x.Value as object));
existingValue.Normalize();
return existingValue;
}
}
} | mit | C# |
0f2609c93aaad591d73db99acc7e7957c5051bd8 | update homecontroller sitemap tags | MarkPieszak/aspnetcore-angular2-universal,MarkPieszak/aspnetcore-angular2-universal,MarkPieszak/aspnetcore-angular2-universal,MarkPieszak/aspnetcore-angular2-universal | Server/Controllers/HomeController.cs | Server/Controllers/HomeController.cs | using Asp2017.Server.Helpers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.Prerendering;
using Microsoft.AspNetCore.NodeServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http;
using System.Diagnostics;
using System;
using Asp2017.Server.Models;
namespace AspCoreServer.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public async Task<IActionResult> Index()
{
var prerenderResult = await Request.BuildPrerender();
ViewData["SpaHtml"] = prerenderResult.Html; // our <app-root /> from Angular
ViewData["Title"] = prerenderResult.Globals["title"]; // set our <title> from Angular
ViewData["Styles"] = prerenderResult.Globals["styles"]; // put styles in the correct place
ViewData["Scripts"] = prerenderResult.Globals["scripts"]; // scripts (that were in our header)
ViewData["Meta"] = prerenderResult.Globals["meta"]; // set our <meta> SEO tags
ViewData["Links"] = prerenderResult.Globals["links"]; // set our <link rel="canonical"> etc SEO tags
ViewData["TransferData"] = prerenderResult.Globals["transferData"]; // our transfer data set to window.TRANSFER_CACHE = {};
return View();
}
[HttpGet]
[Route("sitemap.xml")]
public async Task<IActionResult> SitemapXml()
{
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
xml += "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
xml += "<url>";
xml += "<loc>http://localhost:4251/home</loc>";
xml += "<lastmod>" + DateTime.Now.ToString("yyyy-MM-dd") + "</lastmod>";
xml += "</url>";
xml += "<url>";
xml += "<loc>http://localhost:4251/counter</loc>";
xml += "<lastmod>" + DateTime.Now.ToString("yyyy-MM-dd") + "</lastmod>";
xml += "</url>";
xml += "</urlset>";
return Content(xml, "text/xml");
}
public IActionResult Error()
{
return View();
}
}
}
| using Asp2017.Server.Helpers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.Prerendering;
using Microsoft.AspNetCore.NodeServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http;
using System.Diagnostics;
using System;
using Asp2017.Server.Models;
namespace AspCoreServer.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public async Task<IActionResult> Index()
{
var prerenderResult = await Request.BuildPrerender();
ViewData["SpaHtml"] = prerenderResult.Html; // our <app-root /> from Angular
ViewData["Title"] = prerenderResult.Globals["title"]; // set our <title> from Angular
ViewData["Styles"] = prerenderResult.Globals["styles"]; // put styles in the correct place
ViewData["Scripts"] = prerenderResult.Globals["scripts"]; // scripts (that were in our header)
ViewData["Meta"] = prerenderResult.Globals["meta"]; // set our <meta> SEO tags
ViewData["Links"] = prerenderResult.Globals["links"]; // set our <link rel="canonical"> etc SEO tags
ViewData["TransferData"] = prerenderResult.Globals["transferData"]; // our transfer data set to window.TRANSFER_CACHE = {};
return View();
}
[HttpGet]
[Route("sitemap.xml")]
public async Task<IActionResult> SitemapXml()
{
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
xml += "<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
xml += "<sitemap>";
xml += "<loc>http://localhost:4251/home</loc>";
xml += "<lastmod>" + DateTime.Now.ToString("yyyy-MM-dd") + "</lastmod>";
xml += "</sitemap>";
xml += "<sitemap>";
xml += "<loc>http://localhost:4251/counter</loc>";
xml += "<lastmod>" + DateTime.Now.ToString("yyyy-MM-dd") + "</lastmod>";
xml += "</sitemap>";
xml += "</sitemapindex>";
return Content(xml, "text/xml");
}
public IActionResult Error()
{
return View();
}
}
}
| mit | C# |
134287325a4df9982a39e07c19f1b940cd593f3e | Update Token API for JWT login | dhawalharsora/connectedcare-sdk,SnapMD/connectedcare-sdk | SnapMD.ConnectedCare.Sdk/TokenApi.cs | SnapMD.ConnectedCare.Sdk/TokenApi.cs | // Copyright 2015 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Linq;
using SnapMD.ConnectedCare.Sdk.Models;
using Newtonsoft.Json.Linq;
namespace SnapMD.ConnectedCare.Sdk
{
public class TokenApi : ApiCall
{
public TokenApi(string baseUrl, int? hospitalId, string developerId, string apiKey, Interfaces.IWebClient webClient)
: base(baseUrl, webClient, developerId: developerId, apiKey: apiKey)
{
HospitalId = hospitalId;
}
public int? HospitalId { get; private set; }
public string GetToken(string email, string secret)
{
//done V2ing
var request = new
{
email,
password = secret,
hospitalId = HospitalId,
userTypeId = 1
};
var response = Post("v2/account/token", request);
var dataEnumerator = response.ToObject<ApiResponseV2<SerializableToken>>();
if (dataEnumerator.Data != null)
{
foreach (var entry in dataEnumerator.Data)
{
return entry.access_token;
}
}
return null;
}
public string GetToken(string jwt)
{
var response = MakeCall<ApiResponseV2<SerializableToken>>("v2/account/token?jwt=" + jwt);
if (response.Data != null)
{
return response.Data.Select(entry => entry.access_token).FirstOrDefault();
}
return null;
}
}
} | // Copyright 2015 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using SnapMD.ConnectedCare.Sdk.Models;
using Newtonsoft.Json.Linq;
namespace SnapMD.ConnectedCare.Sdk
{
public class TokenApi : ApiCall
{
public TokenApi(string baseUrl, int hospitalId, string developerId, string apiKey, Interfaces.IWebClient webClient)
: base(baseUrl, webClient, developerId: developerId, apiKey: apiKey)
{
HospitalId = hospitalId;
}
public int HospitalId { get; private set; }
public string GetToken(string email, string secret)
{
//done V2ing
var request = new
{
email,
password = secret,
hospitalId = HospitalId,
userTypeId = 1
};
var response = Post("v2/account/token", request);
var dataEnumerator = response.ToObject<ApiResponseV2<SerializableToken>>();
if (dataEnumerator.Data != null)
{
foreach (var entry in dataEnumerator.Data)
{
return entry.access_token;
}
}
return null;
}
}
} | apache-2.0 | C# |
2ba22ea4d5535547197b576004eb1e5c52f043d7 | Add data narrowing check | caronyan/CSharpRecipe | CSharpRecipe/Recipe.DataType/DataTypeExtMethods.cs | CSharpRecipe/Recipe.DataType/DataTypeExtMethods.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Recipe.DataType
{
static class DataTypeExtMethods
{
public static string Base64EncodeBytes(this byte[] inputBytes) => (Convert.ToBase64String(inputBytes));
public static byte[] Base64DecodeString(this string inputStr) => (Convert.FromBase64String(inputStr));
public static int AddNarrowingChecked(this long lhs, long rhs) => checked ((int) (lhs + rhs));
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Recipe.DataType
{
static class DataTypeExtMethods
{
public static string Base64EncodeBytes(this byte[] inputBytes) => (Convert.ToBase64String(inputBytes));
public static byte[] Base64DecodeString(this string inputStr) => (Convert.FromBase64String(inputStr));
}
}
| mit | C# |
a95950fc29e844c6fcc07a17e838db3822975f88 | Fix logic bug in RiakObjectIdConverter | rob-somerville/riak-dotnet-client,basho/riak-dotnet-client,rob-somerville/riak-dotnet-client,basho/riak-dotnet-client | CorrugatedIron/Converters/RiakObjectIdConverter.cs | CorrugatedIron/Converters/RiakObjectIdConverter.cs | // Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// 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 CorrugatedIron.Models;
using Newtonsoft.Json;
using System;
namespace CorrugatedIron.Converters
{
public class RiakObjectIdConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
{
var pos = 0;
var objectIdParts = new string[2];
while(reader.Read())
{
if(pos < 2 && (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.PropertyName))
{
objectIdParts[pos] = reader.Value.ToString();
pos++;
}
}
return new RiakObjectId(objectIdParts);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead
{
get { return true; }
}
public override bool CanConvert(Type objectType)
{
return true;
}
}
} | // Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// 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 CorrugatedIron.Models;
using Newtonsoft.Json;
using System;
namespace CorrugatedIron.Converters
{
public class RiakObjectIdConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
{
var pos = 0;
var objectIdParts = new string[2];
while(reader.Read())
{
if(pos < 2 && reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.PropertyName)
{
objectIdParts[pos] = reader.Value.ToString();
pos++;
}
}
return new RiakObjectId(objectIdParts);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead
{
get { return true; }
}
public override bool CanConvert(Type objectType)
{
return true;
}
}
} | apache-2.0 | C# |
0287eac031d9a9911dfe9675a17b9ace458e7764 | Update ISerializer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/ISerializer.cs | TIKSN.Core/Serialization/ISerializer.cs | namespace TIKSN.Serialization
{
/// <summary>
/// Serializer interface
/// </summary>
/// <typeparam name="TSerial">Type to serialize to, usually string or byte array</typeparam>
public interface ISerializer<TSerial> where TSerial : class
{
/// <summary>
/// Serialize to <typeparamref name="TSerial" /> type
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
TSerial Serialize<T>(T obj);
}
}
| namespace TIKSN.Serialization
{
/// <summary>
/// Serializer interface
/// </summary>
/// <typeparam name="TSerial">Type to serialize to, usually string or byte array</typeparam>
public interface ISerializer<TSerial> where TSerial : class
{
/// <summary>
/// Serialize to <typeparamref name="TSerial"/> type
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
TSerial Serialize<T>(T obj);
}
} | mit | C# |
fba13099294a54ceb1bfba6569afa0549adeb355 | Fix NoAccessToProjectView | joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net | Joinrpg/Views/Shared/ErrorNoAccessToProject.cshtml | Joinrpg/Views/Shared/ErrorNoAccessToProject.cshtml | @model JoinRpg.Web.Models.ErrorNoAccessToProjectViewModel
@{
ViewBag.Title = "Нет доступа к проекту " + Model.ProjectName;
}
<h2>@ViewBag.Title</h2>
<p>У вас нет доступа к проекту @Html.ActionLink(Model.ProjectName, "Index", "Game", new {Model.ProjectId}, null).
Обратитесь к @(new MvcHtmlString(string.Join(", ", Model.CanGrantAccess.Select(user => Html.DisplayFor(u => user))))), чтобы получить доступ
</p>
| @model JoinRpg.Web.Models.ErrorNoAccessToProjectViewModel
@{
ViewBag.Title = "Нет доступа к проекту " + Model.ProjectName;
}
<h2>@ViewBag.Title</h2>
<p>У вас нет доступа к проекту @Html.ActionLink(Model.ProjectName, "Index", "Game", new {Model.ProjectId}, null).
Обратитесь к @string.Join(", ", Model.CanGrantAccess.Select(user => string.Format("<a href=\"mailto: {0}\">{1}</a>", user.Email, user.DisplayName))), чтобы получить доступ
</p>
| mit | C# |
9bee168065f13a3c393c0a7a6ed6f156e2f73c87 | Update AssemblyInfo.cs | ovatsus/Apps,ovatsus/Apps | UKTrains.WP8/Properties/AssemblyInfo.cs | UKTrains.WP8/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UKTrains.WP8")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UKTrains.WP8")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("70bdbb9e-1f06-4d61-bedc-4979bf01c0b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UKTrains.WP8")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UKTrains.WP8")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("70bdbb9e-1f06-4d61-bedc-4979bf01c0b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| apache-2.0 | C# |
78e033f0877f90e24506aaefe72a5037aafce33f | Fix object lifetime | stofte/linq-editor,stofte/ream-editor,stofte/ream-editor,stofte/ream-editor,stofte/ream-editor | LinqEditor.Core.Backend/Isolated/AppDomainProxy.cs | LinqEditor.Core.Backend/Isolated/AppDomainProxy.cs | using IQToolkit.Data;
using LinqEditor.Core.CodeAnalysis.Injected;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace LinqEditor.Core.Backend.Isolated
{
public class AppDomainProxy : MarshalByRefObject
{
private Assembly _schema;
private string _dbType;
private string _connectionString;
public void Initialize(string schemaAssemblyPath, string connectionString)
{
_schema = Assembly.LoadFile(schemaAssemblyPath);
_dbType = string.Format("{0}.DatabaseWithAttributes", _schema.GetTypes()[0].Namespace);
_connectionString = connectionString;
}
public IEnumerable<DataTable> Execute(byte[] assembly)
{
var assm = Assembly.Load(assembly);
return Execute(assm);
}
public IEnumerable<DataTable> Execute(string queryAssemblyPath)
{
var assm = Assembly.LoadFile(queryAssemblyPath);
return Execute(assm);
}
private IEnumerable<DataTable> Execute(Assembly assm)
{
var queryType = assm.GetType(string.Format("{0}.Program", assm.GetTypes()[0].Namespace));
var instance = Activator.CreateInstance(queryType) as IDynamicQuery;
var provider = DbEntityProvider.From("IQToolkit.Data.SqlClient", _connectionString, _dbType);
provider.Connection.Open();
var dumps = instance.Execute(provider);
provider.Connection.Close();
return dumps;
}
// http://blogs.microsoft.co.il/sasha/2008/07/19/appdomains-and-remoting-life-time-service/
public override object InitializeLifetimeService()
{
return null;
}
}
}
| using IQToolkit.Data;
using LinqEditor.Core.CodeAnalysis.Injected;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace LinqEditor.Core.Backend.Isolated
{
public class AppDomainProxy : MarshalByRefObject
{
private Assembly _schema;
private string _dbType;
private string _connectionString;
public void Initialize(string schemaAssemblyPath, string connectionString)
{
_schema = Assembly.LoadFile(schemaAssemblyPath);
_dbType = string.Format("{0}.DatabaseWithAttributes", _schema.GetTypes()[0].Namespace);
_connectionString = connectionString;
}
public IEnumerable<DataTable> Execute(byte[] assembly)
{
var assm = Assembly.Load(assembly);
return Execute(assm);
}
public IEnumerable<DataTable> Execute(string queryAssemblyPath)
{
var assm = Assembly.LoadFile(queryAssemblyPath);
return Execute(assm);
}
private IEnumerable<DataTable> Execute(Assembly assm)
{
var queryType = assm.GetType(string.Format("{0}.Program", assm.GetTypes()[0].Namespace));
var instance = Activator.CreateInstance(queryType) as IDynamicQuery;
var provider = DbEntityProvider.From("IQToolkit.Data.SqlClient", _connectionString, _dbType);
provider.Connection.Open();
var dumps = instance.Execute(provider);
provider.Connection.Close();
return dumps;
}
}
}
| mit | C# |
116050ef9f07ef8654e8cd996be88fba36c2749c | Fix visibility | steakpinball/WWWNetworking | WWWNetworking/FormProgressRequest.cs | WWWNetworking/FormProgressRequest.cs | using System;
using System.Collections;
using UnityEngine;
namespace WWWNetworking
{
/// <summary>
/// Request which requires an upload.
/// </summary>
public class FormProgressRequest : FormRequest
{
/// <summary>
/// Upload progress callback.
/// </summary>
/// <value>Callback</value>
Action<float> m_UploadProgress { get; set; }
/// <summary>
/// Download progress callback.
/// </summary>
/// <value>Callback</value>
Action<float> m_DownloadProgress { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="T:WWWNetworking.FormProgressRequest"/> class.
/// </summary>
/// <param name="url">URL for request</param>
/// <param name="form">Form data</param>
/// <param name="uploadProgress">Upload progress callback</param>
/// <param name="downloadProgress">Download progress callback</param>
/// <param name="success">Success callback</param>
/// <param name="error">Error callback</param>
public FormProgressRequest(string url, WWWForm form, Action<float> uploadProgress, Action<float> downloadProgress, Action<WWW> success, Action<string> error) : base(url, form, success, error)
{
m_UploadProgress = uploadProgress;
m_DownloadProgress = downloadProgress;
}
/// <summary>
/// Invokes the upload progress callback.
/// </summary>
/// <param name="progress">Progress as a percentage from 0 to 1</param>
protected void OnUploadProgress(float progress)
{
m_UploadProgress?.Invoke(progress);
}
/// <summary>
/// Invokes the download progress delegate.
/// </summary>
/// <param name="progress">Progress as a percentage from 0 to 1</param>
protected void OnDownloadProgress(float progress)
{
m_DownloadProgress?.Invoke(progress);
}
#region Overrides
/// <summary>
/// Runs the request.
/// </summary>
/// <returns>Enumerator for coroutine</returns>
public override IEnumerator RunRequest()
{
using (var www = new WWW(Url, Form))
{
while (!www.isDone && www.uploadProgress < 1)
{
OnUploadProgress(www.uploadProgress);
yield return null;
}
OnUploadProgress(www.uploadProgress);
while (!www.isDone)
{
OnDownloadProgress(www.progress);
yield return null;
}
OnDownloadProgress(www.progress);
CheckErrorOrSuccess(www);
}
}
#endregion
}
}
| using System;
using System.Collections;
using UnityEngine;
namespace WWWNetworking
{
/// <summary>
/// Request which requires an upload.
/// </summary>
public class FormProgressRequest : FormRequest
{
/// <summary>
/// Upload progress callback.
/// </summary>
/// <value>Callback</value>
Action<float> m_UploadProgress { get; set; }
/// <summary>
/// Download progress callback.
/// </summary>
/// <value>Callback</value>
Action<float> m_DownloadProgress { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="T:WWWNetworking.FormProgressRequest"/> class.
/// </summary>
/// <param name="url">URL for request</param>
/// <param name="form">Form data</param>
/// <param name="uploadProgress">Upload progress callback</param>
/// <param name="downloadProgress">Download progress callback</param>
/// <param name="success">Success callback</param>
/// <param name="error">Error callback</param>
public FormProgressRequest(string url, WWWForm form, Action<float> uploadProgress, Action<float> downloadProgress, Action<WWW> success, Action<string> error) : base(url, form, success, error)
{
m_UploadProgress = uploadProgress;
m_DownloadProgress = downloadProgress;
}
/// <summary>
/// Invokes the upload progress callback.
/// </summary>
/// <param name="progress">Progress as a percentage from 0 to 1</param>
protected void OnUploadProgress(float progress)
{
m_UploadProgress?.Invoke(progress);
}
/// <summary>
/// Invokes the download progress delegate.
/// </summary>
/// <param name="progress">Progress as a percentage from 0 to 1</param>
protected void OnDownloadProgress(float progress)
{
m_DownloadProgress?.Invoke(progress);
}
#region Overrides
/// <summary>
/// Runs the request.
/// </summary>
/// <returns>Enumerator for coroutine</returns>
public override IEnumerator RunRequest()
{
using (var www = new WWW(Url, Form))
{
while (!www.isDone && www.uploadProgress < 1)
{
OnUploadProgress(www.uploadProgress);
yield return null;
}
OnUploadProgress(www.uploadProgress);
while (!www.isDone)
{
OnDownloadProgress(www.progress);
yield return null;
}
OnDownloadProgress(www.progress);
CheckErrorOrSuccess(www);
}
}
#endregion
}
}
| mit | C# |
8d085fc05c912f7695846460d903c055323a7c36 | Replace Blockstream.info clearnet links to .onion | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Backend/WebsiteTorifier.cs | WalletWasabi.Backend/WebsiteTorifier.cs | using NBitcoin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace WalletWasabi.Backend
{
public class WebsiteTorifier
{
public string RootFolder { get; }
public string UnversionedFolder { get; }
public WebsiteTorifier(string rootFolder)
{
RootFolder = rootFolder;
UnversionedFolder = Path.GetFullPath(Path.Combine(RootFolder, "unversioned"));
}
public void CloneAndUpdateOnionIndexHtml()
{
var path = Path.Combine(RootFolder, "index.html");
var onionPath = Path.Combine(RootFolder, "onion-index.html");
var content = File.ReadAllText(path);
content = content.Replace("http://wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion", "https://wasabiwallet.io", StringComparison.Ordinal);
content = content.Replace("https://blockstream.info/tx/e4a789d16a24a6643dfee06e018ad27648b896daae6a3577ae0f4eddcc4d9174", "http://explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion/tx/e4a789d16a24a6643dfee06e018ad27648b896daae6a3577ae0f4eddcc4d9174", StringComparison.Ordinal);
content = content.Replace("https://blockstream.info/tx/c69aed505ca50473e2883130221915689c1474be3c66bcf7ac7dc0e26246afc8", "http://explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion/tx/c69aed505ca50473e2883130221915689c1474be3c66bcf7ac7dc0e26246afc8", StringComparison.Ordinal);
content = content.Replace("https://blockstream.info/tx/ef329b3ed8e790f10f0b522346f1b3d9f1c9d45dfa5b918e92d6f0a25d91c7ce", "http://explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion/tx/ef329b3ed8e790f10f0b522346f1b3d9f1c9d45dfa5b918e92d6f0a25d91c7ce", StringComparison.Ordinal);
content = content.Replace("https://blockstream.info/tx/f82206145413db5c1272d5609c88581c414815e36e400aee6410e0de9a2d46b5", "http://explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion/tx/f82206145413db5c1272d5609c88581c414815e36e400aee6410e0de9a2d46b5", StringComparison.Ordinal);
content = content.Replace("https://blockstream.info/tx/a7157780b7c696ab24767113d9d34cdbc0eba5c394c89aec4ed1a9feb326bea5", "http://explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion/tx/a7157780b7c696ab24767113d9d34cdbc0eba5c394c89aec4ed1a9feb326bea5", StringComparison.Ordinal);
File.WriteAllText(onionPath, content);
}
}
}
| using NBitcoin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace WalletWasabi.Backend
{
public class WebsiteTorifier
{
public string RootFolder { get; }
public string UnversionedFolder { get; }
public WebsiteTorifier(string rootFolder)
{
RootFolder = rootFolder;
UnversionedFolder = Path.GetFullPath(Path.Combine(RootFolder, "unversioned"));
}
public void CloneAndUpdateOnionIndexHtml()
{
var path = Path.Combine(RootFolder, "index.html");
var onionPath = Path.Combine(RootFolder, "onion-index.html");
var content = File.ReadAllText(path);
content = content.Replace("http://wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion", "https://wasabiwallet.io", StringComparison.Ordinal);
File.WriteAllText(onionPath, content);
}
}
}
| mit | C# |
9800db59d45b7fb5cbc1d5d5ec0840c352bd841f | Remove unnecessary using | DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,default0/osu-framework,default0/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,naoey/osu-framework,Tom94/osu-framework,naoey/osu-framework,paparony03/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,paparony03/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,peppy/osu-framework | osu.Framework/Graphics/Containers/IContainer.cs | osu.Framework/Graphics/Containers/IContainer.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;
using System.Collections.Generic;
using OpenTK;
namespace osu.Framework.Graphics.Containers
{
public interface IContainer : IDrawable
{
Vector2 ChildSize { get; }
Vector2 ChildOffset { get; }
Vector2 RelativeToAbsoluteFactor { get; }
Vector2 RelativeChildOffset { get; }
EdgeEffectParameters EdgeEffect { get; set; }
float CornerRadius { get; }
void InvalidateFromChild(Invalidation invalidation);
void Clear(bool dispose = true);
Axes AutoSizeAxes { get; set; }
}
public interface IContainerEnumerable<out T> : IContainer
where T : IDrawable
{
IReadOnlyList<Drawable> InternalChildren { get; }
IReadOnlyList<T> Children { get; }
int RemoveAll(Predicate<T> match);
}
public interface IContainerCollection<in T> : IContainer
where T : IDrawable
{
IReadOnlyList<Drawable> InternalChildren { set; }
IReadOnlyList<T> Children { set; }
void Add(T drawable);
void Add(IEnumerable<T> collection);
void Remove(T drawable);
void Remove(IEnumerable<T> range);
}
}
| // 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;
using System.Collections.Generic;
using OpenTK;
using osu.Framework.Lists;
namespace osu.Framework.Graphics.Containers
{
public interface IContainer : IDrawable
{
Vector2 ChildSize { get; }
Vector2 ChildOffset { get; }
Vector2 RelativeToAbsoluteFactor { get; }
Vector2 RelativeChildOffset { get; }
EdgeEffectParameters EdgeEffect { get; set; }
float CornerRadius { get; }
void InvalidateFromChild(Invalidation invalidation);
void Clear(bool dispose = true);
Axes AutoSizeAxes { get; set; }
}
public interface IContainerEnumerable<out T> : IContainer
where T : IDrawable
{
IReadOnlyList<Drawable> InternalChildren { get; }
IReadOnlyList<T> Children { get; }
int RemoveAll(Predicate<T> match);
}
public interface IContainerCollection<in T> : IContainer
where T : IDrawable
{
IReadOnlyList<Drawable> InternalChildren { set; }
IReadOnlyList<T> Children { set; }
void Add(T drawable);
void Add(IEnumerable<T> collection);
void Remove(T drawable);
void Remove(IEnumerable<T> range);
}
}
| mit | C# |
e0ad2469709bad79e9ea1a39ab1714339a7d0488 | simplify ps | valadas/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,RichardHowells/Dnn.Platform,mitchelsellers/Dnn.Platform,svdv71/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,RichardHowells/Dnn.Platform,robsiera/Dnn.Platform,nvisionative/Dnn.Platform,wael101/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,svdv71/Dnn.Platform,mitchelsellers/Dnn.Platform,RichardHowells/Dnn.Platform,EPTamminga/Dnn.Platform,mitchelsellers/Dnn.Platform,valadas/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,nvisionative/Dnn.Platform,RichardHowells/Dnn.Platform,dnnsoftware/Dnn.Platform,nvisionative/Dnn.Platform,EPTamminga/Dnn.Platform,wael101/Dnn.Platform,EPTamminga/Dnn.Platform,robsiera/Dnn.Platform,robsiera/Dnn.Platform,wael101/Dnn.Platform,svdv71/Dnn.Platform | Build/cake/version.cake | Build/cake/version.cake | #addin Cake.XdtTransform
#addin "Cake.FileHelpers"
#addin Cake.Powershell
#tool "nuget:?package=GitVersion.CommandLine&prerelease"
GitVersion version;
var buildId = EnvironmentVariable("BUILD_BUILDID") ?? "0";
Task("BuildServerSetVersion")
.IsDependentOn("GitVersion")
.Does(() => {
StartPowershellScript("Write-Host ##vso[build.updatebuildnumber]{version.FullSemVer}.{buildId}");
});
Task("GitVersion")
.Does(() => {
version = GitVersion(new GitVersionSettings {
UpdateAssemblyInfo = true,
UpdateAssemblyInfoFilePath = @"SolutionInfo.cs"
});
});
Task("UpdateDnnManifests")
.IsDependentOn("GitVersion")
.DoesForEach(GetFiles("**/*.dnn"), (file) =>
{
var transformFile = File(System.IO.Path.GetTempFileName());
FileAppendText(transformFile, GetXdtTransformation());
XdtTransformConfig(file, transformFile, file);
});
public string GetBuildNumber()
{
return version.LegacySemVerPadded;
}
public string GetProductVersion()
{
return version.MajorMinorPatch;
}
public string GetXdtTransformation()
{
var versionString = $"{version.Major.ToString("00")}.{version.Minor.ToString("00")}.{version.Patch.ToString("00")}";
return $@"<?xml version=""1.0""?>
<dotnetnuke xmlns:xdt=""http://schemas.microsoft.com/XML-Document-Transform"">
<packages>
<package version=""{versionString}""
xdt:Transform=""SetAttributes(version)""
xdt:Locator=""Condition([not(@version)])"" />
</packages>
</dotnetnuke>";
}
| #addin Cake.XdtTransform
#addin "Cake.FileHelpers"
#addin Cake.Powershell
#tool "nuget:?package=GitVersion.CommandLine&prerelease"
GitVersion version;
var buildId = EnvironmentVariable("BUILD_BUILDID") ?? "0";
Task("BuildServerSetVersion")
.IsDependentOn("GitVersion")
.Does(() => {
StartPowershellScript("Write-Host", $"##vso[build.updatebuildnumber]{version.FullSemVer}.{buildId}");
});
Task("GitVersion")
.Does(() => {
version = GitVersion(new GitVersionSettings {
UpdateAssemblyInfo = true,
UpdateAssemblyInfoFilePath = @"SolutionInfo.cs"
});
});
Task("UpdateDnnManifests")
.IsDependentOn("GitVersion")
.DoesForEach(GetFiles("**/*.dnn"), (file) =>
{
var transformFile = File(System.IO.Path.GetTempFileName());
FileAppendText(transformFile, GetXdtTransformation());
XdtTransformConfig(file, transformFile, file);
});
public string GetBuildNumber()
{
return version.LegacySemVerPadded;
}
public string GetProductVersion()
{
return version.MajorMinorPatch;
}
public string GetXdtTransformation()
{
var versionString = $"{version.Major.ToString("00")}.{version.Minor.ToString("00")}.{version.Patch.ToString("00")}";
return $@"<?xml version=""1.0""?>
<dotnetnuke xmlns:xdt=""http://schemas.microsoft.com/XML-Document-Transform"">
<packages>
<package version=""{versionString}""
xdt:Transform=""SetAttributes(version)""
xdt:Locator=""Condition([not(@version)])"" />
</packages>
</dotnetnuke>";
}
| mit | C# |
a8054a7bd5e4e85bb0703a7116272f92f25167af | Rename input files | Rohansi/LoonyVM,Rohansi/LoonyVM,Rohansi/LoonyVM | LoonyVM/Program.cs | LoonyVM/Program.cs | using System.IO;
using System.Threading;
using SFML.Graphics;
using SFML.Window;
namespace LoonyVM
{
public static class Program
{
public static VirtualMachine Machine;
public static RenderWindow Window;
public static void Main(string[] args)
{
Window = new RenderWindow(new VideoMode(640, 480), "", Styles.Close);
Window.SetFramerateLimit(60);
Window.Closed += (sender, eventArgs) => Window.Close();
Window.Resized += (sender, eventArgs) =>
{
var view = new View();
view.Size = new Vector2f(eventArgs.Width, eventArgs.Height);
view.Center = view.Size / 2;
Window.SetView(view);
};
Machine = new VirtualMachine(512 * 1024);
var prog = File.ReadAllBytes("bios.bin");
for (var i = 0; i < prog.Length; i++)
Machine.Memory[i] = prog[i];
var display = new Devices.Display(Machine, Window);
Machine.Attach(display);
var timer = new Devices.Timer();
Machine.Attach(timer);
var kbd = new Devices.Keyboard(Window);
Machine.Attach(kbd);
var hdd = new Devices.HardDrive("disk.img");
Machine.Attach(hdd);
var stepThread = new Thread(() =>
{
while (Window.IsOpen())
{
Machine.Step();
}
});
stepThread.Start();
while (Window.IsOpen())
{
Window.DispatchEvents();
Window.Clear();
Window.Draw(display);
Window.Display();
}
timer.Dispose();
}
}
}
| using System.IO;
using System.Threading;
using SFML.Graphics;
using SFML.Window;
namespace LoonyVM
{
public static class Program
{
public static VirtualMachine Machine;
public static RenderWindow Window;
public static void Main(string[] args)
{
Window = new RenderWindow(new VideoMode(640, 480), "", Styles.Close);
Window.SetFramerateLimit(60);
Window.Closed += (sender, eventArgs) => Window.Close();
Window.Resized += (sender, eventArgs) =>
{
var view = new View();
view.Size = new Vector2f(eventArgs.Width, eventArgs.Height);
view.Center = view.Size / 2;
Window.SetView(view);
};
Machine = new VirtualMachine(512 * 1024);
var prog = File.ReadAllBytes("test.bin");
for (var i = 0; i < prog.Length; i++)
Machine.Memory[i] = prog[i];
var display = new Devices.Display(Machine, Window);
Machine.Attach(display);
var timer = new Devices.Timer();
Machine.Attach(timer);
var kbd = new Devices.Keyboard(Window);
Machine.Attach(kbd);
var hdd = new Devices.HardDrive("hd0.img");
Machine.Attach(hdd);
var stepThread = new Thread(() =>
{
while (Window.IsOpen())
{
Machine.Step();
}
});
stepThread.Start();
while (Window.IsOpen())
{
Window.DispatchEvents();
Window.Clear();
Window.Draw(display);
Window.Display();
}
timer.Dispose();
}
}
}
| unlicense | C# |
4cb648a19eb78aa8f79beeb0748e9f8c747a5b22 | fix skip message | Pondidum/Ledger,Pondidum/Ledger | Ledger.Tests/TestInfrastructure/RequiresRabbitFactAttribute.cs | Ledger.Tests/TestInfrastructure/RequiresRabbitFactAttribute.cs | using System;
using RabbitMQ.Client;
using Xunit;
namespace Ledger.Tests.TestInfrastructure
{
public class RequiresRabbitFactAttribute : FactAttribute
{
public RequiresRabbitFactAttribute()
{
if (IsRabbitAvailable.Value == false)
{
Skip = "RabbitMQ is not available";
}
}
private static readonly Lazy<bool> IsRabbitAvailable;
static RequiresRabbitFactAttribute()
{
IsRabbitAvailable = new Lazy<bool>(() =>
{
try
{
var factory = new ConnectionFactory
{
HostName = "10.0.75.2",
RequestedConnectionTimeout = 1000
};
using (var connection = factory.CreateConnection())
{
return connection.IsOpen;
}
}
catch (Exception)
{
return false;
}
});
}
}
}
| using System;
using RabbitMQ.Client;
using Xunit;
namespace Ledger.Tests.TestInfrastructure
{
public class RequiresRabbitFactAttribute : FactAttribute
{
public RequiresRabbitFactAttribute()
{
if (IsRabbitAvailable.Value == false)
{
Skip = "Postgres is not available";
}
}
private static readonly Lazy<bool> IsRabbitAvailable;
static RequiresRabbitFactAttribute()
{
IsRabbitAvailable = new Lazy<bool>(() =>
{
try
{
var factory = new ConnectionFactory
{
HostName = "10.0.75.2",
RequestedConnectionTimeout = 1000
};
using (var connection = factory.CreateConnection())
{
return connection.IsOpen;
}
}
catch (Exception)
{
return false;
}
});
}
}
}
| lgpl-2.1 | C# |
54b3caa327e0bae737771717ec06487b0013d861 | Document UnrecognizedResponseException | tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,Cyberboss/tgstation-server | src/Tgstation.Server.Client/UnrecognizedResponseException.cs | src/Tgstation.Server.Client/UnrecognizedResponseException.cs | using System;
using System.Globalization;
using System.Net;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Client
{
/// <summary>
/// Occurs when a response is received that did not deserialize to one of the expected <see cref="Api.Models"/>
/// </summary>
sealed class UnrecognizedResponseException : ClientException
{
/// <summary>
/// Construct an <see cref="UnrecognizedResponseException"/> with the <paramref name="data"/> of a response body and the <paramref name="statusCode"/>
/// </summary>
/// <param name="data">The body of the response</param>
/// <param name="statusCode">The <see cref="HttpStatusCode"/> for the <see cref="ClientException"/></param>
public UnrecognizedResponseException(string data, HttpStatusCode statusCode) : base(new ErrorMessage
{
Message = String.Format(CultureInfo.InvariantCulture, "Unrecognized response body: {0}", data),
SeverApiVersion = null
}, statusCode)
{ }
/// <summary>
/// Construct a <see cref="UnrecognizedResponseException"/>
/// </summary>
public UnrecognizedResponseException() { }
/// <summary>
/// Construct an <see cref="UnrecognizedResponseException"/> with a <paramref name="message"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
public UnrecognizedResponseException(string message) : base(message) { }
/// <summary>
/// Construct an <see cref="UnrecognizedResponseException"/> with a <paramref name="message"/> and <paramref name="innerException"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
/// <param name="innerException">The inner <see cref="Exception"/> for the base <see cref="Exception"/></param>
public UnrecognizedResponseException(string message, Exception innerException) : base(message, innerException) { }
}
}
| using System;
using System.Globalization;
using System.Net;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Client
{
sealed class UnrecognizedResponseException : ClientException
{
/// <summary>
/// Construct an <see cref="UnrecognizedResponseException"/> with the <paramref name="data"/> of a response body and the <paramref name="statusCode"/>
/// </summary>
/// <param name="data">The body of the response</param>
/// <param name="statusCode">The <see cref="HttpStatusCode"/> for the <see cref="ClientException"/></param>
public UnrecognizedResponseException(string data, HttpStatusCode statusCode) : base(new ErrorMessage
{
Message = String.Format(CultureInfo.InvariantCulture, "Unrecognized response body: {0}", data),
SeverApiVersion = null
}, statusCode)
{ }
/// <summary>
/// Construct a <see cref="UnrecognizedResponseException"/>
/// </summary>
public UnrecognizedResponseException() { }
/// <summary>
/// Construct an <see cref="UnrecognizedResponseException"/> with a <paramref name="message"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
public UnrecognizedResponseException(string message) : base(message) { }
/// <summary>
/// Construct an <see cref="UnrecognizedResponseException"/> with a <paramref name="message"/> and <paramref name="innerException"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
/// <param name="innerException">The inner <see cref="Exception"/> for the base <see cref="Exception"/></param>
public UnrecognizedResponseException(string message, Exception innerException) : base(message, innerException) { }
}
}
| agpl-3.0 | C# |
0a445c133927799a8719bb790a180b09e9059a9e | Fix error in DateTimeOffsetProvider | VishalMadhvani/allReady,stevejgordon/allReady,HamidMosalla/allReady,MisterJames/allReady,shanecharles/allReady,enderdickerson/allReady,dpaquette/allReady,gitChuckD/allReady,BillWagner/allReady,binaryjanitor/allReady,mgmccarthy/allReady,HamidMosalla/allReady,jonatwabash/allReady,bcbeatty/allReady,anobleperson/allReady,BillWagner/allReady,pranap/allReady,mipre100/allReady,c0g1t8/allReady,c0g1t8/allReady,shanecharles/allReady,mipre100/allReady,arst/allReady,GProulx/allReady,BillWagner/allReady,GProulx/allReady,anobleperson/allReady,HTBox/allReady,pranap/allReady,HTBox/allReady,GProulx/allReady,JowenMei/allReady,enderdickerson/allReady,stevejgordon/allReady,JowenMei/allReady,arst/allReady,forestcheng/allReady,dpaquette/allReady,MisterJames/allReady,shanecharles/allReady,HamidMosalla/allReady,gitChuckD/allReady,shanecharles/allReady,GProulx/allReady,HamidMosalla/allReady,JowenMei/allReady,anobleperson/allReady,binaryjanitor/allReady,mipre100/allReady,gitChuckD/allReady,VishalMadhvani/allReady,chinwobble/allReady,VishalMadhvani/allReady,forestcheng/allReady,mgmccarthy/allReady,colhountech/allReady,HTBox/allReady,HTBox/allReady,arst/allReady,colhountech/allReady,VishalMadhvani/allReady,MisterJames/allReady,binaryjanitor/allReady,chinwobble/allReady,colhountech/allReady,jonatwabash/allReady,stevejgordon/allReady,mgmccarthy/allReady,anobleperson/allReady,bcbeatty/allReady,mgmccarthy/allReady,chinwobble/allReady,stevejgordon/allReady,pranap/allReady,JowenMei/allReady,arst/allReady,enderdickerson/allReady,chinwobble/allReady,BillWagner/allReady,bcbeatty/allReady,pranap/allReady,colhountech/allReady,forestcheng/allReady,jonatwabash/allReady,jonatwabash/allReady,forestcheng/allReady,dpaquette/allReady,enderdickerson/allReady,bcbeatty/allReady,mipre100/allReady,c0g1t8/allReady,gitChuckD/allReady,c0g1t8/allReady,dpaquette/allReady,binaryjanitor/allReady,MisterJames/allReady | AllReadyApp/Web-App/AllReady/Providers/IDateTimeOffsetProvider.cs | AllReadyApp/Web-App/AllReady/Providers/IDateTimeOffsetProvider.cs | using System;
namespace AllReady.Providers
{
public interface IDateTimeOffsetProvider
{
DateTimeOffset AdjustDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0);
DateTimeOffset AdjustDateTimeOffsetTo(TimeZoneInfo timeZoneInfo, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0);
void AdjustDateTimeOffsetTo(string timeZoneId, DateTimeOffset startDateTimeOffset, DateTimeOffset endDateTimeOffset, out DateTimeOffset convertedStartDate, out DateTimeOffset convertedEndDate);
}
public class DateTimeOffsetProvider : IDateTimeOffsetProvider
{
public DateTimeOffset AdjustDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0)
{
return AdjustDateTimeOffsetTo(FindSystemTimeZoneBy(timeZoneId), dateTimeOffset, hour, minute, second);
}
public DateTimeOffset AdjustDateTimeOffsetTo(TimeZoneInfo timeZoneInfo, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0)
{
return new DateTimeOffset(dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day, hour, minute, second, timeZoneInfo.GetUtcOffset(dateTimeOffset));
}
public void AdjustDateTimeOffsetTo(string timeZoneId, DateTimeOffset startDateTimeOffset, DateTimeOffset endDateTimeOffset, out DateTimeOffset convertedStartDate, out DateTimeOffset convertedEndDate)
{
var timeZoneInfo = FindSystemTimeZoneBy(timeZoneId);
convertedStartDate = new DateTimeOffset(startDateTimeOffset.Year, startDateTimeOffset.Month, startDateTimeOffset.Day, 0, 0, 0, timeZoneInfo.GetUtcOffset(startDateTimeOffset));
convertedEndDate = new DateTimeOffset(endDateTimeOffset.Year, endDateTimeOffset.Month, endDateTimeOffset.Day, 0, 0, 0, timeZoneInfo.GetUtcOffset(endDateTimeOffset));
}
private static TimeZoneInfo FindSystemTimeZoneBy(string timeZoneId)
{
return TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
}
}
} | using System;
namespace AllReady.Providers
{
public interface IDateTimeOffsetProvider
{
DateTimeOffset AdjustDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0);
DateTimeOffset AdjustDateTimeOffsetTo(TimeZoneInfo timeZoneInfo, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0);
void AdjustDateTimeOffsetTo(string timeZoneId, DateTimeOffset startDateTimeOffset, DateTimeOffset endDateTimeOffset, out DateTimeOffset convertedStartDate, out DateTimeOffset convertedEndDate);
}
public class DateTimeOffsetProvider : IDateTimeOffsetProvider
{
public DateTimeOffset AdjustDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0)
{
return AdjustDateTimeOffsetTo(FindSystemTimeZoneBy(timeZoneId), dateTimeOffset, hour, minute, second);
}
public DateTimeOffset AdjustDateTimeOffsetTo(TimeZoneInfo timeZoneInfo, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0)
{
return new DateTimeOffset(dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day, hour, minute, second, timeZoneInfo.GetUtcOffset(dateTimeOffset));
}
public void AdjustDateTimeOffsetTo(string timeZoneId, DateTimeOffset startDateTimeOffset, DateTimeOffset endDateTimeOffset, out DateTimeOffset convertedStartDate, out DateTimeOffset convertedEndDate)
{
var timeZoneInfo = FindSystemTimeZoneBy(timeZoneId);
convertedStartDate = new DateTimeOffset(startDateTimeOffset.Year, startDateTimeOffset.Month, startDateTimeOffset.Day, 0, 0, 0, timeZoneInfo.GetUtcOffset(startDateTimeOffset));
convertedEndDate = new DateTimeOffset(endDateTimeOffset.Year, endDateTimeOffset.Month, endDateTimeOffset.Day, 0, 0, 0, timeZoneInfo.GetUtcOffset(endDateTimeOffset);
}
private static TimeZoneInfo FindSystemTimeZoneBy(string timeZoneId)
{
return TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
}
}
} | mit | C# |
aaa0c4fe7da73944a8b7d9e862ba458f14880227 | Add raw message sending, requires xdotool | Goz3rr/SkypeSharp | SkypeSharp/Chat.cs | SkypeSharp/Chat.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace SkypeSharp {
/// <summary>
/// Class representing a Skype CHAT object
/// </summary>
public class Chat : SkypeObject {
/// <summary>
/// List of users in this chat
/// </summary>
public IEnumerable<User> Users {
get {
string[] usernames = GetProperty("MEMBERS").Split(' ');
return usernames.Select(u => new User(Skype, u));
}
}
/// <summary>
/// List of chatmembers, useful for changing roles
/// Skype broke this so it probably doesn't work
/// </summary>
public IEnumerable<ChatMember> ChatMembers {
get {
string[] members = GetProperty("MEMBEROBJECTS").Split(' ');
return members.Select(m => new ChatMember(Skype, m));
}
}
public Chat(Skype skype, string id) : base(skype, id, "CHAT") {}
/// <summary>
/// Send a message to this chat
/// </summary>
/// <param name="text">Text to send</param>
public void Send(string text) {
Skype.Send("CHATMESSAGE " + ID + " " + text);
}
/// <summary>
/// Uses xdotool to attempt to send skype a message
/// </summary>
/// <param name="text"></param>
public void SendRaw(string text) {
Skype.Send("OPEN CHAT " + ID);
Process p = new Process();
p.StartInfo.FileName = "/usr/bin/xdotool";
p.StartInfo.Arguments = String.Format("search --name skype type \"{0}\"", text.Replace("\"", "\\\""));
p.Start();
p.WaitForExit();
p.StartInfo.Arguments = "search --name skype key ctrl+shift+Return";
p.Start();
p.WaitForExit();
}
}
} | using System.Collections.Generic;
using System.Linq;
namespace SkypeSharp {
/// <summary>
/// Class representing a Skype CHAT object
/// </summary>
public class Chat : SkypeObject {
/// <summary>
/// List of users in this chat
/// </summary>
public IEnumerable<User> Users {
get {
string[] usernames = GetProperty("MEMBERS").Split(' ');
return usernames.Select(u => new User(Skype, u));
}
}
/// <summary>
/// List of chatmembers, useful for changing roles
/// Skype broke this so it probably doesn't work
/// </summary>
public IEnumerable<ChatMember> ChatMembers {
get {
string[] members = GetProperty("MEMBEROBJECTS").Split(' ');
return members.Select(m => new ChatMember(Skype, m));
}
}
public Chat(Skype skype, string id) : base(skype, id, "CHAT") {}
/// <summary>
/// Send a message to this chat
/// </summary>
/// <param name="text">Text to send</param>
public void Send(string text) {
Skype.Send("CHATMESSAGE " + ID + " " + text);
}
}
} | mit | C# |
f5bac2b03b0338a993337e300920e3f489b411c0 | Add documentation from IViewport | charlenni/Mapsui,charlenni/Mapsui | Mapsui/ViewportState.cs | Mapsui/ViewportState.cs | // Copyright (c) The Mapsui authors.
// The Mapsui authors licensed this file under the MIT license.
// See the LICENSE file in the project root for full license information.
using Mapsui.Extensions;
using Mapsui.Utilities;
namespace Mapsui
{
public record class ViewportState
{
/// <summary>
/// The X coordinate of the center of the viewport in world coordinates
/// </summary>
public double CenterX { get; init; }
/// <summary>
/// The Y coordinate of the center of the viewport in world coordinates
/// </summary>
public double CenterY { get; init; }
/// <summary>
/// Resolution of the viewport in units per pixel
/// </summary>
/// <remarks>
/// The Resolution in Mapsui is what is often called zoom level. Because Mapsui is projection independent, there
/// aren't any zoom levels as other map libraries have. If your map has EPSG:3857 as projection
/// and you want to calculate the zoom, you should use the following equation
///
/// var zoom = (float)Math.Log(78271.51696401953125 / resolution, 2);
/// </remarks>
public double Resolution { get; init; }
/// <summary>
/// Viewport rotation from True North (clockwise degrees)
/// </summary>
public double Rotation { get; init; }
/// <summary>
/// Width of viewport in screen pixels
/// </summary>
public double Width { get; init; }
/// <summary>
/// Height of viewport in screen pixels
/// </summary>
public double Height { get; init; }
/// <summary>
/// MRect of viewport in map coordinates respecting Rotation
/// </summary>
/// <remarks>
/// This MRect is horizontally and vertically aligned, even if the viewport
/// is rotated. So this MRect perhaps contain parts, that are not visible.
/// </remarks>
public MRect Extent { get; private init; }
/// <summary>
/// IsRotated is true, when viewport displays map rotated
/// </summary>
public bool IsRotated { get; private init; }
public ViewportState(double centerX, double centerY, double resolution, double rotation, double width, double height)
{
CenterX = centerX;
CenterY = centerY;
Resolution = resolution;
Rotation = rotation;
Width = width;
Height = height;
// Secondary fields
IsRotated = !double.IsNaN(Rotation) && Rotation > Constants.Epsilon && Rotation < 360 - Constants.Epsilon;
if (!IsRotated) Rotation = 0; // If not rotated set _rotation explicitly to exactly 0
Extent = this.GetExtent();
}
}
}
| // Copyright (c) The Mapsui authors.
// The Mapsui authors licensed this file under the MIT license.
// See the LICENSE file in the project root for full license information.
using Mapsui.Extensions;
using Mapsui.Utilities;
namespace Mapsui
{
public record class ViewportState
{
public double CenterX { get; init; }
public double CenterY { get; init; }
public double Resolution { get; init; }
public double Rotation { get; init; }
public double Width { get; init; }
public double Height { get; init; }
public MRect Extent { get; private init; }
public bool IsRotated { get; private init; }
public ViewportState(double centerX, double centerY, double resolution, double rotation, double width, double height)
{
CenterX = centerX;
CenterY = centerY;
Resolution = resolution;
Rotation = rotation;
Width = width;
Height = height;
// Secondary fields
IsRotated = !double.IsNaN(Rotation) && Rotation > Constants.Epsilon && Rotation < 360 - Constants.Epsilon;
if (!IsRotated) Rotation = 0; // If not rotated set _rotation explicitly to exactly 0
Extent = this.GetExtent();
}
}
}
| mit | C# |
300879c9eaa64812390ce46f06d2da55d0fc43a6 | add bi-directional topic mq utility. this works for receive topics. | masatoshiitoh/unity_mqlib | unity_mqlib/BidirTopic.cs | unity_mqlib/BidirTopic.cs | // This source code is licensed under the Apache License, version 2.0.
//
// The APL v2.0:
//
//---------------------------------------------------------------------------
// Copyright (C) 2007-2013 GoPivotal, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------
//
using UnityEngine;
using System.Collections;
using System.Threading;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.MessagePatterns;
using RabbitMQ.Util;
public class BidirTopic : MonoBehaviour {
public string serverip;
public string ToClientEx;
ConnectionFactory cf;
IConnection conn;
IModel ch = null;
QueueingBasicConsumer consumer;
System.Collections.Queue queue = null;
string lastMessage;
// Use this for initialization
void Start()
{
cf = new ConnectionFactory();
cf.HostName = serverip;
conn = cf.CreateConnection();
conn.ConnectionShutdown += new ConnectionShutdownEventHandler(LogConnClose);
ch = conn.CreateModel();
ch.ExchangeDeclare(ToClientEx, "topic",false,true,null);
string queueName = ch.QueueDeclare();
ch.QueueBind(queueName, ToClientEx, "#");
consumer = new QueueingBasicConsumer(ch);
ch.BasicConsume(queueName, true, consumer);
queue = new System.Collections.Queue();
queue.Clear();
}
// Update is called once per frame
void Update()
{
if (ch == null || consumer == null) return;
BasicDeliverEventArgs ea;
while ((ea = (BasicDeliverEventArgs)consumer.Queue.DequeueNoWait(null)) != null)
{
var body = ea.Body;
var routingKey = ea.RoutingKey;
var message = Encoding.UTF8.GetString(body);
queue.Enqueue(message + " from " + routingKey);
}
}
void OnGUI()
{
if (queue != null && queue.Count > 0)
{
lastMessage = queue.Dequeue().ToString();
}
GUILayout.Label((string)lastMessage);
}
public static void LogConnClose(IConnection conn, ShutdownEventArgs reason)
{
Debug.Log("Closing connection normally. " + conn + " with reason " + reason);
}
}
| using UnityEngine;
using System.Collections;
public class BidirTopic : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| apache-2.0 | C# |
96d6649105d032720eecfcde9b7728c6bb416210 | Introduce UIVisibilityFlags property in AndroidGameActivity | ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework | osu.Framework.Android/AndroidGameActivity.cs | osu.Framework.Android/AndroidGameActivity.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 Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
namespace osu.Framework.Android
{
public abstract class AndroidGameActivity : Activity
{
protected abstract Game CreateGame();
/// <summary>
/// The visibility flags for the system UI (status and navigation bars)
/// </summary>
public SystemUiFlags UIVisibilityFlags
{
get => (SystemUiFlags)Window.DecorView.SystemUiVisibility;
set => Window.DecorView.SystemUiVisibility = (StatusBarVisibility)value;
}
private AndroidGameView gameView;
public override void OnTrimMemory([GeneratedEnum] TrimMemory level)
{
base.OnTrimMemory(level);
gameView.Host?.Collect();
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(gameView = new AndroidGameView(this, CreateGame()));
}
protected override void OnPause()
{
base.OnPause();
// Because Android is not playing nice with Background - we just kill it
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
public override void OnBackPressed()
{
// Avoid the default implementation that does close the app.
// This only happens when the back button could not be captured from OnKeyDown.
}
// On some devices and keyboard combinations the OnKeyDown event does not propagate the key event to the view.
// Here it is done manually to ensure that the keys actually land in the view.
public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
return gameView.OnKeyDown(keyCode, e);
}
public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
return gameView.OnKeyUp(keyCode, e);
}
public override bool OnKeyLongPress([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
return gameView.OnKeyLongPress(keyCode, e);
}
}
}
| // 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 Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
namespace osu.Framework.Android
{
public abstract class AndroidGameActivity : Activity
{
protected abstract Game CreateGame();
private AndroidGameView gameView;
public override void OnTrimMemory([GeneratedEnum] TrimMemory level)
{
base.OnTrimMemory(level);
gameView.Host?.Collect();
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(gameView = new AndroidGameView(this, CreateGame()));
}
protected override void OnPause()
{
base.OnPause();
// Because Android is not playing nice with Background - we just kill it
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
public override void OnBackPressed()
{
// Avoid the default implementation that does close the app.
// This only happens when the back button could not be captured from OnKeyDown.
}
// On some devices and keyboard combinations the OnKeyDown event does not propagate the key event to the view.
// Here it is done manually to ensure that the keys actually land in the view.
public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
return gameView.OnKeyDown(keyCode, e);
}
public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
return gameView.OnKeyUp(keyCode, e);
}
public override bool OnKeyLongPress([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
return gameView.OnKeyLongPress(keyCode, e);
}
}
}
| mit | C# |
aa597c193468b5b2f4c798412b41f003ad5e1e2d | Copy documentation across to SettingsSlider | EVAST9919/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,2yangk23/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,ppy/osu,johnneijzen/osu,UselessToucan/osu,johnneijzen/osu,EVAST9919/osu,NeoAdonis/osu,smoogipooo/osu | osu.Game/Overlays/Settings/SettingsSlider.cs | osu.Game/Overlays/Settings/SettingsSlider.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 System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsSlider<T> : SettingsSlider<T, OsuSliderBar<T>>
where T : struct, IEquatable<T>, IComparable<T>, IConvertible
{
}
public class SettingsSlider<TValue, TSlider> : SettingsItem<TValue>
where TValue : struct, IEquatable<TValue>, IComparable<TValue>, IConvertible
where TSlider : OsuSliderBar<TValue>, new()
{
protected override Drawable CreateControl() => new TSlider
{
Margin = new MarginPadding { Top = 5, Bottom = 5 },
RelativeSizeAxes = Axes.X
};
/// <summary>
/// When set, value changes based on user input are only transferred to any bound control's Current on commit.
/// This is useful if the UI interaction could be adversely affected by the value changing, such as the position of the <see cref="SliderBar{T}"/> on the screen.
/// </summary>
public bool TransferValueOnCommit
{
get => ((TSlider)Control).TransferValueOnCommit;
set => ((TSlider)Control).TransferValueOnCommit = value;
}
/// <summary>
/// A custom step value for each key press which actuates a change on this control.
/// </summary>
public float KeyboardStep
{
get => ((TSlider)Control).KeyboardStep;
set => ((TSlider)Control).KeyboardStep = value;
}
/// <summary>
/// Whether to format the tooltip as a percentage or the actual value.
/// </summary>
public bool DisplayAsPercentage
{
get => ((TSlider)Control).DisplayAsPercentage;
set => ((TSlider)Control).DisplayAsPercentage = value;
}
}
}
| // 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 System;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsSlider<T> : SettingsSlider<T, OsuSliderBar<T>>
where T : struct, IEquatable<T>, IComparable<T>, IConvertible
{
}
public class SettingsSlider<TValue, TSlider> : SettingsItem<TValue>
where TValue : struct, IEquatable<TValue>, IComparable<TValue>, IConvertible
where TSlider : OsuSliderBar<TValue>, new()
{
protected override Drawable CreateControl() => new TSlider
{
Margin = new MarginPadding { Top = 5, Bottom = 5 },
RelativeSizeAxes = Axes.X
};
public bool TransferValueOnCommit
{
get => ((TSlider)Control).TransferValueOnCommit;
set => ((TSlider)Control).TransferValueOnCommit = value;
}
public float KeyboardStep
{
get => ((TSlider)Control).KeyboardStep;
set => ((TSlider)Control).KeyboardStep = value;
}
public bool DisplayAsPercentage
{
get => ((TSlider)Control).DisplayAsPercentage;
set => ((TSlider)Control).DisplayAsPercentage = value;
}
}
}
| mit | C# |
23a1a8e3f552d1097060cb5d507d774794bc7af0 | Add title on link of ln services in the dashboard | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Components/StoreLightningServices/Default.cshtml | BTCPayServer/Components/StoreLightningServices/Default.cshtml | @using Microsoft.AspNetCore.Mvc.TagHelpers
@model BTCPayServer.Components.StoreLightningServices.StoreLightningServicesViewModel
@if (Model.Services != null && Model.Services.Any())
{
<div id="[email protected]" class="widget store-lightning-services">
<header class="mb-4">
<h6>Lightning Services</h6>
<a class asp-controller="UIStores" asp-action="Lightning" asp-route-storeId="@Model.Store.Id" asp-route-cryptoCode="@Model.CryptoCode">Details</a>
</header>
<div id="Services" class="services-list">
@foreach (var service in Model.Services)
{
@if (!string.IsNullOrEmpty(service.Error))
{
<div class="service" id="@($"Service-{service.ServiceName}")">
<img src="@($"~/img/{service.Type.ToLower()}.png")" asp-append-version="true" alt="@service.DisplayName" />
<small class="d-block mt-3 lh-sm fw-semibold text-danger">@service.Error</small>
</div>
}
else if (string.IsNullOrEmpty(service.Link))
{
<a title="@service.DisplayName" asp-controller="UIServer" asp-action="Service" asp-route-serviceName="@service.ServiceName" asp-route-cryptoCode="@service.CryptoCode" class="service" id="@($"Service-{service.ServiceName}")">
<img src="@($"~/img/{service.Type.ToLower()}.png")" asp-append-version="true" alt="@service.DisplayName" />
</a>
}
else
{
<a title="@service.DisplayName" href="@service.Link" target="_blank" rel="noreferrer noopener" class="service" id="@($"Service-{service.ServiceName}")">
<img src="@($"~/img/{service.Type.ToLower()}.png")" asp-append-version="true" alt="@service.DisplayName" />
</a>
}
}
</div>
</div>
}
| @using Microsoft.AspNetCore.Mvc.TagHelpers
@model BTCPayServer.Components.StoreLightningServices.StoreLightningServicesViewModel
@if (Model.Services != null && Model.Services.Any())
{
<div id="[email protected]" class="widget store-lightning-services">
<header class="mb-4">
<h6>Lightning Services</h6>
<a class asp-controller="UIStores" asp-action="Lightning" asp-route-storeId="@Model.Store.Id" asp-route-cryptoCode="@Model.CryptoCode">Details</a>
</header>
<div id="Services" class="services-list">
@foreach (var service in Model.Services)
{
@if (!string.IsNullOrEmpty(service.Error))
{
<div class="service" id="@($"Service-{service.ServiceName}")">
<img src="@($"~/img/{service.Type.ToLower()}.png")" asp-append-version="true" alt="@service.DisplayName" />
<small class="d-block mt-3 lh-sm fw-semibold text-danger">@service.Error</small>
</div>
}
else if (string.IsNullOrEmpty(service.Link))
{
<a asp-controller="UIServer" asp-action="Service" asp-route-serviceName="@service.ServiceName" asp-route-cryptoCode="@service.CryptoCode" class="service" id="@($"Service-{service.ServiceName}")">
<img src="@($"~/img/{service.Type.ToLower()}.png")" asp-append-version="true" alt="@service.DisplayName" />
</a>
}
else
{
<a href="@service.Link" target="_blank" rel="noreferrer noopener" class="service" id="@($"Service-{service.ServiceName}")">
<img src="@($"~/img/{service.Type.ToLower()}.png")" asp-append-version="true" alt="@service.DisplayName" />
</a>
}
}
</div>
</div>
}
| mit | C# |
1d079e73e1ed1d687bb75107cbfdf6195604c67c | Remove unused using | ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework/Input/CustomInputManager.cs | osu.Framework/Input/CustomInputManager.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 System.Collections.Immutable;
using System.Linq;
using osu.Framework.Input.Handlers;
namespace osu.Framework.Input
{
/// <summary>
/// An <see cref="InputManager"/> implementation which allows managing of <see cref="InputHandler"/>s manually.
/// </summary>
public class CustomInputManager : InputManager
{
protected override ImmutableArray<InputHandler> InputHandlers => inputHandlers;
private ImmutableArray<InputHandler> inputHandlers = ImmutableArray.Create<InputHandler>();
protected void AddHandler(InputHandler handler)
{
if (!handler.Initialize(Host)) return;
inputHandlers = inputHandlers.Append(handler).ToImmutableArray();
}
protected void RemoveHandler(InputHandler handler)
{
inputHandlers = inputHandlers.Where(h => h != handler).ToImmutableArray();
}
protected override void Dispose(bool isDisposing)
{
foreach (var h in inputHandlers)
h.Dispose();
base.Dispose(isDisposing);
}
}
}
| // 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 System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using osu.Framework.Input.Handlers;
namespace osu.Framework.Input
{
/// <summary>
/// An <see cref="InputManager"/> implementation which allows managing of <see cref="InputHandler"/>s manually.
/// </summary>
public class CustomInputManager : InputManager
{
protected override ImmutableArray<InputHandler> InputHandlers => inputHandlers;
private ImmutableArray<InputHandler> inputHandlers = ImmutableArray.Create<InputHandler>();
protected void AddHandler(InputHandler handler)
{
if (!handler.Initialize(Host)) return;
inputHandlers = inputHandlers.Append(handler).ToImmutableArray();
}
protected void RemoveHandler(InputHandler handler)
{
inputHandlers = inputHandlers.Where(h => h != handler).ToImmutableArray();
}
protected override void Dispose(bool isDisposing)
{
foreach (var h in inputHandlers)
h.Dispose();
base.Dispose(isDisposing);
}
}
}
| mit | C# |
c7305f0b4462cf77440d9f74dc42e37f9e7fe6ee | Simplify implementation structure | johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,johnneijzen/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,peppy/osu-new,2yangk23/osu,peppy/osu,peppy/osu | osu.Game.Rulesets.Catch/Mods/CatchModRelax.cs | osu.Game.Rulesets.Catch/Mods/CatchModRelax.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.Framework.Graphics;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModRelax : ModRelax, IApplicableToDrawableRuleset<CatchHitObject>
{
public override string Description => @"Use the mouse to control the catcher.";
public void ApplyToDrawableRuleset(DrawableRuleset<CatchHitObject> drawableRuleset)
{
drawableRuleset.Cursor.Add(new MouseInputHelper((CatchPlayfield)drawableRuleset.Playfield));
}
private class MouseInputHelper : Drawable, IKeyBindingHandler<CatchAction>, IRequireHighFrequencyMousePosition
{
private readonly CatcherArea.Catcher catcher;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;
public MouseInputHelper(CatchPlayfield playfield)
{
catcher = playfield.CatcherArea.MovableCatcher;
RelativeSizeAxes = Axes.Both;
}
//disable keyboard controls
public bool OnPressed(CatchAction action) => true;
public bool OnReleased(CatchAction action) => true;
protected override bool OnMouseMove(MouseMoveEvent e)
{
catcher.UpdatePosition(e.MousePosition.X / DrawSize.X);
return base.OnMouseMove(e);
}
}
}
}
| // 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.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osuTK;
using System;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModRelax : ModRelax, IApplicableToDrawableRuleset<CatchHitObject>
{
public override string Description => @"Use the mouse to control the catcher.";
public void ApplyToDrawableRuleset(DrawableRuleset<CatchHitObject> drawableRuleset) =>
((Container)drawableRuleset.Playfield.Parent).Add(new CatchModRelaxHelper(drawableRuleset.Playfield as CatchPlayfield));
private class CatchModRelaxHelper : Drawable, IKeyBindingHandler<CatchAction>, IRequireHighFrequencyMousePosition
{
private readonly CatcherArea.Catcher catcher;
public CatchModRelaxHelper(CatchPlayfield catchPlayfield)
{
catcher = catchPlayfield.CatcherArea.MovableCatcher;
RelativeSizeAxes = Axes.Both;
}
//disable keyboard controls
public bool OnPressed(CatchAction action) => true;
public bool OnReleased(CatchAction action) => true;
protected override bool OnMouseMove(MouseMoveEvent e)
{
catcher.UpdatePosition(e.MousePosition.X / DrawSize.X);
return base.OnMouseMove(e);
}
}
}
}
| mit | C# |
05a8202e80515ce18b7d6eb51dfb97b2d858a149 | Handle exception messages with unescaped braces (providing no format arguments are supplied). | DimensionDataCBUSydney/Compute.Api.Client | ComputeClient/Compute.Client/Exceptions/ApiClientException.cs | ComputeClient/Compute.Client/Exceptions/ApiClientException.cs | // ReSharper disable once CheckNamespace
// Backwards compatibility
namespace DD.CBU.Compute.Api.Client
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// The base class for API client exceptions.
/// </summary>
[Serializable]
public abstract class ApiClientException
: Exception
{
/// <summary>
/// Initialises a new instance of the <see cref="ApiClientException"/> class.
/// Create a new <see cref="ApiClientException"/>.
/// </summary>
/// <param name="messageOrFormat">
/// The exception message or message format.
/// </param>
/// <param name="formatArguments">
/// Optional message format arguments.
/// </param>
protected ApiClientException(string messageOrFormat, params object[] formatArguments)
: base(SafeFormat(messageOrFormat, formatArguments))
{
}
/// <summary>
/// Initialises a new instance of the <see cref="ApiClientException"/> class.
/// Create a new <see cref="ApiClientException"/>.
/// </summary>
/// <param name="messageOrFormat">
/// The exception message or message format.
/// </param>
/// <param name="innerException">
/// A previous exception that caused the current exception to be raised.
/// </param>
/// <param name="formatArguments">
/// Optional message format arguments.
/// </param>
protected ApiClientException(string messageOrFormat, Exception innerException, params object[] formatArguments)
: base(SafeFormat(messageOrFormat, formatArguments), innerException)
{
}
/// <summary>
/// Initialises a new instance of the <see cref="ApiClientException"/> class.
/// Deserialisation constructor for <see cref="ApiClientException"/>.
/// </summary>
/// <param name="info">
/// A <see cref="SerializationInfo"/> serialisation data store that holds the serialized exception data.
/// </param>
/// <param name="context">
/// A <see cref="StreamingContext"/> value that indicates the source of the serialised data.
/// </param>
/// <exception cref="ArgumentNullException">
/// The <paramref name="info"/> parameter is null.
/// </exception>
/// <exception cref="SerializationException">
/// The class name is <c>null</c> or <see cref="Exception.HResult"/> is zero (0).
/// </exception>
protected ApiClientException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Safely format the specified message.
/// </summary>
/// <param name="messageOrFormat">
/// The message or message-format specifier.
/// </param>
/// <param name="formatArguments">
/// Optional message format arguments.
/// </param>
/// <returns>
/// The formatted message, unless there are no format arguments (in which case <paramref name="messageOrFormat"/> is returned).
/// </returns>
protected static string SafeFormat(string messageOrFormat, object[] formatArguments)
{
if (formatArguments == null || formatArguments.Length == 0)
return messageOrFormat;
try
{
return string.Format(messageOrFormat, formatArguments);
}
catch (FormatException)
{
return messageOrFormat;
}
}
}
} | // ReSharper disable once CheckNamespace
// Backwards compatibility
namespace DD.CBU.Compute.Api.Client
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// The base class for API client exceptions.
/// </summary>
[Serializable]
public abstract class ApiClientException
: Exception
{
/// <summary>
/// Initialises a new instance of the <see cref="ApiClientException"/> class.
/// Create a new <see cref="ApiClientException"/>.
/// </summary>
/// <param name="messageOrFormat">
/// The exception message or message format.
/// </param>
/// <param name="formatArguments">
/// Optional message format arguments.
/// </param>
protected ApiClientException(string messageOrFormat, params object[] formatArguments)
: base(string.Format(messageOrFormat, formatArguments))
{
}
/// <summary>
/// Initialises a new instance of the <see cref="ApiClientException"/> class.
/// Create a new <see cref="ApiClientException"/>.
/// </summary>
/// <param name="messageOrFormat">
/// The exception message or message format.
/// </param>
/// <param name="innerException">
/// A previous exception that caused the current exception to be raised.
/// </param>
/// <param name="formatArguments">
/// Optional message format arguments.
/// </param>
protected ApiClientException(string messageOrFormat, Exception innerException, params object[] formatArguments)
: base(string.Format(messageOrFormat, formatArguments), innerException)
{
}
/// <summary>
/// Initialises a new instance of the <see cref="ApiClientException"/> class.
/// Deserialisation constructor for <see cref="ApiClientException"/>.
/// </summary>
/// <param name="info">
/// A <see cref="SerializationInfo"/> serialisation data store that holds the serialized exception data.
/// </param>
/// <param name="context">
/// A <see cref="StreamingContext"/> value that indicates the source of the serialised data.
/// </param>
/// <exception cref="ArgumentNullException">
/// The <paramref name="info"/> parameter is null.
/// </exception>
/// <exception cref="SerializationException">
/// The class name is <c>null</c> or <see cref="Exception.HResult"/> is zero (0).
/// </exception>
protected ApiClientException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
} | mit | C# |
e9224a37e97215e1d20b0d1a04a28f488716a798 | Fix typos in BaseAuthentication. | Alan-Lun/git-p3 | Microsoft.TeamFoundation.Authentication/BaseAuthentication.cs | Microsoft.TeamFoundation.Authentication/BaseAuthentication.cs | using System;
namespace Microsoft.TeamFoundation.Authentication
{
/// <summary>
/// Base authentication mechanisms for setting, retrieving, and deleting stored credentials.
/// </summary>
public abstract class BaseAuthentication : IAuthentication
{
/// <summary>
/// Deletes a <see cref="Credential"/> from the storage used by the authentication object.
/// </summary>
/// <param name="targetUri">
/// The uniform resource indicator used to uniquely identify the credentials.
/// </param>
public abstract void DeleteCredentials(Uri targetUri);
/// <summary>
/// Gets a <see cref="Credential"/> from the storage used by the authentication object.
/// </summary>
/// <param name="targetUri">
/// The uniform resource indicator used to uniquely identify the credentials.
/// </param>
/// <param name="credentials">
/// If successful a <see cref="Credential"/> object from the authentication object,
/// authority or storage; otherwise <see langword="null"/>.
/// </param>
/// <returns><see langword="true"/> if successful; otherwise <see langword="false"/>.</returns>
public abstract bool GetCredentials(Uri targetUri, out Credential credentials);
/// <summary>
/// Sets a <see cref="Credential"/> in the storage used by the authentication object.
/// </summary>
/// <param name="targetUri">
/// The uniform resource indicator used to uniquely identify the credentials.
/// </param>
/// <param name="credentials">The value to be stored.</param>
/// <returns><see langword="true"/> if successful; otherwise <see langword="false"/>.</returns>
public abstract bool SetCredentials(Uri targetUri, Credential credentials);
}
}
| using System;
namespace Microsoft.TeamFoundation.Authentication
{
/// <summary>
/// Base authentication mechanisms for setting, retrieving, and deleting stored credentials.
/// </summary>
public abstract class BaseAuthentication : IAuthentication
{
/// <summary>
/// Deletes a <see cref="Credential"/> from the storage used by the authentication object.
/// </summary>
/// <param name="targetUri">
/// The uniform resource indicator used to uniquely identitfy the credentials.
/// </param>
public abstract void DeleteCredentials(Uri targetUri);
/// <summary>
/// Gets a <see cref="Credential"/> from the storage used by the authentication object.
/// </summary>
/// <param name="targetUri">
/// The uniform resource indicator used to uniquely identitfy the credentials.
/// </param>
/// <param name="credentials">
/// If successful a <see cref="Credential"/> object from the authentication object,
/// authority or storage; otherwise `null`.
/// </param>
/// <returns>True if successful; otherwise false.</returns>
public abstract bool GetCredentials(Uri targetUri, out Credential credentials);
/// <summary>
/// Sets a <see cref="Credential"/> in the storage used by the authentication object.
/// </summary>
/// <param name="targetUri">
/// The uniform resource indicator used to uniquely identitfy the credentials.
/// </param>
/// <param name="credentials">The value to be stored.</param>
/// <returns>True if successful; otherwise false.</returns>
public abstract bool SetCredentials(Uri targetUri, Credential credentials);
}
}
| mit | C# |
1fab6f7867260877d3a0e908e4a170eb36e3cf2e | Mark IItemStatus as obsolete (#6914) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Client/Items/Components/IItemStatus.cs | Content.Client/Items/Components/IItemStatus.cs | using Robust.Client.UserInterface;
namespace Content.Client.Items.Components
{
/// <summary>
/// Allows a component to provide status tooltips next to the hands interface.
/// </summary>
public interface IItemStatus
{
/// <summary>
/// Called to get a control that represents the status for this component.
/// </summary>
/// <returns>
/// The control to render as status.
/// </returns>
[Obsolete("Use ItemStatusCollectMessage")]
public Control MakeControl();
/// <summary>
/// Called when the item no longer needs this status (say, dropped from hand)
/// </summary>
/// <remarks>
/// <para>
/// Useful to allow you to drop the control for the GC, if you need to.
/// </para>
/// <para>
/// Note that this may be called after a second invocation of <see cref="MakeControl"/> (for example if the user switches the item between two hands).
/// </para>
/// </remarks>
[Obsolete("Use ItemStatusCollectMessage")]
public void DestroyControl(Control control)
{
}
}
}
| using Robust.Client.UserInterface;
namespace Content.Client.Items.Components
{
/// <summary>
/// Allows a component to provide status tooltips next to the hands interface.
/// </summary>
public interface IItemStatus
{
/// <summary>
/// Called to get a control that represents the status for this component.
/// </summary>
/// <returns>
/// The control to render as status.
/// </returns>
public Control MakeControl();
/// <summary>
/// Called when the item no longer needs this status (say, dropped from hand)
/// </summary>
/// <remarks>
/// <para>
/// Useful to allow you to drop the control for the GC, if you need to.
/// </para>
/// <para>
/// Note that this may be called after a second invocation of <see cref="MakeControl"/> (for example if the user switches the item between two hands).
/// </para>
/// </remarks>
public void DestroyControl(Control control)
{
}
}
}
| mit | C# |
eb10849010bd75e3fdeb73ad5c7a3e390dd6a7d1 | fix wrong product header section | Kentico/cloud-sample-app-net,Kentico/cloud-sample-app-net,Kentico/Deliver-Dancing-Goat-.NET-MVC,Kentico/Deliver-Dancing-Goat-.NET-MVC,Kentico/cloud-sample-app-net | DancingGoat/Views/Shared/_ProductLayout.cshtml | DancingGoat/Views/Shared/_ProductLayout.cshtml | @using Kentico.Kontent.Delivery
@model DancingGoat.Models.IProduct
@inject IConfiguration Configuration
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = Model.ProductProductName;
}
<section title="headers" id="head">
@await Html.PartialAsync("HeadersMetadata", Model)
</section>
<article class="product-detail">
<div class="row">
<div class="col-md-12">
<header>
<h2>@Html.DisplayFor(vm => vm.ProductProductName)</h2>
</header>
</div>
</div>
<div class="row-fluid">
<div class="col-lg-7 col-md-6">
<figure class="image">
@Html.AssetImage(Configuration, Model.ProductImage.FirstOrDefault())
</figure>
<div class="description">
@Html.Raw(string.Join("\n", Model.ProductShortDescription?.Blocks ?? (Model.ProductLongDescription?.Blocks ?? Enumerable.Empty<IRichTextBlock>())))
@RenderSection("ProductSpecificProperties", false)
</div>
</div>
@RenderSection("ProductSpecificForm", false)
</div>
</article>
@section Scripts
{
@RenderSection("Scripts", false)
} | @using Kentico.Kontent.Delivery
@model DancingGoat.Models.IProduct
@inject IConfiguration Configuration
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = Model.ProductProductName;
}
<section title="headers" id="head"></section>
@await Html.PartialAsync("HeadersMetadata", Model)
}
<article class="product-detail">
<div class="row">
<div class="col-md-12">
<header>
<h2>@Html.DisplayFor(vm => vm.ProductProductName)</h2>
</header>
</div>
</div>
<div class="row-fluid">
<div class="col-lg-7 col-md-6">
<figure class="image">
@Html.AssetImage(Configuration, Model.ProductImage.FirstOrDefault())
</figure>
<div class="description">
@Html.Raw(string.Join("\n", Model.ProductShortDescription?.Blocks ?? (Model.ProductLongDescription?.Blocks ?? Enumerable.Empty<IRichTextBlock>())))
@RenderSection("ProductSpecificProperties", false)
</div>
</div>
@RenderSection("ProductSpecificForm", false)
</div>
</article>
@section Scripts
{
@RenderSection("Scripts", false)
} | mit | C# |
3c1c93009e67066d849de41308dab0da74e8542f | Initialize Android Correctly | charlenni/Mapsui,charlenni/Mapsui | Samples/Mapsui.Samples.Maui/Platforms/Android/MainActivity.cs | Samples/Mapsui.Samples.Maui/Platforms/Android/MainActivity.cs | using Android.App;
using Android.Content.PM;
using Microsoft.Maui;
namespace Mapsui.Samples.Maui
{
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
public class MainActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Platform.Init(this, savedInstanceState);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
} | using Android.App;
using Android.Content.PM;
using Microsoft.Maui;
namespace Mapsui.Samples.Maui
{
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
public class MainActivity : MauiAppCompatActivity
{
}
} | mit | C# |
53734a39359930f4a53b6e5498cb8a7f4bcf0f31 | Update ColorsAndPalette.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Formatting/ColorsAndPalette.cs | Examples/CSharp/Formatting/ColorsAndPalette.cs | using System.IO;
using Aspose.Cells;
using System.Drawing;
namespace Aspose.Cells.Examples.Formatting
{
public class ColorsAndPalette
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiating an Workbook object
Workbook workbook = new Workbook();
//Adding Orchid color to the palette at 55th index
workbook.ChangePalette(Color.Orchid, 55);
//Adding a new worksheet to the Excel object
int i = workbook.Worksheets.Add();
//Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[i];
//Accessing the "A1" cell from the worksheet
Cell cell = worksheet.Cells["A1"];
//Adding some value to the "A1" cell
cell.PutValue("Hello Aspose!");
//Defining new Style object
Style styleObject = workbook.Styles[workbook.Styles.Add()];
//Setting the Orchid (custom) color to the font
styleObject.Font.Color = Color.Orchid;
//Applying the style to the cell
cell.SetStyle(styleObject);
//Saving the Excel file
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Auto);
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using System.Drawing;
namespace Aspose.Cells.Examples.Formatting
{
public class ColorsAndPalette
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiating an Workbook object
Workbook workbook = new Workbook();
//Adding Orchid color to the palette at 55th index
workbook.ChangePalette(Color.Orchid, 55);
//Adding a new worksheet to the Excel object
int i = workbook.Worksheets.Add();
//Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[i];
//Accessing the "A1" cell from the worksheet
Cell cell = worksheet.Cells["A1"];
//Adding some value to the "A1" cell
cell.PutValue("Hello Aspose!");
//Defining new Style object
Style styleObject = workbook.Styles[workbook.Styles.Add()];
//Setting the Orchid (custom) color to the font
styleObject.Font.Color = Color.Orchid;
//Applying the style to the cell
cell.SetStyle(styleObject);
//Saving the Excel file
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Auto);
}
}
} | mit | C# |
5e97d1b9ca468008bc338da84c47baa85eaf8697 | replace XPathSelect by a PCL version of code | g0rdan/EpubReader.Cross | Source/VersFx.Formats.Text.Epub/Readers/RootFilePathReader.cs | Source/VersFx.Formats.Text.Epub/Readers/RootFilePathReader.cs | using System;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
using System.Xml.Linq;
using VersFx.Formats.Text.Epub.Utils;
namespace VersFx.Formats.Text.Epub.Readers
{
internal static class RootFilePathReader
{
public static async Task<string> GetRootFilePathAsync(ZipArchive epubArchive)
{
const string EPUB_CONTAINER_FILE_PATH = "META-INF/container.xml";
ZipArchiveEntry containerFileEntry = epubArchive.GetEntry(EPUB_CONTAINER_FILE_PATH);
if (containerFileEntry == null)
throw new Exception(String.Format("EPUB parsing error: {0} file not found in archive.", EPUB_CONTAINER_FILE_PATH));
XDocument containerDocument;
using (Stream containerStream = containerFileEntry.Open())
containerDocument = await XmlUtils.LoadDocumentAsync(containerStream).ConfigureAwait(false);
var rootFileNode = ((containerDocument.Root.FirstNode as XContainer).FirstNode as XContainer);
return (rootFileNode as XElement).FirstAttribute.Value;
}
}
}
| using System;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using VersFx.Formats.Text.Epub.Utils;
namespace VersFx.Formats.Text.Epub.Readers
{
internal static class RootFilePathReader
{
public static async Task<string> GetRootFilePathAsync(ZipArchive epubArchive)
{
const string EPUB_CONTAINER_FILE_PATH = "META-INF/container.xml";
ZipArchiveEntry containerFileEntry = epubArchive.GetEntry(EPUB_CONTAINER_FILE_PATH);
if (containerFileEntry == null)
throw new Exception(String.Format("EPUB parsing error: {0} file not found in archive.", EPUB_CONTAINER_FILE_PATH));
XDocument containerDocument;
using (Stream containerStream = containerFileEntry.Open())
containerDocument = await XmlUtils.LoadDocumentAsync(containerStream).ConfigureAwait(false);
XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(new NameTable());
xmlNamespaceManager.AddNamespace("cns", "urn:oasis:names:tc:opendocument:xmlns:container");
XElement rootFileNode = containerDocument.Root;
//TODO need investigate what I have to do there for corrent replcacing
// old line: XElement rootFileNode = containerDocument.Root.XPathSelectElement("/cns:container/cns:rootfiles/cns:rootfile", xmlNamespaceManager);
return rootFileNode.Attribute("full-path").Value;
}
}
}
| unlicense | C# |
55ece37a0300b1c35cd4f9dd0a3a329db91b7e41 | Fix JobHandlerTypeSerializerTest | InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform | InfinniPlatform.Scheduler.Tests/Common/JobHandlerTypeSerializerTest.cs | InfinniPlatform.Scheduler.Tests/Common/JobHandlerTypeSerializerTest.cs | using System;
using System.Threading.Tasks;
using InfinniPlatform.IoC;
using InfinniPlatform.Tests;
using Moq;
using NUnit.Framework;
namespace InfinniPlatform.Scheduler.Common
{
[TestFixture(Category = TestCategories.UnitTest)]
public class JobHandlerTypeSerializerTest
{
private const string HandlerType = "InfinniPlatform.SchedulerCommon.JobHandlerTypeSerializerTest+MyJobHandler,InfinniPlatform.Scheduler.Tests";
[Test]
public void ShouldCheckIfCanSerialize()
{
// Given
var resolver = new Mock<IContainerResolver>();
resolver.Setup(i => i.Services).Returns(new[] { typeof(MyJobHandler) });
var target = new JobHandlerTypeSerializer(resolver.Object);
// When
var result1 = target.CanSerialize(typeof(MyJobHandler));
var result2 = target.CanSerialize(typeof(JobHandlerTypeSerializerTest));
// Then
Assert.IsTrue(result1);
Assert.IsFalse(result2);
}
[Test]
public void ShouldSerialize()
{
// Given
var resolver = new Mock<IContainerResolver>();
var target = new JobHandlerTypeSerializer(resolver.Object);
// When
var result = target.Serialize(typeof(MyJobHandler));
// Then
Assert.AreEqual(HandlerType, result);
}
[Test]
public void ShouldDeserialize()
{
// Given
var resolver = new Mock<IContainerResolver>();
resolver.Setup(i => i.Services).Returns(new[] { typeof(MyJobHandler) });
resolver.Setup(i => i.Resolve(typeof(MyJobHandler))).Returns(new MyJobHandler());
var target = new JobHandlerTypeSerializer(resolver.Object);
// When
var result = target.Deserialize(HandlerType);
// Then
Assert.IsInstanceOf<MyJobHandler>(result);
}
private class MyJobHandler : IJobHandler
{
public Task Handle(IJobInfo jobInfo, IJobHandlerContext context)
{
throw new NotImplementedException();
}
}
}
} | using System;
using System.Threading.Tasks;
using InfinniPlatform.IoC;
using InfinniPlatform.Tests;
using Moq;
using NUnit.Framework;
namespace InfinniPlatform.Scheduler.Common
{
[TestFixture(Category = TestCategories.UnitTest)]
public class JobHandlerTypeSerializerTest
{
private const string HandlerType = "InfinniPlatform.Scheduler.Tests.Common.JobHandlerTypeSerializerTest+MyJobHandler,InfinniPlatform.Scheduler.Tests";
[Test]
public void ShouldCheckIfCanSerialize()
{
// Given
var resolver = new Mock<IContainerResolver>();
resolver.Setup(i => i.Services).Returns(new[] { typeof(MyJobHandler) });
var target = new JobHandlerTypeSerializer(resolver.Object);
// When
var result1 = target.CanSerialize(typeof(MyJobHandler));
var result2 = target.CanSerialize(typeof(JobHandlerTypeSerializerTest));
// Then
Assert.IsTrue(result1);
Assert.IsFalse(result2);
}
[Test]
public void ShouldSerialize()
{
// Given
var resolver = new Mock<IContainerResolver>();
var target = new JobHandlerTypeSerializer(resolver.Object);
// When
var result = target.Serialize(typeof(MyJobHandler));
// Then
Assert.AreEqual(HandlerType, result);
}
[Test]
public void ShouldDeserialize()
{
// Given
var resolver = new Mock<IContainerResolver>();
resolver.Setup(i => i.Services).Returns(new[] { typeof(MyJobHandler) });
resolver.Setup(i => i.Resolve(typeof(MyJobHandler))).Returns(new MyJobHandler());
var target = new JobHandlerTypeSerializer(resolver.Object);
// When
var result = target.Deserialize(HandlerType);
// Then
Assert.IsInstanceOf<MyJobHandler>(result);
}
private class MyJobHandler : IJobHandler
{
public Task Handle(IJobInfo jobInfo, IJobHandlerContext context)
{
throw new NotImplementedException();
}
}
}
} | agpl-3.0 | C# |
90efd4ae95872fe3b9e2d4cc0d9dca4d4cc61d44 | Fix nullability. | ExRam/ExRam.Gremlinq | src/ExRam.Gremlinq.Providers.WebSocket/GremlinClientFactory.cs | src/ExRam.Gremlinq.Providers.WebSocket/GremlinClientFactory.cs | using System;
using System.Net.WebSockets;
using Gremlin.Net.Driver;
namespace ExRam.Gremlinq.Providers.WebSocket
{
public static class GremlinClientFactory
{
private sealed class DefaultGremlinClientFactory : IGremlinClientFactory
{
public IGremlinClient Create(GremlinServer gremlinServer, IMessageSerializer messageSerializer, ConnectionPoolSettings connectionPoolSettings, Action<ClientWebSocketOptions> webSocketConfiguration, string? sessionId = null)
{
return new GremlinClient(
gremlinServer,
messageSerializer,
connectionPoolSettings,
webSocketConfiguration,
sessionId);
}
}
private sealed class FuncGremlinClientFactory : IGremlinClientFactory
{
private readonly Func<GremlinServer, IMessageSerializer, ConnectionPoolSettings, Action<ClientWebSocketOptions>, string?, IGremlinClient> _factory;
public FuncGremlinClientFactory(Func<GremlinServer, IMessageSerializer, ConnectionPoolSettings, Action<ClientWebSocketOptions>, string?, IGremlinClient> factory)
{
_factory = factory;
}
public IGremlinClient Create(GremlinServer gremlinServer, IMessageSerializer messageSerializer, ConnectionPoolSettings connectionPoolSettings, Action<ClientWebSocketOptions> webSocketConfiguration, string? sessionId = null) => _factory(gremlinServer, messageSerializer, connectionPoolSettings, webSocketConfiguration, sessionId);
}
public static readonly IGremlinClientFactory Default = new DefaultGremlinClientFactory();
public static IGremlinClientFactory Create(Func<GremlinServer, IMessageSerializer, ConnectionPoolSettings, Action<ClientWebSocketOptions>, string?, IGremlinClient> factory) => new FuncGremlinClientFactory(factory);
}
}
| using System;
using System.Net.WebSockets;
using Gremlin.Net.Driver;
namespace ExRam.Gremlinq.Providers.WebSocket
{
public static class GremlinClientFactory
{
private sealed class DefaultGremlinClientFactory : IGremlinClientFactory
{
public IGremlinClient Create(GremlinServer gremlinServer, IMessageSerializer? messageSerializer = null, ConnectionPoolSettings? connectionPoolSettings = null, Action<ClientWebSocketOptions>? webSocketConfiguration = null, string? sessionId = null)
{
return new GremlinClient(
gremlinServer,
messageSerializer,
connectionPoolSettings,
webSocketConfiguration,
sessionId);
}
}
private sealed class FuncGremlinClientFactory : IGremlinClientFactory
{
private readonly Func<GremlinServer, IMessageSerializer, ConnectionPoolSettings, Action<ClientWebSocketOptions>, string?, IGremlinClient> _factory;
public FuncGremlinClientFactory(Func<GremlinServer, IMessageSerializer, ConnectionPoolSettings, Action<ClientWebSocketOptions>, string?, IGremlinClient> factory)
{
_factory = factory;
}
public IGremlinClient Create(GremlinServer gremlinServer, IMessageSerializer messageSerializer, ConnectionPoolSettings connectionPoolSettings, Action<ClientWebSocketOptions> webSocketConfiguration, string? sessionId = null) => _factory(gremlinServer, messageSerializer, connectionPoolSettings, webSocketConfiguration, sessionId);
}
public static readonly IGremlinClientFactory Default = new DefaultGremlinClientFactory();
public static IGremlinClientFactory Create(Func<GremlinServer, IMessageSerializer, ConnectionPoolSettings, Action<ClientWebSocketOptions>, string?, IGremlinClient> factory) => new FuncGremlinClientFactory(factory);
}
}
| mit | C# |
49cafcce6108fa375369dc8f1b2ea93dfd288ef0 | build fix - do not follow redirects when faking transparent redirects. | ronin1/braintree_dotnet,scottmeyer/braintree_dotnet,ronin1/braintree_dotnet,scottmeyer/braintree_dotnet,braintree/braintree_dotnet,scottmeyer/braintree_dotnet,braintree/braintree_dotnet,ronin1/braintree_dotnet,scottmeyer/braintree_dotnet | Braintree.Tests/TestHelper.cs | Braintree.Tests/TestHelper.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using NUnit.Framework;
namespace Braintree.Tests
{
public class TestHelper
{
public static int CompareModificationsById(Modification left, Modification right)
{
return left.Id.CompareTo(right.Id);
}
public static String QueryStringForTR(Request trParams, Request req, String postURL, BraintreeService service)
{
String trData = TrUtil.BuildTrData(trParams, "http://example.com", service);
String postData = "tr_data=" + HttpUtility.UrlEncode(trData, Encoding.UTF8) + "&";
postData += req.ToQueryString();
var request = WebRequest.Create(postURL) as HttpWebRequest;
request.Method = "POST";
request.KeepAlive = false;
request.AllowAutoRedirect = false;
byte[] buffer = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = buffer.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
var response = request.GetResponse() as HttpWebResponse;
String query = new Uri(response.GetResponseHeader("Location")).Query;
response.Close();
return query;
}
public static void AreDatesEqual(DateTime expected, DateTime actual)
{
Assert.AreEqual(expected.Day, actual.Day);
Assert.AreEqual(expected.Month, actual.Month);
Assert.AreEqual(expected.Year, actual.Year);
}
public static void AssertIncludes(String expected, String all)
{
Assert.IsTrue(all.IndexOf(expected) >= 0, "Expected:\n" + all + "\nto include:\n" + expected);
}
public static Boolean IncludesSubscription(ResourceCollection<Subscription> collection, Subscription subscription)
{
foreach (Subscription item in collection)
{
if (item.Id.Equals(subscription.Id)) {
return true;
}
}
return false;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using NUnit.Framework;
namespace Braintree.Tests
{
public class TestHelper
{
public static int CompareModificationsById(Modification left, Modification right)
{
return left.Id.CompareTo(right.Id);
}
public static String QueryStringForTR(Request trParams, Request req, String postURL, BraintreeService service)
{
String trData = TrUtil.BuildTrData(trParams, "http://example.com", service);
String postData = "tr_data=" + HttpUtility.UrlEncode(trData, Encoding.UTF8) + "&";
postData += req.ToQueryString();
var request = WebRequest.Create(postURL) as HttpWebRequest;
request.Method = "POST";
request.KeepAlive = false;
byte[] buffer = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = buffer.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
var response = request.GetResponse() as HttpWebResponse;
String query = response.ResponseUri.Query;
response.Close();
return query;
}
public static void AreDatesEqual(DateTime expected, DateTime actual)
{
Assert.AreEqual(expected.Day, actual.Day);
Assert.AreEqual(expected.Month, actual.Month);
Assert.AreEqual(expected.Year, actual.Year);
}
public static void AssertIncludes(String expected, String all)
{
Assert.IsTrue(all.IndexOf(expected) >= 0, "Expected:\n" + all + "\nto include:\n" + expected);
}
public static Boolean IncludesSubscription(ResourceCollection<Subscription> collection, Subscription subscription)
{
foreach (Subscription item in collection)
{
if (item.Id.Equals(subscription.Id)) {
return true;
}
}
return false;
}
}
}
| mit | C# |
d758e926412eac041f6d214c91486403a2f5ef4c | Update EntityQueryRepository.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/Data/EntityFrameworkCore/EntityQueryRepository.cs | TIKSN.Framework.Core/Data/EntityFrameworkCore/EntityQueryRepository.cs | using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityQueryRepository<TContext, TEntity, TIdentity> : EntityRepository<TContext, TEntity>, IQueryRepository<TEntity, TIdentity>, IStreamRepository<TEntity>
where TContext : DbContext
where TEntity : class, IEntity<TIdentity>, new()
where TIdentity : IEquatable<TIdentity>
{
public EntityQueryRepository(TContext dbContext) : base(dbContext)
{
}
protected IQueryable<TEntity> Entities => dbContext.Set<TEntity>().AsNoTracking();
public Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.AnyAsync(a => a.ID.Equals(id), cancellationToken);
}
public Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.SingleAsync(entity => entity.ID.Equals(id), cancellationToken);
}
public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.SingleOrDefaultAsync(entity => entity.ID.Equals(id), cancellationToken);
}
public async Task<IEnumerable<TEntity>> ListAsync(IEnumerable<TIdentity> ids, CancellationToken cancellationToken)
{
if (ids == null) throw new ArgumentNullException(nameof(ids));
return await Entities.Where(entity => ids.Contains(entity.ID)).ToListAsync(cancellationToken);
}
public async IAsyncEnumerable<TEntity> StreamAllAsync(CancellationToken cancellationToken)
{
await foreach (var entity in Entities.AsAsyncEnumerable().WithCancellation(cancellationToken))
{
yield return entity;
}
}
}
} | using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityQueryRepository<TContext, TEntity, TIdentity> : EntityRepository<TContext, TEntity>, IQueryRepository<TEntity, TIdentity>, IStreamRepository<TEntity>
where TContext : DbContext
where TEntity : class, IEntity<TIdentity>, new()
where TIdentity : IEquatable<TIdentity>
{
public EntityQueryRepository(TContext dbContext) : base(dbContext)
{
}
protected IQueryable<TEntity> Entities => dbContext.Set<TEntity>().AsNoTracking();
public Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.AnyAsync(a => a.ID.Equals(id), cancellationToken);
}
public Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.SingleAsync(entity => entity.ID.Equals(id), cancellationToken);
}
public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.SingleOrDefaultAsync(entity => entity.ID.Equals(id), cancellationToken);
}
public async Task<IEnumerable<TEntity>> ListAsync(IEnumerable<TIdentity> ids, CancellationToken cancellationToken)
{
return await Entities.Where(entity => ids.Contains(entity.ID)).ToListAsync(cancellationToken);
}
public async IAsyncEnumerable<TEntity> StreamAllAsync(CancellationToken cancellationToken)
{
await foreach (var entity in Entities.AsAsyncEnumerable().WithCancellation(cancellationToken))
{
yield return entity;
}
}
}
} | mit | C# |
8d7288dfb3bc49165f2ca080d9c5a293215f30d9 | Update LibUsbLeControllerTests.cs | huysentruitw/win-beacon,ghkim69/win-beacon | test/WinBeacon.Tests/LibUsbLeControllerTests.cs | test/WinBeacon.Tests/LibUsbLeControllerTests.cs | /*
* Copyright 2015 Huysentruit Wouter
*
* 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.Threading;
using NUnit.Framework;
using WinBeacon.Stack.Controllers;
namespace WinBeacon.Tests
{
[TestFixture]
public class LibUsbLeControllerTests
{
private const int vid = 0x050D;
private const int pid = 0x065A;
/// <summary>
/// This is a live test that needs some pre-requisites:
/// * A BLE compatible dongle with WinUSB driver
/// * The correct vid and pid combination in the consts above
/// * A beacon that broadcasts at minimum 2Hz rate (iPad users can use the BLEBeacon app to advertise as a beacon)
/// </summary>
[Test]
[Ignore]
public void LibUsbLeController_WaitForLeMetaEvent()
{
var leMetaEventReceived = false;
using (var controller = new LibUsbLeController(vid, pid))
{
controller.Open();
controller.EnableScanning();
controller.LeMetaEventReceived += (sender, e) =>
{
if (e.LeMetaEvent.Code == Stack.Hci.EventCode.LeMeta)
leMetaEventReceived = true;
};
Thread.Sleep(1 * 1000);
}
Assert.IsTrue(leMetaEventReceived, "No meta event received");
}
}
}
| /*
* Copyright 2015 Huysentruit Wouter
*
* 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.Threading;
using NUnit.Framework;
using WinBeacon.Stack.Controllers;
namespace WinBeacon.Tests
{
[TestFixture]
public class LibUsbLeControllerTests
{
private const int vid = 0x050D;
private const int pid = 0x065A;
/// <summary>
/// This is a live test that needs some pre-requisites:
/// * A BLE compatible dongle with WinUSB driver
/// * The correct vid & pid combination in the consts above
/// * A beacon that broadcasts at minimum 2Hz rate (iPad users can use the BLEBeacon app to advertise as a beacon)
/// </summary>
[Test]
[Ignore]
public void LibUsbLeController_WaitForLeMetaEvent()
{
var leMetaEventReceived = false;
using (var controller = new LibUsbLeController(vid, pid))
{
controller.Open();
controller.EnableScanning();
controller.LeMetaEventReceived += (sender, e) =>
{
if (e.LeMetaEvent.Code == Stack.Hci.EventCode.LeMeta)
leMetaEventReceived = true;
};
Thread.Sleep(1 * 1000);
}
Assert.IsTrue(leMetaEventReceived, "No meta event received");
}
}
}
| mit | C# |
3b3f4c5fb0218cbd14c2fe523c8a4903613fb93b | Change the target to get working on build server | rcasady616/Selenium.WeDriver.Equip,rcasady616/Selenium.WeDriver.Equip | SeleniumExtension/SauceLabs/SauceDriverKeys.cs | SeleniumExtension/SauceLabs/SauceDriverKeys.cs | using System;
namespace SeleniumExtension.SauceLabs
{
public class SauceDriverKeys
{
public static string SAUCELABS_USERNAME
{
get
{
var userName = Environment.GetEnvironmentVariable("SAUCELABS_USERNAME");
if(string.IsNullOrEmpty(userName))
throw new Exception("Missing environment variable, name: SAUCELABS_USERNAME");
return userName;
}
}
public static string SAUCELABS_ACCESSKEY
{
get
{
var userName = Environment.GetEnvironmentVariable("SAUCELABS_ACCESSKEY");
if (string.IsNullOrEmpty(userName))
throw new Exception("Missing environment variable, name: SAUCELABS_ACCESSKEY");
return userName;
}
}
}
}
| using System;
namespace SeleniumExtension.SauceLabs
{
public class SauceDriverKeys
{
public static string SAUCELABS_USERNAME
{
get
{
var userName = Environment.GetEnvironmentVariable("SAUCELABS_USERNAME", EnvironmentVariableTarget.User);
if(string.IsNullOrEmpty(userName))
throw new Exception("Missing environment variable, name: SAUCELABS_USERNAME");
return userName;
}
}
public static string SAUCELABS_ACCESSKEY
{
get
{
var userName = Environment.GetEnvironmentVariable("SAUCELABS_ACCESSKEY", EnvironmentVariableTarget.User);
if (string.IsNullOrEmpty(userName))
throw new Exception("Missing environment variable, name: SAUCELABS_ACCESSKEY");
return userName;
}
}
}
}
| mit | C# |
70d85f2e3ba5ced804330586c90bc5d733e2479f | test 'getLatestEvents' | Pondidum/Ledger,Pondidum/Ledger | Ledger.Stores.Fs.Tests/EventSaveLoadTests.cs | Ledger.Stores.Fs.Tests/EventSaveLoadTests.cs | using System;
using System.IO;
using System.Linq;
using NSubstitute;
using Shouldly;
using TestsDomain.Events;
using Xunit;
namespace Ledger.Stores.Fs.Tests
{
public class EventSaveLoadTests : IDisposable
{
private readonly string _root;
public EventSaveLoadTests()
{
_root = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(_root);
}
[Fact]
public void The_events_should_keep_types()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll {NewName = "Deed"},
new FixNameSpelling {NewName = "Fix"},
};
var id = Guid.NewGuid();
var store = new FileEventStore(_root);
store.SaveEvents(id, toSave);
var loaded = store.LoadEvents(id);
loaded.First().ShouldBeOfType<NameChangedByDeedPoll>();
loaded.Last().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_events_for_the_correct_aggregate_are_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
var store = new FileEventStore(_root);
store.SaveEvents(first, new[] { new FixNameSpelling { NewName = "Fix" } });
store.SaveEvents(second, new[] { new NameChangedByDeedPoll { NewName = "Deed" } });
var loaded = store.LoadEvents(first);
loaded.Single().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_the_latest_sequence_is_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
var store = new FileEventStore(_root);
store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 4 } });
store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 5 } });
store.SaveEvents(second, new[] { new NameChangedByDeedPoll { SequenceID = 6 } });
store
.GetLatestSequenceFor(first)
.ShouldBe(5);
}
[Fact]
public void Loading_events_since_only_gets_events_after_the_sequence()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll { SequenceID = 3 },
new FixNameSpelling { SequenceID = 4 },
new FixNameSpelling { SequenceID = 5 },
new FixNameSpelling { SequenceID = 6 },
};
var id = Guid.NewGuid();
var store = new FileEventStore(_root);
store.SaveEvents(id, toSave);
var loaded = store.LoadEventsSince(id, 4);
loaded.Select(x => x.SequenceID).ShouldBe(new[] { 5, 6 });
}
public void Dispose()
{
try
{
Directory.Delete(_root, true);
}
catch (Exception)
{
}
}
}
}
| using System;
using System.IO;
using System.Linq;
using NSubstitute;
using Shouldly;
using TestsDomain.Events;
using Xunit;
namespace Ledger.Stores.Fs.Tests
{
public class EventSaveLoadTests : IDisposable
{
private readonly string _root;
public EventSaveLoadTests()
{
_root = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(_root);
}
[Fact]
public void The_events_should_keep_types()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll {NewName = "Deed"},
new FixNameSpelling {NewName = "Fix"},
};
var id = Guid.NewGuid();
var store = new FileEventStore(_root);
store.SaveEvents(id, toSave);
var loaded = store.LoadEvents(id);
loaded.First().ShouldBeOfType<NameChangedByDeedPoll>();
loaded.Last().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_events_for_the_correct_aggregate_are_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
var store = new FileEventStore(_root);
store.SaveEvents(first, new[] { new FixNameSpelling { NewName = "Fix" } });
store.SaveEvents(second, new[] { new NameChangedByDeedPoll { NewName = "Deed" } });
var loaded = store.LoadEvents(first);
loaded.Single().ShouldBeOfType<FixNameSpelling>();
}
public void Dispose()
{
try
{
Directory.Delete(_root, true);
}
catch (Exception)
{
}
}
}
}
| lgpl-2.1 | C# |
818d313247cf1fbab940ce6cf6f052454794a8f2 | Use extension method on MessageContext instead of helper class | BizTalkComponents/CopyContextProperty | Src/CopyContextProperty/CopyContextProperty.cs | Src/CopyContextProperty/CopyContextProperty.cs | using BizTalkComponents.Utils.ContextPropertyHelpers;
using BizTalkComponents.Utils.PropertyBagHelpers;
using Microsoft.BizTalk.Component.Interop;
using Microsoft.BizTalk.Message.Interop;
namespace BizTalkComponents.PipelineComponents.CopyContextProperty
{
[ComponentCategory(CategoryTypes.CATID_PipelineComponent)]
[System.Runtime.InteropServices.Guid("98EB6BA0-4FBC-44C5-8A53-A7D37C46A396")]
[ComponentCategory(CategoryTypes.CATID_Any)]
public partial class CopyContextProperty : IComponent, IBaseComponent,
IPersistPropertyBag, IComponentUI
{
private const string SourcePropertyName = "SourceProperty";
private const string DestinationPropertyName = "DestinationPropertyName";
public string SourceProperty { get; set; }
public string DestinationProperty { get; set; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
{
var sourceContextProperty = new ContextProperty(SourceProperty);
var destinationContextProperty = new ContextProperty(DestinationProperty);
pInMsg.Context.Copy(sourceContextProperty, destinationContextProperty);
return pInMsg;
}
public void Load(IPropertyBag propertyBag, int errorLog)
{
if (string.IsNullOrEmpty(SourceProperty))
{
SourceProperty = PropertyBagHelper.ToStringOrDefault(PropertyBagHelper.ReadPropertyBag(propertyBag, SourcePropertyName), string.Empty);
}
if (string.IsNullOrEmpty(DestinationProperty))
{
DestinationProperty = PropertyBagHelper.ToStringOrDefault(PropertyBagHelper.ReadPropertyBag(propertyBag, DestinationPropertyName), string.Empty);
}
}
public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
{
PropertyBagHelper.WritePropertyBag(propertyBag, SourcePropertyName, SourceProperty);
PropertyBagHelper.WritePropertyBag(propertyBag, DestinationPropertyName, DestinationProperty);
}
}
}
| using BizTalkComponents.Utils.ContextPropertyHelpers;
using BizTalkComponents.Utils.PropertyBagHelpers;
using Microsoft.BizTalk.Component.Interop;
using Microsoft.BizTalk.Message.Interop;
namespace BizTalkComponents.PipelineComponents.CopyContextProperty
{
[ComponentCategory(CategoryTypes.CATID_PipelineComponent)]
[System.Runtime.InteropServices.Guid("98EB6BA0-4FBC-44C5-8A53-A7D37C46A396")]
[ComponentCategory(CategoryTypes.CATID_Any)]
public partial class CopyContextProperty : IComponent, IBaseComponent,
IPersistPropertyBag, IComponentUI
{
private const string SourcePropertyName = "SourceProperty";
private const string DestinationPropertyName = "DestinationPropertyName";
public string SourceProperty { get; set; }
public string DestinationProperty { get; set; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
{
var sourceContextProperty = new ContextProperty(SourceProperty);
var destinationContextProperty = new ContextProperty(DestinationProperty);
ContextPropertyHelper.CopyContextProperty(pInMsg, sourceContextProperty, destinationContextProperty);
return pInMsg;
}
public void Load(IPropertyBag propertyBag, int errorLog)
{
if (string.IsNullOrEmpty(SourceProperty))
{
SourceProperty = PropertyBagHelper.ToStringOrDefault(PropertyBagHelper.ReadPropertyBag(propertyBag, SourcePropertyName), string.Empty);
}
if (string.IsNullOrEmpty(DestinationProperty))
{
DestinationProperty = PropertyBagHelper.ToStringOrDefault(PropertyBagHelper.ReadPropertyBag(propertyBag, DestinationPropertyName), string.Empty);
}
}
public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
{
PropertyBagHelper.WritePropertyBag(propertyBag, SourcePropertyName, SourceProperty);
PropertyBagHelper.WritePropertyBag(propertyBag, DestinationPropertyName, DestinationProperty);
}
}
}
| mit | C# |
3fa0c5723a64ce6ec994b48a1cd375103eea6b18 | Write logs to console only in case of error | repometric/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli,binore/linterhub-cli | src/Metrics.Integrations.Linters.Cli/LogManager.cs | src/Metrics.Integrations.Linters.Cli/LogManager.cs | namespace Metrics.Integrations.Linters
{
using System;
using System.IO;
using System.Text;
// TODO: Improve logging.
public class LogManager : IDisposable
{
public StringBuilder LogWriter { get; }
private bool saved = false;
private bool error = false;
public LogManager()
{
LogWriter = new StringBuilder();
}
public void Log(string format, params object[] args)
{
LogWriter.AppendLine(string.Format(format, args));
}
public void Trace(string message, params object[] args)
{
Log("TRACE: " + message + " {0}", string.Join(" ", args));
}
public void Error(string message, params object[] args)
{
error = true;
Log("ERROR: " + message + " {0}", string.Join(" ", args));
System.Console.Error.WriteLine(string.Format(message + " {0}", string.Join(" ", args)));
}
public void Save(string fileName)
{
saved = true;
File.WriteAllText(fileName, LogWriter.ToString());
}
public void Dispose()
{
if (!saved && error)
{
System.Console.Write(LogWriter.ToString());
}
}
}
} | namespace Metrics.Integrations.Linters
{
using System;
using System.IO;
using System.Text;
// TODO: Improve logging.
public class LogManager : IDisposable
{
public StringBuilder LogWriter { get; }
private bool saved = false;
public LogManager()
{
LogWriter = new StringBuilder();
}
public void Log(string format, params object[] args)
{
LogWriter.AppendLine(string.Format(format, args));
}
public void Trace(string message, params object[] args)
{
Log("TRACE: " + message + " {0}", string.Join(" ", args));
}
public void Error(string message, params object[] args)
{
Log("ERROR: " + message + " {0}", string.Join(" ", args));
System.Console.Error.WriteLine(string.Format(message + " {0}", string.Join(" ", args)));
}
public void Save(string fileName)
{
saved = true;
File.WriteAllText(fileName, LogWriter.ToString());
}
public void Dispose()
{
if (!saved)
{
System.Console.Write(LogWriter.ToString());
}
}
}
} | mit | C# |
6b1eaa62fab3103e55e8721ffaefca302bf637c4 | test setup fix | yetanotherchris/Remy | src/Remy.Tests/Unit/Core/Tasks/TypeManagerTests.cs | src/Remy.Tests/Unit/Core/Tasks/TypeManagerTests.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Remy.Core.Tasks;
using Remy.Tests.StubsAndMocks;
using Serilog;
namespace Remy.Tests.Unit.Core.Tasks
{
[TestFixture]
public class TypeManagerTests
{
private ILogger _logger;
private string _currentDir;
private string _pluginsDirectory;
[SetUp]
public void Setup()
{
_logger = new LoggerConfiguration()
.WriteTo
.LiterateConsole()
.CreateLogger();
_currentDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
_pluginsDirectory = Path.Combine(_currentDir, "plugins");
if (Directory.Exists(_pluginsDirectory))
Directory.Delete(_pluginsDirectory, true);
else
Directory.CreateDirectory(_pluginsDirectory);
}
[TearDown]
public void TearDown()
{
try
{
Directory.Delete(_pluginsDirectory, true);
}
catch
{
}
}
[Test]
public void should_return_all_itasks_and_register_yamlname_for_keys()
{
// given + when
Dictionary<string, ITask> tasks = TypeManager.GetRegisteredTaskInstances(_logger);
// then
Assert.That(tasks.Count, Is.EqualTo(4));
KeyValuePair<string, ITask> task = tasks.First();
Assert.That(task.Value, Is.Not.Null);
Assert.That(task.Key, Is.EqualTo(task.Value.YamlName));
}
[Test]
public void should_add_tasks_from_plugins_directory()
{
// given - copy MockTask (Remy.tests.dll) into plugins/
string nugetFolder = Path.Combine(_pluginsDirectory, "Remy.tests", "lib", "net461");
Directory.CreateDirectory(nugetFolder);
File.Copy(Path.Combine(_currentDir, "Remy.tests.dll"), Path.Combine(nugetFolder, "Remy.tests.dll"));
// when
Dictionary<string, ITask> tasks = TypeManager.GetRegisteredTaskInstances(_logger);
// then
Assert.That(tasks.Count, Is.EqualTo(5));
KeyValuePair<string, ITask> task = tasks.FirstOrDefault(x => x.Key == "mock-task");
Assert.That(task, Is.Not.Null);
Assert.That(task.Key, Is.EqualTo(task.Value.YamlName));
Assert.That(task.Value, Is.Not.Null);
Assert.That(task.Value.GetType().Name, Is.EqualTo(typeof(MockTask).Name));
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Remy.Core.Tasks;
using Remy.Tests.StubsAndMocks;
using Serilog;
namespace Remy.Tests.Unit.Core.Tasks
{
[TestFixture]
public class TypeManagerTests
{
private ILogger _logger;
private string _currentDir;
private string _pluginsDirectory;
[SetUp]
public void Setup()
{
_logger = new LoggerConfiguration()
.WriteTo
.LiterateConsole()
.CreateLogger();
_currentDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
_pluginsDirectory = Path.Combine(_currentDir, "plugins");
if (Directory.Exists(_pluginsDirectory))
Directory.Delete(_pluginsDirectory, true);
Directory.CreateDirectory(_pluginsDirectory);
}
[TearDown]
public void TearDown()
{
try
{
Directory.Delete(_pluginsDirectory, true);
}
catch
{
}
}
[Test]
public void should_return_all_itasks_and_register_yamlname_for_keys()
{
// given + when
Dictionary<string, ITask> tasks = TypeManager.GetRegisteredTaskInstances(_logger);
// then
Assert.That(tasks.Count, Is.EqualTo(4));
KeyValuePair<string, ITask> task = tasks.First();
Assert.That(task.Value, Is.Not.Null);
Assert.That(task.Key, Is.EqualTo(task.Value.YamlName));
}
[Test]
public void should_add_tasks_from_plugins_directory()
{
// given - copy MockTask (Remy.tests.dll) into plugins/
string nugetFolder = Path.Combine(_pluginsDirectory, "Remy.tests", "lib", "net461");
Directory.CreateDirectory(nugetFolder);
File.Copy(Path.Combine(_currentDir, "Remy.tests.dll"), Path.Combine(nugetFolder, "Remy.tests.dll"));
// when
Dictionary<string, ITask> tasks = TypeManager.GetRegisteredTaskInstances(_logger);
// then
Assert.That(tasks.Count, Is.EqualTo(5));
KeyValuePair<string, ITask> task = tasks.FirstOrDefault(x => x.Key == "mock-task");
Assert.That(task, Is.Not.Null);
Assert.That(task.Key, Is.EqualTo(task.Value.YamlName));
Assert.That(task.Value, Is.Not.Null);
Assert.That(task.Value.GetType().Name, Is.EqualTo(typeof(MockTask).Name));
}
}
} | mit | C# |
6b2d13ede04dfc80feaf4d04543bfc09c5867aac | set internal visiblity to Tests projects | solomobro/Instagram,solomobro/Instagram,solomobro/Instagram | src/Solomobro.Instagram/Properties/AssemblyInfo.cs | src/Solomobro.Instagram/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("Solomobro.Instagram")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Solomobro.Instagram")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Set internals visibility to test proj
[assembly: InternalsVisibleTo("Solomobro.Instagram.Tests")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3a2d6b6b-bb96-4ca4-998c-330fcf1beece")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.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("Solomobro.Instagram")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Solomobro.Instagram")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3a2d6b6b-bb96-4ca4-998c-330fcf1beece")]
// 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# |
824ab3196e49d657d3185e3c65e838af0fbf01f5 | Include request URL in HTTP error message | CalebChalmers/KAGTools | KAGTools/Helpers/ApiHelper.cs | KAGTools/Helpers/ApiHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using KAGTools.Data;
using Newtonsoft.Json;
namespace KAGTools.Helpers
{
public static class ApiHelper
{
private const string UrlPlayer = "https://api.kag2d.com/v1/player/{0}";
private const string UrlServers = "https://api.kag2d.com/v1/game/thd/kag/servers";
private static readonly HttpClient httpClient;
static ApiHelper()
{
httpClient = new HttpClient();
}
public static async Task<ApiPlayerResults> GetPlayer(string username)
{
return await HttpGetApiResult<ApiPlayerResults>(string.Format(UrlPlayer, username));
}
public static async Task<ApiServerResults> GetServers(params ApiFilter[] filters)
{
string filterJson = "?filters=" + JsonConvert.SerializeObject(filters);
return await HttpGetApiResult<ApiServerResults>(UrlServers + filterJson);
}
private static async Task<T> HttpGetApiResult<T>(string requestUri) where T : class
{
try
{
string data = await httpClient.GetStringAsync(requestUri);
return data != null ? JsonConvert.DeserializeObject<T>(data) : null;
}
catch (HttpRequestException e)
{
MessageBox.Show(string.Format("{0}{2}{2}Request URL: {1}", e.Message, requestUri, Environment.NewLine), "HTTP Request Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
return null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using KAGTools.Data;
using Newtonsoft.Json;
namespace KAGTools.Helpers
{
public static class ApiHelper
{
private const string UrlPlayer = "https://api.kag2d.com/v1/player/{0}";
private const string UrlServers = "https://api.kag2d.com/v1/game/thd/kag/servers";
private static readonly HttpClient httpClient;
static ApiHelper()
{
httpClient = new HttpClient();
}
public static async Task<ApiPlayerResults> GetPlayer(string username)
{
return await HttpGetApiResult<ApiPlayerResults>(string.Format(UrlPlayer, username));
}
public static async Task<ApiServerResults> GetServers(params ApiFilter[] filters)
{
string filterJson = "?filters=" + JsonConvert.SerializeObject(filters);
return await HttpGetApiResult<ApiServerResults>(UrlServers + filterJson);
}
private static async Task<T> HttpGetApiResult<T>(string requestUri) where T : class
{
try
{
string data = await httpClient.GetStringAsync(requestUri);
return data != null ? JsonConvert.DeserializeObject<T>(data) : null;
}
catch (HttpRequestException e)
{
MessageBox.Show(e.Message, "HTTP Request Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
return null;
}
}
}
| mit | C# |
d3d1f60303fb72a247edc7d919646cf957b93b5f | fix property name bug | StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis | service/DotNetApis.Structure/AssemblyJson.cs | service/DotNetApis.Structure/AssemblyJson.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetApis.Structure.Entities;
using Newtonsoft.Json;
namespace DotNetApis.Structure
{
/// <summary>
/// Structured documentation for an assembly within a NuGet package.
/// </summary>
public sealed class AssemblyJson
{
/// <summary>
/// The full name of the assembly.
/// </summary>
[JsonProperty("n")]
public string FullName { get; set; }
/// <summary>
/// The path (within the NuGet package) of the assembly.
/// </summary>
[JsonProperty("p")]
public string Path { get; set; }
/// <summary>
/// The size of the assembly, in bytes.
/// </summary>
[JsonProperty("s")]
public long FileLength { get; set; }
/// <summary>
/// Assembly-level attributes.
/// </summary>
[JsonProperty("b")]
public IReadOnlyList<AttributeJson> Attributes { get; set; }
/// <summary>
/// Types defined by this assembly.
/// </summary>
[JsonProperty("t")]
public IReadOnlyList<IEntity> Types { get; set; }
public override string ToString() => Path;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetApis.Structure.Entities;
using Newtonsoft.Json;
namespace DotNetApis.Structure
{
/// <summary>
/// Structured documentation for an assembly within a NuGet package.
/// </summary>
public sealed class AssemblyJson
{
/// <summary>
/// The full name of the assembly.
/// </summary>
[JsonProperty("n")]
public string FullName { get; set; }
/// <summary>
/// The path (within the NuGet package) of the assembly.
/// </summary>
[JsonProperty("n")]
public string Path { get; set; }
/// <summary>
/// The size of the assembly, in bytes.
/// </summary>
[JsonProperty("s")]
public long FileLength { get; set; }
/// <summary>
/// Assembly-level attributes.
/// </summary>
[JsonProperty("b")]
public IReadOnlyList<AttributeJson> Attributes { get; set; }
/// <summary>
/// Types defined by this assembly.
/// </summary>
[JsonProperty("t")]
public IReadOnlyList<IEntity> Types { get; set; }
public override string ToString() => Path;
}
}
| mit | C# |
2996e8438fb0cfb6709cc7f2c4a94d5bde6c0be5 | Fix CacheMiss test | vanashimko/MPP.Mapper | MapperTests/DtoMapperTests.cs | MapperTests/DtoMapperTests.cs | using System;
using Xunit;
using Mapper;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
namespace Mapper.Tests
{
public class DtoMapperTests
{
[Fact]
public void Map_NullPassed_ExceptionThrown()
{
IMapper mapper = new DtoMapper();
Assert.Throws<ArgumentNullException>(() => mapper.Map<object, object>(null));
}
[Fact]
public void Map_TwoCompatibleFields_TwoFieldsAssigned()
{
IMapper mapper = new DtoMapper();
var source = new Source
{
FirstProperty = 1,
SecondProperty = "a",
ThirdProperty = 3.14,
FourthProperty = 2
};
var expected = new Destination
{
FirstProperty = source.FirstProperty,
SecondProperty = source.SecondProperty,
};
Destination actual = mapper.Map<Source, Destination>(source);
Assert.Equal(expected, actual);
}
[Fact]
public void Map_CacheMiss_GetCacheForDidNotCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
mockCache.Setup(cache => cache.HasCacheFor(It.IsAny<MappingEntryInfo>())).Returns(false);
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Never);
}
[Fact]
public void Map_CacheHit_GetCacheForCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
mockCache.Setup(mock => mock.HasCacheFor(It.IsAny<MappingEntryInfo>())).Returns(true);
mockCache.Setup(mock => mock.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>())).Returns(x => x);
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Once);
}
}
} | using System;
using Xunit;
using Mapper;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
namespace Mapper.Tests
{
public class DtoMapperTests
{
[Fact]
public void Map_NullPassed_ExceptionThrown()
{
IMapper mapper = new DtoMapper();
Assert.Throws<ArgumentNullException>(() => mapper.Map<object, object>(null));
}
[Fact]
public void Map_TwoCompatibleFields_TwoFieldsAssigned()
{
IMapper mapper = new DtoMapper();
var source = new Source
{
FirstProperty = 1,
SecondProperty = "a",
ThirdProperty = 3.14,
FourthProperty = 2
};
var expected = new Destination
{
FirstProperty = source.FirstProperty,
SecondProperty = source.SecondProperty,
};
Destination actual = mapper.Map<Source, Destination>(source);
Assert.Equal(expected, actual);
}
[Fact]
public void Map_CacheMiss_GetCacheForDidNotCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Never);
}
[Fact]
public void Map_CacheHit_GetCacheForCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
mockCache.Setup(mock => mock.HasCacheFor(It.IsAny<MappingEntryInfo>())).Returns(true);
mockCache.Setup(mock => mock.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>())).Returns(x => x);
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Once);
}
}
} | mit | C# |
04e74391367225e6d687c2d4c10337fa2263c8c3 | Update version to 2.1.1-alpha | catcherwong/Nancy.Swagger,khellang/Nancy.Swagger,yahehe/Nancy.Swagger | etc/CommonAssemblyInfo.cs | etc/CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("Kristian Hellang and Contributors")]
[assembly: AssemblyCopyright("Copyright Kristian Hellang 2014")]
[assembly: AssemblyVersion("2.1.1")]
[assembly: AssemblyFileVersion("2.1.1")]
[assembly: AssemblyInformationalVersion("2.1.1-alpha")] | using System.Reflection;
[assembly: AssemblyCompany("Kristian Hellang and Contributors")]
[assembly: AssemblyCopyright("Copyright Kristian Hellang 2014")]
[assembly: AssemblyVersion("2.1.0")]
[assembly: AssemblyFileVersion("2.1.0")]
[assembly: AssemblyInformationalVersion("2.1.0-alpha")] | mit | C# |
1dfbe9038a77ecbff351596f6cf262b2972582b3 | Fix new soldier button | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | BatteryCommander.Web/Views/Soldier/List.cshtml | BatteryCommander.Web/Views/Soldier/List.cshtml | @model IEnumerable<BatteryCommander.Common.Models.Soldier>
@{
ViewBag.Title = "Soldiers";
}
<h2>@ViewBag.Title</h2>
<div class="btn-group" role="group">
@Html.ActionLink("Add a Soldier", "New", null, new { @class = "btn btn-primary" })
@Html.ActionLink("Bulk Add/Edit Soldiers", "Bulk", null, new { @class = "btn btn-default" })
@Html.ActionLink("Include Inactive Soldiers", "List", new { activeOnly = false }, new { @class = "btn btn-default" })
</div>
<table class="table table-striped">
<tr>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Group)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Position)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().MOS)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Notes)</th>
<th></th>
</tr>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Group)</td>
<td>@Html.DisplayFor(s => soldier.Position)</td>
<td>@Html.DisplayFor(s => soldier.Rank, new { UseShortName = true })</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.MOS, new { UseShortName = true })</td>
<td>@Html.DisplayFor(s => soldier.Notes)</td>
<td>@Html.ActionLink("View", "View", new { soldierId = soldier.Id }, new { @class = "btn btn-default" })</td>
</tr>
}
</table> | @model IEnumerable<BatteryCommander.Common.Models.Soldier>
@{
ViewBag.Title = "Soldiers";
}
<h2>@ViewBag.Title</h2>
<div class="btn-group" role="group">
@Html.ActionLink("Add a Soldier", "Edit", null, new { @class = "btn btn-primary" })
@Html.ActionLink("Bulk Add/Edit Soldiers", "Bulk", null, new { @class = "btn btn-default" })
@Html.ActionLink("Include Inactive Soldiers", "List", new { activeOnly = false }, new { @class = "btn btn-default" })
</div>
<table class="table table-striped">
<tr>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Group)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Position)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().MOS)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Notes)</th>
<th></th>
</tr>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Group)</td>
<td>@Html.DisplayFor(s => soldier.Position)</td>
<td>@Html.DisplayFor(s => soldier.Rank, new { UseShortName = true })</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.MOS, new { UseShortName = true })</td>
<td>@Html.DisplayFor(s => soldier.Notes)</td>
<td>@Html.ActionLink("View", "View", new { soldierId = soldier.Id }, new { @class = "btn btn-default" })</td>
</tr>
}
</table> | mit | C# |
4a99656d93b4e0d6a6547ba7cf4c10cbcfd12c0b | enhance dynamicobject feature | IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework | Src/iFramework/Infrastructure/DynamicJson.cs | Src/iFramework/Infrastructure/DynamicJson.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using Newtonsoft.Json.Linq;
namespace IFramework.Infrastructure
{
public class DynamicJson : DynamicObject
{
internal Newtonsoft.Json.Linq.JObject _json;
public DynamicJson(Newtonsoft.Json.Linq.JObject json)
{
_json = json;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
bool ret = false;
JToken value;
if (_json.TryGetValue(binder.Name, out value))
{
if (value is JValue)
{
result = (value as JValue).Value;
}
else if (value is JObject)
{
result = new DynamicJson(value as JObject);
}
else
{
result = value;
}
ret = true;
}
else
{
result = null;
}
return ret;
}
public override bool TrySetMember(SetMemberBinder binder, object val)
{
bool ret = true;
try
{
var property = _json.Property(binder.Name);
if (property != null)
{
property.Value = JToken.FromObject(val);
}
else
{
_json.Add(binder.Name, new JObject(val));
}
}
catch (Exception)
{
ret = false;
}
return ret;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using Newtonsoft.Json.Linq;
namespace IFramework.Infrastructure
{
public class DynamicJson : DynamicObject
{
internal Newtonsoft.Json.Linq.JObject _json;
public DynamicJson(Newtonsoft.Json.Linq.JObject json)
{
_json = json;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
bool ret = false;
JToken value;
if (_json.TryGetValue(binder.Name, out value))
{
result = (value as JValue).Value;
ret = true;
}
else
{
result = null;
}
return ret;
}
public override bool TrySetMember(SetMemberBinder binder, object val)
{
bool ret = true;
try
{
var property = _json.Property(binder.Name);
if (property != null)
{
property.Value = JToken.FromObject(val);
}
else
{
_json.Add(binder.Name, new JObject(val));
}
}
catch (Exception)
{
ret = false;
}
return ret;
}
}
}
| mit | C# |
26dda4aa0650a17ff0cd7b8f1a70cf9a5e66cb0c | Add clock Face and Window classes. Draw a line. Setting FG color is TODO. | clicketyclack/gtksharp_clock | gtksharp_clock/Program.cs | gtksharp_clock/Program.cs | using System;
using Gtk;
// http://www.mono-project.com/docs/gui/gtksharp/widgets/widget-colours/
namespace gtksharp_clock
{
class MainClass
{
public static void Main(string[] args)
{
Application.Init();
ClockWindow win = new ClockWindow ();
win.Show();
Application.Run();
}
}
class ClockWindow : Window
{
public ClockWindow() : base("ClockWindow")
{
SetDefaultSize(250, 200);
SetPosition(WindowPosition.Center);
ClockFace cf = new ClockFace();
Gdk.Color black = new Gdk.Color();
Gdk.Color.Parse("black", ref black);
Gdk.Color grey = new Gdk.Color();
Gdk.Color.Parse("grey", ref grey);
this.ModifyBg(StateType.Normal, grey);
cf.ModifyBg(StateType.Normal, grey);
this.ModifyFg(StateType.Normal, black);
cf.ModifyFg(StateType.Normal, black);
this.DeleteEvent += DeleteWindow;
Add(cf);
ShowAll();
}
static void DeleteWindow(object obj, DeleteEventArgs args)
{
Application.Quit();
}
}
class ClockFace : DrawingArea
{
public ClockFace() : base()
{
this.SetSizeRequest(600, 600);
this.ExposeEvent += OnExposed;
}
public void OnExposed(object o, ExposeEventArgs args)
{
Gdk.Color black = new Gdk.Color();
Gdk.Color.Parse("black", ref black);
this.ModifyFg(StateType.Normal, black);
this.GdkWindow.DrawLine(this.Style.BaseGC(StateType.Normal), 0, 0, 400, 300);
}
}
}
| using System;
using Gtk;
namespace gtksharp_clock
{
class MainClass
{
public static void Main(string[] args)
{
Application.Init();
MainWindow win = new MainWindow();
win.Show();
Application.Run();
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.