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
c38508e9bf4d04bb7aa4af57313659d3738b8138
Set property store before creating the root collection to make the property store available for some internal file hiding logic
FubarDevelopment/WebDavServer,FubarDevelopment/WebDavServer,FubarDevelopment/WebDavServer
FubarDev.WebDavServer.FileSystem.DotNet/DotNetFileSystem.cs
FubarDev.WebDavServer.FileSystem.DotNet/DotNetFileSystem.cs
// <copyright file="DotNetFileSystem.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.IO; using System.Threading; using System.Threading.Tasks; using FubarDev.WebDavServer.Props.Store; using Microsoft.VisualStudio.Threading; namespace FubarDev.WebDavServer.FileSystem.DotNet { public class DotNetFileSystem : ILocalFileSystem { private readonly PathTraversalEngine _pathTraversalEngine; public DotNetFileSystem(DotNetFileSystemOptions options, string rootFolder, PathTraversalEngine pathTraversalEngine, IPropertyStoreFactory propertyStoreFactory = null) { RootDirectoryPath = rootFolder; _pathTraversalEngine = pathTraversalEngine; Options = options; PropertyStore = propertyStoreFactory?.Create(this); var rootDir = new DotNetDirectory(this, null, new DirectoryInfo(rootFolder), new Uri(string.Empty, UriKind.Relative)); Root = new AsyncLazy<ICollection>(() => Task.FromResult<ICollection>(rootDir)); } public string RootDirectoryPath { get; } public AsyncLazy<ICollection> Root { get; } public DotNetFileSystemOptions Options { get; } public IPropertyStore PropertyStore { get; } public Task<SelectionResult> SelectAsync(string path, CancellationToken ct) { return _pathTraversalEngine.TraverseAsync(this, path, ct); } } }
// <copyright file="DotNetFileSystem.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.IO; using System.Threading; using System.Threading.Tasks; using FubarDev.WebDavServer.Props.Store; using Microsoft.VisualStudio.Threading; namespace FubarDev.WebDavServer.FileSystem.DotNet { public class DotNetFileSystem : ILocalFileSystem { private readonly PathTraversalEngine _pathTraversalEngine; public DotNetFileSystem(DotNetFileSystemOptions options, string rootFolder, PathTraversalEngine pathTraversalEngine, IPropertyStoreFactory propertyStoreFactory = null) { RootDirectoryPath = rootFolder; _pathTraversalEngine = pathTraversalEngine; var rootDir = new DotNetDirectory(this, null, new DirectoryInfo(rootFolder), new Uri(string.Empty, UriKind.Relative)); Root = new AsyncLazy<ICollection>(() => Task.FromResult<ICollection>(rootDir)); Options = options; PropertyStore = propertyStoreFactory?.Create(this); } public string RootDirectoryPath { get; } public AsyncLazy<ICollection> Root { get; } public DotNetFileSystemOptions Options { get; } public IPropertyStore PropertyStore { get; } public Task<SelectionResult> SelectAsync(string path, CancellationToken ct) { return _pathTraversalEngine.TraverseAsync(this, path, ct); } } }
mit
C#
103b8bb475359053d8b3673c072813476206e27f
Add StreamId ToString overload
damianh/Cedar.EventStore,SQLStreamStore/SQLStreamStore,SQLStreamStore/SQLStreamStore
src/SqlStreamStore/Streams/StreamId.cs
src/SqlStreamStore/Streams/StreamId.cs
namespace SqlStreamStore.Streams { using System; using SqlStreamStore.Imports.Ensure.That; using SqlStreamStore.Infrastructure; /// <summary> /// Represents a valid Stream Id. Is implicitly convertable to/from a string. /// </summary> public sealed class StreamId : IEquatable<StreamId> { /// <summary> /// Initializes a new instance of the <see cref="StreamId"/> class. /// </summary> /// <param name="value">The value.</param> public StreamId(string value) { Ensure.That(value, nameof(value)) .IsNotNullOrWhiteSpace() .DoesNotContainWhitespace(); Value = value; } /// <summary> /// Gets the value. /// </summary> public string Value { get; } /// <summary> /// Returns a string representation of the current StreamId value. /// /// </summary> /// /// <returns> /// String representation of the StreamId value. /// </returns> public override string ToString() { return Value; } /// <summary> /// Performs an implicit conversion from <see cref="StreamId"/> to <see cref="System.String"/>. /// </summary> /// <param name="streamId">The stream identifier.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator string(StreamId streamId) => streamId?.Value; /// <summary> /// Performs an implicit conversion from <see cref="System.String"/> to <see cref="StreamId"/>. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator StreamId(string value) => new StreamId(value); /// <inheritdoc /> public bool Equals(StreamId other) => !ReferenceEquals(null, other) && (ReferenceEquals(this, other) || string.Equals(Value, other.Value)); /// <inheritdoc /> public override bool Equals(object obj) => !ReferenceEquals(null, obj) && (ReferenceEquals(this, obj) || obj is StreamId && Equals((StreamId)obj)); /// <inheritdoc /> public override int GetHashCode() => Value.GetHashCode(); public static bool operator ==(StreamId left, StreamId right) => Equals(left, right); public static bool operator !=(StreamId left, StreamId right) => !Equals(left, right); } }
namespace SqlStreamStore.Streams { using System; using SqlStreamStore.Imports.Ensure.That; using SqlStreamStore.Infrastructure; /// <summary> /// Represents a valid Stream Id. Is implicitly convertable to/from a string. /// </summary> public sealed class StreamId : IEquatable<StreamId> { /// <summary> /// Initializes a new instance of the <see cref="StreamId"/> class. /// </summary> /// <param name="value">The value.</param> public StreamId(string value) { Ensure.That(value, nameof(value)) .IsNotNullOrWhiteSpace() .DoesNotContainWhitespace(); Value = value; } /// <summary> /// Gets the value. /// </summary> public string Value { get; } /// <summary> /// Performs an implicit conversion from <see cref="StreamId"/> to <see cref="System.String"/>. /// </summary> /// <param name="streamId">The stream identifier.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator string(StreamId streamId) => streamId?.Value; /// <summary> /// Performs an implicit conversion from <see cref="System.String"/> to <see cref="StreamId"/>. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator StreamId(string value) => new StreamId(value); /// <inheritdoc /> public bool Equals(StreamId other) => !ReferenceEquals(null, other) && (ReferenceEquals(this, other) || string.Equals(Value, other.Value)); /// <inheritdoc /> public override bool Equals(object obj) => !ReferenceEquals(null, obj) && (ReferenceEquals(this, obj) || obj is StreamId && Equals((StreamId)obj)); /// <inheritdoc /> public override int GetHashCode() => Value.GetHashCode(); public static bool operator ==(StreamId left, StreamId right) => Equals(left, right); public static bool operator !=(StreamId left, StreamId right) => !Equals(left, right); } }
mit
C#
34bd25abe6eb3995469ceee045d258bf54812395
fix compiler warning
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
unity/library/UtyMap.Unity/Explorer/Customization/CustomizationService.cs
unity/library/UtyMap.Unity/Explorer/Customization/CustomizationService.cs
using System.Collections.Generic; using UnityEngine; namespace UtyMap.Unity.Explorer.Customization { /// <summary> Maintains list of customization properties. </summary> public sealed class CustomizationService { private readonly Dictionary<string, Material> _sharedMaterials; /// <summary> Creates instance of <see cref="CustomizationService"/>. </summary> public CustomizationService() { _sharedMaterials = new Dictionary<string, Material>(); } #region Materials /// <summary> Gets shared material by key. </summary> /// <remarks> Should be called from UI thread only. </remarks> public Material GetSharedMaterial(string key) { if (!_sharedMaterials.ContainsKey(key)) _sharedMaterials[key] = Resources.Load<Material>(key); return _sharedMaterials[key]; } #endregion } }
using System; using System.Collections.Generic; using UnityEngine; namespace UtyMap.Unity.Explorer.Customization { /// <summary> Maintains list of customization properties. </summary> public sealed class CustomizationService { private readonly Dictionary<string, Type> _modelBehaviours; private readonly Dictionary<string, Material> _sharedMaterials; /// <summary> Creates instance of <see cref="CustomizationService"/>. </summary> public CustomizationService() { _sharedMaterials = new Dictionary<string, Material>(); } #region Materials /// <summary> Gets shared material by key. </summary> /// <remarks> Should be called from UI thread only. </remarks> public Material GetSharedMaterial(string key) { if (!_sharedMaterials.ContainsKey(key)) _sharedMaterials[key] = Resources.Load<Material>(key); return _sharedMaterials[key]; } #endregion } }
apache-2.0
C#
9af939b1416e56b931aaf542885aa2d064a6bf3d
Add attribute for checking if password and conformation password match
ahmedmatem/primus-flex,ahmedmatem/primus-flex,ahmedmatem/primus-flex
PrimusFlex.Web/Areas/Admin/ViewModels/Employees/CreateEmployeeViewModel.cs
PrimusFlex.Web/Areas/Admin/ViewModels/Employees/CreateEmployeeViewModel.cs
namespace PrimusFlex.Web.Areas.Admin.ViewModels.Employees { using System.ComponentModel.DataAnnotations; using Infrastructure.Mapping; using Data.Models.Types; using Data.Models; public class CreateEmployeeViewModel : IMapFrom<Employee>, IMapTo<Employee> { [Required] [StringLength(60, MinimumLength = 3)] public string Name { get; set; } [Required] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string PhoneNumber { get; set; } // Bank details [Required] public BankName BankName { get; set; } [Required] public string SortCode { get; set; } [Required] public string Account { get; set; } } }
namespace PrimusFlex.Web.Areas.Admin.ViewModels.Employees { using System.ComponentModel.DataAnnotations; using Infrastructure.Mapping; using Data.Models.Types; using Data.Models; public class CreateEmployeeViewModel : IMapFrom<Employee>, IMapTo<Employee> { [Required] [StringLength(60, MinimumLength = 3)] public string Name { get; set; } [Required] public string Email { get; set; } [Required] public string Password { get; set; } [Required] public string ConfirmPassword { get; set; } public string PhoneNumber { get; set; } // Bank details [Required] public BankName BankName { get; set; } [Required] public string SortCode { get; set; } [Required] public string Account { get; set; } } }
mit
C#
86eeaef12e98de24f3595263b00678e424556a55
Bump version to 0.10
github-for-unity/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity,mpOzelot/Unity
common/SolutionInfo.cs
common/SolutionInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.10.0.0"; } }
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.9.1.0"; } }
mit
C#
b2e56530d030b89af781084e2d95546edcc831ff
implement getSG on GameManager.cs for other object can get game's status
GROWrepo/Santa_Inc
Assets/script/monoBehavior/GameManager.cs
Assets/script/monoBehavior/GameManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { STATUS_GAME SG; dialog current; // Use this for initialization void Start () { SG = STATUS_GAME.MENU; current = null; } // Update is called once per frame void Update () { } private void OnGUI() { if(this.SG == STATUS_GAME.DIALOGING) { if (this.current == null) this.SG = STATUS_GAME.PAUSE; else { } } } private void setCurrent(dialog dialogs) { this.current = dialogs; } public STATUS_GAME getSG() { return this.SG; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { STATUS_GAME SG; dialog current; // Use this for initialization void Start () { SG = STATUS_GAME.MENU; current = null; } // Update is called once per frame void Update () { } private void OnGUI() { if(this.SG == STATUS_GAME.DIALOGING) { if (this.current == null) this.SG = STATUS_GAME.PAUSE; else { } } } private void setCurrent(dialog dialogs) { this.current = dialogs; } }
mit
C#
d6a7ebaa2bee82395e8b2e5bd4246cce5b1a48e7
Bump version to 0.13.3
quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot
CactbotOverlay/Properties/AssemblyInfo.cs
CactbotOverlay/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.13.3.0")] [assembly: AssemblyFileVersion("0.13.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.13.2.0")] [assembly: AssemblyFileVersion("0.13.2.0")]
apache-2.0
C#
f2c6bc3a5d7e715e7c69bacacb662ff1412f213c
同步版本号,Senparc.Weixin SDK 全面支持 .NET Core 2.1.0-rc1-final
JeffreySu/WxOpen,JeffreySu/WxOpen
src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Properties/AssemblyInfo.cs
src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Senparc.Weixin.WxOpen")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Senparc.Weixin.WxOpen")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("379d8c97-4f96-45af-9f91-6bd160514495")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.10.0.*")] //[assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Senparc.Weixin.WxOpen")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Senparc.Weixin.WxOpen")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("379d8c97-4f96-45af-9f91-6bd160514495")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.9.2.*")] //[assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
0bd8f06467db1bffbd379a630b5558c1af98c60d
Fix Typo
topgenorth/gplus-quickstart-xamarin.android
gplus-quickstart-xamarin/MainActivity.cs
gplus-quickstart-xamarin/MainActivity.cs
using Android.App; using Android.Content; using Android.OS; using Android.Util; using Android.Views; using Android.Widget; namespace com.xamarin.googleplus.quickstart { [Activity(Label = "@string/app_name", MainLauncher = true, Icon = "@drawable/ic_launcher")] public class MainActivity : ListActivity { static readonly string TAG = typeof(MainActivity).FullName; static readonly string[] _examples = { "Google+ Sign In Button 1", "Account Picker" }; ArrayAdapter<string> _menuAdapter; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); if (this.IsGooglePlayServicesInstalled()) { Log.Debug(TAG, "Google Play Services are installed."); _menuAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, _examples); } else { Toast.MakeText(this, "Google Play Services is not available on this device. Please install and restart.", ToastLength.Short).Show(); _menuAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, new string[0]); } ListAdapter = _menuAdapter; } protected override void OnListItemClick(ListView l, View v, int position, long id) { base.OnListItemClick(l, v, position, id); switch (position) { case 0: StartActivity(new Intent(this, typeof(SignInButtonExample))); break; case 1: StartActivity(new Intent(this, typeof(AccountPickerExample))); break; default: Toast.MakeText(this, "Don't know how to handle item " + position, ToastLength.Short).Show(); break; } } } }
using Android.App; using Android.Content; using Android.OS; using Android.Util; using Android.Views; using Android.Widget; namespace com.xamarin.googleplus.quickstart { [Activity(Label = "@string/app_name", MainLauncher = true, Icon = "@drawable/ic_launcher")] public class MainActivity : ListActivity { static readonly string TAG = typeof(MainActivity).FullName; static readonly string[] _examples = { "Google+ Sign In Button 1", "Account Picker" }; ArrayAdapter<string> _menuAdapter; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); if (this.IsGooglePlayServicesInstalled()) { Log.Debug(TAG, "Google Play Services are installed."); _menuAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, _examples); } else { Toast.MakeText(this, "Google Play Services is not available on this device. Please install and restart", ToastLength.Short).Show(); _menuAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, new string[0]); } ListAdapter = _menuAdapter; } protected override void OnListItemClick(ListView l, View v, int position, long id) { base.OnListItemClick(l, v, position, id); switch (position) { case 0: StartActivity(new Intent(this, typeof(SignInButtonExample))); break; case 1: StartActivity(new Intent(this, typeof(AccountPickerExample))); break; default: Toast.MakeText(this, "Don't know how to handle item " + position, ToastLength.Short).Show(); break; } } } }
apache-2.0
C#
db4863f4949b0be14d5ce5f1b4104646d2bbbf28
Fix build. Woops.
mvpete/aspekt
Aspekt.Target/Program.cs
Aspekt.Target/Program.cs
using Aspekt.Logging; using System; namespace Aspekt.Target { class Program { [Log] void Foo() { LogAttribute la = new LogAttribute(); } static void Main(string[] args) { while (true) { Application.Test("Object", typeof(Program), 15, Application.Choice.No); var k = Console.ReadKey(); if (k.Key == ConsoleKey.Q) break; } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }
using Aspekt.Logging; using System; namespace Aspekt.Target { class Program { [Log] void Foo() { LogAttribute la = new LogAttribute(); la.OnEntryLevel = Levels.Debug; } static void Main(string[] args) { while (true) { Application.Test("Object", typeof(Program), 15, Application.Choice.No); var k = Console.ReadKey(); if (k.Key == ConsoleKey.Q) break; } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }
mit
C#
a5105af8e2b1b82d74308f0330e73362b33ac63e
Fix up bad test.
gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT
LINQToTTree/LINQToTTreeLib.Tests/Statements/StatementRecordPairValuesTest.cs
LINQToTTree/LINQToTTreeLib.Tests/Statements/StatementRecordPairValuesTest.cs
using System.Linq; using System.Text.RegularExpressions; using LinqToTTreeInterfacesLib; using LINQToTTreeLib.Statements; using LINQToTTreeLib.Utils; using Microsoft.Pex.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LINQToTTreeLib.Tests { /// <summary> ///This is a test class for StatementRecordPairValuesTest and is intended ///to contain all StatementRecordPairValuesTest Unit Tests ///</summary> [TestClass] [PexClass(typeof(StatementRecordPairValues))] public partial class StatementRecordPairValuesTest { [TestInitialize] public void initTest() { TypeUtils._variableNameCounter = 0; } /// <summary> ///A test for CodeItUp ///</summary> [PexMethod] public string CodeItUpTest([PexAssumeUnderTest] StatementRecordPairValues target) { var actual = target.CodeItUp().ToArray(); Assert.AreEqual(1, actual.Length, "only xpected one line"); return actual[0]; } /// <summary> ///A test for RenameVariable ///</summary> [PexMethod] public StatementRecordPairValues RenameVariableTest([PexAssumeUnderTest] StatementRecordPairValues target, string origin, string final) { target.RenameVariable(origin, final); var finder = new Regex(string.Format("\b{0}\b", origin)); var hasit = target.CodeItUp().Where(s => finder.IsMatch(s)).Any(); Assert.IsFalse(hasit, "found some code that contained the original guy"); return target; } [PexMethod] public static void TestTryCombine([PexAssumeUnderTest] StatementRecordPairValues target, IStatement statement) { var canComb = target.TryCombineStatement(statement, null); Assert.IsNotNull(statement, "Second statement null should cause a failure"); var allSame = target.CodeItUp().Zip(statement.CodeItUp(), (f, s) => f == s).All(t => t); Assert.AreEqual(allSame, canComb, "not expected combination!"); } } }
using System.Linq; using System.Text.RegularExpressions; using LinqToTTreeInterfacesLib; using LINQToTTreeLib.Statements; using LINQToTTreeLib.Utils; using Microsoft.Pex.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LINQToTTreeLib.Tests { /// <summary> ///This is a test class for StatementRecordPairValuesTest and is intended ///to contain all StatementRecordPairValuesTest Unit Tests ///</summary> [TestClass] [PexClass(typeof(StatementRecordPairValues))] public partial class StatementRecordPairValuesTest { [TestInitialize] public void initTest() { TypeUtils._variableNameCounter = 0; } /// <summary> ///A test for CodeItUp ///</summary> [PexMethod] public string CodeItUpTest([PexAssumeUnderTest] StatementRecordPairValues target) { var actual = target.CodeItUp().ToArray(); Assert.AreEqual(1, actual.Length, "only xpected one line"); return actual[0]; } /// <summary> ///A test for RenameVariable ///</summary> [PexMethod] public StatementRecordPairValues RenameVariableTest([PexAssumeUnderTest] StatementRecordPairValues target, string origin, string final) { target.RenameVariable(origin, final); var finder = new Regex(string.Format("\b{0}\b", origin)); var hasit = target.CodeItUp().Where(s => finder.IsMatch(s)).Any(); Assert.IsFalse(hasit, "found some code that contained the original guy"); return target; } [PexMethod] public static void TestTryCombine([PexAssumeUnderTest] StatementRecordPairValues target, IStatement statement) { var canComb = target.TryCombineStatement(statement, null); Assert.IsNotNull(statement, "Second statement null should cause a failure"); var allSame = target.CodeItUp().Zip(statement.CodeItUp(), (f, s) => f == s).All(t => t); Assert.AreEqual(allSame, canComb, "not expected combination!"); } [TestMethod] public static void TestMultipleValuesSame() { // Make sure we can deal with when more then one item has the same value. Assert.Inconclusive("ops"); } } }
lgpl-2.1
C#
625eb78a118566dc72161da36c9b5997d10309e4
Simplify with an early exit for null sample
UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,UselessToucan/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.Bindables; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Game.Configuration; using osu.Framework.Utils; 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. /// </summary> public double HoverDebounceTime { get; } = 20; protected readonly HoverSampleSet SampleSet; private Bindable<double?> lastPlaybackTime; public HoverSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal) { SampleSet = sampleSet; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(AudioManager audio, SessionStatics statics) { lastPlaybackTime = statics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime); sampleHover = audio.Samples.Get($@"UI/generic-hover{SampleSet.GetDescription()}"); } protected override bool OnHover(HoverEvent e) { if (sampleHover == null) return false; bool enoughTimePassedSinceLastPlayback = !lastPlaybackTime.Value.HasValue || Time.Current - lastPlaybackTime.Value >= HoverDebounceTime; if (enoughTimePassedSinceLastPlayback) { sampleHover.Frequency.Value = 0.96 + RNG.NextDouble(0.08); sampleHover.Play(); lastPlaybackTime.Value = Time.Current; } return false; } } 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.Bindables; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Game.Configuration; using osu.Framework.Utils; 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. /// </summary> public double HoverDebounceTime { get; } = 20; protected readonly HoverSampleSet SampleSet; private Bindable<double?> lastPlaybackTime; public HoverSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal) { SampleSet = sampleSet; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(AudioManager audio, SessionStatics statics) { lastPlaybackTime = statics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime); sampleHover = audio.Samples.Get($@"UI/generic-hover{SampleSet.GetDescription()}"); } protected override bool OnHover(HoverEvent e) { bool enoughTimePassedSinceLastPlayback = !lastPlaybackTime.Value.HasValue || Time.Current - lastPlaybackTime.Value >= HoverDebounceTime; if (enoughTimePassedSinceLastPlayback && sampleHover != null) { sampleHover.Frequency.Value = 0.96 + RNG.NextDouble(0.08); sampleHover.Play(); lastPlaybackTime.Value = Time.Current; } return base.OnHover(e); } } public enum HoverSampleSet { [Description("")] Loud, [Description("-soft")] Normal, [Description("-softer")] Soft } }
mit
C#
c964f3c36fd3c75bad4302959ecc748f6394cda4
Add new property on HstsPreload
LordMike/SslLabsLib
Library/SslLabsLib/Objects/HstsPreload.cs
Library/SslLabsLib/Objects/HstsPreload.cs
using System; using Newtonsoft.Json; using SslLabsLib.Code; using SslLabsLib.Enums; namespace SslLabsLib.Objects { public class HstsPreload { /// <summary> /// Source name /// </summary> [JsonProperty("source")] public string Source { get; set; } /// <summary> /// Preload status /// </summary> [JsonProperty("status")] public HstsPreloadStatus Status { get; set; } /// <summary> /// Error message, when status is "error" /// </summary> [JsonProperty("error")] public string Error { get; set; } /// <summary> /// Hostname of this preload /// </summary> [JsonProperty("hostname")] public string Hostname { get; set; } /// <summary> /// Time, as a Unix timestamp, when the preload database was retrieved /// </summary> [JsonProperty("sourceTime")] [JsonConverter(typeof(MillisecondEpochConverter))] public DateTime SourceTime { get; set; } } }
using System; using Newtonsoft.Json; using SslLabsLib.Code; using SslLabsLib.Enums; namespace SslLabsLib.Objects { public class HstsPreload { /// <summary> /// Source name /// </summary> [JsonProperty("source")] public string Source { get; set; } /// <summary> /// Preload status /// </summary> [JsonProperty("status")] public HstsPreloadStatus Status { get; set; } /// <summary> /// Error message, when status is "error" /// </summary> [JsonProperty("error")] public string Error { get; set; } /// <summary> /// Time, as a Unix timestamp, when the preload database was retrieved /// </summary> [JsonProperty("sourceTime")] [JsonConverter(typeof(MillisecondEpochConverter))] public DateTime SourceTime { get; set; } } }
mit
C#
f270e5c78f18c843041aeaf0223245c7867bb267
Bump version.
JohanLarsson/Gu.Roslyn.Asserts
Gu.Roslyn.Asserts/Properties/AssemblyInfo.cs
Gu.Roslyn.Asserts/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Gu.Roslyn.Asserts.Properties")] [assembly: AssemblyDescription("Asserts for testing Roslyn analyzers and code fixes.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Johan Larsson")] [assembly: AssemblyProduct("Gu.Roslyn.Asserts.Properties")] [assembly: AssemblyCopyright("Copyright © Johan Larsson 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("f407a423-47a0-4b6e-8287-6d045cf4d8fb")] [assembly: AssemblyVersion("0.1.1.0")] [assembly: AssemblyFileVersion("0.1.1.0")] [assembly: AssemblyInformationalVersion("0.1.1.0-dev")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Gu.Roslyn.Asserts.Properties")] [assembly: AssemblyDescription("Asserts for testing Roslyn analyzers and code fixes.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Johan Larsson")] [assembly: AssemblyProduct("Gu.Roslyn.Asserts.Properties")] [assembly: AssemblyCopyright("Copyright © Johan Larsson 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("f407a423-47a0-4b6e-8287-6d045cf4d8fb")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0.0-dev")]
mit
C#
6911376088b15d6fe24a1b3b0c4facb4113f63e0
Fix array index.
sharpjs/PSql,sharpjs/PSql
PSql.Core/_Utilities/SqlCommandExtensions.cs
PSql.Core/_Utilities/SqlCommandExtensions.cs
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Management.Automation; using static System.FormattableString; namespace PSql { internal static class SqlCommandExtensions { public static IEnumerable<PSObject> ExecuteAndProjectToPSObjects(this SqlCommand command) { if (command is null) throw new ArgumentNullException(nameof(command)); if (command.Connection.State == ConnectionState.Closed) command.Connection.Open(); using (var reader = command.ExecuteReader()) { var names = null as string[]; // Advance to next row in any result set while (!reader.Read()) { if (!reader.NextResult()) yield break; names = null; } // If this is the first row in its result set, get the column names if (names == null) names = GetColumnNames(reader); // Return the row as a PowerShell object yield return Project(reader, names); } } private static string[] GetColumnNames(SqlDataReader reader) { var names = new string[reader.FieldCount]; for (var i = 0; i < names.Length; i++) names[i] = reader.GetName(i) ?? Invariant($"Col{i}"); return names; } private static PSObject Project(SqlDataReader reader, string[] names) { var obj = new PSObject(); for (var i = 0; i < names.Length; i++) { obj.Properties.Add(new PSNoteProperty( name: names[i], value: reader.IsDBNull(i) ? null : reader.GetValue(i) )); } return obj; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Management.Automation; using static System.FormattableString; namespace PSql { internal static class SqlCommandExtensions { public static IEnumerable<PSObject> ExecuteAndProjectToPSObjects(this SqlCommand command) { if (command is null) throw new ArgumentNullException(nameof(command)); if (command.Connection.State == ConnectionState.Closed) command.Connection.Open(); using (var reader = command.ExecuteReader()) { var names = null as string[]; // Advance to next row in any result set while (!reader.Read()) { if (!reader.NextResult()) yield break; names = null; } // If this is the first row in its result set, get the column names if (names == null) names = GetColumnNames(reader); // Return the row as a PowerShell object yield return Project(reader, names); } } private static string[] GetColumnNames(SqlDataReader reader) { var names = new string[reader.FieldCount]; for (var i = 0; i < names.Length; i++) names[0] = reader.GetName(i) ?? Invariant($"Col{i}"); return names; } private static PSObject Project(SqlDataReader reader, string[] names) { var obj = new PSObject(); for (var i = 0; i < names.Length; i++) { obj.Properties.Add(new PSNoteProperty( name: names[i], value: reader.IsDBNull(i) ? null : reader.GetValue(i) )); } return obj; } } }
isc
C#
605f26be8343a326fc4b3a78cc21d39ba884217d
Remove unused code
ektrah/nsec
src/Cryptography/Sha256.cs
src/Cryptography/Sha256.cs
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using static Interop.Libsodium; namespace NSec.Cryptography { // // SHA-256 // // FIPS Secure Hash Algorithm (SHA) with a 256-bit message digest // // References: // // RFC 6234 - US Secure Hash Algorithms (SHA and SHA-based HMAC and // HKDF) // // Parameters: // // Input Size - Between 0 and 2^61-1 bytes. Since a Span<byte> can // hold between 0 to 2^31-1 bytes, we do not check the length of // inputs. // // Hash Size - 32 bytes (128 bits of security). // public sealed class Sha256 : HashAlgorithm { private static readonly Lazy<bool> s_selfTest = new Lazy<bool>(new Func<bool>(SelfTest)); public Sha256() : base( minHashSize: crypto_hash_sha256_BYTES, defaultHashSize: crypto_hash_sha256_BYTES, maxHashSize: crypto_hash_sha256_BYTES) { if (!s_selfTest.Value) throw new InvalidOperationException(); } internal override void HashCore( ReadOnlySpan<byte> data, Span<byte> hash) { Debug.Assert(hash.Length == crypto_hash_sha256_BYTES); crypto_hash_sha256_init(out crypto_hash_sha256_state state); crypto_hash_sha256_update(ref state, ref data.DangerousGetPinnableReference(), (ulong)data.Length); crypto_hash_sha256_final(ref state, ref hash.DangerousGetPinnableReference()); } private static bool SelfTest() { return (crypto_hash_sha256_bytes() == (IntPtr)crypto_hash_sha256_BYTES) && (crypto_hash_sha256_statebytes() == (IntPtr)Unsafe.SizeOf<crypto_hash_sha256_state>()); } } }
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using static Interop.Libsodium; namespace NSec.Cryptography { // // SHA-256 // // FIPS Secure Hash Algorithm (SHA) with a 256-bit message digest // // References: // // RFC 6234 - US Secure Hash Algorithms (SHA and SHA-based HMAC and // HKDF) // // Parameters: // // Input Size - Between 0 and 2^61-1 bytes. Since a Span<byte> can // hold between 0 to 2^31-1 bytes, we do not check the length of // inputs. // // Hash Size - 32 bytes (128 bits of security). // public sealed class Sha256 : HashAlgorithm { private static readonly Lazy<bool> s_selfTest = new Lazy<bool>(new Func<bool>(SelfTest)); public Sha256() : base( minHashSize: crypto_hash_sha256_BYTES, defaultHashSize: crypto_hash_sha256_BYTES, maxHashSize: crypto_hash_sha256_BYTES) { if (!s_selfTest.Value) throw new InvalidOperationException(); } internal override void HashCore( ReadOnlySpan<byte> data, Span<byte> hash) { Debug.Assert(hash.Length == crypto_hash_sha256_BYTES); crypto_hash_sha256_init(out crypto_hash_sha256_state state); if (!data.IsEmpty) { crypto_hash_sha256_update(ref state, ref data.DangerousGetPinnableReference(), (ulong)data.Length); } // crypto_hash_sha256_final expects an output buffer with a // size of exactly crypto_hash_sha256_BYTES, so we need to // copy when truncating the output. if (hash.Length == crypto_hash_sha256_BYTES) { crypto_hash_sha256_final(ref state, ref hash.DangerousGetPinnableReference()); } else { byte[] result = new byte[crypto_hash_sha256_BYTES]; // TODO: avoid placing sensitive data in managed memory crypto_hash_sha256_final(ref state, result); new ReadOnlySpan<byte>(result, 0, hash.Length).CopyTo(hash); } } private static bool SelfTest() { return (crypto_hash_sha256_bytes() == (IntPtr)crypto_hash_sha256_BYTES) && (crypto_hash_sha256_statebytes() == (IntPtr)Unsafe.SizeOf<crypto_hash_sha256_state>()); } } }
mit
C#
1e6d1bffcdc0d63966a26bf05aaa48436a861d07
Make Compose a non-extension method
sharper-library/Sharper.C.Function
Sharper.C.Function/Data/FunctionModule.cs
Sharper.C.Function/Data/FunctionModule.cs
using System; namespace Sharper.C.Data { using static UnitModule; public static class FunctionModule { public static Func<A, B> Fun<A, B>(Func<A, B> f) => f; public static Func<A, Unit> Fun<A>(Action<A> f) => ToFunc(f); public static Action<A> Act<A>(Action<A> f) => f; public static A Id<A>(A a) => a; public static Func<B, A> Const<A, B>(A a) => b => a; public static Func<B, A, C> Flip<A, B, C>(Func<A, B, C> f) => (b, a) => f(a, b); public static Func<A, C> Compose<A, B, C>(Func<B, C> f, Func<A, B> g) => a => f(g(a)); public static Func<A, C> Then<A, B, C>(this Func<A, B> f, Func<B, C> g) => a => g(f(a)); public static Func<A, Func<B, C>> Curry<A, B, C>(Func<A, B, C> f) => a => b => f(a, b); public static Func<A, B, C> Uncurry<A, B, C>(Func<A, Func<B, C>> f) => (a, b) => f(a)(b); } }
using System; namespace Sharper.C.Data { using static UnitModule; public static class FunctionModule { public static Func<A, B> Fun<A, B>(Func<A, B> f) => f; public static Func<A, Unit> Fun<A>(Action<A> f) => ToFunc(f); public static Action<A> Act<A>(Action<A> f) => f; public static A Id<A>(A a) => a; public static Func<B, A> Const<A, B>(A a) => b => a; public static Func<B, A, C> Flip<A, B, C>(Func<A, B, C> f) => (b, a) => f(a, b); public static Func<A, C> Compose<A, B, C>(this Func<B, C> f, Func<A, B> g) => a => f(g(a)); public static Func<A, C> Then<A, B, C>(this Func<A, B> f, Func<B, C> g) => a => g(f(a)); public static Func<A, Func<B, C>> Curry<A, B, C>(Func<A, B, C> f) => a => b => f(a, b); public static Func<A, B, C> Uncurry<A, B, C>(Func<A, Func<B, C>> f) => (a, b) => f(a)(b); } }
mit
C#
ccb4ca4415be17ef14759df45823c6c2672d3ce7
Make non-nullable parameters nullable
SICU-Stress-Measurement-System/frontend-cs
StressMeasurementSystem/Models/Patient.cs
StressMeasurementSystem/Models/Patient.cs
using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private uint? _age; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name? name, uint? age, Organization? organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _age = age; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } }
using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private uint? _age; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name name, uint age, Organization organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _age = age; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } }
apache-2.0
C#
1eb2c74e57c3d18dfcac974bf7c52101a18806ec
Fix countdown serialisation
peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu
osu.Game/Online/Multiplayer/MultiplayerCountdown.cs
osu.Game/Online/Multiplayer/MultiplayerCountdown.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 MessagePack; using osu.Game.Online.Multiplayer.Countdown; namespace osu.Game.Online.Multiplayer { /// <summary> /// Describes the current countdown in a <see cref="MultiplayerRoom"/>. /// </summary> [MessagePackObject] [Union(0, typeof(MatchStartCountdown))] // IMPORTANT: Add rules to SignalRUnionWorkaroundResolver for new derived types. [Union(1, typeof(ForceGameplayStartCountdown))] public abstract class MultiplayerCountdown { /// <summary> /// A unique identifier for this countdown. /// </summary> [Key(0)] public int ID { get; set; } /// <summary> /// The amount of time remaining in the countdown. /// </summary> /// <remarks> /// This is only sent once from the server upon initial retrieval of the <see cref="MultiplayerRoom"/> or via a <see cref="CountdownStartedEvent"/>. /// </remarks> [Key(1)] public TimeSpan TimeRemaining { get; set; } /// <summary> /// Whether only a single instance of this <see cref="MultiplayerCountdown"/> type may be active at any one time. /// </summary> [IgnoreMember] public virtual bool IsExclusive => true; } }
// 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 MessagePack; using osu.Game.Online.Multiplayer.Countdown; namespace osu.Game.Online.Multiplayer { /// <summary> /// Describes the current countdown in a <see cref="MultiplayerRoom"/>. /// </summary> [MessagePackObject] [Union(0, typeof(MatchStartCountdown))] // IMPORTANT: Add rules to SignalRUnionWorkaroundResolver for new derived types. [Union(1, typeof(ForceGameplayStartCountdown))] public abstract class MultiplayerCountdown { /// <summary> /// A unique identifier for this countdown. /// </summary> [Key(0)] public int ID { get; set; } /// <summary> /// The amount of time remaining in the countdown. /// </summary> /// <remarks> /// This is only sent once from the server upon initial retrieval of the <see cref="MultiplayerRoom"/> or via a <see cref="CountdownStartedEvent"/>. /// </remarks> [Key(1)] public TimeSpan TimeRemaining { get; set; } /// <summary> /// Whether only a single instance of this <see cref="MultiplayerCountdown"/> type may be active at any one time. /// </summary> public virtual bool IsExclusive => true; } }
mit
C#
8f5da87f915564c84fe8c068e67bb913c25c25b8
Change Say nodes to use ToString
exodrifter/unity-rumor
Nodes/Say.cs
Nodes/Say.cs
using Exodrifter.Rumor.Engine; using Exodrifter.Rumor.Expressions; using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Exodrifter.Rumor.Nodes { /// <summary> /// Sets the dialog in the rumor state. /// </summary> [Serializable] public sealed class Say : Node, ISerializable { /// <summary> /// The text to replace the dialog with. /// </summary> private readonly Expression text; /// <summary> /// Creates a new Say node. /// </summary> /// <param name="text"> /// The text to replace the dialog with. /// </param> public Say(string text) { this.text = new LiteralExpression(text); } /// <summary> /// Creates a new Say node. /// </summary> /// <param name="text"> /// The expression to replace the dialog with. /// </param> public Say(Expression text) { this.text = text; } /// <summary> /// Evaluates the text of this node in the specified Rumor. /// </summary> /// <param name="rumor">The Rumor to evaluate against.</param> /// <returns>The text.</returns> public string EvaluateText(Engine.Rumor rumor) { return text.Evaluate(rumor.Scope).ToString(); } /// <summary> /// Evaluates the text of this node in the specified Scope. /// </summary> /// <param name="rumor">The Scope to evaluate against.</param> /// <returns>The text.</returns> public string EvaluateText(Scope scope) { return text.Evaluate(scope).ToString(); } public override IEnumerator<RumorYield> Run(Engine.Rumor rumor) { rumor.State.SetDialog(EvaluateText(rumor.Scope)); yield return new ForAdvance(); } #region Serialization public Say(SerializationInfo info, StreamingContext context) { text = (Expression)info.GetValue("text", typeof(Expression)); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("text", text, typeof(Expression)); } #endregion } }
using Exodrifter.Rumor.Engine; using Exodrifter.Rumor.Expressions; using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Exodrifter.Rumor.Nodes { /// <summary> /// Sets the dialog in the rumor state. /// </summary> [Serializable] public sealed class Say : Node, ISerializable { /// <summary> /// The text to replace the dialog with. /// </summary> private readonly Expression text; /// <summary> /// Creates a new Say node. /// </summary> /// <param name="text"> /// The text to replace the dialog with. /// </param> public Say(string text) { this.text = new LiteralExpression(text); } /// <summary> /// Creates a new Say node. /// </summary> /// <param name="text"> /// The expression to replace the dialog with. /// </param> public Say(Expression text) { this.text = text; } /// <summary> /// Evaluates the text of this node in the specified Rumor. /// </summary> /// <param name="rumor">The Rumor to evaluate against.</param> /// <returns>The text.</returns> public string EvaluateText(Engine.Rumor rumor) { return text.Evaluate(rumor.Scope).AsString(); } /// <summary> /// Evaluates the text of this node in the specified Scope. /// </summary> /// <param name="rumor">The Scope to evaluate against.</param> /// <returns>The text.</returns> public string EvaluateText(Scope scope) { return text.Evaluate(scope).AsString(); } public override IEnumerator<RumorYield> Run(Engine.Rumor rumor) { rumor.State.SetDialog(EvaluateText(rumor.Scope)); yield return new ForAdvance(); } #region Serialization public Say(SerializationInfo info, StreamingContext context) { text = (Expression)info.GetValue("text", typeof(Expression)); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("text", text, typeof(Expression)); } #endregion } }
mit
C#
879bb6df73e46d6880a3d10b3f81283b04612c4f
Clean this up
Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Client/IServerClientFactory.cs
src/Tgstation.Server.Client/IServerClientFactory.cs
using System; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Client { /// <summary> /// Factory for creating <see cref="IServerClient"/>s /// </summary> public interface IServerClientFactory { /// <summary> /// Create a <see cref="IServerClient"/> /// </summary> /// <param name="host">The URL to access TGS</param> /// <param name="username">The username to for the <see cref="IServerClient"/></param> /// <param name="password">The password for the <see cref="IServerClient"/></param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param> /// <param name="timeout">The <see cref="TimeSpan"/> representing timeout for the connection</param> /// <returns>A <see cref="Task{TResult}"/> resulting in a new <see cref="IServerClient"/></returns> Task<IServerClient> CreateServerClient(Uri host, string username, string password, TimeSpan timeout = default, CancellationToken cancellationToken = default); /// <summary> /// Create a <see cref="IServerClient"/> /// </summary> /// <param name="host">The URL to access TGS</param> /// <param name="token">The <see cref="Token"/> to access the API with</param> /// <param name="timeout">The <see cref="TimeSpan"/> representing timeout for the connection</param> /// <returns>A new <see cref="IServerClient"/></returns> IServerClient CreateServerClient(Uri host, Token token, TimeSpan timeout = default); } }
using System; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Client { /// <summary> /// Factory for creating <see cref="IServerClient"/>s /// </summary> public interface IServerClientFactory { /// <summary> /// Create a <see cref="IServerClient"/> /// </summary> /// <param name="host">The URL to access TGS</param> /// <param name="username">The username to for the <see cref="IServerClient"/></param> /// <param name="password">The password for the <see cref="IServerClient"/></param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param> /// <param name="timeout">The <see cref="TimeSpan"/> representing timeout for the connection</param> /// <returns>A <see cref="Task{TResult}"/> resulting in a new <see cref="IServerClient"/> on success, <see langword="null"/> if <paramref name="host"/> is invalid</returns> Task<IServerClient> CreateServerClient(Uri host, string username, string password, TimeSpan timeout = default, CancellationToken cancellationToken = default); /// <summary> /// Create a <see cref="IServerClient"/> /// </summary> /// <param name="host">The URL to access TGS</param> /// <param name="token">The <see cref="Token"/> to access the API with</param> /// <param name="timeout">The <see cref="TimeSpan"/> representing timeout for the connection</param> /// <returns>A new <see cref="IServerClient"/></returns> IServerClient CreateServerClient(Uri host, Token token, TimeSpan timeout = default); } }
agpl-3.0
C#
69926e399a806e3e6e6aec9381ce834a138ec564
rename method for clarity
Babblesort/GameOfLife
Engine/GenerationResolver.cs
Engine/GenerationResolver.cs
namespace Engine { public static class GenerationResolver { public static Generation ResolveNextGeneration(Grid grid, Rules rules, Generation cells) { var nextGen = new Generation(); foreach (var cell in cells) { nextGen.Add(cell.Key, CellAliveNextGen(cell.Value, NeighborsCount(cell.Key, grid, cells), rules)); } return nextGen; } public static int NeighborsCount(RowCol cell, Grid grid, Generation cells) { var count = 0; count += LiveCellAtLocation(grid.NeighborTL(cell), cells); count += LiveCellAtLocation(grid.NeighborTT(cell), cells); count += LiveCellAtLocation(grid.NeighborTR(cell), cells); count += LiveCellAtLocation(grid.NeighborLL(cell), cells); count += LiveCellAtLocation(grid.NeighborRR(cell), cells); count += LiveCellAtLocation(grid.NeighborBL(cell), cells); count += LiveCellAtLocation(grid.NeighborBB(cell), cells); count += LiveCellAtLocation(grid.NeighborBR(cell), cells); return count; } public static int LiveCellAtLocation(RowCol location, Generation cells) => cells[location] ? 1 : 0; public static bool CellAliveNextGen(bool alive, int neighborCount, Rules rules) { var survives = alive && rules.SurviveNeighborCounts.Contains(neighborCount); var born = !alive && rules.BirthNeighborCounts.Contains(neighborCount); return survives || born; } } }
namespace Engine { public static class GenerationResolver { public static Generation ResolveNextGeneration(Grid grid, Rules rules, Generation cells) { var nextGen = new Generation(); foreach (var cell in cells) { nextGen.Add(cell.Key, CellAliveNextGen(cell.Value, NeighborsCount(cell.Key, grid, cells), rules)); } return nextGen; } public static int NeighborsCount(RowCol cell, Grid grid, Generation cells) { var count = 0; count += NeighborCount(grid.NeighborTL(cell), cells); count += NeighborCount(grid.NeighborTT(cell), cells); count += NeighborCount(grid.NeighborTR(cell), cells); count += NeighborCount(grid.NeighborLL(cell), cells); count += NeighborCount(grid.NeighborRR(cell), cells); count += NeighborCount(grid.NeighborBL(cell), cells); count += NeighborCount(grid.NeighborBB(cell), cells); count += NeighborCount(grid.NeighborBR(cell), cells); return count; } public static int NeighborCount(RowCol neighbor, Generation cells) => cells[neighbor] ? 1 : 0; public static bool CellAliveNextGen(bool alive, int neighborCount, Rules rules) { var survives = alive && rules.SurviveNeighborCounts.Contains(neighborCount); var born = !alive && rules.BirthNeighborCounts.Contains(neighborCount); return survives || born; } } }
mit
C#
3716e857852a0990b3e482b3a709b4545a5d58c1
Fix build issues for TeamCity.
alexmullans/Siftables-Emulator
Siftables/MainWindow.xaml.cs
Siftables/MainWindow.xaml.cs
namespace Siftables { public partial class MainWindowView { public MainWindowView() { InitializeComponent(); } } }
namespace Siftables { public partial class MainWindowView { public MainWindowView() { InitializeComponent(); DoAllOfTheThings(); } } }
bsd-2-clause
C#
4173fe2616deccbbda175a048fd35e5890ed3fac
update for 0.6.4
sillsdev/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp
sample/GstPlayer.cs
sample/GstPlayer.cs
// GstPlayer.cs - a simple Vorbis media player using GStreamer // // Author: Alp Toker <alp@atoker.com> // // Copyright (c) 2002 Alp Toker using System; using Gst; public class GstTest { static void Main(string[] args) { Application.Init (); /* create a new bin to hold the elements */ Pipeline bin = new Pipeline("pipeline"); /* create a disk reader */ Element filesrc = ElementFactory.Make ("filesrc", "disk_source"); filesrc.SetProperty ("location", args[0]); /* now it's time to get the decoder */ Element decoder = ElementFactory.Make ("vorbisfile", "decode"); /* and an audio sink */ Element osssink = ElementFactory.Make ("osssink", "play_audio"); /* add objects to the main pipeline */ bin.Add (filesrc); bin.Add (decoder); bin.Add (osssink); /* connect the elements */ filesrc.Link (decoder); decoder.Link (osssink); /* start playing */ bin.SetState (ElementState.Playing); while (bin.Iterate ()); /* stop the bin */ bin.SetState (ElementState.Null); } }
// GstPlayer.cs - a simple Vorbis media player using GStreamer // // Author: Alp Toker <alp@atoker.com> // // Copyright (c) 2002 Alp Toker using System; using Gst; public class GstTest { static void Main(string[] args) { Application.Init (); /* create a new bin to hold the elements */ Pipeline bin = new Pipeline("pipeline"); /* create a disk reader */ Element filesrc = ElementFactory.Make ("filesrc", "disk_source"); filesrc.SetProperty ("location", new GLib.Value (args[0])); /* now it's time to get the decoder */ Element decoder = ElementFactory.Make ("vorbisdec", "decode"); /* and an audio sink */ Element osssink = ElementFactory.Make ("osssink", "play_audio"); /* add objects to the main pipeline */ bin.Add (filesrc); bin.Add (decoder); bin.Add (osssink); /* connect the elements */ filesrc.Connect (decoder); decoder.Connect (osssink); /* start playing */ bin.SetState (ElementState.Playing); while (bin.Iterate ()); /* stop the bin */ bin.SetState (ElementState.Null); } }
lgpl-2.1
C#
8499b780203a833d1fdf6d101adab497be4a95b2
Make tests run paralell
nopara73/DotNetTor
src/DotNetTor.Tests/Properties/AssemblyInfo.cs
src/DotNetTor.Tests/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using Xunit; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DotNetTor.Tests")] [assembly: AssemblyTrademark("")] [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true, MaxParallelThreads = 1)] // 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("ecc736d1-d4a9-4cd3-954b-7a795e46550f")]
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DotNetTor.Tests")] [assembly: AssemblyTrademark("")] // 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("ecc736d1-d4a9-4cd3-954b-7a795e46550f")]
mit
C#
37e3201e8d8b72d526fdeb00a9bc6f0549adef2a
Format tabs
LibertyLocked/webscripthook,LibertyLocked/webscripthook,LibertyLocked/webscripthook,LibertyLocked/webscripthook
VStats-plugin/WorldHelper.cs
VStats-plugin/WorldHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GTA; using GTA.Math; using GTA.Native; namespace VStats_plugin { class WorldHelper { static Dictionary<string, string> radioDict = new Dictionary<string, string> { {"RADIO_01_CLASS_ROCK", "Los Santos Rock Radio"}, {"RADIO_02_POP", "Non-Stop-Pop FM"}, {"RADIO_03_HIPHOP_NEW", "Radio Los Santos"}, {"RADIO_04_PUNK", "Channel X"}, {"RADIO_05_TALK_01", "West Coast Talk Radio"}, {"RADIO_06_COUNTRY", "Rebel Radio"}, {"RADIO_07_DANCE_01", "Soulwax FM"}, {"RADIO_08_MEXICAN", "East Los FM"}, {"RADIO_09_HIPHOP_OLD", "West Coast Classics"}, {"RADIO_11_TALK_02", "Blaine County Radio"}, {"RADIO_12_REGGAE", "Blue Ark"}, {"RADIO_13_JAZZ", "Worldwide FM"}, {"RADIO_14_DANCE_02", "FlyLo FM"}, {"RADIO_15_MOTOWN", "The Lowdown 91.1"}, {"RADIO_16_SILVERLAKE", "Radio Mirror Park"}, {"RADIO_17_FUNK", "Space 103.2"}, {"RADIO_18_90S_ROCK", "Vinewood Boulevard Radio"}, {"RADIO_19_USER", "Self Radio"}, {"RADIO_20_THELAB", "The Lab"}, {"RADIO_OFF", "Radio Off"}, {"", "Radio Off"}, }; public static string GetRadioFriendlyName(string displayName) { string friendlyName; if (radioDict.TryGetValue(displayName, out friendlyName)) return friendlyName; else return ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GTA; using GTA.Math; using GTA.Native; namespace VStats_plugin { class WorldHelper { static Dictionary<string, string> radioDict = new Dictionary<string, string> { {"RADIO_01_CLASS_ROCK", "Los Santos Rock Radio"}, {"RADIO_02_POP", "Non-Stop-Pop FM"}, {"RADIO_03_HIPHOP_NEW", "Radio Los Santos"}, {"RADIO_04_PUNK", "Channel X"}, {"RADIO_05_TALK_01", "West Coast Talk Radio"}, {"RADIO_06_COUNTRY", "Rebel Radio"}, {"RADIO_07_DANCE_01", "Soulwax FM"}, {"RADIO_08_MEXICAN", "East Los FM"}, {"RADIO_09_HIPHOP_OLD", "West Coast Classics"}, {"RADIO_11_TALK_02", "Blaine County Radio"}, {"RADIO_12_REGGAE", "Blue Ark"}, {"RADIO_13_JAZZ", "Worldwide FM"}, {"RADIO_14_DANCE_02", "FlyLo FM"}, {"RADIO_15_MOTOWN", "The Lowdown 91.1"}, {"RADIO_16_SILVERLAKE", "Radio Mirror Park"}, {"RADIO_17_FUNK", "Space 103.2"}, {"RADIO_18_90S_ROCK", "Vinewood Boulevard Radio"}, {"RADIO_19_USER", "Self Radio"}, {"RADIO_20_THELAB", "The Lab"}, {"RADIO_OFF", "Radio Off"}, {"", "Radio Off"}, }; public static string GetRadioFriendlyName(string displayName) { string friendlyName; if (radioDict.TryGetValue(displayName, out friendlyName)) return friendlyName; else return ""; } } }
mit
C#
2afced7bb0620e9452b98b908650ae9886ad6674
Change format of JSON for SlideRun to match API
edwardsdl/snaggertown-slide
src/SAJ.SnaggerTown.Hardware.Slide/SlideRun.cs
src/SAJ.SnaggerTown.Hardware.Slide/SlideRun.cs
using System; namespace SAJ.SnaggerTown.Hardware.Slide { /// <summary> /// Represents an instance of a Snagger traveling down the slide /// </summary> internal class SlideRun { #region Public Properties /// <summary> /// Gets or sets the Snagger's ID /// </summary> public int SnaggerId { get; set; } /// <summary> /// Gets or sets the date and time the Snagger tripped the top proximity sensor /// </summary> public DateTime OccurredOn { get; set; } /// <summary> /// Gets or sets the time in milliseconds it took for the Snagger to reach the bottom of the slide /// </summary> public int TimeInMs { get; set; } #endregion /// <summary> /// Generates a JSON encoded string representing the content of the POST request /// </summary> /// <returns> /// A JSON encoded string representing the content of the POST request /// </returns> public string ToPostRequestContent() { return "{ \"keyfobNum\": \"" + SnaggerId.ToString() + "\", \"startTimeStamp\": \"" + OccurredOn + "\", \"endTimeStamp\": \"" + OccurredOn.Add(TimeSpan.FromMilliseconds(TimeInMs)) + "\" }"; } } }
using System; namespace SAJ.SnaggerTown.Hardware.Slide { /// <summary> /// Represents an instance of a Snagger traveling down the slide /// </summary> internal class SlideRun { #region Public Properties /// <summary> /// Gets or sets the Snagger's ID /// </summary> public int SnaggerId { get; set; } /// <summary> /// Gets or sets the date and time the Snagger tripped the top proximity sensor /// </summary> public DateTime OccurredOn { get; set; } /// <summary> /// Gets or sets the time in milliseconds it took for the Snagger to reach the bottom of the slide /// </summary> public int TimeInMs { get; set; } #endregion /// <summary> /// Generates a JSON encoded string representing the content of the POST request /// </summary> /// <returns> /// A JSON encoded string representing the content of the POST request /// </returns> public string ToPostRequestContent() { return "{ \"SnaggerId\": \"" + SnaggerId + "\", \"OccurredOn\": \"" + OccurredOn + "\", \"TimeInMs\": \"" + TimeInMs + "\" }"; } } }
mit
C#
28c5f5af8c11434d36ed3677f4ba80ac22a1ab0d
Fix travis/mono by remove SUO
HelloKitty/SceneJect,HelloKitty/SceneJect
src/Sceneject.Autofac/AutofacServiceAdapter.cs
src/Sceneject.Autofac/AutofacServiceAdapter.cs
using Autofac; using SceneJect.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace SceneJect.Autofac { public class AutofacServiceAdapter : ContainerServiceProvider, IResolver, IServiceRegister { private readonly AutofacRegisterationStrat registerationStrat = new AutofacRegisterationStrat(new ContainerBuilder()); public override IServiceRegister Registry { get { return registerationStrat; } } private IResolver resolver = null; public override IResolver Resolver { get { return GenerateResolver(); } } private readonly object syncObj = new object(); private IResolver GenerateResolver() { if(resolver == null) { //double check locking lock(syncObj) if (resolver == null) resolver = new AutofacResolverStrat(registerationStrat.Build()); } return resolver; } } }
using Autofac; using SceneJect.Autofac; using SceneJect.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace SceneJect.Autofac { public class AutofacServiceAdapter : ContainerServiceProvider, IResolver, IServiceRegister { private readonly AutofacRegisterationStrat registerationStrat = new AutofacRegisterationStrat(new ContainerBuilder()); public override IServiceRegister Registry { get { return registerationStrat; } } private IResolver resolver = null; public override IResolver Resolver { get { return GenerateResolver(); } } private readonly object syncObj = new object(); private IResolver GenerateResolver() { if(resolver == null) { //double check locking lock(syncObj) if (resolver == null) resolver = new AutofacResolverStrat(registerationStrat.Build()); } return resolver; } } }
mit
C#
ce382e825a39cc9d03b1dc1ffa392278d711bf66
Bump version.
FacilityApi/FacilityJavaScript,FacilityApi/FacilityJavaScript,FacilityApi/FacilityJavaScript
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("0.3.1.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
using System.Reflection; [assembly: AssemblyVersion("0.3.0.0")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
mit
C#
4c89ce354bcc45b21ad5fefdf0e3a6835128cb50
Change unit test output validation in DepartmentTests.cs to use Assert.AreEqual().
TimCollins/ManagementSpeakGenerator
src/MSG.UnitTests/DepartmentTests.cs
src/MSG.UnitTests/DepartmentTests.cs
using System.Collections.Generic; using MSG.DomainLogic; using NUnit.Framework; namespace MSG.UnitTests { [TestFixture] class DepartmentTests { private List<int> _defaults; [SetUp] public void SetUpDefaultNumbers() { _defaults = new List<int>{17, 6, 1, 17, 2, 1, 4, 7, 5, 1, 3, 2}; } [TearDown] public void UndoRandomNumberSetting() { MoqUtil.UndoMockRandomNumber(); } [Test] public void VerifyHumanResourcesSpacing() { _defaults.Insert(7, 1); MoqUtil.SetupRandMock(_defaults.ToArray()); string output = DomainFactory.Generator.GetSentences(1)[0]; Assert.AreEqual("The Group Chief Human Resources Officer globally streamlines the process across the board.", output); } [Test] public void VerifyCustomerRelationsSpacing() { _defaults.Insert(7, 7); MoqUtil.SetupRandMock(_defaults.ToArray()); string output = DomainFactory.Generator.GetSentences(1)[0]; Assert.AreEqual("The Group Chief Customer Relations Officer globally streamlines the process across the board.", output); } [Test] public void VerifyMarketingSpacing() { _defaults.Insert(7, 14); MoqUtil.SetupRandMock(_defaults.ToArray()); string output = DomainFactory.Generator.GetSentences(1)[0]; Assert.AreEqual("The Group Chief Marketing Officer globally streamlines the process across the board.", output); } [Test] [ExpectedException(typeof(RandomNumberException))] public void VerifyInvalidValueHandled() { _defaults.Insert(7, 50); MoqUtil.SetupRandMock(_defaults.ToArray()); DomainFactory.Generator.GetSentences(1); } } }
using System.Collections.Generic; using MSG.DomainLogic; using NUnit.Framework; namespace MSG.UnitTests { [TestFixture] class DepartmentTests { private List<int> _defaults; [SetUp] public void SetUpDefaultNumbers() { _defaults = new List<int>{17, 6, 1, 17, 2, 1, 4, 7, 5, 1, 3, 2}; } [TearDown] public void UndoRandomNumberSetting() { MoqUtil.UndoMockRandomNumber(); } [Test] public void VerifyHumanResourcesSpacing() { _defaults.Insert(7, 1); MoqUtil.SetupRandMock(_defaults.ToArray()); string output = DomainFactory.Generator.GetSentences(1)[0]; Assert.IsTrue(output.Contains("Human Resources ")); } [Test] public void VerifyCustomerRelationsSpacing() { _defaults.Insert(7, 7); MoqUtil.SetupRandMock(_defaults.ToArray()); string output = DomainFactory.Generator.GetSentences(1)[0]; Assert.IsTrue(output.Contains("Customer Relations ")); } [Test] public void VerifyMarketingSpacing() { _defaults.Insert(7, 14); MoqUtil.SetupRandMock(_defaults.ToArray()); string output = DomainFactory.Generator.GetSentences(1)[0]; Assert.IsTrue(output.Contains("Marketing ")); } [Test] [ExpectedException(typeof(RandomNumberException))] public void VerifyInvalidValueHandled() { _defaults.Insert(7, 50); MoqUtil.SetupRandMock(_defaults.ToArray()); DomainFactory.Generator.GetSentences(1); } } }
mit
C#
f9af01da8c8fa57c0acd0017670da804e797f567
Update docs a little
Deadpikle/NetSparkle,Deadpikle/NetSparkle
src/NetSparkle/Enums/SecurityMode.cs
src/NetSparkle/Enums/SecurityMode.cs
namespace NetSparkleUpdater.Enums { /// <summary> /// Controls the situations where files have to be signed with the private key. /// If both a public key and a signature are present, they always have to be valid. /// /// We recommend using SecurityMode.Strict if at all possible. /// /// Note that <see cref="ReleaseNotesGrabber"/> needs to have /// <see cref="ReleaseNotesGrabber.ChecksReleaseNotesSignature"/> set to true in order /// to verify signatures. /// </summary> public enum SecurityMode { /// <summary> /// All files (with or without signature) will be accepted. /// This mode is strongly NOT recommended. It can cause critical security issues. /// </summary> Unsafe = 1, /// <summary> /// If there is a public key, the app cast and download file have to be signed. /// If there isn't a public key, files without a signature will also be accepted. /// This mode is a mix between Unsafe and Strict and can have some security issues if the /// public key gets lost in the application. /// </summary> UseIfPossible = 2, /// <summary> /// The app cast and download file have to be signed. This means the public key must exist. This is the default mode. /// </summary> Strict = 3, /// <summary> /// Only verify the signature of software downloads (via an ISignatureVerifier). /// Do not verify the signature of anything else: app casts, release notes, etc. /// </summary> OnlyVerifySoftwareDownloads = 4, } }
namespace NetSparkleUpdater.Enums { /// <summary> /// Controls the situations where files have to be signed with the private key. /// If both a public key and a signature are present, they always have to be valid. /// /// We recommend using SecurityMode.Strict if at all possible. /// </summary> public enum SecurityMode { /// <summary> /// All files (with or without signature) will be accepted. /// This mode is strongly NOT recommended. It can cause critical security issues. /// </summary> Unsafe = 1, /// <summary> /// If there is a public key, the app cast and download file have to be signed. /// If there isn't a public key, files without a signature will also be accepted. /// This mode is a mix between Unsafe and Strict and can have some security issues if the /// public key gets lost in the application. /// </summary> UseIfPossible = 2, /// <summary> /// The app cast and download file have to be signed. This means the public key must exist. This is the default mode. /// </summary> Strict = 3, /// <summary> /// Only verify the signature of software downloads (via an ISignatureVerifier). /// Do not verify the signature of anything else: app casts, release notes, etc. /// </summary> OnlyVerifySoftwareDownloads = 4, } }
mit
C#
b69868394719acefc18df55d43e1858fa9822e12
Correct in order not to use "Wait" method for synchronized method
hukatama024e/MacroRecoderCsScript,hukatama024e/UserInputMacro
src/UserInputMacro/ScriptExecuter.cs
src/UserInputMacro/ScriptExecuter.cs
using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace UserInputMacro { static class ScriptExecuter { public static async Task ExecuteAsync( string scriptPath ) { using( var hook = new UserInputHook() ) { HookSetting( hook ); var script = CSharpScript.Create( File.ReadAllText( scriptPath ), ScriptOptions.Default, typeof( MacroScript ) ); await script.RunAsync( new MacroScript() ); } } private static void LoggingMouseMacro( MouseHookStruct mouseHookStr, int mouseEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteMouseEvent( mouseHookStr, ( MouseHookEvent ) mouseEvent ); } } private static void LoggingKeyMacro( KeyHookStruct keyHookStr, int keyEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteKeyEvent( keyHookStr, ( KeyHookEvent ) keyEvent ); } } private static void HookSetting( UserInputHook hook ) { hook.MouseHook = LoggingMouseMacro; hook.KeyHook = LoggingKeyMacro; hook.HookErrorProc = CommonUtil.HandleException; hook.RegisterKeyHook(); hook.RegisterMouseHook(); } } }
using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace UserInputMacro { static class ScriptExecuter { public static async Task ExecuteAsync( string scriptPath ) { using( var hook = new UserInputHook() ) { HookSetting( hook ); var script = CSharpScript.Create( File.ReadAllText( scriptPath ), ScriptOptions.Default, typeof( MacroScript ) ); await script.RunAsync( new MacroScript() ); } } private static void LoggingMouseMacro( MouseHookStruct mouseHookStr, int mouseEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteMouseEvent( mouseHookStr, ( MouseHookEvent ) mouseEvent ); } } private static void LoggingKeyMacro( KeyHookStruct keyHookStr, int keyEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteKeyEventAsync( keyHookStr, ( KeyHookEvent ) keyEvent ).Wait(); } } private static void HookSetting( UserInputHook hook ) { hook.MouseHook = LoggingMouseMacro; hook.KeyHook = LoggingKeyMacro; hook.HookErrorProc = CommonUtil.HandleException; hook.RegisterKeyHook(); hook.RegisterMouseHook(); } } }
mit
C#
b4762e0e7ad690fad2137a98c0c07e26d020fff9
Update CommonAnimations.cs
Microsoft/composition,clarkezone/composition,clarkezone/composition,Microsoft/composition
SDK10069/SlideShow/SlideShow/CommonAnimations.cs
SDK10069/SlideShow/SlideShow/CommonAnimations.cs
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // 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.Numerics; using System.Text; using System.Threading.Tasks; using Windows.UI.Composition; namespace SlideShow { //------------------------------------------------------------------------------ // // class CommonAnimations // // This class defines some common animation templates and timings used // throughout the application. // //------------------------------------------------------------------------------ class CommonAnimations { public static void Initialize(Compositor compositor) { // Create keyframes to select and unselect: // - Since both Saturation and Opacity use float [0.0 -> 1.0], we can actually use the // same keyframe instances and just bind to different properties. NormalOnAnimation = compositor.CreateScalarKeyFrameAnimation(); NormalOnAnimation.InsertKeyFrame(1.0f, 1.0f /* opaque */); NormalOnAnimation.Duration = NormalTime; SlowOffAnimation = compositor.CreateScalarKeyFrameAnimation(); SlowOffAnimation.InsertKeyFrame(1.0f, 0.0f /* transparent */); SlowOffAnimation.Duration = SlowTime; } public static void Uninitialize() { if (SlowOffAnimation != null) { SlowOffAnimation.Dispose(); SlowOffAnimation = null; } if (NormalOnAnimation != null) { NormalOnAnimation.Dispose(); NormalOnAnimation = null; } } public static ScalarKeyFrameAnimation NormalOnAnimation; public static ScalarKeyFrameAnimation SlowOffAnimation; public static readonly TimeSpan NormalTime = TimeSpan.FromMilliseconds(800); public static readonly TimeSpan SlowTime = TimeSpan.FromMilliseconds(1400); } }
//------------------------------------------------------------------------------ // // Copyright (C) Microsoft. All rights reserved. // //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using Windows.UI.Composition; namespace SlideShow { //------------------------------------------------------------------------------ // // class CommonAnimations // // This class defines some common animation templates and timings used // throughout the application. // //------------------------------------------------------------------------------ class CommonAnimations { public static void Initialize(Compositor compositor) { // Create keyframes to select and unselect: // - Since both Saturation and Opacity use float [0.0 -> 1.0], we can actually use the // same keyframe instances and just bind to different properties. NormalOnAnimation = compositor.CreateScalarKeyFrameAnimation(); NormalOnAnimation.InsertKeyFrame(1.0f, 1.0f /* opaque */); NormalOnAnimation.Duration = NormalTime; SlowOffAnimation = compositor.CreateScalarKeyFrameAnimation(); SlowOffAnimation.InsertKeyFrame(1.0f, 0.0f /* transparent */); SlowOffAnimation.Duration = SlowTime; } public static void Uninitialize() { if (SlowOffAnimation != null) { SlowOffAnimation.Dispose(); SlowOffAnimation = null; } if (NormalOnAnimation != null) { NormalOnAnimation.Dispose(); NormalOnAnimation = null; } } public static ScalarKeyFrameAnimation NormalOnAnimation; public static ScalarKeyFrameAnimation SlowOffAnimation; public static readonly TimeSpan NormalTime = TimeSpan.FromMilliseconds(800); public static readonly TimeSpan SlowTime = TimeSpan.FromMilliseconds(1400); } }
mit
C#
87a512afba394a21584af76f52e3cbd5a5348b05
Update UnityProject/Assets/Scripts/GameModes/NukeOps.cs
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/GameModes/NukeOps.cs
UnityProject/Assets/Scripts/GameModes/NukeOps.cs
using System; using System.Collections.Generic; using UnityEngine; using Antagonists; [CreateAssetMenu(menuName="ScriptableObjects/GameModes/NukeOps")] public class NukeOps : GameMode { [Tooltip("Ratio of nuke ops to player count. A value of 0.2 means there would be " + "2 nuke ops when there are 10 players.")] [Range(0,1)] [SerializeField] private float nukeOpsRatio; /// <summary> /// Set up the station for the game mode /// </summary> public override void SetupRound() { Logger.Log("Setting up NukeOps round!", Category.GameMode); } /// <summary> /// Begin the round /// </summary> public override void StartRound() { Logger.Log("Starting NukeOps round!", Category.GameMode); base.StartRound(); } public override bool IsPossible() { return base.IsPossible() && (FindObjectOfType<Nuke>() != null); } protected override bool ShouldSpawnAntag(PlayerSpawnRequest spawnRequest) { //spawn only if there is not yet any syndicate ops (and at least one other player) or //the ratio is too low var existingNukeOps = PlayerList.Instance.AntagPlayers.Count; var inGamePlayers = PlayerList.Instance.InGamePlayers.Count; if ((inGamePlayers > 0 && existingNukeOps == 0) || existingNukeOps < Math.Floor(inGamePlayers * nukeOpsRatio)) return true; return false; } }
using System; using System.Collections.Generic; using UnityEngine; using Antagonists; [CreateAssetMenu(menuName="ScriptableObjects/GameModes/NukeOps")] public class NukeOps : GameMode { [Tooltip("Ratio of nuke ops to player count. A value of 0.2 means there would be " + "2 nuke ops when there are 10 players.")] [Range(0,1)] [SerializeField] private float nukeOpsRatio; /// <summary> /// Set up the station for the game mode /// </summary> public override void SetupRound() { Logger.Log("Setting up NukeOps round!", Category.GameMode); } /// <summary> /// Begin the round /// </summary> public override void StartRound() { Logger.Log("Starting NukeOps round!", Category.GameMode); base.StartRound(); } public override bool IsPossible() { return FindObjectOfType<Nuke>() != null ? true : false; } protected override bool ShouldSpawnAntag(PlayerSpawnRequest spawnRequest) { //spawn only if there is not yet any syndicate ops (and at least one other player) or //the ratio is too low var existingNukeOps = PlayerList.Instance.AntagPlayers.Count; var inGamePlayers = PlayerList.Instance.InGamePlayers.Count; if ((inGamePlayers > 0 && existingNukeOps == 0) || existingNukeOps < Math.Floor(inGamePlayers * nukeOpsRatio)) return true; return false; } }
agpl-3.0
C#
a60328cbd9914bc290bceaf18da40344f961e389
update version
campersau/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,BreeeZe/NuGetPackageExplorer
Common/CommonAssemblyInfo.cs
Common/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NuGet Package Explorer")] [assembly: AssemblyCopyright("\x00a9 Luan Nguyen. All rights reserved.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("3.10.0.0")] [assembly: AssemblyFileVersion("3.10.0.0")]
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NuGet Package Explorer")] [assembly: AssemblyCopyright("\x00a9 Luan Nguyen. All rights reserved.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("3.8.0.0")] [assembly: AssemblyFileVersion("3.8.0.0")]
mit
C#
e4adea0f2e8e6f256bc3f329ce66412532a8d229
Increase benchmark iterations
EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an
A-vs-An/PerfTest/Program.cs
A-vs-An/PerfTest/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Management; using AvsAnLib; namespace PerfTest { static class Program { static void Main(string[] args) { var words = File.ReadAllLines(@"..\..\..\AvsAn-Test\354984si.ngl").Where(w => w != "").ToArray(); long sum = 0; Stopwatch sw = Stopwatch.StartNew(); var _ = AvsAn.Query("example").Article; var init = sw.Elapsed; Console.WriteLine("initialization took " + init.TotalMilliseconds); sw.Restart(); const int iters = 400; for (var k = 0; k < iters; k++) { for (var i = 0; i < words.Length; i++) sum += AvsAn.Query(words[i]).Article == "an" ? 1 : 0; for (var i = words.Length - 1; i >= 0; i--) sum += AvsAn.Query(words[i]).Article == "an" ? 1 : 0; } var duration = sw.Elapsed.TotalMilliseconds; var clockrateMHz = new ManagementObjectSearcher(new ObjectQuery("SELECT CurrentClockSpeed FROM Win32_Processor")).Get() .Cast<ManagementObject>().Select(mo => Convert.ToDouble(mo["CurrentClockSpeed"])).Max(); Console.WriteLine(sum + " / " + words.Length + " (" + ((double)sum / words.Length / iters / 2) + ") an rate."); var microseconds = duration / words.Length / iters / 2 * 1000.0; Console.WriteLine(microseconds * 1000.0 + " nanoseconds per lookup"); Console.WriteLine(clockrateMHz * microseconds + " cycles per lookup @ " + clockrateMHz + "MHz"); Console.WriteLine("took " + duration + "ms"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Management; using AvsAnLib; namespace PerfTest { static class Program { static void Main(string[] args) { var words = File.ReadAllLines(@"..\..\..\AvsAn-Test\354984si.ngl").Where(w => w != "").ToArray(); long sum = 0; Stopwatch sw = Stopwatch.StartNew(); var _ = AvsAn.Query("example").Article; var init = sw.Elapsed; Console.WriteLine("initialization took " + init.TotalMilliseconds); sw.Restart(); const int iters = 200; for (var k = 0; k < iters; k++) { for (var i = 0; i < words.Length; i++) sum += AvsAn.Query(words[i]).Article == "an" ? 1 : 0; for (var i = words.Length - 1; i >= 0; i--) sum += AvsAn.Query(words[i]).Article == "an" ? 1 : 0; } var duration = sw.Elapsed.TotalMilliseconds; var clockrateMHz = new ManagementObjectSearcher(new ObjectQuery("SELECT CurrentClockSpeed FROM Win32_Processor")).Get() .Cast<ManagementObject>().Select(mo => Convert.ToDouble(mo["CurrentClockSpeed"])).Max(); Console.WriteLine(sum + " / " + words.Length + " (" + ((double)sum / words.Length / iters / 2) + ") an rate."); var microseconds = duration / words.Length / iters / 2 * 1000.0; Console.WriteLine(microseconds * 1000.0 + " nanoseconds per lookup"); Console.WriteLine(clockrateMHz * microseconds + " cycles per lookup @ " + clockrateMHz + "MHz"); Console.WriteLine("took " + duration + "ms"); } } }
apache-2.0
C#
5ea8a9fce9c2b3561be0da042454f3ec6dd0cec2
Add more Target tests
chkn/Tempest
Desktop/Tempest/Tests/TargetTests.cs
Desktop/Tempest/Tests/TargetTests.cs
// // TargetTests.cs // // Author: // Eric Maupin <me@ermau.com> // // Copyright (c) 2012-2014 Eric Maupin // // 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.Net; using System.Net.Sockets; using NUnit.Framework; namespace Tempest.Tests { [TestFixture] public class TargetTests { [Test] public void CtorNull() { Assert.Throws<ArgumentNullException> (() => new Target (null, 0)); } [Test] public void Ctor() { var target = new Target ("host", 1234); Assert.That (target.Hostname, Is.EqualTo ("host")); Assert.That (target.Port, Is.EqualTo (1234)); } // Extensions [Test] public void ToEndPointNull() { Assert.That (() => TargetExtensions.ToEndPoint (null), Throws.TypeOf<ArgumentNullException>()); } [Test] public void ToEndPointIPv4() { var target = new Target ("127.0.0.1", 1234); EndPoint endPoint = target.ToEndPoint(); Assert.That (endPoint, Is.InstanceOf<IPEndPoint>()); IPEndPoint ip = (IPEndPoint) endPoint; Assert.That (ip.Address, Is.EqualTo (IPAddress.Parse ("127.0.0.1"))); Assert.That (ip.AddressFamily, Is.EqualTo (AddressFamily.InterNetwork)); } [Test] public void ToEndPointIPv6() { var target = new Target ("::1", 1234); EndPoint endPoint = target.ToEndPoint(); Assert.That (endPoint, Is.InstanceOf<IPEndPoint>()); IPEndPoint ip = (IPEndPoint) endPoint; Assert.That (ip.Address, Is.EqualTo (IPAddress.Parse ("::1"))); Assert.That (ip.AddressFamily, Is.EqualTo (AddressFamily.InterNetworkV6)); Assert.That (ip.Port, Is.EqualTo (target.Port)); } [Test] public void ToEndPointHostname() { var target = new Target ("localhost", 1234); EndPoint endPoint = target.ToEndPoint(); Assert.That (endPoint, Is.InstanceOf<DnsEndPoint>()); DnsEndPoint dns = (DnsEndPoint) endPoint; Assert.That (dns.Host, Is.EqualTo (target.Hostname)); Assert.That (dns.Port, Is.EqualTo (target.Port)); } } }
// // TargetTests.cs // // Author: // Eric Maupin <me@ermau.com> // // Copyright (c) 2012 Eric Maupin // // 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 NUnit.Framework; namespace Tempest.Tests { [TestFixture] public class TargetTests { [Test] public void CtorNull() { Assert.Throws<ArgumentNullException> (() => new Target (null, 0)); } } }
mit
C#
f36dfe5deeabeb0a8abdd9c37085a4f37dba8327
Add AllChat to ChatRepository
ethanmoffat/EndlessClient
EOLib/Domain/Chat/IChatRepository.cs
EOLib/Domain/Chat/IChatRepository.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using System.Collections.Generic; using System.Linq; namespace EOLib.Domain.Chat { public interface IChatRepository { string LocalTypedText { get; set; } Dictionary<ChatTab, List<ChatData>> AllChat { get; set; } } public interface IChatProvider { string LocalTypedText { get; } IReadOnlyDictionary<ChatTab, IReadOnlyList<ChatData>> AllChat { get; } } public class ChatRepository : IChatRepository, IChatProvider { public string LocalTypedText { get; set; } public Dictionary<ChatTab, List<ChatData>> AllChat { get; set; } IReadOnlyDictionary<ChatTab, IReadOnlyList<ChatData>> IChatProvider.AllChat { get { return AllChat.ToDictionary( k => k.Key, v => v.Value as IReadOnlyList<ChatData>); } } public ChatRepository() { LocalTypedText = ""; AllChat = new Dictionary<ChatTab, List<ChatData>>(); foreach (var tab in (ChatTab[]) Enum.GetValues(typeof(ChatTab))) AllChat.Add(tab, new List<ChatData>()); } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file namespace EOLib.Domain.Chat { public interface IChatRepository { string LocalTypedText { get; set; } } public interface IChatProvider { string LocalTypedText { get; } } public class ChatRepository : IChatRepository, IChatProvider { public string LocalTypedText { get; set; } public ChatRepository() { LocalTypedText = ""; } } }
mit
C#
050579cc24a7d193ad9929784a2cdab567b16487
Validate data in the ctors
0culus/ElectronicCash
ElectronicCash/ActorName.cs
ElectronicCash/ActorName.cs
using System; namespace ElectronicCash { public struct ActorName { private readonly string _firstName; private readonly string _middleName; private readonly string _lastName; private readonly string _title; private readonly string _entityName; public ActorName(string firstName, string middleName, string lastName, string title) { if (string.IsNullOrEmpty(firstName)) { throw new ArgumentException("First name must not be empty"); } if (string.IsNullOrEmpty(middleName)) { throw new ArgumentException("Middle name must not be empty"); } if (string.IsNullOrEmpty(lastName)) { throw new ArgumentException("Last name must not be empty"); } _firstName = firstName; _middleName = middleName; _lastName = lastName; _title = title; _entityName = null; } public ActorName(string entityName) { if (string.IsNullOrEmpty(entityName)) { throw new ArgumentException("Entity name must be provided"); } _firstName = null; _middleName = null; _lastName = null; _title = null; _entityName = entityName; } public string FirstName => _firstName; public string MiddleName => _middleName; public string LastName => _lastName; public string Title => _title; public string EntityName => _entityName; } }
namespace ElectronicCash { public struct ActorName { private readonly string _firstName; private readonly string _middleName; private readonly string _lastName; private readonly string _title; private readonly string _entityName; public ActorName(string firstName, string middleName, string lastName, string title) { _firstName = firstName; _middleName = middleName; _lastName = lastName; _title = title; _entityName = null; } public ActorName(string entityName) { _firstName = null; _middleName = null; _lastName = null; _title = null; _entityName = entityName; } public string FirstName => _firstName; public string MiddleName => _middleName; public string LastName => _lastName; public string Title => _title; public string EntityName => _entityName; } }
mit
C#
080cc8834e95f3d45dd4f8d044d8c8d041f3eb76
allow providing a custom payload builder
danshapir/JSONAPI.NET,JSONAPIdotNET/JSONAPI.NET,SphtKr/JSONAPI.NET,DefactoSoftware/JSONAPI.NET,SathishN/JSONAPI.NET
JSONAPI/Core/JsonApiConfiguration.cs
JSONAPI/Core/JsonApiConfiguration.cs
using System; using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Dispatcher; using JSONAPI.ActionFilters; using JSONAPI.Http; using JSONAPI.Json; using JSONAPI.Payload; namespace JSONAPI.Core { /// <summary> /// Configuration API for JSONAPI.NET /// </summary> public class JsonApiConfiguration { private readonly IModelManager _modelManager; private Func<IQueryablePayloadBuilder> _payloadBuilderFactory; /// <summary> /// Creates a new configuration /// </summary> public JsonApiConfiguration(IModelManager modelManager) { if (modelManager == null) throw new Exception("You must provide a model manager to begin configuration."); _modelManager = modelManager; _payloadBuilderFactory = () => new DefaultQueryablePayloadBuilderConfiguration().GetBuilder(modelManager); } /// <summary> /// Allows configuring the default queryable payload builder /// </summary> /// <param name="configurationAction">Provides access to a fluent DefaultQueryablePayloadBuilderConfiguration object</param> /// <returns>The same configuration object the method was called on.</returns> public JsonApiConfiguration UsingDefaultQueryablePayloadBuilder(Action<DefaultQueryablePayloadBuilderConfiguration> configurationAction) { _payloadBuilderFactory = () => { var configuration = new DefaultQueryablePayloadBuilderConfiguration(); configurationAction(configuration); return configuration.GetBuilder(_modelManager); }; return this; } /// <summary> /// Allows overriding the default queryable payload builder /// </summary> /// <param name="queryablePayloadBuilder">The custom queryable payload builder to use</param> /// <returns></returns> public JsonApiConfiguration UseCustomQueryablePayloadBuilder(IQueryablePayloadBuilder queryablePayloadBuilder) { _payloadBuilderFactory = () => queryablePayloadBuilder; return this; } /// <summary> /// Applies the running configuration to an HttpConfiguration instance /// </summary> /// <param name="httpConfig">The HttpConfiguration to apply this JsonApiConfiguration to</param> public void Apply(HttpConfiguration httpConfig) { var formatter = new JsonApiFormatter(_modelManager); httpConfig.Formatters.Clear(); httpConfig.Formatters.Add(formatter); var queryablePayloadBuilder = _payloadBuilderFactory(); httpConfig.Filters.Add(new JsonApiQueryableAttribute(queryablePayloadBuilder)); httpConfig.Services.Replace(typeof (IHttpControllerSelector), new PascalizedControllerSelector(httpConfig)); } } }
using System; using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Dispatcher; using JSONAPI.ActionFilters; using JSONAPI.Http; using JSONAPI.Json; using JSONAPI.Payload; namespace JSONAPI.Core { /// <summary> /// Configuration API for JSONAPI.NET /// </summary> public class JsonApiConfiguration { private readonly IModelManager _modelManager; private Func<IQueryablePayloadBuilder> _payloadBuilderFactory; /// <summary> /// Creates a new configuration /// </summary> public JsonApiConfiguration(IModelManager modelManager) { if (modelManager == null) throw new Exception("You must provide a model manager to begin configuration."); _modelManager = modelManager; _payloadBuilderFactory = () => new DefaultQueryablePayloadBuilderConfiguration().GetBuilder(modelManager); } /// <summary> /// Allows configuring the default queryable payload builder /// </summary> /// <param name="configurationAction">Provides access to a fluent DefaultQueryablePayloadBuilderConfiguration object</param> /// <returns>The same configuration object the method was called on.</returns> public JsonApiConfiguration UsingDefaultQueryablePayloadBuilder(Action<DefaultQueryablePayloadBuilderConfiguration> configurationAction) { _payloadBuilderFactory = () => { var configuration = new DefaultQueryablePayloadBuilderConfiguration(); configurationAction(configuration); return configuration.GetBuilder(_modelManager); }; return this; } /// <summary> /// Applies the running configuration to an HttpConfiguration instance /// </summary> /// <param name="httpConfig">The HttpConfiguration to apply this JsonApiConfiguration to</param> public void Apply(HttpConfiguration httpConfig) { var formatter = new JsonApiFormatter(_modelManager); httpConfig.Formatters.Clear(); httpConfig.Formatters.Add(formatter); var queryablePayloadBuilder = _payloadBuilderFactory(); httpConfig.Filters.Add(new JsonApiQueryableAttribute(queryablePayloadBuilder)); httpConfig.Services.Replace(typeof (IHttpControllerSelector), new PascalizedControllerSelector(httpConfig)); } } }
mit
C#
b3ca342e16f4515a19271db71091de84cd153491
Improve time service interface documentation
MarinAtanasov/AppBrix,MarinAtanasov/AppBrix.NetCore
Modules/AppBrix.Time/ITimeService.cs
Modules/AppBrix.Time/ITimeService.cs
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; namespace AppBrix.Time { /// <summary> /// Service which operates with <see cref="DateTime"/>. /// </summary> public interface ITimeService { /// <summary> /// Gets the current time. /// This should be used instead of <see cref="DateTime.Now"/> or <see cref="DateTime.UtcNow"/>. /// </summary> /// <returns>The current date and time.</returns> DateTime GetTime(); /// <summary> /// Converts the specified time to the configured application <see cref="DateTimeKind"/>. /// </summary> /// <param name="time">The specified time.</param> /// <returns>The converted time.</returns> DateTime ToAppTime(DateTime time); /// <summary> /// Converts a given <see cref="DateTime"/> to a predefined <see cref="string"/> representation. /// </summary> /// <param name="time">The time.</param> /// <returns>The string representation of the time.</returns> string ToString(DateTime time); /// <summary> /// Converts a given <see cref="string"/> to a <see cref="DateTime"/> in the configured <see cref="DateTimeKind"/>. /// </summary> /// <param name="time">The date and time in string representation.</param> /// <returns>The date and time.</returns> DateTime ToDateTime(string time); } }
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; namespace AppBrix.Time { /// <summary> /// Service which operates with <see cref="DateTime"/>. /// </summary> public interface ITimeService { /// <summary> /// Gets the current time. /// This should be used instead of DateTime.Now or DateTime.UtcNow. /// </summary> /// <returns></returns> DateTime GetTime(); /// <summary> /// Converts the specified time to the configured application time kind. /// </summary> /// <param name="time">The specified time.</param> /// <returns>The converted time.</returns> DateTime ToAppTime(DateTime time); /// <summary> /// Converts a given <see cref="DateTime"/> to a predefined <see cref="string"/> representation. /// </summary> /// <param name="time">The time.</param> /// <returns>The string representation of the time.</returns> string ToString(DateTime time); /// <summary> /// Converts a given <see cref="string"/> to a <see cref="DateTime"/> in a system time kind. /// </summary> /// <param name="time"></param> /// <returns></returns> DateTime ToDateTime(string time); } }
mit
C#
4cf7e486410214320853039d7f45786fc3baaebd
Add ToString to RtTuple
reinforced/Reinforced.Typings
Reinforced.Typings/Ast/TypeNames/RtTuple.cs
Reinforced.Typings/Ast/TypeNames/RtTuple.cs
using System.Collections.Generic; namespace Reinforced.Typings.Ast.TypeNames { /// <summary> /// AST node for TypeScript tuple type /// </summary> public class RtTuple : RtTypeName { /// <summary> /// Constructs new RtTuple /// </summary> public RtTuple() { TupleTypes = new List<RtTypeName>(); } /// <summary> /// Constructs new RtTuple with specified type paranmeters /// </summary> /// <param name="tupleTypes">Types for tuple</param> public RtTuple(IEnumerable<RtTypeName> tupleTypes) { TupleTypes = new List<RtTypeName>(tupleTypes); } /// <summary> /// Constructs new RtTuple with specified type paranmeters /// </summary> /// <param name="tupleTypes">Types for tuple</param> public RtTuple(params RtTypeName[] tupleTypes) { TupleTypes = new List<RtTypeName>(tupleTypes); } /// <summary> /// All types that must participate tuple /// </summary> public List<RtTypeName> TupleTypes { get; private set; } /// <inheritdoc /> public override IEnumerable<RtNode> Children { get { foreach (var rtTypeName in TupleTypes) { yield return rtTypeName; } } } /// <inheritdoc /> public override void Accept(IRtVisitor visitor) { visitor.Visit(this); } /// <inheritdoc /> public override void Accept<T>(IRtVisitor<T> visitor) { visitor.Visit(this); } /// <inheritdoc /> public override string ToString() { return $"[{string.Join(", ", TupleTypes)}]"; } } }
using System.Collections.Generic; namespace Reinforced.Typings.Ast.TypeNames { /// <summary> /// AST node for TypeScript tuple type /// </summary> public class RtTuple : RtTypeName { /// <summary> /// Constructs new RtTuple /// </summary> public RtTuple() { TupleTypes = new List<RtTypeName>(); } /// <summary> /// Constructs new RtTuple with specified type paranmeters /// </summary> /// <param name="tupleTypes">Types for tuple</param> public RtTuple(IEnumerable<RtTypeName> tupleTypes) { TupleTypes = new List<RtTypeName>(tupleTypes); } /// <summary> /// Constructs new RtTuple with specified type paranmeters /// </summary> /// <param name="tupleTypes">Types for tuple</param> public RtTuple(params RtTypeName[] tupleTypes) { TupleTypes = new List<RtTypeName>(tupleTypes); } /// <summary> /// All types that must participate tuple /// </summary> public List<RtTypeName> TupleTypes { get; private set; } /// <inheritdoc /> public override IEnumerable<RtNode> Children { get { foreach (var rtTypeName in TupleTypes) { yield return rtTypeName; } } } /// <inheritdoc /> public override void Accept(IRtVisitor visitor) { visitor.Visit(this); } /// <inheritdoc /> public override void Accept<T>(IRtVisitor<T> visitor) { visitor.Visit(this); } } }
mit
C#
8501bb17f315a854306ab2a6d33a79df21202fb8
change version of the assembly
icanos/SMAStudio
SMAStudio/Properties/AssemblyInfo.cs
SMAStudio/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; [assembly: log4net.Config.XmlConfigurator(Watch = true)] // 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("SMA Studio 2014")] [assembly: AssemblyDescription("Tool for managing a SMA environment.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Marcus Westin")] [assembly: AssemblyProduct("SMAStudio")] [assembly: AssemblyCopyright("Copyright © Marcus Westin 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.0.2.0")] [assembly: AssemblyFileVersion("0.0.2.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; [assembly: log4net.Config.XmlConfigurator(Watch = true)] // 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("SMA Studio 2014")] [assembly: AssemblyDescription("Tool for managing a SMA environment.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Marcus Westin")] [assembly: AssemblyProduct("SMAStudio")] [assembly: AssemblyCopyright("Copyright © Marcus Westin 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.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
770ec2ac38fc311e16f46f669f50c7966f5a3e98
remove limit
nukedbit/nukedbit-mvvm
NukedBit.Mvvm.DI.AutoFac/AutoFacExtensions.cs
NukedBit.Mvvm.DI.AutoFac/AutoFacExtensions.cs
using Autofac.Builder; using NukedBit.Mvvm.Views; namespace NukedBit.Mvvm.DI.AutoFac { public static class AutoFacExtensions { public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> AsView<TLimit, TActivatorData, TRegistrationStyle>(this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> dep) where TLimit: class { return dep.Named<IView>(typeof (TLimit).Name); } } }
using Autofac.Builder; using NukedBit.Mvvm.Views; namespace NukedBit.Mvvm.DI.AutoFac { public static class AutoFacExtensions { public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> AsView<TLimit, TActivatorData, TRegistrationStyle>(this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> dep) where TLimit: IView { return dep.Named<IView>(typeof (TLimit).Name) .As<IView>(); } } }
apache-2.0
C#
9e171f34f35b6634e4c1b4c1f0637711672eeab0
Use TestCases
ddaspit/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,tombogle/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,ermshiperete/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso
Palaso.Tests/Email/LinuxEmailProviderTests.cs
Palaso.Tests/Email/LinuxEmailProviderTests.cs
using System; using NUnit.Framework; using Palaso.Email; namespace Palaso.Tests.Email { [TestFixture] public class LinuxEmailProviderTests { // Does not change most things. [TestCase(@"hello1234 hello", Result =@"hello1234 hello")] [TestCase("hello\"hello", Result ="hello\"hello")] [TestCase(@"hello`~!@#$%^&*)(][}{/?=+-_|", Result =@"hello`~!@#$%^&*)(][}{/?=+-_|")] // Escapes quote and backslash characters. [TestCase(@"\", Result =@"\\\\\\\\")] [TestCase(@"hello\hello", Result =@"hello\\\\\\\\hello")] [TestCase(@"hello\t\n\a\r\0end", Result =@"hello\\\\\\\\t\\\\\\\\n\\\\\\\\a\\\\\\\\r\\\\\\\\0end")] [TestCase(@"hello'hello", Result =@"hello\'hello")] [TestCase(@"hello'hello'", Result =@"hello\'hello\'")] [TestCase("hello'\"hello", Result ="hello\\'\"hello")] [TestCase(@"C:\'Data\0end", Result =@"C:\\\\\\\\\'Data\\\\\\\\0end")] public string EscapeString(string input) { return LinuxEmailProvider.EscapeString(input); } } }
using System; using NUnit.Framework; using Palaso.Email; namespace Palaso.Tests.Email { [TestFixture] public class LinuxEmailProviderTests { [Test] public void EscapeString() { string input; // Does not change most things. input = @"hello1234 hello"; Assert.That(LinuxEmailProvider.EscapeString(input), Is.EqualTo(input)); input = "hello\"hello"; Assert.That(LinuxEmailProvider.EscapeString(input), Is.EqualTo(input)); input = @"hello`~!@#$%^&*)(][}{/?=+-_|"; Assert.That(LinuxEmailProvider.EscapeString(input), Is.EqualTo(input)); // Escapes quote and backslash characters. Assert.That(LinuxEmailProvider.EscapeString(@"\"), Is.EqualTo(@"\\\\\\\\")); Assert.That(LinuxEmailProvider.EscapeString(@"hello\hello"), Is.EqualTo(@"hello\\\\\\\\hello")); Assert.That(LinuxEmailProvider.EscapeString(@"hello\t\n\a\r\0end"), Is.EqualTo(@"hello\\\\\\\\t\\\\\\\\n\\\\\\\\a\\\\\\\\r\\\\\\\\0end")); Assert.That(LinuxEmailProvider.EscapeString(@"hello'hello"), Is.EqualTo(@"hello\'hello")); Assert.That(LinuxEmailProvider.EscapeString(@"hello'hello'"), Is.EqualTo(@"hello\'hello\'")); Assert.That(LinuxEmailProvider.EscapeString("hello'\"hello"), Is.EqualTo("hello\\'\"hello")); Assert.That(LinuxEmailProvider.EscapeString(@"C:\'Data\0end"), Is.EqualTo(@"C:\\\\\\\\\'Data\\\\\\\\0end")); } } }
mit
C#
f998ca1f25cf0847a7c863de4e8bea8c66e376b4
Remove optional custom object-text mapper.
chasingbob/embark,ideaflare/embark,ubrgw/embark
Embark/Server.cs
Embark/Server.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Web; using System.Text; using System.Threading.Tasks; using Embark.Storage; using Embark.Conversion; using Embark.Interfaces; namespace Embark { /// <summary> /// Server that has a TextFileRepository who's commands get invoked by remote Clients /// </summary> public sealed class Server : IDisposable { /// <summary> /// Host a new network server /// </summary> /// <param name="directory">directory server will save data to. If null default set to C:\MyTemp\Embark\Server\</param> /// <param name="port">port to use, default set to 8080</param> public Server(string directory = null, int port = 8080) { if (directory == null) directory = @"C:\MyTemp\Embark\Server\"; ITextConverter textConverter = new JavascriptSerializerConverter(); var textRepository = new TextFileRepository(directory, textConverter); Uri url = new Uri("http://localhost:" + port + "/embark/"); webHost = new WebServiceHost(textRepository, url); } private WebServiceHost webHost; /// <summary> /// Open the web host of the server /// </summary> public void Start() { webHost.Open(); } /// <summary> /// Close the server web host /// </summary> public void Stop() { webHost.Close(); } /// <summary> /// Dispose the web host /// </summary> public void Dispose() { ((IDisposable)webHost).Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Web; using System.Text; using System.Threading.Tasks; using Embark.Storage; using Embark.Conversion; using Embark.Interfaces; namespace Embark { /// <summary> /// Server that has a TextFileRepository who's commands get invoked by remote Clients /// </summary> public sealed class Server : IDisposable { /// <summary> /// Host a new network server /// </summary> /// <param name="directory">directory server will save data to. If null default set to C:\MyTemp\Embark\Server\</param> /// <param name="port">port to use, default set to 8080</param> /// <param name="textConverter">Custom ITextconverter to use on Clients and Server should be the same, default uses .NET JSON JasaScriptSerializer</param> public Server(string directory = null, int port = 8080, ITextConverter textConverter = null) { if (directory == null) directory = @"C:\MyTemp\Embark\Server\"; if (textConverter == null) textConverter = new JavascriptSerializerConverter(); var textRepository = new TextFileRepository(directory, textConverter); Uri url = new Uri("http://localhost:" + port + "/embark/"); webHost = new WebServiceHost(textRepository, url); } private WebServiceHost webHost; /// <summary> /// Open the web host of the server /// </summary> public void Start() { webHost.Open(); } /// <summary> /// Close the server web host /// </summary> public void Stop() { webHost.Close(); } /// <summary> /// Dispose the web host /// </summary> public void Dispose() { ((IDisposable)webHost).Dispose(); } } }
mit
C#
ce75cfbe1d197ef18408e68b329776e607968062
Remove incorrect mixer setting in AudioManager
NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare
Assets/Scripts/Global/AudioManager.cs
Assets/Scripts/Global/AudioManager.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; public class AudioManager : MonoBehaviour { public static AudioManager instance; [SerializeField] private AudioMixer masterMixer; public AudioMixer MasterMixer => masterMixer; [SerializeField] private AudioMixer gameplayMixer; public AudioMixer GameplayMixer => gameplayMixer; [SerializeField] private AudioMixer microgameMixer; public AudioMixer MicrogameMixer => microgameMixer; // Needed until we clean up legacy uses of AudioAutoAdjust [SerializeField] private AudioMixerGroup microgameSFXGroup; public AudioMixerGroup MicrogameSFXGroup => microgameSFXGroup; [SerializeField] private AudioMixerGroup microgameMusicGroup; public AudioMixerGroup MicrogameMusicGroup => microgameMusicGroup; private void Awake() { instance = this; foreach (PrefsHelper.VolumeType volumeType in Enum.GetValues(typeof(PrefsHelper.VolumeType))) { SetVolume(volumeType, PrefsHelper.GetVolumeSetting(volumeType)); } } public void SetVolume(PrefsHelper.VolumeType volumeType, float volumeLevel) { var dbLevel = AudioHelper.VolumeLevelToDecibals(volumeLevel); switch(volumeType) { case (PrefsHelper.VolumeType.Master): masterMixer.SetFloat("MasterVolume", dbLevel); break; case (PrefsHelper.VolumeType.Music): masterMixer.SetFloat("MusicVolume", dbLevel); gameplayMixer.SetFloat("MusicVolume", dbLevel); microgameMixer.SetFloat("MusicVolume", dbLevel); break; case (PrefsHelper.VolumeType.SFX): masterMixer.SetFloat("SFXVolume", dbLevel); gameplayMixer.SetFloat("SFXVolume", dbLevel); microgameMixer.SetFloat("SFXVolume", dbLevel); break; case (PrefsHelper.VolumeType.Voice): masterMixer.SetFloat("VoiceVolume", dbLevel); gameplayMixer.SetFloat("VoiceVolume", dbLevel); break; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; public class AudioManager : MonoBehaviour { public static AudioManager instance; [SerializeField] private AudioMixer masterMixer; public AudioMixer MasterMixer => masterMixer; [SerializeField] private AudioMixer gameplayMixer; public AudioMixer GameplayMixer => gameplayMixer; [SerializeField] private AudioMixer microgameMixer; public AudioMixer MicrogameMixer => microgameMixer; // Needed until we clean up legacy uses of AudioAutoAdjust [SerializeField] private AudioMixerGroup microgameSFXGroup; public AudioMixerGroup MicrogameSFXGroup => microgameSFXGroup; [SerializeField] private AudioMixerGroup microgameMusicGroup; public AudioMixerGroup MicrogameMusicGroup => microgameMusicGroup; private void Awake() { instance = this; foreach (PrefsHelper.VolumeType volumeType in Enum.GetValues(typeof(PrefsHelper.VolumeType))) { SetVolume(volumeType, PrefsHelper.GetVolumeSetting(volumeType)); } } public void SetVolume(PrefsHelper.VolumeType volumeType, float volumeLevel) { var dbLevel = AudioHelper.VolumeLevelToDecibals(volumeLevel); switch(volumeType) { case (PrefsHelper.VolumeType.Master): masterMixer.SetFloat("MasterVolume", dbLevel); break; case (PrefsHelper.VolumeType.Music): masterMixer.SetFloat("MusicVolume", dbLevel); gameplayMixer.SetFloat("MusicVolume", dbLevel); microgameMixer.SetFloat("MusicVolume", dbLevel); break; case (PrefsHelper.VolumeType.SFX): masterMixer.SetFloat("SFXVolume", dbLevel); gameplayMixer.SetFloat("SFXVolume", dbLevel); microgameMixer.SetFloat("SFXVolume", dbLevel); break; case (PrefsHelper.VolumeType.Voice): masterMixer.SetFloat("VoiceVolume", dbLevel); gameplayMixer.SetFloat("VoiceVolume", dbLevel); microgameMixer.SetFloat("VoiceVolume", dbLevel); break; } } }
mit
C#
5ecadcce178cf8a6064c3843bd5a7ed21adba2f9
clean up unused usings
EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an
A-vs-An/AvsAn-Test/StandardCasesWork.cs
A-vs-An/AvsAn-Test/StandardCasesWork.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AvsAnLib; using ExpressionToCodeLib; using NUnit.Framework; namespace AvsAn_Test { public class StandardCasesWork { [TestCase("an", "unanticipated result")] [TestCase("a", "unanimous vote")] [TestCase("an", "honest decision")] [TestCase("a", "honeysuckle shrub")] [TestCase("an", "0800 number")] [TestCase("an", "∞ of oregano")] [TestCase("a", "NASA scientist")] [TestCase("an", "NSA analyst")] [TestCase("a", "FIAT car")] [TestCase("an", "FAA policy")] [TestCase("an", "A")] public void DoTest(string article, string word) { PAssert.That(() => AvsAn.Query(word).Article == article); } [TestCase("a", "", "")] [TestCase("a", "'", "'")] [TestCase("an", "N", "N ")] [TestCase("a", "NASA", "NAS")] public void CheckOddPrefixes(string article, string word, string prefix) { PAssert.That(() => AvsAn.Query(word).Article == article && AvsAn.Query(word).Prefix == prefix); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AvsAnLib; using ExpressionToCodeLib; using NUnit.Framework; namespace AvsAn_Test { public class StandardCasesWork { [TestCase("an", "unanticipated result")] [TestCase("a", "unanimous vote")] [TestCase("an", "honest decision")] [TestCase("a", "honeysuckle shrub")] [TestCase("an", "0800 number")] [TestCase("an", "∞ of oregano")] [TestCase("a", "NASA scientist")] [TestCase("an", "NSA analyst")] [TestCase("a", "FIAT car")] [TestCase("an", "FAA policy")] [TestCase("an", "A")] public void DoTest(string article, string word) { PAssert.That(() => AvsAn.Query(word).Article == article); } [TestCase("a", "", "")] [TestCase("a", "'", "'")] [TestCase("an", "N", "N ")] [TestCase("a", "NASA", "NAS")] public void CheckOddPrefixes(string article, string word, string prefix) { PAssert.That(() => AvsAn.Query(word).Article == article && AvsAn.Query(word).Prefix == prefix); } } }
apache-2.0
C#
486efe9611345b9f86951b57916d9158ee7482e3
fix : remove Itab injection and resize
AlcoholV/Rim.AcEnhancedCrafting
AcEnhancedCrafting.cs
AcEnhancedCrafting.cs
using System.Linq; using System.Reflection; using AlcoholV.Detouring; using Verse; namespace AlcoholV { [StaticConstructorOnStartup] public class AcEnhancedCrafting { private static readonly BindingFlags[] BindingFlagCombos = { BindingFlags.Instance | BindingFlags.Public, BindingFlags.Static | BindingFlags.Public, BindingFlags.Instance | BindingFlags.NonPublic, BindingFlags.Static | BindingFlags.NonPublic }; static AcEnhancedCrafting() { LongEventHandler.QueueLongEvent(Inject, "Initializing", true, null); } public static Assembly Assembly => Assembly.GetAssembly(typeof(AcEnhancedCrafting)); public static string AssemblyName => Assembly.FullName.Split(',').First(); private static void Inject() { #region Automatic hookup // Loop through all detour attributes and try to hook them up foreach (var targetType in Assembly.GetTypes()) foreach (var bindingFlags in BindingFlagCombos) foreach (var targetMethod in targetType.GetMethods(bindingFlags)) foreach (DetourAttribute detour in targetMethod.GetCustomAttributes(typeof(DetourAttribute), true)) { var flags = detour.bindingFlags != default(BindingFlags) ? detour.bindingFlags : bindingFlags; var sourceMethod = detour.source.GetMethod(targetMethod.Name, flags); if (sourceMethod == null) Log.Error(string.Format(AssemblyName + " Can't find source method {0} with bindingflags {1}", targetMethod.Name, flags)); if (!Detours.TryDetourFromTo(sourceMethod, targetMethod)) Log.Message(AssemblyName + " Failed to get injected properly."); } #endregion Log.Message(AssemblyName + " injected."); } } }
using System.Linq; using System.Reflection; using AlcoholV.Detouring; using Verse; namespace AlcoholV { [StaticConstructorOnStartup] public class AcEnhancedCrafting { private static readonly BindingFlags[] BindingFlagCombos = { BindingFlags.Instance | BindingFlags.Public, BindingFlags.Static | BindingFlags.Public, BindingFlags.Instance | BindingFlags.NonPublic, BindingFlags.Static | BindingFlags.NonPublic }; static AcEnhancedCrafting() { LongEventHandler.QueueLongEvent(Inject, "Initializing", true, null); } public static Assembly Assembly => Assembly.GetAssembly(typeof(AcEnhancedCrafting)); public static string AssemblyName => Assembly.FullName.Split(',').First(); private static void Inject() { #region Automatic hookup // Loop through all detour attributes and try to hook them up foreach (var targetType in Assembly.GetTypes()) foreach (var bindingFlags in BindingFlagCombos) foreach (var targetMethod in targetType.GetMethods(bindingFlags)) foreach (DetourAttribute detour in targetMethod.GetCustomAttributes(typeof(DetourAttribute), true)) { var flags = detour.bindingFlags != default(BindingFlags) ? detour.bindingFlags : bindingFlags; var sourceMethod = detour.source.GetMethod(targetMethod.Name, flags); if (sourceMethod == null) Log.Error(string.Format(AssemblyName + " Can't find source method {0} with bindingflags {1}", targetMethod.Name, flags)); if (!Detours.TryDetourFromTo(sourceMethod, targetMethod)) Log.Message(AssemblyName + " Failed to get injected properly."); } #endregion //InjectTab(typeof(ITab_Bills), typeof(Detouring.ITab_Bills)); Log.Message(AssemblyName + " injected."); } // foreach (var def in defs) // defs.RemoveDuplicates(); // var defs = DefDatabase<ThingDef>.AllDefs.Where(c => (c.inspectorTabs != null) && c.inspectorTabs.Contains(source)).ToList(); //{ //private static void InjectTab(Type source, Type dest) // { // def.inspectorTabs.Remove(source); // def.inspectorTabs.Add(dest); // def.inspectorTabsResolved.Remove(InspectTabManager.GetSharedInstance(source)); // def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(dest)); // } //} } }
mit
C#
176de4301fbcc3cd28ed3b224faa256353f49cd7
Revert "test"
dannyhicco/survival-shooter,dannyhicco/survival-shooter
Assets/Scripts/Managers/ScoreManager.cs
Assets/Scripts/Managers/ScoreManager.cs
using UnityEngine; using UnityEngine.UI; using System.Collections; public class ScoreManager : MonoBehaviour { public static int score; Text text; void Awake () { text = GetComponent <Text> (); score = 0; } void Update () { text.text = "Score: " + score; } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class ScoreManager : MonoBehaviour { public static int score; Text text; void Awake () { text = GetComponent <Text> (); score = 0; } void Update () { text.text = "Score: " + score " And james sucks"; } }
mit
C#
55bf78c71e0debe143b1b8cdc55135148fd0ec08
Add the to be implemented interface to MRect2
charlenni/Mapsui,charlenni/Mapsui
Mapsui/MRect2.cs
Mapsui/MRect2.cs
namespace Mapsui; public class MRect2 { //double Bottom { get; } //MPoint BottomLeft { get; } //MPoint BottomRight { get; } //MPoint Centroid { get; } //double Height { get; } //double Left { get; } //MPoint Max { get; set; } //double MaxX { get; } //double MaxY { get; } //MPoint Min { get; set; } //double MinX { get; } //double MinY { get; } //double Right { get; } //double Top { get; } //MPoint TopLeft { get; } //MPoint TopRight { get; } //IEnumerable<MPoint> Vertices { get; } //double Width { get; } //MRect Clone(); //bool Contains(MPoint? p); //bool Contains(MRect r); //bool Equals(MRect? other); //double GetArea(); //MRect Grow(double amount); //MRect Grow(double amountInX, double amountInY); //bool Intersects(MRect? box); //MRect Join(MRect? box); //MRect Multiply(double factor); //MQuad Rotate(double degrees); }
namespace Mapsui; public class MRect2 { }
mit
C#
63b76c0f66ebff4fe9ab9b806141927f775f8764
Add score controller to GameMenu
lupidan/Tetris
Assets/Scripts/UI/GameMenu.cs
Assets/Scripts/UI/GameMenu.cs
using UnityEngine; using UnityEngine.UI; public class GameMenu : MonoBehaviour { [SerializeField] private Text _scoreLabel; [SerializeField] private Text _highscoreLabel; private IGameController _gameController; private ScoreController _scoreController; #region MonoBehaviour private void OnEnable() { SetDisplayedScore(0); SetDisplayedHighscore(1000); } private void Start() { _scoreController.OnScoreUpdate += SetDisplayedScore; _scoreController.OnHighscoreUpdate += SetDisplayedHighscore; } private void OnDestroy() { _scoreController.OnScoreUpdate -= SetDisplayedScore; _scoreController.OnHighscoreUpdate -= SetDisplayedHighscore; } #endregion #region Public methods public void Initialize(IGameController gameController, ScoreController scoreController) { this._gameController = gameController; this._scoreController = scoreController; } public void SetDisplayedScore(long score) { SetScoreLabel(_scoreLabel, score); } public void SetDisplayedHighscore(long highscore) { SetScoreLabel(_highscoreLabel, highscore); } #endregion #region Button actions public void RestartButtonWasSelected() { _gameController.RestartGame(); } #endregion #region Private methods private void SetScoreLabel(Text label, long score) { label.text = score.ToString("00000000"); } #endregion }
using UnityEngine; using UnityEngine.UI; public class GameMenu : MonoBehaviour { [SerializeField] private Text _scoreLabel; [SerializeField] private Text _highscoreLabel; private IGameController gameController; #region MonoBehaviour private void OnEnable() { SetDisplayedScore(0); SetDisplayedHighscore(1000); } #endregion #region Public methods public void Initialize(IGameController gameController) { this.gameController = gameController; } public void SetDisplayedScore(long score) { SetScoreLabel(_scoreLabel, score); } public void SetDisplayedHighscore(long highscore) { SetScoreLabel(_highscoreLabel, highscore); } #endregion #region Button actions public void RestartButtonWasSelected() { gameController.RestartGame(); } #endregion #region Private methods private void SetScoreLabel(Text label, long score) { label.text = score.ToString("00000000"); } #endregion }
mit
C#
763edf3b8e173221c36cb11901f5a3a598382118
Send notifications during versioned component installs
QuantConnect/Lean,kaffeebrauer/Lean,Jay-Jay-D/LeanSTP,andrewhart098/Lean,FrancisGauthier/Lean,devalkeralia/Lean,squideyes/Lean,tomhunter-gh/Lean,Jay-Jay-D/LeanSTP,andrewhart098/Lean,Obawoba/Lean,StefanoRaggi/Lean,Mendelone/forex_trading,AnshulYADAV007/Lean,andrewhart098/Lean,Jay-Jay-D/LeanSTP,young-zhang/Lean,squideyes/Lean,AnObfuscator/Lean,redmeros/Lean,AnObfuscator/Lean,squideyes/Lean,kaffeebrauer/Lean,kaffeebrauer/Lean,JKarathiya/Lean,Obawoba/Lean,young-zhang/Lean,AnObfuscator/Lean,Mendelone/forex_trading,JKarathiya/Lean,jameschch/Lean,jameschch/Lean,StefanoRaggi/Lean,redmeros/Lean,Jay-Jay-D/LeanSTP,StefanoRaggi/Lean,mabeale/Lean,JKarathiya/Lean,bizcad/Lean,young-zhang/Lean,devalkeralia/Lean,FrancisGauthier/Lean,AnshulYADAV007/Lean,redmeros/Lean,AlexCatarino/Lean,squideyes/Lean,jameschch/Lean,StefanoRaggi/Lean,Mendelone/forex_trading,mabeale/Lean,AlexCatarino/Lean,redmeros/Lean,andrewhart098/Lean,bizcad/Lean,FrancisGauthier/Lean,QuantConnect/Lean,AnshulYADAV007/Lean,tomhunter-gh/Lean,AlexCatarino/Lean,young-zhang/Lean,bizcad/Lean,StefanoRaggi/Lean,tomhunter-gh/Lean,Mendelone/forex_trading,Obawoba/Lean,bizcad/Lean,AnObfuscator/Lean,JKarathiya/Lean,jameschch/Lean,QuantConnect/Lean,mabeale/Lean,Jay-Jay-D/LeanSTP,AnshulYADAV007/Lean,mabeale/Lean,Phoenix1271/Lean,Phoenix1271/Lean,AlexCatarino/Lean,jameschch/Lean,Obawoba/Lean,Phoenix1271/Lean,devalkeralia/Lean,AnshulYADAV007/Lean,FrancisGauthier/Lean,QuantConnect/Lean,Phoenix1271/Lean,kaffeebrauer/Lean,tomhunter-gh/Lean,kaffeebrauer/Lean,devalkeralia/Lean
Common/Packets/DebugPacket.cs
Common/Packets/DebugPacket.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using Newtonsoft.Json; namespace QuantConnect.Packets { /// <summary> /// Send a simple debug message from the users algorithm to the console. /// </summary> public class DebugPacket : Packet { /// <summary> /// String debug message to send to the users console /// </summary> [JsonProperty(PropertyName = "sMessage")] public string Message; /// <summary> /// Associated algorithm Id. /// </summary> [JsonProperty(PropertyName = "sAlgorithmID")] public string AlgorithmId; /// <summary> /// Compile id of the algorithm sending this message /// </summary> [JsonProperty(PropertyName = "sCompileID")] public string CompileId; /// <summary> /// Project Id for this message /// </summary> [JsonProperty(PropertyName = "iProjectID")] public int ProjectId; /// <summary> /// True to emit message as a popup notification (toast), /// false to emit message in console as text /// </summary> [JsonProperty(PropertyName = "bToast")] public bool Toast; /// <summary> /// Default constructor for JSON /// </summary> public DebugPacket() : base (PacketType.Debug) { } /// <summary> /// Create a new instance of the notify debug packet: /// </summary> public DebugPacket(int projectId, string algorithmId, string compileId, string message, bool toast = false) : base(PacketType.Debug) { ProjectId = projectId; Message = message; CompileId = compileId; AlgorithmId = algorithmId; Toast = toast; } } // End Work Packet: } // End of Namespace:
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using Newtonsoft.Json; namespace QuantConnect.Packets { /// <summary> /// Send a simple debug message from the users algorithm to the console. /// </summary> public class DebugPacket : Packet { /// <summary> /// String debug message to send to the users console /// </summary> [JsonProperty(PropertyName = "sMessage")] public string Message; /// <summary> /// Associated algorithm Id. /// </summary> [JsonProperty(PropertyName = "sAlgorithmID")] public string AlgorithmId; /// <summary> /// Compile id of the algorithm sending this message /// </summary> [JsonProperty(PropertyName = "sCompileID")] public string CompileId; /// <summary> /// Project Id for this message /// </summary> [JsonProperty(PropertyName = "iProjectID")] public int ProjectId; /// <summary> /// Default constructor for JSON /// </summary> public DebugPacket() : base (PacketType.Debug) { } /// <summary> /// Create a new instance of the notify debug packet: /// </summary> public DebugPacket(int projectId, string algorithmId, string compileId, string message) : base(PacketType.Debug) { ProjectId = projectId; Message = message; CompileId = compileId; AlgorithmId = algorithmId; } } // End Work Packet: } // End of Namespace:
apache-2.0
C#
e4a456832f61c0a00209c92b7ec95fc464590524
Fix to make path independant to the version
zr40/kyru-dotnet,zr40/kyru-dotnet
Kyru/Core/Config.cs
Kyru/Core/Config.cs
using System; using System.IO; namespace Kyru.Core { internal sealed class Config { internal string storeDirectory; internal Config() { storeDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Kyru", "objects"); } } }
using System; using System.IO; namespace Kyru.Core { internal sealed class Config { internal string storeDirectory; internal Config() { storeDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Kyru", "objects"); } } }
bsd-3-clause
C#
833a7286501aa3e4705a4671f791fceff9c93e21
Revert Parcel to old version to avoid breaking existing clients
goshippo/shippo-csharp-client
Shippo/Parcel.cs
Shippo/Parcel.cs
using System; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Parcel : ShippoId { [JsonProperty (PropertyName = "object_state")] public object ObjectState { get; set; } [JsonProperty (PropertyName = "object_created")] public object ObjectCreated { get; set; } [JsonProperty (PropertyName = "object_updated")] public object ObjectUpdaed { get; set; } [JsonProperty (PropertyName = "object_owner")] public object ObjectOwner { get; set; } [JsonProperty (PropertyName = "length")] public object Length { get; set; } [JsonProperty (PropertyName = "width")] public object Width { get; set; } [JsonProperty (PropertyName = "height")] public object Height { get; set; } [JsonProperty (PropertyName = "distance_unit")] public object DistanceUnit { get; set; } [JsonProperty (PropertyName = "weight")] public object Weight { get; set; } [JsonProperty (PropertyName = "mass_unit")] public object MassUnit { get; set; } [JsonProperty (PropertyName = "template")] public string Template; [JsonProperty (PropertyName = "metadata")] public object Metadata { get; set; } [JsonProperty (PropertyName = "extra")] public object Extra; [JsonProperty (PropertyName = "test")] public bool? Test; } }
using System; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Parcel : ShippoId { [JsonProperty (PropertyName = "object_state")] public string ObjectState; [JsonProperty (PropertyName = "object_created")] public DateTime? ObjectCreated; [JsonProperty (PropertyName = "object_updated")] public DateTime? ObjectUpdaed; [JsonProperty (PropertyName = "object_owner")] public string ObjectOwner; [JsonProperty (PropertyName = "length")] public double Length; [JsonProperty (PropertyName = "width")] public double Width; [JsonProperty (PropertyName = "height")] public double Height; [JsonProperty (PropertyName = "distance_unit")] public string DistanceUnit; [JsonProperty (PropertyName = "weight")] public double Weight; [JsonProperty (PropertyName = "mass_unit")] public string MassUnit; [JsonProperty (PropertyName = "template")] public string Template; [JsonProperty (PropertyName = "metadata")] public string Metadata; [JsonProperty (PropertyName = "extra")] public object Extra; [JsonProperty (PropertyName = "test")] public bool Test; } }
apache-2.0
C#
db2c64bde05226a17b33429c345b8a814771a304
Make TypeNameMatcher generic
appharbor/appharbor-cli
src/AppHarbor/TypeNameMatcher.cs
src/AppHarbor/TypeNameMatcher.cs
using System; using System.Collections.Generic; namespace AppHarbor { public class TypeNameMatcher<T> { private readonly IEnumerable<Type> _candidateTypes; public TypeNameMatcher(IEnumerable<Type> candidateTypes) { _candidateTypes = candidateTypes; } } }
using System; using System.Collections.Generic; namespace AppHarbor { public class TypeNameMatcher { private readonly IEnumerable<Type> _candidateTypes; public TypeNameMatcher(IEnumerable<Type> candidateTypes) { _candidateTypes = candidateTypes; } } }
mit
C#
c4a16beebf0425af25d98fd43ef326177b3f97c1
Add a synchronized RxProperty factory method.
bordoley/RxApp
RxApp/RxProperty.cs
RxApp/RxProperty.cs
using System; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; namespace RxApp { public interface IRxProperty<T> : IObservable<T> { T Value { get; set; } } public static class RxProperty { public static IRxProperty<T> Create<T>(T initialValue) { var subject = new BehaviorSubject<T>(initialValue); return new RxPropertyImpl<T>(subject); } public IRxProperty<T> CreateSynchronized<T>(T initialValue) { var subject = new BehaviorSubject<T>(initialValue).Synchronize(); return new RxPropertyImpl<T>(subject); } private class RxPropertyImpl<T> : IRxProperty<T> { private readonly BehaviorSubject<T> setValues; private readonly IObservable<T> values; internal RxPropertyImpl(BehaviorSubject<T> setValues) { this.setValues = setValues; this.values = this.setValues.DistinctUntilChanged(); } public T Value { get { return setValues.Value; } set { setValues.OnNext(value); } } public IDisposable Subscribe(IObserver<T> observer) { return values.Subscribe(observer); } public override string ToString() { return string.Format("[RxPropertyImpl: Value={0}]", this.setValues.Value); } } } }
using System; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; namespace RxApp { public interface IRxProperty<T> : IObservable<T> { T Value { set; } } public static class RxProperty { public static IRxProperty<T> Create<T>(T initialValue) { return new RxPropertyImpl<T>(initialValue); } private class RxPropertyImpl<T> : IRxProperty<T> { private readonly BehaviorSubject<T> setValues; private readonly IObservable<T> values; internal RxPropertyImpl(T initialValue) { this.setValues = new BehaviorSubject<T>(initialValue); this.values = this.setValues.DistinctUntilChanged(); } public T Value { set { setValues.OnNext(value); } } public IDisposable Subscribe(IObserver<T> observer) { return values.Subscribe(observer); } public override string ToString() { // Behavior subject caches its most recent value so i think this is safe from deadlocks. Need to test. return string.Format("[RxPropertyImpl: Value={0}]", this.values.FirstAsync().Wait()); } } } }
apache-2.0
C#
244f6e7f84897ad73619c863cb1013c293ff679a
Update ObservableResource.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/ObservableResource.cs
src/Core2D/ObservableResource.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; using Core2D.Attributes; namespace Core2D { /// <summary> /// Observable resources base class. /// </summary> public abstract class ObservableResource : ObservableObject { private ImmutableArray<ObservableObject> _resources; /// <summary> /// Initializes a new instance of the <see cref="ObservableResource"/> class. /// </summary> public ObservableResource() : base() => Resources = ImmutableArray.Create<ObservableObject>(); /// <summary> /// Gets or sets shape resources. /// </summary> [Content] public ImmutableArray<ObservableObject> Resources { get => _resources; set => Update(ref _resources, value); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; using Core2D.Attributes; namespace Core2D { /// <summary> /// Observable resources base class. /// </summary> public abstract class ObservableResource : ObservableObject { private ImmutableArray<ObservableObject> _resources; /// <summary> /// Initializes a new instance of the <see cref="ObservableResource"/> class. /// </summary> public ObservableResource() : base() { Resources = ImmutableArray.Create<ObservableObject>(); } /// <summary> /// Gets or sets shape resources. /// </summary> [Content] public ImmutableArray<ObservableObject> Resources { get { return _resources; } set { Update(ref _resources, value); } } } }
mit
C#
fda39de66bd3608b5c227f2165e8784beea45503
fix namespace
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Agent/Program.cs
src/FilterLists.Agent/Program.cs
using System; using System.Threading.Tasks; using FilterLists.Agent.Extensions; using FilterLists.Agent.Features.Lists; using MediatR; using Microsoft.Extensions.DependencyInjection; namespace FilterLists.Agent { public static class Program { private static IServiceProvider _serviceProvider; public static async Task Main() { BuildServiceProvider(); var mediator = _serviceProvider.GetService<IMediator>(); await mediator.Send(new CaptureLists.Command()); } private static void BuildServiceProvider() { var serviceCollection = new ServiceCollection(); serviceCollection.RegisterAgentServices(); _serviceProvider = serviceCollection.BuildServiceProvider(); } } }
using System; using System.Threading.Tasks; using FilterLists.Agent.Extensions; using FilterLists.Agent.Features.Archiver; using MediatR; using Microsoft.Extensions.DependencyInjection; namespace FilterLists.Agent { public static class Program { private static IServiceProvider _serviceProvider; public static async Task Main() { BuildServiceProvider(); var mediator = _serviceProvider.GetService<IMediator>(); await mediator.Send(new CaptureLists.Command()); } private static void BuildServiceProvider() { var serviceCollection = new ServiceCollection(); serviceCollection.RegisterAgentServices(); _serviceProvider = serviceCollection.BuildServiceProvider(); } } }
mit
C#
271fe5f303281420ce1765cca0c69026104ab8eb
stop overwriting the parameter
hibri/HttpMock,mattolenik/HttpMock,oschwald/HttpMock,zhdusurfin/HttpMock
src/HttpMock/RequestProcessor.cs
src/HttpMock/RequestProcessor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using Kayak; using Kayak.Http; namespace HttpMock { public class RequestProcessor : IHttpRequestDelegate { private readonly string _applicationPath; private Dictionary<string, RequestHandler> _handlers; public RequestProcessor(Uri appBaseUri) { _applicationPath = appBaseUri.AbsolutePath; } public void OnRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response) { string pathToMatch = request.Uri.Remove(request.Uri.IndexOf(_applicationPath, 0), _applicationPath.Length); RequestHandler handler = _handlers.Where(x => x.Key.Equals(pathToMatch)).FirstOrDefault().Value; if (handler != null) { var headers = handler.ResponseBuilder.BuildHeaders(); var responseBody = handler.ResponseBuilder.BuildBody(); response.OnResponse(headers, responseBody); } else { HttpResponseHead headers; var responseBody = GetNotStubbedResponse(request, out headers); response.OnResponse(headers, responseBody); } } public RequestHandler Get(string path) { var requestHandler = new RequestHandler(path, this); return requestHandler; } public void ClearHandlers() { _handlers = new Dictionary<string, RequestHandler>(); } public void Add(RequestHandler requestHandler, HttpStatusCode httpStatusCode) { requestHandler.ResponseBuilder.WithStatus(httpStatusCode); _handlers.Add(requestHandler.Path, requestHandler); } private IDataProducer GetNotStubbedResponse(HttpRequestHead request, out HttpResponseHead headers) { IDataProducer body; string data = string.Format("{0} : Not Stubbed", request.Uri); headers = new HttpResponseHead { Status = string.Format("404 {0} Not Stubbed", request.Uri), Headers = new Dictionary<string, string> { {"Content-Type", "text/plain"}, {"Content-Length", data.Length.ToString()}, } }; body = new BufferedBody(data); return body; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using Kayak; using Kayak.Http; namespace HttpMock { public class RequestProcessor : IHttpRequestDelegate { private readonly string _applicationPath; private Dictionary<string, RequestHandler> _handlers; public RequestProcessor(Uri appBaseUri) { _applicationPath = appBaseUri.AbsolutePath; } public void OnRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response) { string pathToMatch = request.Uri.Remove(request.Uri.IndexOf(_applicationPath, 0), _applicationPath.Length); RequestHandler handler = _handlers.Where(x => x.Key.Equals(pathToMatch)).FirstOrDefault().Value; if (handler != null) { var headers = handler.ResponseBuilder.BuildHeaders(); body = handler.ResponseBuilder.BuildBody(); response.OnResponse(headers, body); } else { HttpResponseHead headers; body = GetNotStubbedResponse(request, out headers); response.OnResponse(headers, body); } } public RequestHandler Get(string path) { var requestHandler = new RequestHandler(path, this); return requestHandler; } public void ClearHandlers() { _handlers = new Dictionary<string, RequestHandler>(); } public void Add(RequestHandler requestHandler, HttpStatusCode httpStatusCode) { requestHandler.ResponseBuilder.WithStatus(httpStatusCode); _handlers.Add(requestHandler.Path, requestHandler); } private IDataProducer GetNotStubbedResponse(HttpRequestHead request, out HttpResponseHead headers) { IDataProducer body; string data = string.Format("{0} : Not Stubbed", request.Uri); headers = new HttpResponseHead { Status = string.Format("404 {0} Not Stubbed", request.Uri), Headers = new Dictionary<string, string> { {"Content-Type", "text/plain"}, {"Content-Length", data.Length.ToString()}, } }; body = new BufferedBody(data); return body; } } }
mit
C#
35e8bf6fd2159691c5ff824385212fd75bee9218
Update VBlock.cs
BenVlodgi/VMFParser
VMFParser/VBlock.cs
VMFParser/VBlock.cs
using System.Collections.Generic; using System.Linq; namespace VMFParser { /// <summary>Represents a block containing other IVNodes in a VMF</summary> public class VBlock : IVNode { public string Name { get; private set; } public IList<IVNode> Body { get; private set; } /// <summary>Initializes a new instance of the <see cref="VBlock"/> class from its name and a list of IVNodes.</summary> public VBlock(string name, IList<IVNode> body = null) { Name = name; if (body == null) body = new List<IVNode>(); Body = body; } /// <summary>Initializes a new instance of the <see cref="VBlock"/> class from VMF text.</summary> public VBlock(string[] text) { Name = text[0].Trim(); Body = Utils.ParseToBody(text.SubArray(2, text.Length - 3)); } /// <summary>Generates the VMF text representation of this block.</summary> /// <param name="useTabs">if set to <c>true</c> the text will be tabbed accordingly.</param> public string[] ToVMFStrings(bool useTabs = true) { var text = Utils.BodyToString(Body); if (useTabs) text = text.Select(t => t.Insert(0, "\t")).ToList(); text.Insert(0, Name); text.Insert(1, "{"); text.Add("}"); return text.ToArray(); } public override string ToString() { return base.ToString() + " (" + Name + ")"; } } }
using System.Collections.Generic; using System.Linq; namespace VMFParser { /// <summary>Represents a block containing other IVNodes in a VMF</summary> public class VBlock : IVNode { public string Name { get; private set; } public IList<IVNode> Body { get; private set; } /// <summary>Initializes a new instance of the <see cref="VBlock"/> class from its name and a list of IVNodes.</summary> public VBlock(string name, IList<IVNode> body = null) { Name = name; if (body == null) body = new List<IVNode>(); } /// <summary>Initializes a new instance of the <see cref="VBlock"/> class from VMF text.</summary> public VBlock(string[] text) { Name = text[0].Trim(); Body = Utils.ParseToBody(text.SubArray(2, text.Length - 3)); } /// <summary>Generates the VMF text representation of this block.</summary> /// <param name="useTabs">if set to <c>true</c> the text will be tabbed accordingly.</param> public string[] ToVMFStrings(bool useTabs = true) { var text = Utils.BodyToString(Body); if (useTabs) text = text.Select(t => t.Insert(0, "\t")).ToList(); text.Insert(0, Name); text.Insert(1, "{"); text.Add("}"); return text.ToArray(); } public override string ToString() { return base.ToString() + " (" + Name + ")"; } } }
mit
C#
43c5e47b3cb214a312c9e7a9ad7573398561c7a2
Test GitHub
MagedAlNaamani/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings
DynThings.WebPortal/Controllers/HomeController.cs
DynThings.WebPortal/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DynThings.WebPortal.Controllers { public class HomeController : Controller { //TODO: Design a Main Page with review 4 public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DynThings.WebPortal.Controllers { public class HomeController : Controller { //TODO: Design a Main Page with review 3 public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
mit
C#
a39cbc421df0d9163fb61478fa1552d972016a1c
Update the link. (#1089)
GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio
GoogleCloudExtension/GoogleCloudExtension/Analytics/AnalyticsLearnMoreConstants.cs
GoogleCloudExtension/GoogleCloudExtension/Analytics/AnalyticsLearnMoreConstants.cs
// Copyright 2017 Google Inc. All Rights Reserved. // // 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 GoogleCloudExtension.Analytics { /// <summary> /// Class to hold URL Usage Statistics explanation link and the code for opening it. /// </summary> public static class AnalyticsLearnMoreConstants { /// <summary> /// Url of the page containing a detailed explanation on how and why we collect Usage Statistics. /// </summary> public const string AnalyticsLearnMoreLink = "https://policies.google.com/privacy"; } }
// Copyright 2017 Google Inc. All Rights Reserved. // // 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 GoogleCloudExtension.Analytics { /// <summary> /// Class to hold URL Usage Statistics explanation link and the code for opening it. /// </summary> public static class AnalyticsLearnMoreConstants { /// <summary> /// Url of the page containing a detailed explanation on how and why we collect Usage Statistics. /// </summary> public const string AnalyticsLearnMoreLink = "https://cloud.google.com/tools/visual-studio/docs/usage-reporting"; } }
apache-2.0
C#
76afd7d602e4f2793aa5d400cb674f302bd1e7e6
Add first implementation of "GL.Begin and GL.End conformity" analyzer
occar421/OpenTKAnalyzer
src/OpenTKAnalyzer/OpenTKAnalyzer/OpenTK/Graphics/OpenGL/BeginEndAnalyzer.cs
src/OpenTKAnalyzer/OpenTKAnalyzer/OpenTK/Graphics/OpenGL/BeginEndAnalyzer.cs
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace OpenTKAnalyzer.OpenTK.Graphics.OpenGL { [DiagnosticAnalyzer(LanguageNames.CSharp)] class BeginEndAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "BeginEnd"; private const string Title = "GL.Begin and GL.End comformity"; private const string MessageFormat = "Missing {0}."; private const string Description = ""; private const string Category = "OpenTKAnalyzer:OpenGL"; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: DiagnosticId, title: Title, messageFormat: MessageFormat, category: Category, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Analyze); } private static void Analyze(CodeBlockAnalysisContext context) { // filtering if (context.CodeBlock.Ancestors().OfType<UsingDirectiveSyntax>() .Where(u => u.Name.NormalizeWhitespace().ToFullString() == "OpenTK.Graphics.OpenGL").Any()) { return; } // block contains OpenTK.Graphics.OpenGL var walker = new BlockWalker(); walker.Visit(context.CodeBlock); foreach (var diagnostic in walker.Diagnostics) { context.ReportDiagnostic(diagnostic); } } class BlockWalker : CSharpSyntaxWalker { internal List<Diagnostic> Diagnostics { get; } = new List<Diagnostic>(); public override void VisitBlock(BlockSyntax node) { var statements = node.ChildNodes().OfType<ExpressionStatementSyntax>(); var invocations = statements.Select(s => s.Expression).OfType<InvocationExpressionSyntax>(); var glOperators = invocations.Select(i => i.Expression).OfType<MemberAccessExpressionSyntax>() .Where(m => m.IsKind(SyntaxKind.SimpleMemberAccessExpression)).Where(s => s.GetFirstToken().Text == "GL"); // filtering if (!glOperators.Any()) { base.VisitBlock(node); } // block contains GL.????() var counter = 0; foreach (var op in glOperators) { var opName = op.ChildNodes().Skip(1).First().GetFirstToken().Text; if (opName == "Begin") { counter++; if (counter > 1) { Diagnostics.Add(Diagnostic.Create(Rule, op.Parent.GetLocation(), "GL.End")); counter = 1; } } else if (opName == "End") { counter--; if (counter < 0) { Diagnostics.Add(Diagnostic.Create(Rule, op.Parent.GetLocation(), "GL.Begin")); counter = 0; } } } if (counter > 1) { Diagnostics.Add(Diagnostic.Create(Rule, glOperators.Last().Parent.GetLocation(), "GL.End")); } base.VisitBlock(node); } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace OpenTKAnalyzer.OpenTK.Graphics.OpenGL { [DiagnosticAnalyzer(LanguageNames.CSharp)] class BeginEndAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "BeginEnd"; private const string Title = "GL.Begin and GL.End"; private const string MessageFormat = "{0} is missing."; private const string Description = ""; private const string Category = "OpenTKAnalyzer:OpenGL"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: DiagnosticId, title: Title, messageFormat: MessageFormat, category: Category, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Analyze); } private static void Analyze(CodeBlockAnalysisContext context) { // TODO: syntax walker with block } } }
mit
C#
a01cddd17fa1a2cad4d18ea14b9b7cb311cd0bf1
update and add IShape[] in Shapes Main method
ivayloivanof/OOP.CSharp,ivayloivanof/OOP.CSharp
04.EncapsulationAndPolymorphism/EncapsulationAndPolimophism/Shapes/Program.cs
04.EncapsulationAndPolymorphism/EncapsulationAndPolimophism/Shapes/Program.cs
using System; using Shapes.Class; namespace Shapes { using Interfaces; class Program { static void Main() { IShape[] shapes = new IShape[3]; //We produce figures of he basics of matryoshka dolls shapes[0] = new Circle(4); shapes[1] = new Triangle(5, 8.4, 6.4, 8.5); shapes[2] = new Rectangle(8, 5); foreach (IShape shape in shapes) { Console.WriteLine("area is: {0}", shape.CalculateArea()); Console.WriteLine("perimeter is: {0}", shape.CalculatePerimeter()); } } } }
using System; using Shapes.Class; namespace Shapes { using Interfaces; class Program { static void Main() { IShape circle = new Circle(4); Console.WriteLine("circle area: " + circle.CalculateArea()); Console.WriteLine("circle perimeter: " + circle.CalculatePerimeter()); IShape triangle = new Triangle(5, 8.4, 6.4, 8.5); Console.WriteLine("triangle area: " + triangle.CalculateArea()); Console.WriteLine("triangle perimeter: " + triangle.CalculatePerimeter()); IShape rectangle = new Rectangle(8, 5); Console.WriteLine("rectangle area: " + rectangle.CalculateArea()); Console.WriteLine("rectangle perimeter: " + rectangle.CalculatePerimeter()); Console.WriteLine(); } } }
cc0-1.0
C#
bc290ea395bd3c6bed5ddee1dd0e34fef5ba4d8f
Fix FileSystem to return null from property getters if it has not been initialized.
eylvisaker/AgateLib
AgateLib/IO/FileSystem.cs
AgateLib/IO/FileSystem.cs
// The contents of this file are subject to the Mozilla Public License // Version 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is AgateLib. // // The Initial Developer of the Original Code is Erik Ylvisaker. // Portions created by Erik Ylvisaker are Copyright (C) 2006-2014. // All Rights Reserved. // // Contributor(s): Erik Ylvisaker // using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace AgateLib.IO { public static class FileSystem { static FileSystemObjects fileSystemObjects; public static IFile File { get { if (fileSystemObjects == null) return null; return fileSystemObjects.File; } } public static IPath Path { get { if (fileSystemObjects == null) return null; return fileSystemObjects.Path; } } public static IDirectory Directory { get { if (fileSystemObjects == null) return null; return fileSystemObjects.Directory; } } internal static void Initialize(Drivers.IPlatformFactory platformFactory) { fileSystemObjects = new FileSystemObjects(); platformFactory.Initialize(fileSystemObjects); } } }
// The contents of this file are subject to the Mozilla Public License // Version 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is AgateLib. // // The Initial Developer of the Original Code is Erik Ylvisaker. // Portions created by Erik Ylvisaker are Copyright (C) 2006-2014. // All Rights Reserved. // // Contributor(s): Erik Ylvisaker // using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace AgateLib.IO { public static class FileSystem { static FileSystemObjects fileSystemObjects; public static IFile File { get { return fileSystemObjects.File; } } public static IPath Path { get { return fileSystemObjects.Path; } } public static IDirectory Directory { get { return fileSystemObjects.Directory; } } internal static void Initialize(Drivers.IPlatformFactory platformFactory) { fileSystemObjects = new FileSystemObjects(); platformFactory.Initialize(fileSystemObjects); } } }
mit
C#
10f5c5b0bfe97238337cee776a59caae0d111977
add EventManager
FrozenMoon/KeepFly
Assets/Script/Common/Game.cs
Assets/Script/Common/Game.cs
using UnityEngine; using System.Collections; using GamePlay; using UI; namespace Common { public class Game : MonoSingleton<Game> { public void Start() { DontDestroyOnLoad(this); Init(); } protected override void OnInit() { AudioManager.Instance.Init(); EffectManager.Instance.Init(); UIManager.Instance.Init(); if (!GamePlayManager.Instance.Init()) { UnityEngine.Debug.LogError("GamePlayManager Init fail."); return; } } protected override void OnUnInit() { AudioManager.Instance.UnInit(); EffectManager.Instance.UnInit(); UIManager.Instance.UnInit(); GamePlayManager.Instance.UnInit(); } void Update() { GamePlayManager.Instance.Update(); } } }
using UnityEngine; using System.Collections; using GamePlay; using UI; namespace Common { public class Game : MonoSingleton<Game> { public void Start() { DontDestroyOnLoad(this); Init(); } protected override void OnInit() { AudioManager.Instance.Init(); EffectManager.Instance.Init(); UIManager.Instance.Init(); if (!GamePlayManager.Instance.Init()) { UnityEngine.Debug.LogError("GamePlayManager Init fail."); return; } } protected override void OnUnInit() { AudioManager.Instance.UnInit(); EffectManager.Instance.UnInit(); UIManager.Instance.UnInit(); GamePlayManager.Instance.UnInit(); } void Update() { GamePlayManager.Instance.Update(); } } }
mit
C#
6097593e802200e50de6eec43bff630093eeb3de
Update ErrorController.cs
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
src/SFA.DAS.ProviderApprenticeshipsService.Web/Controllers/ErrorController.cs
src/SFA.DAS.ProviderApprenticeshipsService.Web/Controllers/ErrorController.cs
using System.Web.Mvc; using SFA.DAS.ProviderApprenticeshipsService.Web.Attributes; namespace SFA.DAS.ProviderApprenticeshipsService.Web.Controllers { using System; [AllowAllRoles] [AllowAnonymous] public class ErrorController : Controller { public ViewResult BadRequest() { Response.StatusCode = 400; return View("_Error400"); } public ViewResult Forbidden() { Response.StatusCode = 403; return View("_Error403"); } public ViewResult NotFound() { Response.StatusCode = 404; return View("_Error404"); } public ViewResult InternalServerError(Exception ex) { Response.StatusCode = 500; return View("_Error500"); } public ActionResult InvalidState() { return View("_InvalidState"); } } }
using System.Web.Mvc; using SFA.DAS.ProviderApprenticeshipsService.Web.Attributes; namespace SFA.DAS.ProviderApprenticeshipsService.Web.Controllers { using System; [AllowAllRoles] public class ErrorController : Controller { public ViewResult BadRequest() { Response.StatusCode = 400; return View("_Error400"); } public ViewResult Forbidden() { Response.StatusCode = 403; return View("_Error403"); } public ViewResult NotFound() { Response.StatusCode = 404; return View("_Error404"); } public ViewResult InternalServerError(Exception ex) { Response.StatusCode = 500; return View("_Error500"); } public ActionResult InvalidState() { return View("_InvalidState"); } } }
mit
C#
dd3317194f5835ce7fed8ba2da8ce367e8a2992c
Make tower abstract class
TeamLeoTolstoy/Leo
Game/StopTheBunny/Tower.cs
Game/StopTheBunny/Tower.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StopTheBunny { public class abstract Tower : GameObject { private int damage; public override char Sign { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override Color Color { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override char[] ElementSize { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public int Damage { get { return.this.damage;} set { if (value<0) { throw new ArgumentException(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StopTheBunny { public class Tower : GameObject { private int damage; public override char Sign { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override Color Color { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override char[] ElementSize { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public int Damage { get { return.this.damage;} set { if (value<0) { throw new ArgumentException(); } } } } }
mit
C#
1f9926c1f63b1641178464b0be56f78fe9cc9af8
Add FolioPaymentIndicator as an indicator (doh)
PietroProperties/holms.platformclient.net
csharp/HOLMS.Platform/HOLMS.Platform/Types/Extensions/Folio/FolioPaymentIndicator.cs
csharp/HOLMS.Platform/HOLMS.Platform/Types/Extensions/Folio/FolioPaymentIndicator.cs
using System; using HOLMS.Support.Conversions; using HOLMS.Types.Extensions; using HOLMS.Types.Primitive; namespace HOLMS.Types.Folio { public partial class FolioPaymentIndicator : EntityIndicator<FolioPaymentIndicator> { public FolioPaymentIndicator(Guid id) { Id = id.ToUUID(); } public override Uuid GetUuidID() => Id; } }
using System; using HOLMS.Support.Conversions; namespace HOLMS.Types.Folio { public partial class FolioPaymentIndicator { public FolioPaymentIndicator(Guid id) { Id = id.ToUUID(); } } }
mit
C#
6b5c7ad72404ebf11fb7cea8b614d787992e77e0
Add iFrame option parameters.
jakerman999/YoutubeDesktop,jakerman999/YoutubeDesktop
YoutubeDesktop/Player.cs
YoutubeDesktop/Player.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace YoutubeDesktop { public partial class Player : Form { const string htmlPrefix = "<!DOCTYPE html><html><body>"; const string htmlSuffix = "</body></html>"; string video = "fWRISvgAygU"; int width = 480; int height = 270; bool OPTautoplay = true; bool OPTkeyboard = true; bool OPTfullscreen = false; bool OPTannotations = false; bool OPTrelated = false; bool OPTcaptions = false; public Player() { InitializeComponent(); DisplayHtml(iFrameHtml()); } private void DisplayHtml(string html) { webBrowser1.DocumentText = "0"; webBrowser1.Document.OpenNew(true); webBrowser1.Document.Write(html); webBrowser1.Refresh(); } private string iFrameOptions() { string options = "?enablejsapi=1&amp;controls=2"; if (OPTautoplay) { options += "&amp;autoplay=1"; } if (OPTkeyboard) { options += "&amp;disablekb=1"; } if (!OPTfullscreen) { options += "&amp;fs=0"; } if (!OPTannotations) { options += "&amp;iv_load_policy=3"; } if (!OPTrelated) { options += "&amp;rel=0"; } if (OPTcaptions) { options += "&amp;cc_load_policy=1"; } //options += "&amp;origin=http%3A%2F%2Flocalhost"; options += "&amp;widgetid=1"; return options; } private string iFrameHtml() { string html = "<iframe id=\"ytplayer\" type=\"text/html\" width=" + width + " height=" + height + "\n"; html += "src = \"https://www.youtube.com/embed/" + video + iFrameOptions() + "\n"; html += "frameborder = \"0\" /> "; return htmlPrefix + html + htmlSuffix; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace YoutubeDesktop { public partial class Player : Form { const string htmlPrefix = "<!DOCTYPE html><html><body>"; const string htmlSuffix = "</body></html>"; string video = "fWRISvgAygU"; int width = 480; int height = 270; public Player() { InitializeComponent(); DisplayHtml(iFrameHtml()); } private void DisplayHtml(string html) { webBrowser1.DocumentText = "0"; webBrowser1.Document.OpenNew(true); webBrowser1.Document.Write(html); webBrowser1.Refresh(); } private string iFrameHtml() { string html = "<iframe id=\"ytplayer\" type=\"text/html\" width=" + width + " height=" + height + "\n"; html += "src = \"https://www.youtube.com/embed/" + video + "?autoplay=1\"\n"; html += "frameborder = \"0\" /> "; return htmlPrefix + html + htmlSuffix; } } }
mit
C#
547a8d794e00a1f48b09c8dbf4b3bbbe2ea5580e
call for image analyzer
andrewlarkin/Photo-Rainbow
Photo-Rainbow/Main.xaml.cs
Photo-Rainbow/Main.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Drawing; namespace Photo_Rainbow { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class Main : Window { private static PhotoServiceManager p = new PhotoServiceManager(); public Main() { InitializeComponent(); FlickrManager f = new FlickrManager(); p.LoadManager(f); } private void Authenticate_Click(object sender, RoutedEventArgs e) { p.Authenticate(); FlickrManager f = (FlickrManager)p.Manager; if (f.url != null) { System.Diagnostics.Process.Start(f.url); } } private void Complete_Auth_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(CodeText.Text)) { MessageBox.Show("You must paste the verifier code into the textbox above."); return; } try { FlickrManager f = (FlickrManager)p.Manager; f.CompleteAuth(CodeText.Text); MessageBox.Show("User authenticated!"); if (f.IsAuthenticated()) { List<Image> imgObjs = f.GetPhotos(); ImageAnalyzer procImages = new ImageAnalyzer(imgObjs); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Drawing; namespace Photo_Rainbow { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class Main : Window { private static PhotoServiceManager p = new PhotoServiceManager(); public Main() { InitializeComponent(); FlickrManager f = new FlickrManager(); p.LoadManager(f); } private void Authenticate_Click(object sender, RoutedEventArgs e) { p.Authenticate(); FlickrManager f = (FlickrManager)p.Manager; if (f.url != null) { System.Diagnostics.Process.Start(f.url); } } private void Complete_Auth_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(CodeText.Text)) { MessageBox.Show("You must paste the verifier code into the textbox above."); return; } try { FlickrManager f = (FlickrManager)p.Manager; f.CompleteAuth(CodeText.Text); MessageBox.Show("User authenticated!"); if (f.IsAuthenticated()) { List<Image> imgObjs = f.GetPhotos(); ImageAnalyzer procImages = new ImageAnalyzer(imgObjs); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
apache-2.0
C#
867c6e85e4cc7290d625f77299d707fa3646eece
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
autofac/Autofac.Extras.CommonServiceLocator
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.CommonServiceLocator")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.CommonServiceLocator")] [assembly: AssemblyDescription("")]
mit
C#
2b55f5830c4ce0fc60772b0c8ace0df5c703bee6
test clock exposes advanced event to manual scheduler
Liwoj/Metrics.NET,alhardy/Metrics.NET,DeonHeyns/Metrics.NET,alhardy/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,etishor/Metrics.NET,Liwoj/Metrics.NET,cvent/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,DeonHeyns/Metrics.NET,mnadel/Metrics.NET,huoxudong125/Metrics.NET,Recognos/Metrics.NET,etishor/Metrics.NET,Recognos/Metrics.NET,ntent-ad/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,huoxudong125/Metrics.NET
Src/Metrics/Utils/Clock.cs
Src/Metrics/Utils/Clock.cs
 using System; namespace Metrics.Utils { public abstract class Clock { private sealed class StopwatchClock : Clock { private static readonly long factor = (1000L * 1000L * 1000L) / System.Diagnostics.Stopwatch.Frequency; public override long Nanoseconds { get { return System.Diagnostics.Stopwatch.GetTimestamp() * factor; } } } private sealed class SystemClock : Clock { public override long Nanoseconds { get { return DateTime.UtcNow.Ticks * 100L; } } } public sealed class TestClock : Clock { private long nanoseconds = 0; public override long Nanoseconds { get { return this.nanoseconds; } } public void Advance(TimeUnit unit, long value) { this.nanoseconds += unit.ToNanoseconds(value); if (Advanced != null) { Advanced(this, this.nanoseconds); } } public event EventHandler<long> Advanced; } public static readonly Clock SystemDateTime = new SystemClock(); public static readonly Clock Default = new StopwatchClock(); public abstract long Nanoseconds { get; } public long Seconds { get { return TimeUnit.Nanoseconds.ToSeconds(Nanoseconds); } } } }
 using System; namespace Metrics.Utils { public abstract class Clock { private sealed class StopwatchClock : Clock { private static readonly long factor = (1000L * 1000L * 1000L) / System.Diagnostics.Stopwatch.Frequency; public override long Nanoseconds { get { return System.Diagnostics.Stopwatch.GetTimestamp() * factor; } } } private sealed class SystemClock : Clock { public override long Nanoseconds { get { return DateTime.UtcNow.Ticks * 100L; } } } public sealed class TestClock : Clock { private long nanoseconds = 0; public override long Nanoseconds { get { return this.nanoseconds; } } public void Advance(TimeUnit unit, long value) { this.nanoseconds += unit.ToNanoseconds(value); } } public static readonly Clock SystemDateTime = new SystemClock(); public static readonly Clock Default = new StopwatchClock(); public abstract long Nanoseconds { get; } public long Seconds { get { return TimeUnit.Nanoseconds.ToSeconds(Nanoseconds); } } } }
apache-2.0
C#
feb86313dc0b940dc65d80c231c12ac5d32126e0
Use standard EventHandler naming
jlewin/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl
MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/HomePrinterPage.cs
MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/HomePrinterPage.cs
/* Copyright (c) 2019, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using MatterHackers.Agg.UI; using MatterHackers.MatterControl.PrinterCommunication; using MatterHackers.MatterControl.SlicerConfiguration; namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { public class HomePrinterPage : WizardPage { public HomePrinterPage(ISetupWizard setupWizard, string headerText, string instructionsText) : base(setupWizard, headerText, instructionsText) { } public override void OnClosed(EventArgs e) { // Unregister listeners printer.Connection.DetailedPrintingStateChanged -= Connection_DetailedPrintingStateChanged; base.OnClosed(e); } public override void OnLoad(EventArgs args) { printer.Connection.DetailedPrintingStateChanged += Connection_DetailedPrintingStateChanged; printer.Connection.HomeAxis(PrinterConnection.Axis.XYZ); if(!printer.Settings.GetValue<bool>(SettingsKey.z_homes_to_max)) { // move so we don't heat the printer while the nozzle is touching the bed printer.Connection.MoveAbsolute(PrinterConnection.Axis.Z, 10, printer.Settings.Helpers.ManualMovementSpeeds().Z); } NextButton.Enabled = false; base.OnLoad(args); } private void Connection_DetailedPrintingStateChanged(object sender, EventArgs e) { if (printer.Connection.DetailedPrintingState != DetailedPrintingState.HomingAxis) { NextButton.Enabled = true; UiThread.RunOnIdle(() => NextButton.InvokeClick()); } } } }
/* Copyright (c) 2019, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using MatterHackers.Agg.UI; using MatterHackers.MatterControl.PrinterCommunication; using MatterHackers.MatterControl.SlicerConfiguration; namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { public class HomePrinterPage : WizardPage { public HomePrinterPage(ISetupWizard setupWizard, string headerText, string instructionsText) : base(setupWizard, headerText, instructionsText) { } public override void OnClosed(EventArgs e) { // Unregister listeners printer.Connection.DetailedPrintingStateChanged -= CheckHomeFinished; base.OnClosed(e); } public override void OnLoad(EventArgs args) { printer.Connection.DetailedPrintingStateChanged += CheckHomeFinished; printer.Connection.HomeAxis(PrinterConnection.Axis.XYZ); if(!printer.Settings.GetValue<bool>(SettingsKey.z_homes_to_max)) { // move so we don't heat the printer while the nozzle is touching the bed printer.Connection.MoveAbsolute(PrinterConnection.Axis.Z, 10, printer.Settings.Helpers.ManualMovementSpeeds().Z); } NextButton.Enabled = false; base.OnLoad(args); } private void CheckHomeFinished(object sender, EventArgs e) { if (printer.Connection.DetailedPrintingState != DetailedPrintingState.HomingAxis) { NextButton.Enabled = true; UiThread.RunOnIdle(() => NextButton.InvokeClick()); } } } }
bsd-2-clause
C#
0ccaf63b1cc60a30271af8636b82534370b4a9ca
Fix GetDescendantsOfType
jasonmcboyd/Treenumerable
Source/Treenumerable/TreeWalkerExtensions/TreeWalkerExtensions.GetDescendantsOfType.cs
Source/Treenumerable/TreeWalkerExtensions/TreeWalkerExtensions.GetDescendantsOfType.cs
using System; using System.Collections.Generic; namespace Treenumerable { public static partial class TreeWalkerExtensions { public static IEnumerable<TResult> GetDescendantsOfType<TSource, TResult>( this ITreeWalker<TSource> walker, IEnumerable<TSource> nodes) { // Validate parameters. if (walker == null) { throw new ArgumentNullException("walker"); } if (nodes == null) { throw new ArgumentNullException("nodes"); } foreach (object descendant in walker.GetDescendants(nodes, n => n is TResult)) { yield return (TResult)descendant; } } } }
using System; using System.Collections.Generic; using System.Linq; namespace Treenumerable { public static partial class TreeWalkerExtensions { public static IEnumerable<TResult> GetDescendantsOfType<TSource, TResult>(this ITreeWalker<TSource> walker, IEnumerable<TSource> nodes, bool includeNodes) { if (nodes == null) { yield break; } foreach (object node in nodes) { if (includeNodes && node is TResult) { yield return (TResult)node; } else { foreach (TResult descendant in walker.GetDescendantsOfType<TSource, TResult>(walker.GetChildren((TSource)node), true)) { yield return descendant; } } } } //public static IEnumerable<T> GetDescendants<T>(this ITreeWalker<T> walker, IEnumerable<T> nodes, Func<T, bool> predicate) //{ // return walker.GetDescendants(nodes, predicate, false); //} //public static IEnumerable<T> GetDescendants<T>(this ITreeWalker<T> walker, T node, Func<T, bool> predicate, bool includeNode) //{ // if (node == null) // { // return Enumerable.Empty<T>(); // } // return walker.GetDescendants(Enumerable.Repeat(node, 1), predicate, includeNode); //} //public static IEnumerable<T> GetDescendants<T>(this ITreeWalker<T> walker, T node, Func<T, bool> predicate) //{ // return walker.GetDescendants<T>(node, predicate, false); //} } }
mit
C#
27b0266d25e5f68288909f7145c44e6f6daab76b
Improve how the link is made and page is cached
2sic/app-blog,2sic/app-blog,2sic/app-blog
bs4/Links.cs
bs4/Links.cs
using ToSic.Razor.Blade; public class Links : Custom.Hybrid.Code12 { /// <Summary> /// Returns a safe url to a post details page /// </Summary> public dynamic LinkToDetailsPage(dynamic post) { return Link.To(pageId: DetailsPageId, parameters: "details=" + post.UrlKey); } /// <Summary> /// Get / cache the page which will show the details of a post /// </Summary> private int DetailsPageId { get { if (_detailsPageId != 0) return _detailsPageId; if (Text.Has(Settings.DetailsPage)) _detailsPageId = int.Parse((App.Settings.Get("DetailsPage", convertLinks: false)).Split(':')[1]); else _detailsPageId = CmsContext.Page.Id; return _detailsPageId; } } private int _detailsPageId; }
using ToSic.Razor.Blade; // todo: change to use Get public class Links : Custom.Hybrid.Code12 { // Returns a safe url to a post details page public dynamic LinkToDetailsPage(dynamic post) { var detailsPageTabId = Text.Has(Settings.DetailsPage) ? int.Parse((AsEntity(App.Settings).GetBestValue("DetailsPage")).Split(':')[1]) : CmsContext.Page.Id; return Link.To(pageId: detailsPageTabId, parameters: "details=" + post.UrlKey); } }
mit
C#
14ecec2cc66ddaa51f2caa169f71bbd3627e353a
print Debug.Log etc to console
jbruening/UnEngine
src/UnEngine/Engine/Debug.cs
src/UnEngine/Engine/Debug.cs
using System; #if UNENG namespace UnEngine #else namespace UnityEngine #endif { public sealed class Debug { public static void Log(object message) { Console.WriteLine (message.ToString ()); } public static void Warning(object message) { Console.WriteLine (message.ToString ()); } public static void Error(object message) { Console.WriteLine (message.ToString ()); } public static void Exception(object message) { Console.WriteLine (message.ToString ()); } public static void Log(object message, Object context) { Console.WriteLine (message.ToString ()); } public static void LogError(object message) { Console.WriteLine (message.ToString ()); } public static void LogError(object message, Object context) { Console.WriteLine (message.ToString ()); } public static void ClearDeveloperConsole(){} public static void LogException(Exception exception) { Console.WriteLine (exception.ToString ()); } public static void LogException(Exception exception, Object context) { Console.WriteLine (exception.ToString ()); } public static void LogWarning(object message) { Console.WriteLine (message.ToString ()); } public static void LogWarning(object message, Object context) { Console.WriteLine (message.ToString ()); } } }
using System; #if UNENG namespace UnEngine #else namespace UnityEngine #endif { public sealed class Debug { public static void Log(object message) { } public static void Warning(object message) { } public static void Error(object message) { } public static void Exception(object message) { } public static void Log(object message, Object context) { } public static void LogError(object message) { } public static void LogError(object message, Object context) { } public static void ClearDeveloperConsole(){} public static void LogException(Exception exception) { } public static void LogException(Exception exception, Object context) { } public static void LogWarning(object message) { } public static void LogWarning(object message, Object context) { } } }
mit
C#
b05374404f2365eb3db9bd063a36683d6ee90401
Update CodeFixProvider.cs
filipw/RemoveRegionAnalyzerAndCodeFix
RemoveRegionAnalyzerAndCodeFix/RemoveRegionAnalyzerAndCodeFix/CodeFixProvider.cs
RemoveRegionAnalyzerAndCodeFix/RemoveRegionAnalyzerAndCodeFix/CodeFixProvider.cs
using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace RemoveRegionAnalyzerAndCodeFix { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RemoveRegionCodeFixProvider)), Shared] public class RemoveRegionCodeFixProvider : CodeFixProvider { private const string title = "Get rid of the damn region"; public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(RemoveRegionAnalyzer.DiagnosticId); } } public sealed override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(context.Span, true, true); var region = node as DirectiveTriviaSyntax; if (region != null) { context.RegisterCodeFix(CodeAction.Create(title, c => { Music.Play("Content\\msg.wav"); var newRoot = root.RemoveNodes(region.GetRelatedDirectives(), SyntaxRemoveOptions.AddElasticMarker); var newDocument = context.Document.WithSyntaxRoot(newRoot); return Task.FromResult(newDocument); } ), context.Diagnostics.First()); } } } }
using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace RemoveRegionAnalyzerAndCodeFix { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RemoveRegionCodeFixProvider)), Shared] public class RemoveRegionCodeFixProvider : CodeFixProvider { private const string title = "Get rid of the damn region"; public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(RemoveRegionAnalyzer.DiagnosticId); } } public sealed override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(context.Span, true, true); var region = node as DirectiveTriviaSyntax; if (region != null) { context.RegisterCodeFix(CodeAction.Create(title, c => { Music.Play("Content\\msg.wav"); var newRoot = root.RemoveNodes(node.GetRelatedDirectives(), SyntaxRemoveOptions.AddElasticMarker); var newDocument = context.Document.WithSyntaxRoot(newRoot); return Task.FromResult(newDocument); } ), context.Diagnostics.First()); } } } }
mit
C#
d4b5603bbae0b2b264b1d436d7966b7c30560c81
Replace WaitOne(TimeSpan) with WaitOne(TimeSpan,false) so 3.5SP1 not needed.
hibernating-rhinos/rhino-esb,ketiko/rhino-esb,jkells/rhino-esb
Rhino.ServiceBus.Tests/Bugs/Occasional_consumer_resolving_when_not_subscribed.cs
Rhino.ServiceBus.Tests/Bugs/Occasional_consumer_resolving_when_not_subscribed.cs
using System; using System.Threading; using Castle.Windsor; using Castle.Windsor.Configuration.Interpreters; using Rhino.ServiceBus.Impl; using Xunit; namespace Rhino.ServiceBus.Tests.Bugs { public class Occasional_consumer_resolving_when_not_subscribed : OccasionalConsumerOf<SimpleMessage> { private readonly IWindsorContainer container; public static ManualResetEvent wait; public static bool GotConsumed; public Occasional_consumer_resolving_when_not_subscribed() { container = new WindsorContainer(new XmlInterpreter()); container.Kernel.AddFacility("rhino.esb", new RhinoServiceBusFacility()); container.AddComponent<Occasional_consumer_resolving_when_not_subscribed>(); container.AddComponent<Not_consumed>(); } [Fact] public void Would_not_gather_occasional_consumer_if_not_instance_subscribed() { using (var bus = container.Resolve<IStartableServiceBus>()) { wait = new ManualResetEvent(false); bus.Start(); using (bus.AddInstanceSubscription(this)) { bus.Send(new SimpleMessage()); wait.WaitOne(TimeSpan.FromSeconds(5), false); } } Assert.False(GotConsumed); } public void Consume(SimpleMessage message) { } } public class SimpleMessage { } public class Not_consumed : OccasionalConsumerOf<SimpleMessage> { public void Consume(SimpleMessage message) { Occasional_consumer_resolving_when_not_subscribed.GotConsumed = true; Occasional_consumer_resolving_when_not_subscribed.wait.Set(); } } }
using System; using System.Threading; using Castle.Windsor; using Castle.Windsor.Configuration.Interpreters; using Rhino.ServiceBus.Impl; using Xunit; namespace Rhino.ServiceBus.Tests.Bugs { public class Occasional_consumer_resolving_when_not_subscribed : OccasionalConsumerOf<SimpleMessage> { private readonly IWindsorContainer container; public static ManualResetEvent wait; public static bool GotConsumed; public Occasional_consumer_resolving_when_not_subscribed() { container = new WindsorContainer(new XmlInterpreter()); container.Kernel.AddFacility("rhino.esb", new RhinoServiceBusFacility()); container.AddComponent<Occasional_consumer_resolving_when_not_subscribed>(); container.AddComponent<Not_consumed>(); } [Fact] public void Would_not_gather_occasional_consumer_if_not_instance_subscribed() { using (var bus = container.Resolve<IStartableServiceBus>()) { wait = new ManualResetEvent(false); bus.Start(); using (bus.AddInstanceSubscription(this)) { bus.Send(new SimpleMessage()); wait.WaitOne(TimeSpan.FromSeconds(5)); } } Assert.False(GotConsumed); } public void Consume(SimpleMessage message) { } } public class SimpleMessage { } public class Not_consumed : OccasionalConsumerOf<SimpleMessage> { public void Consume(SimpleMessage message) { Occasional_consumer_resolving_when_not_subscribed.GotConsumed = true; Occasional_consumer_resolving_when_not_subscribed.wait.Set(); } } }
bsd-3-clause
C#
a55ff736a634d8d77f771c2f86bbd729f9c33789
完成H5支付Demo
mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,down4u/WeiXinMPSDK,lishewen/WeiXinMPSDK,wanddy/WeiXinMPSDK,lishewen/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK,down4u/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK
src/Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Views/TenPayV3/ProductList.cshtml
src/Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Views/TenPayV3/ProductList.cshtml
@model List<Senparc.Weixin.MP.Sample.Models.ProductModel> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>产品列表</title> <style> ul#productList, ul#productList li { list-style: none; /*display: inline;*/ } ul#productList li { border: 1px solid #008b8b; background: #c9ff94; padding: 6%; margin: 4%; overflow: hidden; float: left; } ul#productList li.br { clear: left; } ul#productList li a { text-decoration: none; display: block; overflow: hidden; clear: both; } </style> </head> <body> @if (Senparc.Weixin.BrowserUtility.BrowserUtility.SideInWeixinBrowser(this.Context)) { <div>提示:此网页在微信外部浏览器中打开可以体验“扫一扫支付”和“H5”支付</div> } else { <div>提示:此页面在微信浏览器内打开可以体验微信JS-SDK微信支付</div> } <div> <ul id="productList"> @for (int i = 0; i <= Model.Count - 1; i++) { var item = Model[i]; <li class="@(i > 0 && i % 4 == 0 ? "br" : null)"> <a href="@Url.Action("ProductItem", "TenPayV3", new {productId = item.Id, hc = item.GetHashCode()})"> <h2>@item.Name</h2> <p>@item.Price.ToString("c")</p> <p>点击购买</p> </a> </li> } </ul> </div> </body> </html>
@model List<Senparc.Weixin.MP.Sample.Models.ProductModel> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>产品列表</title> <style> ul#productList, ul#productList li { list-style: none; /*display: inline;*/ } ul#productList li { border: 1px solid #008b8b; background: #c9ff94; padding: 6%; margin: 4%; overflow: hidden; float: left; } ul#productList li.br { clear: left; } ul#productList li a { text-decoration: none; display: block; overflow: hidden; clear: both; } </style> </head> <body> <div> <ul id="productList"> @for (int i = 0; i <= Model.Count - 1; i++) { var item = Model[i]; <li class="@(i > 0 && i % 4==0 ? "br" : null)"> <a href="@Url.Action("ProductItem", "TenPayV3", new {productId = item.Id, hc = item.GetHashCode()})"> <h2>@item.Name</h2> <p>@item.Price.ToString("c")</p> <p>点击购买</p> </a> </li> } </ul> </div> </body> </html>
apache-2.0
C#
e28c33d8be6e8d66c2505cfa5a84c67aaa21fb58
Use the correct call to FunctionNameHelper
USDXStartups/CalendarHelper
shared/AppSettingsHelper.csx
shared/AppSettingsHelper.csx
#load "LogHelper.csx" #load "FunctionNameHelper.csx" using System.Configuration; public static class AppSettingsHelper { public static string GetAppSetting(string SettingName, bool LogValue = true ) { string SettingValue = ""; string methodName = this.GetType().FullName; try { SettingValue = ConfigurationManager.AppSettings[SettingName].ToString(); if ((!String.IsNullOrEmpty(SettingValue)) && LogValue) { LogHelper.Info($"{FunctionnameHelper.GetFunctionName()} {GetFunctionName()} {methodName} Retreived AppSetting {SettingName} with a value of {SettingValue}"); } else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue) { LogHelper.Info($"{FunctionnameHelper.GetFunctionName()} {methodName} Retreived AppSetting {SettingName} but logging value was turned off"); } else if(!String.IsNullOrEmpty(SettingValue)) { LogHelper.Info($"{FunctionnameHelper.GetFunctionName()} {methodName} AppSetting {SettingName} was null or empty"); } } catch (ConfigurationErrorsException ex) { LogHelper.Error($"{FunctionnameHelper.GetFunctionName()} {methodName} Unable to find AppSetting {SettingName} with exception of {ex.Message}"); } catch (System.Exception ex) { LogHelper.Error($"{FunctionnameHelper.GetFunctionName()} {methodName} Looking for AppSetting {SettingName} caused an exception of {ex.Message}"); } return SettingValue; } }
#load "LogHelper.csx" #load "FunctionNameHelper.csx" using System.Configuration; public static class AppSettingsHelper { public static string GetAppSetting(string SettingName, bool LogValue = true ) { string SettingValue = ""; string methodName = this.GetType().FullName; try { SettingValue = ConfigurationManager.AppSettings[SettingName].ToString(); if ((!String.IsNullOrEmpty(SettingValue)) && LogValue) { LogHelper.Info($"{FunctionnameHelper} {GetFunctionName()} {methodName} Retreived AppSetting {SettingName} with a value of {SettingValue}"); } else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue) { LogHelper.Info($"{FunctionnameHelper} {methodName} Retreived AppSetting {SettingName} but logging value was turned off"); } else if(!String.IsNullOrEmpty(SettingValue)) { LogHelper.Info($"{FunctionnameHelper} {methodName} AppSetting {SettingName} was null or empty"); } } catch (ConfigurationErrorsException ex) { LogHelper.Error($"{FunctionnameHelper} {methodName} Unable to find AppSetting {SettingName} with exception of {ex.Message}"); } catch (System.Exception ex) { LogHelper.Error($"{FunctionnameHelper} {methodName} Looking for AppSetting {SettingName} caused an exception of {ex.Message}"); } return SettingValue; } }
mit
C#
f4d323945c69f2953fd543dadae95ffee742dac8
Implement two MemoryMappedFile methods
Haacked/Rothko
src/Threading/MemoryMappedFileWrapper.cs
src/Threading/MemoryMappedFileWrapper.cs
using System.IO; using System.IO.MemoryMappedFiles; namespace Rothko { public sealed class MemoryMappedFileWrapper : IMemoryMappedFile { private readonly MemoryMappedFile innerFile; public MemoryMappedFileWrapper(MemoryMappedFile innerFile) { this.innerFile = innerFile; } public Stream CreateViewStream() { return innerFile.CreateViewStream(); } public Stream CreateViewStream(long offset, long size) { return innerFile.CreateViewStream(offset, size); } public Stream CreateViewStream(long offset, long size, MemoryMappedFileAccess access) { return innerFile.CreateViewStream(offset, size, access); } public void Dispose() { var file = innerFile; if (file != null) file.Dispose(); } } }
using System.IO; using System.IO.MemoryMappedFiles; namespace Rothko { public sealed class MemoryMappedFileWrapper : IMemoryMappedFile { private readonly MemoryMappedFile innerFile; public MemoryMappedFileWrapper(MemoryMappedFile innerFile) { this.innerFile = innerFile; } public Stream CreateViewStream() { return innerFile.CreateViewStream(); } public Stream CreateViewStream(long offset, long size) { throw new System.NotImplementedException(); } public Stream CreateViewStream(long offset, long size, MemoryMappedFileAccess access) { throw new System.NotImplementedException(); } public void Dispose() { var file = innerFile; if (file != null) file.Dispose(); } } }
mit
C#
2b198a2844f4fbfacff4d30f7036058b7f05576f
fix build failure on .NET 4.5
ptoonen/corefx,Jiayili1/corefx,Jiayili1/corefx,ericstj/corefx,BrennanConroy/corefx,shimingsg/corefx,ptoonen/corefx,ViktorHofer/corefx,mmitche/corefx,ptoonen/corefx,ViktorHofer/corefx,wtgodbe/corefx,BrennanConroy/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,ViktorHofer/corefx,mmitche/corefx,ptoonen/corefx,mmitche/corefx,wtgodbe/corefx,shimingsg/corefx,mmitche/corefx,Jiayili1/corefx,Jiayili1/corefx,ptoonen/corefx,ptoonen/corefx,ericstj/corefx,wtgodbe/corefx,wtgodbe/corefx,ericstj/corefx,mmitche/corefx,Jiayili1/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,BrennanConroy/corefx,shimingsg/corefx,ptoonen/corefx,mmitche/corefx,mmitche/corefx,wtgodbe/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,Jiayili1/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx,Jiayili1/corefx
src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.cs
src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.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.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { public partial class Activity { /// <summary> /// Gets or sets the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { ObjectHandle activityHandle = (ObjectHandle)CallContext.LogicalGetData(FieldKey); // Unwrap the Activity if it was set in the same AppDomain (as FieldKey is AppDomain-specific). if (activityHandle != null) { return (Activity)activityHandle.Unwrap(); } return null; } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif set { if (ValidateSetCurrent(value)) { SetCurrent(value); } } } #region private #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private static void SetCurrent(Activity activity) { // Applications may implicitly or explicitly call other AppDomains // that do not have DiagnosticSource DLL, therefore may not be able to resolve Activity type stored in the logical call context. // To avoid it, we wrap Activity with ObjectHandle. CallContext.LogicalSetData(FieldKey, new ObjectHandle(activity)); } // Slot name depends on the AppDomain Id in order to prevent AppDomains to use the same Activity // Cross AppDomain calls are considered as 'external' i.e. only Activity Id and Baggage should be propagated and // new Activity should be started for the RPC calls (incoming and outgoing) private static readonly string FieldKey = $"{typeof(Activity).FullName}_{AppDomain.CurrentDomain.Id}"; #endregion //private } }
// 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.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { public partial class Activity { /// <summary> /// Gets or sets the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { ObjectHandle activityHandle = (ObjectHandle)CallContext.LogicalGetData(FieldKey); // Unwrap the Activity if it was set in the same AppDomain (as FieldKey is AppDomain-specific). if (activityHandle != null) { return (Activity)activityHandle.Unwrap(); } return null; } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif set { if (ValidateSetCurrent) { SetCurrent(value); } } } #region private #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private static void SetCurrent(Activity activity) { // Applications may implicitly or explicitly call other AppDomains // that do not have DiagnosticSource DLL, therefore may not be able to resolve Activity type stored in the logical call context. // To avoid it, we wrap Activity with ObjectHandle. CallContext.LogicalSetData(FieldKey, new ObjectHandle(activity)); } // Slot name depends on the AppDomain Id in order to prevent AppDomains to use the same Activity // Cross AppDomain calls are considered as 'external' i.e. only Activity Id and Baggage should be propagated and // new Activity should be started for the RPC calls (incoming and outgoing) private static readonly string FieldKey = $"{typeof(Activity).FullName}_{AppDomain.CurrentDomain.Id}"; #endregion //private } }
mit
C#
8c85f8bb98cb987937d494275df1d34c3f941c87
Update tests. #386
Sitecore/Sitecore-Instance-Manager
src/SIM.Sitecore9Installer.Tests/Validation/Validators/SqlPefixValidatorTests.cs
src/SIM.Sitecore9Installer.Tests/Validation/Validators/SqlPefixValidatorTests.cs
using AutoFixture; using NSubstitute; using SIM.Sitecore9Installer.Tasks; using SIM.Sitecore9Installer.Validation; using SIM.Sitecore9Installer.Validation.Validators; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace SIM.Sitecore9Installer.Tests.Validation.Validators { public class SqlPefixValidatorTests { [Theory] [InlineData("server","user","pass","prefix","sql-server","sql-user","sql-pass","db-prefix",new string[] {"somedb"},1)] [InlineData("server", "user", "pass", "prefix", "sql-server", "sql-user", "sql-pass", "db-prefix", new string[] { }, 0)] public void DbsWithTheSamePrefix(string server, string user, string pass, string prefix, string serverValue, string userValue, string passValue, string prefixValue, string[] foundDbs, int errorsCount) { SqlPefixValidator val = Substitute.ForPartsOf<SqlPefixValidator>(); val.WhenForAnyArgs(v => v.GetDbList(null, null, null, null)).DoNotCallBase(); val.GetDbList(null, null, null, null).ReturnsForAnyArgs(foundDbs); val.Data["Server"] = server; val.Data["User"] = user; val.Data["Password"] = pass; val.Data["Prefix"] = prefix; Fixture _fix = new Fixture(); Task t = Substitute.For<Task>(_fix.Create<string>(), _fix.Create<int>(), null, new List<InstallParam>(), new Dictionary<string, string>()); t.GlobalParams.Returns(new List<InstallParam>()); t.LocalParams.Returns(new List<InstallParam>()); t.LocalParams.Add(new InstallParam(server, serverValue)); t.LocalParams.Add(new InstallParam(user, userValue)); t.LocalParams.Add(new InstallParam(pass, passValue)); t.LocalParams.Add(new InstallParam(prefix, prefixValue)); //act IEnumerable<ValidationResult> results = val.Evaluate(new Task[] { t}); Assert.Equal(errorsCount,results.Count(r => r.State == Sitecore9Installer.Validation.ValidatorState.Error)); } } }
using NSubstitute; using SIM.Sitecore9Installer.Tasks; using SIM.Sitecore9Installer.Validation; using SIM.Sitecore9Installer.Validation.Validators; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace SIM.Sitecore9Installer.Tests.Validation.Validators { public class SqlPefixValidatorTests { [Theory] [ClassData(typeof(ValidatorTestSetup))] public void NoDbsWithTheSamePrefix(IEnumerable<Task> tasks) { SqlPefixValidator val = Substitute.ForPartsOf<SqlPefixValidator>(); val.WhenForAnyArgs(v => v.GetDbList(null, null, null)).DoNotCallBase(); val.GetDbList(null, null, null).ReturnsForAnyArgs(new string[] { "someDb" }); string server = "SqlServer"; string user = "SqlAdminUser"; string pass = "SqlAdminPassword"; string prefix = "SqlDbPrefix"; val.Data["Server"] = server; val.Data["User"] = user; val.Data["Password"] = pass; val.Data["Prefix"] = prefix; Task t = tasks.First(); t.LocalParams.Add(new InstallParam(server, "sql-server")); t.LocalParams.Add(new InstallParam(user, "sql-user")); t.LocalParams.Add(new InstallParam(pass, "sql-pass")); t.LocalParams.Add(new InstallParam(prefix, "sql-prefix")); IEnumerable<ValidationResult> results = val.Evaluate(tasks); Assert.DoesNotContain(results, r => r.State != Sitecore9Installer.Validation.ValidatorState.Success); } [Theory] [ClassData(typeof(ValidatorTestSetup))] public void DbsWithTheSamePrefix(IEnumerable<Task> tasks) { SqlPefixValidator val = Substitute.ForPartsOf<SqlPefixValidator>(); val.WhenForAnyArgs(v => v.GetDbList(null, null, null)).DoNotCallBase(); string server = "SqlServer"; string user = "SqlAdminUser"; string pass = "SqlAdminPassword"; string prefix = "SqlDbPrefix"; val.Data["Server"] = server; val.Data["User"] = user; val.Data["Password"] = pass; val.Data["Prefix"] = prefix; Task t = tasks.First(); t.LocalParams.Add(new InstallParam(server, "sql-server")); t.LocalParams.Add(new InstallParam(user, "sql-user")); t.LocalParams.Add(new InstallParam(pass, "sql-pass")); t.LocalParams.Add(new InstallParam(prefix, "sql-prefix")); val.GetDbList(null, null, null).ReturnsForAnyArgs(new string[] { "sql-prefixDatabase","SomeOtherDb" }); IEnumerable<ValidationResult> results = val.Evaluate(tasks); Assert.Contains(results, r => r.State == Sitecore9Installer.Validation.ValidatorState.Error); } } }
mit
C#
44794a221458d9cbb9fc67050c2e5c949a0d23fe
Remove extra semicolon
ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework
osu.Framework/Host.cs
osu.Framework/Host.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 osu.Framework.Platform; using osu.Framework.Platform.Linux; using osu.Framework.Platform.MacOS; using osu.Framework.Platform.Windows; namespace osu.Framework { public static class Host { [Obsolete("Use GetSuitableHost(HostConfig) instead.")] public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: return new MacOSGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Windows: return new WindowsGameHost(gameName, bindIPC, portableInstallation); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS})."); } } public static DesktopGameHost GetSuitableHost(HostConfig hostConfig) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.Windows: return new WindowsGameHost(hostConfig); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(hostConfig); case RuntimeInfo.Platform.macOS: return new MacOSGameHost(hostConfig); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS})."); } } } }
// 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.Platform; using osu.Framework.Platform.Linux; using osu.Framework.Platform.MacOS; using osu.Framework.Platform.Windows; using System; namespace osu.Framework { public static class Host { [Obsolete("Use GetSuitableHost(HostConfig) instead.")] public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: return new MacOSGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Windows: return new WindowsGameHost(gameName, bindIPC, portableInstallation); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS})."); } } public static DesktopGameHost GetSuitableHost(HostConfig hostConfig) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.Windows: return new WindowsGameHost(hostConfig); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(hostConfig); case RuntimeInfo.Platform.macOS: return new MacOSGameHost(hostConfig); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS})."); }; } } }
mit
C#
0b508827e4af142c6fced073a86df4d9cb84ad2d
Add copy and paste into Procedural model
effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer
Dev/Editor/Effekseer/GUI/Dock/ProcedualModel.cs
Dev/Editor/Effekseer/GUI/Dock/ProcedualModel.cs
using System; using Effekseer.Data; namespace Effekseer.GUI.Dock { class ProcedualModel : DockPanel { readonly Component.ParameterList paramerterList = null; Component.CopyAndPaste candp = null; public ProcedualModel() { Label = Icons.PanelDynamicParams + Resources.GetString("ProcedualModel_Name") + "###ProcedualModel"; paramerterList = new Component.ParameterList(); candp = new Component.CopyAndPaste("ProceduralModel", GetTargetObject, Read); Core.OnAfterLoad += OnAfterLoad; Core.OnAfterNew += OnAfterLoad; Core.OnBeforeLoad += Core_OnBeforeLoad; Read(); TabToolTip = Resources.GetString("ProcedualModel_Name"); } public void FixValues() { paramerterList.FixValues(); } object GetTargetObject() { return Core.ProcedualModel.ProcedualModels.Selected; } public override void OnDisposed() { FixValues(); Core.OnAfterLoad -= OnAfterLoad; Core.OnAfterNew -= OnAfterLoad; Core.OnBeforeLoad -= Core_OnBeforeLoad; } protected override void UpdateInternal() { float width = Manager.NativeManager.GetContentRegionAvail().X; Manager.NativeManager.PushItemWidth(width - Manager.NativeManager.GetTextLineHeight() * 5.5f); var nextParam = Component.ObjectCollection.Select("", "", Core.ProcedualModel.ProcedualModels.Selected, false, Core.ProcedualModel.ProcedualModels); if (Core.ProcedualModel.ProcedualModels.Selected != nextParam) { Core.ProcedualModel.ProcedualModels.Selected = nextParam; } Manager.NativeManager.PopItemWidth(); Manager.NativeManager.SameLine(); if (Manager.NativeManager.Button(Resources.GetString("DynamicAdd") + "###DynamicAdd")) { Core.ProcedualModel.ProcedualModels.New(); } Manager.NativeManager.SameLine(); if (Manager.NativeManager.Button(Resources.GetString("DynamicDelete") + "###DynamicDelete")) { Core.ProcedualModel.ProcedualModels.Delete(Core.ProcedualModel.ProcedualModels.Selected); } candp.Update(); paramerterList.Update(); } private void Read() { paramerterList.SetValue(Core.ProcedualModel.ProcedualModels); } private void OnAfterLoad(object sender, EventArgs e) { Read(); } private void Core_OnBeforeLoad(object sender, EventArgs e) { paramerterList.SetValue(null); } } }
using System; using Effekseer.Data; namespace Effekseer.GUI.Dock { class ProcedualModel : DockPanel { readonly Component.ParameterList paramerterList = null; public ProcedualModel() { Label = Icons.PanelDynamicParams + Resources.GetString("ProcedualModel_Name") + "###ProcedualModel"; paramerterList = new Component.ParameterList(); Core.OnAfterLoad += OnAfterLoad; Core.OnAfterNew += OnAfterLoad; Core.OnBeforeLoad += Core_OnBeforeLoad; Read(); TabToolTip = Resources.GetString("ProcedualModel_Name"); } public void FixValues() { paramerterList.FixValues(); } public override void OnDisposed() { FixValues(); Core.OnAfterLoad -= OnAfterLoad; Core.OnAfterNew -= OnAfterLoad; Core.OnBeforeLoad -= Core_OnBeforeLoad; } protected override void UpdateInternal() { float width = Manager.NativeManager.GetContentRegionAvail().X; Manager.NativeManager.PushItemWidth(width - Manager.NativeManager.GetTextLineHeight() * 5.5f); var nextParam = Component.ObjectCollection.Select("", "", Core.ProcedualModel.ProcedualModels.Selected, false, Core.ProcedualModel.ProcedualModels); if (Core.ProcedualModel.ProcedualModels.Selected != nextParam) { Core.ProcedualModel.ProcedualModels.Selected = nextParam; } Manager.NativeManager.PopItemWidth(); Manager.NativeManager.SameLine(); if (Manager.NativeManager.Button(Resources.GetString("DynamicAdd") + "###DynamicAdd")) { Core.ProcedualModel.ProcedualModels.New(); } Manager.NativeManager.SameLine(); if (Manager.NativeManager.Button(Resources.GetString("DynamicDelete") + "###DynamicDelete")) { Core.ProcedualModel.ProcedualModels.Delete(Core.ProcedualModel.ProcedualModels.Selected); } paramerterList.Update(); } private void Read() { paramerterList.SetValue(Core.ProcedualModel.ProcedualModels); } private void OnAfterLoad(object sender, EventArgs e) { Read(); } private void Core_OnBeforeLoad(object sender, EventArgs e) { paramerterList.SetValue(null); } } }
mit
C#
375b3005c8f129b22a99f5a9f917dfa873a515b1
Add password button to LoggedIn set
ethanmoffat/EndlessClient
EndlessClient/ControlSets/LoggedInControlSet.cs
EndlessClient/ControlSets/LoggedInControlSet.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.Controllers; using EndlessClient.GameExecution; using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.ControlSets { public class LoggedInControlSet : IntermediateControlSet { private XNAButton _changePasswordButton; public override GameStates GameState { get { return GameStates.LoggedIn; } } public LoggedInControlSet(KeyboardDispatcher dispatcher, IMainButtonController mainButtonController) : base(dispatcher, mainButtonController) { } protected override void InitializeControlsHelper(IControlSet currentControlSet) { base.InitializeControlsHelper(currentControlSet); _changePasswordButton = GetControl(currentControlSet, GameControlIdentifier.ChangePasswordButton, GetPasswordButton); //login panels //password change button } public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) { switch (control) { case GameControlIdentifier.Character1Panel: case GameControlIdentifier.Character2Panel: case GameControlIdentifier.Character3Panel: return null; case GameControlIdentifier.ChangePasswordButton: return _changePasswordButton; default: return base.FindComponentByControlIdentifier(control); } } private XNAButton GetPasswordButton() { var button = new XNAButton(_secondaryButtonTexture, new Vector2(454, 417), new Rectangle(0, 120, 120, 40), new Rectangle(120, 120, 120, 40)); //button.OnClick += ... return button; } protected override XNAButton GetCreateButton() { var button = base.GetCreateButton(); button.OnClick += DoCreateCharacter; return button; } private void DoCreateCharacter(object sender, EventArgs e) { } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.Controllers; using EndlessClient.GameExecution; using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.ControlSets { public class LoggedInControlSet : IntermediateControlSet { public override GameStates GameState { get { return GameStates.LoggedIn; } } public LoggedInControlSet(KeyboardDispatcher dispatcher, IMainButtonController mainButtonController) : base(dispatcher, mainButtonController) { } protected override void InitializeControlsHelper(IControlSet currentControlSet) { base.InitializeControlsHelper(currentControlSet); //login panels //password change button } public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) { switch (control) { case GameControlIdentifier.Character1Panel: case GameControlIdentifier.Character2Panel: case GameControlIdentifier.Character3Panel: case GameControlIdentifier.ChangePasswordButton: return null; default: return base.FindComponentByControlIdentifier(control); } } protected override XNAButton GetCreateButton(bool isCreateCharacterButton) protected override XNAButton GetCreateButton() { var button = base.GetCreateButton(); button.OnClick += DoCreateCharacter; return button; } private void DoCreateCharacter(object sender, EventArgs e) { } } }
mit
C#
63ad6413c86aa8ff0f10dc8d1ed27560a7ccdfb8
Fix warning.
JohanLarsson/Gu.Roslyn.Asserts
Gu.Roslyn.Asserts.XUnit/AssertExceptionTests.cs
Gu.Roslyn.Asserts.XUnit/AssertExceptionTests.cs
namespace Gu.Roslyn.Asserts.XUnit { using Xunit; public class AssertExceptionTests { [Fact] public void CreateReturnsXunitException() { var exception = AssertException.Create("abc"); #pragma warning disable GU0011 // Don't ignore the return value. Assert.IsType<Xunit.Sdk.XunitException>(exception); #pragma warning restore GU0011 // Don't ignore the return value. Assert.Equal("abc", exception.Message); } } }
namespace Gu.Roslyn.Asserts.XUnit { using Xunit; public class AssertExceptionTests { [Fact] public void CreateReturnsXunitException() { var exception = AssertException.Create("abc"); Assert.IsType<Xunit.Sdk.XunitException>(exception); Assert.Equal("abc", exception.Message); } } }
mit
C#
e35377a93653f6bf74d0eb9dc7931698660ab427
Fix character list
Dreadlow/PolarisServer,cyberkitsune/PolarisServer,PolarisTeam/PolarisServer
PolarisServer/Packets/Handlers/CharacterList.cs
PolarisServer/Packets/Handlers/CharacterList.cs
using PolarisServer.Database; using System.Linq; namespace PolarisServer.Packets.Handlers { [PacketHandlerAttr(0x11, 0x02)] public class CharacterList : PacketHandler { #region implemented abstract members of PacketHandler public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size) { if (context.User == null) return; var writer = new PacketWriter(); using (var db = new PolarisEf()) { var chars = db.Characters .Where(w => w.Player.PlayerId == context.User.PlayerId) .OrderBy(o => o.CharacterId) // TODO: Order by last played .Select(s => s); writer.Write((uint)chars.Count()); // Number of characters for (var i = 0; i < 0x4; i++) // Whatever this is writer.Write((byte)0); foreach (var ch in chars) { writer.Write((uint)ch.CharacterId); writer.Write((uint)context.User.PlayerId); for (var i = 0; i < 0x10; i++) writer.Write((byte)0); writer.WriteFixedLengthUtf16(ch.Name, 16); writer.Write((uint)0); writer.WriteStruct(ch.Looks); // Note: Pre-Episode 4 created looks doesn't seem to work anymore writer.WriteStruct(ch.Jobs); for (var i = 0; i < 0xFC; i++) writer.Write((byte)0); } } // Ninji note: This packet may be followed by extra data, // after a fixed-length array of character data structures. // Needs more investigation at some point. // --- // CK note: Extra data is likely current equipment, playtime, etc. // All of that data is currently unaccounted for at the moment. context.SendPacket(0x11, 0x03, 0, writer.ToArray()); } #endregion } }
using PolarisServer.Database; using System.Linq; namespace PolarisServer.Packets.Handlers { [PacketHandlerAttr(0x11, 0x02)] public class RequestCharacterList : PacketHandler { #region implemented abstract members of PacketHandler public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size) { if (context.User == null) return; var writer = new PacketWriter(); using (var db = new PolarisEf()) { var chars = from c in db.Characters where c.Player.PlayerId == context.User.PlayerId select c; writer.Write((uint)chars.Count()); foreach (var ch in chars) { writer.Write((uint)ch.CharacterId); writer.Write((uint)context.User.PlayerId); for (var i = 0; i < 0xC; i++) writer.Write((byte)0); writer.WriteFixedLengthUtf16(ch.Name, 16); writer.Write((uint)0); writer.WriteStruct(ch.Looks); writer.WriteStruct(ch.Jobs); for (var i = 0; i < 0x44; i++) writer.Write((byte)0); } } // Ninji note: This packet may be followed by extra data, // after a fixed-length array of character data structures. // Needs more investigation at some point. // --- // CK note: Extra data is likely current equipment, playtime, etc. // All of that data is currently unaccounted for at the moment. context.SendPacket(0x11, 0x03, 0, writer.ToArray()); } #endregion } }
agpl-3.0
C#
95b8fb09417d5e2d65a059f72b6689253ac7fdc6
update slotname in redirect_uri
fashaikh/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/SimpleWAWS,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS,projectkudu/TryAppService,projectkudu/TryAppService,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/TryAppService
SimpleWAWS/Authentication/GoogleAuthProvider.cs
SimpleWAWS/Authentication/GoogleAuthProvider.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); var slot = String.Empty; if (context.Request.QueryString["x-ms-routing-name"] != null) slot = $"?x-ms-routing-name={context.Request.QueryString["x-ms-routing-name"]}"; builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login{1}", context.Request.Headers["HOST"], slot))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); if (context.IsFunctionsPortalRequest()) { builder.AppendFormat("&state={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "{0}{1}", context.Request.Headers["Referer"], context.Request.Url.Query) )); } else builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); if (context.IsFunctionsPortalRequest()) { var slot = String.Empty; if (context.Request.QueryString["x-ms-routing-name"] != null) slot = $"?x-ms-routing-name={context.Request.QueryString["x-ms-routing-name"]}"; builder.AppendFormat($"{slot}&state={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "{0}{1}", context.Request.Headers["Referer"], context.Request.Url.Query) )); } else builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
apache-2.0
C#
f35ba6330b263e10d8c4a790105eb16c744ea760
Adjust papparlell
michael-reichenauer/Dependinator
Dependinator/ModelParsing/Private/MonoCecilReflection/Private/ReflectionService.cs
Dependinator/ModelParsing/Private/MonoCecilReflection/Private/ReflectionService.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Dependinator.ModelParsing.Private.SolutionFileParsing; using Dependinator.Utils; namespace Dependinator.ModelParsing.Private.MonoCecilReflection.Private { internal class ReflectionService : IReflectionService { public async Task AnalyzeAsync(string filePath, ModelItemsCallback modelItemsCallback) { // filePath = @"C:\Work Files\GitMind\GitMind.sln"; Log.Debug($"Analyze {filePath} ..."); Timing t = Timing.Start(); IReadOnlyList<string> assemblyPaths = Get(filePath); //NotificationReceiver receiver = new NotificationReceiver(modelItemsCallback); //NotificationSender sender = new NotificationSender(receiver); int maxParallel = (int)Math.Ceiling((Environment.ProcessorCount * 0.75) * 1.0); var option = new ParallelOptions {MaxDegreeOfParallelism = maxParallel }; await Task.Run(() => { Parallel.ForEach(assemblyPaths, option, path => AnalyzeAssembly(path, modelItemsCallback)); }); t.Log($"Analyzed {filePath}"); } private static IReadOnlyList<string> Get(string filePath) { Timing t = Timing.Start(); IReadOnlyList<string> assemblyPaths; if (Path.GetExtension(filePath).IsSameIgnoreCase(".sln")) { Solution solution = new Solution(filePath); assemblyPaths = solution.GetProjectOutputPaths("Debug").ToList(); } else { assemblyPaths = new[] { filePath }; } t.Log($"Parsed file {filePath} for {assemblyPaths.Count} assembly paths"); return assemblyPaths; } private static void AnalyzeAssembly(string assemblyPath, ModelItemsCallback modelItemsCallback) { Log.Debug($"Analyze {assemblyPath} ..."); Timing t = Timing.Start(); if (File.Exists(assemblyPath)) { AssemblyAnalyzer analyzer = new AssemblyAnalyzer(); analyzer.Analyze(assemblyPath, modelItemsCallback); } else { Log.Warn($"Assembly path does not exists {assemblyPath}"); } t.Log($"Analyzed assembly {assemblyPath}"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Dependinator.ModelParsing.Private.SolutionFileParsing; using Dependinator.Utils; namespace Dependinator.ModelParsing.Private.MonoCecilReflection.Private { internal class ReflectionService : IReflectionService { public async Task AnalyzeAsync(string filePath, ModelItemsCallback modelItemsCallback) { // filePath = @"C:\Work Files\GitMind\GitMind.sln"; Log.Debug($"Analyze {filePath} ..."); Timing t = Timing.Start(); IReadOnlyList<string> assemblyPaths = Get(filePath); //NotificationReceiver receiver = new NotificationReceiver(modelItemsCallback); //NotificationSender sender = new NotificationSender(receiver); await Task.Run(() => { Parallel.ForEach(assemblyPaths, path => AnalyzeAssembly(path, modelItemsCallback)); }); t.Log($"Analyzed {filePath}"); } private static IReadOnlyList<string> Get(string filePath) { Timing t = Timing.Start(); IReadOnlyList<string> assemblyPaths; if (Path.GetExtension(filePath).IsSameIgnoreCase(".sln")) { Solution solution = new Solution(filePath); assemblyPaths = solution.GetProjectOutputPaths("Debug").ToList(); } else { assemblyPaths = new[] { filePath }; } t.Log($"Parsed file {filePath} for {assemblyPaths.Count} assembly paths"); return assemblyPaths; } private static void AnalyzeAssembly(string assemblyPath, ModelItemsCallback modelItemsCallback) { Log.Debug($"Analyze {assemblyPath} ..."); Timing t = Timing.Start(); if (File.Exists(assemblyPath)) { AssemblyAnalyzer analyzer = new AssemblyAnalyzer(); analyzer.Analyze(assemblyPath, modelItemsCallback); } else { Log.Warn($"Assembly path does not exists {assemblyPath}"); } t.Log($"Analyzed assembly {assemblyPath}"); } } }
mit
C#
e116beb13b7ad1a9551b168d4cdd7c630aa9e2d5
Update JsonGrainStateSerializer.cs
OrleansContrib/Orleans.Providers.MongoDB
Orleans.Providers.MongoDB/StorageProviders/Serializers/JsonGrainStateSerializer.cs
Orleans.Providers.MongoDB/StorageProviders/Serializers/JsonGrainStateSerializer.cs
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Orleans.Providers.MongoDB.Configuration; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.Providers.MongoDB.StorageProviders.Serializers { public class JsonGrainStateSerializer : IGrainStateSerializer { private readonly JsonSerializer serializer; public JsonGrainStateSerializer(ITypeResolver typeResolver, IGrainFactory grainFactory, MongoDBGrainStorageOptions options) { var jsonSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory); options?.ConfigureJsonSerializerSettings?.Invoke(jsonSettings); this.serializer = JsonSerializer.Create(jsonSettings); if (options?.ConfigureJsonSerializerSettings == null) { //// https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/44 //// Always include the default value, so that the deserialization process can overwrite default //// values that are not equal to the system defaults. this.serializer.NullValueHandling = NullValueHandling.Include; this.serializer.DefaultValueHandling = DefaultValueHandling.Populate; } } public void Deserialize(IGrainState grainState, JObject entityData) { var jsonReader = new JTokenReader(entityData); serializer.Populate(jsonReader, grainState.State); } public JObject Serialize(IGrainState grainState) { return JObject.FromObject(grainState.State, serializer); } } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Orleans.Providers.MongoDB.Configuration; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.Providers.MongoDB.StorageProviders.Serializers { public class JsonGrainStateSerializer : IGrainStateSerializer { private readonly JsonSerializer serializer; public JsonGrainStateSerializer(ITypeResolver typeResolver, IGrainFactory grainFactory, MongoDBGrainStorageOptions options) { var jsonSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory); options?.ConfigureJsonSerializerSettings?.Invoke(jsonSettings); this.serializer = JsonSerializer.Create(jsonSettings); if(options?.ConfigureJsonSerializerSettings == null) { //// https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/44 //// Always include the default value, so that the deserialization process can overwrite default //// values that are not equal to the system defaults. this.serializer.NullValueHandling = NullValueHandling.Include; this.serializer.DefaultValueHandling = DefaultValueHandling.Populate; } } public void Deserialize(IGrainState grainState, JObject entityData) { var jsonReader = new JTokenReader(entityData); serializer.Populate(jsonReader, grainState.State); } public JObject Serialize(IGrainState grainState) { return JObject.FromObject(grainState.State, serializer); } } }
mit
C#
27cc50062262142bfbfda33648d0bf0b92a2c4fc
remove logging
NDark/ndinfrastructure,NDark/ndinfrastructure
Unity/Platform/Region/Plugins/PlatformRegion.cs
Unity/Platform/Region/Plugins/PlatformRegion.cs
/** MIT License Copyright (c) 2017 - 2021 NDark 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. */ /** * https://wenrongdev.com/unity53-native-system-language/ */ using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Runtime.InteropServices; public static class PlatformRegion { public static string CheckUnityApplicationSystemLanguage() { string ret = string.Empty; SystemLanguage unitySystemLangauge = Application.systemLanguage; ret = unitySystemLangauge.ToString(); // Debug.Log("CheckApplicationSystemLanguage() ret=" + ret); return ret ; } #if UNITY_ANDROID public static string CurrentAndroidLanguage() { string result = ""; using (AndroidJavaClass cls = new AndroidJavaClass("java.util.Locale")) { if (cls != null) { using (AndroidJavaObject locale = cls.CallStatic<AndroidJavaObject>("getDefault")) { if (locale != null) { result = locale.Call<string>("getLanguage") + "_" + locale.Call<string>("getDefault"); Debug.Log("CurrentAndroidLanguage() Android lang: " + result); } else { Debug.LogError("CurrentAndroidLanguage() locale null"); } } } else { Debug.LogError("CurrentAndroidLanguage() cls null"); } } Debug.LogWarning("CurrentAndroidLanguage() result" + result); return result; } #endif #if UNITY_IPHONE [DllImport("__Internal")] private static extern string CurIOSLang(); public static string CurrentiOSLanguage() { string ret = CurIOSLang(); Debug.LogWarning("CurrentAndroidLanguage() ret" + ret); return ret; } #endif }
/** MIT License Copyright (c) 2017 - 2021 NDark 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. */ /** * https://wenrongdev.com/unity53-native-system-language/ */ using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Runtime.InteropServices; public static class PlatformRegion { public static string CheckUnityApplicationSystemLanguage() { string ret = string.Empty; SystemLanguage unitySystemLangauge = Application.systemLanguage; ret = unitySystemLangauge.ToString(); Debug.Log("CheckApplicationSystemLanguage() ret=" + ret); return ret ; } #if UNITY_ANDROID public static string CurrentAndroidLanguage() { string result = ""; using (AndroidJavaClass cls = new AndroidJavaClass("java.util.Locale")) { if (cls != null) { using (AndroidJavaObject locale = cls.CallStatic<AndroidJavaObject>("getDefault")) { if (locale != null) { result = locale.Call<string>("getLanguage") + "_" + locale.Call<string>("getDefault"); Debug.Log("CurrentAndroidLanguage() Android lang: " + result); } else { Debug.LogError("CurrentAndroidLanguage() locale null"); } } } else { Debug.LogError("CurrentAndroidLanguage() cls null"); } } Debug.LogWarning("CurrentAndroidLanguage() result" + result); return result; } #endif #if UNITY_IPHONE [DllImport("__Internal")] private static extern string CurIOSLang(); public static string CurrentiOSLanguage() { string ret = CurIOSLang(); Debug.LogWarning("CurrentAndroidLanguage() ret" + ret); return ret; } #endif }
mit
C#
2a1edcefdccd363ffc89b29986b49a26702d9754
Update EntryPoint.cs
5minlab/minamo,5minlab/minamo,5minlab/minamo
UnityProject/Assets/Minamo/Editor/EntryPoint.cs
UnityProject/Assets/Minamo/Editor/EntryPoint.cs
using System.IO; using UnityEngine; namespace Assets.Minamo.Editor { /// <summary> /// cli entry point /// </summary> public class EntryPoint { public static void Build() { string configFilePath; if (!EnvironmentReader.TryRead("CONFIG_PATH", out configFilePath)) { Debug.Log("cannot find CONFIG_PATH"); return; } string outputFilePath; if (!EnvironmentReader.TryRead("OUTPUT_PATH", out outputFilePath)) { Debug.Log("cannot find OUTPUT_PATH"); return; } BuildCommon(configFilePath, outputFilePath); } internal static void BuildCommon(string configFilePath, string outputFilePath) { var content = File.ReadAllText(configFilePath); var config = new Config(content); var currModifiers = config.CreateCurrentModifiers(); var nextModifiers = config.CreateConfigModifiers(); foreach (var m in nextModifiers) { var tokens = m.GetType().ToString().Split('.'); var name = tokens[tokens.Length - 1]; Debug.LogFormat("[MinamoLog] {0}: {1}", name, m.GetConfigText()); m.Apply(); } var executor = config.PlayerBuild; Debug.LogFormat("[MinamoLog] {0}: {1}", "PlayerBuildExecutor", executor.GetConfigText()); executor.Build(outputFilePath); // restore foreach (var m in currModifiers) { m.Apply(); } } public static void ExportPackage() { string output; if (EnvironmentReader.TryRead("EXPORT_PATH", out output)) { Debug.LogFormat("export package : {0}", output); var b = new PackageBuilder(); b.Build(output); } } public static void VersionName() { var v = Version.Name(); Debug.LogFormat("MinamoVersion={0}", v); } } }
using System.IO; using UnityEngine; namespace Assets.Minamo.Editor { /// <summary> /// cli entry point /// </summary> public class EntryPoint { public static void Build() { string configFilePath; if (!EnvironmentReader.TryRead("CONFIG_PATH", out configFilePath)) { Debug.Log("cannot find CONFIG_PATH"); return; } string outputFilePath; if (!EnvironmentReader.TryRead("OUTPUT_PATH", out outputFilePath)) { Debug.Log("cannot find OUTPUT_PATH"); return; } BuildCommon(configFilePath, outputFilePath); } internal static void BuildCommon(string configFilePath, string outputFilePath) { var content = File.ReadAllText(configFilePath); var config = new Config(content); var currModifiers = config.CreateCurrentModifiers(); var nextModifiers = config.CreateCurrentModifiers(); foreach (var m in nextModifiers) { var tokens = m.GetType().ToString().Split('.'); var name = tokens[tokens.Length - 1]; Debug.LogFormat("[MinamoLog] {0}: {1}", name, m.GetConfigText()); m.Apply(); } var executor = config.PlayerBuild; Debug.LogFormat("[MinamoLog] {0}: {1}", "PlayerBuildExecutor", executor.GetConfigText()); executor.Build(outputFilePath); // restore foreach (var m in currModifiers) { m.Apply(); } } public static void ExportPackage() { string output; if (EnvironmentReader.TryRead("EXPORT_PATH", out output)) { Debug.LogFormat("export package : {0}", output); var b = new PackageBuilder(); b.Build(output); } } public static void VersionName() { var v = Version.Name(); Debug.LogFormat("MinamoVersion={0}", v); } } }
mit
C#
1a298503a6d65b954405e28d014902e65b1ce5e8
Initialize GitExecutable with the git executable path
appharbor/appharbor-cli
src/AppHarbor/GitExecutable.cs
src/AppHarbor/GitExecutable.cs
using System; using System.IO; namespace AppHarbor { public class GitExecutable { private readonly FileInfo _gitExecutable; public GitExecutable() { var programFilesPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); var gitExecutablePath = Path.Combine(programFilesPath, "Git", "bin", "git.exe"); _gitExecutable = new FileInfo(gitExecutablePath); } } }
namespace AppHarbor { public class GitExecutable { } }
mit
C#
fba8a66d70c8ac350abd275af1e9ed9aaf9088aa
increase version no
gigya/microdot
SolutionVersion.cs
SolutionVersion.cs
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // 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 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER 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.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Gigya Inc.")] [assembly: AssemblyCopyright("© 2018 Gigya Inc.")] [assembly: AssemblyDescription("Microdot Framework")] [assembly: AssemblyVersion("1.7.11.0")] [assembly: AssemblyFileVersion("1.7.11.0")] [assembly: AssemblyInformationalVersion("1.7.11.0")] // 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)] [assembly: CLSCompliant(false)]
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // 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 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER 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.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Gigya Inc.")] [assembly: AssemblyCopyright("© 2018 Gigya Inc.")] [assembly: AssemblyDescription("Microdot Framework")] [assembly: AssemblyVersion("1.7.10.0")] [assembly: AssemblyFileVersion("1.7.10.0")] [assembly: AssemblyInformationalVersion("1.7.10.0")] // 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)] [assembly: CLSCompliant(false)]
apache-2.0
C#
be1151862ddeb89e6142ad7e9fea130c6c0c8c9c
Test the "XmlOnlY" case and unspecified case on .WithAccept() In both cases, content type should be "application/xml"
gregsochanik/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper
src/SevenDigital.Api.Wrapper.Integration.Tests/EndpointTests/ResponseAcceptTests.cs
src/SevenDigital.Api.Wrapper.Integration.Tests/EndpointTests/ResponseAcceptTests.cs
using System.Net; using Newtonsoft.Json.Linq; using NUnit.Framework; using SevenDigital.Api.Schema.Releases; using SevenDigital.Api.Wrapper.Requests; namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests { [TestFixture] public class ResponseAcceptTests { [Test] public async void Response_with_JsonPreferred_should_be_Ok_status() { var request = RequestARelease() .WithAccept(AcceptFormat.JsonPreferred); var response = await request.Response(); Assert.That(response, Is.Not.Null); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [Test] public async void Response_with_JsonPreferred_should_be_json() { var request = RequestARelease() .WithAccept(AcceptFormat.JsonPreferred); var response = await request.Response(); Assert.That(response.Body, Is.Not.StringContaining("xml")); Assert.That(response.Body, Is.Not.StringContaining("<")); Assert.That(response.Body, Is.StringContaining("{")); dynamic json = JObject.Parse(response.Body); Assert.That(json, Is.Not.Null); } [Test] public async void Response_with_JsonPreferred_should_have_json_ContentType() { var request = RequestARelease() .WithAccept(AcceptFormat.JsonPreferred); var response = await request.Response(); Assert.That(response.Headers.ContainsKey("Content-Type"), Is.True); Assert.That(response.Headers["Content-Type"], Is.StringStarting("application/json")); Assert.That(response.ContentTypeIsJson(), Is.True); } [Test] public async void Response_with_XmlOnly_should_have_xml_ContentType() { var request = RequestARelease() .WithAccept(AcceptFormat.XmlOnly); var response = await request.Response(); Assert.That(response, Is.Not.Null); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); Assert.That(response.Headers.ContainsKey("Content-Type"), Is.True); Assert.That(response.Headers["Content-Type"], Is.StringStarting("application/xml")); Assert.That(response.ContentTypeIsJson(), Is.False); } [Test] public async void Response_with_default_accept_should_have_xml_ContentType() { var request = RequestARelease(); var response = await request.Response(); Assert.That(response, Is.Not.Null); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); Assert.That(response.Headers.ContainsKey("Content-Type"), Is.True); Assert.That(response.Headers["Content-Type"], Is.StringStarting("application/xml")); Assert.That(response.ContentTypeIsJson(), Is.False); } private IFluentApi<Release> RequestARelease() { return Api<Release>.Create .ForReleaseId(1685647) .WithParameter("country", "GB"); } } }
using System.Net; using Newtonsoft.Json.Linq; using NUnit.Framework; using SevenDigital.Api.Schema.Releases; using SevenDigital.Api.Wrapper.Requests; namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests { [TestFixture] public class ResponseAcceptTests { [Test] public async void Response_With_JsonPreferred_ShouldBeOk() { var request = Api<Release>.Create .ForReleaseId(1685647) .WithParameter("country", "GB") .WithAccept(AcceptFormat.JsonPreferred); var response = await request.Response(); Assert.That(response, Is.Not.Null); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); } [Test] public async void Response_With_JsonPreferred_ShouldBeJson() { var request = Api<Release>.Create .ForReleaseId(1685647) .WithParameter("country", "GB") .WithAccept(AcceptFormat.JsonPreferred); var response = await request.Response(); Assert.That(response.Body, Is.Not.StringContaining("xml")); Assert.That(response.Body, Is.Not.StringContaining("<")); Assert.That(response.Body, Is.StringContaining("{")); dynamic json = JObject.Parse(response.Body); Assert.That(json, Is.Not.Null); } [Test] public async void Response_With_JsonPreferred_ShouldHave_jsonContentType() { var request = Api<Release>.Create .ForReleaseId(1685647) .WithParameter("country", "GB") .WithAccept(AcceptFormat.JsonPreferred); var response = await request.Response(); Assert.That(response.Headers.ContainsKey("Content-Type"), Is.True); Assert.That(response.Headers["Content-Type"], Is.StringStarting("application/json")); Assert.That(response.ContentTypeIsJson(), Is.True); } } }
mit
C#
36f6ba3db36cbab481920f63bed3b695d183f766
Rename _hashProvider to _hMacProvider.
rahku/corefx,ravimeda/corefx,nelsonsar/corefx,Jiayili1/corefx,shimingsg/corefx,dtrebbien/corefx,stephenmichaelf/corefx,mmitche/corefx,gkhanna79/corefx,cydhaselton/corefx,rahku/corefx,twsouthwick/corefx,cartermp/corefx,shmao/corefx,benpye/corefx,tijoytom/corefx,vidhya-bv/corefx-sorting,Yanjing123/corefx,JosephTremoulet/corefx,elijah6/corefx,Priya91/corefx-1,Jiayili1/corefx,richlander/corefx,krk/corefx,parjong/corefx,brett25/corefx,vs-team/corefx,marksmeltzer/corefx,jlin177/corefx,mokchhya/corefx,benpye/corefx,Petermarcu/corefx,benjamin-bader/corefx,janhenke/corefx,gkhanna79/corefx,Frank125/corefx,Chrisboh/corefx,janhenke/corefx,josguil/corefx,ravimeda/corefx,khdang/corefx,ellismg/corefx,nchikanov/corefx,yizhang82/corefx,MaggieTsang/corefx,PatrickMcDonald/corefx,manu-silicon/corefx,n1ghtmare/corefx,billwert/corefx,mellinoe/corefx,PatrickMcDonald/corefx,shrutigarg/corefx,twsouthwick/corefx,seanshpark/corefx,KrisLee/corefx,dhoehna/corefx,twsouthwick/corefx,ravimeda/corefx,tstringer/corefx,dhoehna/corefx,adamralph/corefx,ericstj/corefx,seanshpark/corefx,tijoytom/corefx,ptoonen/corefx,alexperovich/corefx,manu-silicon/corefx,krk/corefx,twsouthwick/corefx,Chrisboh/corefx,shmao/corefx,marksmeltzer/corefx,rjxby/corefx,huanjie/corefx,alexperovich/corefx,shimingsg/corefx,jlin177/corefx,ViktorHofer/corefx,ptoonen/corefx,khdang/corefx,nelsonsar/corefx,the-dwyer/corefx,seanshpark/corefx,nbarbettini/corefx,janhenke/corefx,fgreinacher/corefx,lggomez/corefx,nbarbettini/corefx,alphonsekurian/corefx,yizhang82/corefx,ptoonen/corefx,zhenlan/corefx,akivafr123/corefx,parjong/corefx,pgavlin/corefx,mafiya69/corefx,stone-li/corefx,mafiya69/corefx,tijoytom/corefx,zhenlan/corefx,SGuyGe/corefx,mafiya69/corefx,jhendrixMSFT/corefx,690486439/corefx,Alcaro/corefx,mmitche/corefx,jcme/corefx,krk/corefx,SGuyGe/corefx,mmitche/corefx,Petermarcu/corefx,MaggieTsang/corefx,mazong1123/corefx,kkurni/corefx,vidhya-bv/corefx-sorting,janhenke/corefx,nbarbettini/corefx,dhoehna/corefx,shmao/corefx,jcme/corefx,lggomez/corefx,stone-li/corefx,DnlHarvey/corefx,shmao/corefx,mellinoe/corefx,Priya91/corefx-1,shrutigarg/corefx,manu-silicon/corefx,jcme/corefx,mafiya69/corefx,richlander/corefx,richlander/corefx,JosephTremoulet/corefx,gregg-miskelly/corefx,kyulee1/corefx,parjong/corefx,dsplaisted/corefx,ravimeda/corefx,rjxby/corefx,690486439/corefx,andyhebear/corefx,weltkante/corefx,heXelium/corefx,nchikanov/corefx,pallavit/corefx,jcme/corefx,the-dwyer/corefx,tstringer/corefx,mellinoe/corefx,kyulee1/corefx,ericstj/corefx,tstringer/corefx,twsouthwick/corefx,lggomez/corefx,parjong/corefx,pallavit/corefx,billwert/corefx,alexandrnikitin/corefx,jeremymeng/corefx,dhoehna/corefx,vidhya-bv/corefx-sorting,ericstj/corefx,elijah6/corefx,stone-li/corefx,shmao/corefx,Chrisboh/corefx,nchikanov/corefx,DnlHarvey/corefx,heXelium/corefx,alphonsekurian/corefx,benjamin-bader/corefx,Petermarcu/corefx,elijah6/corefx,Yanjing123/corefx,jcme/corefx,lggomez/corefx,nbarbettini/corefx,lggomez/corefx,zmaruo/corefx,benpye/corefx,lydonchandra/corefx,MaggieTsang/corefx,shahid-pk/corefx,Ermiar/corefx,pallavit/corefx,alphonsekurian/corefx,mazong1123/corefx,rahku/corefx,fgreinacher/corefx,jlin177/corefx,dotnet-bot/corefx,alexperovich/corefx,krytarowski/corefx,Chrisboh/corefx,billwert/corefx,ellismg/corefx,elijah6/corefx,marksmeltzer/corefx,axelheer/corefx,YoupHulsebos/corefx,rajansingh10/corefx,wtgodbe/corefx,wtgodbe/corefx,parjong/corefx,n1ghtmare/corefx,SGuyGe/corefx,s0ne0me/corefx,SGuyGe/corefx,ellismg/corefx,alexandrnikitin/corefx,yizhang82/corefx,jlin177/corefx,jcme/corefx,dhoehna/corefx,andyhebear/corefx,ptoonen/corefx,kkurni/corefx,shrutigarg/corefx,stephenmichaelf/corefx,YoupHulsebos/corefx,krytarowski/corefx,mmitche/corefx,billwert/corefx,mazong1123/corefx,weltkante/corefx,shrutigarg/corefx,mazong1123/corefx,dhoehna/corefx,YoupHulsebos/corefx,rahku/corefx,Chrisboh/corefx,lggomez/corefx,lydonchandra/corefx,MaggieTsang/corefx,ravimeda/corefx,MaggieTsang/corefx,elijah6/corefx,Ermiar/corefx,seanshpark/corefx,dsplaisted/corefx,kkurni/corefx,cartermp/corefx,gregg-miskelly/corefx,tstringer/corefx,rubo/corefx,CloudLens/corefx,pgavlin/corefx,YoupHulsebos/corefx,axelheer/corefx,krk/corefx,PatrickMcDonald/corefx,tstringer/corefx,brett25/corefx,comdiv/corefx,shimingsg/corefx,BrennanConroy/corefx,jlin177/corefx,benjamin-bader/corefx,krytarowski/corefx,jeremymeng/corefx,the-dwyer/corefx,dhoehna/corefx,stone-li/corefx,matthubin/corefx,nelsonsar/corefx,zhenlan/corefx,seanshpark/corefx,comdiv/corefx,the-dwyer/corefx,yizhang82/corefx,gkhanna79/corefx,Priya91/corefx-1,stormleoxia/corefx,Jiayili1/corefx,vs-team/corefx,tijoytom/corefx,mafiya69/corefx,tijoytom/corefx,gregg-miskelly/corefx,billwert/corefx,mellinoe/corefx,CherryCxldn/corefx,krk/corefx,690486439/corefx,dsplaisted/corefx,Frank125/corefx,Petermarcu/corefx,josguil/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,PatrickMcDonald/corefx,ericstj/corefx,jhendrixMSFT/corefx,parjong/corefx,the-dwyer/corefx,nchikanov/corefx,marksmeltzer/corefx,adamralph/corefx,tijoytom/corefx,benpye/corefx,gkhanna79/corefx,690486439/corefx,matthubin/corefx,billwert/corefx,rajansingh10/corefx,alphonsekurian/corefx,benjamin-bader/corefx,mazong1123/corefx,josguil/corefx,krk/corefx,690486439/corefx,marksmeltzer/corefx,krk/corefx,Jiayili1/corefx,benjamin-bader/corefx,khdang/corefx,vidhya-bv/corefx-sorting,dotnet-bot/corefx,rahku/corefx,mmitche/corefx,Alcaro/corefx,lydonchandra/corefx,rubo/corefx,pallavit/corefx,KrisLee/corefx,BrennanConroy/corefx,stephenmichaelf/corefx,shahid-pk/corefx,jeremymeng/corefx,JosephTremoulet/corefx,jhendrixMSFT/corefx,ptoonen/corefx,cydhaselton/corefx,manu-silicon/corefx,axelheer/corefx,shmao/corefx,jhendrixMSFT/corefx,nchikanov/corefx,rubo/corefx,dotnet-bot/corefx,mokchhya/corefx,jlin177/corefx,krytarowski/corefx,stormleoxia/corefx,nchikanov/corefx,Yanjing123/corefx,KrisLee/corefx,stone-li/corefx,Alcaro/corefx,stone-li/corefx,CloudLens/corefx,mokchhya/corefx,PatrickMcDonald/corefx,iamjasonp/corefx,alexperovich/corefx,vidhya-bv/corefx-sorting,stephenmichaelf/corefx,the-dwyer/corefx,axelheer/corefx,dotnet-bot/corefx,Petermarcu/corefx,rjxby/corefx,khdang/corefx,ravimeda/corefx,Ermiar/corefx,jlin177/corefx,JosephTremoulet/corefx,gregg-miskelly/corefx,dtrebbien/corefx,zhenlan/corefx,ericstj/corefx,comdiv/corefx,zhenlan/corefx,cydhaselton/corefx,ravimeda/corefx,rajansingh10/corefx,DnlHarvey/corefx,billwert/corefx,comdiv/corefx,stephenmichaelf/corefx,pallavit/corefx,khdang/corefx,Yanjing123/corefx,shimingsg/corefx,uhaciogullari/corefx,stormleoxia/corefx,ViktorHofer/corefx,manu-silicon/corefx,fgreinacher/corefx,MaggieTsang/corefx,bitcrazed/corefx,krytarowski/corefx,akivafr123/corefx,krytarowski/corefx,shimingsg/corefx,BrennanConroy/corefx,janhenke/corefx,heXelium/corefx,Frank125/corefx,DnlHarvey/corefx,n1ghtmare/corefx,alphonsekurian/corefx,SGuyGe/corefx,matthubin/corefx,CherryCxldn/corefx,Petermarcu/corefx,iamjasonp/corefx,uhaciogullari/corefx,wtgodbe/corefx,weltkante/corefx,tstringer/corefx,ellismg/corefx,benpye/corefx,weltkante/corefx,kkurni/corefx,s0ne0me/corefx,iamjasonp/corefx,alexperovich/corefx,KrisLee/corefx,lydonchandra/corefx,Priya91/corefx-1,the-dwyer/corefx,kkurni/corefx,brett25/corefx,stormleoxia/corefx,seanshpark/corefx,nbarbettini/corefx,pallavit/corefx,rahku/corefx,shimingsg/corefx,bitcrazed/corefx,cydhaselton/corefx,twsouthwick/corefx,richlander/corefx,huanjie/corefx,dotnet-bot/corefx,yizhang82/corefx,rjxby/corefx,MaggieTsang/corefx,cartermp/corefx,heXelium/corefx,iamjasonp/corefx,rjxby/corefx,Jiayili1/corefx,jhendrixMSFT/corefx,shimingsg/corefx,alphonsekurian/corefx,rjxby/corefx,ViktorHofer/corefx,ViktorHofer/corefx,DnlHarvey/corefx,josguil/corefx,adamralph/corefx,cydhaselton/corefx,JosephTremoulet/corefx,twsouthwick/corefx,ptoonen/corefx,cartermp/corefx,mokchhya/corefx,dtrebbien/corefx,fgreinacher/corefx,kyulee1/corefx,Jiayili1/corefx,nchikanov/corefx,ellismg/corefx,Frank125/corefx,nbarbettini/corefx,seanshpark/corefx,weltkante/corefx,pgavlin/corefx,ViktorHofer/corefx,alexandrnikitin/corefx,Ermiar/corefx,wtgodbe/corefx,weltkante/corefx,cartermp/corefx,Ermiar/corefx,mellinoe/corefx,elijah6/corefx,weltkante/corefx,iamjasonp/corefx,jhendrixMSFT/corefx,mafiya69/corefx,richlander/corefx,Ermiar/corefx,josguil/corefx,alexandrnikitin/corefx,kkurni/corefx,CherryCxldn/corefx,gkhanna79/corefx,huanjie/corefx,jeremymeng/corefx,akivafr123/corefx,gkhanna79/corefx,JosephTremoulet/corefx,nelsonsar/corefx,ViktorHofer/corefx,bitcrazed/corefx,rubo/corefx,s0ne0me/corefx,mokchhya/corefx,alexperovich/corefx,richlander/corefx,JosephTremoulet/corefx,ptoonen/corefx,akivafr123/corefx,marksmeltzer/corefx,matthubin/corefx,yizhang82/corefx,vs-team/corefx,Priya91/corefx-1,stephenmichaelf/corefx,richlander/corefx,Petermarcu/corefx,wtgodbe/corefx,CloudLens/corefx,wtgodbe/corefx,uhaciogullari/corefx,ellismg/corefx,kyulee1/corefx,mazong1123/corefx,shahid-pk/corefx,CherryCxldn/corefx,shahid-pk/corefx,Alcaro/corefx,jeremymeng/corefx,bitcrazed/corefx,rjxby/corefx,akivafr123/corefx,josguil/corefx,YoupHulsebos/corefx,pgavlin/corefx,khdang/corefx,uhaciogullari/corefx,Chrisboh/corefx,benpye/corefx,vs-team/corefx,andyhebear/corefx,alexandrnikitin/corefx,nbarbettini/corefx,rahku/corefx,shahid-pk/corefx,tijoytom/corefx,mellinoe/corefx,zhenlan/corefx,wtgodbe/corefx,n1ghtmare/corefx,rajansingh10/corefx,SGuyGe/corefx,mmitche/corefx,CloudLens/corefx,shmao/corefx,parjong/corefx,Jiayili1/corefx,marksmeltzer/corefx,Ermiar/corefx,mazong1123/corefx,manu-silicon/corefx,dotnet-bot/corefx,axelheer/corefx,Yanjing123/corefx,iamjasonp/corefx,iamjasonp/corefx,elijah6/corefx,lggomez/corefx,zhenlan/corefx,ericstj/corefx,benjamin-bader/corefx,YoupHulsebos/corefx,gkhanna79/corefx,stone-li/corefx,zmaruo/corefx,andyhebear/corefx,manu-silicon/corefx,zmaruo/corefx,mmitche/corefx,yizhang82/corefx,mokchhya/corefx,huanjie/corefx,jhendrixMSFT/corefx,DnlHarvey/corefx,alexperovich/corefx,ericstj/corefx,s0ne0me/corefx,cydhaselton/corefx,krytarowski/corefx,Priya91/corefx-1,cartermp/corefx,ViktorHofer/corefx,dtrebbien/corefx,rubo/corefx,brett25/corefx,shahid-pk/corefx,janhenke/corefx,axelheer/corefx,alphonsekurian/corefx,n1ghtmare/corefx,dotnet-bot/corefx,cydhaselton/corefx,zmaruo/corefx,bitcrazed/corefx,YoupHulsebos/corefx
src/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HMACCommon.cs
src/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/HMACCommon.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Security.Cryptography; using Internal.Cryptography; namespace Internal.Cryptography { // // This class provides the common functionality for HMACSHA1, HMACSHA256, HMACMD5, etc. // Ideally, this would be encapsulated in a common base class but the preexisting contract // locks these public classes into deriving directly from HMAC so we have to use encapsulation // and delegation to HMACCommon instead. // // This wrapper adds the ability to change the Key on the fly for compat with the desktop. // internal sealed class HMACCommon { public HMACCommon(String hashAlgorithmId, byte[] key) { _hashAlgorithmId = hashAlgorithmId; ChangeKey(key); } public int HashSizeInBits { get { return _hMacProvider.HashSizeInBytes * 8; } } public void ChangeKey(byte[] key) { HashProvider oldHashProvider = _hMacProvider; _hMacProvider = null; if (oldHashProvider != null) oldHashProvider.Dispose(true); _hMacProvider = HashProviderDispenser.CreateMacProvider(_hashAlgorithmId, key); } // Adds new data to be hashed. This can be called repeatedly in order to hash data from incontiguous sources. public void AppendHashData(byte[] data, int offset, int count) { _hMacProvider.AppendHashData(data, offset, count); } // Compute the hash based on the appended data and resets the HashProvider for more hashing. public byte[] FinalizeHashAndReset() { return _hMacProvider.FinalizeHashAndReset(); } public void Dispose(bool disposing) { if (disposing) { if (_hMacProvider != null) _hMacProvider.Dispose(true); _hMacProvider = null; } } private readonly String _hashAlgorithmId; private HashProvider _hMacProvider; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Security.Cryptography; using Internal.Cryptography; namespace Internal.Cryptography { // // This class provides the common functionality for HMACSHA1, HMACSHA256, HMACMD5, etc. // Ideally, this would be encapsulated in a common base class but the preexisting contract // locks these public classes into deriving directly from HMAC so we have to use encapsulation // and delegation to HMACCommon instead. // // This wrapper adds the ability to change the Key on the fly for compat with the desktop. // internal sealed class HMACCommon { public HMACCommon(String hashAlgorithmId, byte[] key) { _hashAlgorithmId = hashAlgorithmId; ChangeKey(key); } public int HashSizeInBits { get { return _hashProvider.HashSizeInBytes * 8; } } public void ChangeKey(byte[] key) { HashProvider oldHashProvider = _hashProvider; _hashProvider = null; if (oldHashProvider != null) oldHashProvider.Dispose(true); _hashProvider = HashProviderDispenser.CreateMacProvider(_hashAlgorithmId, key); } // Adds new data to be hashed. This can be called repeatedly in order to hash data from incontiguous sources. public void AppendHashData(byte[] data, int offset, int count) { _hashProvider.AppendHashData(data, offset, count); } // Compute the hash based on the appended data and resets the HashProvider for more hashing. public byte[] FinalizeHashAndReset() { return _hashProvider.FinalizeHashAndReset(); } public void Dispose(bool disposing) { if (disposing) { if (_hashProvider != null) _hashProvider.Dispose(true); _hashProvider = null; } } private readonly String _hashAlgorithmId; private HashProvider _hashProvider; } }
mit
C#
2ef9d559841b1a794ba825eae6d3f1eef0b810b2
Correct implementation of configuration
headdetect/ComputerRemote-Server
CLI/Utils/Paramaters.cs
CLI/Utils/Paramaters.cs
using RemoteLib.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ComputerRemote.CLI.Utils { public class Paramaters { private static Configuration config = new Configuration("options.json"); static Paramaters() { if (!config.KeyExists("Debug")) config["Debug"] = new ConfigBlob("Debug", true); if (!config.KeyExists("Multicast")) config["Multicast"] = new ConfigBlob("Multicast", true); config.Save(); } /// <summary> /// Gets or sets a value indicating whether debug OUTPUT is enabled /// </summary> /// <value> /// <c>true</c> if debug OUTPUT is enabled; otherwise, <c>false</c>. /// </value> public static bool DebugEnabled { get { return (bool)config["Debug"]; } set { config["Debug"] = value; config.Save(); } } /// <summary> /// Gets or sets a value indicating whether server multicasting is enabled. /// </summary> /// <value> /// <c>true</c> if server multicasting is enabled; otherwise, <c>false</c>. /// </value> public static bool Multicating { get { return (bool)config["Multicast"]; } set { config["Multicast"] = value; config.Save(); } } } }
using RemoteLib.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ComputerRemote.CLI.Utils { public class Paramaters { static Paramaters() { Configuration config = new Configuration("options.json"); if (!config.KeyExists("Debug")) config["Debug"] = new ConfigBlob("Debug", true); if (!config.KeyExists("Multicast")) config["Multicast"] = new ConfigBlob("Multicast", true); DebugEnabled = (bool)config["Debug"]; Multicating = (bool)config["Multicast"]; config.Save(); } /// <summary> /// Gets or sets a value indicating whether debug OUTPUT is enabled /// </summary> /// <value> /// <c>true</c> if debug OUTPUT is enabled; otherwise, <c>false</c>. /// </value> public static bool DebugEnabled { get; set; } /// <summary> /// Gets or sets a value indicating whether server multicasting is enabled. /// </summary> /// <value> /// <c>true</c> if server multicasting is enabled; otherwise, <c>false</c>. /// </value> public static bool Multicating { get; set; } } }
mit
C#