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 |
|---|---|---|---|---|---|---|---|---|
860dfb09cf6ccee4b10196ce8f0b72287303c72b | Update ZoomBorderTests.cs | wieslawsoltes/PanAndZoom,PanAndZoom/PanAndZoom,PanAndZoom/PanAndZoom,wieslawsoltes/MatrixPanAndZoomDemo,wieslawsoltes/PanAndZoom | tests/Avalonia.Controls.PanAndZoom.UnitTests/ZoomBorderTests.cs | tests/Avalonia.Controls.PanAndZoom.UnitTests/ZoomBorderTests.cs | using Xunit;
namespace Avalonia.Controls.PanAndZoom.UnitTests
{
public class ZoomBorderTests
{
[Fact(Skip = "The CI tests are failing.")]
public void ZoomBorder_Ctor()
{
var target = new ZoomBorder();
Assert.NotNull(target);
Assert.Equal(ButtonName.Middle, target.PanButton);
Assert.Equal(1.2, target.ZoomSpeed);
Assert.Equal(StretchMode.Uniform, target.Stretch);
Assert.Equal(1.0, target.ZoomX);
Assert.Equal(1.0, target.ZoomY);
Assert.Equal(0.0, target.OffsetX);
Assert.Equal(0.0, target.OffsetY);
Assert.True(target.EnableConstrains);
Assert.Equal(double.NegativeInfinity, target.MinZoomX);
Assert.Equal(double.PositiveInfinity, target.MaxZoomX);
Assert.Equal(double.NegativeInfinity, target.MinZoomY);
Assert.Equal(double.PositiveInfinity, target.MaxZoomY);
Assert.Equal(double.NegativeInfinity, target.MinOffsetX);
Assert.Equal(double.PositiveInfinity, target.MaxOffsetX);
Assert.Equal(double.NegativeInfinity, target.MinOffsetY);
Assert.Equal(double.PositiveInfinity, target.MaxOffsetY);
Assert.True(target.EnablePan);
Assert.True(target.EnableZoom);
Assert.True(target.EnableGestureZoom);
Assert.True(target.EnableGestureRotation);
Assert.True(target.EnableGestureTranslation);
}
}
}
| using Xunit;
namespace Avalonia.Controls.PanAndZoom.UnitTests
{
public class ZoomBorderTests
{
[Fact]
public void ZoomBorder_Ctor()
{
var target = new ZoomBorder();
Assert.NotNull(target);
Assert.Equal(ButtonName.Middle, target.PanButton);
Assert.Equal(1.2, target.ZoomSpeed);
Assert.Equal(StretchMode.Uniform, target.Stretch);
Assert.Equal(1.0, target.ZoomX);
Assert.Equal(1.0, target.ZoomY);
Assert.Equal(0.0, target.OffsetX);
Assert.Equal(0.0, target.OffsetY);
Assert.True(target.EnableConstrains);
Assert.Equal(double.NegativeInfinity, target.MinZoomX);
Assert.Equal(double.PositiveInfinity, target.MaxZoomX);
Assert.Equal(double.NegativeInfinity, target.MinZoomY);
Assert.Equal(double.PositiveInfinity, target.MaxZoomY);
Assert.Equal(double.NegativeInfinity, target.MinOffsetX);
Assert.Equal(double.PositiveInfinity, target.MaxOffsetX);
Assert.Equal(double.NegativeInfinity, target.MinOffsetY);
Assert.Equal(double.PositiveInfinity, target.MaxOffsetY);
Assert.True(target.EnablePan);
Assert.True(target.EnableZoom);
Assert.True(target.EnableGestureZoom);
Assert.True(target.EnableGestureRotation);
Assert.True(target.EnableGestureTranslation);
}
}
}
| mit | C# |
be932fae6d356107a3e5ec84a56ad3b07f6e6b0a | Update copyright year | HearthSim/HearthDb | HearthDb/Properties/AssemblyInfo.cs | HearthDb/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("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2018")]
[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("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// 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("10.0.0.22611")]
[assembly: AssemblyFileVersion("10.0.0.22611")]
| 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("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// 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("10.0.0.22611")]
[assembly: AssemblyFileVersion("10.0.0.22611")]
| mit | C# |
0aa843f50877fddb290834f6886aed091d5e547c | Bump version so 12.2.0.27358 | HearthSim/HearthDb | HearthDb/Properties/AssemblyInfo.cs | HearthDb/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("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2018")]
[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("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// 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("12.2.0.27358")]
[assembly: AssemblyFileVersion("12.2.0.27358")]
| 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("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2018")]
[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("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// 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("12.2.0.26757")]
[assembly: AssemblyFileVersion("12.2.0.26757")]
| mit | C# |
751f4cd26ddc7b5d37953102afb2aa6a13e62be2 | Bump to version 0.0.2 | ekblom/noterium | Noterium/Properties/AssemblyInfo.cs | Noterium/Properties/AssemblyInfo.cs | using System.Reflection;
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("Noterium")]
[assembly: AssemblyDescription("Main executable for Noterium")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Viktor Ekblom")]
[assembly: AssemblyProduct("Noterium")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//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("0.0.2.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
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("Noterium")]
[assembly: AssemblyDescription("Main executable for Noterium")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Viktor Ekblom")]
[assembly: AssemblyProduct("Noterium")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//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("0.0.1.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
78adc86baaf337abfefd00a3864bcde443ffd377 | Set config of domain context after initialization, otherwise sub modules are added twice | SlashGames/slash-framework,SlashGames/slash-framework,SlashGames/slash-framework | Source/Slash.Unity.StrangeIoC/Source/Initialization/ApplicationEntryPoint.cs | Source/Slash.Unity.StrangeIoC/Source/Initialization/ApplicationEntryPoint.cs | namespace Slash.Unity.StrangeIoC.Initialization
{
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using strange.extensions.context.impl;
using Slash.Reflection.Utils;
using Slash.Unity.InspectorExt.PropertyDrawers;
using Slash.Unity.StrangeIoC.Configs;
using Slash.Unity.StrangeIoC.Modules;
using UnityEngine;
public class ApplicationEntryPoint : ApplicationEntryPoint<ApplicationDomainContext>
{
}
public class ApplicationEntryPoint<TDomainContext> : ModuleView
where TDomainContext : ApplicationDomainContext, new()
{
[TypeProperty(BaseType = typeof(StrangeBridge))]
public List<string> BridgeTypes;
/// <summary>
/// Main config for application.
/// </summary>
public StrangeConfig Config;
private void Awake()
{
var domainContext = new TDomainContext();
// Add bridges.
foreach (var bridgeType in this.BridgeTypes)
{
if (bridgeType != null)
{
domainContext.AddBridge(ReflectionUtils.FindType(bridgeType));
}
}
domainContext.Init();
domainContext.Config = this.Config;
domainContext.SetModuleView(this);
Context.firstContext = this.context = domainContext;
}
private IEnumerator LaunchContextWhenReady(TDomainContext domainContext)
{
yield return new WaitUntil(() => domainContext.IsReadyToLaunch);
domainContext.Launch();
}
private void Start()
{
this.context.Start();
// Launch when ready.
this.StartCoroutine(this.LaunchContextWhenReady((TDomainContext) this.context));
}
}
} | namespace Slash.Unity.StrangeIoC.Initialization
{
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using strange.extensions.context.impl;
using Slash.Reflection.Utils;
using Slash.Unity.InspectorExt.PropertyDrawers;
using Slash.Unity.StrangeIoC.Configs;
using Slash.Unity.StrangeIoC.Modules;
using UnityEngine;
public class ApplicationEntryPoint : ApplicationEntryPoint<ApplicationDomainContext>
{
}
public class ApplicationEntryPoint<TDomainContext> : ModuleView
where TDomainContext : ApplicationDomainContext, new()
{
[TypeProperty(BaseType = typeof(StrangeBridge))]
public List<string> BridgeTypes;
/// <summary>
/// Main config for application.
/// </summary>
public StrangeConfig Config;
private void Awake()
{
var domainContext = new TDomainContext {Config = this.Config};
// Add bridges.
foreach (var bridgeType in this.BridgeTypes)
{
if (bridgeType != null)
{
domainContext.AddBridge(ReflectionUtils.FindType(bridgeType));
}
}
domainContext.Init();
domainContext.SetModuleView(this);
Context.firstContext = this.context = domainContext;
}
private IEnumerator LaunchContextWhenReady(TDomainContext domainContext)
{
yield return new WaitUntil(() => domainContext.IsReadyToLaunch);
domainContext.Launch();
}
private void Start()
{
this.context.Start();
// Launch when ready.
this.StartCoroutine(this.LaunchContextWhenReady((TDomainContext) this.context));
}
}
} | mit | C# |
00b71a9d310d2a11f3d37341c966c2d2dd466b3f | Fix build error | jackmagic313/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,djyou/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,peshen/azure-sdk-for-net,mihymel/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,pilor/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jamestao/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,pankajsn/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,djyou/azure-sdk-for-net,jamestao/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,shutchings/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,begoldsm/azure-sdk-for-net,stankovski/azure-sdk-for-net,peshen/azure-sdk-for-net,shutchings/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,atpham256/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,shutchings/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,samtoubia/azure-sdk-for-net,begoldsm/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,olydis/azure-sdk-for-net,btasdoven/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,jamestao/azure-sdk-for-net,nathannfan/azure-sdk-for-net,AzCiS/azure-sdk-for-net,pankajsn/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,begoldsm/azure-sdk-for-net,olydis/azure-sdk-for-net,nathannfan/azure-sdk-for-net,AzCiS/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,olydis/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,stankovski/azure-sdk-for-net,btasdoven/azure-sdk-for-net,AzCiS/azure-sdk-for-net,jamestao/azure-sdk-for-net,samtoubia/azure-sdk-for-net,markcowl/azure-sdk-for-net,pilor/azure-sdk-for-net,hyonholee/azure-sdk-for-net,mihymel/azure-sdk-for-net,hyonholee/azure-sdk-for-net,djyou/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,hyonholee/azure-sdk-for-net,mihymel/azure-sdk-for-net,peshen/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,pankajsn/azure-sdk-for-net,atpham256/azure-sdk-for-net,pilor/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,samtoubia/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,samtoubia/azure-sdk-for-net,btasdoven/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,nathannfan/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,hyonholee/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,atpham256/azure-sdk-for-net | src/ResourceManagement/Network/Microsoft.Azure.Management.Network/Generated/Models/ConnectionResetSharedKey.cs | src/ResourceManagement/Network/Microsoft.Azure.Management.Network/Generated/Models/ConnectionResetSharedKey.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Microsoft.Rest.Azure;
public partial class ConnectionResetSharedKey
{
/// <summary>
/// Initializes a new instance of the ConnectionResetSharedKey class.
/// </summary>
public ConnectionResetSharedKey() { }
/// <summary>
/// Initializes a new instance of the ConnectionResetSharedKey class.
/// </summary>
public ConnectionResetSharedKey(int keyLength)
{
KeyLength = keyLength;
}
/// <summary>
/// The virtual network connection reset shared key length, should
/// between 1 and 128.
/// </summary>
[JsonProperty(PropertyName = "keyLength")]
public int KeyLength { get; set; }
/// <summary>
/// Validate the object. Throws ValidationException if validation fails.
/// </summary>
public virtual void Validate()
{
if (this.KeyLength > 128)
{
throw new ValidationException(ValidationRules.InclusiveMaximum, "KeyLength", 128);
}
if (this.KeyLength < 1)
{
throw new ValidationException(ValidationRules.InclusiveMinimum, "KeyLength", 1);
}
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Microsoft.Rest.Azure;
public partial class ConnectionResetSharedKey
{
/// <summary>
/// Initializes a new instance of the ConnectionResetSharedKey class.
/// </summary>
public ConnectionResetSharedKey() { }
/// <summary>
/// Initializes a new instance of the ConnectionResetSharedKey class.
/// </summary>
public ConnectionResetSharedKey(long keyLength)
{
KeyLength = keyLength;
}
/// <summary>
/// The virtual network connection reset shared key length
/// </summary>
[JsonProperty(PropertyName = "keyLength")]
public long KeyLength { get; set; }
/// <summary>
/// Validate the object. Throws ValidationException if validation fails.
/// </summary>
public virtual void Validate()
{
if (this.KeyLength.Length > 128)
{
throw new ValidationException(ValidationRules.MaxLength, "KeyLength", 128);
}
if (this.KeyLength.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "KeyLength", 1);
}
}
}
}
| mit | C# |
c9257b42f52e05ba0d82c6db6b65543a3ad17ec3 | remove json require flag which fails serialisation from table config when MI config updates applied. Cannot yet remove the fields as they are required by the interface in the nuget package | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Support.Web/Configuration/EmployerUsersApiConfiguration.cs | src/SFA.DAS.EmployerUsers.Support.Web/Configuration/EmployerUsersApiConfiguration.cs | using Newtonsoft.Json;
using SFA.DAS.EmployerUsers.Api.Client;
namespace SFA.DAS.EmployerUsers.Support.Web.Configuration
{
public class EmployerUsersApiConfiguration : IEmployerUsersApiConfiguration
{
[JsonRequired]
public string ApiBaseUrl { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
[JsonRequired]
public string IdentifierUri { get; set; }
public string Tenant { get; set; }
public string ClientCertificateThumbprint { get; set; }
}
} | using Newtonsoft.Json;
using SFA.DAS.EmployerUsers.Api.Client;
namespace SFA.DAS.EmployerUsers.Support.Web.Configuration
{
public class EmployerUsersApiConfiguration : IEmployerUsersApiConfiguration
{
[JsonRequired]
public string ApiBaseUrl { get; set; }
[JsonRequired]
public string ClientId { get; set; }
[JsonRequired]
public string ClientSecret { get; set; }
[JsonRequired]
public string IdentifierUri { get; set; }
[JsonRequired]
public string Tenant { get; set; }
[JsonRequired]
public string ClientCertificateThumbprint { get; set; }
}
} | mit | C# |
69d9f298810d4f7ca60d7fe99b76c7f4845e781d | Add property | davkean/audio-switcher | src/AudioSwitcher/Presentation/ContextMenuPresenter.cs | src/AudioSwitcher/Presentation/ContextMenuPresenter.cs | // -----------------------------------------------------------------------
// Copyright (c) David Kean. All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Drawing;
using System.Windows.Forms;
using AudioSwitcher.ApplicationModel;
using AudioSwitcher.Presentation.UI;
namespace AudioSwitcher.Presentation
{
// Provides the base class for context menu presenters
internal abstract class ContextMenuPresenter : Presenter, IDisposable
{
private readonly AudioContextMenuStrip _contextMenu;
private readonly IApplication _application;
protected ContextMenuPresenter(IApplication application)
{
_application = application;
_contextMenu = CreateContextMenu();
_contextMenu.Closed += (sender, e) => OnClosed(EventArgs.Empty);
}
public AudioContextMenuStrip ContextMenu => _contextMenu;
public IApplication Application => _application;
protected virtual AudioContextMenuStrip CreateContextMenu()
{
return new AudioContextMenuStrip();
}
public void Show(Point screenLocation)
{
ContextMenu.ShowInSystemTray(screenLocation);
}
public void Close()
{
_contextMenu.Close(ToolStripDropDownCloseReason.AppFocusChange);
}
public virtual void Dispose()
{
// WORKAROUND: It's not possible to dispose of a context menu strip
// in its Closed event because it tries to do some work after that
// and throws ObjectDisposedException. To workaround this, we hold
// off disposing them until the next idle event.
_application.RunOnNextIdle(() => _contextMenu.Dispose());
}
}
}
| // -----------------------------------------------------------------------
// Copyright (c) David Kean. All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Drawing;
using System.Windows.Forms;
using AudioSwitcher.ApplicationModel;
using AudioSwitcher.Presentation.UI;
namespace AudioSwitcher.Presentation
{
// Provides the base class for context menu presenters
internal abstract class ContextMenuPresenter : Presenter, IDisposable
{
private readonly AudioContextMenuStrip _contextMenu;
private readonly IApplication _application;
protected ContextMenuPresenter(IApplication application)
{
_application = application;
_contextMenu = CreateContextMenu();
_contextMenu.Closed += (sender, e) => OnClosed(EventArgs.Empty);
}
public AudioContextMenuStrip ContextMenu => _contextMenu;
protected virtual AudioContextMenuStrip CreateContextMenu()
{
return new AudioContextMenuStrip();
}
public void Show(Point screenLocation)
{
ContextMenu.ShowInSystemTray(screenLocation);
}
public void Close()
{
_contextMenu.Close(ToolStripDropDownCloseReason.AppFocusChange);
}
public virtual void Dispose()
{
// WORKAROUND: It's not possible to dispose of a context menu strip
// in its Closed event because it tries to do some work after that
// and throws ObjectDisposedException. To workaround this, we hold
// off disposing them until the next idle event.
_application.RunOnNextIdle(() => _contextMenu.Dispose());
}
}
}
| mit | C# |
6823a94ed34e27da0796102eaf55d53e75980ec1 | Allow .mustache extension as well for Nustache views | jammycakes/dolstagis.web,jammycakes/dolstagis.web,jammycakes/dolstagis.web | src/Dolstagis.Web/Views/Nustache/NustacheViewEngine.cs | src/Dolstagis.Web/Views/Nustache/NustacheViewEngine.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using global::Nustache.Core;
namespace Dolstagis.Web.Views.Nustache
{
public class NustacheViewEngine : ViewEngineBase
{
private static readonly string[] _extensions = new[] { "mustache", "nustache" };
public override IEnumerable<string> Extensions
{
get { return _extensions; }
}
protected override IView CreateView(VirtualPath pathToView, Static.IResourceLocator locator)
{
var resource = locator.GetResource(pathToView);
if (resource == null || !resource.Exists) {
throw new ViewNotFoundException("There is no view at " + pathToView.ToString());
}
return new NustacheView(this, pathToView, resource);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using global::Nustache.Core;
namespace Dolstagis.Web.Views.Nustache
{
public class NustacheViewEngine : ViewEngineBase
{
private static readonly string[] _extensions = new[] { "nustache" };
public override IEnumerable<string> Extensions
{
get { return _extensions; }
}
protected override IView CreateView(VirtualPath pathToView, Static.IResourceLocator locator)
{
var resource = locator.GetResource(pathToView);
if (resource == null || !resource.Exists) {
throw new ViewNotFoundException("There is no view at " + pathToView.ToString());
}
return new NustacheView(this, pathToView, resource);
}
}
}
| mit | C# |
1916fd14580cf70f460abee0c453fbc12135e9e6 | Fix #1478: Typo in stem_exclusion property serialization | wawrzyn/elasticsearch-net,LeoYao/elasticsearch-net,abibell/elasticsearch-net,LeoYao/elasticsearch-net,SeanKilleen/elasticsearch-net,tkirill/elasticsearch-net,joehmchan/elasticsearch-net,DavidSSL/elasticsearch-net,faisal00813/elasticsearch-net,ststeiger/elasticsearch-net,robrich/elasticsearch-net,starckgates/elasticsearch-net,robrich/elasticsearch-net,faisal00813/elasticsearch-net,robertlyson/elasticsearch-net,junlapong/elasticsearch-net,mac2000/elasticsearch-net,mac2000/elasticsearch-net,tkirill/elasticsearch-net,ststeiger/elasticsearch-net,robertlyson/elasticsearch-net,gayancc/elasticsearch-net,junlapong/elasticsearch-net,starckgates/elasticsearch-net,abibell/elasticsearch-net,mac2000/elasticsearch-net,SeanKilleen/elasticsearch-net,gayancc/elasticsearch-net,starckgates/elasticsearch-net,gayancc/elasticsearch-net,faisal00813/elasticsearch-net,SeanKilleen/elasticsearch-net,tkirill/elasticsearch-net,robertlyson/elasticsearch-net,DavidSSL/elasticsearch-net,joehmchan/elasticsearch-net,DavidSSL/elasticsearch-net,wawrzyn/elasticsearch-net,junlapong/elasticsearch-net,robrich/elasticsearch-net,LeoYao/elasticsearch-net,wawrzyn/elasticsearch-net,abibell/elasticsearch-net,joehmchan/elasticsearch-net,ststeiger/elasticsearch-net | src/Nest/Domain/Analysis/Analyzers/LanguageAnalyzer.cs | src/Nest/Domain/Analysis/Analyzers/LanguageAnalyzer.cs | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// A set of analyzers aimed at analyzing specific language text.
/// </summary>
public class LanguageAnalyzer : AnalyzerBase
{
public LanguageAnalyzer(Language language)
{
language.ThrowIfNull("language");
var name = Enum.GetName(typeof (Language), language);
if (name == null)
language.ThrowIfNull("language");
var langName = name.ToLowerInvariant();
Type = langName;
}
/// <summary>
/// A list of stopword to initialize the stop filter with. Defaults to the english stop words.
/// </summary>
[JsonProperty("stopwords")]
public IEnumerable<string> StopWords { get; set; }
[JsonProperty("stem_exclusion")]
public IEnumerable<string> StemExclusionList { get; set; }
/// <summary>
/// A path (either relative to config location, or absolute) to a stopwords file configuration.
/// </summary>
[JsonProperty("stopwords_path")]
public string StopwordsPath { get; set; }
}
} | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// A set of analyzers aimed at analyzing specific language text.
/// </summary>
public class LanguageAnalyzer : AnalyzerBase
{
public LanguageAnalyzer(Language language)
{
language.ThrowIfNull("language");
var name = Enum.GetName(typeof (Language), language);
if (name == null)
language.ThrowIfNull("language");
var langName = name.ToLowerInvariant();
Type = langName;
}
/// <summary>
/// A list of stopword to initialize the stop filter with. Defaults to the english stop words.
/// </summary>
[JsonProperty("stopwords")]
public IEnumerable<string> StopWords { get; set; }
[JsonProperty("stem_exclusion ")]
public IEnumerable<string> StemExclusionList { get; set; }
/// <summary>
/// A path (either relative to config location, or absolute) to a stopwords file configuration.
/// </summary>
[JsonProperty("stopwords_path")]
public string StopwordsPath { get; set; }
}
} | apache-2.0 | C# |
65f160d7cf8a4a4b4e1d47279f49e2d564e73d8d | Add test for not nugetting something when there's no package available | BenPhegan/NuGet.Extensions | NuGet.Extensions.Tests/ReferenceAnalysers/ReferenceNugetifierBinaryTests.cs | NuGet.Extensions.Tests/ReferenceAnalysers/ReferenceNugetifierBinaryTests.cs | using System;
using System.Linq;
using Moq;
using NUnit.Framework;
namespace NuGet.Extensions.Tests.ReferenceAnalysers
{
[TestFixture]
public class ReferenceNugetifierBinaryTests
{
[Test]
public void EmptyProjectHasNoNuggettedDependencies()
{
var nugetifier = ReferenceNugetifierTester.BuildNugetifier();
var nugettedDependencies = ReferenceNugetifierTester.GetManifestDependencies(nugetifier);
Assert.That(nugettedDependencies, Is.Empty);
}
[Test]
public void SingleDependencyListedInManifestDependencies()
{
var singleDependency = ProjectReferenceTestData.ConstructMockDependency();
var projectWithSingleDependency = ProjectReferenceTestData.ConstructMockProject(new[] {singleDependency.Object});
var packageRepositoryWithOnePackage = ProjectReferenceTestData.CreateMockRepository();
var nugetifier = ReferenceNugetifierTester.BuildNugetifier(vsProject: projectWithSingleDependency, packageRepository: packageRepositoryWithOnePackage);
var nugettedDependencies = ReferenceNugetifierTester.GetManifestDependencies(nugetifier);
Assert.That(nugettedDependencies, Is.Not.Empty);
Assert.That(nugettedDependencies.Single().Id, Contains.Substring(ProjectReferenceTestData.PackageInRepository));
}
[Test]
public void SingleDependencyWithCorrespondingPackageGetsNugetted()
{
var singleDependency = ProjectReferenceTestData.ConstructMockDependency();
var projectWithSingleDependency = ProjectReferenceTestData.ConstructMockProject(new[] { singleDependency.Object });
var packageRepositoryWithCorrespondingPackage = ProjectReferenceTestData.CreateMockRepository();
var nugetifier = ReferenceNugetifierTester.BuildNugetifier(vsProject: projectWithSingleDependency, packageRepository: packageRepositoryWithCorrespondingPackage);
ReferenceNugetifierTester.NugetifyReferencesInProject(nugetifier);
singleDependency.Verify(binaryDependency => binaryDependency.ConvertToNugetReferenceWithHintPath(It.IsAny<string>()), Times.Once());
}
[Test]
public void SingleDependencyWithoutCorrespondingPackageNotNugetted()
{
var singleDependency = ProjectReferenceTestData.ConstructMockDependency();
var projectWithSingleDependency = ProjectReferenceTestData.ConstructMockProject(new[] { singleDependency.Object });
var nugetifier = ReferenceNugetifierTester.BuildNugetifier(vsProject: projectWithSingleDependency);
ReferenceNugetifierTester.NugetifyReferencesInProject(nugetifier);
singleDependency.Verify(binaryDependency => binaryDependency.ConvertToNugetReferenceWithHintPath(It.IsAny<string>()), Times.Never());
}
}
}
| using System;
using System.Linq;
using Moq;
using NUnit.Framework;
namespace NuGet.Extensions.Tests.ReferenceAnalysers
{
[TestFixture]
public class ReferenceNugetifierBinaryTests
{
[Test]
public void EmptyProjectHasNoNuggettedDependencies()
{
var nugetifier = ReferenceNugetifierTester.BuildNugetifier();
var nugettedDependencies = ReferenceNugetifierTester.GetManifestDependencies(nugetifier);
Assert.That(nugettedDependencies, Is.Empty);
}
[Test]
public void SingleDependencyListedInManifestDependencies()
{
var singleDependency = ProjectReferenceTestData.ConstructMockDependency();
var projectWithSingleDependency = ProjectReferenceTestData.ConstructMockProject(new[] {singleDependency.Object});
var packageRepositoryWithOnePackage = ProjectReferenceTestData.CreateMockRepository();
var nugetifier = ReferenceNugetifierTester.BuildNugetifier(vsProject: projectWithSingleDependency, packageRepository: packageRepositoryWithOnePackage);
var nugettedDependencies = ReferenceNugetifierTester.GetManifestDependencies(nugetifier);
Assert.That(nugettedDependencies, Is.Not.Empty);
Assert.That(nugettedDependencies.Single().Id, Contains.Substring(ProjectReferenceTestData.PackageInRepository));
}
[Test]
public void SingleDependencyWithCorrespondingPackageGetsNugetted()
{
var singleDependency = ProjectReferenceTestData.ConstructMockDependency();
var projectWithSingleDependency = ProjectReferenceTestData.ConstructMockProject(new[] { singleDependency.Object });
var packageRepositoryWithOnePackage = ProjectReferenceTestData.CreateMockRepository();
var nugetifier = ReferenceNugetifierTester.BuildNugetifier(vsProject: projectWithSingleDependency, packageRepository: packageRepositoryWithOnePackage);
ReferenceNugetifierTester.NugetifyReferencesInProject(nugetifier);
singleDependency.Verify(binaryDependency => binaryDependency.ConvertToNugetReferenceWithHintPath(It.IsAny<string>()), Times.Once());
}
}
}
| mit | C# |
ada61bc7c33c78e24c46fd2a6022f3d03163af33 | Update _Identity.cshtml | vtfuture/BForms,vtfuture/BForms,vtfuture/BForms | BForms.Docs/Areas/Demo/Views/Contributors/Grid/Details/_Identity.cshtml | BForms.Docs/Areas/Demo/Views/Contributors/Grid/Details/_Identity.cshtml | @using BForms.Docs.Resources
@using BForms.Html
@using BForms.Models
@model BForms.Docs.Areas.Demo.Models.ContributorDetailsModel
<h3 class="editable">
@Html.BsGlyphicon(Glyphicon.User)
Identity
@Html.BsGlyphicon(Glyphicon.Pencil, new Dictionary<string, object> {{ "class", "open-editable" }})
</h3>
@Html.Partial("Grid/Details/_IdentityReadonly", Model)
@Html.Partial("Grid/Details/_IdentityEditable", Model)
| @using BForms.Docs.Resources
@using BForms.Html
@using BForms.Models
@model BForms.Docs.Areas.Demo.Models.ContributorDetailsModel
<h3 class="editable">
@Html.BsGlyphicon(Glyphicon.User)
Identity
@Html.BsGlyphicon(Glyphicon.Pencil)
</h3>
@Html.Partial("Grid/Details/_IdentityReadonly", Model)
@Html.Partial("Grid/Details/_IdentityEditable", Model) | mit | C# |
2fb9b4173a658629dd35f3629e722f81055eb24e | Revert back to local temp folder | TorchAPI/Torch | Torch/Managers/FilesystemManager.cs | Torch/Managers/FilesystemManager.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using Torch.API;
namespace Torch.Managers
{
public class FilesystemManager : Manager
{
private static readonly Logger _log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Temporary directory for Torch that is cleared every time the program is started.
/// </summary>
public string TempDirectory { get; }
/// <summary>
/// Directory that contains the current Torch assemblies.
/// </summary>
public string TorchDirectory { get; }
public FilesystemManager(ITorchBase torchInstance) : base(torchInstance)
{
var torch = new FileInfo(typeof(FilesystemManager).Assembly.Location).Directory.FullName;
TempDirectory = Directory.CreateDirectory(Path.Combine(torch, "tmp")).FullName;
TorchDirectory = torch;
_log.Debug($"Clearing tmp directory at {TempDirectory}");
ClearTemp();
}
private void ClearTemp()
{
foreach (var file in Directory.GetFiles(TempDirectory, "*", SearchOption.AllDirectories))
File.Delete(file);
}
/// <summary>
/// Move the given file (if it exists) to a temporary directory that will be cleared the next time the application starts.
/// </summary>
public void SoftDelete(string path, string file)
{
string source = Path.Combine(path, file);
if (!File.Exists(source))
return;
var rand = Path.GetRandomFileName();
var dest = Path.Combine(TempDirectory, rand);
File.Move(source, rand);
string rsource = Path.Combine(path, rand);
File.Move(rsource, dest);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using Torch.API;
namespace Torch.Managers
{
public class FilesystemManager : Manager
{
private static readonly Logger _log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Temporary directory for Torch that is cleared every time the program is started.
/// </summary>
public string TempDirectory { get; }
/// <summary>
/// Directory that contains the current Torch assemblies.
/// </summary>
public string TorchDirectory { get; }
public FilesystemManager(ITorchBase torchInstance) : base(torchInstance)
{
var tmp = Path.Combine(Path.GetTempPath(), "Torch");
var torch = new FileInfo(typeof(FilesystemManager).Assembly.Location).Directory.FullName;
if (Path.GetPathRoot(tmp) == Path.GetPathRoot(torch))
{
TempDirectory = tmp;
}
else
{
TempDirectory = Directory.CreateDirectory(Path.Combine(torch, "tmp")).FullName;
TorchDirectory = torch;
_log.Info($"Clearing tmp directory at {TempDirectory}");
ClearTemp();
}
}
private void ClearTemp()
{
foreach (var file in Directory.GetFiles(TempDirectory, "*", SearchOption.AllDirectories))
File.Delete(file);
}
/// <summary>
/// Move the given file (if it exists) to a temporary directory that will be cleared the next time the application starts.
/// </summary>
public void SoftDelete(string path, string file)
{
string source = Path.Combine(path, file);
if (!File.Exists(source))
return;
var rand = Path.GetRandomFileName();
var dest = Path.Combine(TempDirectory, rand);
File.Move(source, rand);
string rsource = Path.Combine(path, rand);
File.Move(rsource, dest);
}
}
}
| apache-2.0 | C# |
3a2e5e28f1b0d4f18dd9e2482a4e85c6ab341241 | add vms | UnstableMutex/WorkTemp,UnstableMutex/WorkTemp,UnstableMutex/WorkTemp,UnstableMutex/WorkTemp | WebPool/WebPool/Models/PoolModel.cs | WebPool/WebPool/Models/PoolModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebPool.DB.DBModels;
namespace WebPool.Models
{
public class PoolViewModel
{
public Pool Pool { get; set; }
public IReadOnlyList<QuestionViewModel> Questions { get; set; }
}
public class QuestionViewModel
{
public string Indexer { get; set; }
}
public class OpenQuestionViewModel : QuestionViewModel, IControlName
{
public string Index { get; }
public string Name { get; }
}
public class CheckedQuestionViewModel : QuestionViewModel, IControlName
{
private readonly Question _model;
public CheckedQuestionViewModel(Question model)
{
_model = model;
}
public string Index => _model.ID.Surr();
public string Name { get; }
}
public class CheckedAnswerViewModel : IControlName
{
private readonly CheckAnswer _model;
private readonly IControlName _parent;
public CheckedAnswerViewModel(CheckAnswer model, IControlName parent)
{
_model = model;
_parent = parent;
}
public string Answer { get; }
public string Index => _parent.Index + _model.ID.Surr();
public string Name => "CheckedAnswer";
}
static class Ext
{
public static string Surr(this string s)
{
return "[" + s + "]";
}
public static string Surr(this int s)
{
return "[" + s + "]";
}
}
public interface IControlName
{
string Index { get; }
string Name { get; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebPool.DB.DBModels;
namespace WebPool.Models
{
public class PoolViewModel
{
public Pool Pool { get; set; }
public IReadOnlyList<QuestionViewModel> Questions { get; set; }
}
public class QuestionViewModel
{
public string Indexer { get; set; }
}
public class OpenQuestionViewModel : QuestionViewModel
{
}
public class CheckedQuestionViewModel : QuestionViewModel
{
}
public class CheckedAnswerViewModel
{ }
} | unlicense | C# |
dbebfac0c55b34865f469434648307c1013f479d | Add test for count | loekd/ServiceFabric.Mocks | test/ServiceFabric.Mocks.Tests/MocksTests/MockReliableDictionaryTests.cs | test/ServiceFabric.Mocks.Tests/MocksTests/MockReliableDictionaryTests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using ServiceFabric.Mocks.ReliableCollections;
using System.Threading;
namespace ServiceFabric.Mocks.Tests.MocksTests
{
[TestClass]
public class MockReliableDictionaryTests
{
[TestMethod]
public async Task DictionaryAddDuplicateKeyExceptionTypeTest()
{
const string key = "key";
var dictionary = new MockReliableDictionary<string, string>(new Uri("fabric://MockReliableDictionary"));
var tx = new MockTransaction(null, 1);
await dictionary.AddAsync(tx, key, "value");
await Assert.ThrowsExceptionAsync<ArgumentException>(async () =>
{
await dictionary.AddAsync(tx, key, "value");
});
}
[TestMethod]
public async Task DictionaryAddAndRetrieveTest()
{
const string key = "key";
const string value = "value";
var dictionary = new MockReliableDictionary<string, string>(new Uri("fabric://MockReliableDictionary"));
var tx = new MockTransaction(null, 1);
await dictionary.AddAsync(tx, key, value);
var actual = await dictionary.TryGetValueAsync(tx, key);
Assert.AreEqual(actual.Value, value);
}
[TestMethod]
public async Task DictionaryCountTest()
{
const string key = "key";
const string value = "value";
var dictionary = new MockReliableDictionary<string, string>(new Uri("fabric://MockReliableDictionary"));
var tx = new MockTransaction(null, 1);
await dictionary.AddAsync(tx, key, value);
var actual = dictionary.Count;
Assert.AreEqual(1, actual);
}
[TestMethod]
public async Task DictionaryCreateKeyEnumerableAsyncTest()
{
const string key = "key";
const string value = "value";
var dictionary = new MockReliableDictionary<string, string>(new Uri("fabric://MockReliableDictionary"));
var tx = new MockTransaction(null, 1);
await dictionary.AddAsync(tx, key, value);
var enumerable = await dictionary.CreateKeyEnumerableAsync(tx);
var enumerator = enumerable.GetAsyncEnumerator();
await enumerator.MoveNextAsync(CancellationToken.None);
var actual = enumerator.Current;
Assert.AreEqual(key, actual);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using ServiceFabric.Mocks.ReliableCollections;
using System.Threading;
namespace ServiceFabric.Mocks.Tests.MocksTests
{
[TestClass]
public class MockReliableDictionaryTests
{
[TestMethod]
public async Task DictionaryAddDuplicateKeyExceptionTypeTest()
{
const string key = "key";
var dictionary = new MockReliableDictionary<string, string>(new Uri("fabric://MockReliableDictionary"));
var tx = new MockTransaction(null, 1);
await dictionary.AddAsync(tx, key, "value");
await Assert.ThrowsExceptionAsync<ArgumentException>(async () =>
{
await dictionary.AddAsync(tx, key, "value");
});
}
[TestMethod]
public async Task DictionaryAddAndRetrieveTest()
{
const string key = "key";
const string value = "value";
var dictionary = new MockReliableDictionary<string, string>(new Uri("fabric://MockReliableDictionary"));
var tx = new MockTransaction(null, 1);
await dictionary.AddAsync(tx, key, value);
var actual = await dictionary.TryGetValueAsync(tx, key);
Assert.AreEqual(actual.Value, value);
}
[TestMethod]
public async Task DictionaryCreateKeyEnumerableAsyncTest()
{
const string key = "key";
const string value = "value";
var dictionary = new MockReliableDictionary<string, string>(new Uri("fabric://MockReliableDictionary"));
var tx = new MockTransaction(null, 1);
await dictionary.AddAsync(tx, key, value);
var enumerable = await dictionary.CreateKeyEnumerableAsync(tx);
var enumerator = enumerable.GetAsyncEnumerator();
await enumerator.MoveNextAsync(CancellationToken.None);
var actual = enumerator.Current;
Assert.AreEqual(key, actual);
}
}
}
| mit | C# |
7a86686f40836dd58939ebbd00c0e7107f7c099c | Make nullable | UselessToucan/osu,ppy/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu | osu.Game/Online/Chat/NowPlayingCommand.cs | osu.Game/Online/Chat/NowPlayingCommand.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Users;
namespace osu.Game.Online.Chat
{
public class NowPlayingCommand : Component
{
[Resolved]
private IChannelPostTarget channelManager { get; set; }
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private Bindable<WorkingBeatmap> currentBeatmap { get; set; }
private readonly Channel target;
/// <summary>
/// Creates a new <see cref="NowPlayingCommand"/> to post the currently-playing beatmap to a parenting <see cref="IChannelPostTarget"/>.
/// </summary>
/// <param name="target">The target channel to post to. If <c>null</c>, the currently-selected channel will be posted to.</param>
public NowPlayingCommand(Channel target = null)
{
this.target = target;
}
protected override void LoadComplete()
{
base.LoadComplete();
string verb;
BeatmapInfo beatmap;
switch (api.Activity.Value)
{
case UserActivity.SoloGame solo:
verb = "playing";
beatmap = solo.Beatmap;
break;
case UserActivity.Editing edit:
verb = "editing";
beatmap = edit.Beatmap;
break;
default:
verb = "listening to";
beatmap = currentBeatmap.Value.BeatmapInfo;
break;
}
var beatmapString = beatmap.OnlineBeatmapID.HasValue ? $"[{api.WebsiteRootUrl}/b/{beatmap.OnlineBeatmapID} {beatmap}]" : beatmap.ToString();
channelManager.PostMessage($"is {verb} {beatmapString}", true, target);
Expire();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Users;
namespace osu.Game.Online.Chat
{
public class NowPlayingCommand : Component
{
[Resolved]
private IChannelPostTarget channelManager { get; set; }
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private Bindable<WorkingBeatmap> currentBeatmap { get; set; }
private readonly Channel target;
public NowPlayingCommand(Channel target)
{
this.target = target;
}
protected override void LoadComplete()
{
base.LoadComplete();
string verb;
BeatmapInfo beatmap;
switch (api.Activity.Value)
{
case UserActivity.SoloGame solo:
verb = "playing";
beatmap = solo.Beatmap;
break;
case UserActivity.Editing edit:
verb = "editing";
beatmap = edit.Beatmap;
break;
default:
verb = "listening to";
beatmap = currentBeatmap.Value.BeatmapInfo;
break;
}
var beatmapString = beatmap.OnlineBeatmapID.HasValue ? $"[{api.WebsiteRootUrl}/b/{beatmap.OnlineBeatmapID} {beatmap}]" : beatmap.ToString();
channelManager.PostMessage($"is {verb} {beatmapString}", true, target);
Expire();
}
}
}
| mit | C# |
da0405a4c62f32ba0f8c4e331923facf75fc71bb | Add moving shortcutkey | phillyai/Linking-VPL | Linking/Form1.cs | Linking/Form1.cs | using System;
using System.Drawing;
using System.Windows.Forms;
using Linking.Controls;
using Linking.Core;
using Linking.Core.Blocks;
namespace Linking
{
public partial class Form1 : Form
{
private Board _board;
private BoardControl _control;
public Form1()
{
//이것도 커밋해 보시지!!
InitializeComponent();
_board = new Board();
_control = new BoardControl(_board);
_control.Location = new Point(0, 0);
_control.Size = new Size(hScrollBar1.Maximum * 30 + Width, vScrollBar1.Maximum * 30 + Height);
this.Controls.Add(_control);
this.KeyDown += Form1_KeyDown;
KeyPreview = true;
EntryBlock entry = new EntryBlock(_board);
entry.Location = new Point(00, 50);
_control.AddBlocks(entry);
_board.Entry = entry;
}
private void ScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
_control.Location = new Point(-hScrollBar1.Value * 30, -vScrollBar1.Value * 30);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (!e.Control) return;
if (e.KeyCode == Keys.Left && hScrollBar1.Value != hScrollBar1.Minimum)
hScrollBar1.Value -= 1;
else if (e.KeyCode == Keys.Right && hScrollBar1.Value != hScrollBar1.Maximum)
hScrollBar1.Value += 1;
if (e.KeyCode == Keys.Up && vScrollBar1.Value != vScrollBar1.Minimum)
vScrollBar1.Value -= 1;
else if (e.KeyCode == Keys.Down && vScrollBar1.Value != vScrollBar1.Maximum)
vScrollBar1.Value += 1;
ScrollBar1_Scroll(null, null);
}
}
}
| using System;
using System.Drawing;
using System.Windows.Forms;
using Linking.Controls;
using Linking.Core;
using Linking.Core.Blocks;
namespace Linking
{
public partial class Form1 : Form
{
private Board _board;
private BoardControl _control;
public Form1()
{
//이것도 커밋해 보시지!!
InitializeComponent();
_board = new Board();
_control = new BoardControl(_board);
_control.Location = new Point(0, 0);
_control.Size = new Size(hScrollBar1.Maximum * 30 + Width, vScrollBar1.Maximum * 30 + Height);
this.Controls.Add(_control);
EntryBlock entry = new EntryBlock(_board);
entry.Location = new Point(00, 50);
_control.AddBlocks(entry);
_board.Entry = entry;
}
private void ScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
_control.Location = new Point(-hScrollBar1.Value * 30, -vScrollBar1.Value * 30);
}
}
}
| mit | C# |
43836c86659a49ba55d7ed892dca58cb355c3f0e | Add string based YAML tasks. | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/IO/YamlTasks.cs | source/Nuke.Common/IO/YamlTasks.cs | // Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.IO;
using Nuke.Core.Execution;
using Nuke.Core.Tooling;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
[assembly: IconClass(typeof(YamlTasks), "file-empty2")]
namespace Nuke.Common.IO
{
[PublicAPI]
public class YamlTasks
{
public static void YamlSerializeToFile (object obj, string path, Configure<SerializerBuilder> configurator = null)
{
File.WriteAllText(path, YamlSerialize(obj, configurator));
}
[Pure]
public static T YamlDeserializeFromFile<T> (string path, Configure<DeserializerBuilder> configurator = null)
{
return YamlDeserialize<T>(File.ReadAllText(path), configurator);
}
[Pure]
public static string YamlSerialize (object obj, Configure<SerializerBuilder> configurator = null)
{
var builder = new SerializerBuilder()
.WithNamingConvention(new CamelCaseNamingConvention());
builder = configurator.InvokeSafe(builder);
var serializer = builder.Build();
return serializer.Serialize(obj);
}
[Pure]
public static T YamlDeserialize<T> (string content, Configure<DeserializerBuilder> configurator = null)
{
var builder = new DeserializerBuilder()
.WithNamingConvention(new CamelCaseNamingConvention());
builder = configurator.InvokeSafe(builder);
var deserializer = builder.Build();
return deserializer.Deserialize<T>(content);
}
}
}
| // Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.IO;
using Nuke.Core.Execution;
using Nuke.Core.Tooling;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
[assembly: IconClass(typeof(YamlTasks), "file-empty2")]
namespace Nuke.Common.IO
{
[PublicAPI]
public class YamlTasks
{
public static void YamlSerialize<T> (T obj, string path, Configure<SerializerBuilder> configurator = null)
{
var builder = new SerializerBuilder()
.WithNamingConvention(new CamelCaseNamingConvention());
builder = configurator.InvokeSafe(builder);
var serializer = builder.Build();
var content = serializer.Serialize(obj);
File.WriteAllText(path, content);
}
[Pure]
public static T YamlDeserialize<T> (string path, Configure<DeserializerBuilder> configurator = null)
{
var builder = new DeserializerBuilder()
.WithNamingConvention(new CamelCaseNamingConvention());
builder = configurator.InvokeSafe(builder);
var content = File.ReadAllText(path);
var deserializer = builder.Build();
return deserializer.Deserialize<T>(content);
}
}
}
| mit | C# |
2ea1bc0f1b898c7061a89abdd1f33f23a3997932 | Fix SlaveOk name | mongodb-csharp/mongodb-csharp | source/MongoDB/QueryOptions.cs | source/MongoDB/QueryOptions.cs | namespace MongoDB
{
/// <summary>
/// Query options
/// </summary>
/// <remarks>
/// Oplog replay: 8 (internal replication use only - drivers should not implement)
/// </remarks>
public enum QueryOptions {
/// <summary>
/// None
/// </summary>
None = 0,
/// <summary>
/// Tailable cursor
/// </summary>
TailableCursor = 2,
/// <summary>
/// Slave OK
/// </summary>
SlaveOk = 4,
/// <summary>
/// No cursor timeout
/// </summary>
NoCursorTimeout = 16
}
} | namespace MongoDB
{
/// <summary>
/// Query options
/// </summary>
/// <remarks>
/// Oplog replay: 8 (internal replication use only - drivers should not implement)
/// </remarks>
public enum QueryOptions {
/// <summary>
/// None
/// </summary>
None = 0,
/// <summary>
/// Tailable cursor
/// </summary>
TailableCursor = 2,
/// <summary>
/// Slave OK
/// </summary>
SlaveOK = 4,
/// <summary>
/// No cursor timeout
/// </summary>
NoCursorTimeout = 16
}
} | apache-2.0 | C# |
b189cee21fbccdc54bb6111e0f443cb5a93bf7ab | Refactor code. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Authentication/CompPlatformAuthenticationEvents.cs | src/CompetitionPlatform/Authentication/CompPlatformAuthenticationEvents.cs | using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
namespace CompetitionPlatform.Authentication
{
public class CompPlatformAuthenticationEvents : OpenIdConnectEvents
{
public override Task RemoteFailure(FailureContext context)
{
context.HandleResponse();
context.Response.Redirect("/Home/AuthenticationFailed");
return Task.FromResult(0);
}
}
}
| using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
namespace CompetitionPlatform.Authentication
{
public class CompPlatformAuthenticationEvents : OpenIdConnectEvents
{
public override Task RemoteFailure(FailureContext context)
{
context.HandleResponse();
context.Response.Redirect("/Home/AuthenticationFailed");
return Task.FromResult(0);
}
}
}
| mit | C# |
c34fc05c468a19ee081176fccb96f907108227a1 | set synced rev. nr. 2218 in assembly info | bsoja/ZXing.Net,DHMechatronicAG/ZXing.Net,bsoja/ZXing.Net,bsoja/ZXing.Net,micjahn/ZXing.Net,micjahn/ZXing.Net,micjahn/ZXing.Net,DHMechatronicAG/ZXing.Net,DHMechatronicAG/ZXing.Net | Source/lib/Properties/AssemblyInfo.cs | Source/lib/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
#if NET20
[assembly: AssemblyTitle("zxing.net for .net 2.0")]
#endif
#if NET40
[assembly: AssemblyTitle("zxing.net for .net 4.0")]
#endif
#if SILVERLIGHT4
[assembly: AssemblyTitle("zxing.net for silverlight 4")]
#endif
#if WINDOWS_PHONE70
[assembly: AssemblyTitle("zxing.net for windows phone 7.0")]
#endif
#if WINDOWS_PHONE71
[assembly: AssemblyTitle("zxing.net for windows phone 7.1")]
#endif
[assembly: AssemblyDescription("port of the java based barcode scanning library for .net (java zxing rev. 2218)")]
[assembly: AssemblyCompany("ZXing.Net Developement")]
[assembly: AssemblyProduct("ZXing.Net")]
[assembly: AssemblyCopyright("Copyright 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Guid("ECE3AB74-9DD1-4CFB-9D48-FCBFB30E06D6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Revision
// Build Number
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")]
[assembly: InternalsVisibleTo("zxing.test, PublicKey=0024000004800000140100000602000000240000525341310008000001000100014c9a01956f13a339130616473f69f975e086d9a3a56278936b12c48ca45a4ddfee05c21cdc22aedd84e9468283127a20bba4761c4e0d9836623fc991d562a508845fe314a435bd6c6ff4b0b1d7a141ef93dc1c62252438723f0f93668288673ea6042e583b0eed040e3673aca584f96d4dca19937fbed30e6cd3c0409db82d5c5d2067710d8d86e008447201d99238b94d91171bb0edf3e854985693051ba5167ca6ae650aca5dd65471d68835db00ce1728c58c7bbf9a5d152f491123caf9c0f686dc4e48e1ef63eaf738a12b3771c24d595cc5a5b5daf2cc7611756e9ba3cc89f08fb9adf39685bd5356858c010eb9aa8a767e5ef020408e0c9746cbb5a8")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
#if NET20
[assembly: AssemblyTitle("zxing.net for .net 2.0")]
#endif
#if NET40
[assembly: AssemblyTitle("zxing.net for .net 4.0")]
#endif
#if SILVERLIGHT4
[assembly: AssemblyTitle("zxing.net for silverlight 4")]
#endif
#if WINDOWS_PHONE70
[assembly: AssemblyTitle("zxing.net for windows phone 7.0")]
#endif
#if WINDOWS_PHONE71
[assembly: AssemblyTitle("zxing.net for windows phone 7.1")]
#endif
[assembly: AssemblyDescription("port of the java based barcode scanning library for .net (java zxing rev. 2196)")]
[assembly: AssemblyCompany("ZXing.Net Developement")]
[assembly: AssemblyProduct("ZXing.Net")]
[assembly: AssemblyCopyright("Copyright 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Guid("ECE3AB74-9DD1-4CFB-9D48-FCBFB30E06D6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Revision
// Build Number
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")]
[assembly: InternalsVisibleTo("zxing.test, PublicKey=0024000004800000140100000602000000240000525341310008000001000100014c9a01956f13a339130616473f69f975e086d9a3a56278936b12c48ca45a4ddfee05c21cdc22aedd84e9468283127a20bba4761c4e0d9836623fc991d562a508845fe314a435bd6c6ff4b0b1d7a141ef93dc1c62252438723f0f93668288673ea6042e583b0eed040e3673aca584f96d4dca19937fbed30e6cd3c0409db82d5c5d2067710d8d86e008447201d99238b94d91171bb0edf3e854985693051ba5167ca6ae650aca5dd65471d68835db00ce1728c58c7bbf9a5d152f491123caf9c0f686dc4e48e1ef63eaf738a12b3771c24d595cc5a5b5daf2cc7611756e9ba3cc89f08fb9adf39685bd5356858c010eb9aa8a767e5ef020408e0c9746cbb5a8")] | apache-2.0 | C# |
81746d7d3d1641a5bfd17fe67f9bc72579c3daae | Use Queue+lock and simplify | smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework | osu.Framework/Allocation/AsyncDisposalQueue.cs | osu.Framework/Allocation/AsyncDisposalQueue.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace osu.Framework.Allocation
{
/// <summary>
/// A queue which batches object disposal on threadpool threads.
/// </summary>
internal static class AsyncDisposalQueue
{
private static readonly Queue<IDisposable> disposal_queue = new Queue<IDisposable>();
private static Task runTask;
public static void Enqueue(IDisposable disposable)
{
lock (disposal_queue)
disposal_queue.Enqueue(disposable);
if (runTask?.Status < TaskStatus.Running)
return;
runTask = Task.Run(() =>
{
lock (disposal_queue)
{
while (disposal_queue.Count > 0)
disposal_queue.Dequeue().Dispose();
}
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace osu.Framework.Allocation
{
/// <summary>
/// A queue which batches object disposal on threadpool threads.
/// </summary>
internal static class AsyncDisposalQueue
{
private static readonly ConcurrentQueue<IDisposable> disposal_queue = new ConcurrentQueue<IDisposable>();
private static readonly object task_lock = new object();
private static Task runTask;
public static void Enqueue(IDisposable disposable)
{
disposal_queue.Enqueue(disposable);
lock (task_lock)
{
if (runTask != null
&& (runTask.Status == TaskStatus.WaitingForActivation
|| runTask.Status == TaskStatus.WaitingToRun
|| runTask.Status == TaskStatus.Created))
{
return;
}
runTask = Task.Run(() =>
{
while (disposal_queue.TryDequeue(out var toDispose))
toDispose.Dispose();
});
}
}
}
}
| mit | C# |
2cffce805aef4f2430328b8c39f6262c94cfe362 | add flashlight mod | smoogipoo/osu,ppy/osu,DrabWeb/osu,peppy/osu,naoey/osu,naoey/osu,smoogipoo/osu,UselessToucan/osu,johnneijzen/osu,2yangk23/osu,smoogipooo/osu,UselessToucan/osu,EVAST9919/osu,DrabWeb/osu,NeoAdonis/osu,ZLima12/osu,NeoAdonis/osu,ppy/osu,naoey/osu,ZLima12/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,EVAST9919/osu,2yangk23/osu,DrabWeb/osu,peppy/osu,UselessToucan/osu,johnneijzen/osu,NeoAdonis/osu | osu.Game.Rulesets.Osu/Mods/OsuModFlashlight.cs | osu.Game.Rulesets.Osu/Mods/OsuModFlashlight.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.OpenGL.Vertices;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.UI;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModFlashlight : ModFlashlight, IApplicableToRulesetContainer<OsuHitObject>
{
public override double ScoreMultiplier => 1.12;
public void ApplyToRulesetContainer(RulesetContainer<OsuHitObject> rulesetContainer)
{
rulesetContainer.KeyBindingInputManager.Add(new Flashlight
{
RelativeSizeAxes = Axes.Both,
});
}
private class Flashlight : Drawable, IRequireHighFrequencyMousePosition
{
private Shader shader;
private readonly MousePositionWrapper mousePosWrapper = new MousePositionWrapper();
protected override DrawNode CreateDrawNode() => new FlashlightDrawNode();
protected override void ApplyDrawNode(DrawNode node)
{
base.ApplyDrawNode(node);
var flashNode = (FlashlightDrawNode)node;
flashNode.Shader = shader;
flashNode.ScreenSpaceDrawQuad = ScreenSpaceDrawQuad;
flashNode.MousePosWrapper = mousePosWrapper;
flashNode.FlashlightSize = 100f;
}
[BackgroundDependencyLoader]
private void load(ShaderManager shaderManager)
{
shader = shaderManager.Load(VertexShaderDescriptor.POSITION, "Flashlight");
}
protected override bool OnMouseMove(MouseMoveEvent e)
{
mousePosWrapper.MousePosition = e.ScreenSpaceMousePosition;
return base.OnMouseMove(e);
}
}
private class MousePositionWrapper
{
public Vector2 MousePosition;
}
private class FlashlightDrawNode : DrawNode
{
public Shader Shader;
public Quad ScreenSpaceDrawQuad;
public MousePositionWrapper MousePosWrapper;
public float FlashlightSize;
private bool sizeSet;
public override void Draw(Action<TexturedVertex2D> vertexAction)
{
base.Draw(vertexAction);
Shader.Bind();
// ReSharper disable once AssignmentInConditionalExpression
if(sizeSet = !sizeSet)
Shader.GetUniform<float>("flashlightSize").UpdateValue(ref FlashlightSize);
Shader.GetUniform<Vector2>("mousePos").UpdateValue(ref MousePosWrapper.MousePosition);
Texture.WhitePixel.DrawQuad(ScreenSpaceDrawQuad, DrawColourInfo.Colour, vertexAction: vertexAction);
Shader.Unbind();
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModFlashlight : ModFlashlight
{
public override double ScoreMultiplier => 1.12;
}
}
| mit | C# |
6620eadec3f1c7fe5fac7b98d52683d1a05aba4a | Reduce default hover sound debounce interval | NeoAdonis/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu,UselessToucan/osu,ppy/osu | osu.Game/Graphics/UserInterface/HoverSounds.cs | osu.Game/Graphics/UserInterface/HoverSounds.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Framework.Threading;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverSounds : CompositeDrawable
{
private SampleChannel sampleHover;
/// <summary>
/// Length of debounce for hover sound playback, in milliseconds. Default is 50ms.
/// </summary>
public double HoverDebounceTime { get; } = 20;
protected readonly HoverSampleSet SampleSet;
public HoverSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal)
{
SampleSet = sampleSet;
RelativeSizeAxes = Axes.Both;
}
private ScheduledDelegate playDelegate;
protected override bool OnHover(HoverEvent e)
{
playDelegate?.Cancel();
if (HoverDebounceTime <= 0)
sampleHover?.Play();
else
playDelegate = Scheduler.AddDelayed(() => sampleHover?.Play(), HoverDebounceTime);
return base.OnHover(e);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleHover = audio.Samples.Get($@"UI/generic-hover{SampleSet.GetDescription()}");
}
}
public enum HoverSampleSet
{
[Description("")]
Loud,
[Description("-soft")]
Normal,
[Description("-softer")]
Soft
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Framework.Threading;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverSounds : CompositeDrawable
{
private SampleChannel sampleHover;
/// <summary>
/// Length of debounce for hover sound playback, in milliseconds. Default is 50ms.
/// </summary>
public double HoverDebounceTime { get; } = 50;
protected readonly HoverSampleSet SampleSet;
public HoverSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal)
{
SampleSet = sampleSet;
RelativeSizeAxes = Axes.Both;
}
private ScheduledDelegate playDelegate;
protected override bool OnHover(HoverEvent e)
{
playDelegate?.Cancel();
if (HoverDebounceTime <= 0)
sampleHover?.Play();
else
playDelegate = Scheduler.AddDelayed(() => sampleHover?.Play(), HoverDebounceTime);
return base.OnHover(e);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleHover = audio.Samples.Get($@"UI/generic-hover{SampleSet.GetDescription()}");
}
}
public enum HoverSampleSet
{
[Description("")]
Loud,
[Description("-soft")]
Normal,
[Description("-softer")]
Soft
}
}
| mit | C# |
07c2e0ced0bd443b784ff0418ae432f78e852c80 | Change ASP.NET tool version to reflect project format. | blackdwarf/cli,EdwardBlair/cli,ravimeda/cli,nguerrera/cli,ravimeda/cli,EdwardBlair/cli,Faizan2304/cli,EdwardBlair/cli,dasMulli/cli,AbhitejJohn/cli,AbhitejJohn/cli,weshaggard/cli,svick/cli,mlorbetske/cli,Faizan2304/cli,mlorbetske/cli,jonsequitur/cli,harshjain2/cli,weshaggard/cli,dasMulli/cli,jonsequitur/cli,blackdwarf/cli,weshaggard/cli,weshaggard/cli,livarcocc/cli-1,johnbeisner/cli,harshjain2/cli,johnbeisner/cli,nguerrera/cli,jonsequitur/cli,AbhitejJohn/cli,weshaggard/cli,nguerrera/cli,blackdwarf/cli,mlorbetske/cli,ravimeda/cli,livarcocc/cli-1,svick/cli,jonsequitur/cli,nguerrera/cli,blackdwarf/cli,dasMulli/cli,johnbeisner/cli,Faizan2304/cli,livarcocc/cli-1,AbhitejJohn/cli,mlorbetske/cli,svick/cli,harshjain2/cli | src/Microsoft.DotNet.ProjectJsonMigration/ConstantPackageVersions.cs | src/Microsoft.DotNet.ProjectJsonMigration/ConstantPackageVersions.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DotNet.ProjectJsonMigration
{
internal class ConstantPackageVersions
{
public const string AspNetToolsVersion = "1.0.0-msbuild1-final";
public const string TestSdkPackageVersion = "15.0.0-preview-20161024-02";
public const string XUnitPackageVersion = "2.2.0-beta3-build3402";
public const string XUnitRunnerPackageVersion = "2.2.0-beta4-build1188";
public const string MstestTestAdapterVersion = "1.1.3-preview";
public const string MstestTestFrameworkVersion = "1.0.4-preview";
}
} | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DotNet.ProjectJsonMigration
{
internal class ConstantPackageVersions
{
public const string AspNetToolsVersion = "1.0.0-rc1-final";
public const string TestSdkPackageVersion = "15.0.0-preview-20161024-02";
public const string XUnitPackageVersion = "2.2.0-beta3-build3402";
public const string XUnitRunnerPackageVersion = "2.2.0-beta4-build1188";
public const string MstestTestAdapterVersion = "1.1.3-preview";
public const string MstestTestFrameworkVersion = "1.0.4-preview";
}
} | mit | C# |
97b314d61155e5dfa192f1cbf639638a8a112e70 | Update QuoteRepository.cs | Youngsie1997/NadekoBot,PravEF/EFNadekoBot,Midnight-Myth/Mitternacht-NEW,WoodenGlaze/NadekoBot,halitalf/NadekoMods,Midnight-Myth/Mitternacht-NEW,powered-by-moe/MikuBot,Blacnova/NadekoBot,ScarletKuro/NadekoBot,Midnight-Myth/Mitternacht-NEW,shikhir-arora/NadekoBot,miraai/NadekoBot,Nielk1/NadekoBot,Taknok/NadekoBot,gfrewqpoiu/NadekoBot,ShadowNoire/NadekoBot,Midnight-Myth/Mitternacht-NEW | src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs | src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs | using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
{
var rngk = new NadekoRandom();
string lowertext = text.ToLowerInvariant();
string uppertext = text.ToUpperInvariant();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword && (q.Text.Contains(text) || q.Text.Contains(lowertext) || q.Text.Contains(uppertext))).OrderBy(q => rngk.Next()).FirstOrDefaultAsync();
}
}
}
| using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
{
var rngk = new NadekoRandom();
lowertext = text.ToLowerInvariant();
uppertext = text.ToUpperInvariant();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword && (q.Text.Contains(text) || q.Text.Contains(lowertext) || q.Text.Contains(uppertext))).OrderBy(q => rngk.Next()).FirstOrDefaultAsync();
}
}
}
| unlicense | C# |
7a85591e3f92dbe6655b75b31d0e5b34aafbcc9c | remove redundant code | modulexcite/colored-console,colored-console/colored-console,colored-console/colored-console,modulexcite/colored-console | src/ColoredConsole/ColorConsole.cs | src/ColoredConsole/ColorConsole.cs | // <copyright file="ColorConsole.cs" company="ColoredConsole contributors">
// Copyright (c) ColoredConsole contributors. (coloredconsole@gmail.com)
// </copyright>
namespace ColoredConsole
{
using System;
public static class ColorConsole
{
private static readonly object @lock = new object();
public static void WriteLine(ColorText text)
{
lock (@lock)
{
foreach (var token in text.ToTokenArray())
{
if (token.Color.HasValue)
{
var originalColor = Console.ForegroundColor;
Console.ForegroundColor = token.Color.Value;
try
{
Console.Write(token);
}
finally
{
Console.ForegroundColor = originalColor;
}
}
else
{
Console.Write(token);
}
}
Console.WriteLine();
}
}
public static void WriteLine(params ColorToken[] tokens)
{
WriteLine(new ColorText(tokens));
}
}
}
| // <copyright file="ColorConsole.cs" company="ColoredConsole contributors">
// Copyright (c) ColoredConsole contributors. (coloredconsole@gmail.com)
// </copyright>
namespace ColoredConsole
{
using System;
public static class ColorConsole
{
private static readonly object @lock = new object();
public static void WriteLine(ColorText text)
{
lock (@lock)
{
foreach (var token in text.ToTokenArray())
{
if (token.Color.HasValue)
{
var originalColor = Console.ForegroundColor;
Console.ForegroundColor = token.Color.Value;
try
{
Console.Write(token);
}
finally
{
Console.ForegroundColor = originalColor;
}
}
else
{
Console.Write(token);
}
}
Console.WriteLine();
}
}
public static void WriteLine(params ColorToken[] tokens)
{
if (tokens == null)
{
return;
}
WriteLine(new ColorText(tokens));
}
public static void WriteLine()
{
Console.WriteLine();
}
}
}
| mit | C# |
f4e70cf38cddfafecfd906298cd0ce9f453a1d75 | Remove unimplemented WhenReboot flag. | HangfireIO/Cronos | src/Cronos/CronExpressionFlag.cs | src/Cronos/CronExpressionFlag.cs | using System;
namespace Cronos
{
[Flags]
public enum CronExpressionFlag
{
None = 0x0,
DayOfMonthStar = 0x1,
DayOfWeekStar = 0x2,
MinuteStar = 0x4,
HourStar = 0x8,
SecondStar = 0x10,
DayOfMonthLast = 0x20,
DayOfWeekLast = 0x40,
}
}
| using System;
namespace Cronos
{
[Flags]
public enum CronExpressionFlag
{
None = 0x0,
DayOfMonthStar = 0x1,
DayOfWeekStar = 0x2,
WhenReboot = 0x4, // TODO: Remove this
MinuteStar = 0x8,
HourStar = 0x10,
SecondStar = 0x20,
DayOfMonthLast = 0x40,
DayOfWeekLast = 0x80,
}
}
| mit | C# |
ce4e77f436f8e01f190fc18e04f762a81574f938 | add some specification around exception handling behaviour. | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts.UnitTests/Commands/AccountLevyStatus/An_UpdateAccountToLevyHandler_.cs | src/SFA.DAS.EmployerAccounts.UnitTests/Commands/AccountLevyStatus/An_UpdateAccountToLevyHandler_.cs | using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using NUnit.Framework.Internal;
using SFA.DAS.EmployerAccounts.Commands.AccountLevyStatus;
using SFA.DAS.EmployerAccounts.Data;
namespace SFA.DAS.EmployerAccounts.UnitTests.Commands.AccountLevyStatus
{
[ExcludeFromCodeCoverage]
[TestFixture]
public class An_UpdateAccountToLevyHandler_
{
private UpdateAccountToLevyHandler _sut;
private long _accountId = 90125;
private Mock<IEmployerAccountRepository> _accountRepository;
[SetUp]
public void Setup()
{
_accountRepository
=
new Mock<IEmployerAccountRepository>();
_sut
=
new UpdateAccountToLevyHandler(
_accountRepository.Object);
}
[Test]
public async Task Updates_Account_To_Be_Levy()
{
_sut
.Handle(
new UpdateAccountToLevy(_accountId));
_accountRepository
.Verify(
m =>
m.SetAccountAsLevy(
_accountId));
}
[Test]
public async Task Propagates_Errors()
{
_accountRepository
.Setup(
m =>
m.SetAccountAsLevy(
It.IsAny<long>()))
.ThrowsAsync(new TestException());
Assert
.ThrowsAsync<TestException>(
() =>
_sut
.Handle(
new UpdateAccountToLevy(_accountId)));
}
}
public class TestException : Exception
{
}
} | using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using SFA.DAS.EmployerAccounts.Commands.AccountLevyStatus;
using SFA.DAS.EmployerAccounts.Data;
namespace SFA.DAS.EmployerAccounts.UnitTests.Commands.AccountLevyStatus
{
[ExcludeFromCodeCoverage]
[TestFixture]
public class An_UpdateAccountToLevyHandler_
{
private UpdateAccountToLevyHandler _sut;
private long _accountId = 90125;
private Mock<IEmployerAccountRepository> _accountRepository;
[SetUp]
public void Setup()
{
_accountRepository
=
new Mock<IEmployerAccountRepository>();
_sut
=
new UpdateAccountToLevyHandler(
_accountRepository.Object);
}
[Test]
public async Task Updates_Account_To_Be_Levy()
{
_sut
.Handle(
new UpdateAccountToLevy(_accountId));
_accountRepository
.Verify(
m =>
m.SetAccountAsLevy(
_accountId));
}
}
} | mit | C# |
6bff2c63138403de54c005b76c8bcffbe669a8e8 | Change property name | andrelmp/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,skynode/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,skynode/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers | src/Services/Catalog/Catalog.API/IntegrationEvents/Events/OrderStockNotConfirmedIntegrationEvent.cs | src/Services/Catalog/Catalog.API/IntegrationEvents/Events/OrderStockNotConfirmedIntegrationEvent.cs | namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events
{
using BuildingBlocks.EventBus.Events;
using System.Collections.Generic;
public class OrderStockNotConfirmedIntegrationEvent : IntegrationEvent
{
public int OrderId { get; }
public List<ConfirmedOrderStockItem> OrderStockItems { get; }
public OrderStockNotConfirmedIntegrationEvent(int orderId,
List<ConfirmedOrderStockItem> orderStockItems)
{
OrderId = orderId;
OrderStockItems = orderStockItems;
}
}
public class ConfirmedOrderStockItem
{
public int ProductId { get; }
public bool Confirmed { get; }
public ConfirmedOrderStockItem(int productId, bool confirmed)
{
ProductId = productId;
Confirmed = confirmed;
}
}
} | namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events
{
using BuildingBlocks.EventBus.Events;
using System.Collections.Generic;
public class OrderStockNotConfirmedIntegrationEvent : IntegrationEvent
{
public int OrderId { get; }
public IEnumerable<ConfirmedOrderStockItem> OrderStockItem { get; }
public OrderStockNotConfirmedIntegrationEvent(int orderId,
IEnumerable<ConfirmedOrderStockItem> orderStockItem)
{
OrderId = orderId;
OrderStockItem = orderStockItem;
}
}
public class ConfirmedOrderStockItem
{
public int ProductId { get; }
public bool Confirmed { get; }
public ConfirmedOrderStockItem(int productId, bool confirmed)
{
ProductId = productId;
Confirmed = confirmed;
}
}
} | mit | C# |
62d9b355385414ee7409a10c4bb2c17ec4177125 | Update version | agileharbor/shipStationAccess | src/Global/GlobalAssemblyInfo.cs | src/Global/GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.71.0" ) ] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.70.0" ) ] | bsd-3-clause | C# |
5d9bb0bd08b3b0e3c2228735e6cc734ac25c0e00 | Disable flaky test https://github.com/Azure/azure-webjobs-sdk-script/issues/1674 | Azure/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script | test/WebJobs.Script.Tests.Integration/ApplicationInsights/ApplicationInsightsCSharpEndToEndTests.cs | test/WebJobs.Script.Tests.Integration/ApplicationInsights/ApplicationInsightsCSharpEndToEndTests.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.Azure.WebJobs.Script.Tests.ApplicationInsights
{
public class ApplicationInsightsCSharpEndToEndTests : ApplicationInsightsEndToEndTestsBase<ApplicationInsightsCSharpEndToEndTests.TestFixture>
{
public ApplicationInsightsCSharpEndToEndTests(TestFixture fixture) : base(fixture)
{
}
[Fact(Skip = "unstable test. https://github.com/Azure/azure-webjobs-sdk-script/issues/1674")]
public async Task ApplicationInsights_Succeeds()
{
await ApplicationInsights_SucceedsTest();
}
public class TestFixture : ApplicationInsightsTestFixture
{
private const string ScriptRoot = @"TestScripts\CSharp";
public TestFixture() : base(ScriptRoot, "csharp")
{
}
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.Azure.WebJobs.Script.Tests.ApplicationInsights
{
public class ApplicationInsightsCSharpEndToEndTests : ApplicationInsightsEndToEndTestsBase<ApplicationInsightsCSharpEndToEndTests.TestFixture>
{
public ApplicationInsightsCSharpEndToEndTests(TestFixture fixture) : base(fixture)
{
}
[Fact]
public async Task ApplicationInsights_Succeeds()
{
await ApplicationInsights_SucceedsTest();
}
public class TestFixture : ApplicationInsightsTestFixture
{
private const string ScriptRoot = @"TestScripts\CSharp";
public TestFixture() : base(ScriptRoot, "csharp")
{
}
}
}
}
| mit | C# |
42ba93628c1b0edd61cf3e6f099bdaa0b7525dfd | Add unit test for analyzing class without imported namespace. | tiesmaster/DebuggerStepThroughRemover,modulexcite/DebuggerStepThroughRemover | DebuggerStepThroughRemover/DebuggerStepThroughRemover.Test/AnalyzerTests.cs | DebuggerStepThroughRemover/DebuggerStepThroughRemover.Test/AnalyzerTests.cs | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestHelper;
namespace DebuggerStepThroughRemover.Test
{
[TestClass]
public class AnalyzerTests : DiagnosticVerifier
{
[TestMethod]
public void WithEmptySourceFile_ShouldNotFindAnything()
{
var test = @"";
VerifyCSharpDiagnostic(test);
}
[TestMethod]
public void Analyzer_WithImportedNameSpace_ShouldReportAttribute()
{
var test = @"
using System.Diagnostics;
namespace ConsoleApplication1
{
[DebuggerStepThrough]
class TypeName
{
}
}";
var expected = new DiagnosticResult
{
Id = "DebuggerStepThroughRemover",
Message = $"Type 'TypeName' is decorated with DebuggerStepThrough attribute",
Severity = DiagnosticSeverity.Warning,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 6, 5)
}
};
VerifyCSharpDiagnostic(test, expected);
}
[TestMethod]
public void Analyzer_WithoutImportedNameSpace_ShouldReportAttribute()
{
var test = @"
namespace ConsoleApplication1
{
[System.Diagnostics.DebuggerStepThrough]
class TypeName
{
}
}";
var expected = new DiagnosticResult
{
Id = "DebuggerStepThroughRemover",
Message = $"Type 'TypeName' is decorated with DebuggerStepThrough attribute",
Severity = DiagnosticSeverity.Warning,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 4, 5)
}
};
VerifyCSharpDiagnostic(test, expected);
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new DebuggerStepThroughRemoverAnalyzer();
}
}
} | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestHelper;
namespace DebuggerStepThroughRemover.Test
{
[TestClass]
public class AnalyzerTests : DiagnosticVerifier
{
[TestMethod]
public void WithEmptySourceFile_ShouldNotFindAnything()
{
var test = @"";
VerifyCSharpDiagnostic(test);
}
[TestMethod]
public void Analyzer_WithImportedNameSpace_ShouldReportAttribute()
{
var test = @"
using System.Diagnostics;
namespace ConsoleApplication1
{
[DebuggerStepThrough]
class TypeName
{
}
}";
var expected = new DiagnosticResult
{
Id = "DebuggerStepThroughRemover",
Message = $"Type 'TypeName' is decorated with DebuggerStepThrough attribute",
Severity = DiagnosticSeverity.Warning,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 6, 5)
}
};
VerifyCSharpDiagnostic(test, expected);
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new DebuggerStepThroughRemoverAnalyzer();
}
}
} | mit | C# |
c584488185744a76798c8999f51eba77af0c8052 | Fix message length. (#809) | ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,Lidefeath/ACE,ACEmulator/ACE,LtRipley36706/ACE | Source/ACE.Server/Network/GameEvent/Events/GameEventDefenderNotification.cs | Source/ACE.Server/Network/GameEvent/Events/GameEventDefenderNotification.cs | using System;
using ACE.Entity.Enum;
using ACE.Server.Network.Enum;
namespace ACE.Server.Network.GameEvent.Events
{
public class GameEventDefenderNotification : GameEventMessage
{
public GameEventDefenderNotification(Session session, string attackerName, DamageType damageType, float percent, uint damage, DamageLocation damageLocation, bool criticalHit, AttackConditions attackConditions)
: base(GameEventType.DefenderNotification, GameMessageGroup.UIQueue, session)
{
Writer.WriteString16L(attackerName);
Writer.Write((uint)damageType);
Writer.Write((double)percent);
Writer.Write(damage);
Writer.Write((uint)damageLocation);
Writer.Write(Convert.ToUInt32(criticalHit));
Writer.Write((UInt64)attackConditions);
Writer.Align();
}
}
}
| using System;
using ACE.Entity.Enum;
using ACE.Server.Network.Enum;
namespace ACE.Server.Network.GameEvent.Events
{
public class GameEventDefenderNotification : GameEventMessage
{
public GameEventDefenderNotification(Session session, string attackerName, DamageType damageType, float percent, uint damage, DamageLocation damageLocation, bool criticalHit, AttackConditions attackConditions)
: base(GameEventType.DefenderNotification, GameMessageGroup.UIQueue, session)
{
Writer.WriteString16L(attackerName);
Writer.Write((uint)damageType);
Writer.Write((double)percent);
Writer.Write(damage);
Writer.Write((uint)damageLocation);
Writer.Write(Convert.ToUInt16(criticalHit));
Writer.Write((UInt64)attackConditions);
}
}
}
| agpl-3.0 | C# |
46cf8c02724ecef4da1ddadd743fd5e524b263c2 | add note to ExampleAttribute | mvalipour/xbehave.net,modulexcite/xbehave.net,hitesh97/xbehave.net,modulexcite/xbehave.net,mvalipour/xbehave.net,adamralph/xbehave.net,xbehave/xbehave.net,hitesh97/xbehave.net | src/Xbehave.2/ExampleAttribute.cs | src/Xbehave.2/ExampleAttribute.cs | // <copyright file="ExampleAttribute.cs" company="xBehave.net contributors">
// Copyright (c) xBehave.net contributors. All rights reserved.
// </copyright>
namespace Xbehave
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Xunit.Sdk;
/// <summary>
/// Provides example values for a scenario passed as arguments to the scenario method.
/// This attribute is designed as a synonym of <see cref="Xunit.InlineDataAttribute"/>,
/// which is the most commonly used data attribute, but you can also use any type of attribute derived from
/// <see cref="Xunit.Sdk.DataAttribute"/> to provide a data source for a scenario.
/// E.g. <see cref="Xunit.InlineDataAttribute"/> or
/// <see cref="Xunit.MemberDataAttribute"/>.
/// </summary>
[DataDiscoverer("Xunit.Sdk.InlineDataDiscoverer", "xunit.core")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Following the pattern of Xunit.InlineDataAttribute.")]
public sealed class ExampleAttribute : DataAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ExampleAttribute"/> class.
/// This attribute is designed as a synonym of <see cref="Xunit.InlineDataAttribute"/>,
/// which is the most commonly used data attribute, but you can also use any type of attribute derived from
/// <see cref="Xunit.Sdk.DataAttribute"/> to provide a data source for a scenario.
/// E.g. <see cref="Xunit.InlineDataAttribute"/> or
/// <see cref="Xunit.MemberDataAttribute"/>.
/// </summary>
/// <param name="data">The data values to pass to the scenario.</param>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "data", Justification = "Following the pattern of Xunit.InlineDataAttribute.")]
public ExampleAttribute(params object[] data)
{
}
/// <inheritdoc/>
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
// NOTE (adamralph): When adding wpa81 support, see InlineDataAttribute implementation
throw new InvalidOperationException();
}
}
}
| // <copyright file="ExampleAttribute.cs" company="xBehave.net contributors">
// Copyright (c) xBehave.net contributors. All rights reserved.
// </copyright>
namespace Xbehave
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Xunit.Sdk;
/// <summary>
/// Provides example values for a scenario passed as arguments to the scenario method.
/// This attribute is designed as a synonym of <see cref="Xunit.InlineDataAttribute"/>,
/// which is the most commonly used data attribute, but you can also use any type of attribute derived from
/// <see cref="Xunit.Sdk.DataAttribute"/> to provide a data source for a scenario.
/// E.g. <see cref="Xunit.InlineDataAttribute"/> or
/// <see cref="Xunit.MemberDataAttribute"/>.
/// </summary>
[DataDiscoverer("Xunit.Sdk.InlineDataDiscoverer", "xunit.core")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Following the pattern of Xunit.InlineDataAttribute.")]
public sealed class ExampleAttribute : DataAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ExampleAttribute"/> class.
/// This attribute is designed as a synonym of <see cref="Xunit.InlineDataAttribute"/>,
/// which is the most commonly used data attribute, but you can also use any type of attribute derived from
/// <see cref="Xunit.Sdk.DataAttribute"/> to provide a data source for a scenario.
/// E.g. <see cref="Xunit.InlineDataAttribute"/> or
/// <see cref="Xunit.MemberDataAttribute"/>.
/// </summary>
/// <param name="data">The data values to pass to the scenario.</param>
[SuppressMessage(
"Microsoft.Usage",
"CA1801:ReviewUnusedParameters",
MessageId = "data",
Justification = "Following the pattern of Xunit.InlineDataAttribute.")]
public ExampleAttribute(params object[] data)
{
}
/// <inheritdoc/>
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
// This should never be called, because the discoverer can always find the data.
throw new InvalidOperationException();
}
}
}
| mit | C# |
65eccffa65abb46176369b351e68ff6355512c38 | Update Inventory.cs | mihov/J.D.Salinger | Waits/TheGame/Inventory.cs | Waits/TheGame/Inventory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Waits
{
class Inventory
{
private Dictionary<Item, int> items;
private int money;
public Inventory(int money, params Item[] items)
{
this.Money = money;
foreach (Item item in items)
{
if (this.items.ContainsKey(item))
{
this.items[item]++;
}
else
{
this.items.Add(item, 1);
}
}
}
public int Money
{
get { return this.money; }
set
{
if (value < 0)
{
throw new ArgumentException("Money can't be less than 0.");
}
this.money = value;
}
}
public void Stash(Item item, int count)
{
if (this.items.ContainsKey(item))
{
this.items[item] += count;
}
else
{
this.items.Add(item, count);
}
}
public Item Take(Item item, int count)
{
if (this.items.ContainsKey(item))
{
if (this.items[item] < count)
{
//TODO some exception when you can't get that many items
}
if (this.items[item] == count)
{
this.items.Remove(item);
}
this.items[item] -= count;
}
else
{
//TODO some exception when you can't get that many items
}
return item;
//TODO empty item?
}
public override string ToString()
{
StringBuilder result = new StringBuilder();
foreach (var item in this.items)
{
result.AppendFormat("{0} x {1}", item.Key, item.Value);
result.AppendLine();
}
return base.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Waits
{
class Inventory
{
private List<Item> items;
private int money;
public Inventory(int money, params Item[] items)
{
this.Money = money;
foreach (Item item in items)
{
this.items.Add(item);
}
}
public int Money
{
get { return this.money; }
set
{
if (value < 0)
{
throw new ArgumentException("Money can't be less than 0.");
}
this.money = value;
}
}
public void Stash(Item item)
{
items.Add(item);
}
public Item Take(Item item)
{
if (items.Contains(item))
{
items.Remove(item);
return item;
}
return item;//TODO empty item?
}
}
}
| unlicense | C# |
bde64e3dd125dacadd30e60f52f2d3ff541f44c2 | Add "virtual" + AddCompletedStep | rapidcore/rapidcore,rapidcore/rapidcore | src/Migration/MigrationInfo.cs | src/Migration/MigrationInfo.cs | using System;
using System.Collections.Generic;
namespace RapidCore.Migration
{
/// <summary>
/// Information about a migration that has run, either
/// fully or partially
/// </summary>
public class MigrationInfo
{
public virtual string Id { get; set; }
/// <summary>
/// Gets or sets the name of the migration.
/// </summary>
public virtual string Name { get; set; }
/// <summary>
/// Gets or sets the list of steps that have been successfully completed.
/// </summary>
public virtual List<string> StepsCompleted { get; set; } = new List<string>();
/// <summary>
/// Gets or sets a value indicating whether the migration has
/// been completed (i.e. all steps have run successfully).
/// </summary>
public virtual bool MigrationCompleted { get; set; }
/// <summary>
/// Gets or sets the total migration time in milliseconds
/// </summary>
public virtual long TotalMigrationTimeInMs { get; set; }
/// <summary>
/// Gets or sets the completed at date and time in UTC.
/// </summary>
public virtual DateTime CompletedAtUtc { get; set; }
/// <summary>
/// Add a completed step
/// </summary>
/// <param name="stepName">The name of the completed step</param>
public virtual void AddCompletedStep(string stepName)
{
StepsCompleted.Add(stepName);
}
}
} | using System;
using System.Collections.Generic;
namespace RapidCore.Migration
{
/// <summary>
/// Information about a migration that has run, either
/// fully or partially
/// </summary>
public class MigrationInfo
{
public virtual string Id { get; set; }
/// <summary>
/// Gets or sets the name of the migration.
/// </summary>
public virtual string Name { get; set; }
/// <summary>
/// Gets or sets the list of steps that have been successfully completed.
/// </summary>
public List<string> StepsCompleted { get; set; } = new List<string>();
/// <summary>
/// Gets or sets a value indicating whether the migration has
/// been completed (i.e. all steps have run successfully).
/// </summary>
public bool MigrationCompleted { get; set; }
/// <summary>
/// Gets or sets the total migration time in milliseconds
/// </summary>
public long TotalMigrationTimeInMs { get; set; }
/// <summary>
/// Gets or sets the completed at date and time in UTC.
/// </summary>
public DateTime CompletedAtUtc { get; set; }
}
} | mit | C# |
a97d34db76918623c84c4cc5c48590d81316dded | add Elapsed to measure | aloneguid/support | src/NetBox/Performance/Measure.cs | src/NetBox/Performance/Measure.cs | using System;
using System.Diagnostics;
namespace NetBox.Performance
{
/// <summary>
/// Measures a time slice as precisely as possible
/// </summary>
public class Measure : IDisposable
{
private readonly Stopwatch _sw = new Stopwatch();
/// <summary>
/// Creates the measure object
/// </summary>
public Measure()
{
_sw.Start();
}
/// <summary>
/// Returns number of elapsed ticks since the start of measure.
/// The measuring process will continue running.
/// </summary>
public long ElapsedTicks => _sw.ElapsedTicks;
/// <summary>
/// Returns number of elapsed milliseconds since the start of measure.
/// The measuring process will continue running.
/// </summary>
public long ElapsedMilliseconds => _sw.ElapsedMilliseconds;
/// <summary>
/// Gets time elapsed from the time this measure was created
/// </summary>
public TimeSpan Elapsed => _sw.Elapsed;
/// <summary>
/// Stops measure object if still running
/// </summary>
public void Dispose()
{
if (_sw.IsRunning)
{
_sw.Stop();
}
}
}
}
| using System;
using System.Diagnostics;
namespace NetBox.Performance
{
/// <summary>
/// Measures a time slice as precisely as possible
/// </summary>
public class Measure : IDisposable
{
private readonly Stopwatch _sw = new Stopwatch();
/// <summary>
/// Creates the measure object
/// </summary>
public Measure()
{
_sw.Start();
}
/// <summary>
/// Returns number of elapsed ticks since the start of measure.
/// The measuring process will continue running.
/// </summary>
public long ElapsedTicks => _sw.ElapsedTicks;
/// <summary>
/// Returns number of elapsed milliseconds since the start of measure.
/// The measuring process will continue running.
/// </summary>
public long ElapsedMilliseconds => _sw.ElapsedMilliseconds;
/// <summary>
/// Stops measure object if still running
/// </summary>
public void Dispose()
{
if (_sw.IsRunning)
{
_sw.Stop();
}
}
}
}
| mit | C# |
aca5b49994fd6f19b6c9f216e49e1d0dc82a7b13 | Test [Authorize] attribute added to Goofy.Component.ControllersAndRoutes.HomeController: | GoofyCMS/Backend,GoofyCMS/Backend,GoofyCMS/Backend | components/Goofy.Component.ControllersAndRoutes/Controllers/HomeController.cs | components/Goofy.Component.ControllersAndRoutes/Controllers/HomeController.cs | using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.OptionsModel;
using System.Linq;
namespace Goofy.Component.ControllersAndRoutes.Controllers
{
public class HomeController : Controller
{
private readonly ControllerAndRoutesConfiguration _config;
private readonly IWriter _writer;
private readonly BookContext _bookContext;
public HomeController(IWriter writer, IOptions<ControllerAndRoutesConfiguration> config, BookContext bookContext)
{
_writer = writer;
_config = config.Value;
_bookContext = bookContext;
}
// GET: /hello/
[HttpGet("hello")]
[Authorize(Policy = "RequireViewComponent")]
public string Index()
{
var message = "Hello World from a third party controller, protected by a RequireViewComponent policy.";
_writer.Write(message);
return string.Format("Message \"{0}\" was written on wwwroot directory. \n The value of SampleKey in the config.json file is \"{1}\"", message, _config.SampleKey);
}
[HttpGet("book")]
public Book[] Book()
{
//return null;
return _bookContext.Books.ToArray();
}
}
}
| using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.OptionsModel;
using System.Linq;
namespace Goofy.Component.ControllersAndRoutes.Controllers
{
public class HomeController : Controller
{
private readonly ControllerAndRoutesConfiguration _config;
private readonly IWriter _writer;
private readonly BookContext _bookContext;
public HomeController(IWriter writer, IOptions<ControllerAndRoutesConfiguration> config, BookContext bookContext)
{
_writer = writer;
_config = config.Value;
_bookContext = bookContext;
}
// GET: /hello/
[HttpGet("hello")]
public string Index()
{
var message = "Hello World from a third party controller";
_writer.Write(message);
return string.Format("Message \"{0}\" was written on wwwroot directory. \n The value of SampleKey in the config.json file is \"{1}\"", message, _config.SampleKey);
}
[HttpGet("book")]
public Book[] Book()
{
//return null;
return _bookContext.Books.ToArray();
}
}
}
| mit | C# |
206d9b21a1fe1dbf42ec69deb1995cab1a2efe49 | Fix broken LfMerge executable | sillsdev/LfMerge,ermshiperete/LfMerge,sillsdev/LfMerge,ermshiperete/LfMerge,sillsdev/LfMerge,ermshiperete/LfMerge | src/LfMerge.Core/MainClass.cs | src/LfMerge.Core/MainClass.cs | // Copyright (c) 2016 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using Autofac;
using LfMerge.Core.Actions.Infrastructure;
using LfMerge.Core.LanguageForge.Infrastructure;
using LfMerge.Core.Logging;
using LfMerge.Core.MongoConnector;
using LfMerge.Core.Reporting;
using LfMerge.Core.Queues;
using LfMerge.Core.Settings;
using Palaso.Progress;
namespace LfMerge.Core
{
public static class MainClass
{
public static IContainer Container { get; internal set; }
public static ILogger Logger { get; set; }
static MainClass()
{
if (Container == null)
Container = RegisterTypes().Build();
Logger = Container.Resolve<ILogger>();
}
internal static ContainerBuilder RegisterTypes()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<LfMergeSettings>().SingleInstance().AsSelf();
containerBuilder.RegisterType<SyslogLogger>().SingleInstance().As<ILogger>()
.WithParameter(new TypedParameter(typeof(string), "LfMerge"));
containerBuilder.RegisterType<LanguageDepotProject>().As<ILanguageDepotProject>();
containerBuilder.RegisterType<ProcessingState.Factory>().As<IProcessingStateDeserialize>();
containerBuilder.RegisterType<ChorusHelper>().SingleInstance().AsSelf();
containerBuilder.RegisterType<MongoConnection>().SingleInstance().As<IMongoConnection>().ExternallyOwned();
containerBuilder.RegisterType<MongoProjectRecordFactory>().AsSelf();
containerBuilder.RegisterType<EntryCounts>().AsSelf();
containerBuilder.RegisterType<SyslogProgress>().As<IProgress>();
containerBuilder.RegisterType<LanguageForgeProxy>().As<ILanguageForgeProxy>();
Actions.Action.Register(containerBuilder);
Queue.Register(containerBuilder);
return containerBuilder;
}
}
}
| // Copyright (c) 2016 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using Autofac;
using LfMerge.Core.Actions.Infrastructure;
using LfMerge.Core.LanguageForge.Infrastructure;
using LfMerge.Core.Logging;
using LfMerge.Core.MongoConnector;
using LfMerge.Core.Reporting;
using LfMerge.Core.Queues;
using LfMerge.Core.Settings;
using Palaso.Progress;
namespace LfMerge.Core
{
public static class MainClass
{
public static IContainer Container { get; internal set; }
public static ILogger Logger { get; set; }
public static void Initialize()
{
if (Container == null)
Container = RegisterTypes().Build();
Logger = Container.Resolve<ILogger>();
}
internal static ContainerBuilder RegisterTypes()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<LfMergeSettings>().SingleInstance().AsSelf();
containerBuilder.RegisterType<SyslogLogger>().SingleInstance().As<ILogger>()
.WithParameter(new TypedParameter(typeof(string), "LfMerge"));
containerBuilder.RegisterType<LanguageDepotProject>().As<ILanguageDepotProject>();
containerBuilder.RegisterType<ProcessingState.Factory>().As<IProcessingStateDeserialize>();
containerBuilder.RegisterType<ChorusHelper>().SingleInstance().AsSelf();
containerBuilder.RegisterType<MongoConnection>().SingleInstance().As<IMongoConnection>().ExternallyOwned();
containerBuilder.RegisterType<MongoProjectRecordFactory>().AsSelf();
containerBuilder.RegisterType<EntryCounts>().AsSelf();
containerBuilder.RegisterType<SyslogProgress>().As<IProgress>();
containerBuilder.RegisterType<LanguageForgeProxy>().As<ILanguageForgeProxy>();
Actions.Action.Register(containerBuilder);
Queue.Register(containerBuilder);
return containerBuilder;
}
}
}
| mit | C# |
ce74056b10930df2c7d0c1c71e42838c88320a28 | Add Single/AggregateContactsSupported properties for MT | moljac/Xamarin.Mobile,xamarin/Xamarin.Mobile,orand/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile,nexussays/Xamarin.Mobile,xamarin/Xamarin.Mobile | MonoTouch/MonoMobile.Extensions/Contacts/AddressBook.cs | MonoTouch/MonoMobile.Extensions/Contacts/AddressBook.cs | using System;
using System.Linq;
using System.Linq.Expressions;
using MonoTouch.AddressBook;
using System.Collections.Generic;
namespace Xamarin.Contacts
{
public class AddressBook
: IQueryable<Contact>
{
public AddressBook()
{
this.addressBook = new ABAddressBook();
this.provider = new ContactQueryProvider (this.addressBook);
}
public bool IsReadOnly
{
get { return true; }
}
public bool SingleContactsSupported
{
get { return true; }
}
public bool AggregateContactsSupported
{
get { return false; }
}
public bool PreferContactAggregation
{
get;
set;
}
public IEnumerator<Contact> GetEnumerator()
{
return this.addressBook.GetPeople().Select (ContactHelper.GetContact).GetEnumerator();
}
public Contact Load (string id)
{
if (String.IsNullOrWhiteSpace (id))
throw new ArgumentNullException ("id");
int rowId;
if (!Int32.TryParse (id, out rowId))
throw new ArgumentException ("Not a valid contact ID", "id");
ABPerson person = this.addressBook.GetPerson (rowId);
if (person == null)
return null;
return ContactHelper.GetContact (person);
}
private readonly ABAddressBook addressBook;
private readonly IQueryProvider provider;
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
Type IQueryable.ElementType
{
get { return typeof(Contact); }
}
Expression IQueryable.Expression
{
get { return Expression.Constant (this); }
}
IQueryProvider IQueryable.Provider
{
get { return this.provider; }
}
}
} | using System;
using System.Linq;
using System.Linq.Expressions;
using MonoTouch.AddressBook;
using System.Collections.Generic;
namespace Xamarin.Contacts
{
public class AddressBook
: IQueryable<Contact>
{
public AddressBook()
{
this.addressBook = new ABAddressBook();
this.provider = new ContactQueryProvider (this.addressBook);
}
public bool IsReadOnly
{
get { return true; }
}
public bool PreferContactAggregation
{
get;
set;
}
public IEnumerator<Contact> GetEnumerator()
{
return this.addressBook.GetPeople().Select (ContactHelper.GetContact).GetEnumerator();
}
public Contact Load (string id)
{
if (String.IsNullOrWhiteSpace (id))
throw new ArgumentNullException ("id");
int rowId;
if (!Int32.TryParse (id, out rowId))
throw new ArgumentException ("Not a valid contact ID", "id");
ABPerson person = this.addressBook.GetPerson (rowId);
if (person == null)
return null;
return ContactHelper.GetContact (person);
}
private readonly ABAddressBook addressBook;
private readonly IQueryProvider provider;
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
Type IQueryable.ElementType
{
get { return typeof(Contact); }
}
Expression IQueryable.Expression
{
get { return Expression.Constant (this); }
}
IQueryProvider IQueryable.Provider
{
get { return this.provider; }
}
}
} | apache-2.0 | C# |
e14fd0f1d001217e2bd7f39cdd355213d5e1f941 | Fix bug in SampleCourse | riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy | sample/sample_course/content/en/calculator/20_the_view/the_view.dothtml.csx | sample/sample_course/content/en/calculator/20_the_view/the_view.dothtml.csx | using DotVVM.Framework.Controls;
CorrectCode = "/resources/calculator_stub.dothtml";
GetDirectives("/attribute::*")
.CountEquals(1)
.IsViewModelDirective("CourseFormat.CalculatorViewModel");
GetControls("/child::node()")
.CountEquals(2);
GetControls("/child::node()[1]")
.IsOfType<RawLiteral>();
GetControls("/RawLiteral[1]/@EncodedText")
.StringEquals("<!doctype html>");
GetControls("/html")
.CountEquals(1);
GetControls("/html/child::node()")
.CountEquals(1);
GetControls("/html/body")
.CountEquals(1); | using DotVVM.Framework.Controls;
CorrectCode = "/resources/calculator_stub.dothtml";
GetDirectives("/attribute::*")
.CountEquals(1)
.IsViewModelDirective("CourseFormat.CalculatorViewModel");
GetControls("/child::node()")
.CountEquals(2);
GetControls("/child::node()[1]")
.IsOfType<RawLiteral>();
GetControls("/RawLiteral[1]/@EncodedText")
.TextEquals("<!doctype html>");
GetControls("/html")
.CountEquals(1);
GetControls("/html/child::node()")
.CountEquals(1);
GetControls("/html/body")
.CountEquals(1); | apache-2.0 | C# |
53303bfce7c3c26e23632c4693d889a5c354638f | Remove code to trigger expiry of funds processing until fix has been implemented for the calculation | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ExpireFundsJob.cs | src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ExpireFundsJob.cs | using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
public ExpireFundsJob(IMessageSession messageSession)
{
_messageSession = messageSession;
}
public Task Run(
[TimerTrigger("0 0 0 28 * *")] TimerInfo timer,
ILogger logger)
{
return Task.FromResult(0);
// return _messageSession.Send(new ExpireFundsCommand());
}
}
} | using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
public ExpireFundsJob(IMessageSession messageSession)
{
_messageSession = messageSession;
}
public Task Run([TimerTrigger("0 0 0 28 * *")] TimerInfo timer, ILogger logger)
{
return _messageSession.Send(new ExpireFundsCommand());
}
}
} | mit | C# |
6a2de7eaa6fba965a90754beafb6a8f4ca81d460 | Add Mutex creation extension methods that take an ACL (#42281) | cshung/coreclr,cshung/coreclr,cshung/coreclr,cshung/coreclr,cshung/coreclr,cshung/coreclr | src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Mutex.cs | src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Mutex.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 enable
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Kernel32
{
internal const uint CREATE_MUTEX_INITIAL_OWNER = 0x1;
[DllImport(Libraries.Kernel32, EntryPoint = "OpenMutexW", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeWaitHandle OpenMutex(uint desiredAccess, bool inheritHandle, string name);
[DllImport(Libraries.Kernel32, EntryPoint = "CreateMutexExW", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeWaitHandle CreateMutexEx(IntPtr lpMutexAttributes, string? name, uint flags, uint desiredAccess);
[DllImport(Libraries.Kernel32, SetLastError = true)]
internal static extern bool ReleaseMutex(SafeWaitHandle handle);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Kernel32
{
internal const uint CREATE_MUTEX_INITIAL_OWNER = 0x1;
[DllImport(Interop.Libraries.Kernel32, EntryPoint = "OpenMutexW", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeWaitHandle OpenMutex(uint desiredAccess, bool inheritHandle, string name);
[DllImport(Interop.Libraries.Kernel32, EntryPoint = "CreateMutexExW", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafeWaitHandle CreateMutexEx(IntPtr lpMutexAttributes, string? name, uint flags, uint desiredAccess);
[DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
internal static extern bool ReleaseMutex(SafeWaitHandle handle);
}
}
| mit | C# |
d1b915cdc9c11c36f8be1643fbf6be5d273c3e7a | Fix type | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Converters/RpcStatusStringConverter.cs | WalletWasabi.Gui/Converters/RpcStatusStringConverter.cs | using Avalonia.Data.Converters;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using WalletWasabi.BitcoinCore.Monitor;
using WalletWasabi.Exceptions;
using WalletWasabi.Helpers;
namespace WalletWasabi.Gui.Converters
{
public class RpcStatusStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is null)
{
return string.Empty;
}
if (value is RpcStatus val)
{
return val.ToString();
}
else
{
throw new TypeArgumentException(value, typeof(RpcStatus), nameof(value));
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| using Avalonia.Data.Converters;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using WalletWasabi.BitcoinCore.Monitor;
using WalletWasabi.Exceptions;
using WalletWasabi.Helpers;
namespace WalletWasabi.Gui.Converters
{
public class RpcStatusStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is null)
{
return string.Empty;
}
if (value is RpcStatus val)
{
return val.ToString();
}
else
{
throw new TypeArgumentException(value, typeof(Version), nameof(value));
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
35dd63db70f0bab52e09afa555d2dfcc59abb22f | update test result to match namespace change | RWE-Nexus/EnergyTrading-MDM-Client,phatcher/EnergyTrading-MDM-Client | Code/EnergyTrading.MDM.Client.IntegrationTests/SourceSystem/MdmService/MdmServiceEntityUpdateTests.cs | Code/EnergyTrading.MDM.Client.IntegrationTests/SourceSystem/MdmService/MdmServiceEntityUpdateTests.cs | // <autogenerated>
// This file was generated by T4 code generator CreateIntegrationTestsScript.tt.
// Any changes made to this file manually will be lost next time the file is regenerated.
// </autogenerated>
namespace EnergyTrading.Mdm.Client.IntegrationTests.SourceSystem.MdmService
{
using System.Configuration;
using System.Linq;
using System.Net;
using NUnit.Framework;
using EnergyTrading.Mdm.Contracts;
[TestFixture]
public class MdmServiceEntityUpdateIntegrationTests : MdmServiceIntegrationTestBase
{
private SourceSystem sourcesystem;
protected override void OnSetup()
{
ConfigurationManager.AppSettings["MdmCaching"] = false.ToString();
base.OnSetup();
sourcesystem = SourceSystemData.PostBasicEntity();
}
[Test]
public void ShouldSucceedUpdateWhenETagMatches()
{
// given
var id = int.Parse(sourcesystem.ToMdmId().Identifier);
// when
var response = MdmService.Get<SourceSystem>(id);
var entity = response.Message;
entity.Identifiers = new MdmIdList() {entity.Identifiers.SystemId()};
// then
response = MdmService.Update(id, entity, response.Tag);
Assert.IsTrue(response.IsValid, "###Error : " + response.Code + " : " + (response.Fault == null ? string.Empty : response.Fault.Message + " : " + response.Fault.Reason));
}
[Test]
public void ShouldFailUpdateWhenETagDiffers()
{
// given
var id = int.Parse(sourcesystem.ToMdmId().Identifier);
// when
var response = MdmService.Get<SourceSystem>(id);
// then
response = MdmService.Update(id, response.Message, "\"999888777666555\"");
Assert.IsFalse(response.IsValid);
Assert.AreEqual(HttpStatusCode.PreconditionFailed, response.Code);
Assert.AreEqual("Exception of type 'EnergyTrading.Mdm.Services.VersionConflictException' was thrown.", response.Fault.Message);
}
}
}
| // <autogenerated>
// This file was generated by T4 code generator CreateIntegrationTestsScript.tt.
// Any changes made to this file manually will be lost next time the file is regenerated.
// </autogenerated>
namespace EnergyTrading.Mdm.Client.IntegrationTests.SourceSystem.MdmService
{
using System.Configuration;
using System.Linq;
using System.Net;
using NUnit.Framework;
using EnergyTrading.Mdm.Contracts;
[TestFixture]
public class MdmServiceEntityUpdateIntegrationTests : MdmServiceIntegrationTestBase
{
private SourceSystem sourcesystem;
protected override void OnSetup()
{
ConfigurationManager.AppSettings["MdmCaching"] = false.ToString();
base.OnSetup();
sourcesystem = SourceSystemData.PostBasicEntity();
}
[Test]
public void ShouldSucceedUpdateWhenETagMatches()
{
// given
var id = int.Parse(sourcesystem.ToMdmId().Identifier);
// when
var response = MdmService.Get<SourceSystem>(id);
var entity = response.Message;
entity.Identifiers = new MdmIdList() {entity.Identifiers.SystemId()};
// then
response = MdmService.Update(id, entity, response.Tag);
Assert.IsTrue(response.IsValid, "###Error : " + response.Code + " : " + (response.Fault == null ? string.Empty : response.Fault.Message + " : " + response.Fault.Reason));
}
[Test]
public void ShouldFailUpdateWhenETagDiffers()
{
// given
var id = int.Parse(sourcesystem.ToMdmId().Identifier);
// when
var response = MdmService.Get<SourceSystem>(id);
// then
response = MdmService.Update(id, response.Message, "\"999888777666555\"");
Assert.IsFalse(response.IsValid);
Assert.AreEqual(HttpStatusCode.PreconditionFailed, response.Code);
Assert.AreEqual("Exception of type 'EnergyTrading.MDM.Services.VersionConflictException' was thrown.", response.Fault.Message);
}
}
}
| mit | C# |
d79e752c2f05ed9816ef5aeaa0f1cb642f65aa7e | build script | imperugo/StackExchange.Redis.Extensions,imperugo/StackExchange.Redis.Extensions | targets/Program.cs | targets/Program.cs | using System.IO;
using static Bullseye.Targets;
using static SimpleExec.Command;
namespace Targets
{
internal static class Program
{
public static void Main(string[] args)
{
var sdk = new DotnetSdkManager();
Target("default", DependsOn("test"));
Target(
"build",
Directory.EnumerateFiles("./", "*.sln", SearchOption.AllDirectories),
solution => Run(sdk.GetDotnetCliPath(), $"build \"{solution}\" --configuration Release -f:net5"));
Target(
"test",
DependsOn("build"),
Directory.EnumerateFiles("tests", "*Tests.csproj", SearchOption.AllDirectories),
proj => Run(sdk.GetDotnetCliPath(), $"test \"{proj}\" --configuration Release --no-build -f:net5"));
RunTargetsAndExit(args);
}
}
} | using System.IO;
using static Bullseye.Targets;
using static SimpleExec.Command;
namespace Targets
{
internal static class Program
{
public static void Main(string[] args)
{
var sdk = new DotnetSdkManager();
Target("default", DependsOn("test"));
Target(
"build",
Directory.EnumerateFiles("./", "*.sln", SearchOption.AllDirectories),
solution => Run(sdk.GetDotnetCliPath(), $"build \"{solution}\" --configuration Release -f:netcoreapp3.1"));
Target(
"test",
DependsOn("build"),
Directory.EnumerateFiles("tests", "*Tests.csproj", SearchOption.AllDirectories),
proj => Run(sdk.GetDotnetCliPath(), $"test \"{proj}\" --configuration Release --no-build"));
RunTargetsAndExit(args);
}
}
} | mit | C# |
c5c21c80399b1c7cab7516173e937b02a704ebe5 | access to FileIOPermission should happen inside try body because the it is currently marked as a coreclr critical type in the Unity runtime | drslump/boo,wbardzinski/boo,rmartinho/boo,rmboggs/boo,bamboo/boo,scottstephens/boo,Unity-Technologies/boo,BitPuffin/boo,BITechnologies/boo,rmboggs/boo,bamboo/boo,KingJiangNet/boo,wbardzinski/boo,rmartinho/boo,drslump/boo,bamboo/boo,KingJiangNet/boo,BillHally/boo,KingJiangNet/boo,bamboo/boo,hmah/boo,rmartinho/boo,rmartinho/boo,wbardzinski/boo,KidFashion/boo,KingJiangNet/boo,scottstephens/boo,Unity-Technologies/boo,bamboo/boo,boo-lang/boo,drslump/boo,BillHally/boo,KidFashion/boo,hmah/boo,KingJiangNet/boo,hmah/boo,BITechnologies/boo,boo-lang/boo,Unity-Technologies/boo,BitPuffin/boo,scottstephens/boo,BITechnologies/boo,scottstephens/boo,KidFashion/boo,Unity-Technologies/boo,boo-lang/boo,BITechnologies/boo,BITechnologies/boo,drslump/boo,wbardzinski/boo,hmah/boo,wbardzinski/boo,BitPuffin/boo,boo-lang/boo,rmboggs/boo,BillHally/boo,KingJiangNet/boo,KidFashion/boo,rmboggs/boo,KidFashion/boo,BitPuffin/boo,hmah/boo,scottstephens/boo,hmah/boo,boo-lang/boo,BITechnologies/boo,hmah/boo,BillHally/boo,KidFashion/boo,Unity-Technologies/boo,hmah/boo,BitPuffin/boo,drslump/boo,BitPuffin/boo,BITechnologies/boo,boo-lang/boo,bamboo/boo,wbardzinski/boo,rmartinho/boo,rmartinho/boo,scottstephens/boo,BITechnologies/boo,rmboggs/boo,rmboggs/boo,KingJiangNet/boo,bamboo/boo,rmartinho/boo,drslump/boo,boo-lang/boo,Unity-Technologies/boo,KidFashion/boo,BillHally/boo,wbardzinski/boo,rmartinho/boo,drslump/boo,boo-lang/boo,BillHally/boo,KingJiangNet/boo,Unity-Technologies/boo,rmboggs/boo,BitPuffin/boo,BitPuffin/boo,scottstephens/boo,wbardzinski/boo,scottstephens/boo,hmah/boo,Unity-Technologies/boo,rmboggs/boo,BillHally/boo | src/Boo.Lang.Compiler/Util/Permissions.cs | src/Boo.Lang.Compiler/Util/Permissions.cs | #region license
// Copyright (c) 2009, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Security;
using System.Security.Permissions;
using System.Text;
namespace Boo.Lang.Compiler.Util
{
internal static class Permissions
{
public static bool HasAppDomainPermission
{
get
{
if (null == hasAppDomainPermission)
hasAppDomainPermission = CheckPermission(() => new SecurityPermission(SecurityPermissionFlag.ControlAppDomain));
return (bool) hasAppDomainPermission;
}
}
static bool? hasAppDomainPermission = null;
public static bool HasEnvironmentPermission
{
get
{
if (null == hasEnvironmentPermission)
hasEnvironmentPermission = CheckPermission(() => new EnvironmentPermission(PermissionState.Unrestricted));
return (bool) hasEnvironmentPermission;
}
}
static bool? hasEnvironmentPermission = null;
public static bool HasDiscoveryPermission
{
get
{
if (null == hasDiscoveryPermission)
hasDiscoveryPermission = CheckPermission(() => new FileIOPermission(PermissionState.Unrestricted));
return (bool) hasDiscoveryPermission;
}
}
static bool? hasDiscoveryPermission = null;
static bool CheckPermission(Func<IPermission> permission)
{
try
{
permission().Demand();
return true;
}
catch (Exception)
{
return false;
}
}
}
}
| #region license
// Copyright (c) 2009, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Security;
using System.Security.Permissions;
using System.Text;
namespace Boo.Lang.Compiler.Util
{
internal static class Permissions
{
public static bool HasAppDomainPermission
{
get
{
if (null == hasAppDomainPermission)
hasAppDomainPermission = CheckPermission(new SecurityPermission(SecurityPermissionFlag.ControlAppDomain));
return (bool) hasAppDomainPermission;
}
}
static bool? hasAppDomainPermission = null;
public static bool HasEnvironmentPermission
{
get
{
if (null == hasEnvironmentPermission)
hasEnvironmentPermission = CheckPermission(new EnvironmentPermission(PermissionState.Unrestricted));
return (bool) hasEnvironmentPermission;
}
}
static bool? hasEnvironmentPermission = null;
public static bool HasDiscoveryPermission
{
get
{
if (null == hasDiscoveryPermission)
hasDiscoveryPermission = CheckPermission(new FileIOPermission(PermissionState.Unrestricted));
return (bool) hasDiscoveryPermission;
}
}
static bool? hasDiscoveryPermission = null;
static bool CheckPermission(IPermission permission)
{
bool hasPermission = false;
try
{
permission.Demand();
hasPermission = true;
}
catch (SecurityException)
{
}
return hasPermission;
}
}
}
| bsd-3-clause | C# |
061f8fd7c055a172951ef1e5da6ae929cd50d8a0 | Fix Startup.cs | devkimchi/xUnit-Moq-Sample,devkimchi/xUnit-Moq-Sample,devkimchi/xUnit-Moq-Sample | src/xUnitMoqSampleWeb/Startup.cs | src/xUnitMoqSampleWeb/Startup.cs | using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using XUnitMoqSampleWeb.Helpers;
using XUnitMoqSampleWeb.Services;
namespace XUnitMoqSampleWeb
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddTransient<IHttpClientHelper, HttpClientHelper>();
services.AddTransient<IGitHubApiService, GitHubApiService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
} | using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using XUnitMoqSampleWeb.Services;
namespace XUnitMoqSampleWeb
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddTransient<IGitHubApiService, GitHubApiService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
} | mit | C# |
2262d01afe3ac9dd450866e9723d04cb39ec9bf8 | Update version number. | Damnae/storybrew | editor/Properties/AssemblyInfo.cs | editor/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.27.*")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.26.*")]
| mit | C# |
071d8eb2aa1c9410ac64865ed1c3e7b7eda87eea | Add logger message to establish completion time for ImportPaymentsJob | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerFinance.MessageHandlers/CommandHandlers/ProcessPeriodEndPaymentsCommandHandler.cs | src/SFA.DAS.EmployerFinance.MessageHandlers/CommandHandlers/ProcessPeriodEndPaymentsCommandHandler.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using MediatR;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
using SFA.DAS.EmployerFinance.Queries.GetAllEmployerAccounts;
using SFA.DAS.NLog.Logger;
namespace SFA.DAS.EmployerFinance.MessageHandlers.CommandHandlers
{
public class ProcessPeriodEndPaymentsCommandHandler : IHandleMessages<ProcessPeriodEndPaymentsCommand>
{
private readonly IMediator _mediator;
private readonly ILog _logger;
public ProcessPeriodEndPaymentsCommandHandler(IMediator mediator, ILog logger)
{
_mediator = mediator;
_logger = logger;
}
public async Task Handle(ProcessPeriodEndPaymentsCommand message, IMessageHandlerContext context)
{
var response = await _mediator.SendAsync(new GetAllEmployerAccountsRequest());
var tasks = new List<Task>();
foreach (var account in response.Accounts)
{
_logger.Info($"Creating payment queue message for account ID: '{account.Id}' period end ref: '{message.PeriodEndRef}'");
var sendOptions = new SendOptions();
sendOptions.RouteToThisEndpoint();
sendOptions.RequireImmediateDispatch(); // Circumvent sender outbox
sendOptions.SetMessageId($"{nameof(ImportAccountPaymentsCommand)}-{message.PeriodEndRef}-{account.Id}"); // Allow receiver outbox to de-dupe
tasks.Add(context.Send(new ImportAccountPaymentsCommand { PeriodEndRef = message.PeriodEndRef, AccountId = account.Id }, sendOptions));
}
await Task.WhenAll(tasks);
_logger.Info($"Completed payment message queuing for period end ref: '{message.PeriodEndRef}'");
}
}
}
| using System.Collections.Generic;
using System.Threading.Tasks;
using MediatR;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
using SFA.DAS.EmployerFinance.Queries.GetAllEmployerAccounts;
using SFA.DAS.NLog.Logger;
namespace SFA.DAS.EmployerFinance.MessageHandlers.CommandHandlers
{
public class ProcessPeriodEndPaymentsCommandHandler : IHandleMessages<ProcessPeriodEndPaymentsCommand>
{
private readonly IMediator _mediator;
private readonly ILog _logger;
public ProcessPeriodEndPaymentsCommandHandler(IMediator mediator, ILog logger)
{
_mediator = mediator;
_logger = logger;
}
public async Task Handle(ProcessPeriodEndPaymentsCommand message, IMessageHandlerContext context)
{
var response = await _mediator.SendAsync(new GetAllEmployerAccountsRequest());
var tasks = new List<Task>();
foreach (var account in response.Accounts)
{
_logger.Info($"Creating payment queue message for account ID: '{account.Id}' period end ref: '{message.PeriodEndRef}'");
var sendOptions = new SendOptions();
sendOptions.RouteToThisEndpoint();
sendOptions.RequireImmediateDispatch(); // Circumvent sender outbox
sendOptions.SetMessageId($"{nameof(ImportAccountPaymentsCommand)}-{message.PeriodEndRef}-{account.Id}"); // Allow receiver outbox to de-dupe
tasks.Add(context.Send(new ImportAccountPaymentsCommand { PeriodEndRef = message.PeriodEndRef, AccountId = account.Id }, sendOptions));
}
await Task.WhenAll(tasks);
}
}
}
| mit | C# |
4c36fed13c47df6bf38d2847f43075dc59198d45 | fix sqlQueryable with sqlDependson polymorphic | bantolov/Rhetos | CommonConcepts/Plugins/Rhetos.Dsl.DefaultConcepts/DatabaseWorkarounds/SqlDependsOnDataStructureInfo.cs | CommonConcepts/Plugins/Rhetos.Dsl.DefaultConcepts/DatabaseWorkarounds/SqlDependsOnDataStructureInfo.cs | /*
Copyright (C) 2014 Omega software d.o.o.
This file is part of Rhetos.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
namespace Rhetos.Dsl.DefaultConcepts
{
[Export(typeof(IConceptInfo))]
[ConceptKeyword("SqlDependsOn")]
public class SqlDependsOnDataStructureInfo : IConceptInfo
{
[ConceptKey]
public IConceptInfo Dependent { get; set; }
[ConceptKey]
public DataStructureInfo DependsOn { get; set; }
}
[Export(typeof(IConceptMacro))]
public class SqlDependsOnDataStructureMacro : IConceptMacro<SqlDependsOnDataStructureInfo>
{
public IEnumerable<IConceptInfo> CreateNewConcepts(SqlDependsOnDataStructureInfo conceptInfo, IDslModel existingConcepts)
{
var newConcepts = new List<IConceptInfo>();
if (conceptInfo.DependsOn is PolymorphicInfo
&& conceptInfo.Dependent is SqlQueryableInfo)
{
newConcepts.AddRange(
existingConcepts.FindByType<SqlObjectInfo>()
.Where(p => p.Module == conceptInfo.DependsOn.Module && p.Name == conceptInfo.DependsOn.Name)
.Select(p => new SqlDependsOnSqlObjectInfo
{
Dependent = conceptInfo.Dependent,
DependsOn = p
}));
}
else
{
newConcepts.AddRange(
existingConcepts.FindByReference<PropertyInfo>(p => p.DataStructure, conceptInfo.DependsOn)
.Where(p => p != conceptInfo.Dependent)
.Select(p => new SqlDependsOnPropertyInfo { Dependent = conceptInfo.Dependent, DependsOn = p })
.ToList());
}
return newConcepts;
}
}
}
| /*
Copyright (C) 2014 Omega software d.o.o.
This file is part of Rhetos.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
namespace Rhetos.Dsl.DefaultConcepts
{
[Export(typeof(IConceptInfo))]
[ConceptKeyword("SqlDependsOn")]
public class SqlDependsOnDataStructureInfo : IConceptInfo
{
[ConceptKey]
public IConceptInfo Dependent { get; set; }
[ConceptKey]
public DataStructureInfo DependsOn { get; set; }
}
[Export(typeof(IConceptMacro))]
public class SqlDependsOnDataStructureMacro : IConceptMacro<SqlDependsOnDataStructureInfo>
{
public IEnumerable<IConceptInfo> CreateNewConcepts(SqlDependsOnDataStructureInfo conceptInfo, IDslModel existingConcepts)
{
return existingConcepts.FindByReference<PropertyInfo>(p => p.DataStructure, conceptInfo.DependsOn)
.Where(p => p != conceptInfo.Dependent)
.Select(p => new SqlDependsOnPropertyInfo { Dependent = conceptInfo.Dependent, DependsOn = p })
.ToList();
}
}
}
| agpl-3.0 | C# |
3d09db496fed7121723de97e6c2529f7864a1ae8 | Check with UnitySolutionTracker | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Rider/RiderUnitySharedFilesSavingSuppressor.cs | resharper/resharper-unity/src/Rider/RiderUnitySharedFilesSavingSuppressor.cs | using JetBrains.Annotations;
using JetBrains.DocumentManagers;
using JetBrains.DocumentModel;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features.Documents;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.Rider
{
/// <summary>
/// Removes auto sync through disk for shared files, to avoid unity refresh
/// </summary>
[SolutionComponent]
public class RiderUnitySharedFilesSavingSuppressor : IRiderDocumentSavingSuppressor
{
[NotNull] private readonly UnitySolutionTracker myUnitySolutionTracker;
[NotNull] private readonly DocumentToProjectFileMappingStorage myDocumentToProjectFileMappingStorage;
[NotNull] private readonly ILogger myLogger;
public RiderUnitySharedFilesSavingSuppressor(
[NotNull] UnitySolutionTracker unitySolutionTracker,
[NotNull] DocumentToProjectFileMappingStorage documentToProjectFileMappingStorage,
[NotNull] ILogger logger)
{
myUnitySolutionTracker = unitySolutionTracker;
myDocumentToProjectFileMappingStorage = documentToProjectFileMappingStorage;
myLogger = logger;
}
public bool ShouldSuppress(IDocument document, bool forceSaveOpenDocuments)
{
if (!forceSaveOpenDocuments) return false;
var projectFile = myDocumentToProjectFileMappingStorage.TryGetProjectFile(document);
var isUnitySharedProjectFile = projectFile != null
&& myUnitySolutionTracker.IsUnityGeneratedProject.Value
&& projectFile.IsShared();
if (isUnitySharedProjectFile)
{
myLogger.Verbose("File is shared and contained in Unity project. Skip saving.");
return true;
}
return false;
}
}
} | using JetBrains.Annotations;
using JetBrains.DocumentManagers;
using JetBrains.DocumentModel;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features.Documents;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.Rider
{
/// <summary>
/// Removes auto sync through disk for shared files, to avoid unity refresh
/// </summary>
[SolutionComponent]
public class RiderUnitySharedFilesSavingSuppressor : IRiderDocumentSavingSuppressor
{
[NotNull] private readonly DocumentToProjectFileMappingStorage myDocumentToProjectFileMappingStorage;
[NotNull] private readonly ILogger myLogger;
public RiderUnitySharedFilesSavingSuppressor(
[NotNull] DocumentToProjectFileMappingStorage documentToProjectFileMappingStorage,
[NotNull] ILogger logger)
{
myDocumentToProjectFileMappingStorage = documentToProjectFileMappingStorage;
myLogger = logger;
}
public bool ShouldSuppress(IDocument document, bool forceSaveOpenDocuments)
{
if (!forceSaveOpenDocuments) return false;
var projectFile = myDocumentToProjectFileMappingStorage.TryGetProjectFile(document);
var isUnitySharedProjectFile = projectFile != null
&& projectFile.IsShared()
&& projectFile.GetProject().IsUnityGeneratedProject();
if (isUnitySharedProjectFile)
{
myLogger.Verbose("File is shared and contained in Unity project. Skip saving.");
return true;
}
return false;
}
}
} | apache-2.0 | C# |
26213ad55cb7ebea14e4d986ddfd29945aebbbc7 | Update "cancellation of significant digits" example | MasuqaT-NET/BlogExamples,MasuqaT-NET/BlogSamples,MasuqaT-NET/BlogExamples,MasuqaT-NET/BlogExamples,MasuqaT-NET/BlogExamples,MasuqaT-NET/BlogExamples,MasuqaT-NET/BlogExamples,MasuqaT-NET/BlogExamples,MasuqaT-NET/BlogExamples,MasuqaT-NET/BlogExamples,MasuqaT-NET/BlogExamples | NumericalCalculation/BasicWithCSharp/CancellationOfSignificantDigits/CancellationOfSignificantDigits.cs | NumericalCalculation/BasicWithCSharp/CancellationOfSignificantDigits/CancellationOfSignificantDigits.cs | using System;
namespace CancellationOfSignificantDigits
{
public class CancellationOfSignificantDigits
{
public static void Main(string[] args)
{
CheckCancellation();
}
static Tuple<float, float> NormalSolver(float a, float b, float c)
{
float det = (float)Math.Sqrt(b * b - 4 * a * c);
float x_1 = (-b + det) / 2.0f / a;
float x_2 = (-b - det) / 2.0f / a;
return Tuple.Create(x_1, x_2);
}
static Tuple<float, float> CaredSolver(float a, float b, float c)
{
float det = (float)Math.Sqrt(b * b - 4 * a * c);
float x_1, x_2;
if (b > 0)
{
x_2 = (-b - det) / 2.0f / a;
x_1 = c / (a * x_2);
}
else
{
x_1 = (-b + det) / 2.0f / a;
x_2 = c / (a * x_1);
}
return Tuple.Create(x_1, x_2);
}
static void CheckCancellation()
{
float a = 1.0f, b = -1000.0f, c = 1.0f; // x^2 - 1000x + c = 0
var normal = NormalSolver(a, b, c);
var cared = CaredSolver(a, b, c);
Console.WriteLine("f(x) = x^2 - 1000x + c = 0");
Console.WriteLine($"normal: x_1= {normal.Item1:F8}, x_2= {normal.Item2:F8}");
Console.WriteLine($"f(x_2) -> {(a * normal.Item2 * normal.Item2 + b * normal.Item2 + c):F8}");
Console.WriteLine($"cared : x_1= {cared.Item1:F8}, x_2= {cared.Item2:F8}");
Console.WriteLine($"f(x_2) -> {(a * cared.Item2 * cared.Item2 + b * cared.Item2 + c):F8}");
}
}
}
| using System;
namespace CancellationOfSignificantDigits
{
public class CancellationOfSignificantDigits
{
public static void Main(string[] args)
{
CheckCancellation();
}
static Tuple<float, float> NormalSolver(float a, float b, float c)
{
float det = (float)Math.Sqrt(b * b - 4 * a * c);
float x_1 = (-b + det) / 2.0f / a;
float x_2 = (-b - det) / 2.0f / a;
return Tuple.Create(x_1, x_2);
}
static Tuple<float, float> CaredSolver(float a, float b, float c)
{
float det = (float)Math.Sqrt(b * b - 4 * a * c);
float x_1, x_2;
if (b > 0)
{
x_2 = (-b - det) / 2.0f / a;
x_1 = c / (a * x_2);
}
else
{
x_1 = (-b + det) / 2.0f / a;
x_2 = c / (a * x_1);
}
return Tuple.Create(x_1, x_2);
}
static void CheckCancellation()
{
float a = 1.0f, b = -1000.0f, c = 1.0f; // x^2 - 1000x + c = 0
var normal = NormalSolver(a, b, c);
var cared = CaredSolver(a, b, c);
Console.WriteLine($"normal: x_1= {normal.Item1:F8}, x_2= {normal.Item2:F8}");
Console.WriteLine($"x_2 -> {(a * normal.Item2 * normal.Item2 + b * normal.Item2 + c):F8}");
Console.WriteLine($"cared : x_1= {cared.Item1:F8}, x_2= {cared.Item2:F8}");
Console.WriteLine($"x_2 -> {(a * cared.Item2 * cared.Item2 + b * cared.Item2 + c):F8}");
}
}
}
| mit | C# |
78443146174cf2626bdb3bbbb83f7399af31c5e4 | Remove unused namespace | charlenni/Mapsui,charlenni/Mapsui | Mapsui.Core/ViewportAnimations/SetCenterAndResolutionAnimation.cs | Mapsui.Core/ViewportAnimations/SetCenterAndResolutionAnimation.cs | using System.Collections.Generic;
using Mapsui.Utilities;
namespace Mapsui.ViewportAnimations
{
internal class SetCenterAndResolutionAnimation
{
public static List<AnimationEntry> Create(Viewport viewport, double centerX, double centerY, double resolution, long duration)
{
var animations = new List<AnimationEntry>();
var entry = new AnimationEntry(
start: (viewport.CenterX, viewport.CenterY, viewport.Resolution),
end: (centerX, centerY, resolution),
animationStart: 0,
animationEnd: 1,
easing: Easing.SinInOut,
tick: (e, v) => CenterAndResolutionTick(viewport, e, v),
final: (e) => CenterAndResolutionFinal(viewport, e)
);
animations.Add(entry);
Animation.Start(animations, duration);
return animations;
}
private static void CenterAndResolutionTick(Viewport viewport, AnimationEntry entry, double value)
{
var start = ((double CenterX, double CenterY, double Resolution))entry.Start;
var end = ((double CenterX, double CenterY,double Resolution))entry.End;
var x = start.CenterX + (end.CenterX - start.CenterX) * entry.Easing.Ease(value);
var y = start.CenterY + (end.CenterY - start.CenterY) * entry.Easing.Ease(value);
var r = start.Resolution + (end.Resolution - start.Resolution) * entry.Easing.Ease(value);
viewport.CenterX = x;
viewport.CenterY = y;
viewport.Resolution = r;
}
private static void CenterAndResolutionFinal(Viewport viewport, AnimationEntry entry)
{
var end = ((double CenterX, double CenterY, double Resolution))entry.End;
viewport.CenterX = end.CenterX;
viewport.CenterY = end.CenterY;
viewport.Resolution = end.Resolution;
}
}
}
| using System.Collections.Generic;
using Mapsui.Geometries;
using Mapsui.Utilities;
namespace Mapsui.ViewportAnimations
{
internal class SetCenterAndResolutionAnimation
{
public static List<AnimationEntry> Create(Viewport viewport, double centerX, double centerY, double resolution, long duration)
{
var animations = new List<AnimationEntry>();
var entry = new AnimationEntry(
start: (viewport.CenterX, viewport.CenterY, viewport.Resolution),
end: (centerX, centerY, resolution),
animationStart: 0,
animationEnd: 1,
easing: Easing.SinInOut,
tick: (e, v) => CenterAndResolutionTick(viewport, e, v),
final: (e) => CenterAndResolutionFinal(viewport, e)
);
animations.Add(entry);
Animation.Start(animations, duration);
return animations;
}
private static void CenterAndResolutionTick(Viewport viewport, AnimationEntry entry, double value)
{
var start = ((double CenterX, double CenterY, double Resolution))entry.Start;
var end = ((double CenterX, double CenterY,double Resolution))entry.End;
var x = start.CenterX + (end.CenterX - start.CenterX) * entry.Easing.Ease(value);
var y = start.CenterY + (end.CenterY - start.CenterY) * entry.Easing.Ease(value);
var r = start.Resolution + (end.Resolution - start.Resolution) * entry.Easing.Ease(value);
viewport.CenterX = x;
viewport.CenterY = y;
viewport.Resolution = r;
}
private static void CenterAndResolutionFinal(Viewport viewport, AnimationEntry entry)
{
var end = ((double CenterX, double CenterY, double Resolution))entry.End;
viewport.CenterX = end.CenterX;
viewport.CenterY = end.CenterY;
viewport.Resolution = end.Resolution;
}
}
}
| mit | C# |
389aaff0139e9bc24a98eb379efa9e7fb36dc6e6 | Convert some magic strings to use "nameof" operator | albertodall/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers | src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs | src/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs | using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using System;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services
{
public class IntegrationEventLogService : IIntegrationEventLogService
{
private readonly IntegrationEventLogContext _integrationEventLogContext;
private readonly DbConnection _dbConnection;
public IntegrationEventLogService(DbConnection dbConnection)
{
_dbConnection = dbConnection ?? throw new ArgumentNullException(nameof(dbConnection));
_integrationEventLogContext = new IntegrationEventLogContext(
new DbContextOptionsBuilder<IntegrationEventLogContext>()
.UseSqlServer(_dbConnection)
.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning))
.Options);
}
public Task SaveEventAsync(IntegrationEvent @event, DbTransaction transaction)
{
if (transaction == null)
{
throw new ArgumentNullException(nameof(transaction), $"A {typeof(DbTransaction).FullName} is required as a pre-requisite to save the event.");
}
var eventLogEntry = new IntegrationEventLogEntry(@event);
_integrationEventLogContext.Database.UseTransaction(transaction);
_integrationEventLogContext.IntegrationEventLogs.Add(eventLogEntry);
return _integrationEventLogContext.SaveChangesAsync();
}
public Task MarkEventAsPublishedAsync(IntegrationEvent @event)
{
var eventLogEntry = _integrationEventLogContext.IntegrationEventLogs.Single(ie => ie.EventId == @event.Id);
eventLogEntry.TimesSent++;
eventLogEntry.State = EventStateEnum.Published;
_integrationEventLogContext.IntegrationEventLogs.Update(eventLogEntry);
return _integrationEventLogContext.SaveChangesAsync();
}
}
}
| using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services
{
public class IntegrationEventLogService : IIntegrationEventLogService
{
private readonly IntegrationEventLogContext _integrationEventLogContext;
private readonly DbConnection _dbConnection;
public IntegrationEventLogService(DbConnection dbConnection)
{
_dbConnection = dbConnection?? throw new ArgumentNullException("dbConnection");
_integrationEventLogContext = new IntegrationEventLogContext(
new DbContextOptionsBuilder<IntegrationEventLogContext>()
.UseSqlServer(_dbConnection)
.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning))
.Options);
}
public Task SaveEventAsync(IntegrationEvent @event, DbTransaction transaction)
{
if(transaction == null)
{
throw new ArgumentNullException("transaction", $"A {typeof(DbTransaction).FullName} is required as a pre-requisite to save the event.");
}
var eventLogEntry = new IntegrationEventLogEntry(@event);
_integrationEventLogContext.Database.UseTransaction(transaction);
_integrationEventLogContext.IntegrationEventLogs.Add(eventLogEntry);
return _integrationEventLogContext.SaveChangesAsync();
}
public Task MarkEventAsPublishedAsync(IntegrationEvent @event)
{
var eventLogEntry = _integrationEventLogContext.IntegrationEventLogs.Single(ie => ie.EventId == @event.Id);
eventLogEntry.TimesSent++;
eventLogEntry.State = EventStateEnum.Published;
_integrationEventLogContext.IntegrationEventLogs.Update(eventLogEntry);
return _integrationEventLogContext.SaveChangesAsync();
}
}
}
| mit | C# |
b0ff14901b614fa7a9f4ad1426a0c855bd7a5f6d | add support for vs2013+ css schema | darrenkopp/SassyStudio | SassyStudio.2012/Editor/Intellisense/Integration/DefaultCssSchemaLoader.cs | SassyStudio.2012/Editor/Intellisense/Integration/DefaultCssSchemaLoader.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.VisualStudio.Settings;
using Microsoft.VisualStudio.Shell.Settings;
namespace SassyStudio.Editor.Intellisense
{
interface ICssSchemaLoader
{
ICssSchema Load();
}
[Export(typeof(ICssSchemaLoader))]
class DefaultCssSchemaLoader : ICssSchemaLoader
{
public ICssSchema Load()
{
try
{
var path = Path.Combine(SchemaDirectory, "css-main.xml");
var file = new FileInfo(path);
if (!file.Exists)
return null;
var document = XDocument.Load(path);
return CssSchema.Parse(document, file.Directory);
}
catch (Exception ex)
{
Logger.Log(ex, "Failed to load schema.");
return null;
}
}
string VisualStudioInstallPath
{
get
{
return new ShellSettingsManager(SassyStudioPackage.Instance)
.GetReadOnlySettingsStore(SettingsScope.Configuration)
.GetString(string.Empty, "ShellFolder");
}
}
string SchemaDirectory
{
get
{
var localeId = SassyStudioPackage.Instance.LocaleId;
if (localeId != 0)
{
// we'll assume this is the path moving forward
var vs2013 = Path.Combine(VisualStudioInstallPath, "Common7", "IDE", "CommonExtensions", "Microsoft", "Web", "Schemas", localeId.ToString(), "css");
if (Directory.Exists(vs2013))
return vs2013;
var vs2012 = Path.Combine(VisualStudioInstallPath, "Common7", "Packages", localeId.ToString(), "schemas", "css");
if (Directory.Exists(vs2012))
return vs2012;
}
return string.Empty;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.VisualStudio.Settings;
using Microsoft.VisualStudio.Shell.Settings;
namespace SassyStudio.Editor.Intellisense
{
interface ICssSchemaLoader
{
ICssSchema Load();
}
[Export(typeof(ICssSchemaLoader))]
class DefaultCssSchemaLoader : ICssSchemaLoader
{
public ICssSchema Load()
{
try
{
var path = Path.Combine(SchemaDirectory, "css-main.xml");
var file = new FileInfo(path);
if (!file.Exists)
return null;
var document = XDocument.Load(path);
return CssSchema.Parse(document, file.Directory);
}
catch (Exception ex)
{
Logger.Log(ex, "Failed to load schema.");
return null;
}
}
string VisualStudioInstallPath
{
get
{
return new ShellSettingsManager(SassyStudioPackage.Instance)
.GetReadOnlySettingsStore(SettingsScope.Configuration)
.GetString(string.Empty, "ShellFolder");
}
}
string SchemaDirectory
{
get
{
var localeId = SassyStudioPackage.Instance.LocaleId;
if (localeId != 0)
return Path.Combine(VisualStudioInstallPath, "Common7", "Packages", localeId.ToString(), "schemas", "css");
return string.Empty;
}
}
}
}
| mit | C# |
7fe13f2472e4076b9507e7f72e76ff20dfda5872 | Use proper obsolete attribute. | wvdd007/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,physhi/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,mavasani/roslyn,physhi/roslyn,mavasani/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,dotnet/roslyn,dotnet/roslyn,weltkante/roslyn,KevinRansom/roslyn,wvdd007/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,KevinRansom/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,AmadeusW/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,physhi/roslyn,bartdesmet/roslyn,weltkante/roslyn,wvdd007/roslyn | src/Features/CSharp/Portable/ConvertTupleToStruct/CSharpConvertTupleToStructCodeRefactoringProvider.cs | src/Features/CSharp/Portable/ConvertTupleToStruct/CSharpConvertTupleToStructCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.ConvertTupleToStruct;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct
{
[ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)]
[ExportLanguageService(typeof(IConvertTupleToStructCodeRefactoringProvider), LanguageNames.CSharp)]
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct), Shared]
internal class CSharpConvertTupleToStructCodeRefactoringProvider :
AbstractConvertTupleToStructCodeRefactoringProvider<
ExpressionSyntax,
NameSyntax,
IdentifierNameSyntax,
LiteralExpressionSyntax,
ObjectCreationExpressionSyntax,
TupleExpressionSyntax,
ArgumentSyntax,
TupleTypeSyntax,
TypeDeclarationSyntax,
NamespaceDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpConvertTupleToStructCodeRefactoringProvider()
{
}
protected override ArgumentSyntax GetArgumentWithChangedName(ArgumentSyntax argument, string name)
=> argument.WithNameColon(ChangeName(argument.NameColon, name));
private static NameColonSyntax? ChangeName(NameColonSyntax? nameColon, string name)
{
if (nameColon == null)
{
return null;
}
var newName = SyntaxFactory.IdentifierName(name).WithTriviaFrom(nameColon.Name);
return nameColon.WithName(newName);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.ConvertTupleToStruct;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct
{
[ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)]
[ExportLanguageService(typeof(IConvertTupleToStructCodeRefactoringProvider), LanguageNames.CSharp)]
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct), Shared]
internal class CSharpConvertTupleToStructCodeRefactoringProvider :
AbstractConvertTupleToStructCodeRefactoringProvider<
ExpressionSyntax,
NameSyntax,
IdentifierNameSyntax,
LiteralExpressionSyntax,
ObjectCreationExpressionSyntax,
TupleExpressionSyntax,
ArgumentSyntax,
TupleTypeSyntax,
TypeDeclarationSyntax,
NamespaceDeclarationSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpConvertTupleToStructCodeRefactoringProvider()
{
}
protected override ArgumentSyntax GetArgumentWithChangedName(ArgumentSyntax argument, string name)
=> argument.WithNameColon(ChangeName(argument.NameColon, name));
private static NameColonSyntax? ChangeName(NameColonSyntax? nameColon, string name)
{
if (nameColon == null)
{
return null;
}
var newName = SyntaxFactory.IdentifierName(name).WithTriviaFrom(nameColon.Name);
return nameColon.WithName(newName);
}
}
}
| mit | C# |
ed482462a70928f4328c25585385a69c1ee4bab4 | Fix filtered test result ordering | cezarypiatek/MaintainableSelenium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium,cezarypiatek/Tellurium,cezarypiatek/Tellurium | Src/Dashboard/Services/TestResults/Queries/FindTestResultsFromSession.cs | Src/Dashboard/Services/TestResults/Queries/FindTestResultsFromSession.cs | using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using Tellurium.VisualAssertions.Infrastructure;
using Tellurium.VisualAssertions.Screenshots.Domain;
namespace Tellurium.VisualAssertion.Dashboard.Services.TestResults.Queries
{
public class FindTestResultsFromSession : IQueryAll<TestResult>
{
private readonly long sessionId;
private readonly string browserName;
private readonly TestResultStatusFilter resultStatus;
public FindTestResultsFromSession(long sessionId, string browserName, TestResultStatusFilter resultStatus)
{
this.sessionId = sessionId;
this.browserName = browserName;
this.resultStatus = resultStatus;
}
public List<TestResult> GetQuery(IQueryable<TestResult> query)
{
var testFromSession = query.Where(x=>x.TestSession.Id == sessionId)
.Fetch(x=>x.Pattern)
.Where(x=>x.BrowserName == browserName);
switch (resultStatus)
{
case TestResultStatusFilter.All:
return testFromSession.ToList();
case TestResultStatusFilter.Passed:
return testFromSession.Where(x=>x.Status == TestResultStatus.Passed).OrderBy(x=>x.Id).ToList();
case TestResultStatusFilter.Failed:
return testFromSession.Where(x => x.Status == TestResultStatus.Failed).OrderBy(x => x.Id).ToList();
case TestResultStatusFilter.New:
return testFromSession.Where(x => x.Status == TestResultStatus.NewPattern).OrderBy(x => x.Id).ToList();
default:
throw new ArgumentOutOfRangeException();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using Tellurium.VisualAssertions.Infrastructure;
using Tellurium.VisualAssertions.Screenshots.Domain;
namespace Tellurium.VisualAssertion.Dashboard.Services.TestResults.Queries
{
public class FindTestResultsFromSession : IQueryAll<TestResult>
{
private readonly long sessionId;
private readonly string browserName;
private readonly TestResultStatusFilter resultStatus;
public FindTestResultsFromSession(long sessionId, string browserName, TestResultStatusFilter resultStatus)
{
this.sessionId = sessionId;
this.browserName = browserName;
this.resultStatus = resultStatus;
}
public List<TestResult> GetQuery(IQueryable<TestResult> query)
{
var testFromSession = query.Where(x=>x.TestSession.Id == sessionId)
.Fetch(x=>x.Pattern)
.Where(x=>x.BrowserName == browserName);
switch (resultStatus)
{
case TestResultStatusFilter.All:
return testFromSession.ToList();
case TestResultStatusFilter.Passed:
return testFromSession.Where(x=>x.Status == TestResultStatus.Passed).ToList();
case TestResultStatusFilter.Failed:
return testFromSession.Where(x => x.Status == TestResultStatus.Failed).ToList();
case TestResultStatusFilter.New:
return testFromSession.Where(x => x.Status == TestResultStatus.NewPattern).ToList();
default:
throw new ArgumentOutOfRangeException();
}
}
}
} | mit | C# |
3b3394944e0bf8d56f2781905a52f4a8a9c8a321 | Add comments | sonvister/Binance | src/Binance/Account/Orders/ClientOrder.cs | src/Binance/Account/Orders/ClientOrder.cs | using System;
using Binance.Api;
namespace Binance.Account.Orders
{
public abstract class ClientOrder : IChronological
{
#region Public Properties
/// <summary>
/// Get the user.
/// </summary>
public IBinanceApiUser User { get; }
/// <summary>
/// Get or set the symbol.
/// </summary>
public string Symbol { get; set; }
/// <summary>
/// Get the order type.
/// </summary>
public abstract OrderType Type { get; }
/// <summary>
/// Get or set the order side.
/// </summary>
public OrderSide Side { get; set; }
/// <summary>
/// Get or set the quantity.
/// </summary>
public decimal Quantity { get; set; }
/// <summary>
/// Get or set the client order ID (newClientOrderId).
/// NOTE: This value is set internally after order placement.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Get the transact time.
/// NOTE: This value is set internally after order placement.
/// </summary>
public DateTime Time { get; internal set; }
#endregion Public Properties
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="user"></param>
protected ClientOrder(IBinanceApiUser user)
{
Throw.IfNull(user, nameof(user));
User = user;
}
#endregion Constructors
}
}
| using System;
using Binance.Api;
namespace Binance.Account.Orders
{
public abstract class ClientOrder : IChronological
{
#region Public Properties
/// <summary>
/// Get the user.
/// </summary>
public IBinanceApiUser User { get; }
/// <summary>
/// Get or set the symbol.
/// </summary>
public string Symbol { get; set; }
/// <summary>
/// Get the order type.
/// </summary>
public abstract OrderType Type { get; }
/// <summary>
/// Get or set the order side.
/// </summary>
public OrderSide Side { get; set; }
/// <summary>
/// Get or set the quantity.
/// </summary>
public decimal Quantity { get; set; }
/// <summary>
/// Get or set the client order ID.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Get the transact time.
/// </summary>
public DateTime Time { get; internal set; }
#endregion Public Properties
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="user"></param>
protected ClientOrder(IBinanceApiUser user)
{
Throw.IfNull(user, nameof(user));
User = user;
}
#endregion Constructors
}
}
| mit | C# |
a268405f06e51e5ccc4f7933395cb3acfc313edb | Fix peer up port decoding bug | mstrother/BmpListener | src/BmpListener/Bmp/PeerUpNotification.cs | src/BmpListener/Bmp/PeerUpNotification.cs | using System;
using System.Net;
using BmpListener.Bgp;
using System.Linq;
using BmpListener.MiscUtil.Conversion;
namespace BmpListener.Bmp
{
public class PeerUpNotification : BmpMessage
{
public IPAddress LocalAddress { get; private set; }
public int LocalPort { get; private set; }
public int RemotePort { get; private set; }
public BgpOpenMessage SentOpenMessage { get; private set; }
public BgpOpenMessage ReceivedOpenMessage { get; private set; }
public override void Decode(byte[] data, int offset)
{
if (((PeerHeader.Flags & (1 << 7)) != 0))
{
var ipBytes = new byte[16];
Array.Copy(data, offset, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
offset += 4;
}
else
{
var ipBytes = new byte[4];
Array.Copy(data, offset + 12, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
offset += 16;
}
LocalPort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
RemotePort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
SentOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
offset += SentOpenMessage.Header.Length;
ReceivedOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
}
}
} | using System;
using System.Net;
using BmpListener.Bgp;
using System.Linq;
using BmpListener.MiscUtil.Conversion;
namespace BmpListener.Bmp
{
public class PeerUpNotification : BmpMessage
{
public IPAddress LocalAddress { get; private set; }
public int LocalPort { get; private set; }
public int RemotePort { get; private set; }
public BgpOpenMessage SentOpenMessage { get; private set; }
public BgpOpenMessage ReceivedOpenMessage { get; private set; }
public override void Decode(byte[] data, int offset)
{
if (((PeerHeader.Flags & (1 << 7)) != 0))
{
var ipBytes = new byte[16];
Array.Copy(data, offset, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
}
else
{
var ipBytes = new byte[4];
Array.Copy(data, offset + 12, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
}
LocalPort = EndianBitConverter.Big.ToUInt16(data, 16);
RemotePort = EndianBitConverter.Big.ToUInt16(data, 18);
offset += 20;
SentOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
offset += SentOpenMessage.Header.Length;
ReceivedOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
}
}
} | mit | C# |
001812091c58e0ac171e44b6c5d1d3c41d79be42 | Configure Urls in Program.Main | andrewlock/blog-examples,andrewlock/blog-examples,andrewlock/blog-examples,andrewlock/blog-examples | db-multi-tenancy-in-saaskit/src/DatabaseMultiTenancyWithSaasKit/Program.cs | db-multi-tenancy-in-saaskit/src/DatabaseMultiTenancyWithSaasKit/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace DatabaseMultiTenancyWithSaasKit
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://localhost:5000","http://localhost:5001","http://localhost:5002" )
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace DatabaseMultiTenancyWithSaasKit
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| mit | C# |
84f2126d148b78a5310378a243fd3bc822f467b2 | Fix possible race due to multiple concurrent assignement of the wait event in PendingCall. | Tragetaschen/dbus-sharp,arfbtwn/dbus-sharp,mono/dbus-sharp,mono/dbus-sharp,openmedicus/dbus-sharp,Tragetaschen/dbus-sharp,arfbtwn/dbus-sharp,openmedicus/dbus-sharp | src/PendingCall.cs | src/PendingCall.cs | // Copyright 2007 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Threading;
namespace DBus
{
class PendingCall : IAsyncResult
{
Connection conn;
Message reply = null;
//AutoResetEvent waitHandle = new AutoResetEvent (false);
ManualResetEvent waitHandle;
public PendingCall (Connection conn)
{
this.conn = conn;
}
public Message Reply
{
get {
if (reply != null)
return reply;
if (Thread.CurrentThread == conn.mainThread) {
/*
while (reply == null)
conn.Iterate ();
*/
while (reply == null)
conn.HandleMessage (conn.Transport.ReadMessage ());
completedSync = true;
conn.DispatchSignals ();
} else {
if (waitHandle == null)
Interlocked.CompareExchange (ref waitHandle, new ManualResetEvent (false), null);
// TODO: Possible race condition?
while (reply == null)
waitHandle.WaitOne ();
completedSync = false;
}
return reply;
} set {
if (reply != null)
throw new Exception ("Cannot handle reply more than once");
reply = value;
if (waitHandle != null)
waitHandle.Set ();
if (Completed != null)
Completed (reply);
}
}
public event Action<Message> Completed;
bool completedSync;
public void Cancel ()
{
throw new NotImplementedException ();
}
#region IAsyncResult Members
object IAsyncResult.AsyncState
{
get {
return conn;
}
}
WaitHandle IAsyncResult.AsyncWaitHandle
{
get {
if (waitHandle == null)
waitHandle = new ManualResetEvent (false);
return waitHandle;
}
}
bool IAsyncResult.CompletedSynchronously
{
get {
return reply != null && completedSync;
}
}
bool IAsyncResult.IsCompleted
{
get {
return reply != null;
}
}
#endregion
}
}
| // Copyright 2007 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Threading;
namespace DBus
{
class PendingCall : IAsyncResult
{
Connection conn;
Message reply = null;
//AutoResetEvent waitHandle = new AutoResetEvent (false);
ManualResetEvent waitHandle;
public PendingCall (Connection conn)
{
this.conn = conn;
}
public Message Reply
{
get {
if (reply != null)
return reply;
if (Thread.CurrentThread == conn.mainThread) {
/*
while (reply == null)
conn.Iterate ();
*/
while (reply == null)
conn.HandleMessage (conn.Transport.ReadMessage ());
completedSync = true;
conn.DispatchSignals ();
} else {
if (waitHandle == null)
waitHandle = new ManualResetEvent (false);
// TODO: Possible race condition?
while (reply == null)
waitHandle.WaitOne ();
completedSync = false;
}
return reply;
} set {
if (reply != null)
throw new Exception ("Cannot handle reply more than once");
reply = value;
if (waitHandle != null)
waitHandle.Set ();
if (Completed != null)
Completed (reply);
}
}
public event Action<Message> Completed;
bool completedSync;
public void Cancel ()
{
throw new NotImplementedException ();
}
#region IAsyncResult Members
object IAsyncResult.AsyncState
{
get {
return conn;
}
}
WaitHandle IAsyncResult.AsyncWaitHandle
{
get {
if (waitHandle == null)
waitHandle = new ManualResetEvent (false);
return waitHandle;
}
}
bool IAsyncResult.CompletedSynchronously
{
get {
return reply != null && completedSync;
}
}
bool IAsyncResult.IsCompleted
{
get {
return reply != null;
}
}
#endregion
}
}
| mit | C# |
372b331740a1dd400751b1466b810c45eb44ed4d | Test coverage for validation of the --report command line option. | fixie/fixie | src/Fixie.Tests/Execution/OptionsTests.cs | src/Fixie.Tests/Execution/OptionsTests.cs | namespace Fixie.Tests.Execution
{
using System;
using Fixie.Cli;
using Fixie.Execution;
public class OptionsTests
{
public void DemandsAssemblyPathProvided()
{
var options = new Options(null);
Action validate = options.Validate;
validate.ShouldThrow<CommandLineException>(
"Missing required test assembly path.");
}
public void DemandsAssemblyPathExistsOnDisk()
{
var options = new Options("foo.dll");
Action validate = options.Validate;
validate.ShouldThrow<CommandLineException>(
"Specified test assembly does not exist: foo.dll");
}
public void DemandsAssemblyPathDirectoryContainsFixie()
{
var mscorlib = typeof(string).Assembly.Location;
var options = new Options(mscorlib);
Action validate = options.Validate;
validate.ShouldThrow<CommandLineException>(
$"Specified assembly {mscorlib} does not appear to be a test assembly. Ensure that it references Fixie.dll and try again.");
}
public void AcceptsExistingTestAssemblyPath()
{
var assemblyPath = typeof(OptionsTests).Assembly.Location;
var options = new Options(assemblyPath);
options.Validate();
}
public void DemandsValidReportFileNameWhenProvided()
{
var assemblyPath = typeof(OptionsTests).Assembly.Location;
var options = new Options(assemblyPath);
Action validate = options.Validate;
options.Report = "Report.xml";
validate();
options.Report = "\t";
validate.ShouldThrow<CommandLineException>(
"Specified report name is invalid: \t");
}
}
} | namespace Fixie.Tests.Execution
{
using System;
using Fixie.Cli;
using Fixie.Execution;
public class OptionsTests
{
public void DemandsAssemblyPathProvided()
{
var options = new Options(null);
Action validate = options.Validate;
validate.ShouldThrow<CommandLineException>(
"Missing required test assembly path.");
}
public void DemandsAssemblyPathExistsOnDisk()
{
var options = new Options("foo.dll");
Action validate = options.Validate;
validate.ShouldThrow<CommandLineException>(
"Specified test assembly does not exist: foo.dll");
}
public void DemandsAssemblyPathDirectoryContainsFixie()
{
var mscorlib = typeof(string).Assembly.Location;
var options = new Options(mscorlib);
Action validate = options.Validate;
validate.ShouldThrow<CommandLineException>(
$"Specified assembly {mscorlib} does not appear to be a test assembly. Ensure that it references Fixie.dll and try again.");
}
public void AcceptsExistingTestAssemblyPath()
{
var assemblyPath = typeof(OptionsTests).Assembly.Location;
var options = new Options(assemblyPath);
options.Validate();
}
}
} | mit | C# |
3503282b04b25363162b4deea683f4232f24ef5e | update version number | Fearswe/TwitchChatSharp,3ventic/TwitchChatSharp | TwitchChatSharp/Properties/AssemblyInfo.cs | TwitchChatSharp/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("TwitchChatSharp")]
[assembly: AssemblyDescription("Twitch Chat Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("3ventic")]
[assembly: AssemblyProduct("TwitchChatSharp")]
[assembly: AssemblyCopyright("3v.fi © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("31eed20f-8d47-44d8-a223-7d177cb417f6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| using System.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("TwitchChatSharp")]
[assembly: AssemblyDescription("Twitch Chat Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("3ventic")]
[assembly: AssemblyProduct("TwitchChatSharp")]
[assembly: AssemblyCopyright("3v.fi © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("31eed20f-8d47-44d8-a223-7d177cb417f6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
| mit | C# |
f1d892b8c2d8d5ad2e54024728fa1f06f349d533 | Fix issue with null values returned by Memory provider | dontjee/hyde | src/Hyde/Table/Memory/DynamicMemoryQuery.cs | src/Hyde/Table/Memory/DynamicMemoryQuery.cs | using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using TechSmith.Hyde.Table.Azure;
namespace TechSmith.Hyde.Table.Memory
{
internal class DynamicMemoryQuery : AbstractMemoryQuery<dynamic>
{
public DynamicMemoryQuery( IEnumerable<GenericTableEntity> entities )
: base( entities )
{
}
private DynamicMemoryQuery( DynamicMemoryQuery previous )
: base( previous )
{
}
protected override AbstractQuery<dynamic> CreateCopy()
{
return new DynamicMemoryQuery( this );
}
internal override dynamic Convert( GenericTableEntity e )
{
return StripNullValues( e.ConvertToDynamic() );
}
private static dynamic StripNullValues( dynamic obj )
{
dynamic result = new ExpandoObject();
foreach ( var p in ( obj as IDictionary<string, object> ).Where( p => p.Value != null ) )
{
( (IDictionary<string, object>) result ).Add( p );
}
return result;
}
}
}
| using System.Collections.Generic;
using TechSmith.Hyde.Table.Azure;
namespace TechSmith.Hyde.Table.Memory
{
internal class DynamicMemoryQuery : AbstractMemoryQuery<dynamic>
{
public DynamicMemoryQuery( IEnumerable<GenericTableEntity> entities )
: base( entities )
{
}
private DynamicMemoryQuery( DynamicMemoryQuery previous )
: base( previous )
{
}
protected override AbstractQuery<dynamic> CreateCopy()
{
return new DynamicMemoryQuery( this );
}
internal override dynamic Convert( GenericTableEntity e )
{
return e.ConvertToDynamic();
}
}
}
| bsd-3-clause | C# |
37cbc3bee906066250a04437bf3f116e84b9fcba | remove trailing slash | IdentityModel/IdentityModel2,IdentityModel/IdentityModel2,IdentityModel/IdentityModel,IdentityModel/IdentityModel,IdentityModel/IdentityModelv2,IdentityModel/IdentityModelv2 | src/IdentityModel/Client/DiscoveryClient.cs | src/IdentityModel/Client/DiscoveryClient.cs | using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace IdentityModel.Client
{
public class DiscoveryClient
{
private readonly HttpClient _client;
public TimeSpan Timeout
{
set
{
_client.Timeout = value;
}
}
public DiscoveryClient(string url, HttpMessageHandler innerHandler = null)
{
var handler = innerHandler ?? new HttpClientHandler();
url = RemoveTrailingSlash(url);
if (!url.EndsWith(OidcConstants.Discovery.DiscoveryEndpoint, StringComparison.OrdinalIgnoreCase))
{
url = url + OidcConstants.Discovery.DiscoveryEndpoint;
}
_client = new HttpClient(handler)
{
BaseAddress = new Uri(url)
};
}
public async Task<DiscoveryResponse> GetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var response = await _client.GetAsync("", cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new DiscoveryResponse(json);
}
else
{
return new DiscoveryResponse(response.StatusCode, response.ReasonPhrase);
}
}
private static string RemoveTrailingSlash(string url)
{
if (url != null && url.EndsWith("/"))
{
url = url.Substring(0, url.Length - 1);
}
return url;
}
}
} | using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace IdentityModel.Client
{
public class DiscoveryClient
{
private readonly HttpClient _client;
public TimeSpan Timeout
{
set
{
_client.Timeout = value;
}
}
public DiscoveryClient(string url, HttpMessageHandler innerHandler = null)
{
var handler = innerHandler ?? new HttpClientHandler();
if (!url.EndsWith(OidcConstants.Discovery.DiscoveryEndpoint, StringComparison.OrdinalIgnoreCase))
{
url = url + OidcConstants.Discovery.DiscoveryEndpoint;
}
_client = new HttpClient(handler)
{
BaseAddress = new Uri(url)
};
}
public async Task<DiscoveryResponse> GetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var response = await _client.GetAsync("", cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new DiscoveryResponse(json);
}
else
{
return new DiscoveryResponse(response.StatusCode, response.ReasonPhrase);
}
}
}
} | apache-2.0 | C# |
947048b54346e5023a46f5b2feae0b0ec313e9b3 | copy for csproj source | cutsea110/servant-sample-book | ServantClientBook/ServantClientBook/JsonConverter.cs | ServantClientBook/ServantClientBook/JsonConverter.cs |
using Newtonsoft.Json;
using System;
namespace ServantClientBook
{
public class DayConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return DateTime.Parse((string)reader.Value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DateTime d = (DateTime)value;
writer.WriteValue(d.ToString("yyyy-MM-dd"));
}
}
}
| using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServantClientBook
{
public class DayConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return DateTime.Parse((string)reader.Value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DateTime d = (DateTime)value;
writer.WriteValue(d.ToString("yyyy-MM-dd"));
}
}
}
| bsd-3-clause | C# |
e2282e30e5349b7b277977e3aa12a5f2d0cc4727 | Add trivial history programming to overlay window to clear each turn | theAprel/OptionsDisplay | OptionsDisplay/HearthWindow.cs | OptionsDisplay/HearthWindow.cs | using Hearthstone_Deck_Tracker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace OptionsDisplay
{
class HearthWindow : InfoWindow
{
private HearthstoneTextBlock info;
public HearthWindow()
{
info = new HearthstoneTextBlock();
info.Text = "";
info.FontSize = 12;
var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas;
var fromTop = canvas.Height / 2;
var fromLeft = canvas.Width / 2;
Canvas.SetTop(info, fromTop);
Canvas.SetLeft(info, fromLeft);
canvas.Children.Add(info);
}
public void AppendWindowText(string text)
{
info.Text = info.Text + text;
}
public void ClearAll()
{
info.Text = "";
}
public void MoveToHistory()
{
info.Text = "";
}
public void SetWindowText(string text)
{
info.Text = text;
}
}
}
| using Hearthstone_Deck_Tracker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace OptionsDisplay
{
class HearthWindow : InfoWindow
{
private HearthstoneTextBlock info;
public HearthWindow()
{
info = new HearthstoneTextBlock();
info.Text = "";
info.FontSize = 12;
var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas;
var fromTop = canvas.Height / 2;
var fromLeft = canvas.Width / 2;
Canvas.SetTop(info, fromTop);
Canvas.SetLeft(info, fromLeft);
canvas.Children.Add(info);
}
public void AppendWindowText(string text)
{
info.Text = info.Text + text;
}
public void ClearAll()
{
info.Text = "";
}
public void MoveToHistory()
{
return;
}
public void SetWindowText(string text)
{
info.Text = text;
}
}
}
| agpl-3.0 | C# |
4fabcf62da91e00e9b7049558181e4d7d73341ac | Update Customer.cs | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | Test/AdventureWorksFunctionalModel/Sales/Customer.cs | Test/AdventureWorksFunctionalModel/Sales/Customer.cs | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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 AW.Functions;
using NakedFunctions;
namespace AW.Types
{
public record Customer
{
[Hidden]
public virtual int CustomerID { get; init; }
[MemberOrder(15)]
public string CustomerType => this.IsIndividual() ? "Individual" : "Store";
[DescribedAs("xxx"), MemberOrder(10)]
public virtual string AccountNumber { get; init; }
#region Store & Personal customers
[Hidden]
public virtual int? StoreID { get; init; }
[MemberOrder(20)]
public virtual Store Store { get; init; }
[Hidden]
public virtual int? PersonID { get; init; }
[MemberOrder(20)]
public virtual Person Person { get; init; }
#endregion
#region Sales Territory
[Hidden]
public virtual int? SalesTerritoryID { get; init; }
[MemberOrder(30)]
public virtual SalesTerritory SalesTerritory { get; init; }
#endregion
[Hidden]
//
public virtual DateTime CustomerModifiedDate { get; init; }
[Hidden]
public virtual Guid CustomerRowguid { get; init; }
public override string ToString() => $"{AccountNumber} {(Store is null ? Person : Store)}";
public override int GetHashCode() =>base.GetHashCode();
public virtual bool Equals(Customer other) => ReferenceEquals(this, other);
}
} | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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 AW.Functions;
using NakedFunctions;
namespace AW.Types
{
public record Customer
{
[Hidden]
public virtual int CustomerID { get; init; }
[MemberOrder(15)]
public string CustomerType => this.IsIndividual() ? "Individual" : "Store";
[DescribedAs("xxx"), MemberOrder(10)]
public virtual string AccountNumber { get; init; }
#region Sales Territory
[Hidden]
public virtual int? SalesTerritoryID { get; init; }
[MemberOrder(20)]
public virtual SalesTerritory SalesTerritory { get; init; }
#endregion
#region Store & Personal customers
[Hidden]
public virtual int? StoreID { get; init; }
[MemberOrder(20)]
public virtual Store Store { get; init; }
[Hidden]
public virtual int? PersonID { get; init; }
[MemberOrder(20)]
public virtual Person Person { get; init; }
#endregion
[Hidden]
//
public virtual DateTime CustomerModifiedDate { get; init; }
[Hidden]
public virtual Guid CustomerRowguid { get; init; }
public override string ToString() => $"{AccountNumber} {(Store is null ? Person : Store)}";
public override int GetHashCode() =>base.GetHashCode();
public virtual bool Equals(Customer other) => ReferenceEquals(this, other);
}
} | apache-2.0 | C# |
48b6ae2d1d936c0e03473c5d9d7c0c3588874750 | use common equality pattern | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Models/Sorting/SortingPreference.cs | WalletWasabi.Gui/Models/Sorting/SortingPreference.cs | using System;
using System.Diagnostics.CodeAnalysis;
namespace WalletWasabi.Gui.Models.Sorting
{
public struct SortingPreference : IEquatable<SortingPreference>
{
public SortingPreference(SortOrder sortOrder, string colTarget)
{
SortOrder = sortOrder;
ColumnTarget = colTarget;
}
public SortOrder SortOrder { get; set; }
public string ColumnTarget { get; set; }
public SortOrder Match(SortOrder targetOrd, string match)
{
return ColumnTarget == match ? targetOrd : SortOrder.None;
}
#region EqualityAndComparison
public bool Equals(SortingPreference other) => this == other;
public override int GetHashCode() => (SortOrder, ColumnTarget).GetHashCode();
public static bool operator ==(SortingPreference x, SortingPreference y)
=> (x.SortOrder, x.ColumnTarget) == (y.SortOrder, y.ColumnTarget);
public static bool operator !=(SortingPreference x, SortingPreference y) => !(x == y);
#endregion EqualityAndComparison
}
}
| using System;
using System.Diagnostics.CodeAnalysis;
namespace WalletWasabi.Gui.Models.Sorting
{
public struct SortingPreference : IEquatable<SortingPreference>
{
public SortingPreference(SortOrder sortOrder, string colTarget)
{
SortOrder = sortOrder;
ColumnTarget = colTarget;
}
public SortOrder SortOrder { get; set; }
public string ColumnTarget { get; set; }
public bool Equals([AllowNull] SortingPreference other) => SortOrder == other.SortOrder && ColumnTarget == other.ColumnTarget;
public SortOrder Match(SortOrder targetOrd, string match)
{
return ColumnTarget == match ? targetOrd : SortOrder.None;
}
}
}
| mit | C# |
c35ff9eff95bbf41c524dce4eec921d9a01325ac | refactor configuration | Pondidum/Stronk,Pondidum/Stronk | src/Stronk/Extensions.cs | src/Stronk/Extensions.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.CompilerServices;
using Stronk.PropertySelection;
using Stronk.ValueConversion;
using Stronk.ValueSelection;
namespace Stronk
{
public interface IStronkConfiguration
{
IEnumerable<IValueConverter> Converters { get; }
IEnumerable<IPropertySelector> PropertySelectors { get; }
IEnumerable<IValueSelector> ValueSelectors { get; }
}
public class StronkConfiguration : IStronkConfiguration
{
public IEnumerable<IValueConverter> Converters { get; }
public IEnumerable<IPropertySelector> PropertySelectors { get; }
public IEnumerable<IValueSelector> ValueSelectors { get; }
public StronkConfiguration()
{
Converters = new IValueConverter[]
{
new LambdaValueConverter<Uri>(val => new Uri(val)),
new EnumValueConverter(),
new FallbackValueConverter()
};
PropertySelectors = new IPropertySelector[]
{
new PrivateSetterPropertySelector(),
new BackingFieldPropertySelector(),
};
ValueSelectors = new IValueSelector[]
{
new PropertyNameValueSelector(),
};
}
}
public static class Extensions
{
public static void FromAppConfig(this object target)
{
target.FromAppConfig(new StronkConfiguration());
}
public static void FromAppConfig(this object target, IStronkConfiguration configuration)
{
var propertySelectors = configuration.PropertySelectors;
var valueSelectors = configuration.ValueSelectors.ToArray();
var converters = configuration.Converters.ToArray();
var properties = propertySelectors
.SelectMany(selector => selector.Select(target.GetType()));
var args = new ValueSelectorArgs(ConfigurationManager.AppSettings, ConfigurationManager.ConnectionStrings);
foreach (var property in properties)
{
var value = valueSelectors
.Select(filter => filter.Select(args.With(property)))
.Where(v => v != null)
.DefaultIfEmpty(null)
.First();
if (value != null)
{
var converted = converters
.First(c => c.CanMap(property.Type))
.Map(property.Type, value);
property.Assign(target, converted);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Stronk.PropertySelection;
using Stronk.ValueConversion;
using Stronk.ValueSelection;
namespace Stronk
{
public static class Extensions
{
public static void FromAppConfig(this object target)
{
var converters = new IValueConverter[]
{
new LambdaValueConverter<Uri>(val => new Uri(val)),
new EnumValueConverter(),
new FallbackValueConverter()
};
var propertySelectors = new IPropertySelector[]
{
new PrivateSetterPropertySelector(),
new BackingFieldPropertySelector(),
};
var valueSelectors = new IValueSelector[]
{
new PropertyNameValueSelector(),
};
var properties = propertySelectors
.SelectMany(selector => selector.Select(target.GetType()));
var args = new ValueSelectorArgs(ConfigurationManager.AppSettings, ConfigurationManager.ConnectionStrings);
foreach (var property in properties)
{
var value = valueSelectors
.Select(filter => filter.Select(args.With(property)))
.Where(v => v != null)
.DefaultIfEmpty(null)
.First();
if (value != null)
{
var converted = converters
.First(c => c.CanMap(property.Type))
.Map(property.Type, value);
property.Assign(target, converted);
}
}
}
}
}
| lgpl-2.1 | C# |
1199a2e2b5554be2a9ae5e69bc0a824f2ba7674c | Bump version info of Lime Test Console | takenet/lime-csharp | src/Lime.Client.TestConsole/Properties/AssemblyInfo.cs | src/Lime.Client.TestConsole/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("Lime.Client.TestConsole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lime.Client.TestConsole")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//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.12.0")]
[assembly: AssemblyFileVersion("1.0.12.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("Lime.Client.TestConsole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lime.Client.TestConsole")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//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("0.11.0.0")]
[assembly: AssemblyFileVersion("0.11.0.0")]
| apache-2.0 | C# |
1c367400916b57b1377dc400485d726d6094399b | clear secretBytes faster | valdisz/hmac-security,gorandr/hmac-security | src/HMAC/HMAC256SigningAlgorith.cs | src/HMAC/HMAC256SigningAlgorith.cs | namespace Security.HMAC
{
using System;
using System.Security;
using System.Security.Cryptography;
using System.Text;
public sealed class HMAC256SigningAlgorith : ISigningAlgorithm
{
public static readonly ISigningAlgorithm Instance = new HMAC256SigningAlgorith();
public string Sign(SecureString secret, string content)
{
byte[] contentBytes = Encoding.UTF8.GetBytes(content);
byte[] secretBytes = secret.ToByteArray(Encoding.UTF8);
byte[] signatureBytes;
using (var hmac = new HMACSHA256(secretBytes))
{
signatureBytes = hmac.ComputeHash(contentBytes);
}
// we need to remove unencrypted secret from memory
Array.Clear(secretBytes, 0, secretBytes.Length);
return Convert.ToBase64String(signatureBytes);
}
}
} | namespace Security.HMAC
{
using System;
using System.Security;
using System.Security.Cryptography;
using System.Text;
public sealed class HMAC256SigningAlgorith : ISigningAlgorithm
{
public static readonly ISigningAlgorithm Instance = new HMAC256SigningAlgorith();
public string Sign(SecureString secret, string content)
{
byte[] contentBytes = Encoding.UTF8.GetBytes(content);
byte[] secretBytes = secret.ToByteArray(Encoding.UTF8);
byte[] signatureBytes;
using (var hmac = new HMACSHA256(secretBytes))
{
signatureBytes = hmac.ComputeHash(contentBytes);
}
var signature = Convert.ToBase64String(signatureBytes);
// we need to remove unencrypted secret from memory
Array.Clear(secretBytes, 0, secretBytes.Length);
return signature;
}
}
} | mit | C# |
221291a0036a0be61457e755be78697017ff1b33 | Update OMCode.cs | ADAPT/ADAPT | source/ADAPT/Documents/OMCode.cs | source/ADAPT/Documents/OMCode.cs | /*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190430 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class OMCode
{
public OMCode()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponentIds = new List<int>();
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; }
public string Code { get; set; }
public string Description { get; set; }
public List<int> CodeComponentIds { get; set; }
public List<ContextItem> ContextItems { get; set; }
}
}
| /*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190430 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class OMCode
{
public OMCode()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponentIds = new List<int>();
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; }
public string Code { get; set; }
public string PId { get; set; }
public string Description { get; set; }
public List<int> CodeComponentIds { get; set; }
public List<ContextItem> ContextItems { get; set; }
}
}
| epl-1.0 | C# |
d6c6c3343b72c63347651cd390b91b649e73efcf | Update version | benallred/Icing | Icing/SharedAssemblyInfo.cs | Icing/SharedAssemblyInfo.cs | using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ben Allred")]
[assembly: AssemblyCopyright("Copyright © Ben Allred")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2.0")] | using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ben Allred")]
[assembly: AssemblyCopyright("Copyright © Ben Allred")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")] | mit | C# |
320634f42a8402967cb688104e4209df0ead1032 | Remove unnecessary null coalescing operator | Fredi/NetIRC | src/NetIRC/Messages/PingMessage.cs | src/NetIRC/Messages/PingMessage.cs | namespace NetIRC.Messages
{
public class PingMessage : IRCMessage, IServerMessage
{
public string Target { get; }
public PingMessage(ParsedIRCMessage parsedMessage)
{
Target = parsedMessage.Trailing;
}
}
}
| namespace NetIRC.Messages
{
public class PingMessage : IRCMessage, IServerMessage
{
public string Target { get; }
public PingMessage(ParsedIRCMessage parsedMessage)
{
Target = parsedMessage.Trailing ?? parsedMessage.Parameters[0];
}
}
}
| mit | C# |
b90ed6c5daa3dabd0349d7b102171421264d7542 | Update CustomizeThemes.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Formatting/Excel2007Themes/CustomizeThemes.cs | Examples/CSharp/Formatting/Excel2007Themes/CustomizeThemes.cs | using System.IO;
using Aspose.Cells;
using System.Drawing;
namespace Aspose.Cells.Examples.Formatting.Excel2007Themes
{
public class CustomizeThemes
{
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);
//Define Color array (of 12 colors) for Theme.
Color[] carr = new Color[12];
carr[0] = Color.AntiqueWhite; // Background1
carr[1] = Color.Brown; // Text1
carr[2] = Color.AliceBlue; // Background2
carr[3] = Color.Yellow; // Text2
carr[4] = Color.YellowGreen; // Accent1
carr[5] = Color.Red; // Accent2
carr[6] = Color.Pink; // Accent3
carr[7] = Color.Purple; // Accent4
carr[8] = Color.PaleGreen; // Accent5
carr[9] = Color.Orange; // Accent6
carr[10] = Color.Green; // Hyperlink
carr[11] = Color.Gray; // Followed Hyperlink
//Instantiate a Workbook.
//Open the template file.
Workbook workbook = new Workbook(dataDir + "book1.xlsx");
//Set the custom theme with specified colors.
workbook.CustomTheme("CustomeTheme1", carr);
//Save as the excel file.
workbook.Save(dataDir + "output.out.xlsx");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using System.Drawing;
namespace Aspose.Cells.Examples.Formatting.Excel2007Themes
{
public class CustomizeThemes
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Define Color array (of 12 colors) for Theme.
Color[] carr = new Color[12];
carr[0] = Color.AntiqueWhite; // Background1
carr[1] = Color.Brown; // Text1
carr[2] = Color.AliceBlue; // Background2
carr[3] = Color.Yellow; // Text2
carr[4] = Color.YellowGreen; // Accent1
carr[5] = Color.Red; // Accent2
carr[6] = Color.Pink; // Accent3
carr[7] = Color.Purple; // Accent4
carr[8] = Color.PaleGreen; // Accent5
carr[9] = Color.Orange; // Accent6
carr[10] = Color.Green; // Hyperlink
carr[11] = Color.Gray; // Followed Hyperlink
//Instantiate a Workbook.
//Open the template file.
Workbook workbook = new Workbook(dataDir + "book1.xlsx");
//Set the custom theme with specified colors.
workbook.CustomTheme("CustomeTheme1", carr);
//Save as the excel file.
workbook.Save(dataDir + "output.out.xlsx");
}
}
} | mit | C# |
9d6b17e2494a67ff027de4ce1e437ab499bca867 | Update XML doc comment | ilkerhalil/dnlib,picrap/dnlib,ZixiangBoy/dnlib,yck1509/dnlib,jorik041/dnlib,0xd4d/dnlib,Arthur2e5/dnlib,kiootic/dnlib,modulexcite/dnlib | src/DotNet/MD/IRowReaders.cs | src/DotNet/MD/IRowReaders.cs | namespace dot10.DotNet.MD {
/// <summary>
/// Reads metadata table columns
/// </summary>
public interface IColumnReader {
/// <summary>
/// Reads a column
/// </summary>
/// <param name="table">The table to read from</param>
/// <param name="rid">Table row id</param>
/// <param name="column">The column to read</param>
/// <param name="value">Result</param>
/// <returns><c>true</c> if <paramref name="value"/> was updated, <c>false</c> if
/// the column should be read from the original table.</returns>
bool ReadColumn(MDTable table, uint rid, ColumnInfo column, out uint value);
}
/// <summary>
/// Reads table rows
/// </summary>
public interface IRowReader<T> where T : class {
/// <summary>
/// Reads a table row
/// </summary>
/// <param name="rid">Row id</param>
/// <returns>The table row or <c>null</c> if its row should be read from the original
/// table</returns>
T ReadRow(uint rid);
}
}
| namespace dot10.DotNet.MD {
/// <summary>
/// Reads metadata table columns
/// </summary>
public interface IColumnReader {
/// <summary>
/// Reads a column
/// </summary>
/// <param name="table">The table to read from</param>
/// <param name="rid">Table row id</param>
/// <param name="column">The column to read</param>
/// <param name="value">Result</param>
/// <returns><c>true</c> if <paramref name="value"/> was updated, <c>false</c> if
/// the column should be read from the original table.</returns>
bool ReadColumn(MDTable table, uint rid, ColumnInfo column, out uint value);
}
/// <summary>
/// Reads <c>Method</c> table rows
/// </summary>
public interface IRowReader<T> where T : class {
/// <summary>
/// Reads a table row
/// </summary>
/// <param name="rid">Row id</param>
/// <returns>The table row or <c>null</c> if its row should be read from the original
/// table</returns>
T ReadRow(uint rid);
}
}
| mit | C# |
d6c8ede4aa661b81d88c5e58d09a1804ed1d427f | Support tag: [gist]id[/gist] | congdanhqx/BlogEngine.Gist | GistExtension.cs | GistExtension.cs | using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BlogEngine.Gist
{
[Extension("This extension enables Github Gist support for BlogEngine.NET.", "1.0", "Cong Danh")]
public class GistExtension
{
public GistExtension()
{
Post.Serving += Post_Serving;
}
void Post_Serving(object sender, ServingEventArgs e)
{
// [gist id=1234]
e.Body = Regex.Replace(e.Body, "\\[gist\\s[^\\]]*id=(\\d+)[^\\]]*\\]","<script src=\"https://gist.github.com/$1.js\"></script>");
// [gist]1234[/gist]
e.Body = Regex.Replace(e.Body, "\\[gist\\](\\d+)\\[\\/gist\\]", "<script src=\"https://gist.github.com/$1.js\"></script>");
}
}
}
| using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BlogEngine.Gist
{
[Extension("This extension enables Github Gist support for BlogEngine.NET.", "1.0", "Cong Danh")]
public class GistExtension
{
public GistExtension()
{
Post.Serving += Post_Serving;
}
void Post_Serving(object sender, ServingEventArgs e)
{
e.Body = Regex.Replace(e.Body, "\\[gist\\s[^\\]]*id=(\\d+)[^\\]]*\\]","<script src=\"https://gist.github.com/$1.js\"></script>");
}
}
}
| apache-2.0 | C# |
5af87a5319e6ba17ad072053e7e17e9814fea83b | Set OnScreenKeyboardOverlapsGameWindow for Android | ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework | osu.Framework.Android/AndroidGameHost.cs | osu.Framework.Android/AndroidGameHost.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Android.Graphics.Textures;
using osu.Framework.Android.Input;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input;
using osu.Framework.Input.Handlers;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
namespace osu.Framework.Android
{
public class AndroidGameHost : GameHost
{
private readonly AndroidGameView gameView;
public AndroidGameHost(AndroidGameView gameView)
{
this.gameView = gameView;
}
protected override void SetupForRun()
{
base.SetupForRun();
AndroidGameWindow.View = gameView;
Window = new AndroidGameWindow();
}
public override bool OnScreenKeyboardOverlapsGameWindow => true;
public override ITextInputSource GetTextInput()
=> new AndroidTextInput(gameView);
protected override IEnumerable<InputHandler> CreateAvailableInputHandlers()
=> new InputHandler[] { new AndroidKeyboardHandler(gameView), new AndroidTouchHandler(gameView) };
protected override Storage GetStorage(string baseName)
=> new AndroidStorage(baseName, this);
public override void OpenFileExternally(string filename)
=> throw new NotImplementedException();
public override void OpenUrlExternally(string url)
=> throw new NotImplementedException();
public override IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore)
=> new AndroidTextureLoaderStore(underlyingStore);
protected override void PerformExit(bool immediately)
{
// Do not exit on Android, Window.Run() does not block
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Android.Graphics.Textures;
using osu.Framework.Android.Input;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input;
using osu.Framework.Input.Handlers;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
namespace osu.Framework.Android
{
public class AndroidGameHost : GameHost
{
private readonly AndroidGameView gameView;
public AndroidGameHost(AndroidGameView gameView)
{
this.gameView = gameView;
}
protected override void SetupForRun()
{
base.SetupForRun();
AndroidGameWindow.View = gameView;
Window = new AndroidGameWindow();
}
public override ITextInputSource GetTextInput()
=> new AndroidTextInput(gameView);
protected override IEnumerable<InputHandler> CreateAvailableInputHandlers()
=> new InputHandler[] { new AndroidKeyboardHandler(gameView), new AndroidTouchHandler(gameView) };
protected override Storage GetStorage(string baseName)
=> new AndroidStorage(baseName, this);
public override void OpenFileExternally(string filename)
=> throw new NotImplementedException();
public override void OpenUrlExternally(string url)
=> throw new NotImplementedException();
public override IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore)
=> new AndroidTextureLoaderStore(underlyingStore);
protected override void PerformExit(bool immediately)
{
// Do not exit on Android, Window.Run() does not block
}
}
}
| mit | C# |
11ed9a369343134d8626eebc0417d0e37f806d26 | Make IKeyboardControllerImpl public | gmartin7/libpalaso,hatton/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,hatton/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,JohnThomson/libpalaso,chrisvire/libpalaso,hatton/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,JohnThomson/libpalaso,JohnThomson/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,hatton/libpalaso,ermshiperete/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,glasseyes/libpalaso,chrisvire/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso,gmartin7/libpalaso,chrisvire/libpalaso,ddaspit/libpalaso,ddaspit/libpalaso,gmartin7/libpalaso,tombogle/libpalaso,darcywong00/libpalaso,andrew-polk/libpalaso,tombogle/libpalaso,gtryus/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,ddaspit/libpalaso | PalasoUIWindowsForms/Keyboarding/InternalInterfaces/IKeyboardControllerImpl.cs | PalasoUIWindowsForms/Keyboarding/InternalInterfaces/IKeyboardControllerImpl.cs | // --------------------------------------------------------------------------------------------
// <copyright from='2012' to='2012' company='SIL International'>
// Copyright (c) 2012, SIL International. All Rights Reserved.
//
// Distributable under the terms of either the Common Public License or the
// GNU Lesser General Public License, as specified in the LICENSING.txt file.
// </copyright>
// --------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Palaso.WritingSystems;
using Palaso.UI.WindowsForms.Keyboarding.Types;
namespace Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces
{
public delegate void RegisterEventHandler(object sender, RegisterEventArgs e);
/// <summary>
/// Interface for the implementation of the keyboard controller. Implement this
/// interface if you want to provide a double for unit testing. Otherwise the default
/// implementation is sufficient.
/// </summary>
public interface IKeyboardControllerImpl: IDisposable
{
/// <summary>
/// Gets the available keyboards
/// </summary>
KeyboardCollection Keyboards { get; }
/// <summary>
/// Gets or sets the currently active keyboard. This is just a place to record it; setting it does not
/// change the keyboard behavior.
/// </summary>
IKeyboardDefinition ActiveKeyboard { get; set; }
/// <summary>
/// Gets the default system keyboard.
/// </summary>
IKeyboardDefinition DefaultKeyboard { get; }
/// <summary>
/// Registers the control for keyboarding. Called by KeyboardController when the
/// application registers a control by calling KeyboardController.Register.
/// </summary>
/// <param name="control">The control to register</param>
/// <param name="eventHandler">An event handler that receives events from the keyboard
/// adaptors. This gets passed in the ControlAdded event. Currently only IBus makes use
/// of the eventHandler. The event handler is adaptor specific,
/// therefore we use a generic object. If <c>null</c> a default handler is used.</param>
void RegisterControl(Control control, object eventHandler);
/// <summary>
/// Unregisters the control from keyboarding.
/// </summary>
void UnregisterControl(Control control);
/// <summary>
/// Occurs when the application registers the control by calling KeyboardController.Register.
/// </summary>
event RegisterEventHandler ControlAdded;
/// <summary>
/// Occurs when a control gets removed by calling KeyboardController.Unregister.
/// </summary>
event ControlEventHandler ControlRemoving;
Dictionary<Control, object> EventHandlers { get; }
}
}
| // --------------------------------------------------------------------------------------------
// <copyright from='2012' to='2012' company='SIL International'>
// Copyright (c) 2012, SIL International. All Rights Reserved.
//
// Distributable under the terms of either the Common Public License or the
// GNU Lesser General Public License, as specified in the LICENSING.txt file.
// </copyright>
// --------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Palaso.WritingSystems;
using Palaso.UI.WindowsForms.Keyboarding.Types;
namespace Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces
{
public delegate void RegisterEventHandler(object sender, RegisterEventArgs e);
/// <summary>
/// Internal interface for the implementation of the keyboard controller. Implement this
/// interface if you want to provide a double for unit testing. Otherwise the default
/// implementation is sufficient.
/// </summary>
internal interface IKeyboardControllerImpl: IDisposable
{
/// <summary>
/// Gets the available keyboards
/// </summary>
KeyboardCollection Keyboards { get; }
/// <summary>
/// Gets or sets the currently active keyboard. This is just a place to record it; setting it does not
/// change the keyboard behavior.
/// </summary>
IKeyboardDefinition ActiveKeyboard { get; set; }
/// <summary>
/// Gets the default system keyboard.
/// </summary>
IKeyboardDefinition DefaultKeyboard { get; }
/// <summary>
/// Registers the control for keyboarding. Called by KeyboardController when the
/// application registers a control by calling KeyboardController.Register.
/// </summary>
/// <param name="control">The control to register</param>
/// <param name="eventHandler">An event handler that receives events from the keyboard
/// adaptors. This gets passed in the ControlAdded event. Currently only IBus makes use
/// of the eventHandler. The event handler is adaptor specific,
/// therefore we use a generic object. If <c>null</c> a default handler is used.</param>
void RegisterControl(Control control, object eventHandler);
/// <summary>
/// Unregisters the control from keyboarding.
/// </summary>
void UnregisterControl(Control control);
/// <summary>
/// Occurs when the application registers the control by calling KeyboardController.Register.
/// </summary>
event RegisterEventHandler ControlAdded;
/// <summary>
/// Occurs when a control gets removed by calling KeyboardController.Unregister.
/// </summary>
event ControlEventHandler ControlRemoving;
Dictionary<Control, object> EventHandlers { get; }
}
}
| mit | C# |
2dcaf3bc85b370e8644fcb0bf69465f88aaa497a | Change Image to use handler property (Size property is used during initialization on one of the platforms, which happens before constructor) | bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto | Source/Eto/Drawing/Image.cs | Source/Eto/Drawing/Image.cs | using System;
using System.ComponentModel;
namespace Eto.Drawing
{
/// <summary>
/// Handler interface for the <see cref="Image"/> class
/// </summary>
public interface IImage : IInstanceWidget
{
/// <summary>
/// Gets the size of the image, in pixels
/// </summary>
Size Size { get; }
}
/// <summary>
/// Base class for images
/// </summary>
/// <remarks>
/// This provides a base for image functionality so that drawing and widgets can
/// reference any type of image, if supported.
/// For instance, <see cref="Graphics"/> and <see cref="Forms.ImageView"/> can reference
/// any Image-derived object.
/// </remarks>
[TypeConverter(typeof(ImageConverter))]
public abstract class Image : InstanceWidget
{
new IImage Handler { get { return (IImage)base.Handler; } }
/// <summary>
/// Initializes a new instance of an image with the specified type
/// </summary>
/// <param name="generator">Generator to create the handler</param>
/// <param name="type">Type of the handler to create (must be derived from <see cref="IImage"/>)</param>
protected Image(Generator generator, Type type) : base(generator, type)
{
}
/// <summary>
/// Initializes a new instance of an image with the specified handler instance
/// </summary>
/// <remarks>
/// This is useful when you want to create an image that wraps around an existing instance of the
/// handler. This is typically only done from a platform implementation that returns an image instance.
/// </remarks>
/// <param name="generator">Generator for the handler</param>
/// <param name="handler">Instance of the handler to attach to this instance</param>
protected Image(Generator generator, IImage handler) : base(generator, handler)
{
}
/// <summary>
/// Gets the size of the image, in pixels
/// </summary>
public Size Size
{
get { return Handler.Size; }
}
}
}
| using System;
using System.ComponentModel;
namespace Eto.Drawing
{
/// <summary>
/// Handler interface for the <see cref="Image"/> class
/// </summary>
public interface IImage : IInstanceWidget
{
/// <summary>
/// Gets the size of the image, in pixels
/// </summary>
Size Size { get; }
}
/// <summary>
/// Base class for images
/// </summary>
/// <remarks>
/// This provides a base for image functionality so that drawing and widgets can
/// reference any type of image, if supported.
/// For instance, <see cref="Graphics"/> and <see cref="Forms.ImageView"/> can reference
/// any Image-derived object.
/// </remarks>
[TypeConverter(typeof(ImageConverter))]
public abstract class Image : InstanceWidget
{
IImage handler;
/// <summary>
/// Initializes a new instance of an image with the specified type
/// </summary>
/// <param name="generator">Generator to create the handler</param>
/// <param name="type">Type of the handler to create (must be derived from <see cref="IImage"/>)</param>
protected Image(Generator generator, Type type) : base(generator, type)
{
handler = (IImage)Handler;
}
/// <summary>
/// Initializes a new instance of an image with the specified handler instance
/// </summary>
/// <remarks>
/// This is useful when you want to create an image that wraps around an existing instance of the
/// handler. This is typically only done from a platform implementation that returns an image instance.
/// </remarks>
/// <param name="generator">Generator for the handler</param>
/// <param name="handler">Instance of the handler to attach to this instance</param>
protected Image(Generator generator, IImage handler) : base(generator, handler)
{
handler = (IImage)Handler;
}
/// <summary>
/// Gets the size of the image, in pixels
/// </summary>
public Size Size
{
get { return handler.Size; }
}
}
}
| bsd-3-clause | C# |
7c3adfcce9d2727ff2c58c1e4da50c64daa98818 | Check for used UDP ports as well | rasmus/EventFlow | Source/EventFlow.TestHelpers/TcpHelper.cs | Source/EventFlow.TestHelpers/TcpHelper.cs | // The MIT License (MIT)
//
// Copyright (c) 2015-2017 Rasmus Mikkelsen
// Copyright (c) 2015-2017 eBay Software Foundation
// https://github.com/eventflow/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
namespace EventFlow.TestHelpers
{
public class TcpHelper
{
private static readonly Random Random = new Random();
public static int GetFreePort()
{
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
var usedPorts = Enumerable.Empty<int>()
.Concat(ipGlobalProperties.GetActiveTcpListeners().Select(l => l.Port))
.Concat(ipGlobalProperties.GetActiveUdpListeners().Select(l => l.Port))
.Concat(ipGlobalProperties.GetActiveTcpConnections().Select(c => c.LocalEndPoint.Port))
.Distinct();
var portLookup = new HashSet<int>(usedPorts);
while (true)
{
var port = Random.Next(10000, 60000);
if (!portLookup.Contains(port))
{
return port;
}
}
}
}
} | // The MIT License (MIT)
//
// Copyright (c) 2015-2017 Rasmus Mikkelsen
// Copyright (c) 2015-2017 eBay Software Foundation
// https://github.com/eventflow/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
namespace EventFlow.TestHelpers
{
public class TcpHelper
{
private static readonly Random Random = new Random();
public static int GetFreePort()
{
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
var usedPorts = Enumerable.Empty<int>()
.Concat(ipGlobalProperties.GetActiveTcpListeners().Select(l => l.Port))
.Concat(ipGlobalProperties.GetActiveTcpConnections().Select(c => c.LocalEndPoint.Port))
.Distinct();
var portLookup = new HashSet<int>(usedPorts);
while (true)
{
var port = Random.Next(10000, 60000);
if (!portLookup.Contains(port))
{
return port;
}
}
}
}
} | mit | C# |
10230daaee43fc5a3d6bc5b8ceb4746069d0467d | Update ContactObjectValue.cs | smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk | main/Smartsheet/Api/Models/ContactObjectValue.cs | main/Smartsheet/Api/Models/ContactObjectValue.cs | // #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2018 SmartsheetClient
// %%
// 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.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Smartsheet.Api.Models
{
class ContactObjectValue : Contact, ObjectValue
{
public virtual ObjectValueType ObjectType
{
get { return ObjectValueType.CONTACT; }
}
}
}
| // #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2018 SmartsheetClient
// %%
// 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.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Smartsheet.Api.Models
{
class ContactObjectValue : Contact, ObjectValue
{
public virtual ObjectValueType ObjectType
{
get { return ObjectValueType.CONTACT; }
}
}
}
| apache-2.0 | C# |
01955bc63fedcb82badad2d4a8f4cfd052b7370c | Remove accord dependence | tobyclh/UnityCNTK,tobyclh/UnityCNTK | Assets/UnityCNTK/Scripts/Models/TextureTransferModel.cs | Assets/UnityCNTK/Scripts/Models/TextureTransferModel.cs | using UnityEngine;
using CNTK;
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using UnityCNTK;
using System.Net;
using System.Threading;
using UnityEngine.Assertions;
namespace UnityCNTK
{
public class TextureTransferModel : Model
{
/* The implementation is a C# version of the original implementation found in https://github.com/Microsoft/CNTK/blob/master/Tutorials/CNTK_205_Artistic_Style_Transfer.ipynb
This example shows the limitation of the evaluation API, that deviation of parameter cannot be accessed. Therefore, in terms of
optimisation this script adopts a gradient free optimisation, using Accord
*/
public new string relativeModelPath = "Assets/UnityCNTK/Model/VGG.dnn";
public Texture2D styleRef;
public new IEnumerable<Texture2D> input;
public new IEnumerable<Texture2D> output;
public double contentWeight = 5;
public double styleWeight = 1;
public double decay = 0.5f;
// Use this for initialization
public override void LoadModel()
{
var absolutePath = System.IO.Path.Combine(Environment.CurrentDirectory, relativeModelPath);
// Downloader.DownloadPretrainedModel(Downloader.pretrainedModel.VGG16, absolutePath);
}
// Background thread that does the heavy lifting
public double[] ObjectiveFunction()
{
throw new NotImplementedException();
// return new double[2];
}
//post processing output data
protected override void OnEvaluated(Dictionary<Variable, Value> outputDataMap)
{
List<Texture2D> textures = new List<Texture2D>();
// function.Evaluate(new Dictionary<Variable, Value>().Add(inputVar,))
Texture2D outputTexture = new Texture2D(input.FirstOrDefault().width, input.FirstOrDefault().height);
output = textures;
}
public override List<Dictionary<Variable, Value>> OnPreprocess()
{
throw new NotImplementedException();
Assert.IsNotNull(device);
Assert.IsNotNull(input);
if (function == null) LoadModel();
var inputVar = function.Arguments.Single();
var inputDataMap = new Dictionary<Variable, Value>() { { inputVar, input.ToValue(device) } };
var outputDataMap = new Dictionary<Variable, Value>() { { function.Output, null } };
return new List<Dictionary<Variable, Value>>() { inputDataMap, outputDataMap };
}
}
}
| using UnityEngine;
using CNTK;
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using UnityCNTK;
using System.Net;
using System.Threading;
using Accord.Math.Optimization;
using UnityEngine.Assertions;
namespace UnityCNTK
{
public class TextureTransferModel : Model
{
/* The implementation is a C# version of the original implementation found in https://github.com/Microsoft/CNTK/blob/master/Tutorials/CNTK_205_Artistic_Style_Transfer.ipynb
This example shows the limitation of the evaluation API, that deviation of parameter cannot be accessed. Therefore, in terms of
optimisation this script adopts a gradient free optimisation, using Accord
*/
public new string relativeModelPath = "Assets/UnityCNTK/Model/VGG.dnn";
public Texture2D styleRef;
public new IEnumerable<Texture2D> input;
public new IEnumerable<Texture2D> output;
public double contentWeight = 5;
public double styleWeight = 1;
public double decay = 0.5f;
// Use this for initialization
public override void LoadModel()
{
var absolutePath = System.IO.Path.Combine(Environment.CurrentDirectory, relativeModelPath);
// Downloader.DownloadPretrainedModel(Downloader.pretrainedModel.VGG16, absolutePath);
}
// Background thread that does the heavy lifting
public double[] ObjectiveFunction()
{
throw new NotImplementedException();
// return new double[2];
}
//post processing output data
protected override void OnEvaluated(Dictionary<Variable, Value> outputDataMap)
{
List<Texture2D> textures = new List<Texture2D>();
// function.Evaluate(new Dictionary<Variable, Value>().Add(inputVar,))
Texture2D outputTexture = new Texture2D(input.FirstOrDefault().width, input.FirstOrDefault().height);
output = textures;
}
public override List<Dictionary<Variable, Value>> OnPreprocess()
{
throw new NotImplementedException();
Assert.IsNotNull(device);
Assert.IsNotNull(input);
if (function == null) LoadModel();
var inputVar = function.Arguments.Single();
var inputDataMap = new Dictionary<Variable, Value>() { { inputVar, input.ToValue(device) } };
var outputDataMap = new Dictionary<Variable, Value>() { { function.Output, null } };
return new List<Dictionary<Variable, Value>>() { inputDataMap, outputDataMap };
}
}
}
| mit | C# |
38a6005d075afcc9611b65ac1756d6f324f3c421 | remove unused imports | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | Dashen/View.cs | Dashen/View.cs | using System;
using System.IO;
using System.Linq;
namespace Dashen
{
public class View
{
private readonly ModelInfoRepository _modelInfo;
public View(ModelInfoRepository modelInfo)
{
_modelInfo = modelInfo;
}
private string GetTemplate()
{
using (var stream = GetType().Assembly.GetManifestResourceStream("Dashen.Static.views.Index.htm"))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
private string GetComponents()
{
var components = _modelInfo
.All()
.Select(info => info.Component.Name)
.Distinct()
.Select(name => string.Format("<script type='text/jsx' src='models/type/{0}'></script>", name));
return string.Join(Environment.NewLine, components);
}
public string Render()
{
return GetTemplate()
.Replace("{components}", GetComponents());
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Text;
using Dashen.Infrastructure;
namespace Dashen
{
public class View
{
private readonly ModelInfoRepository _modelInfo;
public View(ModelInfoRepository modelInfo)
{
_modelInfo = modelInfo;
}
private string GetTemplate()
{
using (var stream = GetType().Assembly.GetManifestResourceStream("Dashen.Static.views.Index.htm"))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
private string GetComponents()
{
var components = _modelInfo
.All()
.Select(info => info.Component.Name)
.Distinct()
.Select(name => string.Format("<script type='text/jsx' src='models/type/{0}'></script>", name));
return string.Join(Environment.NewLine, components);
}
public string Render()
{
return GetTemplate()
.Replace("{components}", GetComponents());
}
}
}
| lgpl-2.1 | C# |
3ddc928421c3693d78cc7de71e54a582a8eebae3 | Update ReporterSettingsTests.cs | GHPReporter/Ghpr.Core,GHPReporter/Ghpr.Core,GHPReporter/Ghpr.Core | Ghpr.Tests.Tests/Core/Settings/ReporterSettingsTests.cs | Ghpr.Tests.Tests/Core/Settings/ReporterSettingsTests.cs | using System;
using Ghpr.Core.Exceptions;
using Ghpr.Core.Settings;
using Ghpr.Core.Utils;
using NUnit.Framework;
namespace Ghpr.Core.Tests.Core.Settings
{
[TestFixture]
public class ReporterSettingsTests
{
[Test]
public void LoadedCorrectly()
{
var settings = "Ghpr.Core.Tests.Settings.json".LoadSettingsAs<ReporterSettings>().DefaultSettings;
Assert.AreEqual("Awesome project", settings.ProjectName);
Assert.AreEqual("Ghpr.LocalFileSystem.dll", settings.DataServiceFile);
Assert.AreEqual("log.dll", settings.LoggerFile);
Assert.AreEqual("C:\\_GHPReporter_Core_Report", settings.OutputPath);
Assert.AreEqual(true, settings.RealTimeGeneration);
Assert.AreEqual("GHP Report", settings.ReportName);
Assert.AreEqual(10, settings.Retention.Amount);
Assert.AreEqual(new DateTime(2018, 8, 20, 10, 15, 42),
settings.Retention.Till); //"2018-08-20 10:15:42"
Assert.AreEqual("66e6f6ba-5b35-475a-a617-394696331f28", settings.RunGuid);
Assert.AreEqual("Awesome run", settings.RunName);
Assert.AreEqual(5, settings.RunsToDisplay);
Assert.AreEqual("Sprint name", settings.Sprint);
Assert.AreEqual(7, settings.TestsToDisplay);
Assert.AreEqual(true, settings.EscapeTestOutput);
}
[Test]
public void FileNotFound()
{
Assert.Throws<ReadSettingsFileException>(() =>
{
"Ghpr.Core.Tests.Settings1.json".LoadSettingsAs<ReporterSettings>();
});
}
}
}
| using System;
using System.IO;
using Ghpr.Core.Exceptions;
using Ghpr.Core.Settings;
using Ghpr.Core.Utils;
using NUnit.Framework;
namespace Ghpr.Core.Tests.Core.Settings
{
[TestFixture]
public class ReporterSettingsTests
{
[Test]
public void LoadedCorrectly()
{
var settings = "Ghpr.Core.Tests.Settings.json".LoadSettingsAs<ReporterSettings>().DefaultSettings;
Assert.AreEqual("Awesome project", settings.ProjectName);
Assert.AreEqual("Ghpr.LocalFileSystem.dll", settings.DataServiceFile);
Assert.AreEqual("log.dll", settings.LoggerFile);
Assert.AreEqual("C:\\_GHPReporter_Core_Report", settings.OutputPath);
Assert.AreEqual(true, settings.RealTimeGeneration);
Assert.AreEqual("GHP Report", settings.ReportName);
Assert.AreEqual(10, settings.Retention.Amount);
Assert.AreEqual(new DateTime(2018, 8, 20, 10, 15, 42),
settings.Retention.Till); //"2018-08-20 10:15:42"
Assert.AreEqual("66e6f6ba-5b35-475a-a617-394696331f28", settings.RunGuid);
Assert.AreEqual("Awesome run", settings.RunName);
Assert.AreEqual(5, settings.RunsToDisplay);
Assert.AreEqual("Sprint name", settings.Sprint);
Assert.AreEqual(7, settings.TestsToDisplay);
Assert.AreEqual(true, settings.EscapeTestOutput);
}
[Test]
public void FileNotFound()
{
Assert.Throws<ReadSettingsFileException>(() =>
{
"Ghpr.Core.Tests.Settings1.json".LoadSettingsAs<ReporterSettings>();
});
}
}
}
| mit | C# |
56d3eebf9a430e56a2386864ebe62970a9733103 | add disconnect log | balloon-stat/GetComments.unity | GetComments.cs | GetComments.cs | using UnityEngine;
public class GetComments : MonoBehaviour {
string liveID = "";
string liveURL = "";
LiveComments live = null;
void OnGUI() {
GUI.Label(new Rect(15, 5, 100, 30), "Input URL");
liveURL = GUI.TextField(new Rect(10, 30, 300, 25), liveURL);
if (GUI.Button(new Rect(315, 30, 50, 25), "接続")) {
var url = "http://live.nicovideo.jp/watch/";
var ix = liveURL.IndexOf("?");
ix = ix != -1 ? ix : liveURL.Length;
liveID = liveURL.Substring(0, ix)
.Substring(url.Length);
Debug.Log("View: " + liveID);
live.Run(liveID);
}
if (GUI.Button(new Rect(315, 60, 50, 25), "切断")) {
live.DisConnect();
Debug.Log("Disconnect");
}
}
void Start() {
Debug.Log("Start");
live = new LiveComments();
live.numRoom = 2;
CommentClient.FromRes = 0;
}
// res: コメント内容, no, prem, id, room_label
void Update() {
var res = live.Res;
if (res != null)
Debug.Log(res[4] + ": " + res[0]);
}
}
| using UnityEngine;
public class GetComments : MonoBehaviour {
string liveID = "";
string liveURL = "";
LiveComments live = null;
void OnGUI() {
GUI.Label(new Rect(15, 5, 100, 30), "Input URL");
liveURL = GUI.TextField(new Rect(10, 30, 300, 25), liveURL);
if (GUI.Button(new Rect(315, 30, 50, 25), "接続")) {
var url = "http://live.nicovideo.jp/watch/";
var ix = liveURL.IndexOf("?");
ix = ix != -1 ? ix : liveURL.Length;
liveID = liveURL.Substring(0, ix)
.Substring(url.Length);
Debug.Log("View: " + liveID);
live.Run(liveID);
}
if (GUI.Button(new Rect(315, 60, 50, 25), "切断")) {
live.DisConnect();
Debug.Log("Disconnect");
}
}
void Start() {
Debug.Log("Start");
live = new LiveComments();
live.numRoom = 2;
CommentClient.FromRes = 0;
}
// res: コメント内容, no, prem, id, room_label
void Update() {
var res = live.Res;
if (res != null)
Debug.Log(res[4] + ": " + res[0]);
}
}
| mit | C# |
a79b5640bd4673407819a20486cd099a09ac1993 | remove unused using | EhrgoHealth/CS6440,EhrgoHealth/CS6440 | src/EhrgoHealth.Web/Startup.cs | src/EhrgoHealth.Web/Startup.cs | using System;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(EhrgoHealth.Web.Startup))]
namespace EhrgoHealth.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterModule(new AutofacWebTypesModule());
builder.Register((a) =>
{
var context = a.Resolve<HttpContextBase>();
if(context != null)
{
return context.GetOwinContext().Get<ApplicationSignInManager>();
}
return null;
});
builder.Register((a) =>
{
var context = a.Resolve<HttpContextBase>();
if(context != null)
{
return context.GetOwinContext().Get<ApplicationUserManager>();
}
return null;
});
builder.Register((a) =>
{
var context = a.Resolve<HttpContextBase>();
if(context != null)
{
return context.GetOwinContext().Authentication;
}
return null;
});
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
ConfigureAuth(app);
}
}
} | using System;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Owin;
[assembly: OwinStartupAttribute(typeof(EhrgoHealth.Web.Startup))]
namespace EhrgoHealth.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterModule(new AutofacWebTypesModule());
builder.Register((a) =>
{
var context = a.Resolve<HttpContextBase>();
if(context != null)
{
return context.GetOwinContext().Get<ApplicationSignInManager>();
}
return null;
});
builder.Register((a) =>
{
var context = a.Resolve<HttpContextBase>();
if(context != null)
{
return context.GetOwinContext().Get<ApplicationUserManager>();
}
return null;
});
builder.Register((a) =>
{
var context = a.Resolve<HttpContextBase>();
if(context != null)
{
return context.GetOwinContext().Authentication;
}
return null;
});
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
ConfigureAuth(app);
}
}
} | mit | C# |
1f4c17b8f856a1d010fd2e45345d199c51dfba14 | Apply changes to AllowScreenSuspension bindable | UselessToucan/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu | osu.Game/Screens/Play/ScreenSuspensionHandler.cs | osu.Game/Screens/Play/ScreenSuspensionHandler.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
namespace osu.Game.Screens.Play
{
/// <summary>
/// Ensures screen is not suspended / dimmed while gameplay is active.
/// </summary>
public class ScreenSuspensionHandler : Component
{
private readonly GameplayClockContainer gameplayClockContainer;
private Bindable<bool> isPaused;
private readonly Bindable<bool> disableSuspensionBindable = new Bindable<bool>();
[Resolved]
private GameHost host { get; set; }
public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
{
this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
}
protected override void LoadComplete()
{
base.LoadComplete();
isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
isPaused.BindValueChanged(paused =>
{
if (paused.NewValue)
host.AllowScreenSuspension.RemoveSource(disableSuspensionBindable);
else
host.AllowScreenSuspension.AddSource(disableSuspensionBindable);
}, true);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
isPaused?.UnbindAll();
host?.AllowScreenSuspension.RemoveSource(disableSuspensionBindable);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
namespace osu.Game.Screens.Play
{
/// <summary>
/// Ensures screen is not suspended / dimmed while gameplay is active.
/// </summary>
public class ScreenSuspensionHandler : Component
{
private readonly GameplayClockContainer gameplayClockContainer;
private Bindable<bool> isPaused;
[Resolved]
private GameHost host { get; set; }
public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
{
this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
}
protected override void LoadComplete()
{
base.LoadComplete();
// This is the only usage game-wide of suspension changes.
// Assert to ensure we don't accidentally forget this in the future.
Debug.Assert(host.AllowScreenSuspension.Value);
isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
isPaused?.UnbindAll();
if (host != null)
host.AllowScreenSuspension.Value = true;
}
}
}
| mit | C# |
a5e9189f8a0234f082c65abfbc30e4ff04970e78 | Use float instead of int | markmnl/FalconUDP | FalconHelper.cs | FalconHelper.cs | using System;
namespace FalconUDP
{
internal static class FalconHelper
{
internal static unsafe void WriteFalconHeader(byte[] dstBuffer,
int dstIndex,
PacketType type,
SendOptions opts,
ushort seq,
ushort payloadSize)
{
fixed (byte* ptr = &dstBuffer[dstIndex])
{
*ptr = (byte)((byte)opts | (byte)type);
*(ushort*)(ptr + 1) = seq;
*(ushort*)(ptr + 3) = payloadSize;
}
}
internal static unsafe void WriteAdditionalFalconHeader(byte[] dstBuffer,
int dstIndex,
PacketType type,
SendOptions opts,
ushort payloadSize)
{
fixed (byte* ptr = &dstBuffer[dstIndex])
{
*ptr = (byte)((byte)opts | (byte)type);
*(ushort*)(ptr + 1) = payloadSize;
}
}
internal static void WriteAck(AckDetail ack,
byte[] dstBuffer,
int dstIndex)
{
float ellapsedMilliseconds = ack.EllapsedSecondsSinceEnqueud * 1000.0f;
ushort stopoverMilliseconds = ellapsedMilliseconds > ushort.MaxValue
? ushort.MaxValue
: (ushort)ellapsedMilliseconds; // TODO log warning if was greater than MaxValue
WriteFalconHeader(dstBuffer,
dstIndex,
ack.Type,
ack.Channel,
ack.Seq,
stopoverMilliseconds);
}
}
}
| using System;
namespace FalconUDP
{
internal static class FalconHelper
{
internal static unsafe void WriteFalconHeader(byte[] dstBuffer,
int dstIndex,
PacketType type,
SendOptions opts,
ushort seq,
ushort payloadSize)
{
fixed (byte* ptr = &dstBuffer[dstIndex])
{
*ptr = (byte)((byte)opts | (byte)type);
*(ushort*)(ptr + 1) = seq;
*(ushort*)(ptr + 3) = payloadSize;
}
}
internal static unsafe void WriteAdditionalFalconHeader(byte[] dstBuffer,
int dstIndex,
PacketType type,
SendOptions opts,
ushort payloadSize)
{
fixed (byte* ptr = &dstBuffer[dstIndex])
{
*ptr = (byte)((byte)opts | (byte)type);
*(ushort*)(ptr + 1) = payloadSize;
}
}
internal static void WriteAck(AckDetail ack,
byte[] dstBuffer,
int dstIndex)
{
float ellapsedMilliseconds = ack.EllapsedSecondsSinceEnqueud * 1000;
ushort stopoverMilliseconds = ellapsedMilliseconds > ushort.MaxValue
? ushort.MaxValue
: (ushort)ellapsedMilliseconds; // TODO log warning if was greater than MaxValue
WriteFalconHeader(dstBuffer,
dstIndex,
ack.Type,
ack.Channel,
ack.Seq,
stopoverMilliseconds);
}
}
}
| mit | C# |
39b871d786483b8401fec9e57cbaf3f58ec5198d | implement most of it | openmedicus/gtk-sharp,akrisiun/gtk-sharp,akrisiun/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,antoniusriha/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,akrisiun/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,antoniusriha/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp | sample/GtkDemo/DemoApplicationWindow.cs | sample/GtkDemo/DemoApplicationWindow.cs | //
// ApplicationWindow.cs, port of appwindow.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
/* Application main window
*
* Demonstrates a typical application window, with menubar, toolbar, statusbar.
*/
// : - Is this necesary? /* Set up item factory to go away with the window */
using System;
using Gtk;
using GtkSharp;
namespace GtkDemo
{
public class DemoApplicationWindow
{
private Gtk.Window window;
// static ItemFactoryEntry items[] = { new ItemFactoryEntry ("/_File", null, 0, 0, "<Branch>" )};
public DemoApplicationWindow ()
{
window = new Gtk.Window ("Demo Application Window");
window.SetDefaultSize (400, 300);
window.DeleteEvent += new DeleteEventHandler (WindowDelete);
VBox vbox = new VBox (false, 0);
window.Add (vbox);
// Create the menubar
AccelGroup accelGroup = new AccelGroup ();
window.AddAccelGroup (accelGroup);
MenuBar menubar = CreateMenu ();
vbox.PackStart (menubar, false, false, 0);
Toolbar toolbar = CreateToolbar ();
vbox.PackStart (toolbar, false, false, 0);
TextView textview = new TextView ();
vbox.PackStart (textview, true, true, 0);
Statusbar statusbar = new Statusbar ();
statusbar.Push (1, "Cursor at row 0 column 0 - 0 chars in document");
vbox.PackStart (statusbar, false, false, 0);
//ItemFactory itemFactory = new ItemFactory (typeof (MenuBar),"<main>", accelGroup);
// static ItemFactoryEntry items[] = { new ItemFactoryEntry ("/_File", null, 0, 0, "<Branch>" )};
// Set up item factory to go away with the window
// Is this necesary ?
// create menu items
//STUCK : Didn't find any examples of ItemFactory
window.ShowAll ();
}
private MenuBar CreateMenu ()
{
MenuBar menubar = new MenuBar ();
MenuItem file = new MenuItem ("File");
menubar.Append (file);
return menubar;
}
private Toolbar CreateToolbar ()
{
Toolbar toolbar = new Toolbar ();
Button open = Button.NewFromStock (Stock.Open);
open.Clicked += new EventHandler (OnToolbarClicked);
toolbar.AppendWidget (open, "Open", "Open");
Button quit = Button.NewFromStock (Stock.Quit);
quit.Clicked += new EventHandler (OnToolbarClicked);
toolbar.AppendWidget (quit, "Quit", "Quit");
Button gtk = new Button ("Gtk#");
gtk.Clicked += new EventHandler (OnToolbarClicked);
toolbar.AppendWidget (gtk, "Gtk#", "Gtk#");
return toolbar;
}
private void OnToolbarClicked (object o, EventArgs args)
{
MessageDialog md = new MessageDialog (window, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, "You selected a toolbar button.");
md.Run ();
md.Hide ();
md.Dispose ();
}
private void WindowDelete (object o, DeleteEventArgs args)
{
window.Hide ();
window.Destroy ();
}
}
}
| //
// ApplicationWindow.cs, port of appwindow.c from gtk-demo
//
// Author: Daniel Kornhauser <dkor@alum.mit.edu>
//
// Copyright (C) 2003, Ximian Inc.
/* Application main window
*
* Demonstrates a typical application window, with menubar, toolbar, statusbar.
*/
// : - Is this necesary? /* Set up item factory to go away with the window */
using System;
using Gtk;
using GtkSharp;
namespace GtkDemo
{
public class DemoApplicationWindow
{
private Gtk.Window window;
// static ItemFactoryEntry items[] = { new ItemFactoryEntry ("/_File", null, 0, 0, "<Branch>" )};
public DemoApplicationWindow ()
{
window = new Gtk.Window ("Demo Application Window");
window.DeleteEvent += new DeleteEventHandler (WindowDelete);
Table table = new Table (1, 4, false);
window.Add (table);
// Create the menubar
AccelGroup accelGroup = new AccelGroup ();
window.AddAccelGroup (accelGroup);
//ItemFactory itemFactory = new ItemFactory ((uint) typeof (MenuBar),"<main>", accelGroup);
// static ItemFactoryEntry items[] = { new ItemFactoryEntry ("/_File", null, 0, 0, "<Branch>" )};
// Set up item factory to go away with the window
// Is this necesary ?
// create menu items
//STUCK : Didn't find any examples of ItemFactory
window.ShowAll ();
}
private void WindowDelete (object o, DeleteEventArgs args)
{
window.Hide ();
window.Destroy ();
}
}
}
| lgpl-2.1 | C# |
d1549625d8720e244d79119455d5a681a021c451 | Use the new TypeInfo API for checking generic types. | djanosik/Moon.OData | src/Moon.AspNet.OData/ODataOptionsModelBinder.cs | src/Moon.AspNet.OData/ODataOptionsModelBinder.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.ModelBinding;
using Moon.OData;
using Moon.Reflection;
using System.Reflection;
namespace Moon.AspNet.OData
{
/// <summary>
/// <see cref="IModelBinder" /> implementation to bind models of type <see cref="ODataOptions{TEntity}" />.
/// </summary>
public class ODataOptionsModelBinder : IModelBinder
{
readonly IEnumerable<IPrimitiveType> primitives;
/// <summary>
/// Initializes a new instance of the <see cref="ODataOptionsModelBinder" /> class.
/// </summary>
/// <param name="primitives">An enumeration of primitive types.</param>
public ODataOptionsModelBinder(IEnumerable<IPrimitiveType> primitives)
{
this.primitives = primitives;
}
/// <summary>
/// Binds an <see cref="ODataQuery{TEntity}" /> parameter if possible.
/// </summary>
/// <param name="bindingContext">The binding context.</param>
public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
{
ModelBindingResult result = null;
var request = bindingContext.OperationBindingContext.HttpContext.Request;
var modelType = bindingContext.ModelType;
var typeInfo = modelType.GetTypeInfo();
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(ODataOptions<>))
{
var model = Class.Create(modelType, GetOptions(request), primitives);
result = new ModelBindingResult(model, bindingContext.ModelName, true);
}
return Task.FromResult(result);
}
IDictionary<string, string> GetOptions(HttpRequest request)
{
Requires.NotNull(request, nameof(request));
return request.Query.ToDictionary(p => p.Key, p => p.Value.FirstOrDefault());
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.ModelBinding;
using Moon.OData;
using Moon.Reflection;
namespace Moon.AspNet.OData
{
/// <summary>
/// <see cref="IModelBinder" /> implementation to bind models of type <see cref="ODataOptions{TEntity}" />.
/// </summary>
public class ODataOptionsModelBinder : IModelBinder
{
readonly IEnumerable<IPrimitiveType> primitives;
/// <summary>
/// Initializes a new instance of the <see cref="ODataOptionsModelBinder" /> class.
/// </summary>
/// <param name="primitives">An enumeration of primitive types.</param>
public ODataOptionsModelBinder(IEnumerable<IPrimitiveType> primitives)
{
this.primitives = primitives;
}
/// <summary>
/// Binds an <see cref="ODataQuery{TEntity}" /> parameter if possible.
/// </summary>
/// <param name="bindingContext">The binding context.</param>
public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
{
ModelBindingResult result = null;
var request = bindingContext.OperationBindingContext.HttpContext.Request;
var modelType = bindingContext.ModelType;
if (modelType.IsGenericType && modelType.GetGenericTypeDefinition() == typeof(ODataOptions<>))
{
var model = Class.Create(modelType, GetOptions(request), primitives);
result = new ModelBindingResult(model, bindingContext.ModelName, true);
}
return Task.FromResult(result);
}
IDictionary<string, string> GetOptions(HttpRequest request)
{
Requires.NotNull(request, nameof(request));
return request.Query.ToDictionary(p => p.Key, p => p.Value.FirstOrDefault());
}
}
} | mit | C# |
7828748e60f01ca299067b5e5ae7a7378c8a59cc | handle old-style errors | gitsno/MySqlConnector,mysql-net/MySqlConnector,gitsno/MySqlConnector,mysql-net/MySqlConnector | src/MySqlConnector/Serialization/ErrorPayload.cs | src/MySqlConnector/Serialization/ErrorPayload.cs | using System.Text;
using MySql.Data.MySqlClient;
namespace MySql.Data.Serialization
{
// See https://dev.mysql.com/doc/internals/en/packet-ERR_Packet.html
internal class ErrorPayload
{
public int ErrorCode { get; }
public string State { get; }
public string Message { get; }
public MySqlException ToException()
{
return new MySqlException(ErrorCode, State, Message);
}
public static ErrorPayload Create(PayloadData payload)
{
var reader = new ByteArrayReader(payload.ArraySegment);
reader.ReadByte(Signature);
var errorCode = reader.ReadUInt16();
var stateMarker = Encoding.ASCII.GetString(reader.ReadByteString(1));
string state, message;
if (stateMarker == "#")
{
state = Encoding.ASCII.GetString(reader.ReadByteString(5));
message = Encoding.UTF8.GetString(reader.ReadByteString(payload.ArraySegment.Count - 9));
}
else
{
state = "HY000";
message = stateMarker + Encoding.UTF8.GetString(reader.ReadByteString(payload.ArraySegment.Count - 4));
}
return new ErrorPayload(errorCode, state, message);
}
public const byte Signature = 0xFF;
private ErrorPayload(int errorCode, string state, string message)
{
ErrorCode = errorCode;
State = state;
Message = message;
}
}
}
| using System.Text;
using MySql.Data.MySqlClient;
namespace MySql.Data.Serialization
{
// See https://dev.mysql.com/doc/internals/en/packet-ERR_Packet.html
internal class ErrorPayload
{
public int ErrorCode { get; }
public string State { get; }
public string Message { get; }
public MySqlException ToException()
{
return new MySqlException(ErrorCode, State, Message);
}
public static ErrorPayload Create(PayloadData payload)
{
var reader = new ByteArrayReader(payload.ArraySegment);
reader.ReadByte(Signature);
var errorCode = reader.ReadUInt16();
reader.ReadByte(0x23);
var state = Encoding.ASCII.GetString(reader.ReadByteString(5));
var message = Encoding.UTF8.GetString(reader.ReadByteString(payload.ArraySegment.Count - 9));
return new ErrorPayload(errorCode, state, message);
}
public const byte Signature = 0xFF;
private ErrorPayload(int errorCode, string state, string message)
{
ErrorCode = errorCode;
State = state;
Message = message;
}
}
}
| mit | C# |
214746bca22c0f8087709596484f03150ad67fa5 | Optimize updating of server list We can compare new endpoints firstly, to save Save() call if they're equal values-wise. | KlappPc/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,KlappPc/ArchiSteamFarm,KlappPc/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,i3at/ArchiSteamFarm,i3at/ArchiSteamFarm,JustArchi/ArchiSteamFarm | ArchiSteamFarm/InMemoryServerListProvider.cs | ArchiSteamFarm/InMemoryServerListProvider.cs | /*
_ _ _ ____ _ _____
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
Copyright 2015-2016 Łukasz "JustArchi" Domeradzki
Contact: JustArchi@JustArchi.net
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.Diagnostics.CodeAnalysis;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SteamKit2.Discovery;
namespace ArchiSteamFarm {
internal sealed class InMemoryServerListProvider : IServerListProvider {
[JsonProperty(Required = Required.DisallowNull)]
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")]
private HashSet<IPEndPoint> Servers = new HashSet<IPEndPoint>();
internal event EventHandler ServerListUpdated = delegate { };
public Task<IEnumerable<IPEndPoint>> FetchServerListAsync() => Task.FromResult<IEnumerable<IPEndPoint>>(Servers);
public Task UpdateServerListAsync(IEnumerable<IPEndPoint> endPoints) {
if (endPoints == null) {
Logging.LogNullError(nameof(endPoints));
return Task.Delay(0);
}
HashSet<IPEndPoint> newEndPoints = new HashSet<IPEndPoint>(endPoints);
if (Servers.SetEquals(newEndPoints)) {
return Task.Delay(0);
}
Servers = newEndPoints;
ServerListUpdated(this, EventArgs.Empty);
return Task.Delay(0);
}
}
}
| /*
_ _ _ ____ _ _____
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
Copyright 2015-2016 Łukasz "JustArchi" Domeradzki
Contact: JustArchi@JustArchi.net
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.Diagnostics.CodeAnalysis;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SteamKit2.Discovery;
namespace ArchiSteamFarm {
internal sealed class InMemoryServerListProvider : IServerListProvider {
[JsonProperty(Required = Required.DisallowNull)]
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")]
private HashSet<IPEndPoint> Servers = new HashSet<IPEndPoint>();
internal event EventHandler ServerListUpdated = delegate { };
public Task<IEnumerable<IPEndPoint>> FetchServerListAsync() => Task.FromResult<IEnumerable<IPEndPoint>>(Servers);
public Task UpdateServerListAsync(IEnumerable<IPEndPoint> endpoints) {
if (endpoints == null) {
Logging.LogNullError(nameof(endpoints));
return Task.Delay(0);
}
Servers.Clear();
foreach (IPEndPoint endpoint in endpoints) {
Servers.Add(endpoint);
}
ServerListUpdated(this, EventArgs.Empty);
return Task.Delay(0);
}
}
}
| apache-2.0 | C# |
76f9440c8227f0df59cdfe02d246c66af7872069 | Test exponent of NumberParser without exponent sign | smbecker/Eto.Parse,ArsenShnurkov/Eto.Parse,ArsenShnurkov/Eto.Parse,picoe/Eto.Parse,picoe/Eto.Parse,smbecker/Eto.Parse | Eto.Parse.Tests/Parsers/NumberParserTests.cs | Eto.Parse.Tests/Parsers/NumberParserTests.cs | using System;
using NUnit.Framework;
using Eto.Parse.Parsers;
using System.Linq;
namespace Eto.Parse.Tests.Parsers
{
[TestFixture]
public class NumberParserTests
{
[Test]
public void TestDecimal()
{
var sample = "123.4567,1234567";
var grammar = new Grammar();
var num = new NumberParser { AllowDecimal = true, AllowSign = false };
grammar.Inner = (+num.Named("str")).SeparatedBy(",");
var match = grammar.Match(sample);
Assert.IsTrue(match.Success, match.ErrorMessage);
CollectionAssert.AreEquivalent(new Decimal[] { 123.4567M, 1234567M }, match.Find("str").Select(m => num.GetValue(m)));
}
[Test]
public void TestSign()
{
var sample = "123.4567,+123.4567,-123.4567";
var grammar = new Grammar();
var num = new NumberParser { AllowSign = true, AllowDecimal = true };
grammar.Inner = (+num.Named("str")).SeparatedBy(",");
var match = grammar.Match(sample);
Assert.IsTrue(match.Success, match.ErrorMessage);
CollectionAssert.AreEquivalent(new Decimal[] { 123.4567M, 123.4567M, -123.4567M }, match.Find("str").Select(m => num.GetValue(m)));
}
[Test]
public void TestExponent()
{
var sample = "123E-02,123E+10,123.4567E+5,1234E2";
var grammar = new Grammar();
var num = new NumberParser { AllowDecimal = true, AllowExponent = true };
grammar.Inner = (+num.Named("str")).SeparatedBy(",");
var match = grammar.Match(sample);
Assert.IsTrue(match.Success, match.ErrorMessage);
CollectionAssert.AreEquivalent(new Decimal[] { 123E-2M, 123E+10M, 123.4567E+5M, 1234E+2M }, match.Find("str").Select(m => num.GetValue(m)));
}
}
}
| using System;
using NUnit.Framework;
using Eto.Parse.Parsers;
using System.Linq;
namespace Eto.Parse.Tests.Parsers
{
[TestFixture]
public class NumberParserTests
{
[Test]
public void TestDecimal()
{
var sample = "123.4567,1234567";
var grammar = new Grammar();
var num = new NumberParser { AllowDecimal = true, AllowSign = false };
grammar.Inner = (+num.Named("str")).SeparatedBy(",");
var match = grammar.Match(sample);
Assert.IsTrue(match.Success, match.ErrorMessage);
CollectionAssert.AreEquivalent(new Decimal[] { 123.4567M, 1234567M }, match.Find("str").Select(m => num.GetValue(m)));
}
[Test]
public void TestSign()
{
var sample = "123.4567,+123.4567,-123.4567";
var grammar = new Grammar();
var num = new NumberParser { AllowSign = true, AllowDecimal = true };
grammar.Inner = (+num.Named("str")).SeparatedBy(",");
var match = grammar.Match(sample);
Assert.IsTrue(match.Success, match.ErrorMessage);
CollectionAssert.AreEquivalent(new Decimal[] { 123.4567M, 123.4567M, -123.4567M }, match.Find("str").Select(m => num.GetValue(m)));
}
[Test]
public void TestExponent()
{
var sample = "123E-02,123E+10,123.4567E+5";
var grammar = new Grammar();
var num = new NumberParser { AllowDecimal = true, AllowExponent = true };
grammar.Inner = (+num.Named("str")).SeparatedBy(",");
var match = grammar.Match(sample);
Assert.IsTrue(match.Success, match.ErrorMessage);
CollectionAssert.AreEquivalent(new Decimal[] { 123E-2M, 123E+10M, 123.4567E+5M }, match.Find("str").Select(m => num.GetValue(m)));
}
}
}
| mit | C# |
db2650e792d72d517f459b385b6b4cecd6d4ace8 | Use the invariant culture when formatting numbers so that different contributors locale settings don't produce different html. | castleproject/castle-READONLY-SVN-dump,castleproject/castle-READONLY-SVN-dump,carcer/Castle.Components.Validator,castleproject/Castle.Transactions,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Transactions,castleproject/Castle.Transactions,castleproject/Castle.Facilities.Wcf-READONLY,castleproject/Castle.Facilities.Wcf-READONLY,codereflection/Castle.Components.Scheduler | Experiments/AnakiaNet/Anakia/SimpleHelper.cs | Experiments/AnakiaNet/Anakia/SimpleHelper.cs | // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Anakia
{
using System;
using System.Collections;
using System.IO;
using System.Globalization;
public class SimpleHelper
{
public String FileSizeInKBytes(String basePath, String file)
{
FileInfo info = new FileInfo(Path.Combine(basePath, file));
if (info.Exists)
{
return String.Format(CultureInfo.InvariantCulture,"{0:#.##}", info.Length / 1024f).ToString();
}
throw new Exception("File " + info.FullName + " was not found");
}
public String RemoveOffset(String offset, String path)
{
return path.Substring(offset.Length);
}
public String Relativize(String offset, String path, String page)
{
try
{
if (offset.Length >= path.Length)
{
return String.Format("./{0}", page);
}
else
{
String newPath = path.Substring(offset.Length);
return String.Format(".{0}/{1}", newPath, page);
}
}
catch(Exception)
{
throw;
}
}
public String GetShortTypeName(String typeName)
{
String[] parts = typeName.Split('.');
return parts[parts.Length - 1];
}
public int GetLevels(String path)
{
return path.Split('/').Length - 1;
}
public Stack CreateStack()
{
return new Stack();
}
public int Push(Stack stack)
{
stack.Push(String.Empty);
return stack.Count;
}
public int Pop(Stack stack)
{
stack.Pop();
return stack.Count;
}
}
}
| // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Anakia
{
using System;
using System.Collections;
using System.IO;
public class SimpleHelper
{
public String FileSizeInKBytes(String basePath, String file)
{
FileInfo info = new FileInfo(Path.Combine(basePath, file));
if (info.Exists)
{
return String.Format("{0:#.##}", info.Length / 1024f).ToString();
}
throw new Exception("File " + info.FullName + " was not found");
}
public String RemoveOffset(String offset, String path)
{
return path.Substring(offset.Length);
}
public String Relativize(String offset, String path, String page)
{
try
{
if (offset.Length >= path.Length)
{
return String.Format("./{0}", page);
}
else
{
String newPath = path.Substring(offset.Length);
return String.Format(".{0}/{1}", newPath, page);
}
}
catch(Exception)
{
throw;
}
}
public String GetShortTypeName(String typeName)
{
String[] parts = typeName.Split('.');
return parts[parts.Length - 1];
}
public int GetLevels(String path)
{
return path.Split('/').Length - 1;
}
public Stack CreateStack()
{
return new Stack();
}
public int Push(Stack stack)
{
stack.Push(String.Empty);
return stack.Count;
}
public int Pop(Stack stack)
{
stack.Pop();
return stack.Count;
}
}
}
| apache-2.0 | C# |
9b01f2488fe6c39644c1a8b5ca286a7c12b3568b | Make all remaining methods virtual | AsynkronIT/protoactor-dotnet | src/Proto.Actor/RootContextDecorator.cs | src/Proto.Actor/RootContextDecorator.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Proto
{
public abstract class RootContextDecorator : IRootContext
{
private readonly IRootContext _context;
protected RootContextDecorator(IRootContext context) => _context = context;
public virtual PID Spawn(Props props) => _context.Spawn(props);
public virtual PID SpawnNamed(Props props, string name) => _context.SpawnNamed(props, name);
public virtual PID SpawnPrefix(Props props, string prefix) => _context.SpawnPrefix(props, prefix);
public virtual void Send(PID target, object message) => _context.Send(target, message);
public virtual void Request(PID target, object message) => _context.Request(target, message);
public virtual void Request(PID target, object message, PID? sender) =>
_context.Request(target, message, sender);
public virtual Task<T> RequestAsync<T>(PID target, object message, TimeSpan timeout) =>
_context.RequestAsync<T>(target, message, timeout);
public virtual Task<T> RequestAsync<T>(PID target, object message, CancellationToken cancellationToken) =>
_context.RequestAsync<T>(target, message, cancellationToken);
public virtual Task<T> RequestAsync<T>(PID target, object message) => _context.RequestAsync<T>(target, message);
public virtual MessageHeader Headers => _context.Headers;
public virtual object? Message => _context.Message;
public virtual void Stop(PID pid) => _context.Stop(pid);
public virtual Task StopAsync(PID pid) => _context.StopAsync(pid);
public virtual void Poison(PID pid) => _context.Poison(pid);
public virtual Task PoisonAsync(PID pid) => _context.PoisonAsync(pid);
public virtual PID? Parent => null;
public virtual PID? Self => null;
public virtual PID? Sender => null;
public virtual IActor? Actor => null;
public virtual ActorSystem System => ActorSystem.Default;
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Proto
{
public abstract class RootContextDecorator : IRootContext
{
private readonly IRootContext _context;
protected RootContextDecorator(IRootContext context) => _context = context;
public virtual PID Spawn(Props props) => _context.Spawn(props);
public virtual PID SpawnNamed(Props props, string name) => _context.SpawnNamed(props, name);
public virtual PID SpawnPrefix(Props props, string prefix) => _context.SpawnPrefix(props, prefix);
public virtual void Send(PID target, object message) => _context.Send(target, message);
public virtual void Request(PID target, object message) => _context.Request(target, message);
public virtual void Request(PID target, object message, PID? sender) =>
_context.Request(target, message, sender);
public virtual Task<T> RequestAsync<T>(PID target, object message, TimeSpan timeout) =>
_context.RequestAsync<T>(target, message, timeout);
public virtual Task<T> RequestAsync<T>(PID target, object message, CancellationToken cancellationToken) =>
_context.RequestAsync<T>(target, message, cancellationToken);
public virtual Task<T> RequestAsync<T>(PID target, object message) => _context.RequestAsync<T>(target, message);
public virtual MessageHeader Headers => _context.Headers;
public virtual object? Message => _context.Message;
public void Stop(PID pid) => _context.Stop(pid);
public Task StopAsync(PID pid) => _context.StopAsync(pid);
public void Poison(PID pid) => _context.Poison(pid);
public Task PoisonAsync(PID pid) => _context.PoisonAsync(pid);
public virtual PID? Parent => null;
public virtual PID? Self => null;
public virtual PID? Sender => null;
public virtual IActor? Actor => null;
public virtual ActorSystem System => ActorSystem.Default;
}
} | apache-2.0 | C# |
46ce5cabbcbb1346d48588972a1bb35dc9d43758 | Change MembershipIdentity so it is not an abstract class. bugid: 153 | rockfordlhotka/csla,BrettJaner/csla,MarimerLLC/csla,ronnymgm/csla-light,JasonBock/csla,MarimerLLC/csla,MarimerLLC/csla,ronnymgm/csla-light,jonnybee/csla,JasonBock/csla,jonnybee/csla,jonnybee/csla,rockfordlhotka/csla,JasonBock/csla,rockfordlhotka/csla,ronnymgm/csla-light,BrettJaner/csla,BrettJaner/csla | cslalightcs/Csla/Security/MembershipIdentity.partial.cs | cslalightcs/Csla/Security/MembershipIdentity.partial.cs | using System;
using System.Security.Principal;
using Csla.Serialization;
using System.Collections.Generic;
using Csla.Core.FieldManager;
using System.Runtime.Serialization;
using Csla.DataPortalClient;
using Csla.Silverlight;
using Csla.Core;
namespace Csla.Security
{
public partial class MembershipIdentity : ReadOnlyBase<MembershipIdentity>, IIdentity
{
public static void GetMembershipIdentity<T>(EventHandler<DataPortalResult<T>> completed, string userName, string password, bool isRunOnWebServer) where T : MembershipIdentity
{
DataPortal<T> dp = new DataPortal<T>();
dp.FetchCompleted += completed;
dp.BeginFetch(new Criteria(userName, password, typeof(T), isRunOnWebServer));
}
}
}
| using System;
using System.Security.Principal;
using Csla.Serialization;
using System.Collections.Generic;
using Csla.Core.FieldManager;
using System.Runtime.Serialization;
using Csla.DataPortalClient;
using Csla.Silverlight;
using Csla.Core;
namespace Csla.Security
{
public abstract partial class MembershipIdentity : ReadOnlyBase<MembershipIdentity>, IIdentity
{
public static void GetMembershipIdentity<T>(EventHandler<DataPortalResult<T>> completed, string userName, string password, bool isRunOnWebServer) where T : MembershipIdentity
{
DataPortal<T> dp = new DataPortal<T>();
dp.FetchCompleted += completed;
dp.BeginFetch(new Criteria(userName, password, typeof(T), isRunOnWebServer));
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.