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 |
---|---|---|---|---|---|---|---|---|
14f43e3749a0322dbccd817764192a95f0b989af | Bump version to 1.0.1.0 | PatrickDinh/Toolbelt.Upserter | Toolbelt.Upserter/Properties/AssemblyInfo.cs | Toolbelt.Upserter/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Toolbelt.Upserter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Toolbelt.Upserter")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b8dd6a55-5c9c-44d5-9067-c8662960f19b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Toolbelt.Upserter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Toolbelt.Upserter")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b8dd6a55-5c9c-44d5-9067-c8662960f19b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
ec9349b3418911ed4ac6c1d6ef73fdffc21354b8 | Update CharlinAgramonte.cs (#316) | planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/CharlinAgramonte.cs | src/Firehose.Web/Authors/CharlinAgramonte.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using Firehose.Web.Infrastructure;
namespace Firehose.Web
{
public class CharlinAgramonte : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Charlin";
public string LastName => "Agramonte";
public string ShortBioOrTagLine => "Software Engineer";
public string StateOrRegion => "Dominican Republic";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "Chard003";
public string GravatarHash => "7db2bb2eed17e8df7e78b0d5461d90b0";
public string GitHubHandle => "char0394";
public GeoPosition Position => new GeoPosition(18.4735438,-69.9456919);
public Uri WebSite => new Uri("https://xamgirl.com/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://xamgirl.com/rss"); } }
public bool Filter(SyndicationItem item) =>
item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin"));
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using Firehose.Web.Infrastructure;
namespace Firehose.Web
{
public class CharlinAgramonte : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Charlin";
public string LastName => "Agramonte";
public string ShortBioOrTagLine => "Software Engineer";
public string StateOrRegion => "Dominican Republic";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "Chard003";
public string GravatarHash => "7db2bb2eed17e8df7e78b0d5461d90b0";
public string GitHubHandle => "char0394";
public GeoPosition Position => new GeoPosition(18.4735438,-69.9456919);
public Uri WebSite => new Uri("https://xamgirl.com/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://xamgirl.com/rss"); } }
public bool Filter(SyndicationItem item) =>
item.Title.Text.ToLowerInvariant().Contains("xamarin") ||
item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin"));
}
}
| mit | C# |
9905d23120bda188c5b2962984845d75f908efd0 | Undo changes with ScriptRuntimeException | lunet-io/scriban,textamina/scriban | src/Scriban/Syntax/ScriptRuntimeException.cs | src/Scriban/Syntax/ScriptRuntimeException.cs | // Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using Scriban.Helpers;
using Scriban.Parsing;
namespace Scriban.Syntax
{
public class ScriptRuntimeException : Exception
{
public ScriptRuntimeException(SourceSpan span, string message) : base(message)
{
Span = span;
}
public ScriptRuntimeException(SourceSpan span, string message, Exception innerException) : base(message, innerException)
{
Span = span;
}
public SourceSpan Span { get; }
public override string ToString()
{
return new LogMessage(ParserMessageType.Error, Span, Message).ToString();
}
}
public class ScriptParserRuntimeException : ScriptRuntimeException
{
public ScriptParserRuntimeException(SourceSpan span, string message, List<LogMessage> parserMessages) : this(span, message, parserMessages, null)
{
}
public ScriptParserRuntimeException(SourceSpan span, string message, List<LogMessage> parserMessages, Exception innerException) : base(span, message, innerException)
{
if (parserMessages == null) throw new ArgumentNullException(nameof(parserMessages));
ParserMessages = parserMessages;
}
public List<LogMessage> ParserMessages { get; }
public override string ToString()
{
var messagesAsText = StringHelper.Join("\n", ParserMessages);
return $"{base.ToString()} Parser messages:\n {messagesAsText}";
}
}
} | // Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using Scriban.Helpers;
using Scriban.Parsing;
namespace Scriban.Syntax
{
public class ScriptRuntimeException : Exception
{
public ScriptRuntimeException(SourceSpan span, string message) : this(span, message, null)
{
}
public ScriptRuntimeException(SourceSpan span, string message, Exception innerException) : base(new LogMessage(ParserMessageType.Error, span, message).ToString(), innerException)
{
Span = span;
}
public SourceSpan Span { get; }
public override string ToString()
{
return new LogMessage(ParserMessageType.Error, Span, Message).ToString();
}
}
public class ScriptParserRuntimeException : ScriptRuntimeException
{
public ScriptParserRuntimeException(SourceSpan span, string message, List<LogMessage> parserMessages) : this(span, message, parserMessages, null)
{
}
public ScriptParserRuntimeException(SourceSpan span, string message, List<LogMessage> parserMessages, Exception innerException) : base(span, message, innerException)
{
if (parserMessages == null) throw new ArgumentNullException(nameof(parserMessages));
ParserMessages = parserMessages;
}
public List<LogMessage> ParserMessages { get; }
public override string ToString()
{
var messagesAsText = StringHelper.Join("\n", ParserMessages);
return $"{base.ToString()} Parser messages:\n {messagesAsText}";
}
}
} | bsd-2-clause | C# |
8a71ae7e5cae8947dbc609d144cc783440ffba00 | Return compilation object from CSharpCompiler.Compile method. | JeffreyZhao/SeeJit | src/SeeJit.Core/Compilation/CSharpCompiler.cs | src/SeeJit.Core/Compilation/CSharpCompiler.cs | namespace SeeJit.Compilation
{
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
public class CSharpCompiler
{
public static CSharpCompilation Compile(string assemblyName, string code, TextWriter errorWriter)
{
var syntaxTree = CSharpSyntaxTree.ParseText(code);
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
};
var compilation = CSharpCompilation.Create(
assemblyName,
new[] { syntaxTree },
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
if (result.Success)
{
Assembly.Load(ms.ToArray());
return compilation;
}
var failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (var diagnostic in failures)
{
errorWriter.WriteLine($"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.GetMessage()}");
}
return null;
}
}
}
} | namespace SeeJit.Compilation
{
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
public class CSharpCompiler
{
public static SemanticModel Compile(string assemblyName, string code, TextWriter errorWriter)
{
var syntaxTree = CSharpSyntaxTree.ParseText(code);
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
};
var compilation = CSharpCompilation.Create(
assemblyName,
new[] { syntaxTree },
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
if (result.Success)
{
Assembly.Load(ms.ToArray());
return compilation.GetSemanticModel(syntaxTree);
}
var failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (var diagnostic in failures)
{
errorWriter.WriteLine($"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.GetMessage()}");
}
return null;
}
}
}
} | mit | C# |
c181c0181176b3894f1ffba11ebe0b468b79f2f2 | change fileSize to long (from int) | kfrancis/wistia.net | src/Wistia.Core/Services/Data/Models/Asset.cs | src/Wistia.Core/Services/Data/Models/Asset.cs | #region License, Terms and Conditions
//
// Asset.cs
//
// Author: Kori Francis <twitter.com/djbyter>
// Copyright (C) 2014 Kori Francis. All rights reserved.
//
// THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
//
// 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.
//
#endregion
using System;
using System.Linq;
namespace Wistia.Core.Services.Data.Models
{
/// <summary>
/// Asset
/// </summary>
public class Asset
{
/// <summary>
/// The asset url
/// </summary>
public string url { get; set; }
/// <summary>
/// The pixel width of the asset
/// </summary>
public int width { get; set; }
/// <summary>
/// The pixel height of the asset
/// </summary>
public int height { get; set; }
/// <summary>
/// The file size (in bytes) of the asset
/// </summary>
public long fileSize { get; set; }
/// <summary>
/// The type of content
/// </summary>
public string contentType { get; set; }
/// <summary>
/// The asset type
/// </summary>
public string type { get; set; }
}
}
| #region License, Terms and Conditions
//
// Asset.cs
//
// Author: Kori Francis <twitter.com/djbyter>
// Copyright (C) 2014 Kori Francis. All rights reserved.
//
// THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
//
// 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.
//
#endregion
using System;
using System.Linq;
namespace Wistia.Core.Services.Data.Models
{
/// <summary>
/// Asset
/// </summary>
public class Asset
{
/// <summary>
/// The asset url
/// </summary>
public string url { get; set; }
/// <summary>
/// The pixel width of the asset
/// </summary>
public int width { get; set; }
/// <summary>
/// The pixel height of the asset
/// </summary>
public int height { get; set; }
/// <summary>
/// The file size (in bytes) of the asset
/// </summary>
public int fileSize { get; set; }
/// <summary>
/// The type of content
/// </summary>
public string contentType { get; set; }
/// <summary>
/// The asset type
/// </summary>
public string type { get; set; }
}
}
| mit | C# |
7ab028576ed581073f338eb1abaa11c58620a2cb | Change `RoundedButton` to source from overlay colour provider | NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu | osu.Game/Graphics/UserInterfaceV2/RoundedButton.cs | osu.Game/Graphics/UserInterfaceV2/RoundedButton.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
namespace osu.Game.Graphics.UserInterfaceV2
{
public class RoundedButton : OsuButton, IFilterable
{
public override float Height
{
get => base.Height;
set
{
base.Height = value;
if (IsLoaded)
updateCornerRadius();
}
}
[BackgroundDependencyLoader(true)]
private void load([CanBeNull] OverlayColourProvider overlayColourProvider, OsuColour colours)
{
BackgroundColour = overlayColourProvider?.Highlight1 ?? colours.Blue3;
}
protected override void LoadComplete()
{
base.LoadComplete();
updateCornerRadius();
}
private void updateCornerRadius() => Content.CornerRadius = DrawHeight / 2;
public virtual IEnumerable<string> FilterTerms => new[] { Text.ToString() };
public bool MatchingFilter
{
set => this.FadeTo(value ? 1 : 0);
}
public bool FilteringActive { get; set; }
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Graphics.UserInterfaceV2
{
public class RoundedButton : OsuButton, IFilterable
{
public override float Height
{
get => base.Height;
set
{
base.Height = value;
if (IsLoaded)
updateCornerRadius();
}
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.Blue3;
}
protected override void LoadComplete()
{
base.LoadComplete();
updateCornerRadius();
}
private void updateCornerRadius() => Content.CornerRadius = DrawHeight / 2;
public virtual IEnumerable<string> FilterTerms => new[] { Text.ToString() };
public bool MatchingFilter
{
set => this.FadeTo(value ? 1 : 0);
}
public bool FilteringActive { get; set; }
}
}
| mit | C# |
451dd5c8f0f28dfec98c01ed3284b422535abbda | fix LockedFramebuffer.Size assigment from constructor | AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,Perspex/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia | src/Avalonia.Visuals/Platform/LockedFramebuffer.cs | src/Avalonia.Visuals/Platform/LockedFramebuffer.cs | using System;
namespace Avalonia.Platform
{
public class LockedFramebuffer : ILockedFramebuffer
{
private readonly Action _onDispose;
public LockedFramebuffer(IntPtr address, PixelSize size, int rowBytes, Vector dpi, PixelFormat format,
Action onDispose)
{
_onDispose = onDispose;
Address = address;
Size = size;
RowBytes = rowBytes;
Dpi = dpi;
Format = format;
}
public IntPtr Address { get; }
public PixelSize Size { get; }
public int RowBytes { get; }
public Vector Dpi { get; }
public PixelFormat Format { get; }
public void Dispose()
{
_onDispose?.Invoke();
}
}
}
| using System;
namespace Avalonia.Platform
{
public class LockedFramebuffer : ILockedFramebuffer
{
private readonly Action _onDispose;
public LockedFramebuffer(IntPtr address, PixelSize size, int rowBytes, Vector dpi, PixelFormat format,
Action onDispose)
{
_onDispose = onDispose;
Address = address;
Size = Size;
RowBytes = rowBytes;
Dpi = dpi;
Format = format;
}
public IntPtr Address { get; }
public PixelSize Size { get; }
public int RowBytes { get; }
public Vector Dpi { get; }
public PixelFormat Format { get; }
public void Dispose()
{
_onDispose?.Invoke();
}
}
}
| mit | C# |
117c1d67144bb0df11dd95e9c0b4d37ef5a6081a | Remove unused exc message | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Extensions/ExceptionExtensions.cs | WalletWasabi/Extensions/ExceptionExtensions.cs | using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using WalletWasabi.Helpers;
using WalletWasabi.Hwi.Exceptions;
using WalletWasabi.Models;
namespace System
{
public static class ExceptionExtensions
{
public static Dictionary<string, string> Translations { get; } = new Dictionary<string, string>
{
["too-long-mempool-chain"] = "At least one coin you are trying to spend is part of long or heavy chain of unconfirmed transactions. You must wait for some previous transactions to confirm.",
["bad-txns-inputs-missingorspent"] = "At least one coin you are trying to spend is already spent.",
["missing-inputs"] = "At least one coin you are trying to spend is already spent.",
["txn-mempool-conflict"] = "At least one coin you are trying to spend is already spent.",
["bad-txns-inputs-duplicate"] = "The transaction contains duplicated inputs.",
["bad-txns-nonfinal"] = "The transaction is not final and cannot be broadcasted.",
["bad-txns-oversize"] = "The transaction is too big.",
["invalid password"] = "Wrong password.",
["Invalid wallet name"] = "Invalid wallet name.",
["Wallet name is already taken"] = "Wallet name is already taken."
};
public static string ToTypeMessageString(this Exception ex)
{
var trimmed = Guard.Correct(ex.Message);
if (trimmed.Length == 0)
{
if (ex is HwiException hwiEx)
{
return $"{hwiEx.GetType().Name}: {hwiEx.ErrorCode}";
}
return ex.GetType().Name;
}
else
{
return $"{ex.GetType().Name}: {ex.Message}";
}
}
public static string ToUserFriendlyString(this Exception ex)
{
var trimmed = Guard.Correct(ex.Message);
if (trimmed.Length == 0)
{
return ex.ToTypeMessageString();
}
else
{
if (ex is HwiException hwiEx && hwiEx.ErrorCode == HwiErrorCode.DeviceConnError)
{
return "Could not find the hardware wallet.\nMake sure it is connected.";
}
foreach (KeyValuePair<string, string> pair in Translations)
{
if (trimmed.Contains(pair.Key, StringComparison.InvariantCultureIgnoreCase))
{
return pair.Value;
}
}
return ex.ToTypeMessageString();
}
}
public static SerializableException ToSerializableException(this Exception ex)
{
return new SerializableException(ex);
}
}
}
| using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using WalletWasabi.Helpers;
using WalletWasabi.Hwi.Exceptions;
using WalletWasabi.Models;
namespace System
{
public static class ExceptionExtensions
{
public static Dictionary<string, string> Translations { get; } = new Dictionary<string, string>
{
["too-long-mempool-chain"] = "At least one coin you are trying to spend is part of long or heavy chain of unconfirmed transactions. You must wait for some previous transactions to confirm.",
["bad-txns-inputs-missingorspent"] = "At least one coin you are trying to spend is already spent.",
["missing-inputs"] = "At least one coin you are trying to spend is already spent.",
["txn-mempool-conflict"] = "At least one coin you are trying to spend is already spent.",
["bad-txns-inputs-duplicate"] = "The transaction contains duplicated inputs.",
["bad-txns-nonfinal"] = "The transaction is not final and cannot be broadcasted.",
["bad-txns-oversize"] = "The transaction is too big.",
["invalid password"] = "Wrong password.",
["Invalid wallet name"] = "Invalid wallet name.",
["Wallet name is already taken"] = "Wallet name is already taken.",
["The invoice this PSBT is paying has already been partially or completely paid"] = "The invoice has already been paid"
};
public static string ToTypeMessageString(this Exception ex)
{
var trimmed = Guard.Correct(ex.Message);
if (trimmed.Length == 0)
{
if (ex is HwiException hwiEx)
{
return $"{hwiEx.GetType().Name}: {hwiEx.ErrorCode}";
}
return ex.GetType().Name;
}
else
{
return $"{ex.GetType().Name}: {ex.Message}";
}
}
public static string ToUserFriendlyString(this Exception ex)
{
var trimmed = Guard.Correct(ex.Message);
if (trimmed.Length == 0)
{
return ex.ToTypeMessageString();
}
else
{
if (ex is HwiException hwiEx && hwiEx.ErrorCode == HwiErrorCode.DeviceConnError)
{
return "Could not find the hardware wallet.\nMake sure it is connected.";
}
foreach (KeyValuePair<string, string> pair in Translations)
{
if (trimmed.Contains(pair.Key, StringComparison.InvariantCultureIgnoreCase))
{
return pair.Value;
}
}
return ex.ToTypeMessageString();
}
}
public static SerializableException ToSerializableException(this Exception ex)
{
return new SerializableException(ex);
}
}
}
| mit | C# |
55fedfb38fda13694cb02dd08593261a9cdcac23 | Add MaxDeltaTime to Time class (#663) | prime31/Nez,prime31/Nez,ericmbernier/Nez,prime31/Nez | Nez.Portable/Utils/Time.cs | Nez.Portable/Utils/Time.cs | using System.Runtime.CompilerServices;
namespace Nez
{
/// <summary>
/// provides frame timing information
/// </summary>
public static class Time
{
/// <summary>
/// total time the game has been running
/// </summary>
public static float TotalTime;
/// <summary>
/// delta time from the previous frame to the current, scaled by timeScale
/// </summary>
public static float DeltaTime;
/// <summary>
/// unscaled version of deltaTime. Not affected by timeScale
/// </summary>
public static float UnscaledDeltaTime;
/// <summary>
/// secondary deltaTime for use when you need to scale two different deltas simultaneously
/// </summary>
public static float AltDeltaTime;
/// <summary>
/// total time since the Scene was loaded
/// </summary>
public static float TimeSinceSceneLoad;
/// <summary>
/// time scale of deltaTime
/// </summary>
public static float TimeScale = 1f;
/// <summary>
/// time scale of altDeltaTime
/// </summary>
public static float AltTimeScale = 1f;
/// <summary>
/// total number of frames that have passed
/// </summary>
public static uint FrameCount;
/// <summary>
/// Maximum value that DeltaTime can be. This can be useful to prevent physics from breaking when dragging
/// the game window or if your game hitches.
/// </summary>
public static float MaxDeltaTime = float.MaxValue;
internal static void Update(float dt)
{
if(dt > MaxDeltaTime)
dt = MaxDeltaTime;
TotalTime += dt;
DeltaTime = dt * TimeScale;
AltDeltaTime = dt * AltTimeScale;
UnscaledDeltaTime = dt;
TimeSinceSceneLoad += dt;
FrameCount++;
}
internal static void SceneChanged()
{
TimeSinceSceneLoad = 0f;
}
/// <summary>
/// Allows to check in intervals. Should only be used with interval values above deltaTime,
/// otherwise it will always return true.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool CheckEvery(float interval)
{
// we subtract deltaTime since timeSinceSceneLoad already includes this update ticks deltaTime
return (int) (TimeSinceSceneLoad / interval) > (int) ((TimeSinceSceneLoad - DeltaTime) / interval);
}
}
}
| using System.Runtime.CompilerServices;
namespace Nez
{
/// <summary>
/// provides frame timing information
/// </summary>
public static class Time
{
/// <summary>
/// total time the game has been running
/// </summary>
public static float TotalTime;
/// <summary>
/// delta time from the previous frame to the current, scaled by timeScale
/// </summary>
public static float DeltaTime;
/// <summary>
/// unscaled version of deltaTime. Not affected by timeScale
/// </summary>
public static float UnscaledDeltaTime;
/// <summary>
/// secondary deltaTime for use when you need to scale two different deltas simultaneously
/// </summary>
public static float AltDeltaTime;
/// <summary>
/// total time since the Scene was loaded
/// </summary>
public static float TimeSinceSceneLoad;
/// <summary>
/// time scale of deltaTime
/// </summary>
public static float TimeScale = 1f;
/// <summary>
/// time scale of altDeltaTime
/// </summary>
public static float AltTimeScale = 1f;
/// <summary>
/// total number of frames that have passed
/// </summary>
public static uint FrameCount;
internal static void Update(float dt)
{
TotalTime += dt;
DeltaTime = dt * TimeScale;
AltDeltaTime = dt * AltTimeScale;
UnscaledDeltaTime = dt;
TimeSinceSceneLoad += dt;
FrameCount++;
}
internal static void SceneChanged()
{
TimeSinceSceneLoad = 0f;
}
/// <summary>
/// Allows to check in intervals. Should only be used with interval values above deltaTime,
/// otherwise it will always return true.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool CheckEvery(float interval)
{
// we subtract deltaTime since timeSinceSceneLoad already includes this update ticks deltaTime
return (int) (TimeSinceSceneLoad / interval) > (int) ((TimeSinceSceneLoad - DeltaTime) / interval);
}
}
} | mit | C# |
22c11e1c9ea11777a452d2f404f496f049284d31 | Set RenderTexture.dimension property at first for OpenGL rendering mode | nobnak/DomeMaster | DomeMaster.cs | DomeMaster.cs | using UnityEngine;
using System.Collections;
namespace DomeMasterSystem {
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class DomeMaster : MonoBehaviour {
public enum TextureTypeEnum { RenderTexture = 0, CubeMap }
[System.Flags]
public enum FaceMaskFlags {
Right = 1 << 0,
Left = 1 << 1,
Top = 1 << 2,
Bottom = 1 << 3,
Front = 1 << 4,
Back = 1 << 5 }
public const string PROP_DOME_MASTER_CUBE = "_DomeMasterCube";
public const string PROP_DIRECTION = "_Dir";
public TextureTypeEnum textureType;
public TextureEvent OnUpdateCubemap;
public bool generateMips = false;
public int lod = 10;
public FilterMode filterMode = FilterMode.Trilinear;
public int anisoLevel = 16;
[InspectorFlags]
public FaceMaskFlags faceMask;
Camera _attachedCam;
RenderTexture _cubert;
void OnEnable() {
_attachedCam = GetComponent<Camera> ();
}
void Update() {
var res = (1 << Mathf.Clamp(lod, 1, 13));
CheckInitRenderTexture(res, ref _cubert);
_attachedCam.RenderToCubemap (_cubert, (int)faceMask);
_attachedCam.enabled = false;
Shader.SetGlobalTexture(PROP_DOME_MASTER_CUBE, _cubert);
OnUpdateCubemap.Invoke (_cubert);
}
void OnDisable() {
Release ();
}
void Release() {
DestroyImmediate (_cubert);
}
void CheckInitRenderTexture (int res, ref RenderTexture rt) {
if (rt == null || rt.width != res || rt.autoGenerateMips != generateMips) {
Release ();
rt = new RenderTexture (res, res, 24);
rt.dimension = UnityEngine.Rendering.TextureDimension.Cube;
rt.filterMode = filterMode;
rt.anisoLevel = anisoLevel;
rt.autoGenerateMips = generateMips;
rt.useMipMap = generateMips;
Debug.LogFormat ("Create Cubemap RenderTexture {0}x{1}", res, res);
}
}
[System.Serializable]
public class TextureEvent : UnityEngine.Events.UnityEvent<Texture> {}
}
}
| using UnityEngine;
using System.Collections;
namespace DomeMasterSystem {
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class DomeMaster : MonoBehaviour {
public enum TextureTypeEnum { RenderTexture = 0, CubeMap }
[System.Flags]
public enum FaceMaskFlags {
Right = 1 << 0,
Left = 1 << 1,
Top = 1 << 2,
Bottom = 1 << 3,
Front = 1 << 4,
Back = 1 << 5 }
public const string PROP_DOME_MASTER_CUBE = "_DomeMasterCube";
public const string PROP_DIRECTION = "_Dir";
public TextureTypeEnum textureType;
public TextureEvent OnUpdateCubemap;
public bool generateMips = false;
public int lod = 10;
public FilterMode filterMode = FilterMode.Trilinear;
public int anisoLevel = 16;
[InspectorFlags]
public FaceMaskFlags faceMask;
Camera _attachedCam;
RenderTexture _cubert;
void OnEnable() {
_attachedCam = GetComponent<Camera> ();
}
void Update() {
var res = (1 << Mathf.Clamp(lod, 1, 13));
CheckInitRenderTexture(res, ref _cubert);
_attachedCam.RenderToCubemap (_cubert, (int)faceMask);
_attachedCam.enabled = false;
Shader.SetGlobalTexture(PROP_DOME_MASTER_CUBE, _cubert);
OnUpdateCubemap.Invoke (_cubert);
}
void OnDisable() {
Release ();
}
void Release() {
DestroyImmediate (_cubert);
}
void CheckInitRenderTexture (int res, ref RenderTexture rt) {
if (rt == null || rt.width != res || rt.autoGenerateMips != generateMips) {
Release ();
rt = new RenderTexture (res, res, 24);
rt.filterMode = filterMode;
rt.anisoLevel = anisoLevel;
rt.dimension = UnityEngine.Rendering.TextureDimension.Cube;
rt.autoGenerateMips = generateMips;
rt.useMipMap = generateMips;
rt.Create ();
Debug.LogFormat ("Create Cubemap RenderTexture {0}x{1}", res, res);
}
}
[System.Serializable]
public class TextureEvent : UnityEngine.Events.UnityEvent<Texture> {}
}
}
| mit | C# |
9246593a309884a9f12b6f5e295cf9af12f6b793 | Bump version | gonzalocasas/NetMetrixSDK | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NetMetrixSDK")]
[assembly: AssemblyDescription("Net-Metrix SDK for Windows Phone applications")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Gonzalo Casas")]
[assembly: AssemblyProduct("NetMetrix SDK")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d26acda3-5465-4207-8fd0-a1bbedd41bbc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NetMetrixSDK")]
[assembly: AssemblyDescription("Net-Metrix SDK for Windows Phone applications")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Gonzalo Casas")]
[assembly: AssemblyProduct("NetMetrix SDK")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d26acda3-5465-4207-8fd0-a1bbedd41bbc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| mit | C# |
576548773f3372fcfaee69c9e8238ace66da276c | Document and clean up the binding code | rdparker/RabidWarren.Collections | Enumerable.cs | Enumerable.cs | // -----------------------------------------------------------------------
// <copyright file="Enumerable.cs" company="Ron Parker">
// Copyright 2014 Ron Parker
// </copyright>
// <summary>
// Provides an extension method for converting IEnumerables to Multimaps.
// </summary>
// -----------------------------------------------------------------------
namespace RabidWarren.Collections.Generic
{
using System;
using System.Collections.Generic;
/// <summary>
/// Contains extension methods for <see cref="System.Collections.Generic.IEnumerable{TSource}"/>.
/// </summary>
public static class Enumerable
{
/// <summary>
/// Converts the source to an <see cref="RabidWarren.Collections.Generic.Multimap{TSource, TKey, TValue}"/>.
/// </summary>
/// <returns>The <see cref="RabidWarren.Collections.Generic.Multimap{TSource, TKey, TValue}"/>.</returns>
/// <param name="source">The source.</param>
/// <param name="keySelector">The key selector.</param>
/// <param name="valueSelector">The value selector.</param>
/// <typeparam name="TSource">The source type.</typeparam>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The the value type.</typeparam>
public static Multimap<TKey, TValue> ToMultimap<TSource, TKey, TValue>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TValue> valueSelector)
{
var map = new Multimap<TKey, TValue>();
foreach (var entry in source)
{
map.Add(keySelector(entry), valueSelector(entry));
}
return map;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RabidWarren.Collections.Generic
{
public static class Enumerable
{
public static Multimap<TKey, TElement> ToMultimap<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector)
{
var map = new Multimap<TKey, TElement>();
foreach (var entry in source)
{
map.Add(keySelector(entry), elementSelector(entry));
}
return map;
}
}
}
| mit | C# |
04049e1ca5cbe879d25f1ff477f603390a4da4d3 | Fix spelling typos. | dotnet/roslyn,agocke/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,mattscheffer/roslyn,MichalStrehovsky/roslyn,physhi/roslyn,stephentoub/roslyn,panopticoncentral/roslyn,physhi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,physhi/roslyn,orthoxerox/roslyn,cston/roslyn,MichalStrehovsky/roslyn,davkean/roslyn,gafter/roslyn,lorcanmooney/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,DustinCampbell/roslyn,paulvanbrenk/roslyn,wvdd007/roslyn,mattscheffer/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,nguerrera/roslyn,Giftednewt/roslyn,xasx/roslyn,davkean/roslyn,agocke/roslyn,sharwell/roslyn,cston/roslyn,mattscheffer/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,reaction1989/roslyn,MichalStrehovsky/roslyn,agocke/roslyn,heejaechang/roslyn,genlu/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,orthoxerox/roslyn,eriawan/roslyn,gafter/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,VSadov/roslyn,heejaechang/roslyn,gafter/roslyn,AlekseyTs/roslyn,swaroop-sridhar/roslyn,OmarTawfik/roslyn,brettfo/roslyn,abock/roslyn,jamesqo/roslyn,jcouv/roslyn,aelij/roslyn,bartdesmet/roslyn,jcouv/roslyn,AlekseyTs/roslyn,sharwell/roslyn,DustinCampbell/roslyn,tmeschter/roslyn,OmarTawfik/roslyn,Hosch250/roslyn,tmat/roslyn,bkoelman/roslyn,paulvanbrenk/roslyn,KevinRansom/roslyn,jamesqo/roslyn,diryboy/roslyn,VSadov/roslyn,nguerrera/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,lorcanmooney/roslyn,AmadeusW/roslyn,swaroop-sridhar/roslyn,tmat/roslyn,diryboy/roslyn,abock/roslyn,genlu/roslyn,AmadeusW/roslyn,stephentoub/roslyn,bartdesmet/roslyn,reaction1989/roslyn,bkoelman/roslyn,VSadov/roslyn,Hosch250/roslyn,ErikSchierboom/roslyn,dpoeschl/roslyn,KirillOsenkov/roslyn,jamesqo/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,nguerrera/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,OmarTawfik/roslyn,DustinCampbell/roslyn,paulvanbrenk/roslyn,weltkante/roslyn,tmeschter/roslyn,Giftednewt/roslyn,dotnet/roslyn,brettfo/roslyn,KevinRansom/roslyn,jmarolf/roslyn,davkean/roslyn,khyperia/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,genlu/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mmitche/roslyn,khyperia/roslyn,jcouv/roslyn,xasx/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,tmat/roslyn,mmitche/roslyn,tannergooding/roslyn,Hosch250/roslyn,tannergooding/roslyn,aelij/roslyn,swaroop-sridhar/roslyn,aelij/roslyn,bartdesmet/roslyn,reaction1989/roslyn,bkoelman/roslyn,dpoeschl/roslyn,Giftednewt/roslyn,weltkante/roslyn,abock/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,mavasani/roslyn,sharwell/roslyn,xasx/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,mmitche/roslyn,stephentoub/roslyn,cston/roslyn,eriawan/roslyn,orthoxerox/roslyn,mgoertz-msft/roslyn,tmeschter/roslyn,mavasani/roslyn,dpoeschl/roslyn,jmarolf/roslyn,lorcanmooney/roslyn,khyperia/roslyn | src/Compilers/Core/Portable/Operations/ICompoundAssignmentOperation.cs | src/Compilers/Core/Portable/Operations/ICompoundAssignmentOperation.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Operations
{
/// <summary>
/// Represents a compound assignment that mutates the target with the result of a binary operation.
/// <para>
/// Current usage:
/// (1) C# compound assignment expression.
/// (2) VB compound assignment expression.
/// </para>
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface ICompoundAssignmentOperation : IAssignmentOperation
{
/// <summary>
/// Kind of binary operation.
/// </summary>
BinaryOperatorKind OperatorKind { get; }
/// <summary>
/// Operator method used by the operation, null if the operation does not use an operator method.
/// </summary>
IMethodSymbol OperatorMethod { get; }
/// <summary>
/// <code>true</code> if this assignment contains a 'lifted' binary operation.
/// </summary>
bool IsLifted { get; }
/// <summary>
/// <code>true</code> if overflow checking is performed for the arithmetic operation.
/// </summary>
bool IsChecked { get; }
/// <summary>
/// Conversion applied to <see cref="IAssignmentOperation.Target"/> before the operation occurs.
/// </summary>
CommonConversion InConversion { get; }
/// <summary>
/// Conversion applied to the result of the binary operation, before it is assigned back to
/// <see cref="IAssignmentOperation.Target"/>.
/// </summary>
CommonConversion OutConversion { get; }
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Operations
{
/// <summary>
/// Represents a compound assignment that mutates the target with the result of a binary operation.
/// <para>
/// Current usage:
/// (1) C# compound assignment expression.
/// (2) VB compound assignment expression.
/// </para>
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface ICompoundAssignmentOperation : IAssignmentOperation
{
/// <summary>
/// Kind of binary operation.
/// </summary>
BinaryOperatorKind OperatorKind { get; }
/// <summary>
/// Operator method used by the operation, null if the operation does not use an operator method.
/// </summary>
IMethodSymbol OperatorMethod { get; }
/// <summary>
/// <code>true</code> if this assignment contains a 'lifted' binary operation.
/// </summary>
bool IsLifted { get; }
/// <summary>
/// <code>true</code> if overflow checking is performed for the arithmetic operation.
/// </summary>
bool IsChecked { get; }
/// <summary>
/// Conversion applied to <see cref="IAssignmentOperation.Target"/> before the operation occurs.
/// </summary>
CommonConversion InConversion { get; }
/// <summary>
/// Conversion appliec to the result of the compound operation, before it is assigned back to
/// <see cref="IAssignmentOperation.Target"/>.
/// </summary>
CommonConversion OutConversion { get; }
}
}
| mit | C# |
1bc132f88af2662aaaffaceaef8e37209ae9b45a | Update from last commit | mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype | src/Glimpse.Agent.Web/Framework/DefaultIgnoredRequestPolicyProvider.cs | src/Glimpse.Agent.Web/Framework/DefaultIgnoredRequestPolicyProvider.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Agent.Web
{
public class DefaultIgnoredRequestPolicyProvider : IIgnoredRequestPolicyProvider
{
private readonly ITypeService _typeService;
public DefaultIgnoredRequestPolicyProvider(ITypeService typeService)
{
_typeService = typeService;
}
public IEnumerable<IIgnoredRequestPolicy> Policies
{
get { return _typeService.Resolve<IIgnoredRequestPolicy>().ToArray(); }
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Agent.Web
{
public class DefaultIgnoredRequestProvider : IIgnoredRequestProvider
{
private readonly ITypeService _typeService;
public DefaultIgnoredRequestProvider(ITypeService typeService)
{
_typeService = typeService;
}
public IEnumerable<IIgnoredRequestPolicy> Policies
{
get { return _typeService.Resolve<IIgnoredRequestPolicy>().ToArray(); }
}
}
} | mit | C# |
4bb1eb49bca60382763b99ce8dbe716be8184a1b | clean up Obsolete method | wangkanai/Detection | src/Responsive.Core/src/Builders/ResponsiveOptionsBuilderExtensions.cs | src/Responsive.Core/src/Builders/ResponsiveOptionsBuilderExtensions.cs | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using Wangkanai.Detection;
using Wangkanai.Responsive;
namespace Microsoft.AspNetCore.Builder
{
public static class ResponsiveOptionsBuilderExtensions
{
public static IResponsiveOptionsBuilder DefaultView(
this IResponsiveOptionsBuilder optionsBuilder,
DeviceType target,
DeviceType prefer)
{
throw new NotImplementedException();
}
}
}
| // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using Wangkanai.Detection;
using Wangkanai.Responsive;
namespace Microsoft.AspNetCore.Builder
{
public static class ResponsiveOptionsBuilderExtensions
{
public static IResponsiveOptionsBuilder DefaultView(
this IResponsiveOptionsBuilder optionsBuilder,
DeviceType target,
DeviceType prefer)
{
throw new NotImplementedException();
}
[Obsolete("This is an experimental API, its might change when finalize.")]
public static IResponsiveOptionsBuilder DefaultTablet(
this IResponsiveOptionsBuilder optionsBuilder,
DeviceType preferred)
{
throw new NotImplementedException();
}
[Obsolete("This is an experimental API, its might change when finalize.")]
public static IResponsiveOptionsBuilder DefaultMobile(
this IResponsiveOptionsBuilder optionsBuilder,
DeviceType preferred)
{
throw new NotImplementedException();
}
[Obsolete("This is an experimental API, its might change when finalize.")]
public static IResponsiveOptionsBuilder DefaultDesktop(
this IResponsiveOptionsBuilder optionsBuilder,
DeviceType preferred)
{
throw new NotImplementedException();
}
}
}
| apache-2.0 | C# |
86b6131307c33bae13b017935ebb30dfda6a7628 | Update RunPoolingSystem.cs | cdrandin/Simple-Object-Pooling | Source/RunPoolingSystem.cs | Source/RunPoolingSystem.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RunPoolingSystem : MonoBehaviour
{
public bool test;
public List<GameObject> objects_to_pool;
public List<GameObject> objects_in_the_pool;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
{
GameObject obj = PoolingSystem.instance.PS_Instantiate(objects_to_pool[Random.Range(0, objects_to_pool.Count)],
new Vector3(Random.Range(-5.0f, 5.0f), 3.0f, Random.Range(-5.0f, 5.0f)),
Quaternion.identity);
if(obj == null) return;
objects_in_the_pool.Add(obj);
}
else if(Input.GetKeyDown(KeyCode.Backspace))
{
if(objects_in_the_pool.Count > 0)
{
int i = Random.Range(0, objects_in_the_pool.Count);
PoolingSystem.instance.PS_Destroy(objects_in_the_pool[i]);
objects_in_the_pool.RemoveAt(i);
}
}
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RunPoolingSystem : MonoBehaviour
{
public bool test;
public List<GameObject> objects_to_pool;
public List<GameObject> objects_in_the_pool;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
{
GameObject obj = null;
obj = PoolingSystem.instance.PS_Instantiate(objects_to_pool[Random.Range(0, objects_to_pool.Count)],
new Vector3(Random.Range(-5.0f, 5.0f), 3.0f, Random.Range(-5.0f, 5.0f)),
Quaternion.identity);
if(obj == null) return;
objects_in_the_pool.Add(obj);
}
else if(Input.GetKeyDown(KeyCode.Backspace))
{
if(objects_in_the_pool.Count > 0)
{
int i = Random.Range(0, objects_in_the_pool.Count);
if(!test)
{
PoolingSystem.instance.PS_Destroy(objects_in_the_pool[i]);
}
else
{
PoolingSystem.instance.PS_Destroy(objects_in_the_pool[i]);
}
objects_in_the_pool.RemoveAt(i);
}
}
}
}
| mit | C# |
9c95ec18de971d56717e270882f6bbf85c81df32 | Update WeaponComponent with using directive for Matcha.Game.Colors. | jguarShark/Unity2D-Components,cmilr/Unity2D-Components | Weapons/WeaponComponent.cs | Weapons/WeaponComponent.cs | using UnityEngine;
using System.Collections;
using Matcha.Game.Colors;
public class WeaponComponent : CacheBehaviour {
public string idleAnimation;
public string runAnimation;
public string jumpAnimation;
void Start ()
{
// spriteRenderer.color = new Color(0f, 0f, 0f, 1f); // Set to opaque black
SetAnimations();
}
void SetAnimations()
{
idleAnimation = name + "_Idle";
runAnimation = name + "_Run";
jumpAnimation = name + "_Jump";
}
public void PlayIdleAnimation()
{
animator.speed = IDLE_SPEED;
animator.Play(Animator.StringToHash(idleAnimation));
}
public void PlayRunAnimation()
{
animator.speed = RUN_SPEED;
animator.Play(Animator.StringToHash(runAnimation));
}
public void PlayJumpAnimation()
{
animator.speed = JUMP_SPEED;
animator.Play(Animator.StringToHash(jumpAnimation));
}
} | using UnityEngine;
using System.Collections;
public class WeaponComponent : CacheBehaviour {
public string idleAnimation;
public string runAnimation;
public string jumpAnimation;
void Start ()
{
// spriteRenderer.color = new Color(0f, 0f, 0f, 1f); // Set to opaque black
SetAnimations();
}
void SetAnimations()
{
idleAnimation = name + "_Idle";
runAnimation = name + "_Run";
jumpAnimation = name + "_Jump";
}
public void PlayIdleAnimation()
{
animator.speed = IDLE_SPEED;
animator.Play(Animator.StringToHash(idleAnimation));
}
public void PlayRunAnimation()
{
animator.speed = RUN_SPEED;
animator.Play(Animator.StringToHash(runAnimation));
}
public void PlayJumpAnimation()
{
animator.speed = JUMP_SPEED;
animator.Play(Animator.StringToHash(jumpAnimation));
}
} | mit | C# |
fcafc32ed31d490093d39cd9f4b36245e95cda7a | work done on opening scene | oussamabonnor1/Catcheep | Documents/Unity3D/Catcheep/Assets/Scripts/OpeningSceneScript.cs | Documents/Unity3D/Catcheep/Assets/Scripts/OpeningSceneScript.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class OpeningSceneScript : MonoBehaviour {
// Use this for initialization
void Start ()
{
StartCoroutine(opening());
}
// Update is called once per frame
void Update () {
}
IEnumerator opening()
{
yield return new WaitForSeconds(2.5f);
SceneManager.LoadScene(1);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class OpeningSceneScript : MonoBehaviour {
// Use this for initialization
void Start ()
{
StartCoroutine(opening());
}
// Update is called once per frame
void Update () {
}
IEnumerator opening()
{
yield return new WaitForSeconds(3.5f);
SceneManager.LoadScene(1);
}
}
| mit | C# |
a1ea89cf99f946a402b86b61562c86e61c2f2853 | Remove redundant hWnd check | Excel-DNA/IntelliSense | Source/ExcelDna.IntelliSense/UIMonitor/WindowLocationWatcher.cs | Source/ExcelDna.IntelliSense/UIMonitor/WindowLocationWatcher.cs | using System;
using System.Threading;
namespace ExcelDna.IntelliSense
{
public class WindowLocationWatcher : IDisposable
{
IntPtr _hWnd;
SynchronizationContext _syncContextAuto;
WinEventHook _windowLocationChangeHook;
public event EventHandler LocationChanged;
// NOTE: An earlier attempt was to monitor LOCATIONCHANGE only between EVENT_SYSTEM_MOVESIZESTART and EVENT_SYSTEM_MOVESIZEEND
// This nearly worked, and meant we were watching many fewer events ...
// ...but we missed some of the resizing events for the window, leaving our tooltip stranded.
// So until we can find a workaround for that (perhaps a timer would work fine for this), we watch all the LOCATIONCHANGE events.
public WindowLocationWatcher(IntPtr hWnd, SynchronizationContext syncContextAuto)
{
_hWnd = hWnd;
_syncContextAuto = syncContextAuto;
_windowLocationChangeHook = new WinEventHook(WinEventHook.WinEvent.EVENT_OBJECT_LOCATIONCHANGE, WinEventHook.WinEvent.EVENT_OBJECT_LOCATIONCHANGE, _syncContextAuto, _hWnd);
_windowLocationChangeHook.WinEventReceived += _windowLocationChangeHook_WinEventReceived;
}
void _windowLocationChangeHook_WinEventReceived(object sender, WinEventHook.WinEventArgs winEventArgs)
{
#if DEBUG
Logger.WinEvents.Verbose($"{winEventArgs.EventType} - Window {winEventArgs.WindowHandle:X} ({Win32Helper.GetClassName(winEventArgs.WindowHandle)} - Object/Child {winEventArgs.ObjectId} / {winEventArgs.ChildId} - Thread {winEventArgs.EventThreadId} at {winEventArgs.EventTimeMs}");
#endif
LocationChanged?.Invoke(this, EventArgs.Empty);
}
public void Dispose()
{
if (_windowLocationChangeHook != null)
{
_windowLocationChangeHook.Dispose();
_windowLocationChangeHook = null;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace ExcelDna.IntelliSense
{
public class WindowLocationWatcher : IDisposable
{
IntPtr _hWnd;
SynchronizationContext _syncContextAuto;
WinEventHook _windowLocationChangeHook;
public event EventHandler LocationChanged;
// NOTE: An earlier attempt was to monitor LOCATIONCHANGE only between EVENT_SYSTEM_MOVESIZESTART and EVENT_SYSTEM_MOVESIZEEND
// This nearly worked, and meant we were watching many fewer events ...
// ...but we missed some of the resizing events for the window, leaving our tooltip stranded.
// So until we can find a workaround for that (perhaps a timer would work fine for this), we watch all the LOCATIONCHANGE events.
public WindowLocationWatcher(IntPtr hWnd, SynchronizationContext syncContextAuto)
{
_hWnd = hWnd;
_syncContextAuto = syncContextAuto;
_windowLocationChangeHook = new WinEventHook(WinEventHook.WinEvent.EVENT_OBJECT_LOCATIONCHANGE, WinEventHook.WinEvent.EVENT_OBJECT_LOCATIONCHANGE, _syncContextAuto, _hWnd);
_windowLocationChangeHook.WinEventReceived += _windowLocationChangeHook_WinEventReceived;
}
void _windowLocationChangeHook_WinEventReceived(object sender, WinEventHook.WinEventArgs winEventArgs)
{
#if DEBUG
Logger.WinEvents.Verbose($"{winEventArgs.EventType} - Window {winEventArgs.WindowHandle:X} ({Win32Helper.GetClassName(winEventArgs.WindowHandle)} - Object/Child {winEventArgs.ObjectId} / {winEventArgs.ChildId} - Thread {winEventArgs.EventThreadId} at {winEventArgs.EventTimeMs}");
#endif
if (winEventArgs.WindowHandle == _hWnd)
LocationChanged?.Invoke(this, EventArgs.Empty);
}
public void Dispose()
{
if (_windowLocationChangeHook != null)
{
_windowLocationChangeHook.Dispose();
_windowLocationChangeHook = null;
}
}
}
}
| mit | C# |
5b86faaaa273e1c6270401265e2c957f31589e13 | Remove semicolons from poll page | stevenhillcox/voting-application,tpkelly/voting-application,stevenhillcox/voting-application,tpkelly/voting-application,stevenhillcox/voting-application,Generic-Voting-Application/voting-application,Generic-Voting-Application/voting-application,JDawes-ScottLogic/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,Generic-Voting-Application/voting-application | VotingApplication/VotingApplication.Web/Views/Poll/Index.cshtml | VotingApplication/VotingApplication.Web/Views/Poll/Index.cshtml | <!DOCTYPE html>
<html ng-app="VoteOn-Poll">
<head>
<title>Vote On</title>
<meta name="viewport" content="initial-scale=1">
@Styles.Render("~/Bundles/StyleLib/AngularMaterial")
@Styles.Render("~/Bundles/StyleLib/FontAwesome")
@Styles.Render("~/Bundles/VotingStyle")
</head>
<body>
<div layout="column" flex layout-fill>
<toolbar></toolbar>
<div ng-view></div>
</div>
@Scripts.Render("~/Bundles/ScriptLib/JQuery")
@Scripts.Render("~/Bundles/ScriptLib/JQuerySignalR")
@Scripts.Render("~/Bundles/ScriptLib/Angular")
@Scripts.Render("~/Bundles/ScriptLib/AngularAnimate")
@Scripts.Render("~/Bundles/ScriptLib/AngularAria")
@Scripts.Render("~/Bundles/ScriptLib/AngularMaterial")
@Scripts.Render("~/Bundles/ScriptLib/AngularMessages")
@Scripts.Render("~/Bundles/ScriptLib/AngularRoute")
@Scripts.Render("~/Bundles/ScriptLib/AngularCharts")
@Scripts.Render("~/Bundles/ScriptLib/AngularSignalR")
@Scripts.Render("~/Bundles/ScriptLib/ngStorage")
@Scripts.Render("~/Bundles/ScriptLib/moment")
@Scripts.Render("~/Bundles/Script")
</body>
</html> | <!DOCTYPE html>
<html ng-app="VoteOn-Poll">
<head>
<title>Vote On</title>
<meta name="viewport" content="initial-scale=1">
@Styles.Render("~/Bundles/StyleLib/AngularMaterial")
@Styles.Render("~/Bundles/StyleLib/FontAwesome")
@Styles.Render("~/Bundles/VotingStyle")
</head>
<body>
<div layout="column" flex layout-fill>
<toolbar></toolbar>
<div ng-view></div>
</div>
@Scripts.Render("~/Bundles/ScriptLib/JQuery");
@Scripts.Render("~/Bundles/ScriptLib/JQuerySignalR");
@Scripts.Render("~/Bundles/ScriptLib/Angular")
@Scripts.Render("~/Bundles/ScriptLib/AngularAnimate")
@Scripts.Render("~/Bundles/ScriptLib/AngularAria")
@Scripts.Render("~/Bundles/ScriptLib/AngularMaterial")
@Scripts.Render("~/Bundles/ScriptLib/AngularMessages")
@Scripts.Render("~/Bundles/ScriptLib/AngularRoute")
@Scripts.Render("~/Bundles/ScriptLib/AngularCharts")
@Scripts.Render("~/Bundles/ScriptLib/AngularSignalR")
@Scripts.Render("~/Bundles/ScriptLib/ngStorage")
@Scripts.Render("~/Bundles/ScriptLib/moment")
@Scripts.Render("~/Bundles/Script")
</body>
</html> | apache-2.0 | C# |
08d70ee74a8e63d87273e6dcf34564199b702e36 | Fix tests | visualeyes/cabinet,visualeyes/cabinet,visualeyes/cabinet | test/Cabinet.Tests/Config/FileCabinetConverterFactoryFacts.cs | test/Cabinet.Tests/Config/FileCabinetConverterFactoryFacts.cs | using Cabinet.Config;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Cabinet.Tests.Config {
public class FileCabinetConverterFactoryFacts {
private readonly FileCabinetConfigConverterFactory converterFactory;
public FileCabinetConverterFactoryFacts() {
this.converterFactory = new FileCabinetConfigConverterFactory();
}
[Theory]
[InlineData(null), InlineData(""), InlineData(" ")]
public void NullEmpty_GetConverter_Throws(string providerType) {
Assert.Throws<ArgumentNullException>(() => this.converterFactory.GetConverter(providerType));
}
[Theory]
[InlineData(null), InlineData(""), InlineData(" ")]
public void NullEmpty_RegisterProvider_Throws(string providerType) {
var converter = new Mock<ICabinetProviderConfigConverter>();
Assert.Throws<ArgumentNullException>(() => this.converterFactory.RegisterProvider(providerType, converter.Object));
}
[Fact]
public void Null_Converter_Throws() {
ICabinetProviderConfigConverter converter = null;
Assert.Throws<ArgumentNullException>(() => this.converterFactory.RegisterProvider("providerType", converter));
}
}
}
| using Cabinet.Config;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Cabinet.Tests.Config {
public class FileCabinetConverterFactoryFacts {
private readonly FileCabinetConfigConverterFactory converterFactory;
public FileCabinetConverterFactoryFacts() {
this.converterFactory = new FileCabinetConfigConverterFactory();
}
[Theory]
[InlineData(null), InlineData(""), InlineData(" ")]
public void NullEmpty_GetConverter_Throws(string providerType) {
Assert.Throws<ArgumentNullException>(() => this.converterFactory.GetConverter(providerType));
}
[Theory]
[InlineData(null), InlineData(""), InlineData(" ")]
public void NullEmpty_RegisterProvider_Throws(string providerType) {
var converter = new Mock<ICabinetProviderConfigConverter>();
Assert.Throws<ArgumentNullException>(() => this.converterFactory.RegisterProvider(providerType, converter.Object));
}
[Fact]
public void Null_Converter_Throws(string providerType) {
ICabinetProviderConfigConverter converter = null;
Assert.Throws<ArgumentNullException>(() => this.converterFactory.RegisterProvider("providerType", converter));
}
}
}
| mit | C# |
a391a0af041f1163c3ad83bab8d3f7439d80eb85 | Update AssemblyInfo.cs | 304NotModified/NLog.ManualFlush,NLog/NLog.ManualFlush | NLog.ManualFlush/Properties/AssemblyInfo.cs | NLog.ManualFlush/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NLog.ManualFlush")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("NLog")]
[assembly: AssemblyProduct("NLog.ManualFlush")]
[assembly: AssemblyCopyright("Copyright © NLog 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a2c648b2-ef6e-4774-8e8c-686a85cff2bf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NLog.ManualFlush")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("NLog.ManualFlush")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a2c648b2-ef6e-4774-8e8c-686a85cff2bf")]
// 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# |
a130e9d325866f29b086adafa68f7cf38c001b99 | Disable test on MacOS. | dlemstra/Magick.NET,dlemstra/Magick.NET | tests/Magick.NET.Tests/Settings/MagickSettingsTests/TheFontProperty.cs | tests/Magick.NET.Tests/Settings/MagickSettingsTests/TheFontProperty.cs | // Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickSettingsTests
{
public class TheFontProperty
{
[Fact]
public void ShouldSetTheFontWhenReadingImage()
{
if (OperatingSystem.IsMacOS)
return;
using (var image = new MagickImage())
{
Assert.Null(image.Settings.Font);
image.Settings.Font = "Courier New";
image.Settings.FontPointsize = 40;
image.Read("pango:Test");
Assert.Equal(128, image.Width);
Assert.Contains(image.Height, new[] { 58, 62 });
ColorAssert.Equal(MagickColors.Black, image, 26, 22);
}
}
}
}
}
| // Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickSettingsTests
{
public class TheFontProperty
{
[Fact]
public void ShouldSetTheFontWhenReadingImage()
{
using (var image = new MagickImage())
{
Assert.Null(image.Settings.Font);
image.Settings.Font = "Courier New";
image.Settings.FontPointsize = 40;
image.Read("pango:Test");
// Different result on MacOS
if (image.Width != 40)
{
Assert.Equal(128, image.Width);
Assert.Contains(image.Height, new[] { 58, 62 });
ColorAssert.Equal(MagickColors.Black, image, 26, 22);
}
}
}
}
}
}
| apache-2.0 | C# |
df095c07496879a2e833bc55f97e7ab228bcf5ed | Rename MemoryHandle PinnedPointer to Pointer and add property HasPointer. (#14604) | ruben-ayrapetyan/coreclr,poizan42/coreclr,wtgodbe/coreclr,krk/coreclr,yizhang82/coreclr,JosephTremoulet/coreclr,ruben-ayrapetyan/coreclr,cshung/coreclr,wateret/coreclr,poizan42/coreclr,cshung/coreclr,wateret/coreclr,yizhang82/coreclr,wtgodbe/coreclr,krk/coreclr,yizhang82/coreclr,yizhang82/coreclr,JosephTremoulet/coreclr,ruben-ayrapetyan/coreclr,poizan42/coreclr,wtgodbe/coreclr,wateret/coreclr,poizan42/coreclr,JosephTremoulet/coreclr,krk/coreclr,wtgodbe/coreclr,ruben-ayrapetyan/coreclr,ruben-ayrapetyan/coreclr,cshung/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,cshung/coreclr,wtgodbe/coreclr,krk/coreclr,mmitche/coreclr,mmitche/coreclr,mmitche/coreclr,yizhang82/coreclr,mmitche/coreclr,wtgodbe/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,JosephTremoulet/coreclr,ruben-ayrapetyan/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,wateret/coreclr,wateret/coreclr,krk/coreclr,wateret/coreclr,poizan42/coreclr,krk/coreclr,yizhang82/coreclr | src/mscorlib/shared/System/Buffers/MemoryHandle.cs | src/mscorlib/shared/System/Buffers/MemoryHandle.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;
using System.Runtime.InteropServices;
namespace System.Buffers
{
public unsafe struct MemoryHandle : IDisposable
{
private IRetainable _owner;
private void* _pointer;
private GCHandle _handle;
[CLSCompliant(false)]
public MemoryHandle(IRetainable owner, void* pointer = null, GCHandle handle = default(GCHandle))
{
_owner = owner;
_pointer = pointer;
_handle = handle;
}
internal void AddOffset(int offset)
{
if (_pointer == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pointer);
}
else
{
_pointer = (void*)((byte*)_pointer + offset);
}
}
[CLSCompliant(false)]
public void* Pointer => _pointer;
public bool HasPointer => _pointer != null;
public void Dispose()
{
if (_handle.IsAllocated)
{
_handle.Free();
}
if (_owner != null)
{
_owner.Release();
_owner = null;
}
_pointer = null;
}
}
} | // 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;
using System.Runtime.InteropServices;
namespace System.Buffers
{
public unsafe struct MemoryHandle : IDisposable
{
private IRetainable _owner;
private void* _pointer;
private GCHandle _handle;
[CLSCompliant(false)]
public MemoryHandle(IRetainable owner, void* pinnedPointer = null, GCHandle handle = default(GCHandle))
{
_owner = owner;
_pointer = pinnedPointer;
_handle = handle;
}
internal void AddOffset(int offset)
{
if (_pointer == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pointer);
}
else
{
_pointer = (void*)((byte*)_pointer + offset);
}
}
[CLSCompliant(false)]
public void* PinnedPointer => _pointer;
public void Dispose()
{
if (_handle.IsAllocated)
{
_handle.Free();
}
if (_owner != null)
{
_owner.Release();
_owner = null;
}
_pointer = null;
}
}
} | mit | C# |
7f6bf67ab991640ee65b8de75f97f49a4b486289 | Update comments | Kentico/Deliver-.NET-SDK,Kentico/delivery-sdk-net | Kentico.Kontent.Delivery.Abstractions/IDeliveryCacheManager.cs | Kentico.Kontent.Delivery.Abstractions/IDeliveryCacheManager.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Kentico.Kontent.Delivery.Abstractions
{
/// <summary>
/// Cache responses against the Kentico Kontent Delivery API.
/// </summary>
public interface IDeliveryCacheManager
{
/// <summary>
/// Returns or Adds data to the cache
/// </summary>
/// <typeparam name="T">A generic type</typeparam>
/// <param name="key">A cache key</param>
/// <param name="valueFactory">A factory which returns a data</param>
/// <param name="shouldCache"></param>
/// <param name="dependenciesFactory"></param>
/// <returns>The data of a generic type</returns>
Task<T> GetOrAddAsync<T>(string key, Func<Task<T>> valueFactory, Func<T, bool> shouldCache = null, Func<T, IEnumerable<string>> dependenciesFactory = null);
/// <summary>
/// Tries to return a data
/// </summary>
/// <typeparam name="T">Generic type</typeparam>
/// <param name="key">A cache key</param>
/// <param name="value">Returns data in out parameter if are there.</param>
/// <returns>Returns true or false.</returns>
Task<bool> TryGetAsync<T>(string key, out T value);
/// <summary>
/// Invalidates data by the key
/// </summary>
/// <param name="key">A cache key</param>
/// <returns></returns>
Task InvalidateDependencyAsync(string key);
/// <summary>
/// Clears cache
/// </summary>
/// <returns></returns>
Task ClearAsync();
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Kentico.Kontent.Delivery.Abstractions
{
public interface IDeliveryCacheManager
{
Task<T> GetOrAddAsync<T>(string key, Func<Task<T>> valueFactory, Func<T, bool> shouldCache = null, Func<T, IEnumerable<string>> dependenciesFactory = null);
Task<bool> TryGetAsync<T>(string key, out T value);
Task InvalidateDependencyAsync(string key);
Task ClearAsync();
}
}
| mit | C# |
b50461251f57483085ab4cb856ff06eb442250b0 | Add more tests for ExportDocumentsCommand | eggapauli/MyDocs,eggapauli/MyDocs | Common.Test/ViewModel/ExportDocumentsCommandTest.cs | Common.Test/ViewModel/ExportDocumentsCommandTest.cs | using FakeItEasy;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyDocs.Common.Contract.Service;
using MyDocs.Common.Model;
using System.Threading.Tasks;
namespace MyDocs.Common.Test.ViewModel
{
public partial class DocumentViewModelTest
{
[TestMethod]
public void ExportDocumentsCommandShouldBeEnabled()
{
var sut = CreateSut();
sut.ExportDocumentsCommand.CanExecute(null).Should().BeTrue();
}
[TestMethod]
public void ExportDocumentsCommandShouldFailWhenUnlicensed()
{
var licenseService = A.Fake<ILicenseService>();
var exportDocumentService = A.Fake<IExportDocumentService>();
A.CallTo(() => licenseService.Unlock("ExportImportDocuments")).Throws(new LicenseStatusException("Test", LicenseStatus.Locked));
var sut = CreateSut(licenseService: licenseService, exportDocumentService: exportDocumentService);
using (Fake.CreateScope())
{
sut.ExportDocumentsCommand.Execute(null);
WaitForCommand();
A.CallTo(() => exportDocumentService.ExportDocuments()).MustNotHaveHappened();
}
}
[TestMethod]
public void ExportDocumentsCommandShouldSucceedWhenLicensed()
{
var exportDocumentService = A.Fake<IExportDocumentService>();
var sut = CreateSut(exportDocumentService: exportDocumentService);
using (Fake.CreateScope())
{
sut.ExportDocumentsCommand.Execute(null);
WaitForCommand();
A.CallTo(() => exportDocumentService.ExportDocuments()).MustHaveHappened();
}
}
[TestMethod]
public void ViewModelShouldBeBusyWhileExportingDocuments()
{
var tcs = new TaskCompletionSource<object>();
var exportDocumentService = A.Fake<IExportDocumentService>();
A.CallTo(() => exportDocumentService.ExportDocuments()).Returns(tcs.Task);
var sut = CreateSut(exportDocumentService: exportDocumentService);
sut.IsBusy.Should().BeFalse();
sut.ExportDocumentsCommand.Execute(null);
WaitForCommand();
sut.IsBusy.Should().BeTrue();
tcs.SetResult(null);
WaitForCommand();
sut.IsBusy.Should().BeFalse();
}
}
}
| using FakeItEasy;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyDocs.Common.Contract.Service;
using MyDocs.Common.Model;
namespace MyDocs.Common.Test.ViewModel
{
public partial class DocumentViewModelTest
{
[TestMethod]
public void ExportDocumentsCommandShouldBeEnabled()
{
var sut = CreateSut();
sut.ExportDocumentsCommand.CanExecute(null).Should().BeTrue();
}
[TestMethod]
public void ExportDocumentsCommandShouldFailWhenUnlicensed()
{
var licenseService = A.Fake<ILicenseService>();
var exportDocumentService = A.Fake<IExportDocumentService>();
A.CallTo(() => licenseService.Unlock("ExportImportDocuments")).Throws(new LicenseStatusException("Test", LicenseStatus.Locked));
var sut = CreateSut(licenseService: licenseService, exportDocumentService: exportDocumentService);
using (Fake.CreateScope())
{
sut.ExportDocumentsCommand.Execute(null);
WaitForCommand();
A.CallTo(() => exportDocumentService.ExportDocuments()).MustNotHaveHappened();
}
}
}
}
| mit | C# |
7d928675d0d9343524b04b85757440d199bd4e64 | Delete DeleteRedundantEvents option | melanchall/drywetmidi,melanchall/drywetmidi,melanchall/drymidi | DryWetMidi/Smf/WritingSettings/CompressionPolicy.cs | DryWetMidi/Smf/WritingSettings/CompressionPolicy.cs | using System;
namespace Melanchall.DryWetMidi.Smf
{
/// <summary>
/// Specifies how writing engine should compress MIDI data. The default is <see cref="NoCompression"/>.
/// </summary>
[Flags]
public enum CompressionPolicy
{
/// <summary>
/// Don't use any compression on the MIDI data to write.
/// </summary>
NoCompression = 0,
/// <summary>
/// Use default compression on the MIDI data to write. This option turns on all options
/// that don't lead to data losing (for example, unknown meta events).
/// </summary>
Default =
UseRunningStatus |
NoteOffAsSilentNoteOn |
DeleteDefaultTimeSignature |
DeleteDefaultKeySignature |
DeleteDefaultSetTempo,
/// <summary>
/// Use 'running status' to turn off writing of the status bytes of consecutive events
/// of the same type.
/// </summary>
UseRunningStatus = 1,
/// <summary>
/// Turn Note Off events into the Note On ones with zero velocity. Note that it helps to
/// compress MIDI data in the case of <see cref="UseRunningStatus"/> is used only.
/// </summary>
NoteOffAsSilentNoteOn = 2,
/// <summary>
/// Don't write default Time Signature event.
/// </summary>
DeleteDefaultTimeSignature = 4,
/// <summary>
/// Don't write default Key Signature event.
/// </summary>
DeleteDefaultKeySignature = 8,
/// <summary>
/// Don't write default Set Tempo event.
/// </summary>
DeleteDefaultSetTempo = 16,
/// <summary>
/// Don't write instances of the <see cref="UnknownMetaEvent"/>.
/// </summary>
DeleteUnknownMetaEvents = 32,
/// <summary>
/// Don't write instances of the <see cref="UnknownChunk"/>.
/// </summary>
DeleteUnknownChunks = 64,
}
}
| using System;
namespace Melanchall.DryWetMidi.Smf
{
/// <summary>
/// Specifies how writing engine should compress MIDI data. The default is <see cref="NoCompression"/>.
/// </summary>
[Flags]
public enum CompressionPolicy
{
/// <summary>
/// Don't use any compression on the MIDI data to write.
/// </summary>
NoCompression = 0,
/// <summary>
/// Use default compression on the MIDI data to write. This option turns on all options
/// that don't lead to data losing (for example, unknown meta events).
/// </summary>
Default =
UseRunningStatus |
NoteOffAsSilentNoteOn |
DeleteDefaultTimeSignature |
DeleteDefaultKeySignature |
DeleteDefaultSetTempo |
DeleteRedundantEvents,
/// <summary>
/// Use 'running status' to turn off writing of the status bytes of consecutive events
/// of the same type.
/// </summary>
UseRunningStatus = 1,
/// <summary>
/// Turn Note Off events into the Note On ones with zero velocity. Note that it helps to
/// compress MIDI data in the case of <see cref="UseRunningStatus"/> is used only.
/// </summary>
NoteOffAsSilentNoteOn = 2,
/// <summary>
/// Don't write default Time Signature event.
/// </summary>
DeleteDefaultTimeSignature = 4,
/// <summary>
/// Don't write default Key Signature event.
/// </summary>
DeleteDefaultKeySignature = 8,
/// <summary>
/// Don't write default Set Tempo event.
/// </summary>
DeleteDefaultSetTempo = 16,
/// <summary>
/// Don't write instances of the <see cref="UnknownMetaEvent"/>.
/// </summary>
DeleteUnknownMetaEvents = 32,
/// <summary>
/// Don't write instances of the <see cref="UnknownChunk"/>.
/// </summary>
DeleteUnknownChunks = 64,
/// <summary>
/// Don't write redundant events.
/// </summary>
DeleteRedundantEvents = 128
}
}
| mit | C# |
1a474592625ccc97b47b11bdb953dcdbf3fdd8a9 | Fix taiko difficulty adjust scroll speed being shown with too low precision | ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu | osu.Game.Rulesets.Taiko/Mods/TaikoModDifficultyAdjust.cs | osu.Game.Rulesets.Taiko/Mods/TaikoModDifficultyAdjust.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModDifficultyAdjust : ModDifficultyAdjust
{
[SettingSource("Scroll Speed", "Adjust a beatmap's set scroll speed", LAST_SETTING_ORDER + 1, SettingControlType = typeof(DifficultyAdjustSettingsControl))]
public DifficultyBindable ScrollSpeed { get; } = new DifficultyBindable
{
Precision = 0.05f,
MinValue = 0.25f,
MaxValue = 4,
ReadCurrentFromDifficulty = _ => 1,
};
public override string SettingDescription
{
get
{
string scrollSpeed = ScrollSpeed.IsDefault ? string.Empty : $"Scroll x{ScrollSpeed.Value:N2}";
return string.Join(", ", new[]
{
base.SettingDescription,
scrollSpeed
}.Where(s => !string.IsNullOrEmpty(s)));
}
}
protected override void ApplySettings(BeatmapDifficulty difficulty)
{
base.ApplySettings(difficulty);
if (ScrollSpeed.Value != null) difficulty.SliderMultiplier *= ScrollSpeed.Value.Value;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModDifficultyAdjust : ModDifficultyAdjust
{
[SettingSource("Scroll Speed", "Adjust a beatmap's set scroll speed", LAST_SETTING_ORDER + 1, SettingControlType = typeof(DifficultyAdjustSettingsControl))]
public DifficultyBindable ScrollSpeed { get; } = new DifficultyBindable
{
Precision = 0.05f,
MinValue = 0.25f,
MaxValue = 4,
ReadCurrentFromDifficulty = _ => 1,
};
public override string SettingDescription
{
get
{
string scrollSpeed = ScrollSpeed.IsDefault ? string.Empty : $"Scroll x{ScrollSpeed.Value:N1}";
return string.Join(", ", new[]
{
base.SettingDescription,
scrollSpeed
}.Where(s => !string.IsNullOrEmpty(s)));
}
}
protected override void ApplySettings(BeatmapDifficulty difficulty)
{
base.ApplySettings(difficulty);
if (ScrollSpeed.Value != null) difficulty.SliderMultiplier *= ScrollSpeed.Value.Value;
}
}
}
| mit | C# |
a7bcae48694a1ead3949cedcf866c59d3b77d751 | Add startup value for the slider | peppy/osu,DrabWeb/osu,peppy/osu,naoey/osu,ZLima12/osu,ppy/osu,EVAST9919/osu,Nabile-Rahmani/osu,johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,DrabWeb/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu-new,naoey/osu,2yangk23/osu,UselessToucan/osu,Frontear/osuKyzer,ZLima12/osu,EVAST9919/osu,NeoAdonis/osu,johnneijzen/osu,Drezi126/osu,ppy/osu,DrabWeb/osu,UselessToucan/osu,naoey/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu | osu.Game/Screens/Play/ReplaySettings/PlaybackSettings.cs | osu.Game/Screens/Play/ReplaySettings/PlaybackSettings.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Timing;
using osu.Framework.Configuration;
namespace osu.Game.Screens.Play.ReplaySettings
{
public class PlaybackSettings : ReplayGroup
{
protected override string Title => @"playback";
public IAdjustableClock AdjustableClock { set; get; }
private readonly ReplaySliderBar<double> sliderbar;
public PlaybackSettings()
{
Child = sliderbar = new ReplaySliderBar<double>
{
LabelText = "Playback speed",
Bindable = new BindableDouble(1)
{
Default = 1,
MinValue = 0.5,
MaxValue = 2
},
};
}
protected override void LoadComplete()
{
base.LoadComplete();
if (AdjustableClock == null)
return;
var clockRate = AdjustableClock.Rate;
sliderbar.Bindable.ValueChanged += rateMultiplier => AdjustableClock.Rate = clockRate * rateMultiplier;
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Timing;
using osu.Framework.Configuration;
namespace osu.Game.Screens.Play.ReplaySettings
{
public class PlaybackSettings : ReplayGroup
{
protected override string Title => @"playback";
public IAdjustableClock AdjustableClock { set; get; }
private readonly ReplaySliderBar<double> sliderbar;
public PlaybackSettings()
{
Child = sliderbar = new ReplaySliderBar<double>
{
LabelText = "Playback speed",
Bindable = new BindableDouble
{
Default = 1,
MinValue = 0.5,
MaxValue = 2
},
};
}
protected override void LoadComplete()
{
base.LoadComplete();
if (AdjustableClock == null)
return;
var clockRate = AdjustableClock.Rate;
sliderbar.Bindable.ValueChanged += rateMultiplier => AdjustableClock.Rate = clockRate * rateMultiplier;
}
}
}
| mit | C# |
f3b7a4926e5a26cc8a5df37bb4a3b45c2afe326d | Remove redundant using statements | playmyskay/cppcheck-vs-addin,Dmitry-Me/cppcheck-vs-addin,VioletGiraffe/cppcheck-vs-addin | CPPCheckPlugin/SuppressionsSettingsUI/SuppressionsSettings.xaml.cs | CPPCheckPlugin/SuppressionsSettingsUI/SuppressionsSettings.xaml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace VSPackage.CPPCheckPlugin.SuppressionSettingsUI
{
/// <summary>
/// Interaction logic for SuppressionsSettings.xaml
/// </summary>
public partial class SuppressionsSettings : Window
{
public string suppressionsFilePath;
public SuppressionsSettings(ICodeAnalyzer.SuppressionStorage suppressionStorage, string projectBasePath = null, string projectName = null)
{
InitializeComponent();
suppressionsFilePath = ICodeAnalyzer.suppressionsFilePathByStorage(suppressionStorage, projectBasePath, projectName);
SuppressionsInfo suppressionsInfo = new SuppressionsInfo();
suppressionsInfo.LoadFromFile(suppressionsFilePath);
CppcheckLines.Items = suppressionsInfo.SuppressionLines;
FilesLines.Items = suppressionsInfo.SkippedFilesMask;
IncludesLines.Items = suppressionsInfo.SkippedIncludesMask;
}
private void SaveClick(object sender, RoutedEventArgs e)
{
SuppressionsInfo suppressionsInfo = new SuppressionsInfo();
suppressionsInfo.SuppressionLines = CppcheckLines.Items;
while (suppressionsInfo.SuppressionLines.Remove("")) { /* nothing */ }
suppressionsInfo.SkippedFilesMask = FilesLines.Items;
while (suppressionsInfo.SkippedFilesMask.Remove("")) { /* nothing */ }
suppressionsInfo.SkippedIncludesMask = IncludesLines.Items;
while (suppressionsInfo.SkippedIncludesMask.Remove("")) { /* nothing */ }
suppressionsInfo.SaveToFile(suppressionsFilePath);
Close();
}
private void CancelClick(object sender, RoutedEventArgs e)
{
Close();
}
}
}
| 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.Shapes;
namespace VSPackage.CPPCheckPlugin.SuppressionSettingsUI
{
/// <summary>
/// Interaction logic for SuppressionsSettings.xaml
/// </summary>
public partial class SuppressionsSettings : Window
{
public string suppressionsFilePath;
public SuppressionsSettings(ICodeAnalyzer.SuppressionStorage suppressionStorage, string projectBasePath = null, string projectName = null)
{
InitializeComponent();
suppressionsFilePath = ICodeAnalyzer.suppressionsFilePathByStorage(suppressionStorage, projectBasePath, projectName);
SuppressionsInfo suppressionsInfo = new SuppressionsInfo();
suppressionsInfo.LoadFromFile(suppressionsFilePath);
CppcheckLines.Items = suppressionsInfo.SuppressionLines;
FilesLines.Items = suppressionsInfo.SkippedFilesMask;
IncludesLines.Items = suppressionsInfo.SkippedIncludesMask;
}
private void SaveClick(object sender, RoutedEventArgs e)
{
SuppressionsInfo suppressionsInfo = new SuppressionsInfo();
suppressionsInfo.SuppressionLines = CppcheckLines.Items;
while (suppressionsInfo.SuppressionLines.Remove("")) { /* nothing */ }
suppressionsInfo.SkippedFilesMask = FilesLines.Items;
while (suppressionsInfo.SkippedFilesMask.Remove("")) { /* nothing */ }
suppressionsInfo.SkippedIncludesMask = IncludesLines.Items;
while (suppressionsInfo.SkippedIncludesMask.Remove("")) { /* nothing */ }
suppressionsInfo.SaveToFile(suppressionsFilePath);
Close();
}
private void CancelClick(object sender, RoutedEventArgs e)
{
Close();
}
}
}
| mit | C# |
84f74834416a2dd2df5d6e7e2b56957f85bccf4d | Fix for NH-3111 - SelectJoinDetector should try to rewrite sub queries | lnu/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core | src/NHibernate/Linq/Visitors/SelectJoinDetector.cs | src/NHibernate/Linq/Visitors/SelectJoinDetector.cs | using System.Linq.Expressions;
using NHibernate.Linq.ReWriters;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.Expressions;
namespace NHibernate.Linq.Visitors
{
internal class SelectJoinDetector : NhExpressionTreeVisitor
{
private readonly IIsEntityDecider _isEntityDecider;
private readonly IJoiner _joiner;
private bool _hasIdentifier;
private int _identifierMemberExpressionDepth;
public SelectJoinDetector(IIsEntityDecider isEntityDecider, IJoiner joiner)
{
_isEntityDecider = isEntityDecider;
_joiner = joiner;
}
protected override Expression VisitMemberExpression(MemberExpression expression)
{
if (_isEntityDecider.IsIdentifier(expression.Expression.Type, expression.Member.Name))
_hasIdentifier = true;
else if (_hasIdentifier)
_identifierMemberExpressionDepth++;
var result = base.VisitMemberExpression(expression);
_identifierMemberExpressionDepth--;
if (_isEntityDecider.IsEntity(expression.Type) && (!_hasIdentifier || _identifierMemberExpressionDepth > 0))
{
var key = ExpressionKeyVisitor.Visit(expression, null);
return _joiner.AddJoin(result, key);
}
_hasIdentifier = false;
return result;
}
public void Transform(SelectClause selectClause)
{
selectClause.TransformExpressions(VisitExpression);
}
protected override Expression VisitSubQueryExpression(SubQueryExpression expression)
{
expression.QueryModel.TransformExpressions(VisitExpression);
return expression;
}
}
}
| using System.Linq.Expressions;
using NHibernate.Linq.ReWriters;
using Remotion.Linq.Clauses;
namespace NHibernate.Linq.Visitors
{
internal class SelectJoinDetector : NhExpressionTreeVisitor
{
private readonly IIsEntityDecider _isEntityDecider;
private readonly IJoiner _joiner;
private bool _hasIdentifier;
private int _identifierMemberExpressionDepth;
public SelectJoinDetector(IIsEntityDecider isEntityDecider, IJoiner joiner)
{
_isEntityDecider = isEntityDecider;
_joiner = joiner;
}
protected override Expression VisitMemberExpression(MemberExpression expression)
{
if (_isEntityDecider.IsIdentifier(expression.Expression.Type, expression.Member.Name))
_hasIdentifier = true;
else if (_hasIdentifier)
_identifierMemberExpressionDepth++;
var result = base.VisitMemberExpression(expression);
_identifierMemberExpressionDepth--;
if (_isEntityDecider.IsEntity(expression.Type) && (!_hasIdentifier || _identifierMemberExpressionDepth > 0))
{
var key = ExpressionKeyVisitor.Visit(expression, null);
return _joiner.AddJoin(result, key);
}
_hasIdentifier = false;
return result;
}
public void Transform(SelectClause selectClause)
{
selectClause.TransformExpressions(VisitExpression);
}
}
}
| lgpl-2.1 | C# |
cc3133d1c8af6d6ef6154b960703aafa005af92d | fix observable hash set but indicating to rebuild the list everytime. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Helpers/ConcurrentObservableHashSet.cs | WalletWasabi/Helpers/ConcurrentObservableHashSet.cs | using System.Collections.Generic;
using System.Collections.Specialized;
using ConcurrentCollections;
namespace System.Collections.ObjectModel
{
public class ConcurrentObservableHashSet<T> : INotifyCollectionChanged, IReadOnlyCollection<T>
{
protected ConcurrentHashSet<T> ConcurrentHashSet { get; }
private object Lock { get; }
public ConcurrentObservableHashSet()
{
ConcurrentHashSet = new ConcurrentHashSet<T>();
Lock = new object();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerator<T> GetEnumerator() => ConcurrentHashSet.GetEnumerator();
public bool TryAdd(T item)
{
lock (Lock)
{
if (ConcurrentHashSet.Add(item))
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, Count - 1));
return true;
}
return false;
}
}
public void Clear()
{
lock (Lock)
{
if (ConcurrentHashSet.Count > 0)
{
ConcurrentHashSet.Clear();
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
}
public bool Contains(T item) => ConcurrentHashSet.Contains(item);
public bool TryRemove(T item)
{
lock (Lock)
{
if (ConcurrentHashSet.TryRemove(item))
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
foreach (var hash in ConcurrentHashSet)
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, hash, Count - 1));
}
return true;
}
return false;
}
}
public int Count => ConcurrentHashSet.Count;
}
}
| using System.Collections.Generic;
using System.Collections.Specialized;
using ConcurrentCollections;
namespace System.Collections.ObjectModel
{
public class ConcurrentObservableHashSet<T> : INotifyCollectionChanged, IReadOnlyCollection<T>
{
protected ConcurrentHashSet<T> ConcurrentHashSet { get; }
private object Lock { get; }
public ConcurrentObservableHashSet()
{
ConcurrentHashSet = new ConcurrentHashSet<T>();
Lock = new object();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerator<T> GetEnumerator() => ConcurrentHashSet.GetEnumerator();
public bool TryAdd(T item)
{
lock (Lock)
{
if (ConcurrentHashSet.Add(item))
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, Count - 1));
return true;
}
return false;
}
}
public void Clear()
{
lock (Lock)
{
if (ConcurrentHashSet.Count > 0)
{
ConcurrentHashSet.Clear();
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
}
public bool Contains(T item) => ConcurrentHashSet.Contains(item);
public bool TryRemove(T item)
{
lock (Lock)
{
if (ConcurrentHashSet.TryRemove(item))
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
foreach (var hash in ConcurrentHashSet)
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, hash));
}
return true;
}
return false;
}
}
public int Count => ConcurrentHashSet.Count;
}
}
| mit | C# |
e96dd7982334b22c12e2eec2e3ca08bd48e1fd5c | Change name of the property for the status transition to match the API too | richardlawley/stripe.net,stripe/stripe-dotnet | src/Stripe.net/Entities/StripeStatusTransitions.cs | src/Stripe.net/Entities/StripeStatusTransitions.cs | using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeStatusTransitions : StripeEntity
{
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("canceled")]
public DateTime? Canceled { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("fulfiled")]
public DateTime? Fulfiled { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("paid")]
public DateTime? Paid { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("returned")]
public DateTime? Returned { get; set; }
}
}
| using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeStatusTransitions : StripeEntity
{
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("canceled")]
public DateTime? Canceled { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("fulfiled")]
public DateTime? Fulfilled { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("paid")]
public DateTime? Paid { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("returned")]
public DateTime? Returned { get; set; }
}
}
| apache-2.0 | C# |
eba61ee8159349bc4ecc44c6b6658ad8e2113667 | Remove Hp-Reborn | bunashibu/kikan | Assets/Scripts/Hp/Hp.cs | Assets/Scripts/Hp/Hp.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hp : IGauge<int> {
public void Plus(int quantity) {
Cur += quantity;
AdjustBoundary();
}
public void Minus(int quantity) {
Cur -= quantity;
AdjustBoundary();
}
private void AdjustBoundary() {
if (Cur <= Min)
Die();
if (Cur > Max)
Cur = Max;
}
protected virtual void Die() {
IsDead = true;
Cur = Min;
}
public int Cur { get; protected set; }
public int Min { get; protected set; }
public int Max { get; protected set; }
public bool IsDead { get; protected set; }
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hp : IGauge<int> {
public void Plus(int quantity) {
Cur += quantity;
AdjustBoundary();
}
public void Minus(int quantity) {
Cur -= quantity;
AdjustBoundary();
}
private void AdjustBoundary() {
if (Cur <= Min)
Die();
if (Cur > Max)
Cur = Max;
if (IsDead && (Cur > Min))
Reborn();
}
protected virtual void Die() {
IsDead = true;
Cur = Min;
}
private void Reborn() {
IsDead = false;
}
public int Cur { get; protected set; }
public int Min { get; protected set; }
public int Max { get; protected set; }
public bool IsDead { get; protected set; }
}
| mit | C# |
641656b2e3717f830439bd7eb41157efc410a8c6 | Add new createInstance overloads to scriptbuilderfactory.cs to support scriptbuildersettings args | Ackara/Daterpillar | src/Daterpillar.Core/TextTransformation/ScriptBuilderFactory.cs | src/Daterpillar.Core/TextTransformation/ScriptBuilderFactory.cs | using System;
using System.Collections.Generic;
using System.Reflection;
namespace Acklann.Daterpillar.TextTransformation
{
public class ScriptBuilderFactory
{
public ScriptBuilderFactory()
{
LoadAssemblyTypes();
}
public IScriptBuilder CreateInstance(string name)
{
return CreateInstance(name, ScriptBuilderSettings.Default);
}
public IScriptBuilder CreateInstance(string name, ScriptBuilderSettings settings)
{
try { return (IScriptBuilder)Activator.CreateInstance(Type.GetType(_scriptBuilderTypes[name.ToLower()]), settings); }
catch (KeyNotFoundException) { return new NullScriptBuilder(); }
}
public IScriptBuilder CreateInstance(ConnectionType connectionType)
{
return CreateInstance(string.Concat(connectionType, _targetInterface), ScriptBuilderSettings.Default);
}
public IScriptBuilder CreateInstance(ConnectionType connectionType, ScriptBuilderSettings settings)
{
return CreateInstance(string.Concat(connectionType, _targetInterface), settings);
}
#region Private Members
private string _targetInterface = nameof(IScriptBuilder).Substring(1);
private IDictionary<string, string> _scriptBuilderTypes = new Dictionary<string, string>();
private void LoadAssemblyTypes()
{
Assembly thisAssembly = Assembly.Load(new AssemblyName(typeof(IScriptBuilder).GetTypeInfo().Assembly.FullName));
foreach (var typeInfo in thisAssembly.DefinedTypes)
if (typeInfo.IsPublic && !typeInfo.IsInterface && !typeInfo.IsAbstract && typeof(IScriptBuilder).GetTypeInfo().IsAssignableFrom(typeInfo))
{
_scriptBuilderTypes.Add(typeInfo.Name.ToLower(), typeInfo.FullName);
}
}
#endregion Private Members
}
} | using System;
using System.Collections.Generic;
using System.Reflection;
namespace Acklann.Daterpillar.TextTransformation
{
public class ScriptBuilderFactory
{
public ScriptBuilderFactory()
{
LoadAssemblyTypes();
}
public IScriptBuilder CreateInstance(string name)
{
try { return (IScriptBuilder)Activator.CreateInstance(Type.GetType(_scriptBuilderTypes[name.ToLower()])); }
catch (KeyNotFoundException) { return new NullScriptBuilder(); }
}
public IScriptBuilder CreateInstance(ConnectionType connectionType)
{
return CreateInstance(string.Concat(connectionType, _targetInterface));
}
#region Private Members
private string _targetInterface = nameof(IScriptBuilder).Substring(1);
private IDictionary<string, string> _scriptBuilderTypes = new Dictionary<string, string>();
private void LoadAssemblyTypes()
{
Assembly thisAssembly = Assembly.Load(new AssemblyName(typeof(IScriptBuilder).GetTypeInfo().Assembly.FullName));
foreach (var typeInfo in thisAssembly.DefinedTypes)
if (typeInfo.IsPublic && !typeInfo.IsInterface && !typeInfo.IsAbstract && typeof(IScriptBuilder).GetTypeInfo().IsAssignableFrom(typeInfo))
{
_scriptBuilderTypes.Add(typeInfo.Name.ToLower(), typeInfo.FullName);
}
}
#endregion Private Members
}
} | mit | C# |
7ccb2a1e1b382a0c79993ea880ada8c8c8dad4bc | Improve error message in html attribute merging | riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm | src/Framework/Framework/Compilation/HtmlAttributeValueMerger.cs | src/Framework/Framework/Compilation/HtmlAttributeValueMerger.cs | using DotVVM.Framework.Binding;
using DotVVM.Framework.Compilation.Binding;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
namespace DotVVM.Framework.Compilation
{
public class HtmlAttributeValueMerger: DefaultAttributeValueMerger
{
public static Expression MergeExpressions(GroupedDotvvmProperty property, Expression a, Expression b)
{
var attributeName = property.GroupMemberName;
var separator = HtmlWriter.GetSeparatorForAttribute(attributeName);
var method = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });
return Expression.Add(Expression.Add(a, Expression.Constant(separator), method), b, method);
// return Expression.Call(typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string), typeof(string) }), a, Expression.Constant(separator), b);
}
public static string? MergeValues(GroupedDotvvmProperty property, string? a, string? b)
{
// for perf reasons only do this compile time - we'll deduplicate the attribute if it's a CSS class
if (property.GroupMemberName == "class" && a is string && b is string)
{
var classesA = a.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
var classesB = b.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)
.Where(c => !classesA.Contains(c));
b = string.Join(" ", classesB);
}
return HtmlWriter.JoinAttributeValues(property.GroupMemberName, a, b);
}
public override object? MergePlainValues(DotvvmProperty prop, object? a, object? b)
{
var gProp = (GroupedDotvvmProperty)prop;
if (a is null) return b;
if (b is null) return a;
if (a is string aString && b is string bString)
return HtmlWriter.JoinAttributeValues(gProp.GroupMemberName, aString, bString);
throw new NotSupportedException($"Cannot merge '{gProp.GroupMemberName}' attribute values {a} and {b}, the values must be of type string.");
}
}
}
| using DotVVM.Framework.Binding;
using DotVVM.Framework.Compilation.Binding;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
namespace DotVVM.Framework.Compilation
{
public class HtmlAttributeValueMerger: DefaultAttributeValueMerger
{
public static Expression MergeExpressions(GroupedDotvvmProperty property, Expression a, Expression b)
{
var attributeName = property.GroupMemberName;
var separator = HtmlWriter.GetSeparatorForAttribute(attributeName);
var method = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });
return Expression.Add(Expression.Add(a, Expression.Constant(separator), method), b, method);
// return Expression.Call(typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string), typeof(string) }), a, Expression.Constant(separator), b);
}
public static string? MergeValues(GroupedDotvvmProperty property, string? a, string? b)
{
// for perf reasons only do this compile time - we'll deduplicate the attribute if it's a CSS class
if (property.GroupMemberName == "class" && a is string && b is string)
{
var classesA = a.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
var classesB = b.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)
.Where(c => !classesA.Contains(c));
b = string.Join(" ", classesB);
}
return HtmlWriter.JoinAttributeValues(property.GroupMemberName, a, b);
}
public override object? MergePlainValues(DotvvmProperty prop, object? a, object? b)
{
var gProp = (GroupedDotvvmProperty)prop;
if (a is null) return b;
if (b is null) return a;
if (a is string aString && b is string bString)
return HtmlWriter.JoinAttributeValues(gProp.GroupMemberName, aString, bString);
throw new NotSupportedException($"Cannot merge html attribute values {a} and {b}, the values must be of type string.");
}
}
}
| apache-2.0 | C# |
7b342fe508a15dd2acabff932a4285926136b28b | Add missing CustomerProfileResponse properties | TSEVOLLC/GIDX.SDK-csharp | src/GIDX.SDK/Models/CustomerIdentity/CustomerProfileResponse.cs | src/GIDX.SDK/Models/CustomerIdentity/CustomerProfileResponse.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GIDX.SDK.Models.CustomerIdentity
{
public class CustomerProfileResponse : ResponseBase, IReasonCodes
{
public string MerchantCustomerID { get; set; }
public string ProfileVerificationStatus { get; set; }
public List<string> ReasonCodes { get; set; }
public List<Name> Name { get; set; }
public List<Birth> DateOfBirth { get; set; }
public List<Citizenship> Citizenship { get; set; }
public List<IdDocument> IdDocument { get; set; }
public List<Email> Email { get; set; }
public List<Phone> Phone { get; set; }
public List<Address> Address { get; set; }
public List<Device> Device { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GIDX.SDK.Models.CustomerIdentity
{
public class CustomerProfileResponse : ResponseBase
{
public string MerchantCustomerID { get; set; }
public List<Name> Name { get; set; }
public List<Birth> DateOfBirth { get; set; }
public List<Citizenship> Citizenship { get; set; }
public List<IdDocument> IdDocument { get; set; }
public List<Email> Email { get; set; }
public List<Phone> Phone { get; set; }
public List<Address> Address { get; set; }
public List<Device> Device { get; set; }
}
}
| mit | C# |
07bff2d776840c2b21c9eee82313ee060888a263 | Use Lazy rather than IGitHubServiceProvider | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.InlineReviews/Margins/InlineCommentMarginProvider.cs | src/GitHub.InlineReviews/Margins/InlineCommentMarginProvider.cs | using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Text.Classification;
using GitHub.Services;
using GitHub.VisualStudio;
using GitHub.InlineReviews.Services;
namespace GitHub.InlineReviews.Margins
{
[Export(typeof(IWpfTextViewMarginProvider))]
[Name(InlineCommentMargin.MarginName)]
[Order(After = PredefinedMarginNames.Glyph)]
[MarginContainer(PredefinedMarginNames.Left)]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal sealed class InlineCommentMarginProvider : IWpfTextViewMarginProvider
{
readonly Lazy<IEditorFormatMapService> editorFormatMapService;
readonly Lazy<IViewTagAggregatorFactoryService> tagAggregatorFactory;
readonly Lazy<IInlineCommentPeekService> peekService;
readonly Lazy<IPullRequestSessionManager> sessionManager;
readonly UIContext uiContext;
[ImportingConstructor]
public InlineCommentMarginProvider(
Lazy<IPullRequestSessionManager> sessionManager,
Lazy<IEditorFormatMapService> editorFormatMapService,
Lazy<IViewTagAggregatorFactoryService> tagAggregatorFactory,
Lazy<IInlineCommentPeekService> peekService)
{
this.sessionManager = sessionManager;
this.editorFormatMapService = editorFormatMapService;
this.tagAggregatorFactory = tagAggregatorFactory;
this.peekService = peekService;
uiContext = UIContext.FromUIContextGuid(new Guid(Guids.UIContext_Git));
}
public IWpfTextViewMargin CreateMargin(IWpfTextViewHost wpfTextViewHost, IWpfTextViewMargin parent)
{
if (!uiContext.IsActive)
{
// Only create margin when in the context of a Git repository
return null;
}
return new InlineCommentMargin(
wpfTextViewHost,
peekService.Value,
editorFormatMapService.Value,
tagAggregatorFactory.Value,
sessionManager);
}
}
}
| using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Text.Classification;
using GitHub.Services;
using GitHub.VisualStudio;
using GitHub.InlineReviews.Services;
namespace GitHub.InlineReviews.Margins
{
[Export(typeof(IWpfTextViewMarginProvider))]
[Name(InlineCommentMargin.MarginName)]
[Order(After = PredefinedMarginNames.Glyph)]
[MarginContainer(PredefinedMarginNames.Left)]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal sealed class InlineCommentMarginProvider : IWpfTextViewMarginProvider
{
readonly Lazy<IEditorFormatMapService> editorFormatMapService;
readonly Lazy<IViewTagAggregatorFactoryService> tagAggregatorFactory;
readonly Lazy<IInlineCommentPeekService> peekService;
readonly Lazy<IPullRequestSessionManager> sessionManager;
readonly UIContext uiContext;
[ImportingConstructor]
public InlineCommentMarginProvider(
Lazy<IGitHubServiceProvider> serviceProvider,
Lazy<IEditorFormatMapService> editorFormatMapService,
Lazy<IViewTagAggregatorFactoryService> tagAggregatorFactory,
Lazy<IInlineCommentPeekService> peekService)
{
this.editorFormatMapService = editorFormatMapService;
this.tagAggregatorFactory = tagAggregatorFactory;
this.peekService = peekService;
sessionManager = new Lazy<IPullRequestSessionManager>(() => serviceProvider.Value.GetService<IPullRequestSessionManager>());
uiContext = UIContext.FromUIContextGuid(new Guid(Guids.UIContext_Git));
}
public IWpfTextViewMargin CreateMargin(IWpfTextViewHost wpfTextViewHost, IWpfTextViewMargin parent)
{
if (!uiContext.IsActive)
{
// Only create margin when in the context of a Git repository
return null;
}
return new InlineCommentMargin(
wpfTextViewHost,
peekService.Value,
editorFormatMapService.Value,
tagAggregatorFactory.Value,
sessionManager);
}
}
}
| mit | C# |
91c0aa0bcd46cfa2cffb4567fb71dc4b7946b9bf | Remove duplicate mention of FormCheckbox | EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,n2cms/n2cms,nicklv/n2cms,nicklv/n2cms,EzyWebwerkstaden/n2cms,SntsDev/n2cms,nimore/n2cms,VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,nimore/n2cms,EzyWebwerkstaden/n2cms,SntsDev/n2cms,bussemac/n2cms,nimore/n2cms,EzyWebwerkstaden/n2cms,nicklv/n2cms,DejanMilicic/n2cms,n2cms/n2cms,SntsDev/n2cms,n2cms/n2cms,bussemac/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,nicklv/n2cms,DejanMilicic/n2cms,bussemac/n2cms,nicklv/n2cms,VoidPointerAB/n2cms,n2cms/n2cms,bussemac/n2cms,nimore/n2cms,DejanMilicic/n2cms,bussemac/n2cms | src/Mvc/Dinamico/Dinamico/Registrations/FreeFormRegistration.cs | src/Mvc/Dinamico/Dinamico/Registrations/FreeFormRegistration.cs | using System.Web.UI.WebControls;
using Dinamico.Controllers;
using Dinamico.Models;
using N2.Definitions.Runtime;
using N2.Web.Mvc;
namespace Dinamico.Registrations
{
[Registration]
public class FreeFormRegistration : FluentRegisterer<FreeForm>
{
public override void RegisterDefinition(IContentRegistration<FreeForm> register)
{
register.Part(title: "Free form", description: "A form that can be sumitted and sent to an email address or viewed online.");
register.ControlledBy<FreeFormController>();
register.Definition.SortOrder = 250;
register.Icon("{IconsUrl}/report.png");
register.On(ff => ff.Form).FreeText("Form (with tokens)").Configure(eft =>
{
eft.HelpTitle = "This text supports tokens";
eft.HelpText = "{{FormCheckbox}}, {{FormFile}}, {{FormInput}}, {{FormRadio}}, {{FormSelect}}, {{FormSubmit}}, {{FormTextarea}}";
}).WithTokens();
register.On(ff => ff.SubmitText).FreeText("Thank you text");
using (register.FieldSetContainer("Email", "Email").Begin())
{
register.On(ff => ff.MailFrom).Text("Mail from").Placeholder("[email protected]");
register.On(ff => ff.MailTo).Text("Mail to").Placeholder("[email protected]");
register.On(ff => ff.MailSubject).Text("Mail subject").Placeholder("Mail title");
register.On(ff => ff.MailBody).Text("Mail intro text").Placeholder("Mail text before form answers")
.Configure(et => et.TextMode = TextBoxMode.MultiLine);
}
}
}
} | using System.Web.UI.WebControls;
using Dinamico.Controllers;
using Dinamico.Models;
using N2.Definitions.Runtime;
using N2.Web.Mvc;
namespace Dinamico.Registrations
{
[Registration]
public class FreeFormRegistration : FluentRegisterer<FreeForm>
{
public override void RegisterDefinition(IContentRegistration<FreeForm> register)
{
register.Part(title: "Free form", description: "A form that can be sumitted and sent to an email address or viewed online.");
register.ControlledBy<FreeFormController>();
register.Definition.SortOrder = 250;
register.Icon("{IconsUrl}/report.png");
register.On(ff => ff.Form).FreeText("Form (with tokens)").Configure(eft =>
{
eft.HelpTitle = "This text supports tokens";
eft.HelpText = "{{FormCheckbox}}, {{FormFile}}, {{FormCheckbox}}, {{FormInput}}, {{FormRadio}}, {{FormSelect}}, {{FormSubmit}}, {{FormTextarea}}";
}).WithTokens();
register.On(ff => ff.SubmitText).FreeText("Thank you text");
using (register.FieldSetContainer("Email", "Email").Begin())
{
register.On(ff => ff.MailFrom).Text("Mail from").Placeholder("[email protected]");
register.On(ff => ff.MailTo).Text("Mail to").Placeholder("[email protected]");
register.On(ff => ff.MailSubject).Text("Mail subject").Placeholder("Mail title");
register.On(ff => ff.MailBody).Text("Mail intro text").Placeholder("Mail text before form answers")
.Configure(et => et.TextMode = TextBoxMode.MultiLine);
}
}
}
} | lgpl-2.1 | C# |
aae5b836eafb67d41b49950c3f0e6d01e282d124 | Update Student-Data.cs | DeanCabral/Code-Snippets | Console/Student-Data.cs | Console/Student-Data.cs | class StudentData
{
static void Main(string[] args)
{
GetUserInput();
}
static void GetUserInput()
{
int studentNumber;
string studentName;
string scoredMarks;
Console.Write("Input Student Number: ");
studentNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("Input Student Name: ");
studentName = Console.ReadLine();
Console.Write("Input Maths, English and Science marks: ");
scoredMarks = Console.ReadLine();
GenerateStudentOutput(studentNumber, studentName, scoredMarks);
GetUserInput();
}
static void GenerateStudentOutput(int number, string name, string marks)
{
string[] subjectMarks = marks.Split(' ');
int mathMark = Convert.ToInt32(subjectMarks[0]);
int englishMark = Convert.ToInt32(subjectMarks[1]);
int scienceMark = Convert.ToInt32(subjectMarks[2]);
int total = mathMark + englishMark + scienceMark;
float percentage = total / subjectMarks.Length;
string division = GetDivision(percentage);
Console.WriteLine("Student Number: " + number);
Console.WriteLine("Student Name: " + name);
Console.WriteLine("Maths: " + mathMark);
Console.WriteLine("English: " + englishMark);
Console.WriteLine("Science: " + scienceMark);
Console.WriteLine("Total Marks: " + total);
Console.WriteLine("Percentage: " + percentage.ToString("N2") + "%");
Console.WriteLine("Division: " + division);
Console.WriteLine();
}
static string GetDivision(float percentage)
{
string output = "";
if (percentage >= 70) output = "First Class";
else if (percentage >= 60) output = "Upper-Second Class";
else if (percentage >= 50) output = "Lower-Second Class";
else if (percentage >= 40) output = "Third Class";
else output = "N/A";
return output;
}
}
| class StudentData
{
static void Main(string[] args)
{
GetUserInput();
}
static void GetUserInput()
{
int studentNumber;
string studentName;
string scoredMarks;
Console.Write("Input Student Number: ");
studentNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("Input Student Name: ");
studentName = Console.ReadLine();
Console.Write("Input Maths, English and Science marks: ");
scoredMarks = Console.ReadLine();
GenerateStudentOutput(studentNumber, studentName, scoredMarks);
GetUserInput();
}
static void GenerateStudentOutput(int number, string name, string marks)
{
string[] subjectMarks = marks.Split(' ');
int mathMark = Convert.ToInt32(subjectMarks[0]);
int englishMark = Convert.ToInt32(subjectMarks[1]);
int scienceMark = Convert.ToInt32(subjectMarks[2]);
int total = mathMark + englishMark + scienceMark;
float percentage = total / subjectMarks.Length;
string division = GetDivision(percentage);
Console.WriteLine("Student Number: " + number);
Console.WriteLine("Student Name: " + name);
Console.WriteLine("Maths: " + mathMark);
Console.WriteLine("English: " + englishMark);
Console.WriteLine("Science: " + scienceMark);
Console.WriteLine("Total Marks: " + total);
Console.WriteLine("Percentage: " + percentage.ToString("N2") + "%");
Console.WriteLine("Division: " + division);
Console.WriteLine();
}
static string GetDivision(float percentage)
{
string output = "";
if (percentage >= 70) output = "First Class";
else if (percentage >= 60) output = "Upper-Second Class";
else if (percentage >= 50) output = "Lower-Second Class";
else if (percentage >= 40) output = "Third Class";
else output = "N/A";
return output;
}
}
| mit | C# |
02c28a6e25e42fddda95c2e469e3f3d3b78002c7 | Make the UI fps configurable via a query string argument | ronenmiz/appflinger-mediaroom,ronenmiz/appflinger-mediaroom | AppFlinger.net/Default.aspx.cs | AppFlinger.net/Default.aspx.cs | using System;
using System.Web;
using System.Net;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.TV.TVControls;
using Microsoft.TV.TVControls.Actions;
using Microsoft.TV.TVControls.Collections;
namespace AppFlinger
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int? fps = null;
// Mandatory query string arguments
if (Request.QueryString["host"] == null || Request.QueryString["session_id"] == null)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
Response.SuppressContent = true;
Response.StatusDescription = "Missing query string argument(s) -- host and/or session_id";
return;
}
// Optional query string arguments
if (Request.QueryString["fps"] != null)
{
try
{
fps = int.Parse(Request.QueryString["fps"].ToString());
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
Response.SuppressContent = true;
Response.StatusDescription = "Invalid value of query string argument -- fps";
return;
}
}
string host = Request.QueryString["host"].ToString();
string sessionId = Request.QueryString["session_id"].ToString();
// Set the image URL to be the AppFlinger session snapshot URL (JPEG)
TVImage img = (TVImage) this.Page.FindControl("TVImage1");
img.Url = string.Format("http://{0}/osb/session/snapshot?session_id={1}", host, HttpUtility.UrlEncode(sessionId));
// Set the image refresh frequency
if (fps != null && fps > 0 && fps <= 10)
{
TVActions actions = (TVActions)this.Page.FindControl("TVActions1");
CompositeAction doRefreshImgAction = (CompositeAction)actions.Actions["doRefreshImg"];
TimeoutAction timeoutAction = (TimeoutAction)doRefreshImgAction.InnerActions["timeout"];
timeoutAction.Delay = 1000/fps;
}
// Start the control channel
Global.AppFlingerStart(host, sessionId);
}
}
}
| using System;
using System.Web;
using System.Net;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.TV.TVControls;
using Microsoft.TV.TVControls.Events;
namespace AppFlinger
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["host"] == null || Request.QueryString["session_id"] == null)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
Response.SuppressContent = true;
Response.StatusDescription = "Missing query string argument(s) -- host and/or session_id";
return;
}
string host = Request.QueryString["host"].ToString();
string sessionId = Request.QueryString["session_id"].ToString();
// Set the image URL to be the AppFlinger session snapshot URL (JPEG)
TVImage img = (TVImage) this.Page.FindControl("TVImage1");
img.Url = string.Format("http://{0}/osb/session/snapshot?session_id={1}", host, HttpUtility.UrlEncode(sessionId));
// Start the control channel
Global.AppFlingerStart(host, sessionId);
}
}
}
| agpl-3.0 | C# |
2f9ed212678e5207e6c96867a002acf3c7bf2008 | add support for no language in LiteralNode | Mathos1432/dotNetSPARQL | dotNetSPARQL/Nodes/LiteralNode.cs | dotNetSPARQL/Nodes/LiteralNode.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dotNetSPARQL.Nodes
{
public class LiteralNode : INode
{
private string _value;
private string _language;
public LiteralNode(string value, string language = "")
{
_value = value;
_language = language;
}
public override string ToString()
{
return "\"" + _value + "\"" + (string.IsNullOrWhiteSpace(_language) ? "" : "@" + _language);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dotNetSPARQL.Nodes
{
public class LiteralNode : INode
{
private string _value;
private string _language;
public LiteralNode(string value, string language)
{
_value = value;
_language = language;
}
public override string ToString()
{
return "\"" + _value + "\"@" + _language;
}
}
}
| mit | C# |
a23f8baf25f006956fc66bdcbc9515644450abd4 | Fix EOI emails are not sent | croquet-australia/api.croquet-australia.com.au | source/CroquetAustralia.WebApi/Controllers/TournamentEntryController.cs | source/CroquetAustralia.WebApi/Controllers/TournamentEntryController.cs | using System;
using System.Threading.Tasks;
using System.Web.Http;
using CroquetAustralia.Domain.Features.TournamentEntry;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
using CroquetAustralia.Domain.Features.TournamentEntry.Events;
using CroquetAustralia.Domain.Services.Queues;
namespace CroquetAustralia.WebApi.Controllers
{
[RoutePrefix("tournament-entry")]
public class TournamentEntryController : ApiController
{
private readonly IEventsQueue _eventsQueue;
public TournamentEntryController(IEventsQueue eventsQueue)
{
_eventsQueue = eventsQueue;
}
[HttpPost]
[Route("add-entry")]
public async Task AddEntryAsync(SubmitEntry command)
{
// todo: allow javascript to send null
if (command.PaymentMethod.HasValue && (int)command.PaymentMethod.Value == -1)
{
command.PaymentMethod = null;
}
var entrySubmitted = command.ToEntrySubmitted();
await _eventsQueue.AddMessageAsync(entrySubmitted);
}
[HttpPost]
[Route("payment-received")]
public async Task PaymentReceivedAsync(ReceivePayment command)
{
// todo: extension method command.MapTo<EntrySubmitted>
var @event = new PaymentReceived(command.EntityId, command.PaymentMethod);
await _eventsQueue.AddMessageAsync(@event);
}
}
} | using System.Threading.Tasks;
using System.Web.Http;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
using CroquetAustralia.Domain.Features.TournamentEntry.Events;
using CroquetAustralia.Domain.Services.Queues;
namespace CroquetAustralia.WebApi.Controllers
{
[RoutePrefix("tournament-entry")]
public class TournamentEntryController : ApiController
{
private readonly IEventsQueue _eventsQueue;
public TournamentEntryController(IEventsQueue eventsQueue)
{
_eventsQueue = eventsQueue;
}
[HttpPost]
[Route("add-entry")]
public async Task AddEntryAsync(SubmitEntry command)
{
var entrySubmitted = command.ToEntrySubmitted();
await _eventsQueue.AddMessageAsync(entrySubmitted);
}
[HttpPost]
[Route("payment-received")]
public async Task PaymentReceivedAsync(ReceivePayment command)
{
// todo: extension method command.MapTo<EntrySubmitted>
var @event = new PaymentReceived(command.EntityId, command.PaymentMethod);
await _eventsQueue.AddMessageAsync(@event);
}
}
} | mit | C# |
d53351b063a2c639f72368705d11938aa7610326 | Disable read timeout for now | HelloKitty/Booma.Proxy | src/Booma.Proxy.Client/Decorators/NetworkClientPacketReaderDecorator.cs | src/Booma.Proxy.Client/Decorators/NetworkClientPacketReaderDecorator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
using System.Threading;
namespace Booma.Proxy
{
/// <summary>
/// Decorator that adds header reading functionality to the <see cref="NetworkClientBase"/>.
/// </summary>
public sealed class NetworkClientPacketReaderDecorator : NetworkClientBase, IPacketHeaderReadable
{
/// <summary>
/// The decorated <see cref="NetworkClientBase"/>.
/// </summary>
private NetworkClientBase DecoratedClient { get; }
/// <summary>
/// The serialization service.
/// </summary>
private ISerializerService Serializer { get; }
/// <summary>
/// Thread specific buffer used to deserialize the packet header bytes into.
/// </summary>
private ThreadLocal<byte[]> PacketHeaderBuffer { get; }
/// <summary>
/// </summary>
/// <param name="decoratedClient">The client to decorate.</param>
public NetworkClientPacketReaderDecorator(NetworkClientBase decoratedClient)
{
if(decoratedClient == null) throw new ArgumentNullException(nameof(decoratedClient));
PacketHeaderBuffer = new ThreadLocal<byte[]>(() => new byte[2]);
DecoratedClient = decoratedClient;
}
/// <inheritdoc />
public override async Task<bool> ConnectAsync(IPAddress address, int port)
{
return await DecoratedClient.ConnectAsync(address, port);
}
/// <inheritdoc />
public override async Task DisconnectAsync(int delay)
{
await DecoratedClient.DisconnectAsync(delay);
}
/// <inheritdoc />
public override async Task WriteAsync(byte[] bytes)
{
await DecoratedClient.WriteAsync(bytes);
}
/// <inheritdoc />
public override async Task<byte[]> ReadAsync(byte[] buffer, int start, int count, int timeoutInMilliseconds)
{
return await DecoratedClient.ReadAsync(buffer, start, count, timeoutInMilliseconds);
}
/// <inheritdoc />
public IPacketHeader ReadHeader()
{
return ReadHeaderAsync().Result;
}
/// <inheritdoc />
public async Task<IPacketHeader> ReadHeaderAsync()
{
//The header we know is two bytes.
//If we had access to the stream we could wrap it in a reader and use it
//without knowing the size. Since we don't have access we must manually read
await ReadAsync(PacketHeaderBuffer.Value, 0, 2, 0); //TODO: How long should the timeout be if any?
return Serializer.Deserialize<PSOBBPacketHeader>(PacketHeaderBuffer.Value);
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
PacketHeaderBuffer.Dispose();
base.Dispose(disposing);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
using System.Threading;
namespace Booma.Proxy
{
/// <summary>
/// Decorator that adds header reading functionality to the <see cref="NetworkClientBase"/>.
/// </summary>
public sealed class NetworkClientPacketReaderDecorator : NetworkClientBase, IPacketHeaderReadable
{
/// <summary>
/// The decorated <see cref="NetworkClientBase"/>.
/// </summary>
private NetworkClientBase DecoratedClient { get; }
/// <summary>
/// The serialization service.
/// </summary>
private ISerializerService Serializer { get; }
/// <summary>
/// Thread specific buffer used to deserialize the packet header bytes into.
/// </summary>
private ThreadLocal<byte[]> PacketHeaderBuffer { get; }
/// <summary>
/// </summary>
/// <param name="decoratedClient">The client to decorate.</param>
public NetworkClientPacketReaderDecorator(NetworkClientBase decoratedClient)
{
if(decoratedClient == null) throw new ArgumentNullException(nameof(decoratedClient));
PacketHeaderBuffer = new ThreadLocal<byte[]>(() => new byte[2]);
DecoratedClient = decoratedClient;
}
/// <inheritdoc />
public override async Task<bool> ConnectAsync(IPAddress address, int port)
{
return await DecoratedClient.ConnectAsync(address, port);
}
/// <inheritdoc />
public override async Task DisconnectAsync(int delay)
{
await DecoratedClient.DisconnectAsync(delay);
}
/// <inheritdoc />
public override async Task WriteAsync(byte[] bytes)
{
await DecoratedClient.WriteAsync(bytes);
}
/// <inheritdoc />
public override async Task<byte[]> ReadAsync(byte[] buffer, int start, int count, int timeoutInMilliseconds)
{
return await DecoratedClient.ReadAsync(buffer, start, count, timeoutInMilliseconds);
}
/// <inheritdoc />
public IPacketHeader ReadHeader()
{
return ReadHeaderAsync().Result;
}
/// <inheritdoc />
public async Task<IPacketHeader> ReadHeaderAsync()
{
//The header we know is two bytes.
//If we had access to the stream we could wrap it in a reader and use it
//without knowing the size. Since we don't have access we must manually read
await ReadAsync(PacketHeaderBuffer.Value, 0, 2, 100);
return Serializer.Deserialize<PSOBBPacketHeader>(PacketHeaderBuffer.Value);
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
PacketHeaderBuffer.Dispose();
base.Dispose(disposing);
}
}
}
| agpl-3.0 | C# |
89a84cd00f065d882f5f4d13e4b04b6fa927c234 | Update form name in validation of decision activity | omidnasri/Orchard,Serlead/Orchard,AdvantageCS/Orchard,fassetar/Orchard,hbulzy/Orchard,gcsuk/Orchard,hbulzy/Orchard,bedegaming-aleksej/Orchard,yersans/Orchard,omidnasri/Orchard,yersans/Orchard,aaronamm/Orchard,Fogolan/OrchardForWork,jimasp/Orchard,hannan-azam/Orchard,Fogolan/OrchardForWork,hbulzy/Orchard,jtkech/Orchard,bedegaming-aleksej/Orchard,OrchardCMS/Orchard,IDeliverable/Orchard,yersans/Orchard,AdvantageCS/Orchard,IDeliverable/Orchard,omidnasri/Orchard,OrchardCMS/Orchard,fassetar/Orchard,Dolphinsimon/Orchard,omidnasri/Orchard,aaronamm/Orchard,ehe888/Orchard,hannan-azam/Orchard,IDeliverable/Orchard,Serlead/Orchard,rtpHarry/Orchard,fassetar/Orchard,jersiovic/Orchard,jtkech/Orchard,hannan-azam/Orchard,rtpHarry/Orchard,omidnasri/Orchard,gcsuk/Orchard,Dolphinsimon/Orchard,bedegaming-aleksej/Orchard,AdvantageCS/Orchard,LaserSrl/Orchard,aaronamm/Orchard,AdvantageCS/Orchard,omidnasri/Orchard,AdvantageCS/Orchard,Serlead/Orchard,jtkech/Orchard,Praggie/Orchard,Dolphinsimon/Orchard,IDeliverable/Orchard,jimasp/Orchard,omidnasri/Orchard,OrchardCMS/Orchard,Fogolan/OrchardForWork,Praggie/Orchard,Lombiq/Orchard,Lombiq/Orchard,Fogolan/OrchardForWork,ehe888/Orchard,LaserSrl/Orchard,hannan-azam/Orchard,ehe888/Orchard,jersiovic/Orchard,hbulzy/Orchard,rtpHarry/Orchard,Lombiq/Orchard,omidnasri/Orchard,aaronamm/Orchard,jimasp/Orchard,bedegaming-aleksej/Orchard,Praggie/Orchard,Lombiq/Orchard,fassetar/Orchard,jtkech/Orchard,hbulzy/Orchard,jimasp/Orchard,Serlead/Orchard,IDeliverable/Orchard,jersiovic/Orchard,jersiovic/Orchard,gcsuk/Orchard,Fogolan/OrchardForWork,Dolphinsimon/Orchard,yersans/Orchard,Praggie/Orchard,LaserSrl/Orchard,Serlead/Orchard,rtpHarry/Orchard,LaserSrl/Orchard,ehe888/Orchard,aaronamm/Orchard,yersans/Orchard,OrchardCMS/Orchard,LaserSrl/Orchard,fassetar/Orchard,Dolphinsimon/Orchard,hannan-azam/Orchard,jtkech/Orchard,jimasp/Orchard,Lombiq/Orchard,bedegaming-aleksej/Orchard,rtpHarry/Orchard,OrchardCMS/Orchard,omidnasri/Orchard,gcsuk/Orchard,ehe888/Orchard,Praggie/Orchard,jersiovic/Orchard,gcsuk/Orchard | src/Orchard.Web/Modules/Orchard.Scripting.CSharp/Forms/DecisionForms.cs | src/Orchard.Web/Modules/Orchard.Scripting.CSharp/Forms/DecisionForms.cs | using System;
using Orchard.DisplayManagement;
using Orchard.Forms.Services;
using Orchard.Localization;
namespace Orchard.Scripting.CSharp.Forms {
public class DecisionForms : IFormProvider {
protected dynamic Shape { get; set; }
public Localizer T { get; set; }
public DecisionForms(IShapeFactory shapeFactory) {
Shape = shapeFactory;
T = NullLocalizer.Instance;
}
public void Describe(DescribeContext context) {
Func<IShapeFactory, dynamic> form =
shape => Shape.Form(
Id: "ActionDecision",
_Message: Shape.Textbox(
Id: "outcomes", Name: "Outcomes",
Title: T("Possible Outcomes."),
Description: T("A comma-separated list of possible outcomes."),
Classes: new[] { "text medium" }),
_Script: Shape.TextArea(
Id: "Script", Name: "Script",
Title: T("Script"),
Description: T("The script to run every time the Decision Activity is invoked. You can use ContentItem, Services, WorkContext, Workflow and T(). Call SetOutcome(string outcome) to define the outcome of the activity."),
Classes: new[] { "tokenized" }
)
);
context.Form("ActivityActionDecision", form);
}
}
public class DecisionFormsValidator : IFormEventHandler {
public Localizer T { get; set; }
public void Building(BuildingContext context) {
}
public void Built(BuildingContext context) {
}
public void Validating(ValidatingContext context) {
if (context.FormName == "ActivityActionDecision") {
if (context.ValueProvider.GetValue("Script").AttemptedValue == string.Empty) {
context.ModelState.AddModelError("Script", T("You must provide a Script").Text);
}
}
}
public void Validated(ValidatingContext context) {
}
}
}
| using System;
using Orchard.DisplayManagement;
using Orchard.Forms.Services;
using Orchard.Localization;
namespace Orchard.Scripting.CSharp.Forms {
public class DecisionForms : IFormProvider {
protected dynamic Shape { get; set; }
public Localizer T { get; set; }
public DecisionForms(IShapeFactory shapeFactory) {
Shape = shapeFactory;
T = NullLocalizer.Instance;
}
public void Describe(DescribeContext context) {
Func<IShapeFactory, dynamic> form =
shape => Shape.Form(
Id: "ActionDecision",
_Message: Shape.Textbox(
Id: "outcomes", Name: "Outcomes",
Title: T("Possible Outcomes."),
Description: T("A comma-separated list of possible outcomes."),
Classes: new[] { "text medium" }),
_Script: Shape.TextArea(
Id: "Script", Name: "Script",
Title: T("Script"),
Description: T("The script to run every time the Decision Activity is invoked. You can use ContentItem, Services, WorkContext, Workflow and T(). Call SetOutcome(string outcome) to define the outcome of the activity."),
Classes: new[] { "tokenized" }
)
);
context.Form("ActivityActionDecision", form);
}
}
public class DecisionFormsValidator : IFormEventHandler {
public Localizer T { get; set; }
public void Building(BuildingContext context) {
}
public void Built(BuildingContext context) {
}
public void Validating(ValidatingContext context) {
if (context.FormName == "ActionDecision") {
if (context.ValueProvider.GetValue("Script").AttemptedValue == string.Empty) {
context.ModelState.AddModelError("Script", T("You must provide a Script").Text);
}
}
}
public void Validated(ValidatingContext context) {
}
}
} | bsd-3-clause | C# |
e8522a5e66aaf8f794c20f222dd626b459fcc74f | add timeout param | justcoding121/Algorithm-Sandbox,justcoding121/Advanced-Algorithms | Advanced.Algorithms/Distributed/AsyncQueue.cs | Advanced.Algorithms/Distributed/AsyncQueue.cs | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Advanced.Algorithms.Distributed
{
/// <summary>
/// A simple asynchronous multi-thread supporting producer/consumer FIFO queue with minimal locking.
/// </summary>
public class AsyncQueue<T>
{
//data queue.
private readonly Queue<T> queue = new Queue<T>();
//consumer task queue and lock.
private readonly Queue<TaskCompletionSource<T>> consumerQueue = new Queue<TaskCompletionSource<T>>();
private SemaphoreSlim consumerQueueLock = new SemaphoreSlim(1);
public int Count => queue.Count;
/// <summary>
/// Supports multi-threaded producers.
/// Time complexity: O(1).
/// </summary>
public async Task EnqueueAsync(T value, int millisecondsTimeout = int.MaxValue, CancellationToken taskCancellationToken = default(CancellationToken))
{
await consumerQueueLock.WaitAsync(millisecondsTimeout, taskCancellationToken);
if(consumerQueue.Count > 0)
{
var consumer = consumerQueue.Dequeue();
consumer.TrySetResult(value);
}
else
{
queue.Enqueue(value);
}
consumerQueueLock.Release();
}
/// <summary>
/// Supports multi-threaded consumers.
/// Time complexity: O(1).
/// </summary>
public async Task<T> DequeueAsync(int millisecondsTimeout = int.MaxValue, CancellationToken taskCancellationToken = default(CancellationToken))
{
await consumerQueueLock.WaitAsync(millisecondsTimeout, taskCancellationToken);
TaskCompletionSource<T> consumer;
try
{
if (queue.Count > 0)
{
var result = queue.Dequeue();
consumerQueueLock.Release();
return result;
}
consumer = new TaskCompletionSource<T>();
taskCancellationToken.Register(() => consumer.TrySetCanceled());
consumerQueue.Enqueue(consumer);
}
finally
{
consumerQueueLock.Release();
}
return await consumer.Task;
}
}
}
| using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Advanced.Algorithms.Distributed
{
/// <summary>
/// A simple asynchronous multi-thread supporting producer/consumer FIFO queue with minimal locking.
/// </summary>
public class AsyncQueue<T>
{
//data queue.
private readonly Queue<T> queue = new Queue<T>();
//consumer task queue and lock.
private readonly Queue<TaskCompletionSource<T>> consumerQueue = new Queue<TaskCompletionSource<T>>();
private SemaphoreSlim consumerQueueLock = new SemaphoreSlim(1);
/// <summary>
/// Supports multi-threaded producers.
/// Time complexity: O(1).
/// </summary>
public async Task EnqueueAsync(T value, CancellationToken taskCancellationToken = default(CancellationToken))
{
await consumerQueueLock.WaitAsync(taskCancellationToken);
if(consumerQueue.Count > 0)
{
var consumer = consumerQueue.Dequeue();
consumer.SetResult(value);
}
else
{
queue.Enqueue(value);
}
consumerQueueLock.Release();
}
/// <summary>
/// Supports multi-threaded consumers.
/// Time complexity: O(1).
/// </summary>
public async Task<T> DequeueAsync(CancellationToken taskCancellationToken = default(CancellationToken))
{
await consumerQueueLock.WaitAsync(taskCancellationToken);
if (queue.Count > 0)
{
var result = queue.Dequeue();
consumerQueueLock.Release();
return result;
}
var consumer = new TaskCompletionSource<T>();
taskCancellationToken.Register(() => consumer.TrySetCanceled());
consumerQueue.Enqueue(consumer);
consumerQueueLock.Release();
return await consumer.Task;
}
}
}
| mit | C# |
9a5ea511517d8adecf1b779fc88bf5806eafa77d | Update the version number in the CommonUtil AssemblyInfo. | blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon | Compiler/CommonUtil/Properties/AssemblyInfo.cs | Compiler/CommonUtil/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CommonUtil")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CommonUtil")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8e422564-56ee-407c-aef7-b85f895ed320")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.1")]
[assembly: AssemblyFileVersion("2.1.1")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CommonUtil")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CommonUtil")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8e422564-56ee-407c-aef7-b85f895ed320")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
9733593f3eba2c700fc83312c5829a3b256779b1 | Add a root state type | grantcolley/dipstate | DevelopmentInProgress.DipState/DipStateType.cs | DevelopmentInProgress.DipState/DipStateType.cs | using System.Xml.Serialization;
namespace DevelopmentInProgress.DipState
{
public enum DipStateType
{
[XmlEnum("1")]
Standard = 1,
[XmlEnum("2")]
Auto = 2,
[XmlEnum("3")]
Root = 3
}
} | using System.Xml.Serialization;
namespace DevelopmentInProgress.DipState
{
public enum DipStateType
{
[XmlEnum("1")]
Standard = 1,
[XmlEnum("2")]
Auto = 3
}
} | apache-2.0 | C# |
c564ee836838febebb33b50d4ed2f7a5f123397d | Update Class1.cs | wroclawZETO/DokumentyPacjenci | DokumentyPacjenci/DokumentyPacjenci/Class1.cs | DokumentyPacjenci/DokumentyPacjenci/Class1.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DokumentyPacjenci
{
public class Class1
{
void a() { }
int b = 5;
int a = 10;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DokumentyPacjenci
{
public class Class1
{
void a() { }
int b = 5;
}
}
| mit | C# |
08ebe7b55b3e0b60ceed0f3f25084b43d0f1e2af | Fix broken tests getting items from the valid root | pveller/Sitecore.FakeDb,sergeyshushlyapin/Sitecore.FakeDb | test/Sitecore.FakeDb.Serialization.Tests/Deserialize/DeserializeTree.cs | test/Sitecore.FakeDb.Serialization.Tests/Deserialize/DeserializeTree.cs | namespace Sitecore.FakeDb.Serialization.Tests.Deserialize
{
using System.Linq;
using Xunit;
[Trait("Deserialize", "Deserializing a tree of items")]
public class DeserializeTree : DeserializeTestBase
{
public DeserializeTree()
{
this.Db.Add(new DsDbItem(SerializationId.SampleTemplateFolder, true)
{
ParentID = TemplateIDs.TemplateFolder
});
}
[Fact(DisplayName = "Deserializes templates in tree")]
public void DeserializesTemplates()
{
Assert.NotNull(this.Db.Database.GetTemplate(SerializationId.SampleItemTemplate));
}
[Fact(DisplayName = "Deserializes items in tree")]
public void DeserializesItems()
{
var nonTemplateItemCount =
this.Db.Database.GetItem(ItemIDs.TemplateRoot)
.Axes.GetDescendants()
.Count(x =>
x.TemplateID != TemplateIDs.Template &&
x.TemplateID != TemplateIDs.TemplateSection &&
x.TemplateID != TemplateIDs.TemplateField);
Assert.Equal(5, nonTemplateItemCount);
}
}
} | namespace Sitecore.FakeDb.Serialization.Tests.Deserialize
{
using System.Linq;
using Xunit;
[Trait("Deserialize", "Deserializing a tree of items")]
public class DeserializeTree : DeserializeTestBase
{
public DeserializeTree()
{
this.Db.Add(new DsDbItem(SerializationId.SampleTemplateFolder, true)
{
ParentID = TemplateIDs.TemplateFolder
});
}
[Fact(DisplayName = "Deserializes templates in tree")]
public void DeserializesTemplates()
{
Assert.NotNull(this.Db.Database.GetTemplate(SerializationId.SampleItemTemplate));
}
[Fact(DisplayName = "Deserializes items in tree")]
public void DeserializesItems()
{
var nonTemplateItemCount =
this.Db.Database.GetItem(TemplateIDs.TemplateFolder)
.Axes.GetDescendants()
.Count(x =>
x.TemplateID != TemplateIDs.Template &&
x.TemplateID != TemplateIDs.TemplateSection &&
x.TemplateID != TemplateIDs.TemplateField);
Assert.Equal(5, nonTemplateItemCount);
}
}
} | mit | C# |
cba26dccfde78f109977a51d2ad38d8c4b65cd1f | Improve example program | emailclue/emailclue-dotnet | EmailClueConsoleApp/Program.cs | EmailClueConsoleApp/Program.cs | using EmailClue;
using System;
namespace EmailClueConsoleApp
{
class Program
{
static void Main(string[] args)
{
var token = "PUBLIC_TEST_TOKEN";
IEmailClue emailClue = new EmailClue.EmailClue(token);
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
Console.Read();
}
private static void ValidateToConsole(IEmailClue emailClue, string email)
{
Console.WriteLine();
Console.WriteLine("Sending Request...");
var result = emailClue.ValidateEmailAsync(email).Result;
Console.WriteLine();
Console.WriteLine("Results For '{0}'", email);
Console.WriteLine();
Console.WriteLine(result);
Console.WriteLine();
writeLineToConsole();
}
private static void writeLineToConsole()
{
Console.BackgroundColor = ConsoleColor.Gray;
Console.WriteLine(" ");
Console.ResetColor();
}
}
}
| using EmailClue;
using System;
namespace EmailClueConsoleApp
{
class Program
{
static void Main(string[] args)
{
var token = "PUBLIC_TEST_TOKEN";
IEmailClue emailClue = new EmailClue.EmailClue(token);
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
ValidateToConsole(emailClue, "[email protected]");
Console.Read();
}
private static void ValidateToConsole(IEmailClue emailClue, string email)
{
Console.WriteLine();
Console.WriteLine("Sending Request...");
var result = emailClue.ValidateEmailAsync(email).Result;
Console.WriteLine();
Console.WriteLine("Results For '{0}'", email);
Console.WriteLine();
Console.WriteLine(result);
Console.WriteLine();
writeLineToConsole();
}
private static void writeLineToConsole()
{
Console.BackgroundColor = ConsoleColor.Gray;
Console.WriteLine(" ");
Console.ResetColor();
}
}
}
| mit | C# |
bb7592b22693eb749274631acbd496a8dfc84edb | Fix error page. | Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex | backend/src/Squidex/Areas/IdentityServer/Startup.cs | backend/src/Squidex/Areas/IdentityServer/Startup.cs | // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Squidex.Areas.IdentityServer.Config;
using Squidex.Web;
namespace Squidex.Areas.IdentityServer
{
public static class Startup
{
public static void ConfigureIdentityServer(this IApplicationBuilder app)
{
var environment = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
app.Map(Constants.IdentityServerPrefix, identityApp =>
{
if (environment.IsDevelopment())
{
identityApp.UseDeveloperExceptionPage();
}
else
{
identityApp.UseExceptionHandler("/error");
}
identityApp.UseRouting();
identityApp.UseAuthentication();
identityApp.UseAuthorization();
identityApp.UseSquidexIdentityServer();
identityApp.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
});
}
}
}
| // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Squidex.Areas.IdentityServer.Config;
using Squidex.Web;
namespace Squidex.Areas.IdentityServer
{
public static class Startup
{
public static void ConfigureIdentityServer(this IApplicationBuilder app)
{
var environment = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
app.Map(Constants.IdentityServerPrefix, identityApp =>
{
if (!environment.IsDevelopment())
{
identityApp.UseDeveloperExceptionPage();
}
else
{
identityApp.UseExceptionHandler("/error");
}
identityApp.UseRouting();
identityApp.UseAuthentication();
identityApp.UseAuthorization();
identityApp.UseSquidexIdentityServer();
identityApp.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
});
}
}
}
| mit | C# |
934bcaf82e8851415a44656151f30a1c9eb5ed7f | Adjust tests | ppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu | osu.Game.Rulesets.Taiko.Tests/TaikoDifficultyCalculatorTest.cs | osu.Game.Rulesets.Taiko.Tests/TaikoDifficultyCalculatorTest.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Taiko.Difficulty;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Taiko.Tests
{
public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko";
[TestCase(1.9971301024093662d, 200, "diffcalc-test")]
[TestCase(1.9971301024093662d, 200, "diffcalc-test-strong")]
public void Test(double expectedStarRating, int expectedMaxCombo, string name)
=> base.Test(expectedStarRating, expectedMaxCombo, name);
[TestCase(3.1645810961313674d, 200, "diffcalc-test")]
[TestCase(3.1645810961313674d, 200, "diffcalc-test-strong")]
public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name)
=> Test(expectedStarRating, expectedMaxCombo, name, new TaikoModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset().RulesetInfo, beatmap);
protected override Ruleset CreateRuleset() => new TaikoRuleset();
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Taiko.Difficulty;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Taiko.Tests
{
public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko";
[TestCase(2.2420075288523802d, 200, "diffcalc-test")]
[TestCase(2.2420075288523802d, 200, "diffcalc-test-strong")]
public void Test(double expectedStarRating, int expectedMaxCombo, string name)
=> base.Test(expectedStarRating, expectedMaxCombo, name);
[TestCase(3.134084469440479d, 200, "diffcalc-test")]
[TestCase(3.134084469440479d, 200, "diffcalc-test-strong")]
public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name)
=> Test(expectedStarRating, expectedMaxCombo, name, new TaikoModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset().RulesetInfo, beatmap);
protected override Ruleset CreateRuleset() => new TaikoRuleset();
}
}
| mit | C# |
358e570f6ad6705d4efe23c2524d449bbc60ca75 | throw an exception if the expected command is missing | SexyFishHorse/IrcClient4Net | IrcClient4Net/Validators/ResponseValidator.cs | IrcClient4Net/Validators/ResponseValidator.cs | namespace SexyFishHorse.Irc.Client.Validators
{
using System;
using SexyFishHorse.Irc.Client.Models;
public class ResponseValidator : IResponseValidator
{
public void ValidateCommand(IrcMessage message, string expectedCommand)
{
if (string.IsNullOrWhiteSpace(expectedCommand))
{
throw new ArgumentException("Expected command is not set", "expectedCommand");
}
if (message == null)
{
throw new ResponseValidationException("Did not receive a response from the server.");
}
if (message.Command == expectedCommand)
{
return;
}
var errorMessage =
string.Format(
"Expected the message from the server to have command code \"{0}\", received \"{1}\" instead",
expectedCommand,
message.Command);
throw new ResponseValidationException(errorMessage, expectedCommand, message);
}
}
}
| namespace SexyFishHorse.Irc.Client.Validators
{
using SexyFishHorse.Irc.Client.Models;
public class ResponseValidator : IResponseValidator
{
public void ValidateCommand(IrcMessage message, string expectedCommand)
{
if (message == null)
{
throw new ResponseValidationException("Did not receive a response from the server.");
}
if (message.Command == expectedCommand)
{
return;
}
var errorMessage =
string.Format(
"Expected the message from the server to have command code \"{0}\", received \"{1}\" instead",
expectedCommand,
message.Command);
throw new ResponseValidationException(errorMessage, expectedCommand, message);
}
}
}
| mit | C# |
1de94ab92c1dd04f9366236e65190b60f77bcb35 | build fails with latest VS (17.1) due to inconsistent nullability annotations | GeertvanHorrik/Fody,Fody/Fody | FodyHelpers/TryFindTypeFunc.cs | FodyHelpers/TryFindTypeFunc.cs | using System;
using Mono.Cecil;
namespace Fody
{
[Obsolete("No longer required as BaseModuleWeaver.TryFindType has been replace with BaseModuleWeaver.TryFindTypeDefinition", false)]
public delegate bool TryFindTypeFunc(string typeName, out TypeDefinition? type);
} | using System;
using System.Diagnostics.CodeAnalysis;
using Mono.Cecil;
namespace Fody
{
[Obsolete("No longer required as BaseModuleWeaver.TryFindType has been replace with BaseModuleWeaver.TryFindTypeDefinition", false)]
public delegate bool TryFindTypeFunc(string typeName, [NotNullWhen(true)] out TypeDefinition? type);
} | mit | C# |
a1f5ea2b7992f28174bb575e17e5a5cac962435e | change Buffer to store the length independent of the array | acple/ParsecSharp | ParsecSharp/Data/Internal/Buffer.cs | ParsecSharp/Data/Internal/Buffer.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ParsecSharp.Internal
{
public sealed class Buffer<TToken> : IReadOnlyList<TToken>
{
private readonly TToken[] _buffer;
private readonly Lazy<Buffer<TToken>> _next;
public TToken this[int index] => this._buffer[index];
public int Count { get; }
public Buffer<TToken> Next => this._next.Value;
public Buffer(TToken[] buffer, Func<Buffer<TToken>> next) : this(buffer, buffer.Length, next)
{ }
public Buffer(TToken[] buffer, int length, Func<Buffer<TToken>> next)
{
this._buffer = buffer;
this.Count = length;
this._next = new Lazy<Buffer<TToken>>(next, false);
}
public IEnumerator<TToken> GetEnumerator()
=> this._buffer.AsEnumerable().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> this._buffer.GetEnumerator();
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ParsecSharp.Internal
{
public sealed class Buffer<TToken> : IReadOnlyList<TToken>
{
private readonly TToken[] _buffer;
private readonly Lazy<Buffer<TToken>> _next;
public TToken this[int index] => this._buffer[index];
public int Count => this._buffer.Length;
public Buffer<TToken> Next => this._next.Value;
public Buffer(TToken[] buffer, Func<Buffer<TToken>> next)
{
this._buffer = buffer;
this._next = new Lazy<Buffer<TToken>>(next, false);
}
public IEnumerator<TToken> GetEnumerator()
=> this._buffer.AsEnumerable().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> this._buffer.GetEnumerator();
}
}
| mit | C# |
782542ee386dfb9f5e6bd71f0875e37af0cd55ba | Update TypeMatchFilter.cs | Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core,json-api-dotnet/JsonApiDotNetCore | src/JsonApiDotNetCore/Middleware/TypeMatchFilter.cs | src/JsonApiDotNetCore/Middleware/TypeMatchFilter.cs | using System;
using System.Linq;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
namespace JsonApiDotNetCore.Middleware
{
public class TypeMatchFilter : IActionFilter
{
private readonly IJsonApiContext _jsonApiContext;
public TypeMatchFilter(IJsonApiContext jsonApiContext)
{
_jsonApiContext = jsonApiContext;
}
/// <summary>
/// Used to verify the incoming type matches the target type, else return a 409
/// </summary>
public void OnActionExecuting(ActionExecutingContext context)
{
var request = context.HttpContext.Request;
if (IsJsonApiRequest(request) && (request.Method == "PATCH" || request.Method == "POST"))
{
var deserializedType = context.ActionArguments.FirstOrDefault().Value?.GetType();
var targetType = context.ActionDescriptor.Parameters.FirstOrDefault()?.ParameterType;
if (deserializedType != null && targetType != null && deserializedType != targetType)
{
var expectedJsonApiResource = _jsonApiContext.ResourceGraph.GetContextEntity(targetType);
throw new JsonApiException(409,
$"Cannot '{context.HttpContext.Request.Method}' type '{_jsonApiContext.RequestEntity.EntityName}' "
+ $"to '{expectedJsonApiResource?.EntityName}' endpoint.",
detail: "Check that the request payload type matches the type expected by this endpoint.");
}
}
}
private bool IsJsonApiRequest(HttpRequest request)
{
return (request.ContentType?.Equals(Constants.ContentType, StringComparison.OrdinalIgnoreCase) == true);
}
public void OnActionExecuted(ActionExecutedContext context) { /* noop */ }
}
}
| using System;
using System.Linq;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
namespace JsonApiDotNetCore.Middleware
{
public class TypeMatchFilter : IActionFilter
{
private readonly IJsonApiContext _jsonApiContext;
public TypeMatchFilter(IJsonApiContext jsonApiContext)
{
_jsonApiContext = jsonApiContext;
}
/// <summary>
/// Used to verify the incoming type matches the target type, else return a 409
/// </summary>
public void OnActionExecuting(ActionExecutingContext context)
{
var request = context.HttpContext.Request;
if (IsJsonApiRequest(request) && request.Method == "PATCH" || request.Method == "POST")
{
var deserializedType = context.ActionArguments.FirstOrDefault().Value?.GetType();
var targetType = context.ActionDescriptor.Parameters.FirstOrDefault()?.ParameterType;
if (deserializedType != null && targetType != null && deserializedType != targetType)
{
var expectedJsonApiResource = _jsonApiContext.ResourceGraph.GetContextEntity(targetType);
throw new JsonApiException(409,
$"Cannot '{context.HttpContext.Request.Method}' type '{_jsonApiContext.RequestEntity.EntityName}' "
+ $"to '{expectedJsonApiResource?.EntityName}' endpoint.",
detail: "Check that the request payload type matches the type expected by this endpoint.");
}
}
}
private bool IsJsonApiRequest(HttpRequest request)
{
return (request.ContentType?.Equals(Constants.ContentType, StringComparison.OrdinalIgnoreCase) == true);
}
public void OnActionExecuted(ActionExecutedContext context) { /* noop */ }
}
}
| mit | C# |
b00136447aaba7cb32cd13546c0b23d178e96ae5 | Add no-op BindMethod | neuecc/MagicOnion | src/MagicOnion.Server/Glue/MagicOnionGlueService.cs | src/MagicOnion.Server/Glue/MagicOnionGlueService.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using Grpc.Core;
namespace MagicOnion.Server.Glue
{
internal class MagicOnionGlueService
{
public static Type CreateType()
{
var dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
var dynamicModule = dynamicAssembly.DefineDynamicModule("DynamicModule");
var typeBuilder = dynamicModule.DefineType("MagicOnionGlue");
var type = typeBuilder.CreateType()!;
return typeof(MagicOnionGlueService<>).MakeGenericType(type);
}
public static void BindMethod(ServiceBinderBase binder, MagicOnionGlueService service)
{
// no-op at here.
// The MagicOnion service methods are bound by `MagicOnionGlueServiceMethodProvider<TService>`
}
}
[BindServiceMethod(typeof(MagicOnionGlueService), nameof(BindMethod))]
internal class MagicOnionGlueService<TService> : MagicOnionGlueService
where TService : class
{
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
namespace MagicOnion.Server.Glue
{
internal static class MagicOnionGlueService
{
public static Type CreateType()
{
var dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
var dynamicModule = dynamicAssembly.DefineDynamicModule("DynamicModule");
var typeBuilder = dynamicModule.DefineType("MagicOnionGlue");
var type = typeBuilder.CreateType()!;
return typeof(MagicOnionGlueService<>).MakeGenericType(type);
}
}
internal class MagicOnionGlueService<TService>
where TService : class
{
}
}
| mit | C# |
1c853a5f501506d98b51a6fd5189cdfa60e8fa56 | Change the plugin library load path | tparviainen/oscilloscope | PluginLoader.Tests/Plugins_Tests.cs | PluginLoader.Tests/Plugins_Tests.cs | using PluginContracts;
using System;
using System.Collections.Generic;
using Xunit;
namespace PluginLoader.Tests
{
public class Plugins_Tests
{
[Fact]
public void PluginsFoundFromLibsFolder()
{
// Arrange
var path = @"..\..\..\..\Libs";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.NotEmpty(plugins);
}
[Fact]
public void PluginsNotFoundFromCurrentFolder()
{
// Arrange
var path = @".";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.Empty(plugins);
}
}
}
| using PluginContracts;
using System;
using System.Collections.Generic;
using Xunit;
namespace PluginLoader.Tests
{
public class Plugins_Tests
{
[Fact]
public void PluginsFoundFromLibsFolder()
{
// Arrange
var path = @"..\..\..\..\LAN\bin\Debug\netstandard1.3";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.NotEmpty(plugins);
}
[Fact]
public void PluginsNotFoundFromCurrentFolder()
{
// Arrange
var path = @".";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.Empty(plugins);
}
}
}
| mit | C# |
4c17070639bb3de6d907bca1f31aa1c5b400d47e | update design page link (#560) | reactiveui/website,reactiveui/website,reactiveui/website,reactiveui/website | input/contribute/design/index.cshtml | input/contribute/design/index.cshtml | Order: 100
---
<p>
See <a href="https://github.com/reactiveui/website/issues?q=is%3Aissue+is%3Aopen+label%3Adesign">design</a>
</p>
| Order: 100
---
See https://github.com/reactiveui/website/issues?q=is%3Aissue+is%3Aopen+label%3Adesign | mit | C# |
79aa2d0684f6f3d7d6f3efadac0bab6584143566 | Fix to OpenCV example. | mohtamohit/CppSharp,xistoso/CppSharp,Samana/CppSharp,nalkaro/CppSharp,mono/CppSharp,inordertotest/CppSharp,genuinelucifer/CppSharp,txdv/CppSharp,KonajuGames/CppSharp,KonajuGames/CppSharp,genuinelucifer/CppSharp,Samana/CppSharp,mydogisbox/CppSharp,inordertotest/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,inordertotest/CppSharp,u255436/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,Samana/CppSharp,mono/CppSharp,inordertotest/CppSharp,imazen/CppSharp,Samana/CppSharp,mono/CppSharp,ddobrev/CppSharp,KonajuGames/CppSharp,txdv/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,Samana/CppSharp,mohtamohit/CppSharp,SonyaSa/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,SonyaSa/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,mono/CppSharp,xistoso/CppSharp,SonyaSa/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,u255436/CppSharp,KonajuGames/CppSharp,SonyaSa/CppSharp,zillemarco/CppSharp,imazen/CppSharp,inordertotest/CppSharp,mydogisbox/CppSharp,mydogisbox/CppSharp,mohtamohit/CppSharp,xistoso/CppSharp,mydogisbox/CppSharp,mydogisbox/CppSharp,u255436/CppSharp,ddobrev/CppSharp,nalkaro/CppSharp,SonyaSa/CppSharp,nalkaro/CppSharp,txdv/CppSharp,zillemarco/CppSharp,imazen/CppSharp,xistoso/CppSharp,nalkaro/CppSharp,ktopouzi/CppSharp,nalkaro/CppSharp,zillemarco/CppSharp,txdv/CppSharp,xistoso/CppSharp,txdv/CppSharp,imazen/CppSharp,imazen/CppSharp | examples/OpenCV/OpenCV.cs | examples/OpenCV/OpenCV.cs | using CppSharp.Generators;
using CppSharp.Passes;
namespace CppSharp
{
class OpenCV : ILibrary
{
public void Setup(Driver driver)
{
var options = driver.Options;
options.LibraryName = "OpenCV";
options.Headers.Add("opencv2/core/core_c.h");
options.Headers.Add("opencv2/core/types_c.h");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/include/");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/core/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/flann/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/imgproc/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/photo/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/video/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/features2d/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/objdetect/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/calib3d/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/ml/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/highgui/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/contrib/include");
options.OutputDir = "opencv";
}
public void Preprocess(Driver driver, Library lib)
{
}
public void Postprocess(Library lib)
{
}
public void SetupPasses(Driver driver, PassBuilder p)
{
p.FunctionToInstanceMethod();
p.FunctionToStaticMethod();
}
public void GenerateStart(TextTemplate template)
{
}
public void GenerateAfterNamespaces(TextTemplate template)
{
}
static class Program
{
public static void Main(string[] args)
{
ConsoleDriver.Run(new OpenCV());
}
}
}
}
| using CppSharp.Generators;
using CppSharp.Passes;
namespace CppSharp
{
class OpenCV : ILibrary
{
public void Setup(DriverOptions options)
{
options.LibraryName = "OpenCV";
options.Headers.Add("opencv2/core/core_c.h");
options.Headers.Add("opencv2/core/types_c.h");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/include/");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/core/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/flann/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/imgproc/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/photo/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/video/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/features2d/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/objdetect/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/calib3d/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/ml/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/highgui/include");
options.IncludeDirs.Add("../../../examples/OpenCV/opencv/modules/contrib/include");
options.OutputDir = "opencv";
}
public void Preprocess(Driver driver, Library lib)
{
}
public void Postprocess(Library lib)
{
}
public void SetupPasses(Driver driver, PassBuilder p)
{
p.FunctionToInstanceMethod();
p.FunctionToStaticMethod();
}
public void GenerateStart(TextTemplate template)
{
}
public void GenerateAfterNamespaces(TextTemplate template)
{
}
static class Program
{
public static void Main(string[] args)
{
Driver.Run(new OpenCV());
}
}
}
}
| mit | C# |
b55d16d87e3fa8da66871d50f6a4d7ce62f5cb28 | Repair path actions delegate | awaescher/RepoZ,awaescher/RepoZ | RepoZ.Api.Win/IO/WindowsPathActionProvider.cs | RepoZ.Api.Win/IO/WindowsPathActionProvider.cs | using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RepoZ.Api.IO;
using GongSolutions.Shell;
using System.Drawing;
namespace RepoZ.Api.Win.IO
{
public class WindowsPathActionProvider : IPathActionProvider
{
public IEnumerable<PathAction> GetFor(string path)
{
yield return createDefaultPathAction("Open in Windows File Explorer", path);
yield return createPathAction("Open in Windows Command Prompt (cmd.exe)", "cmd.exe", $"/K \"cd /d {path}\"");
yield return createPathAction("Open in Windows PowerShell", "powershell.exe ", $"-noexit -command \"cd '{path}'\"");
string bashSubpath = @"Git\git-bash.exe";
string folder = Environment.ExpandEnvironmentVariables("%ProgramW6432%");
string gitbash = Path.Combine(folder, bashSubpath);
if (!File.Exists(gitbash))
{
folder = Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%");
gitbash = Path.Combine(folder, bashSubpath);
}
if (File.Exists(gitbash))
{
if (path.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
path = path.Substring(0, path.Length - 1);
yield return createPathAction("Open in Git Bash", gitbash, $"\"--cd={path}\"");
}
yield return new PathAction()
{
Name = "Shell",
Action = (sender, args) =>
{
var coords = args as float[];
var i = new ShellItem(path);
var m = new ShellContextMenu(i);
m.ShowContextMenu(new System.Windows.Forms.Button(), new Point((int)coords[0], (int)coords[1]));
},
BeginGroup = true
};
}
private PathAction createPathAction(string name, string process, string arguments = "")
{
return new PathAction()
{
Name = name,
Action = (sender, args) => startProcess(process, arguments)
};
}
private PathAction createDefaultPathAction(string name, string process, string arguments = "")
{
var action = createPathAction(name, process, arguments);
action.IsDefault = true;
return action;
}
private void startProcess(string process, string arguments)
{
Process.Start(process, arguments);
}
}
}
| using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RepoZ.Api.IO;
using GongSolutions.Shell;
using System.Drawing;
namespace RepoZ.Api.Win.IO
{
public class WindowsPathActionProvider : IPathActionProvider
{
public IEnumerable<PathAction> GetFor(string path)
{
yield return createDefaultPathAction("Open in Windows File Explorer", path);
yield return createPathAction("Open in Windows Command Prompt (cmd.exe)", "cmd.exe", $"/K \"cd /d {path}\"");
yield return createPathAction("Open in Windows PowerShell", "powershell.exe ", $"-noexit -command \"cd '{path}'\"");
string bashSubpath = @"Git\git-bash.exe";
string folder = Environment.ExpandEnvironmentVariables("%ProgramW6432%");
string gitbash = Path.Combine(folder, bashSubpath);
if (!File.Exists(gitbash))
{
folder = Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%");
gitbash = Path.Combine(folder, bashSubpath);
}
if (File.Exists(gitbash))
{
if (path.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
path = path.Substring(0, path.Length - 1);
yield return createPathAction("Open in Git Bash", gitbash, $"\"--cd={path}\"");
}
yield return new PathAction()
{
Name = "Shell",
Action = (sender, args) =>
{
var coords = args as float[];
var i = new ShellItem(path);
var m = new ShellContextMenu(i);
m.ShowContextMenu(new System.Windows.Forms.Button(), new Point((int)coords[0], (int)coords[1]));
},
BeginGroup = true
};
}
private PathAction createPathAction(string name, string process, string arguments = "")
{
return new PathAction()
{
Name = name,
Action = (sender, args) => startProcess(process, arguments)
};
}
private PathAction createDefaultPathAction(string name, string process, string arguments = "")
{
var action = createPathAction(name, process, arguments);
action.IsDefault = true;
return action;
}
private Action startProcess(string process, string arguments)
{
return () => Process.Start(process, arguments);
}
}
}
| mit | C# |
ae47eb61caf9ef810cd0d2d56f12164d78f45c05 | Fix test not working when not logged in | ppy/osu,naoey/osu,smoogipoo/osu,DrabWeb/osu,2yangk23/osu,2yangk23/osu,UselessToucan/osu,ZLima12/osu,UselessToucan/osu,DrabWeb/osu,peppy/osu,ZLima12/osu,ppy/osu,peppy/osu,naoey/osu,NeoAdonis/osu,johnneijzen/osu,EVAST9919/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,DrabWeb/osu,NeoAdonis/osu,naoey/osu,johnneijzen/osu,NeoAdonis/osu | osu.Game.Tests/Visual/TestCaseUpdateableBeatmapBackgroundSprite.cs | osu.Game.Tests/Visual/TestCaseUpdateableBeatmapBackgroundSprite.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Rulesets;
using osu.Game.Tests.Beatmaps.IO;
namespace osu.Game.Tests.Visual
{
public class TestCaseUpdateableBeatmapBackgroundSprite : OsuTestCase
{
private UpdateableBeatmapBackgroundSprite backgroundSprite;
[Resolved]
private BeatmapManager beatmaps { get; set; }
[BackgroundDependencyLoader]
private void load(OsuGameBase osu, APIAccess api, RulesetStore rulesets)
{
Bindable<BeatmapInfo> beatmapBindable = new Bindable<BeatmapInfo>();
var imported = ImportBeatmapTest.LoadOszIntoOsu(osu);
Child = backgroundSprite = new UpdateableBeatmapBackgroundSprite { RelativeSizeAxes = Axes.Both };
backgroundSprite.Beatmap.BindTo(beatmapBindable);
var req = new GetBeatmapSetRequest(1);
api.Queue(req);
AddStep("null", () => beatmapBindable.Value = null);
AddStep("imported", () => beatmapBindable.Value = imported.Beatmaps.First());
if (api.IsLoggedIn)
{
AddUntilStep(() => req.Result != null, "wait for api response");
AddStep("online", () => beatmapBindable.Value = new BeatmapInfo
{
BeatmapSet = req.Result?.ToBeatmapSet(rulesets)
});
}
else
{
AddStep("online (login first)", () => { });
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Rulesets;
using osu.Game.Tests.Beatmaps.IO;
namespace osu.Game.Tests.Visual
{
public class TestCaseUpdateableBeatmapBackgroundSprite : OsuTestCase
{
private UpdateableBeatmapBackgroundSprite backgroundSprite;
[Resolved]
private BeatmapManager beatmaps { get; set; }
[BackgroundDependencyLoader]
private void load(OsuGameBase osu, APIAccess api, RulesetStore rulesets)
{
Bindable<BeatmapInfo> beatmapBindable = new Bindable<BeatmapInfo>();
var imported = ImportBeatmapTest.LoadOszIntoOsu(osu);
Child = backgroundSprite = new UpdateableBeatmapBackgroundSprite { RelativeSizeAxes = Axes.Both };
backgroundSprite.Beatmap.BindTo(beatmapBindable);
var req = new GetBeatmapSetRequest(1);
api.Queue(req);
AddStep("null", () => beatmapBindable.Value = null);
AddStep("imported", () => beatmapBindable.Value = imported.Beatmaps.First());
if (api.IsLoggedIn)
AddUntilStep(() => req.Result != null, "wait for api response");
AddStep("online", () => beatmapBindable.Value = new BeatmapInfo
{
BeatmapSet = req.Result?.ToBeatmapSet(rulesets)
});
}
}
}
| mit | C# |
589578d1f403ff8df19078470edfc161536a6876 | Remove trailing slash from base URL | uhaciogullari/SimpleMvcSitemap,FeodorFitsner/SimpleMvcSitemap | SimpleMvcSitemap/BaseUrlProvider.cs | SimpleMvcSitemap/BaseUrlProvider.cs | using System.Web;
using System.Web.Mvc;
namespace SimpleMvcSitemap
{
class BaseUrlProvider : IBaseUrlProvider
{
public string GetBaseUrl(HttpContextBase httpContext)
{
//http://stackoverflow.com/a/1288383/205859
HttpRequestBase request = httpContext.Request;
return string.Format("{0}://{1}{2}", request.Url.Scheme,
request.Url.Authority,
UrlHelper.GenerateContentUrl("~", httpContext))
.TrimEnd('/');
}
}
} | using System.Web;
using System.Web.Mvc;
namespace SimpleMvcSitemap
{
class BaseUrlProvider : IBaseUrlProvider
{
public string GetBaseUrl(HttpContextBase httpContext)
{
//http://stackoverflow.com/a/1288383/205859
HttpRequestBase request = httpContext.Request;
return string.Format("{0}://{1}{2}", request.Url.Scheme,
request.Url.Authority,
UrlHelper.GenerateContentUrl("~", httpContext));
}
}
} | mit | C# |
84bf9bfe05ac92e4726ebadd9af06cf12d746526 | implement figureIdRepository | PedDavid/qip,PedDavid/qip,PedDavid/qip | Server/API.Repositories/FigureIdRepository.cs | Server/API.Repositories/FigureIdRepository.cs | using API.Interfaces.IRepositories;
using System;
using System.Collections.Generic;
using System.Text;
namespace API.Repositories
{
public class FigureIdRepository : IFigureIdRepository {
private readonly SqlServerTemplate _queryTemplate;
public FigureIdRepository(SqlServerTemplate queryTemplate) {
_queryTemplate = queryTemplate;
}
public long GetMaxId() {
return _queryTemplate.QueryForScalar<long>(SELECT_MAX_ID);
}
private static readonly string SELECT_MAX_ID = "SELECT max(id) FROM dbo.Figure";
}
}
| using API.Interfaces.IRepositories;
using System;
using System.Collections.Generic;
using System.Text;
namespace API.Repositories
{
public class FigureIdRepository : IFigureIdRepository {
public long GetMaxId() {
return 0;//TODO
}
}
}
| mit | C# |
aa60605eaec4e95e22d2ae8baf6bcb66005348e5 | Update ICosmosTableRepositoryInitializer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Data/CosmosTable/ICosmosTableRepositoryInitializer.cs | TIKSN.Core/Data/CosmosTable/ICosmosTableRepositoryInitializer.cs | using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Table;
namespace TIKSN.Data.CosmosTable
{
public interface ICosmosTableRepositoryInitializer<T> where T : ITableEntity
{
Task InitializeAsync(CancellationToken cancellationToken);
}
}
| using Microsoft.Azure.Cosmos.Table;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.CosmosTable
{
public interface ICosmosTableRepositoryInitializer<T> where T : ITableEntity
{
Task InitializeAsync(CancellationToken cancellationToken);
}
} | mit | C# |
bce3cbf00a97b8817e34e6bcb9f3937549aecaaf | Update MemoryCachedCurrencyConverterOptions.cs | tiksn/TIKSN-Framework | TIKSN.Core/Finance/Cache/MemoryCachedCurrencyConverterOptions.cs | TIKSN.Core/Finance/Cache/MemoryCachedCurrencyConverterOptions.cs | using System;
namespace TIKSN.Finance.Cache
{
public class MemoryCachedCurrencyConverterOptions
{
public TimeSpan CacheInterval { get; set; }
}
}
| using System;
namespace TIKSN.Finance.Cache
{
public class MemoryCachedCurrencyConverterOptions
{
public TimeSpan CacheInterval { get; set; }
}
} | mit | C# |
205366c377d853d68db35db44c4740980067028d | add StartNotify to SharedData | NaamloosDT/ModCore,NaamloosDT/ModCore | ModCore/Entities/SharedData.cs | ModCore/Entities/SharedData.cs | using ModCore.Api;
using System;
using System.Threading;
namespace ModCore.Entities
{
public class SharedData
{
public CancellationTokenSource CTS { get; internal set; }
public DateTime ProcessStartTime { get; internal set; }
public SemaphoreSlim TimerSempahore { get; internal set; }
public TimerData TimerData { get; internal set; }
public Perspective Perspective { get; internal set; }
public (ulong guild, ulong channel) StartNotify { get; internal set; }
public SharedData()
{
this.TimerSempahore = new SemaphoreSlim(1, 1);
}
}
}
| using ModCore.Api;
using System;
using System.Threading;
namespace ModCore.Entities
{
public class SharedData
{
public CancellationTokenSource CTS { get; private set; }
public DateTime ProcessStartTime { get; private set; }
public SemaphoreSlim TimerSempahore { get; private set; }
public TimerData TimerData { get; set; }
public Perspective Perspective { get; private set; }
public SharedData(CancellationTokenSource cts, DateTime processStartTime, Perspective psp)
{
this.CTS = cts;
this.ProcessStartTime = processStartTime;
this.TimerSempahore = new SemaphoreSlim(1, 1);
this.Perspective = psp;
}
}
}
| mit | C# |
5b09f012ad5bb16ea5c57a3355899008836e49fe | Package Update #CHANGE: Pushed AdamsLair.WinForms 1.1.5 | AdamsLair/winforms | WinForms/Properties/AssemblyInfo.cs | WinForms/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("AdamsLair.WinForms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdamsLair.WinForms")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.5")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("AdamsLair.WinForms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdamsLair.WinForms")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.4")]
| mit | C# |
887b7b565ccbfb0e45da5524ea5a54a83c49ec50 | remove DocumentName | wvdd007/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,ErikSchierboom/roslyn,tmat/roslyn,eriawan/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,genlu/roslyn,eriawan/roslyn,brettfo/roslyn,physhi/roslyn,diryboy/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,aelij/roslyn,KevinRansom/roslyn,wvdd007/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,reaction1989/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,reaction1989/roslyn,davkean/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,stephentoub/roslyn,aelij/roslyn,wvdd007/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,dotnet/roslyn,AlekseyTs/roslyn,tmat/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,weltkante/roslyn,physhi/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,mavasani/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,jmarolf/roslyn,physhi/roslyn,ErikSchierboom/roslyn,tmat/roslyn,brettfo/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,sharwell/roslyn,weltkante/roslyn,gafter/roslyn,AmadeusW/roslyn,sharwell/roslyn,dotnet/roslyn,gafter/roslyn,jmarolf/roslyn,bartdesmet/roslyn,weltkante/roslyn,dotnet/roslyn,KevinRansom/roslyn,aelij/roslyn,genlu/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,mavasani/roslyn,brettfo/roslyn,KirillOsenkov/roslyn,davkean/roslyn,heejaechang/roslyn,genlu/roslyn,AmadeusW/roslyn | src/Features/Core/Portable/FindUsages/ExternalReferenceItem.cs | src/Features/Core/Portable/FindUsages/ExternalReferenceItem.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.
namespace Microsoft.CodeAnalysis.FindUsages
{
/// <summary>
/// Information about a symbol's reference that can be used for display and navigation in an
/// editor. These generally reference items outside of the Roslyn <see cref="Solution"/> model
/// provided by external sources (for example: RichNav).
/// </summary>
internal abstract class ExternalReferenceItem
{
/// <summary>
/// The definition this reference corresponds to.
/// </summary>
public DefinitionItem Definition { get; }
public ExternalReferenceItem(
DefinitionItem definition,
string documentName,
object text,
string displayPath)
{
Definition = definition;
DocumentName = documentName;
Text = text;
DisplayPath = displayPath;
}
public string ProjectName { get; }
/// <remarks>
/// Must be of type Microsoft.VisualStudio.Text.Adornments.ImageElement or
/// Microsoft.VisualStudio.Text.Adornments.ContainerElement or
/// Microsoft.VisualStudio.Text.Adornments.ClassifiedTextElement or System.String
/// </remarks>
public object Text { get; }
public string DisplayPath { get; }
public abstract bool TryNavigateTo(Workspace workspace, bool isPreview);
}
}
| // 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.
namespace Microsoft.CodeAnalysis.FindUsages
{
/// <summary>
/// Information about a symbol's reference that can be used for display and navigation in an
/// editor. These generally reference items outside of the Roslyn <see cref="Solution"/> model
/// provided by external sources (for example: RichNav).
/// </summary>
internal abstract class ExternalReferenceItem
{
/// <summary>
/// The definition this reference corresponds to.
/// </summary>
public DefinitionItem Definition { get; }
public ExternalReferenceItem(
DefinitionItem definition,
string documentName,
string projectName,
object text,
string displayPath)
{
Definition = definition;
DocumentName = documentName;
ProjectName = projectName;
Text = text;
DisplayPath = displayPath;
}
public string DocumentName { get; }
public string ProjectName { get; }
/// <remarks>
/// Must be of type Microsoft.VisualStudio.Text.Adornments.ImageElement or
/// Microsoft.VisualStudio.Text.Adornments.ContainerElement or
/// Microsoft.VisualStudio.Text.Adornments.ClassifiedTextElement or System.String
/// </remarks>
public object Text { get; }
public string DisplayPath { get; }
public abstract bool TryNavigateTo(Workspace workspace, bool isPreview);
}
}
| mit | C# |
fab27872680798aee3398e0414c332b8a04178e0 | Add String ExtensionMethod | Nanabell/NoAdsHere | NoAdsHere/Common/Extentions.cs | NoAdsHere/Common/Extentions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using NoAdsHere.Database.Models.GuildSettings;
namespace NoAdsHere.Common
{
public static class Extentions
{
public static string RemoveWhitespace(this string input)
{
return new string(input
.Where(c => !char.IsWhiteSpace(c))
.ToArray());
}
public static bool CheckChannelPermission(this IMessageChannel channel, ChannelPermission permission, IGuildUser guildUser)
{
var guildchannel = channel as IGuildChannel;
ChannelPermissions perms;
perms = guildchannel != null ? guildUser.GetPermissions(guildchannel) : ChannelPermissions.All(null);
return perms.Has(permission);
}
public static IEnumerable<Ignore> GetIgnoreType(this IEnumerable<Ignore> ignores, IgnoreType type)
=> ignores.Where(i => i.IgnoreType == type || i.IgnoreType == IgnoreType.All);
public static async Task<IEnumerable<CommandInfo>> CheckConditionsAsync(this IEnumerable<CommandInfo> commandInfos,
ICommandContext context, IServiceProvider map = null)
{
var ret = new List<CommandInfo>();
foreach (var commandInfo in commandInfos)
{
if (!(await commandInfo.CheckPreconditionsAsync(context, map)).IsSuccess) continue;
ret.Add(commandInfo);
}
return ret;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using NoAdsHere.Database.Models.GuildSettings;
namespace NoAdsHere.Common
{
public static class Extentions
{
public static bool CheckChannelPermission(this IMessageChannel channel, ChannelPermission permission, IGuildUser guildUser)
{
var guildchannel = channel as IGuildChannel;
ChannelPermissions perms;
perms = guildchannel != null ? guildUser.GetPermissions(guildchannel) : ChannelPermissions.All(null);
return perms.Has(permission);
}
public static IEnumerable<Ignore> GetIgnoreType(this IEnumerable<Ignore> ignores, IgnoreType type)
=> ignores.Where(i => i.IgnoreType == type || i.IgnoreType == IgnoreType.All);
public static async Task<IEnumerable<CommandInfo>> CheckConditionsAsync(this IEnumerable<CommandInfo> commandInfos,
ICommandContext context, IServiceProvider map = null)
{
var ret = new List<CommandInfo>();
foreach (var commandInfo in commandInfos)
{
if (!(await commandInfo.CheckPreconditionsAsync(context, map)).IsSuccess) continue;
ret.Add(commandInfo);
}
return ret;
}
}
} | mit | C# |
600946c58b558a72015b56655026af365037902a | clarify comment in Interop.NETStandard.cs | ravimeda/cli,harshjain2/cli,svick/cli,Faizan2304/cli,dasMulli/cli,livarcocc/cli-1,harshjain2/cli,harshjain2/cli,Faizan2304/cli,livarcocc/cli-1,johnbeisner/cli,johnbeisner/cli,svick/cli,livarcocc/cli-1,Faizan2304/cli,ravimeda/cli,johnbeisner/cli,ravimeda/cli,dasMulli/cli,dasMulli/cli,svick/cli | src/Microsoft.DotNet.MSBuildSdkResolver/Interop.NETStandard.cs | src/Microsoft.DotNet.MSBuildSdkResolver/Interop.NETStandard.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// NOTE: the NET46 build ships with Visual Studio/desktop msbuild on Windows.
// The netstandard1.5 adaptation here acts a proof-of-concept for cross-platform
// portability of the underlying hostfxr API and gives us build and test coverage
// on non-Windows machines. It also ships with msbuild on Mono.
#if NETSTANDARD1_5
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Microsoft.DotNet.MSBuildSdkResolver
{
internal static partial class Interop
{
internal static readonly bool RunningOnWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
internal static string realpath(string path)
{
var ptr = unix_realpath(path, IntPtr.Zero);
var result = Marshal.PtrToStringAnsi(ptr); // uses UTF8 on Unix
unix_free(ptr);
return result;
}
private static int hostfxr_resolve_sdk(string exe_dir, string working_dir, [Out] StringBuilder buffer, int buffer_size)
{
// hostfxr string encoding is platform -specific so dispatch to the
// appropriately annotated P/Invoke for the current platform.
return RunningOnWindows
? windows_hostfxr_resolve_sdk(exe_dir, working_dir, buffer, buffer_size)
: unix_hostfxr_resolve_sdk(exe_dir, working_dir, buffer, buffer_size);
}
[DllImport("hostfxr", EntryPoint = nameof(hostfxr_resolve_sdk), CharSet = CharSet.Unicode, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
private static extern int windows_hostfxr_resolve_sdk(string exe_dir, string working_dir, [Out] StringBuilder buffer, int buffer_size);
// CharSet.Ansi is UTF8 on Unix
[DllImport("hostfxr", EntryPoint = nameof(hostfxr_resolve_sdk), CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern int unix_hostfxr_resolve_sdk(string exe_dir, string working_dir, [Out] StringBuilder buffer, int buffer_size);
// CharSet.Ansi is UTF8 on Unix
[DllImport("libc", EntryPoint = nameof(realpath), CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr unix_realpath(string path, IntPtr buffer);
[DllImport("libc", EntryPoint = "free", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern void unix_free(IntPtr ptr);
}
}
#endif // NETSTANDARD1_5 | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// NOTE: Currently, only the NET46 build ships (with Visual Studio/desktop msbuild),
// but the netstandard1.5 adaptation here acts a proof-of-concept for cross-platform
// portability of the underlying hostfxr API and gives us build and test coverage
// on non-Windows machines.
#if NETSTANDARD1_5
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Microsoft.DotNet.MSBuildSdkResolver
{
internal static partial class Interop
{
internal static readonly bool RunningOnWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
internal static string realpath(string path)
{
var ptr = unix_realpath(path, IntPtr.Zero);
var result = Marshal.PtrToStringAnsi(ptr); // uses UTF8 on Unix
unix_free(ptr);
return result;
}
private static int hostfxr_resolve_sdk(string exe_dir, string working_dir, [Out] StringBuilder buffer, int buffer_size)
{
// hostfxr string encoding is platform -specific so dispatch to the
// appropriately annotated P/Invoke for the current platform.
return RunningOnWindows
? windows_hostfxr_resolve_sdk(exe_dir, working_dir, buffer, buffer_size)
: unix_hostfxr_resolve_sdk(exe_dir, working_dir, buffer, buffer_size);
}
[DllImport("hostfxr", EntryPoint = nameof(hostfxr_resolve_sdk), CharSet = CharSet.Unicode, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
private static extern int windows_hostfxr_resolve_sdk(string exe_dir, string working_dir, [Out] StringBuilder buffer, int buffer_size);
// CharSet.Ansi is UTF8 on Unix
[DllImport("hostfxr", EntryPoint = nameof(hostfxr_resolve_sdk), CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern int unix_hostfxr_resolve_sdk(string exe_dir, string working_dir, [Out] StringBuilder buffer, int buffer_size);
// CharSet.Ansi is UTF8 on Unix
[DllImport("libc", EntryPoint = nameof(realpath), CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr unix_realpath(string path, IntPtr buffer);
[DllImport("libc", EntryPoint = "free", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern void unix_free(IntPtr ptr);
}
}
#endif // NETSTANDARD1_5 | mit | C# |
b2815afbd8071426b8ed21cfdee71b44dc1c220c | Test Fetcher.Login POSTs with correct values | detunized/lastpass-sharp,detunized/lastpass-sharp,rottenorange/lastpass-sharp | test/FetcherTest.cs | test/FetcherTest.cs | using System.Collections.Specialized;
using System.Linq;
using System.Text;
using Moq;
using NUnit.Framework;
namespace LastPass.Test
{
[TestFixture]
class FetcherTest
{
[Test]
public void Login()
{
const string url = "https://lastpass.com/login.php";
const string username = "username";
const string password = "password";
var expectedValues = new NameValueCollection
{
{"method", "mobile"},
{"web", "1"},
{"xml", "1"},
{"username", username},
{"hash", "e379d972c3eb59579abe3864d850b5f54911544adfa2daf9fb53c05d30cdc985"},
{"iterations", "1"}
};
var webClient = new Mock<IWebClient>();
webClient
.Setup(x => x.UploadValues(It.Is<string>(s => s == url),
It.Is<NameValueCollection>(v => AreEqual(v, expectedValues))))
.Returns(Encoding.UTF8.GetBytes(""))
.Verifiable();
new Fetcher(username, password).Login(webClient.Object);
webClient.Verify();
}
private static bool AreEqual(NameValueCollection a, NameValueCollection b)
{
return a.AllKeys.OrderBy(s => s).SequenceEqual(b.AllKeys.OrderBy(s => s)) &&
a.AllKeys.All(s => a[s] == b[s]);
}
}
}
| using System.Collections.Specialized;
using System.Text;
using Moq;
using NUnit.Framework;
namespace LastPass.Test
{
[TestFixture]
class FetcherTest
{
[Test]
public void Login()
{
var webClient = new Mock<IWebClient>();
webClient
.Setup(x => x.UploadValues(It.Is<string>(s => s == "https://lastpass.com/login.php"),
It.IsAny<NameValueCollection>()))
.Returns(Encoding.UTF8.GetBytes(""))
.Verifiable();
new Fetcher("username", "password").Login(webClient.Object);
webClient.Verify();
}
}
}
| mit | C# |
53bbaf61b91ab8ecd9a967f50274b10210d4beb0 | Add region and virtual | rapidcore/rapidcore,rapidcore/rapidcore | src/google-cloud/main/Datastore/Internal/DatastoreReflector.cs | src/google-cloud/main/Datastore/Internal/DatastoreReflector.cs | using System;
using System.Linq;
using System.Reflection;
using RapidCore.Reflection;
namespace RapidCore.GoogleCloud.Datastore.Internal
{
public class DatastoreReflector
{
#region Kind
public virtual string GetKind(object poco)
{
if (poco == null)
{
throw new ArgumentNullException(nameof(poco), "Cannot get kind from null");
}
var type = poco.GetType().GetTypeInfo();
if (type.HasAttribute(typeof(KindAttribute)))
{
var attr = type.GetSpecificAttribute(typeof(KindAttribute)).FirstOrDefault();
return ((KindAttribute) attr)?.Kind;
}
return poco.GetType().Name;
}
#endregion
}
} | using System;
using System.Linq;
using System.Reflection;
using RapidCore.Reflection;
namespace RapidCore.GoogleCloud.Datastore.Internal
{
public class DatastoreReflector
{
public string GetKind(object poco)
{
if (poco == null)
{
throw new ArgumentNullException(nameof(poco), "Cannot get kind from null");
}
var type = poco.GetType().GetTypeInfo();
if (type.HasAttribute(typeof(KindAttribute)))
{
var attr = type.GetSpecificAttribute(typeof(KindAttribute)).FirstOrDefault();
return ((KindAttribute) attr)?.Kind;
}
return poco.GetType().Name;
}
}
} | mit | C# |
a9231d9758eaf5fb5c8838168181e5a3f0a19fa8 | Update AssemblyInfo | link07/Interval-Click,link07/Interval-Click-Graphic,link07/Interval-Click,link07/Interval-Click-Graphic | SLN/Properties/AssemblyInfo.cs | SLN/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Divine Gift Opener")]
[assembly: AssemblyDescription("A program to click anywhere on a windows screen, repeating over a set amount of time; made for Archeage Divine Gifts")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Divine Gift Opener")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b525d131-03ba-4cae-9616-dc206a6ebc33")]
// 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("2.0.4.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Divine Gift Opener")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Divine Gift Opener")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b525d131-03ba-4cae-9616-dc206a6ebc33")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
03dc518f26d92fbe4d839f1f422c3654681c43df | Update example for new config file loading. | kubernetes-client/csharp,kubernetes-client/csharp | examples/simple/PodList.cs | examples/simple/PodList.cs | namespace simple
{
using System;
using System.IO;
using k8s;
class PodList
{
static void Main(string[] args)
{
var k8sClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(k8sClientConfig);
Console.WriteLine("Starting Request!");
var listTask = client.ListNamespacedPodWithHttpMessagesAsync("default").Result;
var list = listTask.Body;
foreach (var item in list.Items) {
Console.WriteLine(item.Metadata.Name);
}
if (list.Items.Count == 0) {
Console.WriteLine("Empty!");
}
}
}
}
| namespace simple
{
using System;
using System.IO;
using k8s;
class PodList
{
static void Main(string[] args)
{
var k8sClientConfig = new KubernetesClientConfiguration();
IKubernetes client = new Kubernetes(k8sClientConfig);
Console.WriteLine("Starting Request!");
var listTask = client.ListNamespacedPodWithHttpMessagesAsync("default").Result;
var list = listTask.Body;
foreach (var item in list.Items) {
Console.WriteLine(item.Metadata.Name);
}
if (list.Items.Count == 0) {
Console.WriteLine("Empty!");
}
}
}
}
| apache-2.0 | C# |
2e2e4198e4cd956eec233a2ccec15728d13a5ca2 | Fix variable capturing issue in text entry samples | iainx/xwt,cra0zy/xwt,mminns/xwt,hamekoz/xwt,directhex/xwt,TheBrainTech/xwt,hwthomas/xwt,akrisiun/xwt,residuum/xwt,mminns/xwt,lytico/xwt,antmicro/xwt,sevoku/xwt,mono/xwt,steffenWi/xwt | Samples/Samples/TextEntries.cs | Samples/Samples/TextEntries.cs | //
// TextEntries.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
namespace Samples
{
public class TextEntries: VBox
{
public TextEntries ()
{
TextEntry te1 = new TextEntry ();
PackStart (te1);
Label la = new Label ();
PackStart (la);
te1.Changed += delegate {
la.Text = "Text: " + te1.Text;
};
PackStart (new Label ("Entry with small font"));
TextEntry te2 = new TextEntry ();
te2.Font = te2.Font.WithSize (te2.Font.Size / 2);
PackStart (te2);
PackStart (new Label ("Entry with placeholder text"));
TextEntry te3 = new TextEntry ();
te3.PlaceholderText = "Placeholder text";
PackStart (te3);
PackStart (new Label ("Entry with no frame"));
TextEntry te4 = new TextEntry();
te4.ShowFrame = false;
PackStart (te4);
}
}
}
| //
// TextEntries.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
namespace Samples
{
public class TextEntries: VBox
{
public TextEntries ()
{
TextEntry te = new TextEntry ();
PackStart (te);
Label la = new Label ();
PackStart (la);
te.Changed += delegate {
la.Text = "Text: " + te.Text;
};
PackStart (new Label ("Entry with small font"));
te = new TextEntry ();
te.Font = te.Font.WithSize (te.Font.Size / 2);
PackStart (te);
PackStart (new Label ("Entry with placeholder text"));
te = new TextEntry ();
te.PlaceholderText = "Placeholder text";
PackStart (te);
PackStart (new Label ("Entry with no frame"));
te = new TextEntry();
te.ShowFrame = false;
PackStart (te);
}
}
}
| mit | C# |
e17b7eaa94c2ac42e0041cb71b46b4dd1e864dd3 | Add --timeline option | ixfalia/banshee,stsundermann/banshee,mono-soc-2011/banshee,Dynalon/banshee-osx,arfbtwn/banshee,Carbenium/banshee,Carbenium/banshee,Dynalon/banshee-osx,ixfalia/banshee,directhex/banshee-hacks,arfbtwn/banshee,dufoli/banshee,Carbenium/banshee,Carbenium/banshee,dufoli/banshee,allquixotic/banshee-gst-sharp-work,lamalex/Banshee,petejohanson/banshee,directhex/banshee-hacks,Dynalon/banshee-osx,stsundermann/banshee,arfbtwn/banshee,stsundermann/banshee,arfbtwn/banshee,ixfalia/banshee,GNOME/banshee,lamalex/Banshee,ixfalia/banshee,Carbenium/banshee,dufoli/banshee,dufoli/banshee,directhex/banshee-hacks,mono-soc-2011/banshee,lamalex/Banshee,mono-soc-2011/banshee,arfbtwn/banshee,Dynalon/banshee-osx,GNOME/banshee,Carbenium/banshee,lamalex/Banshee,directhex/banshee-hacks,arfbtwn/banshee,Dynalon/banshee-osx,babycaseny/banshee,babycaseny/banshee,Dynalon/banshee-osx,petejohanson/banshee,stsundermann/banshee,allquixotic/banshee-gst-sharp-work,ixfalia/banshee,ixfalia/banshee,stsundermann/banshee,allquixotic/banshee-gst-sharp-work,GNOME/banshee,dufoli/banshee,Dynalon/banshee-osx,GNOME/banshee,mono-soc-2011/banshee,dufoli/banshee,babycaseny/banshee,stsundermann/banshee,mono-soc-2011/banshee,babycaseny/banshee,GNOME/banshee,ixfalia/banshee,lamalex/Banshee,arfbtwn/banshee,stsundermann/banshee,petejohanson/banshee,dufoli/banshee,petejohanson/banshee,allquixotic/banshee-gst-sharp-work,directhex/banshee-hacks,GNOME/banshee,allquixotic/banshee-gst-sharp-work,mono-soc-2011/banshee,ixfalia/banshee,Dynalon/banshee-osx,petejohanson/banshee,mono-soc-2011/banshee,petejohanson/banshee,GNOME/banshee,GNOME/banshee,arfbtwn/banshee,directhex/banshee-hacks,lamalex/Banshee,dufoli/banshee,babycaseny/banshee,allquixotic/banshee-gst-sharp-work,stsundermann/banshee,babycaseny/banshee,babycaseny/banshee,babycaseny/banshee | extras/metrics/Main.cs | extras/metrics/Main.cs | //
// Main.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright (c) 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Hyena;
using Hyena.CommandLine;
namespace metrics
{
public class MainEntry
{
const string db_path = "metrics.db";
public static void Main (string [] args)
{
try {
using (var db = new Database (db_path)) {
if (args != null && args.Length > 0 && args[0] == "--timeline") {
var metric = db.GetMetric ("Banshee/StartedAt");
var usage_samples = new SampleModel (String.Format ("WHERE MetricId = {0}", metric.Id), db, "1");
usage_samples.Reload ();
for (long i = 0; i < usage_samples.Cache.Count; i++) {
var sample = usage_samples.Cache.GetValue (i);
Console.WriteLine (
"{1} {0} {2} {0} {3} {0} {4}",
"<TUFTE>", DateTimeUtil.FromDateTime (sample.Stamp), sample.UserId, sample.CacheEntryId, sample.CacheEntryId
);
}
return;
}
db.Import ();
new MetaMetrics (db);
}
} catch (Exception e) {
Console.WriteLine ("Going down, got exception {0}", e);
throw;
}
}
}
}
| //
// Main.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright (c) 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Hyena;
using Hyena.CommandLine;
namespace metrics
{
public class MainEntry
{
const string db_path = "metrics.db";
public static void Main (string [] args)
{
try {
using (var db = new Database (db_path)) {
db.Import ();
new MetaMetrics (db);
}
} catch (Exception e) {
Console.WriteLine ("Going down, got exception {0}", e);
throw;
}
}
}
} | mit | C# |
c9ba31b698cea91509da3c9882e217b6d5688e8a | Update GrahamBeer.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/GrahamBeer.cs | src/Firehose.Web/Authors/GrahamBeer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GrahamBeer : IAmACommunityMember
{
public string FirstName => "Graham";
public string LastName => "Beer";
public string ShortBioOrTagLine => "System Engineer";
public string StateOrRegion => "UK";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "Gbeer7";
public string GravatarHash => "27d2592f62f63479cac9314da41f9af1";
public string GitHubHandle => "Gbeer7";
public GeoPosition Position => new GeoPosition(47.643417, -122.126083);
public Uri WebSite => new Uri("https://graham-beer.github.io/#blog");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://graham-beer.github.io/feed.xml"); }
}
public string GitHubHandle => "Graham-Beer";
public bool Filter(SyndicationItem item)
{
return item.Categories.Where(i => i.Name.Equals("powershell", StringComparison.OrdinalIgnoreCase)).Any();
}
public GeoPosition Position => new GeoPosition(39.0913089, -77.5440391);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GrahamBeer : IAmACommunityMember
{
public string FirstName => "Graham";
public string LastName => "Beer";
public string ShortBioOrTagLine => "System Engineer";
public string StateOrRegion => "UK";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "Gbeer7";
public string GravatarHash => "27d2592f62f63479cac9314da41f9af1";
public string GitHubHandle => "Gbeer7";
public GeoPosition Position => new GeoPosition(47.643417, -122.126083);
public Uri WebSite => new Uri("https://graham-beer.github.io/#blog");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://graham-beer.github.io/feed.xml"); }
}
public string GitHubHandle => "Graham-Beer";
public GeoPosition Position => new GeoPosition(39.0913089, -77.5440391);
}
}
| mit | C# |
d375a86f735d2cad41611f3a9b40e04d5e8ad7c4 | Fix issue #29 - Added Select method to InputElement | nikhilk/scriptsharp,x335/scriptsharp,nikhilk/scriptsharp,nikhilk/scriptsharp,x335/scriptsharp,x335/scriptsharp | src/Libraries/Web/Html/InputElement.cs | src/Libraries/Web/Html/InputElement.cs | // InputElement.cs
// Script#/Libraries/Web
// Copyright (c) Nikhil Kothari.
// Copyright (c) Microsoft Corporation.
// This source code is subject to terms and conditions of the Microsoft
// Public License. A copy of the license can be found in License.txt.
//
using System;
using System.Runtime.CompilerServices;
namespace System.Html {
[IgnoreNamespace]
[Imported]
public class InputElement : Element {
protected internal InputElement() {
}
[IntrinsicProperty]
public FormElement Form {
get {
return null;
}
}
[IntrinsicProperty]
public string Name {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public string Type {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public string Value {
get {
return null;
}
set {
}
}
public void Select() {
}
}
}
| // InputElement.cs
// Script#/Libraries/Web
// Copyright (c) Nikhil Kothari.
// Copyright (c) Microsoft Corporation.
// This source code is subject to terms and conditions of the Microsoft
// Public License. A copy of the license can be found in License.txt.
//
using System;
using System.Runtime.CompilerServices;
namespace System.Html {
[IgnoreNamespace]
[Imported]
public class InputElement : Element {
protected internal InputElement() {
}
[IntrinsicProperty]
public FormElement Form {
get {
return null;
}
}
[IntrinsicProperty]
public string Name {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public string Type {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public string Value {
get {
return null;
}
set {
}
}
}
}
| apache-2.0 | C# |
cdcc805fe7a47d2bc051c3e16596233ba91ac66a | Update oauth completion URI | hartez/TodotxtTouch.WindowsPhone | TodotxtTouch.WindowsPhone/DropBoxLogin.xaml.cs | TodotxtTouch.WindowsPhone/DropBoxLogin.xaml.cs | using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using Microsoft.Phone.Controls;
using TodotxtTouch.WindowsPhone.Messages;
using TodotxtTouch.WindowsPhone.ViewModel;
namespace TodotxtTouch.WindowsPhone
{
public partial class DropboxLogin : PhoneApplicationPage
{
public DropboxLogin()
{
InitializeComponent();
Messenger.Default.Register<CredentialsUpdatedMessage>(this, msg =>
{
if(NavigationService.CanGoBack)
{
NavigationService.GoBack();
}
});
Messenger.Default.Register<RetrievedDropboxTokenMessage>(this, LoadLoginPage);
loginBrowser.LoadCompleted += LoadCompleted;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
((DropboxCredentialsViewModel)DataContext).StartLoginProcessCommand.Execute(null);
}
private void LoadLoginPage(RetrievedDropboxTokenMessage msg)
{
if(!string.IsNullOrEmpty(msg.Error))
{
DispatcherHelper.CheckBeginInvokeOnUI(() => MessageBox.Show(msg.Error));
}
else
{
loginBrowser.Navigate(msg.TokenUri);
}
}
private void LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
//Check for the callback path here (or just check it against "/1/oauth/authorize")
if (e.Uri.Host == "todotxt.codewise-llc.com")
{
Messenger.Default.Send(new DropboxLoginSuccessfulMessage());
}
}
}
} | using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using Microsoft.Phone.Controls;
using TodotxtTouch.WindowsPhone.Messages;
using TodotxtTouch.WindowsPhone.ViewModel;
namespace TodotxtTouch.WindowsPhone
{
public partial class DropboxLogin : PhoneApplicationPage
{
public DropboxLogin()
{
InitializeComponent();
Messenger.Default.Register<CredentialsUpdatedMessage>(this, msg =>
{
if(NavigationService.CanGoBack)
{
NavigationService.GoBack();
}
});
Messenger.Default.Register<RetrievedDropboxTokenMessage>(this, LoadLoginPage);
loginBrowser.LoadCompleted += LoadCompleted;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
((DropboxCredentialsViewModel)DataContext).StartLoginProcessCommand.Execute(null);
}
private void LoadLoginPage(RetrievedDropboxTokenMessage msg)
{
if(!string.IsNullOrEmpty(msg.Error))
{
DispatcherHelper.CheckBeginInvokeOnUI(() => MessageBox.Show(msg.Error));
}
else
{
loginBrowser.Navigate(msg.TokenUri);
}
}
private void LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
//Check for the callback path here (or just check it against "/1/oauth/authorize")
if (e.Uri.Host == "todotxt.traceur-llc.com")
{
Messenger.Default.Send(new DropboxLoginSuccessfulMessage());
}
}
}
} | mit | C# |
13e0a59f707e38144bdfc709121f220f1196b360 | Add note about why `LegacyManiaSkinConfigurationLookup` exist | peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu | osu.Game/Skinning/LegacyManiaSkinConfigurationLookup.cs | osu.Game/Skinning/LegacyManiaSkinConfigurationLookup.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Skinning
{
/// <summary>
/// This class exists for the explicit purpose of ferrying information from ManiaBeatmap in a way LegacySkin can use it.
/// This is because half of the mania legacy skin implementation is in LegacySkin (osu.Game project) which doesn't have visibility
/// over ManiaBeatmap / StageDefinition.
/// </summary>
public class LegacyManiaSkinConfigurationLookup
{
/// <summary>
/// Total columns across all stages.
/// </summary>
public readonly int TotalColumns;
public readonly int? TargetColumn;
public readonly LegacyManiaSkinConfigurationLookups Lookup;
public LegacyManiaSkinConfigurationLookup(int totalColumns, LegacyManiaSkinConfigurationLookups lookup, int? targetColumn = null)
{
TotalColumns = totalColumns;
Lookup = lookup;
TargetColumn = targetColumn;
}
}
public enum LegacyManiaSkinConfigurationLookups
{
ColumnWidth,
ColumnSpacing,
LightImage,
LeftLineWidth,
RightLineWidth,
HitPosition,
ScorePosition,
LightPosition,
HitTargetImage,
ShowJudgementLine,
KeyImage,
KeyImageDown,
NoteImage,
HoldNoteHeadImage,
HoldNoteTailImage,
HoldNoteBodyImage,
HoldNoteLightImage,
HoldNoteLightScale,
ExplosionImage,
ExplosionScale,
ColumnLineColour,
JudgementLineColour,
ColumnBackgroundColour,
ColumnLightColour,
MinimumColumnWidth,
LeftStageImage,
RightStageImage,
BottomStageImage,
Hit300g,
Hit300,
Hit200,
Hit100,
Hit50,
Hit0,
KeysUnderNotes,
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Skinning
{
public class LegacyManiaSkinConfigurationLookup
{
/// <summary>
/// Total columns across all stages.
/// </summary>
public readonly int TotalColumns;
public readonly LegacyManiaSkinConfigurationLookups Lookup;
public readonly int? TargetColumn;
public LegacyManiaSkinConfigurationLookup(int totalColumns, LegacyManiaSkinConfigurationLookups lookup, int? targetColumn = null)
{
TotalColumns = totalColumns;
Lookup = lookup;
TargetColumn = targetColumn;
}
}
public enum LegacyManiaSkinConfigurationLookups
{
ColumnWidth,
ColumnSpacing,
LightImage,
LeftLineWidth,
RightLineWidth,
HitPosition,
ScorePosition,
LightPosition,
HitTargetImage,
ShowJudgementLine,
KeyImage,
KeyImageDown,
NoteImage,
HoldNoteHeadImage,
HoldNoteTailImage,
HoldNoteBodyImage,
HoldNoteLightImage,
HoldNoteLightScale,
ExplosionImage,
ExplosionScale,
ColumnLineColour,
JudgementLineColour,
ColumnBackgroundColour,
ColumnLightColour,
MinimumColumnWidth,
LeftStageImage,
RightStageImage,
BottomStageImage,
Hit300g,
Hit300,
Hit200,
Hit100,
Hit50,
Hit0,
KeysUnderNotes,
}
}
| mit | C# |
c0e708933e3a055392ba7242004605f43472b907 | Use range check for floating point | bradphelan/SketchSolve.NET,bradphelan/SketchSolve.NET,bradphelan/SketchSolve.NET | SketchSolveC#.NET.Spec/Test.cs | SketchSolveC#.NET.Spec/Test.cs | using System;
using NUnit.Framework;
using FluentAssertions;
using SketchSolve;
using System.Linq;
namespace SketchSolve.Spec
{
[TestFixture()]
public class Solver
{
[Test()]
public void HorizontalConstraintShouldWork ()
{
var parameters = new Parameter[]{
new Parameter(0),
new Parameter(1),
new Parameter(2),
new Parameter(3)
};
var points = new point[]{
new point(){x = parameters[0], y = parameters[1]},
new point(){x = parameters[2], y = parameters[3]},
};
var lines = new line[]{
new line(){p1 = points[0], p2 = points[1]}
};
var cons = new constraint[] {
new constraint(){
type =ConstraintEnum.horizontal,
line1 = lines[0]
}
};
var r = SketchSolve.Solver.solve(parameters, cons, true);
points [0].y.Value.Should ().BeInRange (points[1].y.Value-0.001, points[1].y.Value+0.001);
points [0].x.Value.Should ().NotBe (points[1].x.Value);
}
}
}
| using System;
using NUnit.Framework;
using FluentAssertions;
using SketchSolve;
using System.Linq;
namespace SketchSolve.Spec
{
[TestFixture()]
public class Solver
{
[Test()]
public void HorizontalConstraintShouldWork ()
{
var parameters = new Parameter[]{
new Parameter(0),
new Parameter(1),
new Parameter(2),
new Parameter(3)
};
var points = new point[]{
new point(){x = parameters[0], y = parameters[1]},
new point(){x = parameters[2], y = parameters[3]},
};
var lines = new line[]{
new line(){p1 = points[0], p2 = points[1]}
};
var cons = new constraint[] {
new constraint(){
type =ConstraintEnum.horizontal,
line1 = lines[0]
}
};
var r = SketchSolve.Solver.solve(parameters, cons, true);
points [0].y.Value.Should ().Be (points[1].y.Value);
points [0].x.Value.Should ().NotBe (points[1].x.Value);
}
}
}
| bsd-3-clause | C# |
ff154f866e93e19faaec2ff2ddc74d4d6500382f | handle error if can't deserialize body | NTumbleBit/NTumbleBit,DanGould/NTumbleBit | NTumbleBit/ClassicTumbler/Server/BitcoinInputFormatter.cs | NTumbleBit/ClassicTumbler/Server/BitcoinInputFormatter.cs | using Microsoft.AspNetCore.Mvc.Formatters;
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace NTumbleBit.ClassicTumbler.Server
{
public class BitcoinInputFormatter : IInputFormatter
{
static BitcoinInputFormatter()
{
_Parse = typeof(BitcoinInputFormatter).GetTypeInfo().GetMethod("Parse", BindingFlags.Static | BindingFlags.Public);
}
static readonly MethodInfo _Parse;
public bool CanRead(InputFormatterContext context)
{
return (typeof(IBitcoinSerializable).GetTypeInfo().IsAssignableFrom(context.ModelType)) ||
(context.ModelType.IsArray && typeof(IBitcoinSerializable).GetTypeInfo().IsAssignableFrom(context.ModelType.GetTypeInfo().GetElementType()));
}
public Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
{
try
{
BitcoinStream bs = new BitcoinStream(context.HttpContext.Request.Body, false);
Type type = context.ModelType;
var signature = type == typeof(TransactionSignature);
if(context.ModelType.IsArray)
{
var elementType = context.ModelType.GetElementType();
type = typeof(ArrayWrapper<>).MakeGenericType(elementType);
}
if(signature)
{
type = typeof(SignatureWrapper);
}
var result = _Parse.MakeGenericMethod(type).Invoke(null, new object[] { bs });
if(context.ModelType.IsArray)
{
var getElements = type.GetTypeInfo().GetProperty("Elements", BindingFlags.Instance | BindingFlags.Public).GetGetMethod();
result = getElements.Invoke(result, new object[0]);
}
if(signature)
{
result = ((SignatureWrapper)result).Signature;
}
return InputFormatterResult.SuccessAsync(result);
}
catch
{
return InputFormatterResult.FailureAsync();
}
}
public static T Parse<T>(BitcoinStream bs) where T : IBitcoinSerializable
{
T t = default(T);
bs.ReadWrite(ref t);
return t;
}
}
}
| using Microsoft.AspNetCore.Mvc.Formatters;
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace NTumbleBit.ClassicTumbler.Server
{
public class BitcoinInputFormatter : IInputFormatter
{
static BitcoinInputFormatter()
{
_Parse = typeof(BitcoinInputFormatter).GetTypeInfo().GetMethod("Parse", BindingFlags.Static | BindingFlags.Public);
}
static readonly MethodInfo _Parse;
public bool CanRead(InputFormatterContext context)
{
return (typeof(IBitcoinSerializable).GetTypeInfo().IsAssignableFrom(context.ModelType)) ||
(context.ModelType.IsArray && typeof(IBitcoinSerializable).GetTypeInfo().IsAssignableFrom(context.ModelType.GetTypeInfo().GetElementType()));
}
public Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
{
BitcoinStream bs = new BitcoinStream(context.HttpContext.Request.Body, false);
Type type = context.ModelType;
var signature = type == typeof(TransactionSignature);
if(context.ModelType.IsArray)
{
var elementType = context.ModelType.GetElementType();
type = typeof(ArrayWrapper<>).MakeGenericType(elementType);
}
if(signature)
{
type = typeof(SignatureWrapper);
}
var result = _Parse.MakeGenericMethod(type).Invoke(null, new object[] { bs });
if(context.ModelType.IsArray)
{
var getElements = type.GetTypeInfo().GetProperty("Elements", BindingFlags.Instance | BindingFlags.Public).GetGetMethod();
result = getElements.Invoke(result, new object[0]);
}
if(signature)
{
result = ((SignatureWrapper)result).Signature;
}
return InputFormatterResult.SuccessAsync(result);
}
public static T Parse<T>(BitcoinStream bs) where T : IBitcoinSerializable
{
T t = default(T);
bs.ReadWrite(ref t);
return t;
}
}
}
| mit | C# |
853da6b58512d299622beb688cbafca0e0221c9e | Update CameraCache.cs | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit/Utilities/CameraCache.cs | Assets/MixedRealityToolkit/Utilities/CameraCache.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main
/// executes a FindByTag on the scene, which will get worse and worse with more tagged objects.
/// </summary>
public static class CameraCache
{
private static Camera cachedCamera;
/// <summary>
/// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet.
/// </summary>
public static Camera Main
{
get
{
if (cachedCamera != null)
{
if (cachedCamera.gameObject.activeInHierarchy)
{ // If the cached camera is active, return it
// Otherwise, our playspace may have been disabled
// We'll have to search for the next available
return cachedCamera;
}
}
// If the cached camera is null, search for main
var mainCamera = Camera.main;
if (mainCamera == null)
{ // If no main camera was found, create it now
Debug.LogWarning("No main camera found. The Mixed Reality Toolkit requires at least one camera in the scene. One will be generated now.");
mainCamera = new GameObject("Main Camera", typeof(Camera), typeof(AudioListener)) { tag = "MainCamera" }.GetComponent<Camera>();
}
// Cache the main camera
cachedCamera = mainCamera;
return cachedCamera;
}
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main
/// executes a FindByTag on the scene, which will get worse and worse with more tagged objects.
/// </summary>
public static class CameraCache
{
private static Camera cachedCamera;
/// <summary>
/// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet.
/// </summary>
public static Camera Main
{
get
{
if (cachedCamera != null)
{
if (cachedCamera.gameObject.activeInHierarchy)
{ // If the cached camera is active, return it
// Otherwise, our playspace may have been disabled
// We'll have to search for the next available
return cachedCamera;
}
}
// If the cached camera is null, search for main
var mainCamera = Camera.main;
if (mainCamera == null)
{ // If no main camera was found, create it now
Debug.LogWarning("No main camera found. The Mixed Reality Toolkit requires at least one camera in the scene. One will be generated now.");
mainCamera = new GameObject("Main Camera", typeof(Camera)) { tag = "MainCamera" }.GetComponent<Camera>();
}
// Cache the main camera
cachedCamera = mainCamera;
return cachedCamera;
}
}
}
}
| mit | C# |
cb2c044c08bfb22ae3810d6b0d87f3d741c9a224 | Fix exception with CableTerminalPortNode assuming an entity's GridID can never be zero. | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/Power/Nodes/CableTerminalPortNode.cs | Content.Server/Power/Nodes/CableTerminalPortNode.cs | using System.Collections.Generic;
using Content.Server.NodeContainer.Nodes;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Serialization.Manager.Attributes;
namespace Content.Server.Power.Nodes
{
[DataDefinition]
public class CableTerminalPortNode : Node
{
public override IEnumerable<Node> GetReachableNodes()
{
if (Owner.Transform.GridID == GridId.Invalid)
yield break; // No funny nodes in spess.
var entMan = IoCManager.Resolve<IEntityManager>();
var grid = IoCManager.Resolve<IMapManager>().GetGrid(Owner.Transform.GridID);
var gridIndex = grid.TileIndicesFor(Owner.Transform.Coordinates);
var nodes = NodeHelpers.GetCardinalNeighborNodes(entMan, grid, gridIndex, includeSameTile: false);
foreach (var (_, node) in nodes)
{
if (node is CableTerminalNode)
yield return node;
}
}
}
}
| using System.Collections.Generic;
using Content.Server.NodeContainer.Nodes;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Serialization.Manager.Attributes;
namespace Content.Server.Power.Nodes
{
[DataDefinition]
public class CableTerminalPortNode : Node
{
public override IEnumerable<Node> GetReachableNodes()
{
var entMan = IoCManager.Resolve<IEntityManager>();
var grid = IoCManager.Resolve<IMapManager>().GetGrid(Owner.Transform.GridID);
var gridIndex = grid.TileIndicesFor(Owner.Transform.Coordinates);
var nodes = NodeHelpers.GetCardinalNeighborNodes(entMan, grid, gridIndex, includeSameTile: false);
foreach (var (_, node) in nodes)
{
if (node is CableTerminalNode)
yield return node;
}
}
}
}
| mit | C# |
05a4e0ef8965379b284a4f3fff8ebda866281d2f | Add watchapp download URL | garuma/pebble-battery-dashclock-extension,garuma/pebble-battery-dashclock-extension,garuma/pebble-battery-dashclock-extension | DashClockPebbleBatteryExtension/SettingsActivity.cs | DashClockPebbleBatteryExtension/SettingsActivity.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Pebble.Android;
namespace DashClockPebbleBatteryExtension
{
[Activity (Label = "Pebble Battery Extension Settings",
Icon = "@drawable/Icon",
Exported = true,
Theme = "@android:style/Theme.Holo.Light.NoActionBar")]
public class SettingsActivity : Activity
{
const string PbwLocation = "https://neteril.org/pebble/companion_watchapp.pbw";
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
var btn = FindViewById<Button> (Resource.Id.watchAppBtn);
btn.Click += (sender, e) => {
var uri = Android.Net.Uri.Parse (PbwLocation);
var intent = new Intent (Intent.ActionView, uri);
StartActivity (intent);
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Pebble.Android;
namespace DashClockPebbleBatteryExtension
{
[Activity (Label = "Pebble Battery Extension Settings",
Icon = "@drawable/Icon",
Exported = true,
Theme = "@android:style/Theme.Holo.Light.NoActionBar")]
public class SettingsActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
var btn = FindViewById<Button> (Resource.Id.watchAppBtn);
btn.Click += (sender, e) => {
};
}
}
}
| apache-2.0 | C# |
0198e40fcf48c258047dab37daef03aeac7be293 | Fix NullReferenceException in ShowPlanView | terrajobst/nquery-vnext | src/NQuery.Authoring.Wpf/ShowPlans/ShowPlanView.xaml.cs | src/NQuery.Authoring.Wpf/ShowPlans/ShowPlanView.xaml.cs | using System;
using System.Windows;
namespace NQuery.Authoring.Wpf
{
public sealed partial class ShowPlanView
{
public static readonly DependencyProperty ShowPlanProperty = DependencyProperty.Register("ShowPlan", typeof(ShowPlanNode), typeof(ShowPlanView), new FrameworkPropertyMetadata((s, e) => ShowPlanNodeChanged(s, e)));
public ShowPlanView()
{
InitializeComponent();
}
public ShowPlanNode ShowPlan
{
get { return (ShowPlanNode)GetValue(ShowPlanProperty); }
set { SetValue(ShowPlanProperty, value); }
}
private static void ShowPlanNodeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var view = (ShowPlanView) sender;
var model = (ShowPlanNode) e.NewValue;
var viewModel = model == null ? null : new ShowPlanViewModel(model);
view._planTreeView.DataContext = viewModel;
}
}
}
| using System;
using System.Windows;
namespace NQuery.Authoring.Wpf
{
public sealed partial class ShowPlanView
{
public static readonly DependencyProperty ShowPlanProperty = DependencyProperty.Register("ShowPlan", typeof(ShowPlanNode), typeof(ShowPlanView), new FrameworkPropertyMetadata((s, e) => ShowPlanNodeChanged(s, e)));
public ShowPlanView()
{
InitializeComponent();
}
public ShowPlanNode ShowPlan
{
get { return (ShowPlanNode)GetValue(ShowPlanProperty); }
set { SetValue(ShowPlanProperty, value); }
}
private static void ShowPlanNodeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var view = (ShowPlanView) sender;
var model = (ShowPlanNode) e.NewValue;
view._planTreeView.DataContext = new ShowPlanViewModel(model);
}
}
}
| mit | C# |
45a534a1ba0f1c836215c5a4b1578da733c50fdf | Fix duplicated `GlobalSetup` attribute on `BenchmarkMod` | NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,smoogipooo/osu,peppy/osu | osu.Game.Benchmarks/BenchmarkMod.cs | osu.Game.Benchmarks/BenchmarkMod.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using BenchmarkDotNet.Attributes;
using osu.Game.Rulesets.Osu.Mods;
namespace osu.Game.Benchmarks
{
public class BenchmarkMod : BenchmarkTest
{
private OsuModDoubleTime mod;
[Params(1, 10, 100)]
public int Times { get; set; }
public override void SetUp()
{
base.SetUp();
mod = new OsuModDoubleTime();
}
[Benchmark]
public int ModHashCode()
{
var hashCode = new HashCode();
for (int i = 0; i < Times; i++)
hashCode.Add(mod);
return hashCode.ToHashCode();
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using BenchmarkDotNet.Attributes;
using osu.Game.Rulesets.Osu.Mods;
namespace osu.Game.Benchmarks
{
public class BenchmarkMod : BenchmarkTest
{
private OsuModDoubleTime mod;
[Params(1, 10, 100)]
public int Times { get; set; }
[GlobalSetup]
public void GlobalSetup()
{
mod = new OsuModDoubleTime();
}
[Benchmark]
public int ModHashCode()
{
var hashCode = new HashCode();
for (int i = 0; i < Times; i++)
hashCode.Add(mod);
return hashCode.ToHashCode();
}
}
}
| mit | C# |
791de0a94b4dc53b5fe776da19c209a5204e0f7b | remove check in VideoRepository to see if VideoExists | smbc-digital/iag-contentapi | src/StockportContentApi/Repositories/VideoRepository.cs | src/StockportContentApi/Repositories/VideoRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StockportContentApi.Config;
using StockportContentApi.Http;
namespace StockportContentApi.Repositories
{
public interface IVideoRepository
{
string Process(string content);
}
public class VideoRepository : IVideoRepository
{
private readonly TwentyThreeConfig _twentyThreeConfig;
private readonly IHttpClient _httpClient;
private readonly ILogger<VideoRepository> _logger;
private const string StartTag = "{{VIDEO:";
private const string EndTag = "}}";
public VideoRepository(TwentyThreeConfig twentyThreeConfig, IHttpClient httpClient, ILogger<VideoRepository> logger)
{
_twentyThreeConfig = twentyThreeConfig;
_httpClient = httpClient;
_logger = logger;
}
public string Process(string content) =>
ReplaceVideoTagsWithVideoContent(content);
private string ReplaceVideoTagsWithVideoContent(string body)
{
var videoTags = GetVideosTags(body);
foreach (var videoTag in videoTags)
{
var videoId = videoTag
.Replace(StartTag, string.Empty)
.Replace(EndTag, string.Empty);
// if (!VideoExists(videoId)) we are removing this while we work out why /news is being spammed and we work on improving how we get the information for the news pages
body = body.Replace(videoTag, string.Empty);
}
return body;
}
private static IEnumerable<string> GetVideosTags(string body) =>
Regex
.Matches(body, "{{VIDEO:([0-9aA-zZ]*;?[0-9aA-zZ]*)}}")
.OfType<Match>()
.Select(match => match.Value)
.ToList();
private bool VideoExists(string videoId)
{
var videoData = videoId.Split(';');
string url = $"{_twentyThreeConfig.BaseUrl}{videoData[0]}&token={videoData[1]}";
var result = _httpClient.Get(url).Result;
return result != null && result.StatusCode == HttpStatusCode.OK;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StockportContentApi.Config;
using StockportContentApi.Http;
namespace StockportContentApi.Repositories
{
public interface IVideoRepository
{
string Process(string content);
}
public class VideoRepository : IVideoRepository
{
private readonly TwentyThreeConfig _twentyThreeConfig;
private readonly IHttpClient _httpClient;
private readonly ILogger<VideoRepository> _logger;
private const string StartTag = "{{VIDEO:";
private const string EndTag = "}}";
public VideoRepository(TwentyThreeConfig twentyThreeConfig, IHttpClient httpClient, ILogger<VideoRepository> logger)
{
_twentyThreeConfig = twentyThreeConfig;
_httpClient = httpClient;
_logger = logger;
}
public string Process(string content) =>
ReplaceVideoTagsWithVideoContent(content);
private string ReplaceVideoTagsWithVideoContent(string body)
{
var videoTags = GetVideosTags(body);
foreach (var videoTag in videoTags)
{
var videoId = videoTag
.Replace(StartTag, string.Empty)
.Replace(EndTag, string.Empty);
if (!VideoExists(videoId))
body = body.Replace(videoTag, string.Empty);
}
return body;
}
private static IEnumerable<string> GetVideosTags(string body) =>
Regex
.Matches(body, "{{VIDEO:([0-9aA-zZ]*;?[0-9aA-zZ]*)}}")
.OfType<Match>()
.Select(match => match.Value)
.ToList();
private bool VideoExists(string videoId)
{
var videoData = videoId.Split(';');
string url = $"{_twentyThreeConfig.BaseUrl}{videoData[0]}&token={videoData[1]}";
var result = _httpClient.Get(url).Result;
return result != null && result.StatusCode == HttpStatusCode.OK;
}
}
} | mit | C# |
dce4716af2a29d38d425b887da70282e62284c5c | Fix RecordFields and UnionCases not appearing in generated reference docs | modulexcite/FSharp.Formatting,mktange/FSharp.Formatting,mktange/FSharp.Formatting,halcwb/FSharp.Formatting,tpetricek/FSharp.Formatting,halcwb/FSharp.Formatting,ademar/FSharp.Formatting,modulexcite/FSharp.Formatting,halcwb/FSharp.Formatting,theprash/FSharp.Formatting,ademar/FSharp.Formatting,mktange/FSharp.Formatting,modulexcite/FSharp.Formatting,mktange/FSharp.Formatting,theprash/FSharp.Formatting,modulexcite/FSharp.Formatting,Rickasaurus/FSharp.Formatting,Rickasaurus/FSharp.Formatting,modulexcite/FSharp.Formatting,ademar/FSharp.Formatting,tpetricek/FSharp.Formatting,modulexcite/FSharp.Formatting,tpetricek/FSharp.Formatting,theprash/FSharp.Formatting,ademar/FSharp.Formatting,Rickasaurus/FSharp.Formatting,ademar/FSharp.Formatting,tpetricek/FSharp.Formatting,Rickasaurus/FSharp.Formatting,mktange/FSharp.Formatting,mktange/FSharp.Formatting,tpetricek/FSharp.Formatting,theprash/FSharp.Formatting,ademar/FSharp.Formatting,halcwb/FSharp.Formatting,Rickasaurus/FSharp.Formatting,theprash/FSharp.Formatting,tpetricek/FSharp.Formatting,theprash/FSharp.Formatting,halcwb/FSharp.Formatting,halcwb/FSharp.Formatting,Rickasaurus/FSharp.Formatting | misc/templates/reference/type.cshtml | misc/templates/reference/type.cshtml | @using FSharp.MetadataFormat
@{
Layout = "template";
Title = Model.Type.Name + " - " + Properties["project-name"];
}
@{
var members = (IEnumerable<Member>)Model.Type.AllMembers;
var comment = (Comment)Model.Type.Comment;
var byCategory =
members.GroupBy(m => m.Category).OrderBy(g => String.IsNullOrEmpty(g.Key) ? "ZZZ" : g.Key)
.Select((g, n) => new { Index = n, GroupKey = g.Key, Members = g.OrderBy(m => m.Name), Name = String.IsNullOrEmpty(g.Key) ? "Other type members" : g.Key });
}
<h1>@Model.Type.Name</h1>
<div class="xmldoc">
@foreach (var sec in comment.Sections) {
if (!byCategory.Any(g => g.GroupKey == sec.Key)) {
if (sec.Key != "<default>") {
<h2>@sec.Key</h2>
}
@sec.Value
}
}
</div>
@if (byCategory.Count() > 1)
{
<h2>Table of contents</h2>
<ul>
@foreach (var g in byCategory)
{
<li><a href="@("#section" + g.Index.ToString())">@g.Name</a></li>
}
</ul>
}
@foreach (var g in byCategory) {
if (byCategory.Count() > 1) {
<h2>@g.Name<a name="@("section" + g.Index.ToString())"> </a></h2>
var info = comment.Sections.FirstOrDefault(kvp => kvp.Key == g.GroupKey);
if (info.Key != null) {
<div class="xmldoc">
@info.Value
</div>
}
}
@RenderPart("members", new {
Header = "Union Cases",
TableHeader = "Union Case",
Members = Model.Type.UnionCases
})
@RenderPart("members", new {
Header = "Record Fields",
TableHeader = "Record Fieldr",
Members = Model.Type.RecordFields
})
@RenderPart("members", new {
Header = "Constructors",
TableHeader = "Constructor",
Members = g.Members.Where(m => m.Kind == MemberKind.Constructor)
})
@RenderPart("members", new {
Header = "Instance members",
TableHeader = "Instance member",
Members = g.Members.Where(m => m.Kind == MemberKind.InstanceMember)
})
@RenderPart("members", new {
Header = "Static members",
TableHeader = "Static member",
Members = g.Members.Where(m => m.Kind == MemberKind.StaticMember)
})
}
| @using FSharp.MetadataFormat
@{
Layout = "template";
Title = Model.Type.Name + " - " + Properties["project-name"];
}
@{
var members = (IEnumerable<Member>)Model.Type.AllMembers;
var comment = (Comment)Model.Type.Comment;
var byCategory =
members.GroupBy(m => m.Category).OrderBy(g => String.IsNullOrEmpty(g.Key) ? "ZZZ" : g.Key)
.Select((g, n) => new { Index = n, GroupKey = g.Key, Members = g.OrderBy(m => m.Name), Name = String.IsNullOrEmpty(g.Key) ? "Other type members" : g.Key });
}
<h1>@Model.Type.Name</h1>
<div class="xmldoc">
@foreach (var sec in comment.Sections) {
if (!byCategory.Any(g => g.GroupKey == sec.Key)) {
if (sec.Key != "<default>") {
<h2>@sec.Key</h2>
}
@sec.Value
}
}
</div>
@if (byCategory.Count() > 1)
{
<h2>Table of contents</h2>
<ul>
@foreach (var g in byCategory)
{
<li><a href="@("#section" + g.Index.ToString())">@g.Name</a></li>
}
</ul>
}
@foreach (var g in byCategory) {
if (byCategory.Count() > 1) {
<h2>@g.Name<a name="@("section" + g.Index.ToString())"> </a></h2>
var info = comment.Sections.FirstOrDefault(kvp => kvp.Key == g.GroupKey);
if (info.Key != null) {
<div class="xmldoc">
@info.Value
</div>
}
}
@RenderPart("members", new {
Header = "Constructors",
TableHeader = "Constructor",
Members = g.Members.Where(m => m.Kind == MemberKind.Constructor)
})
@RenderPart("members", new {
Header = "Instance members",
TableHeader = "Instance member",
Members = g.Members.Where(m => m.Kind == MemberKind.InstanceMember)
})
@RenderPart("members", new {
Header = "Static members",
TableHeader = "Static member",
Members = g.Members.Where(m => m.Kind == MemberKind.StaticMember)
})
}
| apache-2.0 | C# |
74be53b159a7a2874c5250f96ce4db5ca48a80df | Update Program.cs | IanMcT/StockMarketGame | SMG/SMG/Program.cs | SMG/SMG/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SMG
{
static class Program
{
public static User user;
public static double difficulty = 1000.00;
public static List<Stock> stocks = new List<Stock>();
public static Form1 mainScreen;
public static startScreen startScreen;
public static stockMarketScreen smScreen;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
mainScreen = new Form1();
mainScreen.Show();
Application.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SMG
{
static class Program
{
public static User user;
public static double difficulty = 1000.00;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var MainForm = new Form1();
MainForm.Show();
Application.Run();
}
}
}
| apache-2.0 | C# |
8cb7ef1556409cbff1d2a7e968002c1fa27dc649 | Update this with some more info about what is needed to fix it. | castleproject/castle-READONLY-SVN-dump,castleproject/castle-READONLY-SVN-dump,carcer/Castle.Components.Validator,castleproject/Castle.Transactions,codereflection/Castle.Components.Scheduler,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Transactions,castleproject/Castle.Transactions,castleproject/Castle.Facilities.Wcf-READONLY,castleproject/Castle.Facilities.Wcf-READONLY | ActiveRecord/Castle.ActiveRecord.Tests/MultipleDatabasesTestCase.cs | ActiveRecord/Castle.ActiveRecord.Tests/MultipleDatabasesTestCase.cs | // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.ActiveRecord.Tests
{
using Castle.ActiveRecord.Framework;
using Castle.ActiveRecord.Tests.Model;
using NUnit.Framework;
[TestFixture]
public class MultipleDatabasesTestCase : AbstractActiveRecordTest
{
[SetUp]
public void Setup()
{
base.Init();
ActiveRecordStarter.Initialize( GetConfigSource(),
typeof(Blog), typeof(Post), typeof(Hand), typeof(Test2ARBase) );
Recreate();
}
[Test]
public void OperateOne()
{
Blog[] blogs = Blog.FindAll();
Assert.AreEqual(0, blogs.Length);
CreateBlog();
blogs = Blog.FindAll();
Assert.AreEqual(1, blogs.Length);
}
private static void CreateBlog()
{
Blog blog = new Blog();
blog.Author = "Henry";
blog.Name = "Senseless";
blog.Save();
}
[Test]
public void OperateTheOtherOne()
{
Hand[] hands = Hand.FindAll();
Assert.AreEqual(0, hands.Length);
CreateHand();
hands = Hand.FindAll();
Assert.AreEqual(1, hands.Length);
}
private static void CreateHand()
{
Hand hand = new Hand();
hand.Side = "Right";
hand.Save();
}
[Test]
public void OperateBoth()
{
Blog[] blogs = Blog.FindAll();
Hand[] hands = Hand.FindAll();
Assert.AreEqual(0, blogs.Length);
Assert.AreEqual(0, hands.Length);
CreateBlog();
CreateHand();
blogs = Blog.FindAll();
hands = Hand.FindAll();
Assert.AreEqual(1, blogs.Length);
Assert.AreEqual(1, hands.Length);
}
[Test]
[Ignore("This still needs to be fixed")]
[ExpectedException(typeof(ActiveRecordInitializationException))]
public void MultipleDatabaseInvalidConfigWhenNotRegisterBaseClass() {
base.Init();
//Not registering the base class should not cause AR to silently ignore the configuration
//for the type meaning all classes would use a single database.
//if there is a type in the config which is not registered - but a subclass is then we should throw.
//AFAIK - fixing this requires exposing _type2Config to ActiveRecordStarter.
ActiveRecordStarter.Initialize(GetConfigSource(),
typeof(Blog), typeof(Post), typeof(Hand));
Recreate();
}
}
}
| // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.ActiveRecord.Tests
{
using Castle.ActiveRecord.Framework;
using Castle.ActiveRecord.Tests.Model;
using NUnit.Framework;
[TestFixture]
public class MultipleDatabasesTestCase : AbstractActiveRecordTest
{
[SetUp]
public void Setup()
{
base.Init();
ActiveRecordStarter.Initialize( GetConfigSource(),
typeof(Blog), typeof(Post), typeof(Hand), typeof(Test2ARBase) );
Recreate();
}
[Test]
public void OperateOne()
{
Blog[] blogs = Blog.FindAll();
Assert.AreEqual(0, blogs.Length);
CreateBlog();
blogs = Blog.FindAll();
Assert.AreEqual(1, blogs.Length);
}
private static void CreateBlog()
{
Blog blog = new Blog();
blog.Author = "Henry";
blog.Name = "Senseless";
blog.Save();
}
[Test]
public void OperateTheOtherOne()
{
Hand[] hands = Hand.FindAll();
Assert.AreEqual(0, hands.Length);
CreateHand();
hands = Hand.FindAll();
Assert.AreEqual(1, hands.Length);
}
private static void CreateHand()
{
Hand hand = new Hand();
hand.Side = "Right";
hand.Save();
}
[Test]
public void OperateBoth()
{
Blog[] blogs = Blog.FindAll();
Hand[] hands = Hand.FindAll();
Assert.AreEqual(0, blogs.Length);
Assert.AreEqual(0, hands.Length);
CreateBlog();
CreateHand();
blogs = Blog.FindAll();
hands = Hand.FindAll();
Assert.AreEqual(1, blogs.Length);
Assert.AreEqual(1, hands.Length);
}
[Test]
[Ignore]
[ExpectedException(typeof(ActiveRecordInitializationException))]
public void MultipleDatabaseInvalidConfigWhenNotRegisterBaseClass() {
base.Init();
//Not registering the base class should not cause AR to silently ignore the configuration
//for the type meaning all classes would use a single database.
//if there is a type in the config which is not registered - but a subclass is then we should throw.
ActiveRecordStarter.Initialize(GetConfigSource(),
typeof(Blog), typeof(Post), typeof(Hand));
Recreate();
}
}
}
| apache-2.0 | C# |
d184363b96eb24ac88376d232347dfa590e8a31b | Remove extraneous #if | JustinRChou/nunit,acco32/nunit,JustinRChou/nunit,cPetru/nunit-params,OmicronPersei/nunit,jadarnel27/nunit,agray/nunit,nivanov1984/nunit,mjedrzejek/nunit,pflugs30/nunit,Green-Bug/nunit,NikolayPianikov/nunit,acco32/nunit,ggeurts/nunit,Green-Bug/nunit,NikolayPianikov/nunit,agray/nunit,ggeurts/nunit,pflugs30/nunit,nivanov1984/nunit,JohanO/nunit,OmicronPersei/nunit,nunit/nunit,JohanO/nunit,danielmarbach/nunit,Green-Bug/nunit,jnm2/nunit,appel1/nunit,mikkelbu/nunit,Suremaker/nunit,Suremaker/nunit,appel1/nunit,mikkelbu/nunit,cPetru/nunit-params,acco32/nunit,danielmarbach/nunit,ChrisMaddock/nunit,agray/nunit,mjedrzejek/nunit,ChrisMaddock/nunit,danielmarbach/nunit,jadarnel27/nunit,nunit/nunit,jnm2/nunit,JohanO/nunit | src/Common/nunit/Env.cs | src/Common/nunit/Env.cs | // ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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.Text;
namespace NUnit
{
/// <summary>
/// Env is a static class that provides some of the features of
/// System.Environment that are not available under all runtimes
/// </summary>
public class Env
{
// Define NewLine to be used for this system
// NOTE: Since this is done at compile time for .NET CF,
// these binaries are not yet currently portable.
/// <summary>
/// The newline sequence in the current environment.
/// </summary>
#if PocketPC || WindowsCE || NETCF
public static readonly string NewLine = "\r\n";
#else
public static readonly string NewLine = Environment.NewLine;
#endif
/// <summary>
/// Path to the 'My Documents' folder
/// </summary>
#if PocketPC || WindowsCE || NETCF || PORTABLE
public static string DocumentFolder = @"\My Documents";
#else
public static string DocumentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
#endif
/// <summary>
/// Directory used for file output if not specified on commandline.
/// </summary>
#if SILVERLIGHT || PocketPC || WindowsCE || NETCF || PORTABLE
public static readonly string DefaultWorkDirectory = DocumentFolder;
#else
public static readonly string DefaultWorkDirectory = Environment.CurrentDirectory;
#endif
}
}
| // ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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.Text;
#if NUNIT
#endif
namespace NUnit
{
/// <summary>
/// Env is a static class that provides some of the features of
/// System.Environment that are not available under all runtimes
/// </summary>
public class Env
{
// Define NewLine to be used for this system
// NOTE: Since this is done at compile time for .NET CF,
// these binaries are not yet currently portable.
/// <summary>
/// The newline sequence in the current environment.
/// </summary>
#if PocketPC || WindowsCE || NETCF
public static readonly string NewLine = "\r\n";
#else
public static readonly string NewLine = Environment.NewLine;
#endif
/// <summary>
/// Path to the 'My Documents' folder
/// </summary>
#if PocketPC || WindowsCE || NETCF || PORTABLE
public static string DocumentFolder = @"\My Documents";
#else
public static string DocumentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
#endif
/// <summary>
/// Directory used for file output if not specified on commandline.
/// </summary>
#if SILVERLIGHT || PocketPC || WindowsCE || NETCF || PORTABLE
public static readonly string DefaultWorkDirectory = DocumentFolder;
#else
public static readonly string DefaultWorkDirectory = Environment.CurrentDirectory;
#endif
}
}
| mit | C# |
d818f561f7a4cdcbbf91a5ca8463f3a6a9df692a | Add using statement | TeamnetGroup/schema2fm | src/ConsoleApp/Table.cs | src/ConsoleApp/Table.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApp
{
public class Table
{
private readonly string tableName;
private readonly IEnumerable<Column> columns;
public Table(string tableName, IEnumerable<Column> columns)
{
this.tableName = tableName;
this.columns = columns;
}
public void OutputMigrationCode(TextWriter writer)
{
const string format = "yyyyMMddHHmmss";
writer.WriteLine(@"using FluentMigrator;
namespace Migrations
{");
writer.WriteLine($" [Migration(\"{DateTime.Now.ToString(format)}\")]");
writer.Write($" public class {tableName}Migration : Migration");
writer.WriteLine(@"
{
public override void Up()
{");
writer.Write($" Create.Table(\"{tableName}\")");
columns.ToList().ForEach(c =>
{
writer.WriteLine();
writer.Write(c.FluentMigratorCode());
});
writer.WriteLine(@";
}
public override void Down()
{");
writer.Write($" Delete.Table(\"{tableName}\");");
writer.WriteLine(@"
}
}
}");
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApp
{
public class Table
{
private readonly string tableName;
private readonly IEnumerable<Column> columns;
public Table(string tableName, IEnumerable<Column> columns)
{
this.tableName = tableName;
this.columns = columns;
}
public void OutputMigrationCode(TextWriter writer)
{
const string format = "yyyyMMddHHmmss";
writer.WriteLine(@"namespace Migrations
{");
writer.WriteLine($" [Migration(\"{DateTime.Now.ToString(format)}\")]");
writer.Write($" public class {tableName}Migration : Migration");
writer.WriteLine(@"
{
public override void Up()
{");
writer.Write($" Create.Table(\"{tableName}\")");
columns.ToList().ForEach(c =>
{
writer.WriteLine();
writer.Write(c.FluentMigratorCode());
});
writer.WriteLine(@";
}
public override void Down()
{");
writer.Write($" Delete.Table(\"{tableName}\");");
writer.WriteLine(@"
}
}
}");
}
}
} | mit | C# |
bc0943d47147a8127c7cf69fafe5e68bfa065236 | Add reference to source of debug lookup method | smoogipooo/osu-framework,ppy/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework | osu.Framework/Development/DebugUtils.cs | osu.Framework/Development/DebugUtils.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace osu.Framework.Development
{
public static class DebugUtils
{
public static bool IsDebugBuild => is_debug_build.Value;
private static readonly Lazy<bool> is_debug_build = new Lazy<bool>(() =>
// https://stackoverflow.com/a/2186634
Assembly.GetExecutingAssembly().GetCustomAttributes(false).OfType<DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled)
);
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace osu.Framework.Development
{
public static class DebugUtils
{
public static bool IsDebugBuild => is_debug_build.Value;
private static readonly Lazy<bool> is_debug_build = new Lazy<bool>(() => Assembly.GetExecutingAssembly().GetCustomAttributes(false).OfType<DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled));
}
}
| mit | C# |
76e23d0ebf4e6bb7368bf0b7d0319c527831ca17 | Make FineAmount in the Setting Class nullable. | Programazing/Open-School-Library,Programazing/Open-School-Library | src/Open-School-Library/Models/DatabaseModels/Setting.cs | src/Open-School-Library/Models/DatabaseModels/Setting.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.DatabaseModels
{
public class Setting
{
public int SettingID { get; set; }
[Column(TypeName = "Money")]
public decimal? FineAmount { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.DatabaseModels
{
public class Setting
{
public int SettingID { get; set; }
[Column(TypeName = "Money")]
public decimal FineAmount { get; set; }
}
}
| mit | C# |
5e787c3672d215a34c2754a9122fde8d63a3c990 | Handle broken ItemFinishedEvent error field | canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor | src/SyncTrayzor/SyncThing/ApiClient/ItemFinishedEvent.cs | src/SyncTrayzor/SyncThing/ApiClient/ItemFinishedEvent.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SyncTrayzor.SyncThing.ApiClient
{
public class ItemFinishedEventData
{
[JsonProperty("item")]
public string Item { get; set; }
[JsonProperty("folder")]
public string Folder { get; set; }
// Irritatingly, 'error' is currently a structure containing an 'Err' property,
// but in the future may just become a string....
[JsonProperty("error")]
public JToken ErrorRaw { get; set; }
public string Error
{
get
{
if (this.ErrorRaw == null)
return null;
if (this.ErrorRaw.Type == JTokenType.String)
return (string)this.ErrorRaw;
if (this.ErrorRaw.Type == JTokenType.Object)
return (string)((JObject)this.ErrorRaw)["Err"];
return null;
}
}
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("action")]
public string Action { get; set; }
}
public class ItemFinishedEvent : Event
{
[JsonProperty("data")]
public ItemFinishedEventData Data { get; set; }
public override void Visit(IEventVisitor visitor)
{
visitor.Accept(this);
}
public override string ToString()
{
return String.Format("<ItemFinished ID={0} Time={1} Item={2} Folder={3} Error={4}>", this.Id, this.Time, this.Data.Item, this.Data.Folder, this.Data.Error);
}
}
}
| using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SyncTrayzor.SyncThing.ApiClient
{
public class ItemFinishedEventData
{
[JsonProperty("item")]
public string Item { get; set; }
[JsonProperty("folder")]
public string Folder { get; set; }
[JsonProperty("error")]
public string Error { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("action")]
public string Action { get; set; }
}
public class ItemFinishedEvent : Event
{
[JsonProperty("data")]
public ItemFinishedEventData Data { get; set; }
public override void Visit(IEventVisitor visitor)
{
visitor.Accept(this);
}
public override string ToString()
{
return String.Format("<ItemFinished ID={0} Time={1} Item={2} Folder={3} Error={4}>", this.Id, this.Time, this.Data.Item, this.Data.Folder, this.Data.Error);
}
}
}
| mit | C# |
5606703ddeddde4aba602f7f7b887ad64516b97e | change to use Console logger | MindTouch/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,meebey/ServiceStack,ZocDoc/ServiceStack,ZocDoc/ServiceStack,NServiceKit/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,timba/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,timba/NServiceKit,NServiceKit/NServiceKit,meebey/ServiceStack,timba/NServiceKit,NServiceKit/NServiceKit | ServiceStack.Examples/ServiceStack.Examples.Host.Web/AppHost.cs | ServiceStack.Examples/ServiceStack.Examples.Host.Web/AppHost.cs | using System;
using Funq;
using ServiceStack.CacheAccess;
using ServiceStack.CacheAccess.Providers;
using ServiceStack.Common.Utils;
using ServiceStack.Configuration;
using ServiceStack.DataAccess;
using ServiceStack.Examples.ServiceInterface;
using ServiceStack.Examples.ServiceInterface.Support;
using ServiceStack.Logging;
using ServiceStack.Logging.Support.Logging;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;
using ServiceStack.Redis;
using ServiceStack.WebHost.Endpoints;
namespace ServiceStack.Examples.Host.Web
{
/// <summary>
/// An example of a AppHost to have your services running inside a webserver.
/// </summary>
public class AppHost
: AppHostBase
{
private static ILog log;
public AppHost()
: base("ServiceStack Examples", typeof(GetFactorialService).Assembly)
{
LogManager.LogFactory = new ConsoleLogFactory();
log = LogManager.GetLogger(typeof (AppHost));
}
public override void Configure(Container container)
{
//Signal advanced web browsers what HTTP Methods you accept
base.SetConfig(new EndpointHostConfig
{
GlobalResponseHeaders =
{
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
},
});
container.Register<IResourceManager>(new ConfigurationResourceManager());
container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>()));
var appConfig = container.Resolve<ExampleConfig>();
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(
appConfig.ConnectionString.MapHostAbsolutePath(),
SqliteOrmLiteDialectProvider.Instance));
ConfigureDatabase.Init(container.Resolve<IDbConnectionFactory>());
//register different cache implementations depending on availability
const bool hasRedis = false;
if (hasRedis)
container.Register<ICacheClient>(c => new BasicRedisClientManager());
else
container.Register<ICacheClient>(c => new MemoryCacheClient());
log.InfoFormat("AppHost Configured: " + DateTime.Now);
}
}
} | using System;
using Funq;
using ServiceStack.CacheAccess;
using ServiceStack.CacheAccess.Providers;
using ServiceStack.Common.Utils;
using ServiceStack.Configuration;
using ServiceStack.DataAccess;
using ServiceStack.Examples.ServiceInterface;
using ServiceStack.Examples.ServiceInterface.Support;
using ServiceStack.Logging;
using ServiceStack.Logging.Support.Logging;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;
using ServiceStack.Redis;
using ServiceStack.WebHost.Endpoints;
namespace ServiceStack.Examples.Host.Web
{
/// <summary>
/// An example of a AppHost to have your services running inside a webserver.
/// </summary>
public class AppHost
: AppHostBase
{
private static ILog log;
public AppHost()
: base("ServiceStack Examples", typeof(GetFactorialService).Assembly)
{
LogManager.LogFactory = new DebugLogFactory();
log = LogManager.GetLogger(typeof (AppHost));
}
public override void Configure(Container container)
{
//Signal advanced web browsers what HTTP Methods you accept
base.SetConfig(new EndpointHostConfig
{
GlobalResponseHeaders =
{
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
},
});
container.Register<IResourceManager>(new ConfigurationResourceManager());
container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>()));
var appConfig = container.Resolve<ExampleConfig>();
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(
appConfig.ConnectionString.MapHostAbsolutePath(),
SqliteOrmLiteDialectProvider.Instance));
ConfigureDatabase.Init(container.Resolve<IDbConnectionFactory>());
//register different cache implementations depending on availability
const bool hasRedis = false;
if (hasRedis)
container.Register<ICacheClient>(c => new BasicRedisClientManager());
else
container.Register<ICacheClient>(c => new MemoryCacheClient());
log.InfoFormat("AppHost Configured: " + DateTime.Now);
}
}
} | bsd-3-clause | C# |
60aec44c57c68bae7c10772492b9ed97c31acb8d | Use string in stead of HashSet - much faster | MortenHoustonLudvigsen/CommonMarkSharp,binki/CommonMarkSharp,MortenHoustonLudvigsen/CommonMarkSharp | CommonMarkSharp/InlineParsers/AnyParser.cs | CommonMarkSharp/InlineParsers/AnyParser.cs | using CommonMarkSharp.Blocks;
using CommonMarkSharp.Inlines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CommonMarkSharp.InlineParsers
{
public class AnyParser : IParser<InlineString>
{
public AnyParser(string significantChars)
{
SignificantChars = significantChars;
}
public string SignificantChars { get; private set; }
public string StartsWithChars { get { return null; } }
public InlineString Parse(ParserContext context, Subject subject)
{
if (SignificantChars != null)
{
var chars = subject.TakeWhile(c => !SignificantChars.Contains(c));
if (chars.Any())
{
return new InlineString(chars);
}
}
return new InlineString(subject.Take());
}
}
}
| using CommonMarkSharp.Blocks;
using CommonMarkSharp.Inlines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonMarkSharp.InlineParsers
{
public class AnyParser : IParser<InlineString>
{
public AnyParser(string significantChars)
{
SignificantChars = string.IsNullOrEmpty(significantChars) ? new HashSet<char>(significantChars) : null;
}
public HashSet<char> SignificantChars { get; private set; }
public string StartsWithChars { get { return null; } }
public InlineString Parse(ParserContext context, Subject subject)
{
if (SignificantChars != null)
{
var chars = subject.TakeWhile(c => !SignificantChars.Contains(c));
if (chars.Any())
{
return new InlineString(chars);
}
}
return new InlineString(subject.Take());
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.