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 |
|---|---|---|---|---|---|---|---|---|
a53da81800327b4d09fb98729acd6f72997f6799
|
fix the filtering
|
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
|
src/Firehose.Web/Extensions/SyndicationItemExtensions.cs
|
src/Firehose.Web/Extensions/SyndicationItemExtensions.cs
|
using System.Linq;
using System.ServiceModel.Syndication;
namespace Firehose.Web.Extensions
{
public static class SyndicationItemExtensions
{
public static bool ApplyDefaultFilter(this SyndicationItem item)
{
var hasPowerShellCategory = false;
var hasPowerShellKeywords = false;
if (item.Categories.Count > 0)
{
hasPowerShellCategory = item.Categories.Any(category =>
category.Name.ToLowerInvariant().Contains("powershell"));
}
if (item.ElementExtensions.Count > 0)
{
var element = item.ElementExtensions.FirstOrDefault(e => e.OuterName == "keywords");
if (element != null)
{
var keywords = element.GetObject<string>();
hasPowerShellKeywords = keywords.ToLowerInvariant().Contains("powershell");
}
}
var hasPowerShellTitle = item.Title?.Text.ToLowerInvariant().Contains("powershell") ?? false;
return hasPowerShellTitle || hasPowerShellCategory || hasPowerShellKeywords;
}
}
}
|
using System.Linq;
using System.ServiceModel.Syndication;
namespace Firehose.Web.Extensions
{
public static class SyndicationItemExtensions
{
public static bool ApplyDefaultFilter(this SyndicationItem item)
{
var hasXamarinCategory = false;
var hasXamarinKeywords = false;
if (item.Categories.Count > 0)
{
hasXamarinCategory = item.Categories.Any(category =>
category.Name.ToLowerInvariant().Contains("xamarin"));
}
if (item.ElementExtensions.Count > 0)
{
var element = item.ElementExtensions.FirstOrDefault(e => e.OuterName == "keywords");
if (element != null)
{
var keywords = element.GetObject<string>();
hasXamarinKeywords = keywords.ToLowerInvariant().Contains("xamarin");
}
}
var hasXamarinTitle = item.Title?.Text.ToLowerInvariant().Contains("xamarin") ?? false;
return hasXamarinTitle || hasXamarinCategory || hasXamarinKeywords;
}
}
}
|
mit
|
C#
|
4503596cc478345f10a60528fa6b118d27d6e9f1
|
Make PR status visible when GitSccProvider is loaded
|
github/VisualStudio,github/VisualStudio,github/VisualStudio
|
src/GitHub.InlineReviews/PullRequestStatusPackage.cs
|
src/GitHub.InlineReviews/PullRequestStatusPackage.cs
|
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.ComponentModelHost;
using GitHub.VisualStudio;
using GitHub.InlineReviews.Services;
namespace GitHub.InlineReviews
{
[PackageRegistration(UseManagedResourcesOnly = true)]
[Guid(Guids.PullRequestStatusPackageId)]
[ProvideAutoLoad(Guids.GitSccProviderId)]
public class PullRequestStatusPackage : Package
{
protected override void Initialize()
{
var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
var exportProvider = componentModel.DefaultExportProvider;
var pullRequestStatusManager = exportProvider.GetExportedValue<IPullRequestStatusManager>();
pullRequestStatusManager.Initialize();
}
}
}
|
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.ComponentModelHost;
using GitHub.VisualStudio;
using GitHub.InlineReviews.Services;
namespace GitHub.InlineReviews
{
[PackageRegistration(UseManagedResourcesOnly = true)]
[Guid(Guids.PullRequestStatusPackageId)]
[ProvideAutoLoad(UIContextGuids80.SolutionExists)]
public class PullRequestStatusPackage : Package
{
protected override void Initialize()
{
var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
var exportProvider = componentModel.DefaultExportProvider;
var pullRequestStatusManager = exportProvider.GetExportedValue<IPullRequestStatusManager>();
pullRequestStatusManager.Initialize();
}
}
}
|
mit
|
C#
|
b1a2aa29d870c9f370ab100d206b26e8d124c5eb
|
Fix FuncMultiValueConverter.
|
wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,susloparovdenis/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,punker76/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,OronDF343/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jazzay/Perspex,OronDF343/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,susloparovdenis/Perspex,akrisiun/Perspex,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,MrDaedra/Avalonia,susloparovdenis/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,kekekeks/Perspex,MrDaedra/Avalonia,susloparovdenis/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,kekekeks/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia
|
src/Markup/Perspex.Markup/FuncMultiValueConverter.cs
|
src/Markup/Perspex.Markup/FuncMultiValueConverter.cs
|
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Perspex.Markup
{
/// <summary>
/// A general purpose <see cref="IValueConverter"/> that uses a <see cref="Func{T1, TResult}"/>
/// to provide the converter logic.
/// </summary>
/// <typeparam name="TIn">The type of the inputs.</typeparam>
/// <typeparam name="TOut">The output type.</typeparam>
public class FuncMultiValueConverter<TIn, TOut> : IMultiValueConverter
{
private Func<IEnumerable<TIn>, TOut> _convert;
/// <summary>
/// Initializes a new instance of the <see cref="FuncValueConverter{TIn, TOut}"/> class.
/// </summary>
/// <param name="convert">The convert function.</param>
public FuncMultiValueConverter(Func<IEnumerable<TIn>, TOut> convert)
{
_convert = convert;
}
/// <inheritdoc/>
public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture)
{
var converted = values.OfType<TIn>().ToList();
if (converted.Count == values.Count)
{
return _convert(converted);
}
else
{
return PerspexProperty.UnsetValue;
}
}
}
}
|
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Perspex.Markup
{
/// <summary>
/// A general purpose <see cref="IValueConverter"/> that uses a <see cref="Func{T1, TResult}"/>
/// to provide the converter logic.
/// </summary>
/// <typeparam name="TIn">The type of the inputs.</typeparam>
/// <typeparam name="TOut">The output type.</typeparam>
public class FuncMultiValueConverter<TIn, TOut> : IMultiValueConverter
{
private Func<IEnumerable<TIn>, TOut> _convert;
/// <summary>
/// Initializes a new instance of the <see cref="FuncValueConverter{TIn, TOut}"/> class.
/// </summary>
/// <param name="convert">The convert function.</param>
public FuncMultiValueConverter(Func<IEnumerable<TIn>, TOut> convert)
{
_convert = convert;
}
/// <inheritdoc/>
public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture)
{
return _convert(values.Cast<TIn>());
}
}
}
|
mit
|
C#
|
e53010ec8c86be50fd4addc23577e89f702c63b7
|
remove json serialization for fastlogger
|
fabiocav/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script
|
src/WebJobs.Script.WebHost/Diagnostics/FastLogger.cs
|
src/WebJobs.Script.WebHost/Diagnostics/FastLogger.cs
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Loggers;
using Microsoft.Azure.WebJobs.Logging;
using Microsoft.WindowsAzure.Storage;
using Newtonsoft.Json;
namespace Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics
{
// Adapter for capturing SDK events and logging them to tables.
internal class FastLogger : IAsyncCollector<FunctionInstanceLogEntry>
{
private readonly ILogWriter _writer;
public FastLogger(string hostName, string accountConnectionString)
{
CloudStorageAccount account = CloudStorageAccount.Parse(accountConnectionString);
var client = account.CreateCloudTableClient();
var tableProvider = LogFactory.NewLogTableProvider(client);
string containerName = Environment.MachineName;
this._writer = LogFactory.NewWriter(hostName, containerName, tableProvider);
}
public async Task AddAsync(FunctionInstanceLogEntry item, CancellationToken cancellationToken = default(CancellationToken))
{
await _writer.AddAsync(new FunctionInstanceLogItem
{
FunctionInstanceId = item.FunctionInstanceId,
FunctionName = Utility.GetFunctionShortName(item.FunctionName),
StartTime = item.StartTime,
EndTime = item.EndTime,
TriggerReason = item.TriggerReason,
Arguments = item.Arguments,
ErrorDetails = item.ErrorDetails,
LogOutput = item.LogOutput,
ParentId = item.ParentId
});
}
public Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _writer.FlushAsync();
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Loggers;
using Microsoft.Azure.WebJobs.Logging;
using Microsoft.WindowsAzure.Storage;
using Newtonsoft.Json;
namespace Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics
{
// Adapter for capturing SDK events and logging them to tables.
internal class FastLogger : IAsyncCollector<FunctionInstanceLogEntry>
{
private readonly ILogWriter _writer;
public FastLogger(string hostName, string accountConnectionString)
{
CloudStorageAccount account = CloudStorageAccount.Parse(accountConnectionString);
var client = account.CreateCloudTableClient();
var tableProvider = LogFactory.NewLogTableProvider(client);
string containerName = Environment.MachineName;
this._writer = LogFactory.NewWriter(hostName, containerName, tableProvider);
}
public async Task AddAsync(FunctionInstanceLogEntry item, CancellationToken cancellationToken = default(CancellationToken))
{
// Convert Host to Protocol so we can log it
var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
var jsonClone = JsonConvert.SerializeObject(item, settings);
var item2 = JsonConvert.DeserializeObject<FunctionInstanceLogItem>(jsonClone);
item2.FunctionName = Utility.GetFunctionShortName(item2.FunctionName);
await _writer.AddAsync(item2);
}
public Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _writer.FlushAsync();
}
}
}
|
mit
|
C#
|
b6b697441c140c4a4ba05b21f5701cc6a67dfbd3
|
Change to correct using namespace for ServiceBrokerListener
|
Siliconrob/ServiceBrokerListener,dyatchenko/ServiceBrokerListener,dyatchenko/ServiceBrokerListener,dyatchenko/ServiceBrokerListener,Siliconrob/ServiceBrokerListener
|
ServiceBrokerListener/ServiceBrokerListener.Tablelistener.Core/Program.cs
|
ServiceBrokerListener/ServiceBrokerListener.Tablelistener.Core/Program.cs
|
using CommandLine;
using ServiceBrokerListener.Domain;
using System;
using System.Diagnostics;
using System.Threading;
namespace ServiceBrokerListener.TableListener.Core
{
public class Program
{
public static void Main(string[] args)
{
var options = new Options();
var result = Parser.Default.ParseArguments<Options>(args)
.WithParsed(opts => options = opts);
if (result.Tag == ParserResultType.Parsed)
{
Run(options);
}
DebugMode();
}
private static void DisplayPrompt(Options args)
{
Console.Write("Connected to ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("{0}", args.ConnectionString);
Console.ResetColor();
Console.Write("Database ");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("{0}", args.Database);
Console.ResetColor();
Console.Write("Watching changes on table ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("{0}", args.Table);
Console.ResetColor();
Console.WriteLine("Waiting for 'x' to end or data to be received");
}
private static void Run(Options args)
{
var listener = new SqlDependencyEx(args.ConnectionString, args.Database, args.Table);
listener.TableChanged += ListenerOnTableChanged;
listener.Start();
DisplayPrompt(args);
do
{
Thread.Sleep(100);
} while (Console.ReadKey().KeyChar != 'x');
listener.Stop();
}
private static void ListenerOnTableChanged(object sender, SqlDependencyEx.TableChangedEventArgs tableChangedEventArgs)
{
Console.WriteLine("EventType: {0}", tableChangedEventArgs.NotificationType);
Console.WriteLine("Data: {0}", tableChangedEventArgs.Data);
}
private static void DebugMode()
{
if (!Debugger.IsAttached)
{
return;
}
Console.WriteLine($"{Environment.NewLine}Waiting because debugger is attached");
Console.WriteLine("Press enter key to end");
Console.ReadLine();
}
}
}
|
using CommandLine;
using ServiceBrokerListener.Domain.Core;
using System;
using System.Diagnostics;
using System.Threading;
namespace ServiceBrokerListener.TableListener.Core
{
public class Program
{
public static void Main(string[] args)
{
var options = new Options();
var result = Parser.Default.ParseArguments<Options>(args)
.WithParsed(opts => options = opts);
if (result.Tag == ParserResultType.Parsed)
{
Run(options);
}
DebugMode();
}
private static void DisplayPrompt(Options args)
{
Console.Write("Connected to ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("{0}", args.ConnectionString);
Console.ResetColor();
Console.Write("Database ");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("{0}", args.Database);
Console.ResetColor();
Console.Write("Watching changes on table ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("{0}", args.Table);
Console.ResetColor();
Console.WriteLine("Waiting for 'x' to end or data to be received");
}
private static void Run(Options args)
{
var listener = new SqlDependencyEx(args.ConnectionString, args.Database, args.Table);
listener.TableChanged += ListenerOnTableChanged;
listener.Start();
DisplayPrompt(args);
do
{
Thread.Sleep(100);
} while (Console.ReadKey().KeyChar != 'x');
listener.Stop();
}
private static void ListenerOnTableChanged(object sender, SqlDependencyEx.TableChangedEventArgs tableChangedEventArgs)
{
Console.WriteLine("EventType: {0}", tableChangedEventArgs.NotificationType);
Console.WriteLine("Data: {0}", tableChangedEventArgs.Data);
}
private static void DebugMode()
{
if (!Debugger.IsAttached)
{
return;
}
Console.WriteLine($"{Environment.NewLine}Waiting because debugger is attached");
Console.WriteLine("Press enter key to end");
Console.ReadLine();
}
}
}
|
mit
|
C#
|
9d243eb6d5c0849fd266a4c6f9b64f4aa03f7f01
|
Add unit tests for enum sync history action type read and write.
|
henrikfroehling/TraktApiSharp
|
Source/Tests/TraktApiSharp.Tests/Enums/TraktSyncHistoryActionTypeTests.cs
|
Source/Tests/TraktApiSharp.Tests/Enums/TraktSyncHistoryActionTypeTests.cs
|
namespace TraktApiSharp.Tests.Enums
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using TraktApiSharp.Enums;
[TestClass]
public class TraktSyncHistoryActionTypeTests
{
class TestObject
{
[JsonConverter(typeof(TraktSyncHistoryActionTypeConverter))]
public TraktSyncHistoryActionType Value { get; set; }
}
[TestMethod]
public void TestTraktSyncHistoryActionTypeHasMembers()
{
typeof(TraktSyncHistoryActionType).GetEnumNames().Should().HaveCount(4)
.And.Contain("Unspecified", "Scrobble", "Checkin", "Watch");
}
[TestMethod]
public void TestTraktSyncHistoryActionTypeGetAsString()
{
TraktSyncHistoryActionType.Unspecified.AsString().Should().NotBeNull().And.BeEmpty();
TraktSyncHistoryActionType.Scrobble.AsString().Should().Be("scrobble");
TraktSyncHistoryActionType.Checkin.AsString().Should().Be("checkin");
TraktSyncHistoryActionType.Watch.AsString().Should().Be("watch");
}
[TestMethod]
public void TestTraktSyncHistoryActionTypeWriteAndReadJson_Scrobble()
{
var obj = new TestObject { Value = TraktSyncHistoryActionType.Scrobble };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktSyncHistoryActionType.Scrobble);
}
[TestMethod]
public void TestTraktSyncHistoryActionTypeWriteAndReadJson_Checkin()
{
var obj = new TestObject { Value = TraktSyncHistoryActionType.Checkin };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktSyncHistoryActionType.Checkin);
}
[TestMethod]
public void TestTraktSyncHistoryActionTypeWriteAndReadJson_Watch()
{
var obj = new TestObject { Value = TraktSyncHistoryActionType.Watch };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktSyncHistoryActionType.Watch);
}
[TestMethod]
public void TestTraktSyncHistoryActionTypeWriteAndReadJson_Unspecified()
{
var obj = new TestObject { Value = TraktSyncHistoryActionType.Unspecified };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktSyncHistoryActionType.Unspecified);
}
}
}
|
namespace TraktApiSharp.Tests.Enums
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Enums;
[TestClass]
public class TraktSyncHistoryActionTypeTests
{
[TestMethod]
public void TestTraktSyncHistoryActionTypeHasMembers()
{
typeof(TraktSyncHistoryActionType).GetEnumNames().Should().HaveCount(4)
.And.Contain("Unspecified", "Scrobble", "Checkin", "Watch");
}
[TestMethod]
public void TestTraktSyncHistoryActionTypeGetAsString()
{
TraktSyncHistoryActionType.Unspecified.AsString().Should().NotBeNull().And.BeEmpty();
TraktSyncHistoryActionType.Scrobble.AsString().Should().Be("scrobble");
TraktSyncHistoryActionType.Checkin.AsString().Should().Be("checkin");
TraktSyncHistoryActionType.Watch.AsString().Should().Be("watch");
}
}
}
|
mit
|
C#
|
f1649585bbe4fd4bc92742d1e4acf4d5da05c315
|
remove doc links that still point at wrong location
|
IBM-Bluemix/asp.net5-cloudant,IBM-Bluemix/asp.net5-cloudant
|
src/dotnetCloudantWebstarter/Views/Home/Index.cshtml
|
src/dotnetCloudantWebstarter/Views/Home/Index.cshtml
|
<!DOCTYPE html>
<html>
<head>
<title>ASP.NET 5 Cloudant Starter Application</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<link rel="stylesheet" href="~/css/style.css" />
</head>
<body>
<div class="leftHalf">
<img class="newappIcon" src="~/images/newapp-icon.png" />
<h1>
Welcome to the <span class="blue">.NET Cloudant Web Starter</span> on Bluemix!
</h1>
<p class="description">To get started see the Start Coding guide under your app in your dashboard.</p>
</div>
<div class="rightHalf">
<div class="center">
<header>
<div class='title'>
.NET Cloudant Web Starter
</div>
</header>
<table id='notes' class='records'><tbody></tbody></table>
<div id="loading"> Please wait while the database is being initialized ...</div>
<footer>
<div class='tips'>
Click the Add button to add a record.
<button class='addBtn' onclick="addItem()" title='add record'>
<img src='~/images/add.png' alt='add' />
</button>
</div>
</footer>
<script type="text/javascript" src="~/scripts/util.js"></script>
<script type="text/javascript" src="~/scripts/index.js"></script>
</div>
</div>
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<title>ASP.NET 5 Cloudant Starter Application</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<link rel="stylesheet" href="~/css/style.css" />
</head>
<body>
<div class="leftHalf">
<img class="newappIcon" src="~/images/newapp-icon.png" />
<h1>
Welcome to the <span class="blue">.NET Cloudant Web Starter</span> on Bluemix!
</h1>
<p class="description">Get started by reading our <a href="https://www.ng.bluemix.net/docs/#">documentation</a> or use the Start Coding guide under your app in your dashboard.</p>
</div>
<div class="rightHalf">
<div class="center">
<header>
<div class='title'>
.NET Cloudant Web Starter
</div>
</header>
<table id='notes' class='records'><tbody></tbody></table>
<div id="loading"> Please wait while the database is being initialized ...</div>
<footer>
<div class='tips'>
Click the Add button to add a record.
<button class='addBtn' onclick="addItem()" title='add record'>
<img src='~/images/add.png' alt='add' />
</button>
</div>
</footer>
<script type="text/javascript" src="~/scripts/util.js"></script>
<script type="text/javascript" src="~/scripts/index.js"></script>
</div>
</div>
</body>
</html>
|
apache-2.0
|
C#
|
291894ae0be718cea30474413e874d230aa484a8
|
Use Interlocked instead of CountdownEvent.
|
rubenv/tripod,rubenv/tripod
|
src/Core/Tripod.Core/Tripod.Tasks/RefCountCancellableTask.cs
|
src/Core/Tripod.Core/Tripod.Tasks/RefCountCancellableTask.cs
|
//
// RefCountCancellableTask.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch
//
// 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.Threading;
using System.Threading.Tasks;
namespace Tripod.Tasks
{
public class RefCountCancellableTask<T> : CancellableTask<T>
{
public RefCountCancellableTask (Func<T> function, CancellationTokenSource source) : base(function, source)
{
}
int count = 0;
public override void Cancel ()
{
if (IsCompleted || IsCanceled)
return;
bool should_cancel = false;
lock (this) {
if (count > 0 && Interlocked.Decrement (ref count) == 0 && !IsCompleted)
should_cancel = true;
}
if (should_cancel) {
try {
base.Cancel ();
} catch (TaskCanceledException) { }
}
}
public void Request ()
{
Interlocked.Increment (ref count);
}
}
}
|
//
// RefCountCancellableTask.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch
//
// 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.Threading;
using System.Threading.Tasks;
namespace Tripod.Tasks
{
public class RefCountCancellableTask<T> : CancellableTask<T>
{
public RefCountCancellableTask (Func<T> function, CancellationTokenSource source) : base(function, source)
{
CancellationEvent = new CountdownEvent (0);
}
CountdownEvent CancellationEvent { get; set; }
public override void Cancel ()
{
if (IsCompleted || IsCanceled)
return;
if (CancellationEvent.Signal ()) {
base.Cancel ();
}
}
public void Request ()
{
CancellationEvent.AddCount ();
}
}
}
|
mit
|
C#
|
5bfbf2e3d930f417cea6fc4004c93ede44619ea6
|
Fix a bug
|
CodeComb/Localization,CodeComb/Localization
|
src/CodeComb.AspNet.Localization/CookieRequestCultureProvider.cs
|
src/CodeComb.AspNet.Localization/CookieRequestCultureProvider.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
namespace CodeComb.AspNet.Localization
{
public class CookieRequestCultureProvider : IRequestCultureProvider
{
public HttpContext HttpContext { get; set; }
public string CookieField { get; set; }
public CookieRequestCultureProvider(IHttpContextAccessor httpContextAccessor, string CookieField = "ASPNET_LANG")
{
this.CookieField = CookieField;
HttpContext = httpContextAccessor.HttpContext;
}
public string[] DetermineRequestCulture()
{
if (HttpContext.Request.Cookies[CookieField].Count == 0)
{
var ret = new List<string>();
var tmp = HttpContext.Request.Headers["Accept-Language"].FirstOrDefault();
if (tmp == null)
return new string[] { };
var split = tmp.Split(',');
foreach(var x in split)
{
ret.Add(x.Split(';')[0]);
}
return ret.ToArray();
}
else
{
return new string[] { HttpContext.Request.Cookies[CookieField].ToString() };
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
namespace CodeComb.AspNet.Localization
{
public class CookieRequestCultureProvider : IRequestCultureProvider
{
public HttpContext HttpContext { get; set; }
public string CookieField { get; set; }
public CookieRequestCultureProvider(IHttpContextAccessor httpContextAccessor, string CookieField = "ASPNET_LANG")
{
this.CookieField = CookieField;
HttpContext = httpContextAccessor.HttpContext;
}
public string[] DetermineRequestCulture()
{
if (HttpContext.Request.Cookies[CookieField].Count > 0)
{
var ret = new List<string>();
var tmp = HttpContext.Request.Headers["Accept-Language"].FirstOrDefault();
if (tmp == null)
return new string[] { };
var split = tmp.Split(',');
foreach(var x in split)
{
ret.Add(x.Split(';')[0]);
}
return ret.ToArray();
}
else
{
return new string[] { HttpContext.Request.Cookies[CookieField].ToString() };
}
}
}
}
|
apache-2.0
|
C#
|
fd43f902f3292a74d11a292446de0646cd8c80d1
|
clean up
|
ramzzzay/CoolShop,ramzzzay/CoolShop,ramzzzay/CoolShop
|
CoolShop/Infrastructure/NinjectControllerFactory.cs
|
CoolShop/Infrastructure/NinjectControllerFactory.cs
|
using System;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
namespace CoolShop.Infrastructure
{
public class NinjectControllerFactory : DefaultControllerFactory
{
private readonly IKernel ninjectKernel;
public NinjectControllerFactory()
{
// создание контейнера
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{
// получение объекта контроллера из контейнера
// используя его тип
return controllerType == null
? null
: (IController) ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
// конфигурирование контейнера
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
namespace CoolShop.Infrastructure
{
public class NinjectControllerFactory : DefaultControllerFactory
{
private readonly IKernel ninjectKernel;
public NinjectControllerFactory()
{
// создание контейнера
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{
// получение объекта контроллера из контейнера
// используя его тип
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
// конфигурирование контейнера
}
}
}
|
apache-2.0
|
C#
|
7fbe4829196d7f131a4bb5e9a6d8263b25eda8a4
|
Revert "https://github.com/umbraco/Umbraco-CMS/issues/7469 - Fixed Ambiguous extension method issue by renaming our extension method from Value to GetValue"
|
JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,NikRimington/Umbraco-CMS,mattbrailsford/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS
|
src/Umbraco.ModelsBuilder.Embedded/PublishedElementExtensions.cs
|
src/Umbraco.ModelsBuilder.Embedded/PublishedElementExtensions.cs
|
using System;
using System.Linq.Expressions;
using System.Reflection;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.ModelsBuilder;
using Umbraco.ModelsBuilder.Embedded;
// same namespace as original Umbraco.Web PublishedElementExtensions
// ReSharper disable once CheckNamespace
namespace Umbraco.Web
{
/// <summary>
/// Provides extension methods to models.
/// </summary>
public static class PublishedElementExtensions
{
/// <summary>
/// Gets the value of a property.
/// </summary>
public static TValue Value<TModel, TValue>(this TModel model, Expression<Func<TModel, TValue>> property, string culture = null, string segment = null, Fallback fallback = default, TValue defaultValue = default)
where TModel : IPublishedElement
{
var alias = GetAlias(model, property);
return model.Value<TValue>(alias, culture, segment, fallback, defaultValue);
}
// fixme that one should be public so ppl can use it
private static string GetAlias<TModel, TValue>(TModel model, Expression<Func<TModel, TValue>> property)
{
if (property.NodeType != ExpressionType.Lambda)
throw new ArgumentException("Not a proper lambda expression (lambda).", nameof(property));
var lambda = (LambdaExpression) property;
var lambdaBody = lambda.Body;
if (lambdaBody.NodeType != ExpressionType.MemberAccess)
throw new ArgumentException("Not a proper lambda expression (body).", nameof(property));
var memberExpression = (MemberExpression) lambdaBody;
if (memberExpression.Expression.NodeType != ExpressionType.Parameter)
throw new ArgumentException("Not a proper lambda expression (member).", nameof(property));
var member = memberExpression.Member;
var attribute = member.GetCustomAttribute<ImplementPropertyTypeAttribute>();
if (attribute == null)
throw new InvalidOperationException("Property is not marked with ImplementPropertyType attribute.");
return attribute.Alias;
}
}
}
|
using System;
using System.Linq.Expressions;
using System.Reflection;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.ModelsBuilder;
using Umbraco.ModelsBuilder.Embedded;
// same namespace as original Umbraco.Web PublishedElementExtensions
// ReSharper disable once CheckNamespace
namespace Umbraco.Web
{
/// <summary>
/// Provides extension methods to models.
/// </summary>
public static class PublishedElementExtensions
{
/// <summary>
/// Gets the value of a property.
/// </summary>
public static TValue ValueByExpression<TModel, TValue>(this TModel model, Expression<Func<TModel, TValue>> property, string culture = null, string segment = null, Fallback fallback = default, TValue defaultValue = default)
where TModel : IPublishedElement
{
var alias = GetAlias(model, property);
return model.Value<TValue>(alias, culture, segment, fallback, defaultValue);
}
//This cannot be public due to ambiguous issue with external ModelsBuilder if we do not rename.
private static string GetAlias<TModel, TValue>(TModel model, Expression<Func<TModel, TValue>> property)
{
if (property.NodeType != ExpressionType.Lambda)
throw new ArgumentException("Not a proper lambda expression (lambda).", nameof(property));
var lambda = (LambdaExpression) property;
var lambdaBody = lambda.Body;
if (lambdaBody.NodeType != ExpressionType.MemberAccess)
throw new ArgumentException("Not a proper lambda expression (body).", nameof(property));
var memberExpression = (MemberExpression) lambdaBody;
if (memberExpression.Expression.NodeType != ExpressionType.Parameter)
throw new ArgumentException("Not a proper lambda expression (member).", nameof(property));
var member = memberExpression.Member;
var attribute = member.GetCustomAttribute<ImplementPropertyTypeAttribute>();
if (attribute == null)
throw new InvalidOperationException("Property is not marked with ImplementPropertyType attribute.");
return attribute.Alias;
}
}
}
|
mit
|
C#
|
d2867d7135f99843691c5c62d9985a834b2a97e6
|
fix tests
|
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
|
Rest/NakedObjects.Rest.Test.Data/WithAttachments.cs
|
Rest/NakedObjects.Rest.Test.Data/WithAttachments.cs
|
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System.ComponentModel.DataAnnotations;
using NakedObjects;
using NakedObjects.Value;
namespace RestfulObjects.Test.Data {
public class WithAttachments {
private byte[] attachment = {};
[Key, Title, ConcurrencyCheck]
public virtual int Id { get; set; }
[NakedObjectsIgnore]
public virtual byte[] Attachment {
get { return attachment; }
set { attachment = value; }
}
public virtual FileAttachment FileAttachment {
get { return new FileAttachment(attachment, "afile", "application/pdf"); }
}
public virtual Image Image {
get { return new Image(attachment, "animage", "image/jpeg"); }
}
public virtual Image ImageWithDefault {
get { return new Image(attachment, "animage.gif"); }
}
}
}
|
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System.ComponentModel.DataAnnotations;
using NakedObjects;
using NakedObjects.Value;
namespace RestfulObjects.Test.Data {
public class WithAttachments {
private byte[] attachment = {};
[Key, Title, ConcurrencyCheck]
public virtual int Id { get; set; }
[NakedObjectsIgnore]
public virtual byte[] Attachment {
get { return attachment; }
set { attachment = value; }
}
public virtual FileAttachment FileAttachment {
get { return new FileAttachment(attachment, "afile", "application/pdf"); }
}
public virtual Image Image {
get { return new Image(attachment, "animage", "image/jpeg"); }
}
public virtual Image ImageWithDefault {
get { return new Image(attachment, "animage.gif"); }
}
public virtual void PutAttachment(FileAttachment fa) {
attachment = fa.GetResourceAsByteArray();
}
}
}
|
apache-2.0
|
C#
|
109ce470b52504a836f016ed1a2fdb395d647266
|
Update ProcessExtensions.cs
|
Kittyfisto/SharpRemote,Kittyfisto/SharpRemote,Kittyfisto/SharpRemote
|
SharpRemote.Windows/Extensions/ProcessExtensions.cs
|
SharpRemote.Windows/Extensions/ProcessExtensions.cs
|
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace SharpRemote.Extensions
{
internal static class ProcessExtensions
{
public static bool TryKill(int pid)
{
IntPtr handle = IntPtr.Zero;
try
{
handle = NativeMethods.OpenProcess(ProcessAccessFlags.Terminate,
false,
pid);
if (handle == IntPtr.Zero)
{
var err = Marshal.GetLastWin32Error();
return false;
}
if (!NativeMethods.TerminateProcess(handle, 0))
{
var err = Marshal.GetLastWin32Error();
return false;
}
return true;
}
finally
{
NativeMethods.CloseHandle(handle);
}
}
/// <summary>
/// Tries to kill the given process.
/// </summary>
/// <param name="that"></param>
/// <returns>True when the given process has been killed or doesn't live anymore, false otherwise</returns>
public static bool TryKill(this Process that)
{
if (that == null)
return true;
try
{
return TryKill(that.Id);
}
catch(InvalidOperationException)
{
return false;
}
catch(Exception)
{
return false;
}
}
}
}
|
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace SharpRemote.Extensions
{
internal static class ProcessExtensions
{
public static bool TryKill(int pid)
{
IntPtr handle = IntPtr.Zero;
try
{
handle = NativeMethods.OpenProcess(ProcessAccessFlags.Terminate,
false,
pid);
if (handle == IntPtr.Zero)
{
var err = Marshal.GetLastWin32Error();
return false;
}
if (!NativeMethods.TerminateProcess(handle, 0))
{
var err = Marshal.GetLastWin32Error();
return false;
}
return true;
}
finally
{
NativeMethods.CloseHandle(handle);
}
}
/// <summary>
/// Tries to kill the given process.
/// </summary>
/// <param name="that"></param>
/// <returns>True when the given process has been killed or doesn't live anymore, false otherwise</returns>
public static bool TryKill(this Process that)
{
if (that == null)
return true;
return TryKill(that.Id);
}
}
}
|
mit
|
C#
|
2233036127ac68bf29350999e645a1f9650bd781
|
Improve output of data integrity tests to include all failing values
|
sillsdev/Glyssen,sillsdev/Glyssen
|
ControlDataIntegrityTests/CharacterDetailDataTests.cs
|
ControlDataIntegrityTests/CharacterDetailDataTests.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using ProtoScript.Character;
using ProtoScript.Properties;
namespace ControlDataIntegrityTests
{
[TestFixture]
public class CharacterDetailDataTests
{
[Test]
public void DataIntegrity_NoDuplicateLines()
{
string[] allLines = Resources.CharacterVerseData.Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
var set = new HashSet<string>();
foreach (var line in allLines)
{
if (line.StartsWith("#"))
continue;
Assert.IsTrue(set.Add(line), "Duplicate line: " + line);
}
}
[Test]
public void DataIntegrity_AllCharacterIdsAndDefaultCharactersHaveCharacterDetail()
{
IEnumerable<string> charactersHavingDetail = CharacterDetailData.Singleton.GetAll().Select(d => d.Character);
ISet<string> missingCharacters = new HashSet<string>();
ISet<string> missingDefaultCharacters = new HashSet<string>();
foreach (CharacterVerse cv in ControlCharacterVerseData.Singleton.GetAllQuoteInfo())
{
if (!charactersHavingDetail.Contains(cv.Character))
missingCharacters.Add(cv.Character);
if (!(string.IsNullOrEmpty(cv.DefaultCharacter) || charactersHavingDetail.Contains(cv.DefaultCharacter)))
missingDefaultCharacters.Add(cv.DefaultCharacter);
}
Assert.False(missingCharacters.Any() || missingDefaultCharacters.Any(),
"Characters in Character-Verse data but not in Character-Detail:" +
Environment.NewLine +
OnePerLineWithIndent(missingCharacters) +
Environment.NewLine +
"Default characters in Character-Verse data but not in Character-Detail:" +
Environment.NewLine +
OnePerLineWithIndent(missingDefaultCharacters));
}
[Test]
public void DataIntegrity_AllCharacterDetailsHaveCharacterIdOrDefaultCharacter()
{
IEnumerable<string> charactersIds = ControlCharacterVerseData.Singleton.GetAllQuoteInfo().Select(d => d.Character);
IEnumerable<string> defaultCharacters = ControlCharacterVerseData.Singleton.GetAllQuoteInfo().Select(d => d.DefaultCharacter);
ISet<string> missingCharacters = new HashSet<string>();
foreach (string character in CharacterDetailData.Singleton.GetAll().Select(d => d.Character))
if (!(charactersIds.Contains(character) || defaultCharacters.Contains(character)))
missingCharacters.Add(character);
Assert.False(missingCharacters.Any(),
"Characters in Character-Detail data but not in Character-Verse data:" +
Environment.NewLine +
OnePerLineWithIndent(missingCharacters));
}
private string OnePerLineWithIndent(IEnumerable<string> enumerable)
{
var sb = new StringBuilder();
foreach (string item in enumerable)
sb.Append("\t").Append(item).Append(Environment.NewLine);
return sb.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using ProtoScript.Character;
using ProtoScript.Properties;
namespace ControlDataIntegrityTests
{
[TestFixture]
public class CharacterDetailDataTests
{
[Test]
public void DataIntegrity_NoDuplicateLines()
{
string[] allLines = Resources.CharacterVerseData.Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
var set = new HashSet<string>();
foreach (var line in allLines)
{
if (line.StartsWith("#"))
continue;
Assert.IsTrue(set.Add(line), "Duplicate line: " + line);
}
}
[Test]
public void DataIntegrity_AllCharacterIdsAndDefaultCharactersHaveCharacterDetail()
{
IEnumerable<string> charactersHavingDetail = CharacterDetailData.Singleton.GetAll().Select(d => d.Character);
foreach (CharacterVerse cv in ControlCharacterVerseData.Singleton.GetAllQuoteInfo())
{
Assert.True(charactersHavingDetail.Contains(cv.Character),
"Character '" + cv.Character + "' is in Character-Verse data but not in Character-Detail");
Assert.True(string.IsNullOrEmpty(cv.DefaultCharacter) || charactersHavingDetail.Contains(cv.DefaultCharacter),
"Default character '" + cv.DefaultCharacter + "' is in Character-Verse data but not in Character-Detail");
}
}
[Test]
public void DataIntegrity_AllCharacterDetailsHaveCharacterIdOrDefaultCharacter()
{
IEnumerable<string> charactersIds = ControlCharacterVerseData.Singleton.GetAllQuoteInfo().Select(d => d.Character);
IEnumerable<string> defaultCharacters = ControlCharacterVerseData.Singleton.GetAllQuoteInfo().Select(d => d.DefaultCharacter);
foreach (string character in CharacterDetailData.Singleton.GetAll().Select(d => d.Character))
{
Assert.True(charactersIds.Contains(character) || defaultCharacters.Contains(character),
"Character '" + character + "' is in Character-Detail data but not in Character-Verse data");
}
}
}
}
|
mit
|
C#
|
8afb096e575767b5070ee619b8df34f1bcc8d8c6
|
Remove throw from TryGetOption
|
physhi/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,genlu/roslyn,jasonmalinowski/roslyn,physhi/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,reaction1989/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,eriawan/roslyn,eriawan/roslyn,jmarolf/roslyn,brettfo/roslyn,sharwell/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,davkean/roslyn,mavasani/roslyn,diryboy/roslyn,KevinRansom/roslyn,brettfo/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,heejaechang/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,diryboy/roslyn,panopticoncentral/roslyn,gafter/roslyn,tmat/roslyn,sharwell/roslyn,dotnet/roslyn,wvdd007/roslyn,agocke/roslyn,tannergooding/roslyn,agocke/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,agocke/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,genlu/roslyn,gafter/roslyn,tannergooding/roslyn,weltkante/roslyn,aelij/roslyn,sharwell/roslyn,aelij/roslyn,AmadeusW/roslyn,tmat/roslyn,aelij/roslyn,stephentoub/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,genlu/roslyn,gafter/roslyn,mgoertz-msft/roslyn,reaction1989/roslyn,stephentoub/roslyn,wvdd007/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,weltkante/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,brettfo/roslyn,weltkante/roslyn,mavasani/roslyn,panopticoncentral/roslyn,davkean/roslyn,mavasani/roslyn
|
src/Workspaces/Core/Portable/CodeStyle/AnalyzerConfigOptionsExtensions.cs
|
src/Workspaces/Core/Portable/CodeStyle/AnalyzerConfigOptionsExtensions.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis
{
internal static class AnalyzerConfigOptionsExtensions
{
public static bool TryGetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, Option<T> option, out T value)
{
return TryGetOption(analyzerConfigOptions, (IOption)option, out value);
}
public static bool TryGetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption<T> option, out T value)
{
return TryGetOption(analyzerConfigOptions, option, out value);
}
public static bool TryGetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, IOption option, out T value)
{
foreach (var storageLocation in option.StorageLocations)
{
// This code path will avoid allocating a Dictionary wrapper since we can get direct access to the KeyName.
if (storageLocation is EditorConfigStorageLocation<T> editorConfigStorageLocation &&
analyzerConfigOptions.TryGetValue(editorConfigStorageLocation.KeyName, out var stringValue) &&
editorConfigStorageLocation.TryGetOption(stringValue, typeof(T), out value))
{
return true;
}
if (storageLocation is IEditorConfigStorageLocation configStorageLocation &&
configStorageLocation.TryGetOption(analyzerConfigOptions, option.Type, out var objectValue))
{
value = (T)objectValue;
return true;
}
}
value = default;
return false;
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis
{
internal static class AnalyzerConfigOptionsExtensions
{
public static bool TryGetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, Option<T> option, out T value)
{
return TryGetOption(analyzerConfigOptions, (IOption)option, out value);
}
public static bool TryGetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption<T> option, out T value)
{
return TryGetOption(analyzerConfigOptions, option, out value);
}
public static bool TryGetOption<T>(this AnalyzerConfigOptions analyzerConfigOptions, IOption option, out T value)
{
foreach (var storageLocation in option.StorageLocations)
{
if (storageLocation is EditorConfigStorageLocation<T> editorConfigStorageLocation &&
analyzerConfigOptions.TryGetValue(editorConfigStorageLocation.KeyName, out var stringValue) &&
editorConfigStorageLocation.TryGetOption(stringValue, typeof(T), out value))
{
return true;
}
if (storageLocation is IEditorConfigStorageLocation configStorageLocation &&
configStorageLocation.TryGetOption(analyzerConfigOptions, option.Type, out var objectValue))
{
value = (T)objectValue;
return true;
}
}
throw new ArgumentException("AnalyzerConfigOptions can only be queried with Options that use .editorconfig as a storage location.", nameof(option));
}
}
}
|
mit
|
C#
|
fd75ba28a6b0b2f2f18e10162d5ed616b0836247
|
fix the structured data test
|
merchantwarehouse/syslog4net,akramsaleh/syslog4net,Cayan-LLC/syslog4net,jbeats/syslog4net
|
src/test/unit/syslog4net.Tests/Converters/StructuredDataConverterTests.cs
|
src/test/unit/syslog4net.Tests/Converters/StructuredDataConverterTests.cs
|
using System.IO;
using log4net.Core;
using log4net.Util;
using syslog4net.Converters;
using NUnit.Framework;
namespace syslog4net.Tests.Converters
{
[TestFixture]
public class StrcturedDataConverterTests
{
[Test]
public void ConvertTestNoException()
{
var level = Level.Debug;
var testId = "9001";
var resultString = "[MW@55555 MessageId=\"" + testId + "\" EventSeverity=\"" + level.DisplayName + "\"]";
var writer = new StreamWriter(new MemoryStream());
var converter = new StructuredDataConverter();
var props = new PropertiesDictionary();
props["MessageId"] = testId;
props["log4net:StructuredDataPrefix"] = "MW@55555";
// Additional tests using stack data is prevented as the converter class only pulls from LoggingEvent.GetProperties()
// The data behind this method is setup by log4net itself so testing stack usage would not really apply properly here
//ThreadContext.Stacks["foo"].Push("bar");
var evt = new LoggingEvent(new LoggingEventData() { Properties = props, Level = level });
converter.Format(writer, evt);
writer.Flush();
var result = TestUtilities.GetStringFromStream(writer.BaseStream);
Assert.AreEqual(resultString, result);
}
}
}
|
using System.IO;
using log4net.Core;
using log4net.Util;
using syslog4net.Converters;
using NUnit.Framework;
namespace syslog4net.Tests.Converters
{
[TestFixture]
public class StrcturedDataConverterTests
{
[Test]
public void ConvertTestNoException()
{
var level = Level.Debug;
var testId = "9001";
var resultString = "[MW@55555 MessageId=\"" + testId + "\" EventSeverity=\"" + level.DisplayName + "\"]";
var writer = new StreamWriter(new MemoryStream());
var converter = new StructuredDataConverter();
var props = new PropertiesDictionary();
props["MessageId"] = testId;
// Additional tests using stack data is prevented as the converter class only pulls from LoggingEvent.GetProperties()
// The data behind this method is setup by log4net itself so testing stack usage would not really apply properly here
//ThreadContext.Stacks["foo"].Push("bar");
var evt = new LoggingEvent(new LoggingEventData() { Properties = props, Level = level });
converter.Format(writer, evt);
writer.Flush();
var result = TestUtilities.GetStringFromStream(writer.BaseStream);
Assert.AreEqual(resultString, result);
}
}
}
|
apache-2.0
|
C#
|
dd44d36c55d3a4f385bdd1de663f440750b1e83e
|
Add reset perstat button
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Views/Statuses/List.cshtml
|
Battery-Commander.Web/Views/Statuses/List.cshtml
|
@model BatteryCommander.Web.Controllers.StatusesController.StatusListModel
@{
ViewBag.Title = "Batch Update Statuses";
}
<div class="page-header">
<h1>@ViewBag.Title <span class="badge">@Model.Rows.Count</span></h1>
</div>
<div class="btn-group">
<button id="reset-perstat">Reset PERSTAT</button>
</div>
@using (Html.BeginForm("Save", "Statuses", FormMethod.Post))
{
@Html.AntiForgeryToken()
<table class="table table-striped">
<thead>
<tr>
<th>Status</th>
<th>Last Name</th>
<th>First Name</th>
<th>Rank</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.Rows.Count; ++i)
{
<tr>
<td>
@Html.HiddenFor(_ => Model.Rows[i].SoldierId)
@Html.DropDownListFor(_ => Model.Rows[i].Status, Html.GetEnumSelectList<Soldier.SoldierStatus>(), null, new { @class = "status" })
</td>
<td>@Html.DisplayFor(_ => Model.Rows[i].Soldier.LastName)</td>
<td>@Html.DisplayFor(_ => Model.Rows[i].Soldier.FirstName)</td>
<td>@Model.Rows[i].Soldier.Rank.ShortName()</td>
</tr>
}
</tbody>
</table>
<button type="submit" name="Save">Save Updates</button>
}
@section Scripts{
<script>
$(document).ready(function () {
$("#reset-perstat").click(function () {
if (confirm("Are you sure you wish to reset all Soldiers to UNKNOWN?")) {
$("select.status").val(@((int)Soldier.SoldierStatus.Unknown));
}
});
});
</script>
}
|
@model BatteryCommander.Web.Controllers.StatusesController.StatusListModel
@{
ViewBag.Title = "Batch Update Statuses";
}
<div class="page-header">
<h1>@ViewBag.Title <span class="badge">@Model.Rows.Count</span></h1>
</div>
@using (Html.BeginForm("Save", "Statuses", FormMethod.Post))
{
@Html.AntiForgeryToken()
<table class="table table-striped">
<thead>
<tr>
<th>Unit</th>
<th>Soldier</th>
<th>Status</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.Rows.Count; ++i)
{
<tr>
<td>@Html.DisplayFor(_ => Model.Rows[i].Soldier.Unit)</td>
<td>
@Html.HiddenFor(_ => Model.Rows[i].SoldierId)
@Html.DisplayFor(_ => Model.Rows[i].Soldier)
</td>
<td>
@Html.DropDownListFor(_ => Model.Rows[i].Status, Html.GetEnumSelectList<Soldier.SoldierStatus>(), null, new { @class = "select2" })
</td>
</tr>
}
</tbody>
</table>
<button type="submit" name="Save">Save Updates</button>
}
|
mit
|
C#
|
fcdb42ac5cd34aeb9344719a58144af1ffaecfa8
|
Update AbstractBossBehaviour to handle a single HP per pattern.
|
Noxalus/Xmas-Hell
|
Xmas-Hell/Xmas-Hell-Core/Entities/Bosses/AbstractBossBehaviour.cs
|
Xmas-Hell/Xmas-Hell-Core/Entities/Bosses/AbstractBossBehaviour.cs
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace XmasHell.Entities.Bosses
{
public abstract class AbstractBossBehaviour
{
protected Boss Boss;
protected float InitialBehaviourLife;
protected float CurrentBehaviourLife;
protected bool BehaviourEnded;
public float GetCurrentBehaviourLife()
{
return CurrentBehaviourLife;
}
public float GetLifePercentage()
{
return CurrentBehaviourLife / InitialBehaviourLife;
}
public bool IsBehaviourEnded()
{
return BehaviourEnded;
}
protected AbstractBossBehaviour(Boss boss)
{
Boss = boss;
InitialBehaviourLife = GameConfig.BossDefaultBehaviourLife;
}
public virtual void Start()
{
CurrentBehaviourLife = InitialBehaviourLife;
}
public virtual void Stop()
{
}
public virtual void TakeDamage(float amount)
{
CurrentBehaviourLife -= amount;
}
protected virtual void CheckBehaviourIsEnded()
{
if (CurrentBehaviourLife < 0)
BehaviourEnded = true;
}
public virtual void Update(GameTime gameTime)
{
CheckBehaviourIsEnded();
}
public virtual void Draw(SpriteBatch spriteBatch)
{
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace XmasHell.Entities.Bosses
{
public abstract class AbstractBossBehaviour
{
protected Boss Boss;
protected AbstractBossBehaviour(Boss boss)
{
Boss = boss;
}
public virtual void Start()
{
}
public virtual void Stop()
{
}
public virtual void Update(GameTime gameTime)
{
}
public virtual void Draw(SpriteBatch spriteBatch)
{
}
}
}
|
mit
|
C#
|
b11309b48dc1acc87550b930d435aaad5e40a5f8
|
Use Ticks for EpochTimeExtensions epoch calculations
|
s093294/Thinktecture.IdentityModel,dandresini/Thinktecture.IdentityModel,hajirazin/Thinktecture.IdentityModel,s093294/Thinktecture.IdentityModel,mreasy232/Thinktecture.IdentityModel,BasLijten/Thinktecture.IdentityModel,IdentityModel/Thinktecture.IdentityModel,BenAtStatement1/EmbeddedAuthorizationServer,mreasy232/Thinktecture.IdentityModel,hajirazin/Thinktecture.IdentityModel,kollisp/Thinktecture.IdentityModel,kollisp/Thinktecture.IdentityModel,BasLijten/Thinktecture.IdentityModel,asteffens007/identity_model,IdentityModel/Thinktecture.IdentityModel,asteffens007/identity_model,BenAtStatement1/EmbeddedAuthorizationServer,dandresini/Thinktecture.IdentityModel
|
source/Thinktecture.IdentityModel.Client/EpochTimeExtensions.cs
|
source/Thinktecture.IdentityModel.Client/EpochTimeExtensions.cs
|
/*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see LICENSE
*/
using System;
namespace Thinktecture.IdentityModel.Client
{
public static class EpochTimeExtensions
{
/// <summary>
/// Converts the given date value to epoch time.
/// </summary>
public static long ToEpochTime(this DateTime dateTime)
{
var date = dateTime.ToUniversalTime();
var ticks = date.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
var ts = ticks / TimeSpan.TicksPerSecond;
return ts;
}
/// <summary>
/// Converts the given date value to epoch time.
/// </summary>
public static long ToEpochTime(this DateTimeOffset dateTime)
{
var date = dateTime.ToUniversalTime();
var ticks = date.Ticks - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).Ticks;
var ts = ticks / TimeSpan.TicksPerSecond;
return ts;
}
/// <summary>
/// Converts the given epoch time to a <see cref="DateTime"/> with <see cref="DateTimeKind.Utc"/> kind.
/// </summary>
public static DateTime ToDateTimeFromEpoch(this long intDate)
{
var timeInTicks = intDate * TimeSpan.TicksPerSecond;
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks);
}
/// <summary>
/// Converts the given epoch time to a UTC <see cref="DateTimeOffset"/>.
/// </summary>
public static DateTimeOffset ToDateTimeOffsetFromEpoch(this long intDate)
{
var timeInTicks = intDate * TimeSpan.TicksPerSecond;
return new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(timeInTicks);
}
}
}
|
/*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see LICENSE
*/
using System;
namespace Thinktecture.IdentityModel.Client
{
public static class EpochTimeExtensions
{
/// <summary>
/// Converts the given date value to epoch time.
/// </summary>
public static long ToEpochTime(this DateTime dateTime)
{
var date = dateTime.ToUniversalTime();
var ts = date - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64(ts.TotalSeconds);
}
/// <summary>
/// Converts the given date value to epoch time.
/// </summary>
public static long ToEpochTime(this DateTimeOffset dateTime)
{
var date = dateTime.ToUniversalTime();
var ts = date - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
return Convert.ToInt64(ts.TotalSeconds);
}
/// <summary>
/// Converts the given epoch time to a <see cref="DateTime"/> with <see cref="DateTimeKind.Utc"/> kind.
/// </summary>
public static DateTime ToDateTimeFromEpoch(this long intDate)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(intDate);
}
/// <summary>
/// Converts the given epoch time to a UTC <see cref="DateTimeOffset"/>.
/// </summary>
public static DateTimeOffset ToDateTimeOffsetFromEpoch(this long intDate)
{
return new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(intDate);
}
}
}
|
bsd-3-clause
|
C#
|
d5aeda29cd029b2a47d64b7dd4601762b7b3b144
|
Fix para test
|
TheXDS/MCART
|
src/Tests/CoreTests/Types/Extensions/TimeSpanExtensionsTests.cs
|
src/Tests/CoreTests/Types/Extensions/TimeSpanExtensionsTests.cs
|
/*
TimeSpanExtensionsTests.cs
This file is part of Morgan's CLR Advanced Runtime (MCART)
Author(s):
César Andrés Morgan <xds_xps_ivx@hotmail.com>
Copyright © 2011 - 2021 César Andrés Morgan
Morgan's CLR Advanced Runtime (MCART) is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
Morgan's CLR Advanced Runtime (MCART) is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Globalization;
using TheXDS.MCART.Resources;
using TheXDS.MCART.Types.Extensions;
using Xunit;
namespace TheXDS.MCART.Tests.Types.Extensions
{
public class TimeSpanExtensionsTests
{
[Fact]
public void VerboseTest()
{
Assert.Equal(Strings.Seconds(15),TimeSpan.FromSeconds(15).Verbose());
Assert.Equal(Strings.Minutes(3),TimeSpan.FromSeconds(180).Verbose());
Assert.Equal(Strings.Hours(2),TimeSpan.FromSeconds(7200).Verbose());
Assert.Equal(Strings.Days(5),TimeSpan.FromDays(5).Verbose());
Assert.Equal(
$"{Strings.Minutes(1)}, {Strings.Seconds(5)}",
TimeSpan.FromSeconds(65).Verbose());
Assert.Equal(
$"{Strings.Days(2)}, {Strings.Hours(5)}, {Strings.Minutes(45)}, {Strings.Seconds(23)}",
(TimeSpan.FromDays(2) + TimeSpan.FromHours(5) + TimeSpan.FromMinutes(45) + TimeSpan.FromSeconds(23)).Verbose());
}
[Fact]
public void AsTimeTest()
{
var t = TimeSpan.FromSeconds(60015);
var c = CultureInfo.InvariantCulture;
var r = t.AsTime(c);
Assert.Equal("16:40", r);
Assert.Equal(
string.Format($"{{0:{CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern}}}",
DateTime.MinValue.Add(t)), t.AsTime());
}
}
}
|
/*
TimeSpanExtensionsTests.cs
This file is part of Morgan's CLR Advanced Runtime (MCART)
Author(s):
César Andrés Morgan <xds_xps_ivx@hotmail.com>
Copyright © 2011 - 2021 César Andrés Morgan
Morgan's CLR Advanced Runtime (MCART) is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
Morgan's CLR Advanced Runtime (MCART) is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Globalization;
using TheXDS.MCART.Resources;
using TheXDS.MCART.Types.Extensions;
using Xunit;
namespace TheXDS.MCART.Tests.Types.Extensions
{
public class TimeSpanExtensionsTests
{
[Fact]
public void VerboseTest()
{
Assert.Equal(Strings.Seconds(15),TimeSpan.FromSeconds(15).Verbose());
Assert.Equal(Strings.Minutes(3),TimeSpan.FromSeconds(180).Verbose());
Assert.Equal(Strings.Hours(2),TimeSpan.FromSeconds(7200).Verbose());
Assert.Equal(Strings.Days(5),TimeSpan.FromDays(5).Verbose());
Assert.Equal(
$"{Strings.Minutes(1)}, {Strings.Seconds(5)}",
TimeSpan.FromSeconds(65).Verbose());
Assert.Equal(
$"{Strings.Days(2)}, {Strings.Hours(5)}, {Strings.Minutes(45)}, {Strings.Seconds(23)}",
(TimeSpan.FromDays(2) + TimeSpan.FromHours(5) + TimeSpan.FromMinutes(45) + TimeSpan.FromSeconds(23)).Verbose());
}
[Fact]
public void AsTimeTest()
{
var t = TimeSpan.FromSeconds(60015);
var c = CultureInfo.GetCultureInfo("en-UK");
var r = t.AsTime(c);
Assert.Equal("4:40 p.\u00A0m.", r);
Assert.Equal(
string.Format($"{{0:{CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern}}}",
DateTime.MinValue.Add(t)), t.AsTime());
}
}
}
|
mit
|
C#
|
d730a4474de982d580f1b95c1067f0bb0dab2e9f
|
Disable BaseHttpServerTests due to poor reliabilty
|
RonnChyran/snowflake,faint32/snowflake-1,RonnChyran/snowflake,RonnChyran/snowflake,faint32/snowflake-1,SnowflakePowered/snowflake,faint32/snowflake-1,SnowflakePowered/snowflake,SnowflakePowered/snowflake
|
Snowflake.Tests/Service/HttpServer/BaseHttpServerTests.cs
|
Snowflake.Tests/Service/HttpServer/BaseHttpServerTests.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mono.Net;
using System.IO;
using System.Web;
using System.Net;
using Xunit;
namespace Snowflake.Service.HttpServer.Tests
{
/*public*/ class BaseHttpServerTests
{
[Fact]
public void BaseHttpServerCreation_Test()
{
Assert.NotNull(new FakeHttpServer());
}
[Fact]
public void BaseHttpServerStart_Test()
{
IBaseHttpServer server = new FakeHttpServer();
server.StartServer();
using (WebClient client = new WebClient())
{
Assert.Equal(String.Empty, client.DownloadString("http://localhost:25566"));
}
}
[Fact]
public void BaseHttpServerStop_Test()
{
IBaseHttpServer server = new FakeHttpServer();
bool unableToDownload = false;
server.StartServer();
server.StopServer();
using (WebClient client = new WebClient())
{
try
{
Assert.Equal(String.Empty, client.DownloadString("http://localhost:25566"));
}
catch (WebException)
{
unableToDownload = true;
}
}
Assert.True(unableToDownload);
}
}
class FakeHttpServer : BaseHttpServer
{
public FakeHttpServer() : base(25566) { }
protected async override Task Process(Mono.Net.HttpListenerContext context)
{
var writer = new StreamWriter(context.Response.OutputStream);
writer.Write(String.Empty);
writer.Flush();
context.Response.OutputStream.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mono.Net;
using System.IO;
using System.Web;
using System.Net;
using Xunit;
namespace Snowflake.Service.HttpServer.Tests
{
public class BaseHttpServerTests
{
[Fact]
public void BaseHttpServerCreation_Test()
{
Assert.NotNull(new FakeHttpServer());
}
[Fact]
public void BaseHttpServerStart_Test()
{
IBaseHttpServer server = new FakeHttpServer();
server.StartServer();
using (WebClient client = new WebClient())
{
Assert.Equal(String.Empty, client.DownloadString("http://localhost:25566"));
}
}
[Fact]
public void BaseHttpServerStop_Test()
{
IBaseHttpServer server = new FakeHttpServer();
bool unableToDownload = false;
server.StartServer();
server.StopServer();
using (WebClient client = new WebClient())
{
try
{
Assert.Equal(String.Empty, client.DownloadString("http://localhost:25566"));
}
catch (WebException)
{
unableToDownload = true;
}
}
Assert.True(unableToDownload);
}
}
class FakeHttpServer : BaseHttpServer
{
public FakeHttpServer() : base(25566) { }
protected async override Task Process(Mono.Net.HttpListenerContext context)
{
var writer = new StreamWriter(context.Response.OutputStream);
writer.Write(String.Empty);
writer.Flush();
context.Response.OutputStream.Close();
}
}
}
|
mpl-2.0
|
C#
|
d901e4e2c1cb1a2b0397bb4c67eed8ff6360cdca
|
Make sure SecureRandom call NBitcoin random
|
DanGould/NTumbleBit,NTumbleBit/NTumbleBit
|
NTumbleBit/BouncyCastle/security/SecureRandom.cs
|
NTumbleBit/BouncyCastle/security/SecureRandom.cs
|
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NTumbleBit.BouncyCastle.Security
{
internal class SecureRandom : Random
{
public SecureRandom()
{
}
public override int Next()
{
throw new NotImplementedException();
}
public override int Next(int maxValue)
{
throw new NotImplementedException();
}
public override int Next(int minValue, int maxValue)
{
throw new NotImplementedException();
}
public override void NextBytes(byte[] buffer)
{
RandomUtils.GetBytes(buffer);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NTumbleBit.BouncyCastle.Security
{
internal class SecureRandom : Random
{
public SecureRandom()
{
}
internal static byte[] GetNextBytes(SecureRandom random, int p)
{
throw new NotImplementedException();
}
internal byte NextInt()
{
throw new NotImplementedException();
}
internal void NextBytes(byte[] cekBlock, int p1, int p2)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
c6fe9927bd92c6c59ef5dab4cfb10c39e64103e0
|
Fix return statement
|
TheNoobCompany/LevelingQuestsTNB,F0rTh3H0rd3/LevelingQuestsTNB
|
Profiles/Quester/Scripts/InteractWithHotSpots.cs
|
Profiles/Quester/Scripts/InteractWithHotSpots.cs
|
/* Check if there is HotSpots in the objective */
if (questObjective.Hotspots.Count <= 0)
{
/* Objective CSharpScript with script InteractWithHotSpots requires valid "Hotspots" */
Logging.Write("InteractWithHotSpots requires valid 'HotSpots'.");
questObjective.IsObjectiveCompleted = true;
return false;
}
/* Move to Zone/Hotspot */
if (!MovementManager.InMovement)
{
if (questObjective.Hotspots[Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)].DistanceTo(ObjectManager.Me.Position) > 5)
{
MovementManager.Go(PathFinder.FindPath(questObjective.Hotspots[Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)]));
}
else
{
MovementManager.GoLoop(questObjective.Hotspots);
}
}
/* Search for Entry */
WoWGameObject node = ObjectManager.GetNearestWoWGameObject(ObjectManager.GetWoWGameObjectById(questObjective.Entry));
WoWUnit unit =ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead));
Point pos;
uint baseAddress;
/* If Entry found continue, otherwise continue checking around HotSpots */
if (node.IsValid || unit.IsValid)
{
/* Entry found, GoTo */
if(unit.IsValid)
{
baseAddress = MovementManager.FindTarget(unit); /* Move toward unit */
}
else if (node.IsValid)
{
baseAddress = MovementManager.FindTarget(node); /* Move toward node */
}
Thread.Sleep(100 + Usefuls.Latency); /* ZZZzzzZZZzz */
if (MovementManager.InMovement)
return false; /* Waiting to reach Entry */
/* Entry reached, dismount */
MovementManager.StopMove();
MountTask.DismountMount();
if (questObjective.IgnoreFight)
Quest.GetSetIgnoreFight = true;
/* Interact With Entry */
Interact.InteractWith(baseAddress);
Thread.Sleep(Usefuls.Latency);
/* Wait for the interact cast to be finished, if any */
while (ObjectManager.Me.IsCast)
{
Thread.Sleep(Usefuls.Latency);
}
/* Do Gossip if necessary */
if (questObjective.GossipOptionsInteractWith != 0)
{
Thread.Sleep(250 + Usefuls.Latency);
Quest.SelectGossipOption(questObjective.GossipOptionsInteractWith);
}
if (Others.IsFrameVisible("StaticPopup1Button1"))
Lua.RunMacroText("/click StaticPopup1Button1");
if (ObjectManager.Me.InCombat && !questObjective.IgnoreFight)
return false;
/* Wait if necessary */
if(questObjective.WaitMs > 0)
Thread.Sleep(questObjective.WaitMs);
/* Interact Completed - InternalIndex and count is used to determine if obj is completed - questObjective.IsObjectiveCompleted = true; */
Quest.GetSetIgnoreFight = false;
}
|
/* Check if there is HotSpots in the objective */
if (questObjective.Hotspots.Count <= 0)
{
/* Objective CSharpScript with script InteractWithHotSpots requires valid "Hotspots" */
Logging.Write("InteractWithHotSpots requires valid 'HotSpots'.");
questObjective.IsObjectiveCompleted = true;
return false;
}
/* Move to Zone/Hotspot */
if (!MovementManager.InMovement)
{
if (questObjective.Hotspots[Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)].DistanceTo(ObjectManager.Me.Position) > 5)
{
MovementManager.Go(PathFinder.FindPath(questObjective.Hotspots[Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)]));
}
else
{
MovementManager.GoLoop(questObjective.Hotspots);
}
}
/* Search for Entry */
WoWGameObject node = ObjectManager.GetNearestWoWGameObject(ObjectManager.GetWoWGameObjectById(questObjective.Entry));
WoWUnit unit =ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead));
Point pos;
uint baseAddress;
/* If Entry found continue, otherwise continue checking around HotSpots */
if (node.IsValid || unit.IsValid)
{
/* Entry found, GoTo */
if(unit.IsValid)
{
baseAddress = MovementManager.FindTarget(unit); /* Move toward unit */
}
else if (node.IsValid)
{
baseAddress = MovementManager.FindTarget(node); /* Move toward node */
}
Thread.Sleep(100 + Usefuls.Latency); /* ZZZzzzZZZzz */
if (MovementManager.InMovement)
return false; /* Waiting to reach Entry */
/* Entry reached, dismount */
MovementManager.StopMove();
MountTask.DismountMount();
if (questObjective.IgnoreFight)
Quest.GetSetIgnoreFight = true;
/* Interact With Entry */
Interact.InteractWith(baseAddress);
Thread.Sleep(Usefuls.Latency);
/* Wait for the interact cast to be finished, if any */
while (ObjectManager.Me.IsCast)
{
Thread.Sleep(Usefuls.Latency);
}
/* Do Gossip if necessary */
if (questObjective.GossipOptionsInteractWith != 0)
{
Thread.Sleep(250 + Usefuls.Latency);
Quest.SelectGossipOption(questObjective.GossipOptionsInteractWith);
}
if (Others.IsFrameVisible("StaticPopup1Button1"))
Lua.RunMacroText("/click StaticPopup1Button1");
if (ObjectManager.Me.InCombat && !questObjective.IgnoreFight)
return;
/* Wait if necessary */
if(questObjective.WaitMs > 0)
Thread.Sleep(questObjective.WaitMs);
/* Interact Completed - InternalIndex and count is used to determine if obj is completed - questObjective.IsObjectiveCompleted = true; */
Quest.GetSetIgnoreFight = false;
}
|
mit
|
C#
|
f7c6598c8d15ed87e141f698bddb248410f329b2
|
Reduce chance of exceptions.
|
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
|
src/MitternachtBot/Modules/Utility/Services/CountToNumberService.cs
|
src/MitternachtBot/Modules/Utility/Services/CountToNumberService.cs
|
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
using Mitternacht.Services;
namespace Mitternacht.Modules.Utility.Services {
public class CountToNumberService : IMService {
private readonly DiscordSocketClient _client;
private readonly DbService _db;
private readonly Random _random = new Random();
public CountToNumberService(DiscordSocketClient client, DbService db) {
_client = client;
_db = db;
_client.MessageReceived += CountToMessageReceived;
}
public async Task CountToMessageReceived(SocketMessage msg) {
if(!msg.Author.IsBot && msg.Channel is ITextChannel channel) {
using var uow = _db.UnitOfWork;
var gc = uow.GuildConfigs.For(channel.GuildId);
if(gc.CountToNumberChannelId == channel.Id) {
var match = Regex.Match(msg.Content.Trim(), "\\A(\\d+)");
if(match.Success && ulong.TryParse(match.Groups[1].Value, out var currentnumber)) {
var lastMessages = (await channel.GetMessagesAsync(10).FlattenAsync().ConfigureAwait(false)).ToList();
var messageIndex = lastMessages.FindIndex(m => m.Id == msg.Id);
var previousMessage = lastMessages[messageIndex+1];
var previousMatch = Regex.Match(previousMessage.Content.Trim(), "\\A(\\d+)");
if(gc.CountToNumberDeleteWrongMessages && (previousMatch.Success && ulong.TryParse(previousMatch.Groups[1].Value, out var previousNumberParsingSuccess) && currentnumber - previousNumberParsingSuccess != 1 || previousMessage.Author.Id == msg.Author.Id)) {
await msg.DeleteAsync().ConfigureAwait(false);
} else if(_random.NextDouble() < gc.CountToNumberMessageChance) {
await channel.SendMessageAsync($"{currentnumber + 1}").ConfigureAwait(false);
}
} else if(gc.CountToNumberDeleteWrongMessages) {
await msg.DeleteAsync().ConfigureAwait(false);
}
}
}
}
}
}
|
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
using Mitternacht.Services;
namespace Mitternacht.Modules.Utility.Services {
public class CountToNumberService : IMService {
private readonly DiscordSocketClient _client;
private readonly DbService _db;
private readonly Random _random = new Random();
public CountToNumberService(DiscordSocketClient client, DbService db) {
_client = client;
_db = db;
_client.MessageReceived += CountToMessageReceived;
}
public async Task CountToMessageReceived(SocketMessage msg) {
if(!msg.Author.IsBot && msg.Channel is ITextChannel channel) {
using var uow = _db.UnitOfWork;
var gc = uow.GuildConfigs.For(channel.GuildId);
if(gc.CountToNumberChannelId == channel.Id) {
var match = Regex.Match(msg.Content.Trim(), "\\A(\\d+)");
if(match.Success) {
var currentnumber = ulong.Parse(match.Groups[1].Value);
var lastMessages = (await channel.GetMessagesAsync(10).FlattenAsync().ConfigureAwait(false)).ToList();
var messageIndex = lastMessages.FindIndex(m => m.Id == msg.Id);
var previousMessage = lastMessages[messageIndex+1];
var previousMatch = Regex.Match(previousMessage.Content.Trim(), "\\A(\\d+)");
if(gc.CountToNumberDeleteWrongMessages && (previousMatch.Success && currentnumber - ulong.Parse(previousMatch.Groups[1].Value) != 1 || previousMessage.Author.Id == msg.Author.Id)) {
await msg.DeleteAsync().ConfigureAwait(false);
} else if(_random.NextDouble() < gc.CountToNumberMessageChance) {
await channel.SendMessageAsync($"{currentnumber + 1}").ConfigureAwait(false);
}
} else if(gc.CountToNumberDeleteWrongMessages) {
await msg.DeleteAsync().ConfigureAwait(false);
}
}
}
}
}
}
|
mit
|
C#
|
313c21c9ab7b4008d9d8ec626eb9a4f80ec2b211
|
Remove Document Version after upgrading YesSql (#7589)
|
xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2
|
src/OrchardCore/OrchardCore.Data.Abstractions/Documents/Document.cs
|
src/OrchardCore/OrchardCore.Data.Abstractions/Documents/Document.cs
|
namespace OrchardCore.Data.Documents
{
public class Document : IDocument
{
/// <summary>
/// The <see cref="IDocument.Identifier"/>.
/// </summary>
public string Identifier { get; set; }
}
}
|
namespace OrchardCore.Data.Documents
{
public class Document : IDocument
{
/// <summary>
/// The <see cref="IDocument.Identifier"/>.
/// </summary>
public string Identifier { get; set; }
/// <summary>
/// Only defined to prevent a version missmatch, see https://github.com/sebastienros/yessql/pull/287
/// </summary>
public int Version { get; set; }
}
}
|
bsd-3-clause
|
C#
|
28023e1f7832c925c7f13e021fdce4526645c582
|
remove names from contact page
|
jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox
|
ZirMed.TrainingSandbox/Views/Home/Contact.cshtml
|
ZirMed.TrainingSandbox/Views/Home/Contact.cshtml
|
@{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
</address>
|
@{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a>
<strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Nicolas:</strong> <a href="mailto:nick.wolf@zirmed.com">nick.wolf@zirmed.com</a>
<strong>Dustin2:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Travis:</strong> <a href="mailto:travis.elkins@zirmed.com">travis.elkins@zirmed.com</a>
<strong>Travis2:</strong> <a href="mailto:travis.elkins@zirmed.com">travis.elkins@zirmed.com</a>
<strong>Stephanie:</strong> <a href="mailto:stephanie.craig@zirmed.com">stephanie.craig@zirmed.com</a>
<strong>Bruce Wayne:</strong>
<strong>Larry Briggs:</strong>
<strong>Clark Kent:</strong> <a href="mailto:superman.com">superman.com</a>
<strong>Peter Parker:</strong> <a href="mailto:spider-man.com">spider-man.com</a>
<strong>Oliver Queen:</strong>
<strong>Barry Allen:</strong>
<strong>Bob: </strong>
<strong>Bruce Banner:</strong> <a href="#">Hulk.com</a>
<strong>Wade Winston Wilson:</strong> <a href="#">Deadpool.com</a>
<strong>Albus Dumbledore:</strong>
<strong>Harry Potter:</strong>
<strong>Diana Prince:</strong> <a href="#">WonderWoman.com</a>
<strong>Scott Lang:</strong> <a href="#">Ant-Man.com</a>
</address>
|
mit
|
C#
|
2fa5b3f9adc961acc5365b661a516a8c1fd0885d
|
Enable specific events for metrics (#3818)
|
open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet
|
src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreMetrics.cs
|
src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreMetrics.cs
|
// <copyright file="AspNetCoreMetrics.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Reflection;
using OpenTelemetry.Instrumentation.AspNetCore.Implementation;
namespace OpenTelemetry.Instrumentation.AspNetCore
{
/// <summary>
/// Asp.Net Core Requests instrumentation.
/// </summary>
internal sealed class AspNetCoreMetrics : IDisposable
{
internal static readonly AssemblyName AssemblyName = typeof(HttpInListener).Assembly.GetName();
internal static readonly string InstrumentationName = AssemblyName.Name;
internal static readonly string InstrumentationVersion = AssemblyName.Version.ToString();
private static readonly HashSet<string> DiagnosticSourceEvents = new()
{
"Microsoft.AspNetCore.Hosting.HttpRequestIn",
"Microsoft.AspNetCore.Hosting.HttpRequestIn.Start",
"Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop",
};
private readonly Func<string, object, object, bool> isEnabled = (eventName, obj1, obj2)
=> DiagnosticSourceEvents.Contains(eventName);
private readonly DiagnosticSourceSubscriber diagnosticSourceSubscriber;
private readonly Meter meter;
/// <summary>
/// Initializes a new instance of the <see cref="AspNetCoreMetrics"/> class.
/// </summary>
public AspNetCoreMetrics()
{
this.meter = new Meter(InstrumentationName, InstrumentationVersion);
this.diagnosticSourceSubscriber = new DiagnosticSourceSubscriber(new HttpInMetricsListener("Microsoft.AspNetCore", this.meter), this.isEnabled);
this.diagnosticSourceSubscriber.Subscribe();
}
/// <inheritdoc/>
public void Dispose()
{
this.diagnosticSourceSubscriber?.Dispose();
this.meter?.Dispose();
}
}
}
|
// <copyright file="AspNetCoreMetrics.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics.Metrics;
using System.Reflection;
using OpenTelemetry.Instrumentation.AspNetCore.Implementation;
namespace OpenTelemetry.Instrumentation.AspNetCore
{
/// <summary>
/// Asp.Net Core Requests instrumentation.
/// </summary>
internal sealed class AspNetCoreMetrics : IDisposable
{
internal static readonly AssemblyName AssemblyName = typeof(HttpInListener).Assembly.GetName();
internal static readonly string InstrumentationName = AssemblyName.Name;
internal static readonly string InstrumentationVersion = AssemblyName.Version.ToString();
private readonly DiagnosticSourceSubscriber diagnosticSourceSubscriber;
private readonly Meter meter;
/// <summary>
/// Initializes a new instance of the <see cref="AspNetCoreMetrics"/> class.
/// </summary>
public AspNetCoreMetrics()
{
this.meter = new Meter(InstrumentationName, InstrumentationVersion);
this.diagnosticSourceSubscriber = new DiagnosticSourceSubscriber(new HttpInMetricsListener("Microsoft.AspNetCore", this.meter), null);
this.diagnosticSourceSubscriber.Subscribe();
}
/// <inheritdoc/>
public void Dispose()
{
this.diagnosticSourceSubscriber?.Dispose();
this.meter?.Dispose();
}
}
}
|
apache-2.0
|
C#
|
e682ca4fd9a17cf90ac083ec5ff8faf317606b59
|
Adjust osu!mania scroll speed defaults to be more sane
|
UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,ZLima12/osu,ZLima12/osu,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,2yangk23/osu,smoogipooo/osu
|
osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.cs
|
osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
{
public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(ManiaRulesetSetting.ScrollTime, 1500.0, 50.0, 5000.0, 50.0);
Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms"))
};
}
public enum ManiaRulesetSetting
{
ScrollTime,
ScrollDirection
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
{
public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(ManiaRulesetSetting.ScrollTime, 2250.0, 50.0, 10000.0, 50.0);
Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms"))
};
}
public enum ManiaRulesetSetting
{
ScrollTime,
ScrollDirection
}
}
|
mit
|
C#
|
4a7f84772593b7843682d3ecdec980c373ef97e0
|
Remove star creation debug printing
|
Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare
|
Assets/Microgames/SuikaShake/Scripts/SuikaShakeSparkleSpawner.cs
|
Assets/Microgames/SuikaShake/Scripts/SuikaShakeSparkleSpawner.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SuikaShakeSparkleSpawner : MonoBehaviour
{
[SerializeField]
private float spanwStartTime = .05f;
[SerializeField]
private float spawnFrequency = .25f;
[SerializeField]
private GameObject sparklePrefab;
[SerializeField]
private SuikaShakeSpriteFinder spriteCollection;
[SerializeField]
private BoxCollider2D spawnCollider;
void Update ()
{
InvokeRepeating("createSparkle", spanwStartTime, spawnFrequency);
enabled = false;
}
void createSparkle()
{
var newSparkle = Instantiate(sparklePrefab, transform);
newSparkle.transform.localScale = new Vector3(Random.Range(0, 2) == 0 ? -1f : 1f, 1f, 1f);
newSparkle.transform.eulerAngles = Vector3.forward * Random.Range(0f, 360f);
var chosenSprite = spriteCollection.sprites[Random.Range(0, spriteCollection.sprites.Length)];
var spriteRenderers = newSparkle.GetComponentsInChildren<SpriteRenderer>();
foreach (var sparkleRenderer in spriteRenderers)
{
sparkleRenderer.sprite = chosenSprite;
}
float xOffset = spawnCollider.bounds.extents.x;
float yOffset = spawnCollider.bounds.extents.y;
newSparkle.transform.position += (Vector3)spawnCollider.offset + new Vector3(Random.Range(-xOffset, xOffset), Random.Range(-yOffset, yOffset), 0f);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SuikaShakeSparkleSpawner : MonoBehaviour
{
[SerializeField]
private float spanwStartTime = .05f;
[SerializeField]
private float spawnFrequency = .25f;
[SerializeField]
private GameObject sparklePrefab;
[SerializeField]
private SuikaShakeSpriteFinder spriteCollection;
[SerializeField]
private BoxCollider2D spawnCollider;
void Update ()
{
InvokeRepeating("createSparkle", spanwStartTime, spawnFrequency);
enabled = false;
}
void createSparkle()
{
var newSparkle = Instantiate(sparklePrefab, transform);
newSparkle.transform.localScale = new Vector3(Random.Range(0, 2) == 0 ? -1f : 1f, 1f, 1f);
newSparkle.transform.eulerAngles = Vector3.forward * Random.Range(0f, 360f);
var chosenSprite = spriteCollection.sprites[Random.Range(0, spriteCollection.sprites.Length)];
var spriteRenderers = newSparkle.GetComponentsInChildren<SpriteRenderer>();
foreach (var sparkleRenderer in spriteRenderers)
{
sparkleRenderer.sprite = chosenSprite;
}
float xOffset = spawnCollider.bounds.extents.x;
float yOffset = spawnCollider.bounds.extents.y;
print(newSparkle.transform.position);
newSparkle.transform.position += (Vector3)spawnCollider.offset + new Vector3(Random.Range(-xOffset, xOffset), Random.Range(-yOffset, yOffset), 0f);
}
}
|
mit
|
C#
|
0afb188cde87ea1975d327653b1a4b791c943d2b
|
Remove unused using
|
DrabWeb/osu,naoey/osu,osu-RP/osu-RP,UselessToucan/osu,smoogipoo/osu,DrabWeb/osu,johnneijzen/osu,smoogipooo/osu,Drezi126/osu,NeoAdonis/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,peppy/osu,Nabile-Rahmani/osu,UselessToucan/osu,ZLima12/osu,ppy/osu,DrabWeb/osu,UselessToucan/osu,EVAST9919/osu,naoey/osu,EVAST9919/osu,Damnae/osu,tacchinotacchi/osu,ZLima12/osu,naoey/osu,smoogipoo/osu,smoogipoo/osu,Frontear/osuKyzer,peppy/osu,2yangk23/osu,NeoAdonis/osu,2yangk23/osu,ppy/osu,ppy/osu
|
osu.Desktop.VisualTests/Tests/TestCaseSkipButton.cs
|
osu.Desktop.VisualTests/Tests/TestCaseSkipButton.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Testing;
using osu.Game.Screens.Play;
namespace osu.Desktop.VisualTests.Tests
{
internal class TestCaseSkipButton : TestCase
{
public override string Description => @"Skip skip skippediskip";
public override void Reset()
{
base.Reset();
Add(new SkipButton(Clock.CurrentTime + 5000));
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Testing;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
namespace osu.Desktop.VisualTests.Tests
{
internal class TestCaseSkipButton : TestCase
{
public override string Description => @"Skip skip skippediskip";
public override void Reset()
{
base.Reset();
Add(new SkipButton(Clock.CurrentTime + 5000));
}
}
}
|
mit
|
C#
|
791bf6bc0197118f44654f754f9a407f4bda5f6b
|
Make username text italic
|
smoogipoo/osu,johnneijzen/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,johnneijzen/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,peppy/osu
|
osu.Game/Overlays/Rankings/Tables/UserBasedTable.cs
|
osu.Game/Overlays/Rankings/Tables/UserBasedTable.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Users;
using osu.Game.Scoring;
namespace osu.Game.Overlays.Rankings.Tables
{
public abstract class UserBasedTable : RankingsTable<UserStatistics>
{
protected UserBasedTable(int page, IReadOnlyList<UserStatistics> rankings)
: base(page, rankings)
{
}
protected override TableColumn[] CreateAdditionalHeaders() => new[]
{
new TableColumn("Accuracy", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
new TableColumn("Play Count", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
}.Concat(CreateUniqueHeaders()).Concat(new[]
{
new TableColumn("SS", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
new TableColumn("S", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
new TableColumn("A", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
}).ToArray();
protected sealed override Country GetCountry(UserStatistics item) => item.User.Country;
protected sealed override Drawable CreateFlagContent(UserStatistics item)
{
var username = new LinkFlowContainer(t => t.Font = OsuFont.GetFont(size: TEXT_SIZE, italics: true)) { AutoSizeAxes = Axes.Both };
username.AddUserLink(item.User);
return username;
}
protected sealed override Drawable[] CreateAdditionalContent(UserStatistics item) => new[]
{
new ColoredRowText { Text = item.DisplayAccuracy, },
new ColoredRowText { Text = $@"{item.PlayCount:N0}", },
}.Concat(CreateUniqueContent(item)).Concat(new[]
{
new ColoredRowText { Text = $@"{item.GradesCount[ScoreRank.XH] + item.GradesCount[ScoreRank.X]:N0}", },
new ColoredRowText { Text = $@"{item.GradesCount[ScoreRank.SH] + item.GradesCount[ScoreRank.S]:N0}", },
new ColoredRowText { Text = $@"{item.GradesCount[ScoreRank.A]:N0}", }
}).ToArray();
protected abstract TableColumn[] CreateUniqueHeaders();
protected abstract Drawable[] CreateUniqueContent(UserStatistics item);
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Users;
using osu.Game.Scoring;
namespace osu.Game.Overlays.Rankings.Tables
{
public abstract class UserBasedTable : RankingsTable<UserStatistics>
{
protected UserBasedTable(int page, IReadOnlyList<UserStatistics> rankings)
: base(page, rankings)
{
}
protected override TableColumn[] CreateAdditionalHeaders() => new[]
{
new TableColumn("Accuracy", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
new TableColumn("Play Count", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
}.Concat(CreateUniqueHeaders()).Concat(new[]
{
new TableColumn("SS", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
new TableColumn("S", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
new TableColumn("A", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
}).ToArray();
protected sealed override Country GetCountry(UserStatistics item) => item.User.Country;
protected sealed override Drawable CreateFlagContent(UserStatistics item)
{
var username = new LinkFlowContainer(t => t.Font = OsuFont.GetFont(size: TEXT_SIZE)) { AutoSizeAxes = Axes.Both };
username.AddUserLink(item.User);
return username;
}
protected sealed override Drawable[] CreateAdditionalContent(UserStatistics item) => new[]
{
new ColoredRowText { Text = item.DisplayAccuracy, },
new ColoredRowText { Text = $@"{item.PlayCount:N0}", },
}.Concat(CreateUniqueContent(item)).Concat(new[]
{
new ColoredRowText { Text = $@"{item.GradesCount[ScoreRank.XH] + item.GradesCount[ScoreRank.X]:N0}", },
new ColoredRowText { Text = $@"{item.GradesCount[ScoreRank.SH] + item.GradesCount[ScoreRank.S]:N0}", },
new ColoredRowText { Text = $@"{item.GradesCount[ScoreRank.A]:N0}", }
}).ToArray();
protected abstract TableColumn[] CreateUniqueHeaders();
protected abstract Drawable[] CreateUniqueContent(UserStatistics item);
}
}
|
mit
|
C#
|
5fbd9b3f7be5a8fc4cbd2b8b2a63fc20d4d7bfd5
|
Add "Setter" to PortViewModel property of Ev3ControllerMainViewModel.
|
CountrySideEngineer/Ev3Controller
|
dev/src/Ev3Controller/ViewModel/Ev3ControllerMainViewModel.cs
|
dev/src/Ev3Controller/ViewModel/Ev3ControllerMainViewModel.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ev3Controller.ViewModel
{
public class Ev3ControllerMainViewModel : ViewModelBase
{
#region Constructors and the Finalizer
public Ev3ControllerMainViewModel()
{
}
#endregion
#region Public Properties
/// <summary>
/// View model object about COM port, Ev3PortViewModel.
/// </summary>
protected Ev3PortViewModel _PortViewModel;
public Ev3PortViewModel PortViewModel
{
get
{
if (null == this._PortViewModel)
{
this._PortViewModel = new Ev3PortViewModel();
}
return this._PortViewModel;
}
set
{
this._PortViewModel = value;
this.RaisePropertyChanged("PortViewModel");
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ev3Controller.ViewModel
{
public class Ev3ControllerMainViewModel : ViewModelBase
{
#region Constructors and the Finalizer
public Ev3ControllerMainViewModel()
{
}
#endregion
#region Public Properties
/// <summary>
/// View model object about COM port, Ev3PortViewModel.
/// </summary>
protected Ev3PortViewModel _PortViewModel;
public Ev3PortViewModel PortViewModel
{
get
{
if (null == this._PortViewModel)
{
this._PortViewModel = new Ev3PortViewModel();
}
return this._PortViewModel;
}
}
#endregion
}
}
|
mit
|
C#
|
4b6d87356caaf1f5802a95e8287c398bd9b8604e
|
Test fix
|
tzachshabtay/MonoAGS
|
Source/Tests/Engine/ComponentsFramework/ComponentBindingTests.cs
|
Source/Tests/Engine/ComponentsFramework/ComponentBindingTests.cs
|
using System;
using AGS.API;
using AGS.Engine;
using NUnit.Framework;
namespace Tests
{
[TestFixture]
public class ComponentBindingTests
{
[Test]
public void BindingCalledForExplicitType()
{
AGSEmptyEntity entity = new AGSEmptyEntity("test", Mocks.GetResolver());
AGSCropSelfComponent crop = new AGSCropSelfComponent();
bool bindingCalled = false;
entity.Bind<ICropSelfComponent>(c =>
{
Assert.AreSame(crop, c);
bindingCalled = true;
}, _ => {});
Assert.IsFalse(bindingCalled);
entity.AddComponent<ICropSelfComponent>(crop);
Assert.IsTrue(bindingCalled);
}
[Test]
public void BindingCalledForExplicitTypeAlreadyAdded()
{
AGSEmptyEntity entity = new AGSEmptyEntity("test" + Guid.NewGuid(), Mocks.GetResolver());
AGSCropSelfComponent crop = new AGSCropSelfComponent();
entity.AddComponent<ICropSelfComponent>(crop);
bool bindingCalled = false;
entity.Bind<ICropSelfComponent>(c =>
{
Assert.AreSame(crop, c);
bindingCalled = true;
}, _ => {});
Assert.IsTrue(bindingCalled);
}
}
}
|
using System;
using AGS.API;
using AGS.Engine;
using NUnit.Framework;
namespace Tests
{
[TestFixture]
public class ComponentBindingTests
{
[Test]
public void BindingCalledForExplicitType()
{
AGSEmptyEntity entity = new AGSEmptyEntity("test", Mocks.GetResolver());
AGSCropSelfComponent crop = new AGSCropSelfComponent();
bool bindingCalled = false;
entity.Bind<ICropSelfComponent>(c =>
{
Assert.AreSame(crop, c);
bindingCalled = true;
}, _ => Assert.Fail("Component was somehow removed"));
Assert.IsFalse(bindingCalled);
entity.AddComponent<ICropSelfComponent>(crop);
Assert.IsTrue(bindingCalled);
}
[Test]
public void BindingCalledForExplicitTypeAlreadyAdded()
{
AGSEmptyEntity entity = new AGSEmptyEntity("test" + Guid.NewGuid(), Mocks.GetResolver());
AGSCropSelfComponent crop = new AGSCropSelfComponent();
entity.AddComponent<ICropSelfComponent>(crop);
bool bindingCalled = false;
entity.Bind<ICropSelfComponent>(c =>
{
Assert.AreSame(crop, c);
bindingCalled = true;
}, _ => Assert.Fail("Component was somehow removed"));
Assert.IsTrue(bindingCalled);
}
}
}
|
artistic-2.0
|
C#
|
680bdacedce8361e925ea609bd9c3e45cf6ea377
|
Update LabelPlaceEvent.cs
|
Yonom/BotBits
|
BotBits/Packages/MessageHandler/Events/Internal/LabelPlaceEvent.cs
|
BotBits/Packages/MessageHandler/Events/Internal/LabelPlaceEvent.cs
|
using PlayerIOClient;
namespace BotBits.Events
{
/// <summary>
/// Occurs when someone places label block.
/// </summary>
/// <seealso cref="PlayerEvent{T}" />
[ReceiveEvent("lb")]
internal sealed class LabelPlaceEvent : PlayerEvent<LabelPlaceEvent>
{
/// <summary>
/// Initializes a new instance of the <see cref="LabelPlaceEvent" /> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="client"></param>
internal LabelPlaceEvent(BotBitsClient client, Message message)
: base(client, message, 5)
{
this.X = message.GetInteger(0);
this.Y = message.GetInteger(1);
this.Id = message.GetInteger(2);
this.Text = message.GetString(3);
this.TextColor = message.GetString(4);
this.WrapWidth = message.GetUInt(5);
}
/// <summary>
/// Gets or sets the wrap width of the text.
/// </summary>
/// <value>
/// The wrap width of the text.
/// </value>
public uint WrapWidth { get; set; }
/// <summary>
/// Gets or sets the color of the text.
/// </summary>
/// <value>
/// The color of the text.
/// </value>
public string TextColor { get; set; }
/// <summary>
/// Gets or sets the text.
/// </summary>
/// <value>The text.</value>
public string Text { get; set; }
/// <summary>
/// Gets or sets the block id.
/// </summary>
/// <value>
/// The block id.
/// </value>
public int Id { get; set; }
/// <summary>
/// Gets or sets the coordinate x.
/// </summary>
/// <value>The coordinate x.</value>
public int X { get; set; }
/// <summary>
/// Gets or sets the coordinate y.
/// </summary>
/// <value>The coordinate y.</value>
public int Y { get; set; }
}
}
|
using PlayerIOClient;
namespace BotBits.Events
{
/// <summary>
/// Occurs when someone places label block.
/// </summary>
/// <seealso cref="PlayerEvent{T}" />
[ReceiveEvent("lb")]
internal sealed class LabelPlaceEvent : PlayerEvent<LabelPlaceEvent>
{
/// <summary>
/// Initializes a new instance of the <see cref="LabelPlaceEvent" /> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="client"></param>
internal LabelPlaceEvent(BotBitsClient client, Message message)
: base(client, message, 5)
{
this.X = message.GetInteger(0);
this.Y = message.GetInteger(1);
this.Id = message.GetInteger(2);
this.Text = message.GetString(3);
this.TextColor = message.GetString(4);
this.WrapWidth = message.GetString(5);
}
/// <summary>
/// Gets or sets the wrap width of the text.
/// </summary>
/// <value>
/// The wrap width of the text.
/// </value>
public string WrapWidth { get; set; }
/// <summary>
/// Gets or sets the color of the text.
/// </summary>
/// <value>
/// The color of the text.
/// </value>
public string TextColor { get; set; }
/// <summary>
/// Gets or sets the text.
/// </summary>
/// <value>The text.</value>
public string Text { get; set; }
/// <summary>
/// Gets or sets the block id.
/// </summary>
/// <value>
/// The block id.
/// </value>
public int Id { get; set; }
/// <summary>
/// Gets or sets the coordinate x.
/// </summary>
/// <value>The coordinate x.</value>
public int X { get; set; }
/// <summary>
/// Gets or sets the coordinate y.
/// </summary>
/// <value>The coordinate y.</value>
public int Y { get; set; }
}
}
|
mit
|
C#
|
2dd51b32f3526cc8f935483d2975dfc0fc8091ad
|
Mark 'RaygunMessageReceived' as serializable
|
OpenMagic/OpenMagic.ErrorTracker.Core,OpenMagic/OpenMagic.ErrorTracker.Core
|
source/OpenMagic.ErrorTracker.Core/Events/RaygunMessageReceived.cs
|
source/OpenMagic.ErrorTracker.Core/Events/RaygunMessageReceived.cs
|
using System;
using Mindscape.Raygun4Net.Messages;
namespace OpenMagic.ErrorTracker.Core.Events
{
[Serializable]
public class RaygunMessageReceived : IEvent
{
public RaygunMessageReceived(string apiKey, RaygunMessage raygunMessage)
{
EventId = Guid.NewGuid();
ApiKey = apiKey;
Message = raygunMessage;
}
public Guid EventId { get; }
public string ApiKey { get; }
public RaygunMessage Message { get; }
}
}
|
using System;
using Mindscape.Raygun4Net.Messages;
namespace OpenMagic.ErrorTracker.Core.Events
{
public class RaygunMessageReceived : IEvent
{
public RaygunMessageReceived(string apiKey, RaygunMessage raygunMessage)
{
EventId = Guid.NewGuid();
ApiKey = apiKey;
Message = raygunMessage;
}
public Guid EventId { get; }
public string ApiKey { get; }
public RaygunMessage Message { get; }
}
}
|
mit
|
C#
|
60df5b73bd5da3257c3b06bc2b9113334099b702
|
Add contracts
|
yfakariya/msgpack-rpc-cli,yonglehou/msgpack-rpc-cli
|
src/MsgPack.Rpc.Server/Rpc/Server/Dispatch/OperationDescription.cs
|
src/MsgPack.Rpc.Server/Rpc/Server/Dispatch/OperationDescription.cs
|
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using MsgPack.Rpc.Server.Protocols;
using MsgPack.Serialization;
namespace MsgPack.Rpc.Server.Dispatch
{
/// <summary>
/// Describes RPC service operation (method).
/// </summary>
public sealed class OperationDescription
{
private readonly ServiceDescription _service;
public ServiceDescription Service
{
get
{
Contract.Ensures( Contract.Result<ServiceDescription>() != null );
return this._service;
}
}
private readonly MethodInfo _method;
private readonly Func<ServerRequestContext, ServerResponseContext, Task> _operation;
public Func<ServerRequestContext, ServerResponseContext, Task> Operation
{
get
{
Contract.Ensures( Contract.Result<Func<ServerRequestContext, ServerResponseContext, Task>>() != null );
return this._operation;
}
}
private readonly string _id;
public string Id
{
get
{
Contract.Ensures( !String.IsNullOrEmpty( Contract.Result<string>() ) );
return this._id;
}
}
private OperationDescription( ServiceDescription service, MethodInfo method, string id, Func<ServerRequestContext, ServerResponseContext, Task> operation )
{
this._service = service;
this._method = method;
this._operation = operation;
this._id = id;
}
public static IEnumerable<OperationDescription> FromServiceDescription( RpcServerConfiguration configuration, SerializationContext serializationContext, ServiceDescription service )
{
if ( serializationContext == null )
{
throw new ArgumentNullException( "serializationContext" );
}
if ( service == null )
{
throw new ArgumentNullException( "service" );
}
Contract.Ensures( Contract.Result<IEnumerable<OperationDescription>>() != null );
Contract.Ensures( Contract.ForAll( Contract.Result<IEnumerable<OperationDescription>>(), item => item != null ) );
foreach ( var operation in service.ServiceType.GetMethods().Where( method => method.IsDefined( typeof( MessagePackRpcMethodAttribute ), true ) ) )
{
yield return FromServiceMethodCore( configuration ?? RpcServerConfiguration.Default, serializationContext, service, operation );
}
}
private static OperationDescription FromServiceMethodCore( RpcServerConfiguration configuration, SerializationContext serializationContext, ServiceDescription service, MethodInfo operation )
{
Contract.Requires( configuration != null );
Contract.Ensures( Contract.Result<OperationDescription>() != null );
var serviceInvoker = ServiceInvokerGenerator.Default.GetServiceInvoker( configuration, serializationContext, service, operation );
return new OperationDescription( service, operation, serviceInvoker.OperationId, serviceInvoker.InvokeAsync );
}
}
}
|
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using MsgPack.Serialization;
using MsgPack.Rpc.Server.Protocols;
namespace MsgPack.Rpc.Server.Dispatch
{
/// <summary>
/// Describes RPC service operation (method).
/// </summary>
public sealed class OperationDescription
{
private readonly ServiceDescription _service;
public ServiceDescription Service
{
get { return this._service; }
}
private readonly MethodInfo _method;
private readonly Func<ServerRequestContext, ServerResponseContext, Task> _operation;
public Func<ServerRequestContext, ServerResponseContext, Task> Operation
{
get { return this._operation; }
}
private readonly string _id;
public string Id
{
get { return this._id; }
}
private OperationDescription( ServiceDescription service, MethodInfo method, string id, Func<ServerRequestContext, ServerResponseContext, Task> operation )
{
this._service = service;
this._method = method;
this._operation = operation;
this._id = id;
}
public static IEnumerable<OperationDescription> FromServiceDescription( RpcServerConfiguration configuration, SerializationContext serializationContext, ServiceDescription service )
{
if ( serializationContext == null )
{
throw new ArgumentNullException( "serializationContext" );
}
if ( service == null )
{
throw new ArgumentNullException( "service" );
}
foreach ( var operation in service.ServiceType.GetMethods().Where( method => method.IsDefined( typeof( MessagePackRpcMethodAttribute ), true ) ) )
{
yield return FromServiceMethodCore( configuration ?? RpcServerConfiguration.Default, serializationContext, service, operation );
}
}
private static OperationDescription FromServiceMethodCore( RpcServerConfiguration configuration, SerializationContext serializationContext, ServiceDescription service, MethodInfo operation )
{
var serviceInvoker = ServiceInvokerGenerator.Default.GetServiceInvoker( configuration, serializationContext, service, operation );
return new OperationDescription( service, operation, serviceInvoker.OperationId, serviceInvoker.InvokeAsync );
}
}
}
|
apache-2.0
|
C#
|
b57cf5031134718977b06c8a86c7631365e7f6e7
|
Improve User Guide
|
Arcitectus/Sanderling
|
src/Sanderling/Sanderling.Exe/sample/script/beginners-autopilot.cs
|
src/Sanderling/Sanderling.Exe/sample/script/beginners-autopilot.cs
|
/*
This is a warp to 0km auto-pilot, making your travels faster and thus safer by directly warping to gates/stations.
The bot follows the route set in the in-game autopilot and uses the context menu to initiate warp and dock commands.
To use the bot, set the in-game autopilot route before starting the bot.
Make sure you are undocked before starting the bot because the bot does not undock.
*/
while(true)
{
var Measurement = Sanderling?.MemoryMeasurementParsed?.Value;
var ManeuverType = Measurement?.ShipUi?.Indication?.ManeuverType;
if(ShipManeuverTypeEnum.Warp == ManeuverType ||
ShipManeuverTypeEnum.Jump == ManeuverType)
goto loop; // do nothing while warping or jumping.
// from the set of route element markers in the Info Panel pick the one that represents the next Waypoint/System.
// We assume this is the one which is nearest to the topleft corner of the Screen which is at (0,0)
var RouteElementMarkerNext =
Measurement?.InfoPanelRoute?.RouteElementMarker
?.OrderByCenterDistanceToPoint(new Vektor2DInt(0, 0))?.FirstOrDefault();
if(null == RouteElementMarkerNext)
{
Host.Log("no route found in info panel.");
goto loop;
}
// rightclick the marker to open the contextmenu.
Sanderling.MouseClickRight(RouteElementMarkerNext);
// retrieve a new measurement.
Measurement = Sanderling?.MemoryMeasurementParsed?.Value;
// from the first menu, pick the first entry that contains "dock" or "jump".
var MenuEntry =
Measurement?.Menu?.FirstOrDefault()
?.Entry?.FirstOrDefault(candidate => candidate.Text.RegexMatchSuccessIgnoreCase("dock|jump"));
if(null == MenuEntry)
{
Host.Log("no suitable menu entry found.");
goto loop;
}
Host.Log("menu entry found. clicking to initiate warp.");
Sanderling.MouseClickLeft(MenuEntry);
loop:
// wait for four seconds before repeating.
Host.Delay(4000);
// make sure new measurement will be taken.
Sanderling.InvalidateMeasurement();
}
|
// This is a warp to 0km auto-pilot, making your travels faster and thus safer by directly warping to gates/stations.
while(true)
{
var Measurement = Sanderling?.MemoryMeasurementParsed?.Value;
var ManeuverType = Measurement?.ShipUi?.Indication?.ManeuverType;
if(ShipManeuverTypeEnum.Warp == ManeuverType ||
ShipManeuverTypeEnum.Jump == ManeuverType)
goto loop; // do nothing while warping or jumping.
// from the set of route element markers in the Info Panel pick the one that represents the next Waypoint/System.
// We assume this is the one which is nearest to the topleft corner of the Screen which is at (0,0)
var RouteElementMarkerNext =
Measurement?.InfoPanelRoute?.RouteElementMarker
?.OrderByCenterDistanceToPoint(new Vektor2DInt(0, 0))?.FirstOrDefault();
if(null == RouteElementMarkerNext)
{
Host.Log("no route found in info panel.");
goto loop;
}
// rightclick the marker to open the contextmenu.
Sanderling.MouseClickRight(RouteElementMarkerNext);
// retrieve a new measurement.
Measurement = Sanderling?.MemoryMeasurementParsed?.Value;
// from the first menu, pick the first entry that contains "dock" or "jump".
var MenuEntry =
Measurement?.Menu?.FirstOrDefault()
?.Entry?.FirstOrDefault(candidate => candidate.Text.RegexMatchSuccessIgnoreCase("dock|jump"));
if(null == MenuEntry)
{
Host.Log("no suitable menu entry found.");
goto loop;
}
Host.Log("menu entry found. clicking to initiate warp.");
Sanderling.MouseClickLeft(MenuEntry);
loop:
// wait for four seconds before repeating.
Host.Delay(4000);
// make sure new measurement will be taken.
Sanderling.InvalidateMeasurement();
}
|
apache-2.0
|
C#
|
f06ca9f66788de0a85de392eab07cfe6a070f454
|
Add summary descriptions to public extensions.
|
Cimpress-MCP/dotnet-core-httputils
|
src/Cimpress.Extensions.Http/HttpResponseMessageExtensions.cs
|
src/Cimpress.Extensions.Http/HttpResponseMessageExtensions.cs
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Cimpress.Extensions.Http
{
public static class HttpResponseMessageExtensions
{
/// <summary>
/// Logs a message using the injected logger and throws an exception when the status code indicates an unsuccessful response.
/// </summary>
/// <returns>Returns an awaitable Task.</returns>
/// <param name="message">Extension on a HttpResponseMessage.</param>
/// <param name="logger">Logger used to execute logging.</param>
/// <exception cref="NotSuccessHttpResponseException">Thrown when not success status code</exception>
public static async Task LogAndThrowIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
{
if (!message.IsSuccessStatusCode)
{
var formattedMsg = await LogMessage(message, logger);
throw new NotSuccessHttpResponseException(formattedMsg);
}
}
/// <summary>
/// Logs a message using the injected logger when the status code indicates an unsuccessful response.
/// </summary>
/// <param name="message">Extension on a HttpResponseMessage.</param>
/// <returns>Returns an awaitable Task.</returns>
/// <param name="logger">Logger used to execute logging.</param>
public static async Task LogIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
{
if (!message.IsSuccessStatusCode)
{
await LogMessage(message, logger);
}
}
/// <summary>
/// Throws an exception when the status code indicates an unsuccessful response.
/// </summary>
/// <param name="message">Extension on a HttpResponseMessage.</param>
/// <returns>Returns an awaitable Task.</returns>
/// <exception cref="NotSuccessHttpResponseException">Thrown when not success status code</exception>
public static async Task ThrowIfNotSuccessStatusCode(this HttpResponseMessage message)
{
if (!message.IsSuccessStatusCode)
{
var formattedMsg = await FormatErrorMessage(message);
throw new NotSuccessHttpResponseException(formattedMsg);
}
}
/// <summary>
/// Logs a message using the injected logger.
/// </summary>
/// <returns>Returns an awaitable Task.</returns>
/// <param name="message">Extension on a HttpResponseMessage.</param>
public static async Task<string> LogMessage(HttpResponseMessage message, ILogger logger)
{
string formattedMsg = await message.FormatErrorMessage();
logger.LogError(formattedMsg);
return formattedMsg;
}
public static async Task<string> FormatErrorMessage(this HttpResponseMessage message)
{
var msg = await message.Content.ReadAsStringAsync();
var formattedMsg = $"Error processing request. Status code was {message.StatusCode} when calling '{message.RequestMessage.RequestUri}', message was '{msg}'";
return formattedMsg;
}
}
}
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Cimpress.Extensions.Http
{
public static class HttpResponseMessageExtensions
{
public static async Task LogAndThrowIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
{
if (!message.IsSuccessStatusCode)
{
var formattedMsg = await LogMessage(message, logger);
throw new NotSuccessHttpResponseException(formattedMsg);
}
}
public static async Task LogIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
{
if (!message.IsSuccessStatusCode)
{
await LogMessage(message, logger);
}
}
public static async Task ThrowIfNotSuccessStatusCode(this HttpResponseMessage message)
{
if (!message.IsSuccessStatusCode)
{
var formattedMsg = await FormatErrorMessage(message);
throw new NotSuccessHttpResponseException(formattedMsg);
}
}
public static async Task<string> LogMessage(HttpResponseMessage message, ILogger logger)
{
string formattedMsg = await message.FormatErrorMessage();
logger.LogError(formattedMsg);
return formattedMsg;
}
public static async Task<string> FormatErrorMessage(this HttpResponseMessage message)
{
var msg = await message.Content.ReadAsStringAsync();
var formattedMsg = $"Error processing request. Status code was {message.StatusCode} when calling '{message.RequestMessage.RequestUri}', message was '{msg}'";
return formattedMsg;
}
}
}
|
apache-2.0
|
C#
|
fca30a47a7db80887022a21103ec43ba5bb1bfd2
|
Revert changes to assemblyinfo
|
nrkno/Nrk.HttpRequester
|
source/Nrk.HttpRequester/Properties/AssemblyInfo.cs
|
source/Nrk.HttpRequester/Properties/AssemblyInfo.cs
|
// <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitleAttribute("NRK.HttpRequester")]
[assembly: AssemblyProductAttribute("NRK.HttpRequester")]
[assembly: AssemblyDescriptionAttribute("Library for sending Http Requests, including a fluent interface for creating HttpClient instances")]
[assembly: AssemblyVersionAttribute("1.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: AssemblyFileVersionAttribute("1.0.0")]
[assembly: GuidAttribute("d51e7a23-73d5-49a1-be63-f73e432e9ab3")]
[assembly: AssemblyMetadataAttribute("githash","df607ccdd20d7d6946fc93bc382c4734a81a3be5")]
namespace System {
internal static class AssemblyVersionInformation {
internal const System.String AssemblyTitle = "NRK.HttpRequester";
internal const System.String AssemblyProduct = "NRK.HttpRequester";
internal const System.String AssemblyDescription = "Library for sending Http Requests, including a fluent interface for creating HttpClient instances";
internal const System.String AssemblyVersion = "1.0.0";
internal const System.String AssemblyInformationalVersion = "1.0.0";
internal const System.String AssemblyFileVersion = "1.0.0";
internal const System.String Guid = "d51e7a23-73d5-49a1-be63-f73e432e9ab3";
internal const System.String AssemblyMetadata_githash = "df607ccdd20d7d6946fc93bc382c4734a81a3be5";
}
}
|
// <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitleAttribute("NRK.HttpRequester")]
[assembly: AssemblyProductAttribute("NRK.HttpRequester")]
[assembly: AssemblyDescriptionAttribute("Library for sending Http Requests, including a fluent interface for creating HttpClient instances")]
[assembly: AssemblyVersionAttribute("0.0.0")]
[assembly: AssemblyInformationalVersionAttribute("0.0.0")]
[assembly: AssemblyFileVersionAttribute("0.0.0")]
[assembly: GuidAttribute("d51e7a23-73d5-49a1-be63-f73e432e9ab3")]
[assembly: AssemblyMetadataAttribute("githash","60890f4fee57fb30a3ca57260b4589b69ac40701")]
namespace System {
internal static class AssemblyVersionInformation {
internal const System.String AssemblyTitle = "NRK.HttpRequester";
internal const System.String AssemblyProduct = "NRK.HttpRequester";
internal const System.String AssemblyDescription = "Library for sending Http Requests, including a fluent interface for creating HttpClient instances";
internal const System.String AssemblyVersion = "0.0.0";
internal const System.String AssemblyInformationalVersion = "0.0.0";
internal const System.String AssemblyFileVersion = "0.0.0";
internal const System.String Guid = "d51e7a23-73d5-49a1-be63-f73e432e9ab3";
internal const System.String AssemblyMetadata_githash = "60890f4fee57fb30a3ca57260b4589b69ac40701";
}
}
|
mit
|
C#
|
81e5d6b08778aa72eb22d8ed67b331a28bd9a1e1
|
add some comments for unimplemented class
|
joeaudette/cloudscribe.SimpleContent,joeaudette/cloudscribe.SimpleContent
|
src/cloudscribe.Syndication.Web/Controllers/AtomController.cs
|
src/cloudscribe.Syndication.Web/Controllers/AtomController.cs
|
// Copyright (c) Source Tree Solutions, LLC. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Author: Joe Audette
// Created: 2016-04-01
// Last Modified: 2016-04-01
//
// TODO: implement? having used my best google fu it seems best practice is to only provide one feed
// https://blog.superfeedr.com/feeds/rss/atom/best%20practice/feed-publishing-best-practices/
// rather than both an rss feed and an atom feed
// since the rss feed is working and is probably all I really need I'm leaving this
// unimplemented for now. if someone else wants to implement it and send a pull request
// that would be great
namespace cloudscribe.Syndication.Web.Controllers
{
//http://www.atomenabled.org/developers/syndication/
//public class AtomController
//{
//}
}
|
// Copyright (c) Source Tree Solutions, LLC. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Author: Joe Audette
// Created: 2016-04-01
// Last Modified: 2016-04-01
//
namespace cloudscribe.Syndication.Web.Controllers
{
//http://www.atomenabled.org/developers/syndication/
public class AtomController
{
}
}
|
apache-2.0
|
C#
|
95980b370111233b06e3cb282306089af77d7553
|
Add merging of Def documents
|
Elevator89/RimWorld-Subtranslator
|
Elevator.Subtranslator/Program.cs
|
Elevator.Subtranslator/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommandLine;
using CommandLine.Text;
using System.IO;
using System.Xml.Linq;
namespace Elevator.Subtranslator
{
class Options
{
[Option('d', "defs", Required = true, HelpText = "Definition folder location.")]
public string DefsLocation { get; set; }
[Option('i', "injections", Required = true, HelpText = "Localized 'DefInjected' folder location.")]
public string InjectionsLocation { get; set; }
[Option('o', "output", Required = false, HelpText = "Output folder location.")]
public string OutputLocation { get; set; }
}
class DefDirectoryNameComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
string clearX = x.Replace("Defs", "").Replace("Def", "").TrimEnd('s');
string clearY = y.Replace("Defs", "").Replace("Def", "").TrimEnd('s');
return clearX == clearY;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
ParserResult<Options> parseResult = Parser.Default.ParseArguments<Options>(args);
if (parseResult.Errors.Any()) return;
Options options = parseResult.Value;
XDocument mergedDoc = MergeDefs(options.DefsLocation);
SaveXml(mergedDoc, Path.Combine(options.OutputLocation, "Defs.xml"));
}
static XDocument MergeDefs(string defsFullPath)
{
XDocument mergedXml = new XDocument();
XElement mergedDefs = new XElement("Defs");
mergedXml.Add(mergedDefs);
foreach (string defFilePath in Directory.EnumerateFiles(defsFullPath, "*.xml", SearchOption.AllDirectories))
{
XDocument defXml = LoadXml(defFilePath);
XElement defs = defXml.Root;
foreach (XElement def in defs.Elements())
{
mergedDefs.Add(new XElement(def));
}
}
return mergedXml;
}
static XDocument LoadXml(string filename)
{
using (StreamReader reader = File.OpenText(filename))
{
return XDocument.Load(reader, LoadOptions.PreserveWhitespace);
}
}
static void SaveXml(XDocument doc, string filename)
{
string output = doc.ToString(SaveOptions.None);
File.WriteAllText(filename, output);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommandLine;
using CommandLine.Text;
using System.IO;
namespace Elevator.Subtranslator
{
class Options
{
[Option('d', "defs", Required = true, HelpText = "Definition folder location.")]
public string DefsLocation { get; set; }
[Option('i', "injections", Required = true, HelpText = "Localized 'DefInjected' folder location.")]
public string InjectionsLocation { get; set; }
[Option('o', "output", Required = false, HelpText = "Output folder location.")]
public string OutputLocation { get; set; }
}
class DefDirectoryNameComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
string clearX = x.Replace("Defs", "").Replace("Def", "").TrimEnd('s');
string clearY = y.Replace("Defs", "").Replace("Def", "").TrimEnd('s');
return clearX == clearY;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
ParserResult<Options> parseResult = Parser.Default.ParseArguments<Options>(args);
if (parseResult.Errors.Any()) return;
Options options = parseResult.Value;
IEqualityComparer<string> defDirNameComparer = new DefDirectoryNameComparer();
Dictionary<string, string> injectionDirNameMap = new Dictionary<string, string>(defDirNameComparer);
foreach (string injDefDirFullPath in Directory.EnumerateDirectories(options.InjectionsLocation))
{
injectionDirNameMap[Path.GetFileName(injDefDirFullPath)] = injDefDirFullPath;
}
foreach (string defDirFullPath in Directory.EnumerateDirectories(options.DefsLocation))
{
string defDir = Path.GetFileName(defDirFullPath);
string injDir = injectionDirNameMap.Keys.FirstOrDefault(key => defDirNameComparer.Equals(defDir, key));
if (string.IsNullOrEmpty(injDir))
{
Console.WriteLine("{0} -> ---", defDir);
}
else
{
Console.WriteLine("{0} -> {1}", defDir, injDir);
}
}
}
}
}
|
apache-2.0
|
C#
|
eec50c99462d1bdd5f80a99650cec012c5fe23a3
|
add default permissions
|
thedillonb/octokit.net,forki/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,dampir/octokit.net,M-Zuber/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,SmithAndr/octokit.net,brramos/octokit.net,ivandrofly/octokit.net,gabrielweyer/octokit.net,yonglehou/octokit.net,khellang/octokit.net,fffej/octokit.net,hitesh97/octokit.net,octokit-net-test-org/octokit.net,geek0r/octokit.net,takumikub/octokit.net,TattsGroup/octokit.net,chunkychode/octokit.net,Sarmad93/octokit.net,khellang/octokit.net,shiftkey-tester/octokit.net,octokit-net-test-org/octokit.net,cH40z-Lord/octokit.net,nsnnnnrn/octokit.net,thedillonb/octokit.net,daukantas/octokit.net,dlsteuer/octokit.net,darrelmiller/octokit.net,shiftkey/octokit.net,dampir/octokit.net,naveensrinivasan/octokit.net,shana/octokit.net,M-Zuber/octokit.net,yonglehou/octokit.net,chunkychode/octokit.net,devkhan/octokit.net,Sarmad93/octokit.net,devkhan/octokit.net,hahmed/octokit.net,alfhenrik/octokit.net,shiftkey/octokit.net,editor-tools/octokit.net,mminns/octokit.net,gdziadkiewicz/octokit.net,SmithAndr/octokit.net,rlugojr/octokit.net,ivandrofly/octokit.net,gabrielweyer/octokit.net,octokit/octokit.net,kolbasov/octokit.net,magoswiat/octokit.net,shana/octokit.net,nsrnnnnn/octokit.net,bslliw/octokit.net,shiftkey-tester/octokit.net,ChrisMissal/octokit.net,michaKFromParis/octokit.net,SLdragon1989/octokit.net,gdziadkiewicz/octokit.net,kdolan/octokit.net,octokit-net-test/octokit.net,editor-tools/octokit.net,mminns/octokit.net,TattsGroup/octokit.net,fake-organization/octokit.net,SamTheDev/octokit.net,hahmed/octokit.net,SamTheDev/octokit.net,octokit/octokit.net,adamralph/octokit.net,alfhenrik/octokit.net,rlugojr/octokit.net,eriawan/octokit.net,Red-Folder/octokit.net,eriawan/octokit.net
|
Octokit/Models/Request/NewTeam.cs
|
Octokit/Models/Request/NewTeam.cs
|
using Octokit.Internal;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
public class NewTeam
{
public NewTeam(string name)
{
Name = name;
RepoNames = new Collection<string>();
Permission = Octokit.Permission.Pull;
}
/// <summary>
/// team name
/// </summary>
public string Name { get; set; }
/// <summary>
/// permission associated to this team
/// </summary>
public Permission Permission { get; set; }
/// <summary>
/// array of repo_names this team has permissions to
/// </summary>
//[Parameter(Key="repo_names")]
public Collection<string> RepoNames { get; private set; }
}
}
|
using Octokit.Internal;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
public class NewTeam
{
public NewTeam(string name)
{
Name = name;
RepoNames = new Collection<string>();
}
/// <summary>
/// team name
/// </summary>
public string Name { get; set; }
/// <summary>
/// permission associated to this team
/// </summary>
public Permission Permission { get; set; }
/// <summary>
/// array of repo_names this team has permissions to
/// </summary>
//[Parameter(Key="repo_names")]
public Collection<string> RepoNames { get; private set; }
}
}
|
mit
|
C#
|
f40388f996788348aa62af650b5740dba1ccf899
|
clean ups
|
SEEK-Jobs/pact-net,abhayachauhan/pact-net,SEEK-Jobs/pact-net,SEEK-Jobs/pact-net,mvdbuuse/pact-net,humblelistener/pact-net
|
PactNet/NancyContextExtensions.cs
|
PactNet/NancyContextExtensions.cs
|
using Nancy;
using PactNet.Mocks.MockHttpService.Models;
namespace PactNet
{
public static class NancyContextExtensions
{
const string MockRequest = "MockRequest";
const string MockResponse = "MockResponse";
public static PactProviderServiceRequest GetMockRequest(this NancyContext context)
{
return context.Items.ContainsKey(MockRequest)
? context.Items[MockRequest] as PactProviderServiceRequest
: null;
}
public static PactProviderServiceResponse GetMockResponse(this NancyContext context)
{
return context.Items.ContainsKey(MockResponse)
? context.Items[MockResponse] as PactProviderServiceResponse
: null;
}
public static void SetMockRequest(this NancyContext context, PactProviderServiceRequest mockRequest)
{
context.Items[MockRequest] = mockRequest;
}
public static void SetMockResponse(this NancyContext context, PactProviderServiceResponse mockResponse)
{
context.Items[MockResponse] = mockResponse;
}
}
}
|
using Nancy;
using PactNet.Mocks.MockHttpService.Models;
namespace PactNet
{
public static class NancyContextExtensions
{
public static PactProviderServiceRequest GetMockRequest(this NancyContext context)
{
return context.Items.ContainsKey("MockRequest")
? context.Items["MockRequest"] as PactProviderServiceRequest
: null;
}
public static PactProviderServiceResponse GetMockResponse(this NancyContext context)
{
return context.Items.ContainsKey("MockResponse")
? context.Items["MockResponse"] as PactProviderServiceResponse
: null;
}
public static void SetMockRequest(this NancyContext context, PactProviderServiceRequest mockRequest)
{
context.Items["MockRequest"] = mockRequest;
}
public static void SetMockResponse(this NancyContext context, PactProviderServiceResponse mockResponse)
{
context.Items["MockResponse"] = mockResponse;
}
}
}
|
mit
|
C#
|
f5ff41a3b8bb5046d7fec659e64cc5f6cbf2072d
|
Remove some unused methods.
|
aloneguid/storage
|
test/Storage.Net.Tests.Integration/Utils/Utility.cs
|
test/Storage.Net.Tests.Integration/Utils/Utility.cs
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
namespace Storage.Net.Tests.Integration.Utils
{
public static class Utility
{
public static void ClearTestData(string fileProjectRelativePath)
{
var fileName = fileProjectRelativePath.Split(Path.DirectorySeparatorChar).LastOrDefault();
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
public static void PrepareTestData(string fileProjectRelativePath)
{
var filePath = fileProjectRelativePath.Replace("/", @"\");
var fileName = fileProjectRelativePath.Split(Path.DirectorySeparatorChar).LastOrDefault();
var environmentDir = new DirectoryInfo(Environment.CurrentDirectory);
var itemPathUri = new Uri(Path.Combine(environmentDir?.Parent?.Parent?.Parent?.FullName, filePath));
var itemPath = itemPathUri.LocalPath;
var binFolderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var itemPathInBinUri = new Uri(Path.Combine(binFolderPath, fileName));
var itemPathInBin = itemPathInBinUri.LocalPath;
if (File.Exists(itemPath) && !File.Exists(itemPathInBin))
{
File.Copy(itemPath, itemPathInBin);
}
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
namespace Storage.Net.Tests.Integration.Utils
{
public static class Utility
{
public static string CalculateMd5(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
return CalculateMd5(stream);
}
}
public static string CalculateMd5(Stream stream)
{
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
public static string CalculateMd5(string path)
{
using (var stream = File.OpenRead(path))
{
return CalculateMd5(stream);
}
}
public static bool VerifyMd5Hash(string lHash, string rHash)
{
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
return 0 == comparer.Compare(lHash, rHash);
}
public static void ClearTestData(string fileProjectRelativePath)
{
var fileName = fileProjectRelativePath.Split(Path.DirectorySeparatorChar).LastOrDefault();
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
public static void PrepareTestData(string fileProjectRelativePath)
{
var filePath = fileProjectRelativePath.Replace("/", @"\");
var fileName = fileProjectRelativePath.Split(Path.DirectorySeparatorChar).LastOrDefault();
var environmentDir = new DirectoryInfo(Environment.CurrentDirectory);
var itemPathUri = new Uri(Path.Combine(environmentDir?.Parent?.Parent?.Parent?.FullName, filePath));
var itemPath = itemPathUri.LocalPath;
var binFolderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var itemPathInBinUri = new Uri(Path.Combine(binFolderPath, fileName));
var itemPathInBin = itemPathInBinUri.LocalPath;
if (File.Exists(itemPath) && !File.Exists(itemPathInBin))
{
File.Copy(itemPath, itemPathInBin);
}
}
}
}
|
mit
|
C#
|
7dc16a9390b8ef37f1bbc2056ea7fe3977bcfbbd
|
add unit test for DistributeByHost()
|
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
|
tests/FilterLists.Agent.Tests/UriExtensionsTests.cs
|
tests/FilterLists.Agent.Tests/UriExtensionsTests.cs
|
using System;
using System.Collections.Generic;
using FilterLists.Agent.Extensions;
using Xunit;
namespace FilterLists.Agent.Tests
{
public class UriExtensionsTests
{
[Fact]
public void IsValidUrl_WithValidUrl_ReturnsTrue()
{
const string uriString = "https://www.google.com/";
var uri = new Uri(uriString);
var sut = uri.IsValidUrl();
Assert.True(sut);
}
[Fact]
public void DistributeByHost_HasOverweightHost_DistributesEvenly()
{
var uris = new List<Uri>
{
new Uri("https://www.google.com/"),
new Uri("https://www.google.com/"),
new Uri("https://www.google.com/"),
new Uri("https://www.facebook.com/"),
new Uri("https://www.facebook.com/")
};
var sut = uris.DistributeByHost();
var expected = new List<Uri>
{
new Uri("https://www.google.com/"),
new Uri("https://www.facebook.com/"),
new Uri("https://www.google.com/"),
new Uri("https://www.facebook.com/"),
new Uri("https://www.google.com/")
};
Assert.Equal(expected, sut);
}
}
}
|
using System;
using FilterLists.Agent.Extensions;
using Xunit;
namespace FilterLists.Agent.Tests
{
public class UriExtensionsTests
{
[Fact]
public void IsValidUrl_WithValidUrl_ReturnsTrue()
{
const string uriString = "https://www.google.com/";
var uri = new Uri(uriString);
var sut = uri.IsValidUrl();
Assert.True(sut);
}
}
}
|
mit
|
C#
|
cf9113522302ab6e4428910e1ff1ae3c8153ff68
|
Remove unused code line from DerAsnUtf8StringTests
|
huysentruitw/pem-utils
|
tests/DerConverter.Tests/Asn/KnownTypes/DerAsnUtf8StringTests.cs
|
tests/DerConverter.Tests/Asn/KnownTypes/DerAsnUtf8StringTests.cs
|
using DerConverter.Asn;
using DerConverter.Asn.KnownTypes;
using NUnit.Framework;
namespace DerConverter.Tests.Asn.KnownTypes
{
[TestFixture]
public class DerAsnUtf8StringTests : Base<DerAsnUtf8String, string>
{
public DerAsnUtf8StringTests() : base(DerAsnIdentifiers.Primitive.Utf8String) { }
[TestCase("test", 0x74, 0x65, 0x73, 0x74)]
[TestCase(@"¯\_(ツ)_/¯", 0xC2, 0xAF, 0x5C, 0x5F, 0x28, 0xE3, 0x83, 0x84, 0x29, 0x5F, 0x2F, 0xC2, 0xAF)]
public override void DecodeConstructor_ShouldDecodeCorrectly(string expectedValue, params int[] rawData)
{
base.DecodeConstructor_ShouldDecodeCorrectly(expectedValue, rawData);
}
[TestCase("test", 0x74, 0x65, 0x73, 0x74)]
[TestCase(@"¯\_(ツ)_/¯", 0xC2, 0xAF, 0x5C, 0x5F, 0x28, 0xE3, 0x83, 0x84, 0x29, 0x5F, 0x2F, 0xC2, 0xAF)]
public override void Encode_ShouldEncodeCorrectly(string value, params int[] expectedRawData)
{
base.Encode_ShouldEncodeCorrectly(value, expectedRawData);
}
}
}
|
using DerConverter.Asn;
using DerConverter.Asn.KnownTypes;
using NUnit.Framework;
namespace DerConverter.Tests.Asn.KnownTypes
{
[TestFixture]
public class DerAsnUtf8StringTests : Base<DerAsnUtf8String, string>
{
public DerAsnUtf8StringTests() : base(DerAsnIdentifiers.Primitive.Utf8String) { }
[TestCase("test", 0x74, 0x65, 0x73, 0x74)]
[TestCase(@"¯\_(ツ)_/¯", 0xC2, 0xAF, 0x5C, 0x5F, 0x28, 0xE3, 0x83, 0x84, 0x29, 0x5F, 0x2F, 0xC2, 0xAF)]
public override void DecodeConstructor_ShouldDecodeCorrectly(string expectedValue, params int[] rawData)
{
var d = System.Text.Encoding.UTF8.GetBytes(@"¯\_(ツ)_/¯");
base.DecodeConstructor_ShouldDecodeCorrectly(expectedValue, rawData);
}
[TestCase("test", 0x74, 0x65, 0x73, 0x74)]
[TestCase(@"¯\_(ツ)_/¯", 0xC2, 0xAF, 0x5C, 0x5F, 0x28, 0xE3, 0x83, 0x84, 0x29, 0x5F, 0x2F, 0xC2, 0xAF)]
public override void Encode_ShouldEncodeCorrectly(string value, params int[] expectedRawData)
{
base.Encode_ShouldEncodeCorrectly(value, expectedRawData);
}
}
}
|
apache-2.0
|
C#
|
7130394de5a8824cd5bc5b7759df40f2a667fc69
|
Reduce usage of reflection
|
punker76/Fluent.Ribbon,fluentribbon/Fluent.Ribbon,fluentribbon/Fluent.Ribbon
|
Fluent.Ribbon/Automation/Peers/RibbonControlDataAutomationPeer.cs
|
Fluent.Ribbon/Automation/Peers/RibbonControlDataAutomationPeer.cs
|
namespace Fluent.Automation.Peers
{
using System.Windows.Automation.Peers;
/// <summary>
/// Automation peer for ribbon control items.
/// </summary>
public class RibbonControlDataAutomationPeer : ItemAutomationPeer
{
/// <summary>
/// Creates a new instance.
/// </summary>
public RibbonControlDataAutomationPeer(object item, ItemsControlAutomationPeer itemsControlPeer)
: base(item, itemsControlPeer)
{
}
/// <inheritdoc />
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.DataItem;
}
/// <inheritdoc />
protected override string GetClassNameCore()
{
return "ItemsControlItem";
}
}
}
|
namespace Fluent.Automation.Peers
{
using System.Windows.Automation.Peers;
using Fluent.Extensions;
/// <summary>
/// Automation peer for ribbon control items.
/// </summary>
public class RibbonControlDataAutomationPeer : ItemAutomationPeer
{
/// <summary>
/// Creates a new instance.
/// </summary>
public RibbonControlDataAutomationPeer(object item, ItemsControlAutomationPeer itemsControlPeer)
: base(item, itemsControlPeer)
{
}
/// <inheritdoc />
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.ListItem;
}
/// <inheritdoc />
protected override string GetClassNameCore()
{
var wrapperPeer = this.GetWrapperPeer();
if (wrapperPeer != null)
{
return wrapperPeer.GetClassName();
}
return string.Empty;
}
/// <inheritdoc />
public override object GetPattern(PatternInterface patternInterface)
{
object result = null;
var wrapperPeer = this.GetWrapperPeer();
if (wrapperPeer != null)
{
result = wrapperPeer.GetPattern(patternInterface);
}
return result;
}
}
}
|
mit
|
C#
|
ba18a98fd4f915f6ffb69db1d8d021b984860909
|
Handle Kayak framwork's Invoking event - here we can catch the total number of requests made, as well as do some basic authentication.
|
sgrassie/csharp-github-api,bmroberts1987/csharp-github-api
|
csharp-github-api.IntegrationTests/IntegrationTestBase.cs
|
csharp-github-api.IntegrationTests/IntegrationTestBase.cs
|
using System;
using System.Linq;
using System.Text;
using Kayak;
using Kayak.Framework;
namespace csharp_github_api.IntegrationTests
{
public abstract class IntegrationTestBase : IDisposable
{
protected readonly KayakServer WebServer = new KayakServer();
protected string BaseUrl = "http://localhost:8080";
protected int RequestCount;
protected IntegrationTestBase()
{
var framework = WebServer.UseFramework();
framework.Invoking += framework_Invoking;
WebServer.Start();
}
void framework_Invoking(object sender, InvokingEventArgs e)
{
RequestCount++;
var header = e.Invocation.Context.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(header))
{
var parts = Encoding.ASCII.GetString(Convert.FromBase64String(header.Substring("Basic ".Length))).Split(':');
if (parts.Count() == 2)
{
// Purely an aid to unit testing.
e.Invocation.Context.Response.Headers.Add("Authenticated", "true");
// We don't want to write anything here because it will interfere with our json response from the Services
//e.Invocation.Context.Response.Write(string.Join("|", parts));
}
}
}
public void Dispose()
{
WebServer.Stop();
}
}
}
|
using System;
using Kayak;
using Kayak.Framework;
namespace csharp_github_api.IntegrationTests
{
public abstract class IntegrationTestBase : IDisposable
{
protected readonly KayakServer WebServer = new KayakServer();
protected string BaseUrl = "http://localhost:8080";
protected IntegrationTestBase()
{
WebServer.UseFramework();
WebServer.Start();
}
public void Dispose()
{
WebServer.Stop();
}
}
}
|
apache-2.0
|
C#
|
f8a6258e92571627a36f3c08c9258036d67f6eae
|
Update IDeviceInfo.cs
|
labdogg1003/Xamarin.Plugins,JC-Chris/Xamarin.Plugins,LostBalloon1/Xamarin.Plugins,predictive-technology-laboratory/Xamarin.Plugins,jamesmontemagno/Xamarin.Plugins,tim-hoff/Xamarin.Plugins,monostefan/Xamarin.Plugins
|
DeviceInfo/DeviceInfo/DeviceInfo.Plugin.Abstractions/IDeviceInfo.cs
|
DeviceInfo/DeviceInfo/DeviceInfo.Plugin.Abstractions/IDeviceInfo.cs
|
using System;
/*
* Ported with permission from: Thomasz Cielecki @Cheesebaron
* AppId: https://github.com/Cheesebaron/Cheesebaron.MvxPlugins
*/
//---------------------------------------------------------------------------------
// Copyright 2013 Tomasz Cielecki (tomasz@ostebaronen.dk)
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
// INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing
// permissions and limitations under the License.
//---------------------------------------------------------------------------------
namespace DeviceInfo.Plugin.Abstractions
{
/// <summary>
/// Interface for DeviceInfo
/// </summary>
public interface IDeviceInfo
{
/// <summary>
/// Generates a an AppId optionally using the PhoneId a prefix and a suffix and a Guid to ensure uniqueness
///
/// The AppId format is as follows {prefix}guid{phoneid}{suffix}, where parts in {} are optional.
/// </summary>
/// <param name="usingPhoneId">Setting this to true adds the device specific id to the AppId (remember to give the app the correct permissions)</param>
/// <param name="prefix">Sets the prefix of the AppId</param>
/// <param name="suffix">Sets the suffix of the AppId</param>
/// <returns></returns>
string GenerateAppId(bool usingPhoneId = false, string prefix = null, string suffix = null);
/// <summary>
/// This is the device specific Id (remember the correct permissions in your app to use this)
/// </summary>
string Id { get; }
/// <summary>
/// Get the model of the device
/// </summary>
string Model { get; }
/// <summary>
/// Get the version of the Operating System
/// </summary>
string Version { get; }
/// <summary>
/// Get the platform of the device
/// </summary>
Platform Platform { get; }
}
}
|
using System;
/*
* Ported with permission from: Thomasz Cielecki @Cheesebaron
* AppId: https://github.com/Cheesebaron/Cheesebaron.MvxPlugins
*/
namespace DeviceInfo.Plugin.Abstractions
{
/// <summary>
/// Interface for DeviceInfo
/// </summary>
public interface IDeviceInfo
{
/// <summary>
/// Generates a an AppId optionally using the PhoneId a prefix and a suffix and a Guid to ensure uniqueness
///
/// The AppId format is as follows {prefix}guid{phoneid}{suffix}, where parts in {} are optional.
/// </summary>
/// <param name="usingPhoneId">Setting this to true adds the device specific id to the AppId (remember to give the app the correct permissions)</param>
/// <param name="prefix">Sets the prefix of the AppId</param>
/// <param name="suffix">Sets the suffix of the AppId</param>
/// <returns></returns>
string GenerateAppId(bool usingPhoneId = false, string prefix = null, string suffix = null);
/// <summary>
/// This is the device specific Id (remember the correct permissions in your app to use this)
/// </summary>
string Id { get; }
/// <summary>
/// Get the model of the device
/// </summary>
string Model { get; }
/// <summary>
/// Get the version of the Operating System
/// </summary>
string Version { get; }
/// <summary>
/// Get the platform of the device
/// </summary>
Platform Platform { get; }
}
}
|
mit
|
C#
|
a76ca511f9ef23868e35f31aaa03743e8d710c25
|
Increase timeout for GetNodeVersionTestsAsync.
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Tests/UnitTests/BitcoinCore/SerialNodeBuildingTests.cs
|
WalletWasabi.Tests/UnitTests/BitcoinCore/SerialNodeBuildingTests.cs
|
using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.BitcoinCore;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.BitcoinCore
{
/// <summary>
/// The test in this collection is time-sensitive, therefore this test collection is run in a special way:
/// Parallel-capable test collections will be run first (in parallel), followed by this parallel-disabled test collections (run sequentially).
/// </summary>
/// <seealso href="https://xunit.net/docs/running-tests-in-parallel.html#parallelism-in-test-frameworks"/>
[Collection("Serial unit tests collection")]
public class SerialNodeBuildingTests
{
[Fact]
public async Task GetNodeVersionTestsAsync()
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
Version version = await CoreNode.GetVersionAsync(cts.Token);
Assert.Equal(WalletWasabi.Helpers.Constants.BitcoinCoreVersion, version);
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.BitcoinCore;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.BitcoinCore
{
/// <summary>
/// The test in this collection is time-sensitive, therefore this test collection is run in a special way:
/// Parallel-capable test collections will be run first (in parallel), followed by this parallel-disabled test collections (run sequentially).
/// </summary>
/// <seealso href="https://xunit.net/docs/running-tests-in-parallel.html#parallelism-in-test-frameworks"/>
[Collection("Serial unit tests collection")]
public class SerialNodeBuildingTests
{
[Fact]
public async Task GetNodeVersionTestsAsync()
{
using var cts = new CancellationTokenSource(7000);
Version version = await CoreNode.GetVersionAsync(cts.Token);
Assert.Equal(WalletWasabi.Helpers.Constants.BitcoinCoreVersion, version);
}
}
}
|
mit
|
C#
|
5986a3a7ce1617f97e40f9b6b7baf6dae21d5f83
|
Update summaries
|
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity
|
Assets/MRTK/Core/Definitions/Utilities/VolumeType.cs
|
Assets/MRTK/Core/Definitions/Utilities/VolumeType.cs
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// The possible shapes of bounding volumes for spatial awareness of the user's surroundings.
/// </summary>
public enum VolumeType
{
/// <summary>
/// No specified type.
/// </summary>
None = 0,
/// <summary>
/// Cubic volume aligned with the coordinate axes.
/// </summary>
AxisAlignedCube,
/// <summary>
/// Cubic volume aligned with the user.
/// </summary>
UserAlignedCube,
/// <summary>
/// Spherical volume.
/// </summary>
Sphere
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// todo
/// </summary>
public enum VolumeType
{
/// <summary>
/// No Specified type.
/// </summary>
None = 0,
/// <summary>
/// Cubic volume aligned with the coordinate axes.
/// </summary>
AxisAlignedCube,
/// <summary>
/// Cubic volume aligned with the user.
/// </summary>
UserAlignedCube,
/// <summary>
/// Spherical volume.
/// </summary>
Sphere
}
}
|
mit
|
C#
|
3249b4ac75e94753861d4d4b18f10ecbf0f769ae
|
Fix parsing error
|
Evorlor/Fitachi,Evorlor/Fitachi,Evorlor/Fitachi
|
Assets/Scripts/AdventureScripts/AdventuringPlayer.cs
|
Assets/Scripts/AdventureScripts/AdventuringPlayer.cs
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AdventuringPlayer : MonoBehaviour {
private int AttackDamage;
private float attackSpeed;
public float weakenPlayerMultiplier = 10.0f;
List<Enemy> enemies = new List<Enemy>();
void Awake()
{
attackSpeed = float.Parse(FitbitRestClient.Activities.lifetime.total.distance) / 2 / weakenPlayerMultiplier;
AttackDamage = (int)(float.Parse(FitbitRestClient.Activities.lifetime.total.distance) / weakenPlayerMultiplier);
}
// Use this for initialization
void Start () {
enemies = new List<Enemy>();
InvokeRepeating("attackEnemies", 0, attackSpeed);
Physics.queriesHitTriggers = true;
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D attackedMonster) {
if (attackedMonster.tag=="Monster") {
enemies.Add(attackedMonster.GetComponent<Enemy>());
}
}
void OnTriggerExit2D(Collider2D attackedMonster) {
if (attackedMonster.tag == "Monster") {
enemies.Remove(attackedMonster.GetComponent<Enemy>());
}
}
private void attackEnemies() {
foreach (Enemy monster in enemies) {
monster.TakeDamage(AttackDamage);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AdventuringPlayer : MonoBehaviour {
private int AttackDamage;
private float attackSpeed;
public float weakenPlayerMultiplier = 10.0f;
List<Enemy> enemies = new List<Enemy>();
void Awake()
{
attackSpeed = int.Parse(FitbitRestClient.Activities.lifetime.total.distance) / 2 / weakenPlayerMultiplier;
AttackDamage = (int)(int.Parse(FitbitRestClient.Activities.lifetime.total.distance) / weakenPlayerMultiplier);
}
// Use this for initialization
void Start () {
enemies = new List<Enemy>();
InvokeRepeating("attackEnemies", 0, attackSpeed);
Physics.queriesHitTriggers = true;
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D attackedMonster) {
if (attackedMonster.tag=="Monster") {
enemies.Add(attackedMonster.GetComponent<Enemy>());
}
}
void OnTriggerExit2D(Collider2D attackedMonster) {
if (attackedMonster.tag == "Monster") {
enemies.Remove(attackedMonster.GetComponent<Enemy>());
}
}
private void attackEnemies() {
foreach (Enemy monster in enemies) {
monster.TakeDamage(AttackDamage);
}
}
}
|
mit
|
C#
|
c540f90e4a8a37138c96e4dc56d13631e7991ce5
|
Remove Sample Model
|
kgiszewski/Archetype,imulus/Archetype,Nicholas-Westby/Archetype,kipusoep/Archetype,imulus/Archetype,kgiszewski/Archetype,imulus/Archetype,kgiszewski/Archetype,kjac/Archetype,tomfulton/Archetype,kipusoep/Archetype,tomfulton/Archetype,Nicholas-Westby/Archetype,Nicholas-Westby/Archetype,tomfulton/Archetype,kjac/Archetype,kipusoep/Archetype,kjac/Archetype
|
app/Umbraco/Umbraco.Archetype/PropertyConverters/ArchetypeValueConverter.cs
|
app/Umbraco/Umbraco.Archetype/PropertyConverters/ArchetypeValueConverter.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Models.PublishedContent;
using Archetype.Umbraco.Models;
using Archetype.Umbraco.Extensions;
namespace Archetype.Umbraco.PropertyConverters
{
/* based on the Tim Geyssens sample at: https://github.com/TimGeyssens/MatrixPropEditor/blob/master/SamplePropertyValueConverter/SamplePropertyValueConverter/MatrixValueConverter.cs */
[PropertyValueType(typeof(Archetype.Umbraco.Models.Archetype))]
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
public class ArchetypeValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(PublishedPropertyType propertyType)
{
return propertyType.PropertyEditorAlias.Equals("Imulus.Archetype");
}
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
if (source == null) return null;
var sourceString = source.ToString();
if (sourceString.DetectIsJson())
{
try
{
var archetype = JsonConvert.DeserializeObject <Archetype.Umbraco.Models.Archetype> (sourceString);
return archetype;
}
catch (Exception ex)
{
return null;
}
}
return sourceString;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Models.PublishedContent;
using Archetype.Umbraco.Models;
using Archetype.Umbraco.Extensions;
namespace Archetype.Umbraco.PropertyConverters
{
/* based on the Tim Geyssens sample at: https://github.com/TimGeyssens/MatrixPropEditor/blob/master/SamplePropertyValueConverter/SamplePropertyValueConverter/MatrixValueConverter.cs */
/* sample model
*
* {
"fieldsets": [
{
"alias": "FS1",
"remove": false,
"properties": [
{
"alias": "age",
"value": "abc"
},
{
"alias": "name",
"value": "123"
},
{
"alias": "blah",
"value": ""
},
{
"alias": "age2",
"value": ""
}
]
},
{
"alias": "FS2",
"remove": false,
"properties": [
{
"alias": "foo",
"value": ""
},
{
"alias": "bar",
"value": ""
}
]
}
]
}
*
*/
[PropertyValueType(typeof(Archetype.Umbraco.Models.Archetype))]
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
public class ArchetypeValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(PublishedPropertyType propertyType)
{
return propertyType.PropertyEditorAlias.Equals("Imulus.Archetype");
}
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
if (source == null) return null;
var sourceString = source.ToString();
if (sourceString.DetectIsJson())
{
try
{
var archetype = JsonConvert.DeserializeObject <Archetype.Umbraco.Models.Archetype> (sourceString);
return archetype;
}
catch (Exception ex)
{
return null;
}
}
return sourceString;
}
}
}
|
mit
|
C#
|
de57da81802d9653b0eb57f39e600df98502e08c
|
add method for applying createdOn and modifiedOn on data models
|
olebg/car-mods-heaven,olebg/car-mods-heaven
|
CarModsHeaven/CarModsHeaven/CarModsHeaven.Data/SqlDbContext.cs
|
CarModsHeaven/CarModsHeaven/CarModsHeaven.Data/SqlDbContext.cs
|
using CarModsHeaven.Data.Models;
using CarModsHeaven.Data.Models.Contracts;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Data.Entity;
using System.Linq;
namespace CarModsHeaven.Data
{
public class SqlDbContext : IdentityDbContext<User>
{
public SqlDbContext()
: base("LocalConnection", throwIfV1Schema: false)
{
}
public IDbSet<Project> Projects { get; set; }
public override int SaveChanges()
{
this.ApplyAuditInfoRules();
return base.SaveChanges();
}
private void ApplyAuditInfoRules()
{
foreach (var entry in
this.ChangeTracker.Entries()
.Where(
e =>
e.Entity is IAuditable && ((e.State == EntityState.Added) || (e.State == EntityState.Modified))))
{
var entity = (IAuditable)entry.Entity;
if (entry.State == EntityState.Added && entity.CreatedOn == default(DateTime))
{
entity.CreatedOn = DateTime.Now;
}
else
{
entity.ModifiedOn = DateTime.Now;
}
}
}
public static SqlDbContext Create()
{
return new SqlDbContext();
}
}
}
|
using CarModsHeaven.Data.Models;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
namespace CarModsHeaven.Data
{
public class SqlDbContext : IdentityDbContext<User>
{
public SqlDbContext()
: base("LocalConnection", throwIfV1Schema: false)
{
}
public IDbSet<Project> Projects { get; set; }
public static SqlDbContext Create()
{
return new SqlDbContext();
}
}
}
|
mit
|
C#
|
5c8e7578d26ae8f05e5438a64fe4ddd0741e0dc1
|
fix binary to string serialization
|
OpenTl/OpenTl.Schema
|
src/OpenTl.Schema/Serialization/SerializationUtils.cs
|
src/OpenTl.Schema/Serialization/SerializationUtils.cs
|
namespace OpenTl.Schema.Serialization
{
using System;
using System.Linq;
using System.Text;
public class SerializationUtils
{
public static byte[] GetBytes(string str)
{
return Encoding.UTF8.GetBytes(str);
}
public static string GetString(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
public static byte[] GetBinaryFromString(string str)
{
return str.Select(Convert.ToByte).ToArray();
}
public static string GetStringFromBinary(byte[] bytes)
{
var chars = bytes.Select(Convert.ToChar).ToArray();
return new string(chars);
}
}
}
|
namespace OpenTl.Schema.Serialization
{
using System.Text;
public class SerializationUtils
{
public static byte[] GetBytes(string str)
{
return Encoding.UTF8.GetBytes(str);
}
public static string GetString(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
public static byte[] GetBinaryFromString(string str)
{
var bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static string GetStringFromBinary(byte[] bytes)
{
var length = bytes.Length / sizeof(char) + (bytes.Length % sizeof(char) != 0 ? 1 : 0);
var chars = new char[length];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
}
}
|
mit
|
C#
|
c408ab6ba220ba5fac53e69de9d43349c02f127e
|
Revert " replace duplicate short name, with backward compatibility (#23)"
|
esskar/Serialize.Linq
|
src/Serialize.Linq/Nodes/ConditionalExpressionNode.cs
|
src/Serialize.Linq/Nodes/ConditionalExpressionNode.cs
|
using System;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using Serialize.Linq.Interfaces;
namespace Serialize.Linq.Nodes
{
#region DataContract
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataContract]
#else
[DataContract(Name = "IF")]
#endif
#if !SILVERLIGHT
[Serializable]
#endif
#endregion
public class ConditionalExpressionNode : ExpressionNode<ConditionalExpression>
{
public ConditionalExpressionNode() { }
public ConditionalExpressionNode(INodeFactory factory, ConditionalExpression expression)
: base(factory, expression) { }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "IFF")]
#endif
#endregion
public ExpressionNode IfFalse { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "IFT")]
#endif
#endregion
public ExpressionNode IfTrue { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "C")]
#endif
#endregion
public ExpressionNode Test { get; set; }
/// <summary>
/// Initializes the specified expression.
/// </summary>
/// <param name="expression">The expression.</param>
protected override void Initialize(ConditionalExpression expression)
{
this.Test = this.Factory.Create(expression.Test);
this.IfTrue = this.Factory.Create(expression.IfTrue);
this.IfFalse = this.Factory.Create(expression.IfFalse);
}
/// <summary>
/// Converts this instance to an expression.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public override Expression ToExpression(ExpressionContext context)
{
return Expression.Condition(this.Test.ToExpression(context), this.IfTrue.ToExpression(context), this.IfFalse.ToExpression(context));
}
}
}
|
using System;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using Serialize.Linq.Interfaces;
namespace Serialize.Linq.Nodes
{
#region DataContract
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataContract]
#else
[DataContract(Name = "IF")]
#endif
#if !SILVERLIGHT
[Serializable]
#endif
#endregion
public class ConditionalExpressionNode : ExpressionNode<ConditionalExpression>
{
public ConditionalExpressionNode() { }
public ConditionalExpressionNode(INodeFactory factory, ConditionalExpression expression)
: base(factory, expression) { }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "IFF")]
#endif
#endregion
public ExpressionNode IfFalse { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "IFT")]
#endif
#endregion
public ExpressionNode IfTrue { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
#if SERIALIZE_LINQ_BORKED_VERION
[DataMember(EmitDefaultValue = false, Name = "T")]
#else
[DataMember(EmitDefaultValue = false, Name = "C")]
#endif
#endif
#endregion
public ExpressionNode Test { get; set; }
/// <summary>
/// Initializes the specified expression.
/// </summary>
/// <param name="expression">The expression.</param>
protected override void Initialize(ConditionalExpression expression)
{
this.Test = this.Factory.Create(expression.Test);
this.IfTrue = this.Factory.Create(expression.IfTrue);
this.IfFalse = this.Factory.Create(expression.IfFalse);
}
/// <summary>
/// Converts this instance to an expression.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public override Expression ToExpression(ExpressionContext context)
{
return Expression.Condition(this.Test.ToExpression(context), this.IfTrue.ToExpression(context), this.IfFalse.ToExpression(context));
}
}
}
|
mit
|
C#
|
8b71f642cce900ffd5123956d334f458d93d186d
|
Remove old logging line. Causes an exception if the directory doesn't exist.
|
mhinze/ZBuildLights,Vector241-Eric/ZBuildLights,mhinze/ZBuildLights,Vector241-Eric/ZBuildLights,mhinze/ZBuildLights,Vector241-Eric/ZBuildLights
|
src/ZBuildLightsUpdater/ZBuildLightsUpdaterService.cs
|
src/ZBuildLightsUpdater/ZBuildLightsUpdaterService.cs
|
using System;
using System.Configuration;
using System.Net;
using System.ServiceProcess;
using System.Timers;
using NLog;
namespace ZBuildLightsUpdater
{
public partial class ZBuildLightsUpdaterService : ServiceBase
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private Timer _timer;
private string _triggerUrl;
public ZBuildLightsUpdaterService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Log.Info("ZBuildLights Updater Service Starting...");
_timer = new Timer();
var updateSeconds = Int32.Parse(ConfigurationManager.AppSettings["UpdateIntervalSeconds"]);
_timer.Interval = TimeSpan.FromSeconds(updateSeconds).TotalMilliseconds;
_timer.Elapsed += OnTimerElapsed;
_timer.Start();
_triggerUrl = ConfigurationManager.AppSettings["TriggerUrl"];
Log.Info("ZBuildLights Updater Service Startup Complete.");
}
private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
Log.Debug("Initiating status refresh...");
var request = WebRequest.Create(_triggerUrl);
request.GetResponse();
Log.Debug("Status refresh complete.");
}
protected override void OnStop()
{
Log.Info("ZBuildLights Updater Service Stopping.");
}
}
}
|
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Timers;
using NLog;
namespace ZBuildLightsUpdater
{
public partial class ZBuildLightsUpdaterService : ServiceBase
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private Timer _timer;
private string _triggerUrl;
public ZBuildLightsUpdaterService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
File.AppendAllLines(@"c:\var\ZBuildLights\_logs\servicelog.txt", new[] {"Service starting..."});
Log.Info("ZBuildLights Updater Service Starting...");
_timer = new Timer();
var updateSeconds = Int32.Parse(ConfigurationManager.AppSettings["UpdateIntervalSeconds"]);
_timer.Interval = TimeSpan.FromSeconds(updateSeconds).TotalMilliseconds;
_timer.Elapsed += OnTimerElapsed;
_timer.Start();
_triggerUrl = ConfigurationManager.AppSettings["TriggerUrl"];
Log.Info("ZBuildLights Updater Service Startup Complete.");
}
private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
Log.Debug("Initiating status refresh...");
var request = WebRequest.Create(_triggerUrl);
request.GetResponse();
Log.Debug("Status refresh complete.");
}
protected override void OnStop()
{
Log.Info("ZBuildLights Updater Service Stopping.");
}
}
}
|
mit
|
C#
|
28b8c8c3c9083cfd53e0d8df704b93ddaf82a821
|
add FieldNameEvaluationHandler
|
LayoutFarm/PixelFarm
|
a_mini/projects/PixelFarm/TypeMirror/SimpleReflectionHelper.cs
|
a_mini/projects/PixelFarm/TypeMirror/SimpleReflectionHelper.cs
|
//MIT,2016, WinterDev
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace TypeMirror
{
/// <summary>
/// very base reflection helper
/// </summary>
static class SimpleReflectionHelper
{
public delegate string FieldNameEvaluationHandler(System.Reflection.FieldInfo f);
public static Dictionary<string, T> GetEnumFields<T>(FieldNameEvaluationHandler fieldNameEvaluationHandler = null)
{
Dictionary<string, T> results = new Dictionary<string, T>();
Type typeOfSample = typeof(T);
FieldInfo[] allFields = typeOfSample.GetFields(
BindingFlags.Static |
BindingFlags.NonPublic | BindingFlags.Public);
int j = allFields.Length;
for (int i = 0; i < j; ++i)
{
FieldInfo f = allFields[i];
object value = f.GetValue(null);
if (value is T)
{
if (fieldNameEvaluationHandler != null)
{
results.Add(fieldNameEvaluationHandler(f), (T)value);
}
else
{
results.Add(f.Name, (T)value);
}
}
}
return results;
}
public static List<T> GetEnumValues<T>()
{
List<T> values = new List<T>();
Type typeOfSample = typeof(T);
FieldInfo[] allFields = typeOfSample.GetFields(
BindingFlags.Static |
BindingFlags.NonPublic | BindingFlags.Public);
int j = allFields.Length;
for (int i = 0; i < j; ++i)
{
FieldInfo f = allFields[i];
object value = f.GetValue(null);
if (value is T)
{
values.Add((T)value);
}
}
return values;
}
}
}
|
//MIT,2016, WinterDev
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace TypeMirror
{
/// <summary>
/// very base reflection helper
/// </summary>
static class SimpleReflectionHelper
{
public static Dictionary<string, T> GetEnumFields<T>()
{
Dictionary<string, T> results = new Dictionary<string, T>();
Type typeOfSample = typeof(T);
FieldInfo[] allFields = typeOfSample.GetFields(
BindingFlags.Static |
BindingFlags.NonPublic | BindingFlags.Public);
int j = allFields.Length;
for (int i = 0; i < j; ++i)
{
FieldInfo f = allFields[i];
object value = f.GetValue(null);
if (value is T)
{
results.Add(f.Name, (T)value);
}
}
return results;
}
public static List<T> GetEnumValues<T>()
{
List<T> values = new List<T>();
Type typeOfSample = typeof(T);
FieldInfo[] allFields = typeOfSample.GetFields(
BindingFlags.Static |
BindingFlags.NonPublic | BindingFlags.Public);
int j = allFields.Length;
for (int i = 0; i < j; ++i)
{
FieldInfo f = allFields[i];
object value = f.GetValue(null);
if (value is T)
{
values.Add((T)value);
}
}
return values;
}
}
}
|
bsd-2-clause
|
C#
|
76c990877f592d73f5c665e7a4282828d5edec23
|
Update slack integration service
|
dncuug/dot-net.in.ua,dncuug/dot-net.in.ua,dncuug/dot-net.in.ua
|
src/Core/Services/Posting/SlackPostingService.cs
|
src/Core/Services/Posting/SlackPostingService.cs
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Slack.Webhooks;
using Slack.Webhooks.Blocks;
using Slack.Webhooks.Elements;
namespace Core.Services.Posting
{
public class SlackPostingService: IPostingService
{
private readonly ILogger<SlackPostingService> _logger;
private ISlackClient _client;
public SlackPostingService(string webHookUrl, ILogger<SlackPostingService> logger)
{
_logger = logger;
_client = new SlackClient(webHookUrl);
}
public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags)
{
try
{
var slackMessage = new SlackMessage
{
Channel = "#general",
IconEmoji = Emoji.Newspaper,
Blocks = new List<Block>
{
new Header()
{
Text = new TextObject($"Новости")
},
new Section
{
Text = new TextObject($":newspaper: {message}")
{
Emoji = true,
Type = TextObject.TextType.PlainText
}
},
new Divider(),
new Section
{
Text = new TextObject($"Узнать подробности: <{link}>")
{
Type = TextObject.TextType.Markdown, Verbatim = false
}
}
},
};
await _client.PostAsync(slackMessage);
_logger.LogInformation($"Message was sent to Slack");
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error during send message to Slack");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Slack.Webhooks;
namespace Core.Services.Posting
{
public class SlackPostingService: IPostingService
{
private readonly ILogger<SlackPostingService> _logger;
private ISlackClient _client;
public SlackPostingService(string webHookUrl, ILogger<SlackPostingService> logger)
{
_logger = logger;
_client = new SlackClient(webHookUrl);
}
public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags)
{
try
{
var slackMessage = new SlackMessage
{
Channel = "#general",
Text = $"{message}\n {link}",
IconEmoji = Emoji.Newspaper
};
await _client.PostAsync(slackMessage);
_logger.LogInformation($"Message was sent to Slack");
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error during send message to Slack");
}
}
}
}
|
mit
|
C#
|
e740deb9c38f3b742bf5ae165cdcb13e716f6749
|
Fix getmentions tests and add missing TestMethod attribute
|
msft-shahins/BotBuilder,stevengum97/BotBuilder,stevengum97/BotBuilder,yakumo/BotBuilder,msft-shahins/BotBuilder,yakumo/BotBuilder,stevengum97/BotBuilder,yakumo/BotBuilder,stevengum97/BotBuilder,yakumo/BotBuilder,msft-shahins/BotBuilder,msft-shahins/BotBuilder
|
CSharp/Tests/Microsoft.Bot.Builder.Tests/ActivityExTests.cs
|
CSharp/Tests/Microsoft.Bot.Builder.Tests/ActivityExTests.cs
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.Bot.Connector;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
namespace Microsoft.Bot.Builder.Tests
{
[TestClass]
public class ActivityExTests
{
[TestMethod]
public void HasContent_Test()
{
IMessageActivity activity = DialogTestBase.MakeTestMessage();
Assert.IsFalse(activity.HasContent());
activity.Text = "test";
Assert.IsTrue(activity.HasContent());
}
[TestMethod]
public void GetMentions_Test()
{
IMessageActivity activity = DialogTestBase.MakeTestMessage();
Assert.IsFalse(activity.GetMentions().Any());
activity.Entities = new List<Entity> { new Mention() { Text = "testMention" } };
// Cloning activity to resemble the incoming activity to bot
var clonedActivity = JsonConvert.DeserializeObject<Activity>(JsonConvert.SerializeObject(activity));
Assert.IsTrue(clonedActivity.GetMentions().Any());
Assert.AreEqual("testMention", clonedActivity.GetMentions()[0].Text);
}
}
}
|
using System.Linq;
using Microsoft.Bot.Connector;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Bot.Builder.Tests
{
[TestClass]
public class ActivityExTests
{
[TestMethod]
public void HasContent_Test()
{
IMessageActivity activity = DialogTestBase.MakeTestMessage();
Assert.IsFalse(activity.HasContent());
activity.Text = "test";
Assert.IsTrue(activity.HasContent());
}
public void GetMentions_Test()
{
IMessageActivity activity = DialogTestBase.MakeTestMessage();
Assert.IsFalse(activity.GetMentions().Any());
activity.Entities.Add(new Mention() { Text = "testMention" });
Assert.IsTrue(activity.GetMentions().Any());
Assert.AreEqual("testMention", activity.GetMentions()[0].Text);
}
}
}
|
mit
|
C#
|
4b4ce996c944704d896f2cd5d96d7d47d636e208
|
Initialize client timing at first parent tag (#309)
|
MiniProfiler/dotnet,MiniProfiler/dotnet
|
src/MiniProfiler.AspNetCore.Mvc/ProfileScriptTagHelper.cs
|
src/MiniProfiler.AspNetCore.Mvc/ProfileScriptTagHelper.cs
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace StackExchange.Profiling
{
/// <summary>
/// Tag helper to profile script execution in ASP.NET Core views, e.g.
/// <profile-script name="My Step" />
/// ...script blocks...
/// </profile-script>
/// Include as self closing to provide initialization only.
/// </summary>
[HtmlTargetElement("profile-script", TagStructure = TagStructure.NormalOrSelfClosing)]
public class ProfileScriptTagHelper : TagHelper
{
private const string ClientTimingKey = "MiniProfiler:ClientTiming";
/// <summary>
/// The <see cref="ViewContext"/> for this control, gets injected.
/// </summary>
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; }
/// <summary>
/// The name of this <see cref="MiniProfiler"/> step.
/// </summary>
[HtmlAttributeName("name")]
public string Name { get; set; }
/// <summary>
/// Renders the tag helper.
/// </summary>
/// <param name="context">The context we're rendering in.</param>
/// <param name="output">The output we're rendering to.</param>
/// <returns>The task to await.</returns>
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var isInitialized = ViewContext.HttpContext.Items.ContainsKey(ClientTimingKey);
ViewContext.HttpContext.Items[ClientTimingKey] = true;
output.TagName = null;
output.Content = await output.GetChildContentAsync();
if (MiniProfiler.Current == null)
return;
if (!isInitialized)
output.PreContent.AppendHtml(ClientTimingHelper.InitScript);
if (output.TagMode == TagMode.SelfClosing)
return;
output.PreContent.AppendHtml($"<script>mPt.start('{Name}')</script>");
output.PostContent.SetHtmlContent($"<script>mPt.end('{Name}')</script>");
}
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace StackExchange.Profiling
{
/// <summary>
/// Tag helper to profile script execution in ASP.NET Core views, e.g.
/// <profile-script name="My Step" />
/// ...script blocks...
/// </profile-script>
/// Include as self closing to provide initialization only.
/// </summary>
[HtmlTargetElement("profile-script", TagStructure = TagStructure.NormalOrSelfClosing)]
public class ProfileScriptTagHelper : TagHelper
{
private const string ClientTimingKey = "MiniProfiler:ClientTiming";
/// <summary>
/// The <see cref="ViewContext"/> for this control, gets injected.
/// </summary>
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; }
/// <summary>
/// The name of this <see cref="MiniProfiler"/> step.
/// </summary>
[HtmlAttributeName("name")]
public string Name { get; set; }
/// <summary>
/// Renders the tag helper.
/// </summary>
/// <param name="context">The context we're rendering in.</param>
/// <param name="output">The output we're rendering to.</param>
/// <returns>The task to await.</returns>
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = null;
output.Content = await output.GetChildContentAsync();
if (MiniProfiler.Current == null)
return;
if (!ViewContext.HttpContext.Items.ContainsKey(ClientTimingKey))
{
output.PreContent.AppendHtml(ClientTimingHelper.InitScript);
ViewContext.HttpContext.Items[ClientTimingKey] = true;
}
if (output.TagMode == TagMode.SelfClosing)
return;
output.PreContent.AppendHtml($"<script>mPt.start('{Name}')</script>");
output.PostContent.SetHtmlContent($"<script>mPt.end('{Name}')</script>");
}
}
}
|
mit
|
C#
|
b904ee70863a239ea735eb152a90ecd11d697342
|
add missing messages for test cases
|
NCTUGDC/HearthStone
|
HearthStone/HearthStone.Library.Test/CardManagerUnitTest.cs
|
HearthStone/HearthStone.Library.Test/CardManagerUnitTest.cs
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HearthStone.Library.Test
{
[TestClass]
public class CardManagerUnitTest
{
[TestMethod]
public void CardManagerInstanceTestMethod1()
{
CardManager instance = CardManager.Instance;
Assert.IsNotNull(instance, "CardManager.Instance should not be null");
}
[TestMethod]
public void CardsEnumerableTestMethod1()
{
IEnumerable<Card> cards = CardManager.Instance.Cards;
Assert.IsNotNull(cards, "CardManager.Instance.Cards should not be null");
}
[TestMethod]
public void CardsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Card card in CardManager.Instance.Cards)
{
Assert.IsNotNull(card, "Card object in CardManager.Instance.Cards should not be null");
Assert.IsFalse(IDs.Contains(card.CardID), "ID of Card objects in CardManager.Instance.Cards should not be the same");
IDs.Add(card.CardID);
}
}
[TestMethod]
public void EffectsEnumerableTestMethod1()
{
IEnumerable<Effect> effects = CardManager.Instance.Effects;
Assert.IsNotNull(effects, "CardManager.Instance.Effects should not be null");
}
[TestMethod]
public void EffectsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Effect effect in CardManager.Instance.Effects)
{
Assert.IsNotNull(effect, "Effect object in CardManager.Instance.Effects should not be null");
Assert.IsFalse(IDs.Contains(effect.EffectID), "ID of Effect objects in CardManager.Instance.Effects should not be the same");
IDs.Add(effect.EffectID);
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HearthStone.Library.Test
{
[TestClass]
public class CardManagerUnitTest
{
[TestMethod]
public void CardManagerInstanceTestMethod1()
{
CardManager instance = CardManager.Instance;
Assert.IsNotNull(instance);
}
[TestMethod]
public void CardsEnumerableTestMethod1()
{
IEnumerable<Card> cards = CardManager.Instance.Cards;
Assert.IsNotNull(cards);
}
[TestMethod]
public void CardsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Card card in CardManager.Instance.Cards)
{
Assert.IsNotNull(card);
Assert.IsFalse(IDs.Contains(card.CardID));
IDs.Add(card.CardID);
}
}
[TestMethod]
public void EffectsEnumerableTestMethod1()
{
IEnumerable<Effect> effects = CardManager.Instance.Effects;
Assert.IsNotNull(effects);
}
[TestMethod]
public void EffectsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Effect effect in CardManager.Instance.Effects)
{
Assert.IsNotNull(effect);
Assert.IsFalse(IDs.Contains(effect.EffectID));
IDs.Add(effect.EffectID);
}
}
}
}
|
apache-2.0
|
C#
|
f2e7c309c77f1d4bd09236ebf8681b864a3a1d99
|
add loadWhenActivated parameter.
|
zhongzf/Xamarin.Forms.Platform.Perspex
|
Xamarin.Forms.Platform.PerspexDesktop/DesktopApplication.cs
|
Xamarin.Forms.Platform.PerspexDesktop/DesktopApplication.cs
|
using Perspex;
using Perspex.Controls;
using Perspex.Diagnostics;
using Perspex.Markup.Xaml;
using Perspex.Themes.Default;
using System;
namespace Xamarin.Forms.Platform.PerspexDesktop
{
public class DesktopApplication : Perspex.Application
{
public DesktopApplication()
{
RegisterServices();
InitializeSubsystems((int)Environment.OSVersion.Platform);
InitializeComponent();
}
private void InitializeComponent()
{
var loader = new PerspexXamlLoader();
Styles.Add(new DefaultTheme());
var baseLight = (Perspex.Styling.IStyle)loader.Load(
new Uri("resm:Perspex.Themes.Default.Accents.BaseLight.xaml?assembly=Perspex.Themes.Default"));
Styles.Add(baseLight);
loader.Load(typeof(DesktopApplication), this);
}
public void LoadApplication(Type applicationType, bool debugMode = false, bool loadWhenActivated = false)
{
var window = new DesktopWindow();
if (loadWhenActivated)
{
window.Activated += (sender, e) =>
{
var application = (Xamarin.Forms.Application)Activator.CreateInstance(applicationType);
window.LoadApplication(application);
};
}
Forms.Init(window);
if(debugMode)
{
window.AttachDevTools();
}
if(!loadWhenActivated)
{
var application = (Xamarin.Forms.Application)Activator.CreateInstance(applicationType);
window.LoadApplication(application);
}
window.Show();
this.Run(window);
}
public static void Run(Type applicationType, bool debugMode = false, bool loadWhenActivated = false)
{
var application = new DesktopApplication();
application.LoadApplication(applicationType, debugMode, loadWhenActivated);
}
}
}
|
using Perspex;
using Perspex.Controls;
using Perspex.Diagnostics;
using Perspex.Markup.Xaml;
using Perspex.Themes.Default;
using System;
namespace Xamarin.Forms.Platform.PerspexDesktop
{
public class DesktopApplication : Perspex.Application
{
public DesktopApplication()
{
RegisterServices();
InitializeSubsystems((int)Environment.OSVersion.Platform);
InitializeComponent();
}
private void InitializeComponent()
{
var loader = new PerspexXamlLoader();
Styles.Add(new DefaultTheme());
var baseLight = (Perspex.Styling.IStyle)loader.Load(
new Uri("resm:Perspex.Themes.Default.Accents.BaseLight.xaml?assembly=Perspex.Themes.Default"));
Styles.Add(baseLight);
loader.Load(typeof(DesktopApplication), this);
}
public void LoadApplication(Type applicationType, bool debugMode = false)
{
var window = new DesktopWindow();
Forms.Init(window);
if(debugMode)
{
window.AttachDevTools();
}
var application = (Xamarin.Forms.Application)Activator.CreateInstance(applicationType);
window.LoadApplication(application);
window.Show();
this.Run(window);
}
public static void Run(Type applicationType, bool debugMode = false)
{
var application = new DesktopApplication();
application.LoadApplication(applicationType, debugMode);
}
}
}
|
mit
|
C#
|
805bbbf78d114d35ce825fbffa745c23878deebb
|
Bump version number
|
Killeroo/PowerPing,Killeroo/PowerPing
|
src/PowerPing/properties/AssemblyInfo.cs
|
src/PowerPing/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("PowerPing")]
[assembly: AssemblyDescription("Advanced ICMP Ping Utility")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Matthew Carney")]
[assembly: AssemblyProduct("PowerPing")]
[assembly: AssemblyCopyright("Copyright © Matthew Carney 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("4fa774f6-c5f6-4429-bf60-c3cfc61ec560")]
[assembly: AssemblyVersion("1.4.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("PowerPing")]
[assembly: AssemblyDescription("Advanced ICMP Ping Utility")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Matthew Carney")]
[assembly: AssemblyProduct("PowerPing")]
[assembly: AssemblyCopyright("Copyright © Matthew Carney 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("4fa774f6-c5f6-4429-bf60-c3cfc61ec560")]
[assembly: AssemblyVersion("1.3.1")]
|
mit
|
C#
|
8496907c2afd3a4977bb3640d8490547445b300e
|
Send the test output to the listener
|
mono/guiunit
|
src/framework/GuiUnit/XmlTestListener.cs
|
src/framework/GuiUnit/XmlTestListener.cs
|
using System;
using NUnit.Framework.Api;
using System.Xml.Linq;
using System.IO;
using System.Text;
namespace GuiUnit
{
public class XmlTestListener : ITestListener
{
StringBuilder output = new StringBuilder ();
TextWriter Writer {
get; set;
}
public XmlTestListener (TextWriter writer)
{
Writer = writer;
}
public void TestStarted (ITest test)
{
output.Clear ();
if (test.HasChildren)
Write (new XElement ("suite-started", new XAttribute ("name", test.FullName)));
else
Write (new XElement ("test-started", new XAttribute ("name", test.FullName)));
}
public void TestFinished (ITestResult result)
{
var element = new XElement (result.Test.HasChildren ? "suite-finished" : "test-finished",
new XAttribute ("name", result.Test.FullName),
new XAttribute ("result", ToXmlString (result.ResultState)),
new XAttribute ("passed", result.PassCount),
new XAttribute ("failures", result.FailCount),
new XAttribute ("ignored", result.SkipCount),
new XAttribute ("inconclusive", result.InconclusiveCount)
);
if (!string.IsNullOrEmpty (result.Message))
element.Add (new XAttribute ("message", result.Message));
if (!string.IsNullOrEmpty (result.StackTrace))
element.Add (new XAttribute ("stack-trace", result.StackTrace));
if (output.Length > 0)
element.Add (new XAttribute ("output", output.ToString ()));
Write (element);
}
public void TestOutput (TestOutput testOutput)
{
output.Append (testOutput);
}
object ToXmlString (ResultState resultState)
{
if (resultState == ResultState.Success)
return "Success";
else if (resultState == ResultState.Inconclusive)
return "Inconclusive";
else if (resultState == ResultState.Ignored)
return "Ignored";
else
return "Failure";
}
void Write (XElement element)
{
try {
Writer.WriteLine (element.ToString ());
} catch {
}
}
}
}
|
using System;
using NUnit.Framework.Api;
using System.Xml.Linq;
using System.IO;
namespace GuiUnit
{
public class XmlTestListener : ITestListener
{
TextWriter Writer {
get; set;
}
public XmlTestListener (TextWriter writer)
{
Writer = writer;
}
public void TestStarted (ITest test)
{
if (test.HasChildren)
Write (new XElement ("suite-started", new XAttribute ("name", test.FullName)));
else
Write (new XElement ("test-started", new XAttribute ("name", test.FullName)));
}
public void TestFinished (ITestResult result)
{
var element = new XElement (result.Test.HasChildren ? "suite-finished" : "test-finished",
new XAttribute ("name", result.Test.FullName),
new XAttribute ("result", ToXmlString (result.ResultState)),
new XAttribute ("passed", result.PassCount),
new XAttribute ("failures", result.FailCount),
new XAttribute ("ignored", result.SkipCount),
new XAttribute ("inconclusive", result.InconclusiveCount)
);
if (!string.IsNullOrEmpty (result.Message))
element.Add (new XAttribute ("message", result.Message));
if (!string.IsNullOrEmpty (result.StackTrace))
element.Add (new XAttribute ("stack-trace", result.StackTrace));
Write (element);
}
public void TestOutput (TestOutput testOutput)
{
// Ignore
}
object ToXmlString (ResultState resultState)
{
if (resultState == ResultState.Success)
return "Success";
else if (resultState == ResultState.Inconclusive)
return "Inconclusive";
else if (resultState == ResultState.Ignored)
return "Ignored";
else
return "Failure";
}
void Write (XElement element)
{
try {
Writer.WriteLine (element.ToString ());
} catch {
}
}
}
}
|
mit
|
C#
|
7bc7c3b4b30edced8c372a1702857e84fa88af0b
|
Fix warnings.
|
JohanLarsson/Gu.Roslyn.Asserts
|
Gu.Roslyn.Asserts.Tests/MetadataReferences/ReferenceAssemblyTests.cs
|
Gu.Roslyn.Asserts.Tests/MetadataReferences/ReferenceAssemblyTests.cs
|
namespace Gu.Roslyn.Asserts.Tests.MetadataReferences
{
using System;
using System.IO;
using Microsoft.CodeAnalysis;
using NUnit.Framework;
public static class ReferenceAssemblyTests
{
[TestCase(typeof(int))]
[TestCase(typeof(System.Diagnostics.Debug))]
public static void TryGetAssembly(Type type)
{
#if NETCOREAPP2_0
Assert.Inconclusive("Fix later.");
#endif
Assert.AreEqual(true, ReferenceAssembly.TryGet(type.Assembly, out var metadataReference));
StringAssert.Contains("Reference Assemblies", ((PortableExecutableReference)metadataReference).FilePath);
}
[TestCase(typeof(int))]
[TestCase(typeof(System.Diagnostics.Debug))]
public static void TryGetLocation(Type type)
{
#if NETCOREAPP2_0
Assert.Inconclusive("Fix later.");
#endif
Assert.AreEqual(true, ReferenceAssembly.TryGet(type.Assembly.Location, out var metadataReference));
StringAssert.Contains("Reference Assemblies", ((PortableExecutableReference)metadataReference).FilePath);
}
[TestCase(typeof(int))]
[TestCase(typeof(System.Diagnostics.Debug))]
public static void TryGetFileName(Type type)
{
#if NETCOREAPP2_0
Assert.Inconclusive("Fix later.");
#endif
Assert.AreEqual(true, ReferenceAssembly.TryGet(Path.GetFileNameWithoutExtension(type.Assembly.Location), out var metadataReference));
StringAssert.Contains("Reference Assemblies", ((PortableExecutableReference)metadataReference).FilePath);
}
}
}
|
namespace Gu.Roslyn.Asserts.Tests.MetadataReferences
{
using System;
using System.IO;
using Microsoft.CodeAnalysis;
using NUnit.Framework;
public class ReferenceAssemblyTests
{
[TestCase(typeof(int))]
[TestCase(typeof(System.Diagnostics.Debug))]
public void TryGetAssembly(Type type)
{
#if NETCOREAPP2_0
Assert.Inconclusive("Fix later.");
#endif
Assert.AreEqual(true, ReferenceAssembly.TryGet(type.Assembly, out var metadataReference));
StringAssert.Contains("Reference Assemblies", ((PortableExecutableReference)metadataReference).FilePath);
}
[TestCase(typeof(int))]
[TestCase(typeof(System.Diagnostics.Debug))]
public void TryGetLocation(Type type)
{
#if NETCOREAPP2_0
Assert.Inconclusive("Fix later.");
#endif
Assert.AreEqual(true, ReferenceAssembly.TryGet(type.Assembly.Location, out var metadataReference));
StringAssert.Contains("Reference Assemblies", ((PortableExecutableReference)metadataReference).FilePath);
}
[TestCase(typeof(int))]
[TestCase(typeof(System.Diagnostics.Debug))]
public void TryGetFileName(Type type)
{
#if NETCOREAPP2_0
Assert.Inconclusive("Fix later.");
#endif
Assert.AreEqual(true, ReferenceAssembly.TryGet(Path.GetFileNameWithoutExtension(type.Assembly.Location), out var metadataReference));
StringAssert.Contains("Reference Assemblies", ((PortableExecutableReference)metadataReference).FilePath);
}
}
}
|
mit
|
C#
|
0f9c3d7642d9c9b0df258e350971110baa715581
|
Add ranges preflop
|
DataBaseExam/TexasHold-em-AI
|
Source/TexasHoldem.AI.RaiseTwoSevenTestPlayer/RaiseTwoSevenPlayer.cs
|
Source/TexasHoldem.AI.RaiseTwoSevenTestPlayer/RaiseTwoSevenPlayer.cs
|
namespace TexasHoldem.AI.RaiseTwoSevenTestPlayer
{
using System;
using TexasHoldem.Logic.Players;
using TexasHoldem.Logic.Cards;
using Logic;
public class RaiseTwoSevenPlayer : BasePlayer
{
public override string Name { get; } = "RaiseTwoSeven";
public override PlayerAction GetTurn(GetTurnContext context)
{
//var playHand = HandStrengthValuation.PreFlop(this.FirstCard, this.SecondCard);
if (context.RoundType == GameRoundType.PreFlop)
{
//if (context.MoneyLeft / context.SmallBlind > 100)
//{
// if ()
// if (context.CanCheck)
// {
// return PlayerAction.Raise(context.SmallBlind * 3);
// }
//}
}
else if (context.RoundType == GameRoundType.Flop)
{
}
else if (context.RoundType == GameRoundType.Turn)
{
}
else
{
}
if (FirstCard.Type == CardType.Two && SecondCard.Type == CardType.Seven
|| SecondCard.Type == CardType.Two && FirstCard.Type == CardType.Seven)
{
return PlayerAction.Raise(context.MoneyLeft);
}
else
{
return PlayerAction.Fold();
}
}
}
}
|
namespace TexasHoldem.AI.RaiseTwoSevenTestPlayer
{
using System;
using TexasHoldem.Logic.Players;
using TexasHoldem.Logic.Cards;
using Logic;
public class RaiseTwoSevenPlayer : BasePlayer
{
public override string Name { get; } = "RaiseTwoSeven";
public override PlayerAction GetTurn(GetTurnContext context)
{
if (context.RoundType == GameRoundType.PreFlop)
{
if (context.MoneyLeft / context.SmallBlind > 100)
{
}
}
if (FirstCard.Type == CardType.Two && SecondCard.Type == CardType.Seven
|| SecondCard.Type == CardType.Two && FirstCard.Type == CardType.Seven)
{
return PlayerAction.Raise(context.MoneyLeft);
}
else
{
return PlayerAction.Fold();
}
}
}
}
|
mit
|
C#
|
712708432fd9b4cf7e52bf4241dd333e0241f239
|
use singleton completed task
|
shokanson/jottoweb,shokanson/jottoweb,shokanson/jottoweb,shokanson/jottoweb
|
jottoowin/Hokanson.JottoRepository/RepositoryBase.cs
|
jottoowin/Hokanson.JottoRepository/RepositoryBase.cs
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Hokanson.JottoRepository
{
public abstract class RepositoryBase<T> : IRepository<T>
{
protected static readonly ConcurrentDictionary<string, T> Objects = new ConcurrentDictionary<string, T>(); // Id -> object
// sub-classes should implement if they don't want callers to get the exception
public virtual Task<T> AddAsync(T obj) => throw new NotImplementedException();
public virtual Task<T> UpdateAsync(string id, T obj) => throw new NotImplementedException();
public virtual Task<IEnumerable<T>> GetAllAsync() => Task.FromResult<IEnumerable<T>>(Objects.Values);
public virtual Task<IEnumerable<T>> GetAllAsync(Func<T, bool> predicate) => Task.FromResult(Objects.Values.Where(predicate));
public virtual Task<T> GetAsync(Func<T, bool> predicate) => Task.FromResult(Objects.Values.FirstOrDefault(predicate));
public virtual Task SaveChangesAsync() => Task.CompletedTask; // essentially a no-op
public virtual Task<T> GetAsync(string id)
{
Objects.TryGetValue(id, out T obj);
return Task.FromResult(obj);
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Hokanson.JottoRepository
{
public abstract class RepositoryBase<T> : IRepository<T>
{
protected static readonly ConcurrentDictionary<string, T> Objects = new ConcurrentDictionary<string, T>(); // Id -> object
// sub-classes should implement if they don't want callers to get the exception
public virtual Task<T> AddAsync(T obj) => throw new NotImplementedException();
public virtual Task<T> UpdateAsync(string id, T obj) => throw new NotImplementedException();
public virtual Task<IEnumerable<T>> GetAllAsync() => Task.FromResult<IEnumerable<T>>(Objects.Values);
public virtual Task<IEnumerable<T>> GetAllAsync(Func<T, bool> predicate) => Task.FromResult(Objects.Values.Where(predicate));
public virtual Task<T> GetAsync(Func<T, bool> predicate) => Task.FromResult(Objects.Values.FirstOrDefault(predicate));
public virtual Task SaveChangesAsync() => Task.FromResult(0); // essentially a no-op
public virtual Task<T> GetAsync(string id)
{
Objects.TryGetValue(id, out T obj);
return Task.FromResult(obj);
}
}
}
|
mit
|
C#
|
fa589179eff862591a78f45fb766329d469e23e3
|
Fix so that the screen updates correctly
|
dipeshc/BTDeploy
|
src/MonoTorrent.Interface/src/MonoTorrent.Interface/Program.cs
|
src/MonoTorrent.Interface/src/MonoTorrent.Interface/Program.cs
|
/*
* $Id: Program.cs 880 2006-08-19 22:50:54Z piotr $
* Copyright (c) 2006 by Piotr Wolny <gildur@gmail.com>
*
* 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.IO;
using System;
using Mono.Unix;
using Gtk;
using MonoTorrent.Interface.Controller;
using MonoTorrent.Interface.View;
namespace MonoTorrent.Interface
{
public static class Program
{
public static int Main(string[] args)
{
Init();
Run();
return 0;
}
private static void Init()
{
string basedir = System.Reflection.Assembly.GetExecutingAssembly().Location;
basedir = basedir.Substring(0, basedir.Length - Path.GetFileName(basedir).Length);
basedir = Path.Combine(basedir, "locale");
Catalog.Init("monotorrent", basedir);
CreateDirs();
Application.Init();
GLib.Thread.Init();
}
private static void CreateDirs()
{
CreateDir(PathConstants.CONFIG_DIR);
CreateDir(PathConstants.TORRENTS_DIR);
CreateDir(PathConstants.DOWNLOAD_DIR);
}
private static void CreateDir(string path)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
private static void Run()
{
MainWindow window = new MainWindow();
window.ShowAll();
new WindowController(window);
Application.Run();
}
}
}
|
/*
* $Id: Program.cs 880 2006-08-19 22:50:54Z piotr $
* Copyright (c) 2006 by Piotr Wolny <gildur@gmail.com>
*
* 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.IO;
using System;
using Mono.Unix;
using Gtk;
using MonoTorrent.Interface.Controller;
using MonoTorrent.Interface.View;
namespace MonoTorrent.Interface
{
public static class Program
{
public static int Main(string[] args)
{
Init();
Run();
return 0;
}
private static void Init()
{
string basedir = System.Reflection.Assembly.GetExecutingAssembly().Location;
basedir = basedir.Substring(0, basedir.Length - Path.GetFileName(basedir).Length);
basedir = Path.Combine(basedir, "locale");
Catalog.Init("monotorrent", basedir);
CreateDirs();
Application.Init();
//GLib.Thread.Init();
}
private static void CreateDirs()
{
CreateDir(PathConstants.CONFIG_DIR);
CreateDir(PathConstants.TORRENTS_DIR);
CreateDir(PathConstants.DOWNLOAD_DIR);
}
private static void CreateDir(string path)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
private static void Run()
{
MainWindow window = new MainWindow();
window.ShowAll();
new WindowController(window);
Application.Run();
}
}
}
|
mit
|
C#
|
b0712491c8d89d8eb36f10ed2ef7dd82870a9e96
|
Update EthGetUncleByBlockHashAndIndex.cs
|
Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum
|
src/Nethereum.RPC/Eth/Uncles/EthGetUncleByBlockHashAndIndex.cs
|
src/Nethereum.RPC/Eth/Uncles/EthGetUncleByBlockHashAndIndex.cs
|
using System.Threading.Tasks;
using EdjCase.JsonRpc.Core;
using Nethereum.Hex.HexTypes;
using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth.DTOs;
namespace Nethereum.RPC.Eth.Uncles
{
/// <Summary>
/// eth_getUncleCountByBlockHash
/// Returns the number of uncles in a block from a block matching the given block hash.
/// Parameters
/// DATA, 32 Bytes - hash of a block
/// params: [
/// '0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238'
/// ]
/// Returns
/// QUANTITY - integer of the number of uncles in this block.
/// Example
/// Request
/// curl -X POST --data
/// '{"jsonrpc":"2.0","method":"eth_getUncleCountByBlockHash","params":["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],"id"Block:1}'
/// Result
/// {
/// "id":1,
/// "jsonrpc": "2.0",
/// "result": "0x1" // 1
/// }
/// </Summary>
public class EthGetUncleByBlockHashAndIndex : RpcRequestResponseHandler<BlockWithTransactionHashes>
{
public EthGetUncleByBlockHashAndIndex(IClient client)
: base(client, ApiMethods.eth_getUncleByBlockHashAndIndex.ToString())
{
}
public Task<BlockWithTransactionHashes> SendRequestAsync(string blockHash, HexBigInteger uncleIndex, object id = null)
{
return base.SendRequestAsync(id, blockHash, uncleIndex);
}
public RpcRequest BuildRequest(string blockHash, HexBigInteger uncleIndex, object id = null)
{
return base.BuildRequest(id, blockHash, uncleIndex);
}
}
}
|
using System.Threading.Tasks;
using EdjCase.JsonRpc.Core;
using Nethereum.Hex.HexTypes;
using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth.DTOs;
namespace Nethereum.RPC.Eth.Uncles
{
/// <Summary>
/// eth_getUncleCountByBlockHash
/// Returns the number of uncles in a block from a block matching the given block hash.
/// Parameters
/// DATA, 32 Bytes - hash of a block
/// params: [
/// '0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238'
/// ]
/// Returns
/// QUANTITY - integer of the number of uncles in this block.
/// Example
/// Request
/// curl -X POST --data
/// '{"jsonrpc":"2.0","method":"eth_getUncleCountByBlockHash","params":["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],"id"Block:1}'
/// Result
/// {
/// "id":1,
/// "jsonrpc": "2.0",
/// "result": "0x1" // 1
/// }
/// </Summary>
public class EthGetUncleByBlockHashAndIndex : RpcRequestResponseHandler<BlockWithTransactionHashes>
{
public EthGetUncleByBlockHashAndIndex(IClient client)
: base(client, ApiMethods.eth_getUncleByBlockHashAndIndex.ToString())
{
}
public Task<BlockWithTransactionHashes> SendRequestAsync(string BlockHash, HexBigInteger UncleIndex, object id = null)
{
return base.SendRequestAsync(id, BlockHash, UncleIndex);
}
public RpcRequest BuildRequest(string BlockHash, HexBigInteger UncleIndex, object id = null)
{
return base.BuildRequest(id, BlockHash, UncleIndex);
}
}
}
|
mit
|
C#
|
50d4cf49a74cb7c3a7a6408cb688f08282bca61b
|
Change the log level of JwtBearer (#33271)
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs
|
src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.Extensions.Logging
{
internal static class LoggingExtensions
{
private static Action<ILogger, Exception> _tokenValidationFailed;
private static Action<ILogger, Exception?> _tokenValidationSucceeded;
private static Action<ILogger, Exception> _errorProcessingMessage;
static LoggingExtensions()
{
_tokenValidationFailed = LoggerMessage.Define(
eventId: new EventId(1, "TokenValidationFailed"),
logLevel: LogLevel.Information,
formatString: "Failed to validate the token.");
_tokenValidationSucceeded = LoggerMessage.Define(
eventId: new EventId(2, "TokenValidationSucceeded"),
logLevel: LogLevel.Debug,
formatString: "Successfully validated the token.");
_errorProcessingMessage = LoggerMessage.Define(
eventId: new EventId(3, "ProcessingMessageFailed"),
logLevel: LogLevel.Error,
formatString: "Exception occurred while processing message.");
}
public static void TokenValidationFailed(this ILogger logger, Exception ex)
=> _tokenValidationFailed(logger, ex);
public static void TokenValidationSucceeded(this ILogger logger)
=> _tokenValidationSucceeded(logger, null);
public static void ErrorProcessingMessage(this ILogger logger, Exception ex)
=> _errorProcessingMessage(logger, ex);
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.Extensions.Logging
{
internal static class LoggingExtensions
{
private static Action<ILogger, Exception> _tokenValidationFailed;
private static Action<ILogger, Exception?> _tokenValidationSucceeded;
private static Action<ILogger, Exception> _errorProcessingMessage;
static LoggingExtensions()
{
_tokenValidationFailed = LoggerMessage.Define(
eventId: new EventId(1, "TokenValidationFailed"),
logLevel: LogLevel.Information,
formatString: "Failed to validate the token.");
_tokenValidationSucceeded = LoggerMessage.Define(
eventId: new EventId(2, "TokenValidationSucceeded"),
logLevel: LogLevel.Information,
formatString: "Successfully validated the token.");
_errorProcessingMessage = LoggerMessage.Define(
eventId: new EventId(3, "ProcessingMessageFailed"),
logLevel: LogLevel.Error,
formatString: "Exception occurred while processing message.");
}
public static void TokenValidationFailed(this ILogger logger, Exception ex)
=> _tokenValidationFailed(logger, ex);
public static void TokenValidationSucceeded(this ILogger logger)
=> _tokenValidationSucceeded(logger, null);
public static void ErrorProcessingMessage(this ILogger logger, Exception ex)
=> _errorProcessingMessage(logger, ex);
}
}
|
apache-2.0
|
C#
|
f2ba87a1d2a2f66fa423a682a0eb2ef0f7edef9c
|
Fix placement blueprint test scenes not working
|
NeoAdonis/osu,peppy/osu-new,ppy/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,ppy/osu,EVAST9919/osu,ZLima12/osu,ZLima12/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,peppy/osu,2yangk23/osu,ppy/osu,johnneijzen/osu,EVAST9919/osu,UselessToucan/osu,johnneijzen/osu,smoogipoo/osu
|
osu.Game/Tests/Visual/PlacementBlueprintTestScene.cs
|
osu.Game/Tests/Visual/PlacementBlueprintTestScene.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Events;
using osu.Framework.Timing;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Screens.Edit.Compose;
namespace osu.Game.Tests.Visual
{
[Cached(Type = typeof(IPlacementHandler))]
public abstract class PlacementBlueprintTestScene : OsuTestScene, IPlacementHandler
{
protected Container HitObjectContainer;
private PlacementBlueprint currentBlueprint;
private InputManager inputManager;
protected PlacementBlueprintTestScene()
{
Add(HitObjectContainer = CreateHitObjectContainer().With(c => c.Clock = new FramedClock(new StopwatchClock())));
}
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value.BeatmapInfo.BaseDifficulty.CircleSize = 2;
}
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
var dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
dependencies.CacheAs<IAdjustableClock>(new StopwatchClock());
return dependencies;
}
protected override void LoadComplete()
{
base.LoadComplete();
inputManager = GetContainingInputManager();
Add(currentBlueprint = CreateBlueprint());
}
public void BeginPlacement(HitObject hitObject)
{
}
public void EndPlacement(HitObject hitObject)
{
AddHitObject(CreateHitObject(hitObject));
Remove(currentBlueprint);
Add(currentBlueprint = CreateBlueprint());
}
public void Delete(HitObject hitObject)
{
}
protected override bool OnMouseMove(MouseMoveEvent e)
{
currentBlueprint.UpdatePosition(e.ScreenSpaceMousePosition);
return true;
}
public override void Add(Drawable drawable)
{
base.Add(drawable);
if (drawable is PlacementBlueprint blueprint)
{
blueprint.Show();
blueprint.UpdatePosition(inputManager.CurrentState.Mouse.Position);
}
}
protected virtual void AddHitObject(DrawableHitObject hitObject) => HitObjectContainer.Add(hitObject);
protected virtual Container CreateHitObjectContainer() => new Container { RelativeSizeAxes = Axes.Both };
protected abstract DrawableHitObject CreateHitObject(HitObject hitObject);
protected abstract PlacementBlueprint CreateBlueprint();
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Timing;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Screens.Edit.Compose;
namespace osu.Game.Tests.Visual
{
[Cached(Type = typeof(IPlacementHandler))]
public abstract class PlacementBlueprintTestScene : OsuTestScene, IPlacementHandler
{
protected Container HitObjectContainer;
private PlacementBlueprint currentBlueprint;
protected PlacementBlueprintTestScene()
{
Add(HitObjectContainer = CreateHitObjectContainer());
}
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value.BeatmapInfo.BaseDifficulty.CircleSize = 2;
Add(currentBlueprint = CreateBlueprint());
}
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
var dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
dependencies.CacheAs<IAdjustableClock>(new StopwatchClock());
return dependencies;
}
public void BeginPlacement(HitObject hitObject)
{
}
public void EndPlacement(HitObject hitObject)
{
AddHitObject(CreateHitObject(hitObject));
Remove(currentBlueprint);
Add(currentBlueprint = CreateBlueprint());
}
public void Delete(HitObject hitObject)
{
}
protected virtual Container CreateHitObjectContainer() => new Container { RelativeSizeAxes = Axes.Both };
protected virtual void AddHitObject(DrawableHitObject hitObject) => HitObjectContainer.Add(hitObject);
protected abstract DrawableHitObject CreateHitObject(HitObject hitObject);
protected abstract PlacementBlueprint CreateBlueprint();
}
}
|
mit
|
C#
|
7d56ce63d38433541f12932b2b015d9f6f059615
|
Fix test case failures
|
smoogipoo/osu,EVAST9919/osu,DrabWeb/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu-new,EVAST9919/osu,ZLima12/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,DrabWeb/osu,peppy/osu,peppy/osu,UselessToucan/osu,2yangk23/osu,UselessToucan/osu,smoogipooo/osu,DrabWeb/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,ZLima12/osu,smoogipoo/osu,2yangk23/osu
|
osu.Game/Tests/Visual/RateAdjustedBeatmapTestCase.cs
|
osu.Game/Tests/Visual/RateAdjustedBeatmapTestCase.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Tests.Visual
{
/// <summary>
/// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests.
/// </summary>
public abstract class RateAdjustedBeatmapTestCase : ScreenTestCase
{
protected override void Update()
{
base.Update();
// note that this will override any mod rate application
Beatmap.Value.Track.TempoAdjust = Clock.Rate;
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Tests.Visual
{
/// <summary>
/// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests.
/// </summary>
public abstract class RateAdjustedBeatmapTestCase : ScreenTestCase
{
protected override void Update()
{
base.Update();
// note that this will override any mod rate application
Beatmap.Value.Track.Rate = Clock.Rate;
}
}
}
|
mit
|
C#
|
3daee8df54d9b51438463733eabbfcf229ee7ab6
|
Bump version to 0.15.3
|
quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot
|
plugin/CactbotEventSource/Properties/AssemblyInfo.cs
|
plugin/CactbotEventSource/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotEventSource")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotEventSource")]
[assembly: AssemblyCopyright("Copyright 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("9eb3ba4d-b285-4445-b88b-2fb59b8bb321")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
// CactbotOverlay and CactbotEventSource version should match.
[assembly: AssemblyVersion("0.15.3.0")]
[assembly: AssemblyFileVersion("0.15.3.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotEventSource")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotEventSource")]
[assembly: AssemblyCopyright("Copyright 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("9eb3ba4d-b285-4445-b88b-2fb59b8bb321")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
// CactbotOverlay and CactbotEventSource version should match.
[assembly: AssemblyVersion("0.15.2.0")]
[assembly: AssemblyFileVersion("0.15.2.0")]
|
apache-2.0
|
C#
|
ca0bea753439ce81ddb5eb86ef32fb6cc369c110
|
Rename MaximumCombo to HighestCombo.
|
peppy/osu-new,EVAST9919/osu,UselessToucan/osu,naoey/osu,NotKyon/lolisu,DrabWeb/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,DrabWeb/osu,johnneijzen/osu,johnneijzen/osu,Drezi126/osu,ppy/osu,peppy/osu,ppy/osu,Frontear/osuKyzer,UselessToucan/osu,nyaamara/osu,RedNesto/osu,tacchinotacchi/osu,naoey/osu,NeoAdonis/osu,osu-RP/osu-RP,DrabWeb/osu,default0/osu,ZLima12/osu,naoey/osu,smoogipoo/osu,2yangk23/osu,Damnae/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,theguii/osu,ppy/osu,Nabile-Rahmani/osu,peppy/osu,smoogipoo/osu,ZLima12/osu
|
osu.Game/Modes/ScoreProcesssor.cs
|
osu.Game/Modes/ScoreProcesssor.cs
|
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using osu.Framework.Configuration;
using osu.Game.Modes.Objects.Drawables;
namespace osu.Game.Modes
{
public abstract class ScoreProcessor
{
public virtual Score GetScore() => new Score();
public readonly BindableDouble TotalScore = new BindableDouble { MinValue = 0 };
public readonly BindableDouble Accuracy = new BindableDouble { MinValue = 0, MaxValue = 1 };
public readonly BindableInt Combo = new BindableInt();
public readonly BindableInt HighestCombo = new BindableInt();
public readonly List<JudgementInfo> Judgements = new List<JudgementInfo>();
public ScoreProcessor()
{
Combo.ValueChanged += delegate { HighestCombo.Value = Math.Max(HighestCombo.Value, Combo.Value); };
}
public void AddJudgement(JudgementInfo judgement)
{
Judgements.Add(judgement);
UpdateCalculations(judgement);
judgement.ComboAtHit = (ulong)Combo.Value;
}
/// <summary>
/// Update any values that potentially need post-processing on a judgement change.
/// </summary>
/// <param name="newJudgement">A new JudgementInfo that triggered this calculation. May be null.</param>
protected abstract void UpdateCalculations(JudgementInfo newJudgement);
}
}
|
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using osu.Framework.Configuration;
using osu.Game.Modes.Objects.Drawables;
namespace osu.Game.Modes
{
public abstract class ScoreProcessor
{
public virtual Score GetScore() => new Score();
public readonly BindableDouble TotalScore = new BindableDouble { MinValue = 0 };
public readonly BindableDouble Accuracy = new BindableDouble { MinValue = 0, MaxValue = 1 };
public readonly BindableInt Combo = new BindableInt();
public readonly BindableInt MaximumCombo = new BindableInt();
public readonly List<JudgementInfo> Judgements = new List<JudgementInfo>();
public ScoreProcessor()
{
Combo.ValueChanged += delegate { MaximumCombo.Value = Math.Max(MaximumCombo.Value, Combo.Value); };
}
public void AddJudgement(JudgementInfo judgement)
{
Judgements.Add(judgement);
UpdateCalculations(judgement);
judgement.ComboAtHit = (ulong)Combo.Value;
}
/// <summary>
/// Update any values that potentially need post-processing on a judgement change.
/// </summary>
/// <param name="newJudgement">A new JudgementInfo that triggered this calculation. May be null.</param>
protected abstract void UpdateCalculations(JudgementInfo newJudgement);
}
}
|
mit
|
C#
|
f1d394ace3de1971f769dd9f4b654a7b8920256a
|
change CanInherited rule
|
AspectCore/Abstractions,AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Lite
|
src/AspectCore.Lite.Abstractions.Resolution/TypeInfoExtensions.cs
|
src/AspectCore.Lite.Abstractions.Resolution/TypeInfoExtensions.cs
|
using AspectCore.Lite.Abstractions.Resolution.Generators;
using System;
using System.Linq;
using System.Reflection;
namespace AspectCore.Lite.Abstractions.Resolution
{
public static class TypeInfoExtensions
{
public static bool ValidateAspect(this TypeInfo typeInfo, IAspectValidator aspectValidator)
{
if (typeInfo == null)
{
throw new ArgumentNullException(nameof(typeInfo));
}
if (typeInfo.IsValueType)
{
return false;
}
return typeInfo.DeclaredMethods.Any(method => aspectValidator.Validate(method));
}
public static bool CanInherited(this TypeInfo typeInfo)
{
if (typeInfo == null)
{
throw new ArgumentNullException(nameof(typeInfo));
}
if (!typeInfo.IsClass || typeInfo.IsSealed || typeInfo.IsGenericTypeDefinition)
{
return false;
}
if (typeInfo.IsDefined(typeof(NonAspectAttribute)))
{
return false;
}
if (typeInfo.IsNested)
{
return typeInfo.IsNestedPublic && typeInfo.DeclaringType.GetTypeInfo().IsPublic;
}
else
{
return typeInfo.IsPublic;
}
}
public static TypeInfo CreateProxyTypeInfo(this Type serviceType, Type implementationType, IAspectValidator aspectValidator)
{
var typeGenerator = new AspectTypeGenerator(serviceType, implementationType, aspectValidator);
return typeGenerator.CreateTypeInfo();
}
public static Type CreateProxyType(this Type serviceType, Type implementationType, IAspectValidator aspectValidator)
{
var typeGenerator = new AspectTypeGenerator(serviceType, implementationType, aspectValidator);
return typeGenerator.CreateType();
}
}
}
|
using AspectCore.Lite.Abstractions.Resolution.Generators;
using System;
using System.Linq;
using System.Reflection;
namespace AspectCore.Lite.Abstractions.Resolution
{
public static class TypeInfoExtensions
{
public static bool ValidateAspect(this TypeInfo typeInfo, IAspectValidator aspectValidator)
{
if (typeInfo == null)
{
throw new ArgumentNullException(nameof(typeInfo));
}
if (typeInfo.IsValueType)
{
return false;
}
return typeInfo.DeclaredMethods.Any(method => aspectValidator.Validate(method));
}
public static bool CanInherited(this TypeInfo typeInfo)
{
return typeInfo.IsClass && (typeInfo.IsPublic || (typeInfo.IsNested && typeInfo.IsNestedPublic)) &&
!typeInfo.IsSealed && !typeInfo.IsGenericTypeDefinition;
}
public static TypeInfo CreateProxyTypeInfo(this Type serviceType, Type implementationType, IAspectValidator aspectValidator)
{
var typeGenerator = new AspectTypeGenerator(serviceType, implementationType, aspectValidator);
return typeGenerator.CreateTypeInfo();
}
public static Type CreateProxyType(this Type serviceType, Type implementationType, IAspectValidator aspectValidator)
{
var typeGenerator = new AspectTypeGenerator(serviceType, implementationType, aspectValidator);
return typeGenerator.CreateType();
}
}
}
|
mit
|
C#
|
e397ab9a9b6dd73a7c242518a92e86a65e208cf3
|
fix xref map sorted comparer. (#2191)
|
pascalberger/docfx,dotnet/docfx,dotnet/docfx,superyyrrzz/docfx,pascalberger/docfx,superyyrrzz/docfx,pascalberger/docfx,superyyrrzz/docfx,dotnet/docfx
|
src/Microsoft.DocAsCode.Build.Engine/XRefMaps/XRefSpecUidComparer.cs
|
src/Microsoft.DocAsCode.Build.Engine/XRefMaps/XRefSpecUidComparer.cs
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.Engine
{
using System;
using System.Collections.Generic;
using Microsoft.DocAsCode.Plugins;
public sealed class XRefSpecUidComparer : Comparer<XRefSpec>
{
public static readonly XRefSpecUidComparer Instance = new XRefSpecUidComparer();
public override int Compare(XRefSpec x, XRefSpec y)
{
return StringComparer.InvariantCulture.Compare(x.Uid, y.Uid);
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.Engine
{
using System.Collections.Generic;
using Microsoft.DocAsCode.Plugins;
public sealed class XRefSpecUidComparer : Comparer<XRefSpec>
{
public static readonly XRefSpecUidComparer Instance = new XRefSpecUidComparer();
public override int Compare(XRefSpec x, XRefSpec y)
{
return string.Compare(x.Uid, y.Uid);
}
}
}
|
mit
|
C#
|
5f1abf80a15277af23db9045558e6a66a265fb49
|
Allow Device.SetCooperativeLevel to be called
|
alesliehughes/monoDX,alesliehughes/monoDX
|
Microsoft.DirectX.DirectSound/Microsoft.DirectX.DirectSound/Device.cs
|
Microsoft.DirectX.DirectSound/Microsoft.DirectX.DirectSound/Device.cs
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* 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.ComponentModel;
using System.Windows.Forms;
namespace Microsoft.DirectX.DirectSound
{
public class Device : MarshalByRefObject, IDisposable
{
public event EventHandler Disposing {
add {
throw new NotImplementedException ();
}
remove {
throw new NotImplementedException ();
}
}
public bool Disposed {
get {
throw new NotImplementedException ();
}
}
public Speakers SpeakerConfig {
get {
throw new NotImplementedException ();
}
set {
throw new NotImplementedException ();
}
}
public bool Certified {
get {
throw new NotImplementedException ();
}
}
public Caps Caps {
get {
throw new NotImplementedException ();
}
}
public override bool Equals (object compare)
{
throw new NotImplementedException ();
}
public static bool operator == (Device left, Device right)
{
throw new NotImplementedException ();
}
public static bool operator != (Device left, Device right)
{
throw new NotImplementedException ();
}
public override int GetHashCode ()
{
throw new NotImplementedException ();
}
public Device (IntPtr lp)
{
throw new NotImplementedException ();
}
public Device (Guid guidDev)
{
throw new NotImplementedException ();
}
public Device ()
{
}
public void Dispose ()
{
throw new NotImplementedException ();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public IntPtr GetObjectByValue (int objId)
{
throw new NotImplementedException ();
}
public void SetCooperativeLevel (IntPtr owner, CooperativeLevel level)
{
throw new NotImplementedException ();
}
public void SetCooperativeLevel (Control owner, CooperativeLevel level)
{
}
public void Compact ()
{
throw new NotImplementedException ();
}
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* 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.ComponentModel;
using System.Windows.Forms;
namespace Microsoft.DirectX.DirectSound
{
public class Device : MarshalByRefObject, IDisposable
{
public event EventHandler Disposing {
add {
throw new NotImplementedException ();
}
remove {
throw new NotImplementedException ();
}
}
public bool Disposed {
get {
throw new NotImplementedException ();
}
}
public Speakers SpeakerConfig {
get {
throw new NotImplementedException ();
}
set {
throw new NotImplementedException ();
}
}
public bool Certified {
get {
throw new NotImplementedException ();
}
}
public Caps Caps {
get {
throw new NotImplementedException ();
}
}
public override bool Equals (object compare)
{
throw new NotImplementedException ();
}
public static bool operator == (Device left, Device right)
{
throw new NotImplementedException ();
}
public static bool operator != (Device left, Device right)
{
throw new NotImplementedException ();
}
public override int GetHashCode ()
{
throw new NotImplementedException ();
}
public Device (IntPtr lp)
{
throw new NotImplementedException ();
}
public Device (Guid guidDev)
{
throw new NotImplementedException ();
}
public Device ()
{
}
public void Dispose ()
{
throw new NotImplementedException ();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public IntPtr GetObjectByValue (int objId)
{
throw new NotImplementedException ();
}
public void SetCooperativeLevel (IntPtr owner, CooperativeLevel level)
{
throw new NotImplementedException ();
}
public void SetCooperativeLevel (Control owner, CooperativeLevel level)
{
throw new NotImplementedException ();
}
public void Compact ()
{
throw new NotImplementedException ();
}
}
}
|
mit
|
C#
|
756c99f59d805485cf03654640750dd5d381864d
|
refactor ReservateTheDate()
|
Borayvor/ReservationSystem,Borayvor/ReservationSystem,Borayvor/ReservationSystem
|
ReservationSystem/ReservationSystem/Controllers/CalendarController.cs
|
ReservationSystem/ReservationSystem/Controllers/CalendarController.cs
|
using System;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ReservationSystem.Common;
using ReservationSystem.Extensions;
using ReservationSystem.Services.Data.Contracts;
using ReservationSystem.ViewComponents;
using ReservationSystem.ViewModels.CalendarViewModels;
namespace ReservationSystem.Controllers
{
public class CalendarController : Controller
{
private readonly IMapper mapper;
private readonly IUnitOfWork unitOfWork;
private readonly IReservationService reservationService;
public CalendarController(IMapper mapper, IUnitOfWork unitOfWork, IReservationService reservationService)
{
this.mapper = mapper;
this.unitOfWork = unitOfWork;
this.reservationService = reservationService;
}
[HttpGet]
public IActionResult Index()
{
var currentDate = DateTime.UtcNow.Date;
return this.View(currentDate);
}
[HttpPost]
public IActionResult GetPreviousMonth(long selectedYearMonth)
{
var newSelectedYearMonth = new DateTime(selectedYearMonth).ToUniversalTime().Date;
var selectedYearMonthPrevious = newSelectedYearMonth.Date.AddMonths(-1);
return this.ViewComponent(typeof(CalendarViewComponent), new { selectedYearMonth = selectedYearMonthPrevious });
}
[HttpPost]
public IActionResult GetNextMonth(long selectedYearMonth)
{
var newSelectedYearMonth = new DateTime(selectedYearMonth).ToUniversalTime().Date;
var selectedYearMonthNext = newSelectedYearMonth.Date.AddMonths(1);
return this.ViewComponent(typeof(CalendarViewComponent), new { selectedYearMonth = selectedYearMonthNext });
}
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public IActionResult ReservateTheDate(DateTime date)
{
if (!this.User.Identity.IsAuthenticated || this.User.IsInRole(GlobalConstants.AdministratorRoleName))
{
return this.View("Index", date);
}
if (date.ToUniversalTime().Date < DateTime.UtcNow.Date)
{
return this.View("Index", date);
}
var reservation = this.reservationService.GetByDate(date);
if (!string.IsNullOrWhiteSpace(reservation.OwnerId))
{
return this.View("Index", date);
}
var userId = this.User.GetUserId();
reservation.OwnerId = userId;
this.reservationService.Update(reservation);
this.unitOfWork.SaveChanges();
return this.View("Index", date);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult GetSelectedDateData(DateTime date)
{
var reservation = this.reservationService.GetByDate(date);
var newModel = this.mapper.Map<SelectedDateDataViewModel>(reservation);
return this.ViewComponent(typeof(SelectedDateDataViewComponent), new { viewModel = newModel });
}
}
}
|
using System;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ReservationSystem.Common;
using ReservationSystem.Extensions;
using ReservationSystem.Services.Data.Contracts;
using ReservationSystem.ViewComponents;
using ReservationSystem.ViewModels.CalendarViewModels;
namespace ReservationSystem.Controllers
{
public class CalendarController : Controller
{
private readonly IMapper mapper;
private readonly IUnitOfWork unitOfWork;
private readonly IReservationService reservationService;
public CalendarController(IMapper mapper, IUnitOfWork unitOfWork, IReservationService reservationService)
{
this.mapper = mapper;
this.unitOfWork = unitOfWork;
this.reservationService = reservationService;
}
[HttpGet]
public IActionResult Index()
{
var currentDate = DateTime.UtcNow.Date;
return this.View(currentDate);
}
[HttpPost]
public IActionResult GetPreviousMonth(long selectedYearMonth)
{
var newSelectedYearMonth = new DateTime(selectedYearMonth).ToUniversalTime().Date;
var selectedYearMonthPrevious = newSelectedYearMonth.Date.AddMonths(-1);
return this.ViewComponent(typeof(CalendarViewComponent), new { selectedYearMonth = selectedYearMonthPrevious });
}
[HttpPost]
public IActionResult GetNextMonth(long selectedYearMonth)
{
var newSelectedYearMonth = new DateTime(selectedYearMonth).ToUniversalTime().Date;
var selectedYearMonthNext = newSelectedYearMonth.Date.AddMonths(1);
return this.ViewComponent(typeof(CalendarViewComponent), new { selectedYearMonth = selectedYearMonthNext });
}
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public IActionResult ReservateTheDate(DateTime date)
{
if (!this.User.Identity.IsAuthenticated || this.User.IsInRole(GlobalConstants.AdministratorRoleName))
{
return this.View("Index", date);
}
if (date.Date < DateTime.UtcNow.Date)
{
return this.View("Index", date);
}
var reservation = this.reservationService.GetByDate(date);
if (!string.IsNullOrWhiteSpace(reservation.OwnerId))
{
return this.View("Index", date);
}
var userId = this.User.GetUserId();
reservation.OwnerId = userId;
this.reservationService.Update(reservation);
this.unitOfWork.SaveChanges();
return this.View("Index", date);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult GetSelectedDateData(DateTime date)
{
var reservation = this.reservationService.GetByDate(date);
var newModel = this.mapper.Map<SelectedDateDataViewModel>(reservation);
return this.ViewComponent(typeof(SelectedDateDataViewComponent), new { viewModel = newModel });
}
}
}
|
mit
|
C#
|
132026ea57985119b5d89b4a1bafc0ecb04ac99b
|
bump version to 1.6
|
Sevitec/oneoffixx-connectclient
|
Windows/src/OneOffixx.ConnectClient.WinApp/Properties/AssemblyInfo.cs
|
Windows/src/OneOffixx.ConnectClient.WinApp/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OneOffixx Connect Client")]
[assembly: AssemblyDescription("Test Client for OneOffixx Connect")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sevitec Informatik AG")]
[assembly: AssemblyProduct("OneOffixx.ConnectClient.WinApp")]
[assembly: AssemblyCopyright("Copyright © Sevitec Informatik AG 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.6.0.0")]
[assembly: AssemblyFileVersion("1.6.0.0")]
|
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OneOffixx.ConnectClient.WinApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OneOffixx.ConnectClient.WinApp")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.5.7.0")]
[assembly: AssemblyFileVersion("1.5.7.0")]
|
mit
|
C#
|
8b43b028b2d91bfac0f1b399cb9025aa6de21fa3
|
Add AssemblyLoader class
|
xirqlz/blueprint41
|
Blueprint41.Modeller.Schemas/DatastoreModelComparer.cs
|
Blueprint41.Modeller.Schemas/DatastoreModelComparer.cs
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Blueprint41.Modeller.Schemas
{
public abstract class DatastoreModelComparer
{
public static DatastoreModelComparer Instance { get { return instance.Value; } }
private static Lazy<DatastoreModelComparer> instance = new Lazy<DatastoreModelComparer>(delegate ()
{
string dll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Blueprint41.Modeller.Compare.dll");
if (!File.Exists(dll))
return null;
Type type = AssemblyLoader.GetType(dll, "DatastoreModelComparerImpl");
return (DatastoreModelComparer)Activator.CreateInstance(type);
}, true);
public abstract void GenerateUpgradeScript(modeller model, string storagePath);
}
public static class AssemblyLoader
{
public static Assembly Load(string assemblyFile)
{
byte[] assemblyBytes = File.ReadAllBytes(assemblyFile);
return Assembly.Load(assemblyBytes);
}
public static Type GetType(string assemblyFile, string typeName)
{
Assembly assembly = Load(assemblyFile);
return assembly.GetTypes().First(x => x.Name == typeName);
}
public static Assembly Load(string assemblyFile, string pdbFile)
{
byte[] assemblyBytes = File.ReadAllBytes(assemblyFile);
byte[] pdbBytes = File.ReadAllBytes(pdbFile);
return Assembly.Load(assemblyBytes, pdbBytes);
}
public static Type GetType(string assemblyFile, string pdbFile, string typeName)
{
Assembly assembly = Load(assemblyFile, pdbFile);
return assembly.GetTypes().First(x => x.Name == typeName);
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Blueprint41.Modeller.Schemas
{
public abstract class DatastoreModelComparer
{
public static DatastoreModelComparer Instance { get { return instance.Value; } }
private static Lazy<DatastoreModelComparer> instance = new Lazy<DatastoreModelComparer>(delegate ()
{
string dll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Blueprint41.Modeller.Compare.dll");
if (!File.Exists(dll))
return null;
byte[] assembly = File.ReadAllBytes(dll);
Assembly asm = Assembly.Load(assembly);
Type type = asm.GetTypes().First(x => x.Name == "DatastoreModelComparerImpl");
return (DatastoreModelComparer)Activator.CreateInstance(type);
}, true);
public abstract void GenerateUpgradeScript(modeller model, string storagePath);
}
}
|
mit
|
C#
|
ffecfdc70baa26d625a7b6ce78f0e0433d863792
|
Add ActionsMenu zone to Widget.SummaryAdmin (#6907)
|
petedavis/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2
|
src/OrchardCore.Modules/OrchardCore.Widgets/Views/Widget.SummaryAdmin.cshtml
|
src/OrchardCore.Modules/OrchardCore.Widgets/Views/Widget.SummaryAdmin.cshtml
|
@using OrchardCore.ContentManagement
@{
ContentItem contentItem = Model.ContentItem;
}
<div class="row">
<div class="col-xl-6 col-sm-12 title">
<div class="custom-control custom-checkbox float-left">
<input type="checkbox" class="custom-control-input" value="@contentItem.Id" name="itemIds" id="itemIds-@contentItem.Id">
<label class="custom-control-label" for="itemIds-@contentItem.Id"></label>
</div>
<a admin-for="@contentItem" asp-route-returnUrl="@FullRequestPath" /> - <small class="text-muted">@T["Widget"]</small>
@if (Model.Tags != null)
{
@await DisplayAsync(Model.Tags)
}
@if (Model.Header != null)
{
<div class="header">@await DisplayAsync(Model.Header)</div>
}
@if (Model.Meta != null)
{
<div class="metadata">@await DisplayAsync(Model.Meta)</div>
}
</div>
@if (Model.Actions != null)
{
<div class="col-xl-6 col-sm-12 related">
<div class="float-right">
@await DisplayAsync(Model.Actions)
@if (Model.ActionsMenu != null)
{
<div class="btn-group">
<button type="button" class="btn btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
@T["Actions"]
</button>
<div class="dropdown-menu dropdown-menu-right">
@await DisplayAsync(Model.ActionsMenu)
</div>
</div>
}
</div>
</div>
}
</div>
@if (Model.Content != null)
{
<div class="primary">@await DisplayAsync(Model.Content)</div>
}
|
@using OrchardCore.ContentManagement
@{
ContentItem contentItem = Model.ContentItem;
}
<div class="row">
<div class="col-xl-6 col-sm-12 title">
<div class="custom-control custom-checkbox float-left">
<input type="checkbox" class="custom-control-input" value="@contentItem.Id" name="itemIds" id="itemIds-@contentItem.Id">
<label class="custom-control-label" for="itemIds-@contentItem.Id"></label>
</div>
<a admin-for="@contentItem" asp-route-returnUrl="@FullRequestPath" /> - <small class="text-muted">@T["Widget"]</small>
@if (Model.Tags != null)
{
@await DisplayAsync(Model.Tags)
}
@if (Model.Header != null)
{
<div class="header">@await DisplayAsync(Model.Header)</div>
}
@if (Model.Meta != null)
{
<div class="metadata">@await DisplayAsync(Model.Meta)</div>
}
</div>
@if (Model.Actions != null)
{
<div class="col-xl-6 col-sm-12 related">
<div class="float-right">
@await DisplayAsync(Model.Actions)
</div>
</div>
}
</div>
@if (Model.Content != null)
{
<div class="primary">@await DisplayAsync(Model.Content)</div>
}
|
bsd-3-clause
|
C#
|
4db1ad01ee32a4985bcf172923e2b352f72ce5a6
|
Update IndexModule.cs
|
LeedsSharp/AppVeyorDemo
|
src/AppVeyorDemo/AppVeyorDemo/Modules/IndexModule.cs
|
src/AppVeyorDemo/AppVeyorDemo/Modules/IndexModule.cs
|
namespace AppVeyorDemo.Modules
{
using System.Configuration;
using AppVeyorDemo.Models;
using Nancy;
public class IndexModule : NancyModule
{
public IndexModule()
{
Get["/"] = parameters =>
{
var model = new IndexViewModel
{
HelloName = "AppVeyor",
ServerName = ConfigurationManager.AppSettings["Server_Name"]
};
return View["index", model];
};
}
}
}
|
namespace AppVeyorDemo.Modules
{
using System.Configuration;
using AppVeyorDemo.Models;
using Nancy;
public class IndexModule : NancyModule
{
public IndexModule()
{
Get["/"] = parameters =>
{
var model = new IndexViewModel
{
HelloName = "Leeds#",
ServerName = ConfigurationManager.AppSettings["Server_Name"]
};
return View["index", model];
};
}
}
}
|
apache-2.0
|
C#
|
892d514664eb38274d48f5639ed8864ef0355a62
|
Remove unnecessary Pack directive to fix build break
|
wtgodbe/corefx,ericstj/corefx,ptoonen/corefx,mmitche/corefx,wtgodbe/corefx,mmitche/corefx,mmitche/corefx,shimingsg/corefx,shimingsg/corefx,BrennanConroy/corefx,ericstj/corefx,ptoonen/corefx,wtgodbe/corefx,mmitche/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,mmitche/corefx,ViktorHofer/corefx,wtgodbe/corefx,shimingsg/corefx,ericstj/corefx,wtgodbe/corefx,ericstj/corefx,ptoonen/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ViktorHofer/corefx,mmitche/corefx,ptoonen/corefx,ptoonen/corefx,shimingsg/corefx,BrennanConroy/corefx,BrennanConroy/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ptoonen/corefx,mmitche/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,ericstj/corefx,ViktorHofer/corefx,shimingsg/corefx,ptoonen/corefx
|
src/Common/src/CoreLib/System/Number.NumberBuffer.cs
|
src/Common/src/CoreLib/System/Number.NumberBuffer.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.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System
{
internal static partial class Number
{
// We need 1 additional byte, per length, for the terminating null
private const int DecimalNumberBufferLength = 50 + 1;
private const int DoubleNumberBufferLength = 768 + 1; // 767 for the longest input + 1 for rounding: 4.9406564584124654E-324
private const int Int32NumberBufferLength = 10 + 1; // 10 for the longest input: 2,147,483,647
private const int Int64NumberBufferLength = 19 + 1; // 19 for the longest input: 9,223,372,036,854,775,807
private const int SingleNumberBufferLength = 113 + 1; // 112 for the longest input + 1 for rounding: 1.40129846E-45
private const int UInt32NumberBufferLength = 10 + 1; // 10 for the longest input: 4,294,967,295
private const int UInt64NumberBufferLength = 20 + 1; // 20 for the longest input: 18,446,744,073,709,551,615
internal unsafe ref struct NumberBuffer
{
public int Precision;
public int Scale;
public bool Sign;
public NumberBufferKind Kind;
public Span<char> Digits;
public NumberBuffer(NumberBufferKind kind, char* pDigits, int digitsLength)
{
Precision = 0;
Scale = 0;
Sign = false;
Kind = kind;
Digits = new Span<char>(pDigits, digitsLength);
}
public char* GetDigitsPointer()
{
// This is safe to do since we are a ref struct
return (char*)(Unsafe.AsPointer(ref Digits[0]));
}
}
internal enum NumberBufferKind : byte
{
Unknown = 0,
Integer = 1,
Decimal = 2,
Double = 3,
}
}
}
|
// 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.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System
{
internal static partial class Number
{
// We need 1 additional byte, per length, for the terminating null
private const int DecimalNumberBufferLength = 50 + 1;
private const int DoubleNumberBufferLength = 768 + 1; // 767 for the longest input + 1 for rounding: 4.9406564584124654E-324
private const int Int32NumberBufferLength = 10 + 1; // 10 for the longest input: 2,147,483,647
private const int Int64NumberBufferLength = 19 + 1; // 19 for the longest input: 9,223,372,036,854,775,807
private const int SingleNumberBufferLength = 113 + 1; // 112 for the longest input + 1 for rounding: 1.40129846E-45
private const int UInt32NumberBufferLength = 10 + 1; // 10 for the longest input: 4,294,967,295
private const int UInt64NumberBufferLength = 20 + 1; // 20 for the longest input: 18,446,744,073,709,551,615
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal unsafe ref struct NumberBuffer
{
public int Precision;
public int Scale;
public bool Sign;
public NumberBufferKind Kind;
public Span<char> Digits;
public NumberBuffer(NumberBufferKind kind, char* pDigits, int digitsLength)
{
Precision = 0;
Scale = 0;
Sign = false;
Kind = kind;
Digits = new Span<char>(pDigits, digitsLength);
}
public char* GetDigitsPointer()
{
// This is safe to do since we are a ref struct
return (char*)(Unsafe.AsPointer(ref Digits[0]));
}
}
internal enum NumberBufferKind : byte
{
Unknown = 0,
Integer = 1,
Decimal = 2,
Double = 3,
}
}
}
|
mit
|
C#
|
bbe198bacd69e95b4a8a36bf89b8d2f619a8b864
|
fix for paths with whitespace
|
DevExpress/AjaxControlToolkit,darilek/AjaxControlToolkit,darilek/AjaxControlToolkit,DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit
|
AjaxControlToolkitVsPackage/AjaxControlToolkitVsPackage.cs
|
AjaxControlToolkitVsPackage/AjaxControlToolkitVsPackage.cs
|
using System;
using System.Collections.Generic;
using System.Drawing.Design;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using System.IO;
namespace AjaxControlToolkitVsPackage {
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0"/*, IconResourceID = 400*/)]
[Guid("e79bade7-6755-466f-9788-3d8243bdcc5f")]
[ProvideToolboxItems(1)]
public sealed class AjaxControlToolkitVsPackage : Package {
public AjaxControlToolkitVsPackage() {
this.ToolboxInitialized += (s, e) => {
InstallToolboxItems();
};
this.ToolboxUpgraded += (s, e) => {
RemoveToolboxItems();
InstallToolboxItems();
};
}
void InstallToolboxItems() {
var assembly = LoadToolkitAssembly();
var version = assembly.GetName().Version.ToString(2);
var service = (IToolboxService)GetService(typeof(IToolboxService));
foreach(var item in EnumerateToolboxItems(assembly))
service.AddToolboxItem(item, "AjaxControlToolkit." + version);
}
void RemoveToolboxItems() {
var service = (IToolboxService)GetService(typeof(IToolboxService));
foreach(var item in EnumerateToolboxItems(LoadToolkitAssembly()))
service.RemoveToolboxItem(item);
}
static IEnumerable<ToolboxItem> EnumerateToolboxItems(Assembly assembly) {
return ToolboxService.GetToolboxItems(assembly, null).Cast<ToolboxItem>();
}
static Assembly LoadToolkitAssembly() {
var path = new Uri(typeof(AjaxControlToolkitVsPackage).Assembly.CodeBase).AbsolutePath;
path = Uri.UnescapeDataString(path);
path = Path.GetDirectoryName(path);
path = Path.Combine(path, "AjaxControlToolkit.dll");
return Assembly.LoadFrom(path);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing.Design;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using System.IO;
namespace AjaxControlToolkitVsPackage {
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0"/*, IconResourceID = 400*/)]
[Guid("e79bade7-6755-466f-9788-3d8243bdcc5f")]
[ProvideToolboxItems(1)]
public sealed class AjaxControlToolkitVsPackage : Package {
public AjaxControlToolkitVsPackage() {
this.ToolboxInitialized += (s, e) => {
InstallToolboxItems();
};
this.ToolboxUpgraded += (s, e) => {
RemoveToolboxItems();
InstallToolboxItems();
};
}
void InstallToolboxItems() {
var assembly = LoadToolkitAssembly();
var version = assembly.GetName().Version.ToString(2);
var service = (IToolboxService)GetService(typeof(IToolboxService));
foreach(var item in EnumerateToolboxItems(assembly))
service.AddToolboxItem(item, "AjaxControlToolkit." + version);
}
void RemoveToolboxItems() {
var service = (IToolboxService)GetService(typeof(IToolboxService));
foreach(var item in EnumerateToolboxItems(LoadToolkitAssembly()))
service.RemoveToolboxItem(item);
}
static IEnumerable<ToolboxItem> EnumerateToolboxItems(Assembly assembly) {
return ToolboxService.GetToolboxItems(assembly, null).Cast<ToolboxItem>();
}
static Assembly LoadToolkitAssembly() {
var path = new Uri(typeof(AjaxControlToolkitVsPackage).Assembly.CodeBase).AbsolutePath;
path = Path.GetDirectoryName(path);
path = Path.Combine(path, "AjaxControlToolkit.dll");
return Assembly.LoadFrom(path);
}
}
}
|
bsd-3-clause
|
C#
|
f9b327b98bc6e5113928a7880583c4543eba6fd7
|
test class for new incorrect implementation
|
kontur-csharper/testing,KotlyarovV/testing,kontur-csharper/testing,kontur-csharper/testing,KotlyarovV/testing
|
Challenge/Infrastructure/IncorrectImplementations_Tests.cs
|
Challenge/Infrastructure/IncorrectImplementations_Tests.cs
|
using System;
using System.Linq;
using NUnit.Framework;
namespace Challenge.Infrastructure
{
[TestFixture]
public class GenerateIncorrectTests
{
[Test]
public void Generate()
{
var impls = ChallengeHelpers.GetIncorrectImplementationTypes();
var code = string.Join(Environment.NewLine,
impls.Select(imp => $"public class {imp.Name}_Tests : {nameof(IncorrectImplementation_TestsBase)} {{}}")
);
Console.WriteLine(code);
}
[Test]
public void CheckAllTestsAreInPlace()
{
var implTypes = ChallengeHelpers.GetIncorrectImplementationTypes();
var testedImpls = ChallengeHelpers.GetIncorrectImplementationTests()
.Select(t => t.CreateStatistics())
.ToArray();
foreach (var impl in implTypes)
{
Assert.NotNull(testedImpls.SingleOrDefault(t => t.GetType().FullName == impl.FullName),
"Single implementation of tests for {0} not found. Regenerate tests with test above!", impl.FullName);
}
}
}
#region Generated with test above
public class WordsStatisticsC_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsE_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsL_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsCR_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsE2_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsE3_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsE4_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsL2_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsL3_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsL4_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO1_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO2_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO3_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO4_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO5_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_123_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_998_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_999_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_QWE_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_STA_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_EN_Tests : IncorrectImplementation_TestsBase { }
#endregion
}
|
using System;
using System.Linq;
using NUnit.Framework;
namespace Challenge.Infrastructure
{
[TestFixture]
public class GenerateIncorrectTests
{
[Test]
public void Generate()
{
var impls = ChallengeHelpers.GetIncorrectImplementationTypes();
var code = string.Join(Environment.NewLine,
impls.Select(imp => $"public class {imp.Name}_Tests : {nameof(IncorrectImplementation_TestsBase)} {{}}")
);
Console.WriteLine(code);
}
[Test]
public void CheckAllTestsAreInPlace()
{
var implTypes = ChallengeHelpers.GetIncorrectImplementationTypes();
var testedImpls = ChallengeHelpers.GetIncorrectImplementationTests()
.Select(t => t.CreateStatistics())
.ToArray();
foreach (var impl in implTypes)
{
Assert.NotNull(testedImpls.SingleOrDefault(t => t.GetType().FullName == impl.FullName),
"Single implementation of tests for {0} not found. Regenerate tests with test above!", impl.FullName);
}
}
}
#region Generated with test above
public class WordsStatisticsC_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsE_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsL_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsCR_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsE2_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsE3_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsE4_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsL2_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsL3_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsL4_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO1_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO2_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO3_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO4_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatisticsO5_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_123_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_998_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_999_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_QWE_Tests : IncorrectImplementation_TestsBase { }
public class WordsStatistics_STA_Tests : IncorrectImplementation_TestsBase { }
#endregion
}
|
mit
|
C#
|
8e289fe4db3e6eca9e02d0f86844ef1ff009498f
|
Disable TestMachineNameProperty test on OS X
|
marksmeltzer/corefx,Petermarcu/corefx,jhendrixMSFT/corefx,wtgodbe/corefx,twsouthwick/corefx,mokchhya/corefx,alphonsekurian/corefx,khdang/corefx,stephenmichaelf/corefx,parjong/corefx,pallavit/corefx,jcme/corefx,alexperovich/corefx,elijah6/corefx,twsouthwick/corefx,manu-silicon/corefx,dotnet-bot/corefx,tstringer/corefx,MaggieTsang/corefx,janhenke/corefx,mokchhya/corefx,richlander/corefx,shimingsg/corefx,stone-li/corefx,tstringer/corefx,SGuyGe/corefx,rahku/corefx,billwert/corefx,Petermarcu/corefx,ravimeda/corefx,Ermiar/corefx,axelheer/corefx,tijoytom/corefx,SGuyGe/corefx,adamralph/corefx,tstringer/corefx,benpye/corefx,mazong1123/corefx,Priya91/corefx-1,tijoytom/corefx,shahid-pk/corefx,alphonsekurian/corefx,gkhanna79/corefx,mokchhya/corefx,janhenke/corefx,twsouthwick/corefx,manu-silicon/corefx,zhenlan/corefx,nchikanov/corefx,ravimeda/corefx,zhenlan/corefx,stephenmichaelf/corefx,lggomez/corefx,shmao/corefx,pallavit/corefx,MaggieTsang/corefx,ptoonen/corefx,jlin177/corefx,ViktorHofer/corefx,shahid-pk/corefx,JosephTremoulet/corefx,seanshpark/corefx,nbarbettini/corefx,twsouthwick/corefx,tstringer/corefx,stephenmichaelf/corefx,richlander/corefx,the-dwyer/corefx,benjamin-bader/corefx,iamjasonp/corefx,yizhang82/corefx,ericstj/corefx,stone-li/corefx,DnlHarvey/corefx,krk/corefx,ptoonen/corefx,SGuyGe/corefx,wtgodbe/corefx,Jiayili1/corefx,gkhanna79/corefx,Petermarcu/corefx,wtgodbe/corefx,weltkante/corefx,dotnet-bot/corefx,pallavit/corefx,marksmeltzer/corefx,alexperovich/corefx,tstringer/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,ptoonen/corefx,rjxby/corefx,ViktorHofer/corefx,gkhanna79/corefx,JosephTremoulet/corefx,ericstj/corefx,Priya91/corefx-1,nbarbettini/corefx,billwert/corefx,dhoehna/corefx,alphonsekurian/corefx,ericstj/corefx,rubo/corefx,mmitche/corefx,Chrisboh/corefx,parjong/corefx,yizhang82/corefx,Chrisboh/corefx,Jiayili1/corefx,alphonsekurian/corefx,mmitche/corefx,axelheer/corefx,nchikanov/corefx,dhoehna/corefx,zhenlan/corefx,shmao/corefx,mafiya69/corefx,cartermp/corefx,rjxby/corefx,iamjasonp/corefx,alexperovich/corefx,tijoytom/corefx,marksmeltzer/corefx,rubo/corefx,Ermiar/corefx,benpye/corefx,stone-li/corefx,stone-li/corefx,rahku/corefx,stone-li/corefx,dsplaisted/corefx,lggomez/corefx,rahku/corefx,Chrisboh/corefx,Ermiar/corefx,krk/corefx,ellismg/corefx,ericstj/corefx,gkhanna79/corefx,Jiayili1/corefx,benpye/corefx,jlin177/corefx,dotnet-bot/corefx,jcme/corefx,elijah6/corefx,gkhanna79/corefx,YoupHulsebos/corefx,richlander/corefx,mazong1123/corefx,Priya91/corefx-1,nbarbettini/corefx,dhoehna/corefx,rahku/corefx,shahid-pk/corefx,yizhang82/corefx,marksmeltzer/corefx,richlander/corefx,mmitche/corefx,jlin177/corefx,parjong/corefx,khdang/corefx,rjxby/corefx,jhendrixMSFT/corefx,SGuyGe/corefx,wtgodbe/corefx,cydhaselton/corefx,richlander/corefx,stone-li/corefx,jcme/corefx,ptoonen/corefx,Petermarcu/corefx,lggomez/corefx,lggomez/corefx,janhenke/corefx,nchikanov/corefx,benjamin-bader/corefx,kkurni/corefx,cartermp/corefx,alexperovich/corefx,lggomez/corefx,richlander/corefx,twsouthwick/corefx,krk/corefx,shmao/corefx,iamjasonp/corefx,pallavit/corefx,dsplaisted/corefx,mafiya69/corefx,jhendrixMSFT/corefx,alexperovich/corefx,dhoehna/corefx,ellismg/corefx,mazong1123/corefx,YoupHulsebos/corefx,nbarbettini/corefx,shahid-pk/corefx,kkurni/corefx,ellismg/corefx,benpye/corefx,stephenmichaelf/corefx,cartermp/corefx,shahid-pk/corefx,the-dwyer/corefx,nbarbettini/corefx,jlin177/corefx,cydhaselton/corefx,cydhaselton/corefx,wtgodbe/corefx,krk/corefx,rjxby/corefx,SGuyGe/corefx,shahid-pk/corefx,elijah6/corefx,mmitche/corefx,shmao/corefx,krytarowski/corefx,elijah6/corefx,axelheer/corefx,dotnet-bot/corefx,parjong/corefx,wtgodbe/corefx,mmitche/corefx,axelheer/corefx,mafiya69/corefx,JosephTremoulet/corefx,alexperovich/corefx,rjxby/corefx,krytarowski/corefx,pallavit/corefx,mokchhya/corefx,krytarowski/corefx,rjxby/corefx,ravimeda/corefx,wtgodbe/corefx,jhendrixMSFT/corefx,BrennanConroy/corefx,tijoytom/corefx,benpye/corefx,nbarbettini/corefx,benjamin-bader/corefx,janhenke/corefx,MaggieTsang/corefx,alphonsekurian/corefx,kkurni/corefx,ravimeda/corefx,jlin177/corefx,rahku/corefx,shimingsg/corefx,MaggieTsang/corefx,manu-silicon/corefx,rubo/corefx,JosephTremoulet/corefx,weltkante/corefx,cydhaselton/corefx,dhoehna/corefx,mazong1123/corefx,lggomez/corefx,YoupHulsebos/corefx,ellismg/corefx,Priya91/corefx-1,DnlHarvey/corefx,mazong1123/corefx,nchikanov/corefx,Petermarcu/corefx,MaggieTsang/corefx,billwert/corefx,dotnet-bot/corefx,tijoytom/corefx,manu-silicon/corefx,lggomez/corefx,jlin177/corefx,ptoonen/corefx,DnlHarvey/corefx,tstringer/corefx,parjong/corefx,mazong1123/corefx,weltkante/corefx,mmitche/corefx,manu-silicon/corefx,the-dwyer/corefx,Ermiar/corefx,elijah6/corefx,zhenlan/corefx,rahku/corefx,mafiya69/corefx,fgreinacher/corefx,jcme/corefx,gkhanna79/corefx,tijoytom/corefx,billwert/corefx,mokchhya/corefx,stephenmichaelf/corefx,MaggieTsang/corefx,nbarbettini/corefx,shimingsg/corefx,BrennanConroy/corefx,Jiayili1/corefx,krytarowski/corefx,parjong/corefx,krk/corefx,shmao/corefx,nchikanov/corefx,shimingsg/corefx,khdang/corefx,Ermiar/corefx,mmitche/corefx,alphonsekurian/corefx,shmao/corefx,tijoytom/corefx,Petermarcu/corefx,fgreinacher/corefx,weltkante/corefx,krk/corefx,zhenlan/corefx,stone-li/corefx,parjong/corefx,Chrisboh/corefx,seanshpark/corefx,cartermp/corefx,shimingsg/corefx,the-dwyer/corefx,marksmeltzer/corefx,twsouthwick/corefx,cartermp/corefx,nchikanov/corefx,kkurni/corefx,Jiayili1/corefx,jcme/corefx,yizhang82/corefx,pallavit/corefx,alexperovich/corefx,iamjasonp/corefx,cydhaselton/corefx,dotnet-bot/corefx,ViktorHofer/corefx,krk/corefx,khdang/corefx,YoupHulsebos/corefx,krytarowski/corefx,dhoehna/corefx,adamralph/corefx,seanshpark/corefx,YoupHulsebos/corefx,ravimeda/corefx,dotnet-bot/corefx,zhenlan/corefx,rjxby/corefx,stephenmichaelf/corefx,jhendrixMSFT/corefx,ravimeda/corefx,BrennanConroy/corefx,marksmeltzer/corefx,Chrisboh/corefx,fgreinacher/corefx,billwert/corefx,twsouthwick/corefx,billwert/corefx,nchikanov/corefx,benjamin-bader/corefx,the-dwyer/corefx,iamjasonp/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,iamjasonp/corefx,janhenke/corefx,ViktorHofer/corefx,yizhang82/corefx,ViktorHofer/corefx,benjamin-bader/corefx,jhendrixMSFT/corefx,DnlHarvey/corefx,ptoonen/corefx,ViktorHofer/corefx,kkurni/corefx,YoupHulsebos/corefx,stephenmichaelf/corefx,elijah6/corefx,dhoehna/corefx,axelheer/corefx,ericstj/corefx,MaggieTsang/corefx,cydhaselton/corefx,ViktorHofer/corefx,cartermp/corefx,janhenke/corefx,adamralph/corefx,Ermiar/corefx,khdang/corefx,Chrisboh/corefx,cydhaselton/corefx,benpye/corefx,rahku/corefx,manu-silicon/corefx,Priya91/corefx-1,manu-silicon/corefx,krytarowski/corefx,weltkante/corefx,shimingsg/corefx,weltkante/corefx,jlin177/corefx,SGuyGe/corefx,weltkante/corefx,Ermiar/corefx,DnlHarvey/corefx,yizhang82/corefx,fgreinacher/corefx,ericstj/corefx,ptoonen/corefx,Jiayili1/corefx,YoupHulsebos/corefx,mokchhya/corefx,Jiayili1/corefx,jcme/corefx,shmao/corefx,elijah6/corefx,seanshpark/corefx,mazong1123/corefx,gkhanna79/corefx,billwert/corefx,dsplaisted/corefx,zhenlan/corefx,kkurni/corefx,rubo/corefx,seanshpark/corefx,ellismg/corefx,mafiya69/corefx,iamjasonp/corefx,seanshpark/corefx,the-dwyer/corefx,Petermarcu/corefx,jhendrixMSFT/corefx,ellismg/corefx,yizhang82/corefx,richlander/corefx,mafiya69/corefx,ericstj/corefx,shimingsg/corefx,krytarowski/corefx,marksmeltzer/corefx,Priya91/corefx-1,DnlHarvey/corefx,benjamin-bader/corefx,seanshpark/corefx,ravimeda/corefx,the-dwyer/corefx,khdang/corefx,alphonsekurian/corefx,rubo/corefx,axelheer/corefx
|
src/System.Runtime.Extensions/tests/System/Environment.MachineName.cs
|
src/System.Runtime.Extensions/tests/System/Environment.MachineName.cs
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Runtime.Extensions.Tests
{
public class Environment_MachineName
{
[ActiveIssue(5732, PlatformID.OSX)]
[Fact]
public void TestMachineNameProperty()
{
string computerName = GetComputerName();
Assert.Equal(computerName, Environment.MachineName);
}
internal static string GetComputerName()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return Environment.GetEnvironmentVariable("COMPUTERNAME");
}
else
{
return Interop.Sys.GetNodeName();
}
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Runtime.Extensions.Tests
{
public class Environment_MachineName
{
[Fact]
public void TestMachineNameProperty()
{
string computerName = GetComputerName();
Assert.Equal(computerName, Environment.MachineName);
}
internal static string GetComputerName()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return Environment.GetEnvironmentVariable("COMPUTERNAME");
}
else
{
return Interop.Sys.GetNodeName();
}
}
}
}
|
mit
|
C#
|
6134f7a7f13848e3836c4e121ca65f2977d16cff
|
Update UnityProject/Assets/Scripts/Weapons/Melee/MeleeStun.cs
|
Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation
|
UnityProject/Assets/Scripts/Weapons/Melee/MeleeStun.cs
|
UnityProject/Assets/Scripts/Weapons/Melee/MeleeStun.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Adding this to a weapon stuns the target on hit
/// If the weapon has the StunBaton behaviour it only stuns when the baton is active
/// </summary>
public class MeleeStun : Interactable<HandApply>
{
/// <summary>
/// How long to stun for (in seconds)
/// </summary>
[SerializeField]
private float stunTime;
private StunBaton stunBaton;
public void Start()
{
stunBaton = GetComponent<StunBaton>();
}
protected override bool WillInteract(HandApply interaction, NetworkSide side)
{
if (!base.WillInteract(interaction, side)) return false;
return interaction.UsedObject == gameObject
&& (!stunBaton || stunBaton.isActive)
&& interaction.TargetObject.GetComponent<RegisterPlayer>();
}
protected override void ServerPerformInteraction(HandApply interaction)
{
GameObject target = interaction.TargetObject;
GameObject performer = interaction.Performer;
// Direction for lerp
Vector2 dir = (target.transform.position - performer.transform.position).normalized;
WeaponNetworkActions wna = performer.GetComponent<WeaponNetworkActions>();
// If we're not on help intent we deal damage!
// Note: this has to be done before the stun, because otherwise if we hit ourselves with an activated stun baton on harm intent
// we wouldn't deal damage to ourselves because CmdRequestMeleeAttack checks whether we're stunned
bool helpIntent = interaction.Performer.GetComponent<PlayerMove>().IsHelpIntent;
if (!helpIntent)
{
// Direction of attack towards the attack target.
wna.CmdRequestMeleeAttack(target, gameObject, dir, interaction.TargetBodyPart, LayerType.None);
}
RegisterPlayer registerPlayerVictim = target.GetComponent<RegisterPlayer>();
// Stun the victim. We checke whether the baton is activated in WillInteract
if (registerPlayerVictim)
{
registerPlayerVictim.Stun(stunTime);
SoundManager.PlayNetworkedAtPos("Sparks0" + UnityEngine.Random.Range(1, 4), target.transform.position);
// Special case: If we're on help intent (only stun), we should still show the lerp (unless we're hitting ourselves)
if (helpIntent && performer != target)
{
wna.RpcMeleeAttackLerp(dir, gameObject);
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Adding this to a weapon stuns the target on hit
/// If the weapon has the StunBaton behaviour it only stuns when the baton is active
/// </summary>
public class MeleeStun : Interactable<HandApply>
{
/// <summary>
/// How long to stun for (in seconds)
/// </summary>
[SerializeField]
private float stunTime;
private StunBaton stunBaton;
public void Start()
{
stunBaton = GetComponent<StunBaton>();
}
protected override bool WillInteract(HandApply interaction, NetworkSide side)
{
return interaction.UsedObject == gameObject
&& (!stunBaton || stunBaton.isActive)
&& interaction.TargetObject.GetComponent<RegisterPlayer>();
}
protected override void ServerPerformInteraction(HandApply interaction)
{
GameObject target = interaction.TargetObject;
GameObject performer = interaction.Performer;
// Direction for lerp
Vector2 dir = (target.transform.position - performer.transform.position).normalized;
WeaponNetworkActions wna = performer.GetComponent<WeaponNetworkActions>();
// If we're not on help intent we deal damage!
// Note: this has to be done before the stun, because otherwise if we hit ourselves with an activated stun baton on harm intent
// we wouldn't deal damage to ourselves because CmdRequestMeleeAttack checks whether we're stunned
bool helpIntent = interaction.Performer.GetComponent<PlayerMove>().IsHelpIntent;
if (!helpIntent)
{
// Direction of attack towards the attack target.
wna.CmdRequestMeleeAttack(target, gameObject, dir, interaction.TargetBodyPart, LayerType.None);
}
RegisterPlayer registerPlayerVictim = target.GetComponent<RegisterPlayer>();
// Stun the victim. We checke whether the baton is activated in WillInteract
if (registerPlayerVictim)
{
registerPlayerVictim.Stun(stunTime);
SoundManager.PlayNetworkedAtPos("Sparks0" + UnityEngine.Random.Range(1, 4), target.transform.position);
// Special case: If we're on help intent (only stun), we should still show the lerp (unless we're hitting ourselves)
if (helpIntent && performer != target)
{
wna.RpcMeleeAttackLerp(dir, gameObject);
}
}
}
}
|
agpl-3.0
|
C#
|
7a34de108cb10ce33fbade1066358414b6c5da81
|
rename variables
|
Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare
|
Assets/Resources/Microgames/KnifeDodge/Scripts/KnifeDodgeController.cs
|
Assets/Resources/Microgames/KnifeDodge/Scripts/KnifeDodgeController.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnifeDodgeController : MonoBehaviour {
List<GameObject> knifeList;
List<GameObject> knifeTargetsList;
public GameObject knifePrefab;
public GameObject reimuPrefab;
public GameObject knifeTargetPrefab;
public int numKnives = 14;
public float spawnDistance = 10.0f;
public int knivesRemoved = 4;
public float timeUntilStrike = 3.0f;
public bool tiltedKnives;
// Use this for initialization
void Start () {
SpawnTargets ();
CreateSafeZone ();
SpawnKnives ();
}
void SpawnTargets() {
knifeTargetsList = new List<GameObject> ();
Vector3 offset = new Vector3(-numKnives / 2.0f + 0.5f, -1.0f / 2.0f + 0.5f, 0.0f);
for (int j = 0; j < numKnives; j++) {
GameObject target = Instantiate(knifeTargetPrefab, new Vector3(j, -5.0f, 0.0f) + offset, Quaternion.identity);
knifeTargetsList.Add(target);
}
}
// Spawns several knives above the player.
void SpawnKnives() {
knifeList = new List<GameObject> ();
for (int i = 0; i < knifeTargetsList.Count; i++) {
Vector3 loc = knifeTargetsList [i].transform.position + new Vector3 (0,spawnDistance,0);
GameObject knife = Instantiate (knifePrefab, loc, Quaternion.identity);
knifeList.Add(knife);
foreach (GameObject k in knifeList) {
Physics2D.IgnoreCollision (knife.GetComponent<BoxCollider2D>(), k.GetComponent<BoxCollider2D>());
}
}
if (tiltedKnives) {
knifeTargetsList.Sort ((a, b) => 1 - 2 * Random.Range (0, 1));
}
//Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
for (int i = 0; i < knifeList.Count; i++) {
Vector3 pos = knifeTargetsList [i].transform.position;
//GetClosestTarget (knifeList [i].transform.position).transform.position;
knifeList[i].GetComponent<KnifeDodgeKnife>().SetFacing(pos);
}
}
// Deletes targets to create a safe zone.
void CreateSafeZone() {
int startingIndex = Random.Range (0,knifeTargetsList.Count - knivesRemoved);
for (int i = startingIndex; i < startingIndex + knivesRemoved; i++) {
knifeTargetsList.RemoveAt (startingIndex);
}
}
GameObject GetClosestTarget(Vector3 knifeVector) {
GameObject closest = knifeTargetsList [0];
foreach (GameObject target in knifeTargetsList) {
if (Vector3.Distance (target.transform.position, knifeVector) < Vector3.Distance (closest.transform.position, knifeVector)) {
closest = target;
}
}
return closest;
}
void Update() {
timeUntilStrike -= Time.deltaTime;
if (timeUntilStrike <= 0) {
foreach (GameObject knife in knifeList) {
knife.GetComponent<KnifeDodgeKnife> ().isMoving = true;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnifeDodgeController : MonoBehaviour {
List<GameObject> knifeList;
List<GameObject> knifeTargetsList;
public GameObject knifePrefab;
public GameObject reimuPrefab;
public GameObject knifeTargetPrefab;
public int cols = 14;
public float spawnDistance = 10.0f;
public int targetsRemoved = 4;
public float timeUntilStrike = 3.0f;
public bool tiltedKnives;
// Use this for initialization
void Start () {
SpawnTargets ();
CreateSafeZone ();
SpawnKnives ();
}
void SpawnTargets() {
knifeTargetsList = new List<GameObject> ();
Vector3 offset = new Vector3(-cols / 2.0f + 0.5f, -1.0f / 2.0f + 0.5f, 0.0f);
for (int j = 0; j < cols; j++) {
GameObject target = Instantiate(knifeTargetPrefab, new Vector3(j, -5.0f, 0.0f) + offset, Quaternion.identity);
knifeTargetsList.Add(target);
}
}
// Spawns several knives above the player.
void SpawnKnives() {
knifeList = new List<GameObject> ();
for (int i = 0; i < knifeTargetsList.Count; i++) {
Vector3 loc = knifeTargetsList [i].transform.position + new Vector3 (0,spawnDistance,0);
GameObject knife = Instantiate (knifePrefab, loc, Quaternion.identity);
knifeList.Add(knife);
foreach (GameObject k in knifeList) {
Physics2D.IgnoreCollision (knife.GetComponent<BoxCollider2D>(), k.GetComponent<BoxCollider2D>());
}
}
if (tiltedKnives) {
knifeTargetsList.Sort ((a, b) => 1 - 2 * Random.Range (0, 1));
}
//Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
for (int i = 0; i < knifeList.Count; i++) {
Vector3 pos = knifeTargetsList [i].transform.position;
//GetClosestTarget (knifeList [i].transform.position).transform.position;
knifeList[i].GetComponent<KnifeDodgeKnife>().SetFacing(pos);
}
}
// Deletes targets to create a safe zone.
void CreateSafeZone() {
int startingIndex = Random.Range (0,knifeTargetsList.Count - targetsRemoved);
for (int i = startingIndex; i < startingIndex + targetsRemoved; i++) {
knifeTargetsList.RemoveAt (startingIndex);
}
}
GameObject GetClosestTarget(Vector3 knifeVector) {
GameObject closest = knifeTargetsList [0];
foreach (GameObject target in knifeTargetsList) {
if (Vector3.Distance (target.transform.position, knifeVector) < Vector3.Distance (closest.transform.position, knifeVector)) {
closest = target;
}
}
return closest;
}
void Update() {
timeUntilStrike -= Time.deltaTime;
if (timeUntilStrike <= 0) {
foreach (GameObject knife in knifeList) {
knife.GetComponent<KnifeDodgeKnife> ().isMoving = true;
}
}
}
}
|
mit
|
C#
|
7be834d1d4c0b0ab2a804bbc7e54cc78b50aabaf
|
Update SettingWidthOfAllColumns.cs
|
aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET
|
Examples/CSharp/RowsColumns/HeightAndWidth/SettingWidthOfAllColumns.cs
|
Examples/CSharp/RowsColumns/HeightAndWidth/SettingWidthOfAllColumns.cs
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.HeightAndWidth
{
public class SettingWidthOfAllColumns
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the width of all columns in the worksheet to 20.5
worksheet.Cells.StandardWidth = 20.5;
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
//ExEnd:1
}
}
}
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.HeightAndWidth
{
public class SettingWidthOfAllColumns
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the width of all columns in the worksheet to 20.5
worksheet.Cells.StandardWidth = 20.5;
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
}
}
}
|
mit
|
C#
|
24cd425d42211dd9784e05370bda9b1bd42f020c
|
Tweak to one of the demo programs
|
taylorjg/Monads
|
DemoPrograms/ReaderHaskellDocsExample1/Program.cs
|
DemoPrograms/ReaderHaskellDocsExample1/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using MonadLib;
namespace ReaderHaskellDocsExample1
{
using Bindings = IDictionary<string, int>;
internal class Program
{
private static void Main()
{
var sampleBindings = new Dictionary<string, int>
{
{"count", 3},
{"1", 1},
{"b", 2}
};
Console.Write("Count is correct for bindings " + FormatBindings(sampleBindings) + ": ");
Console.WriteLine(IsCountCorrect(sampleBindings));
}
private static bool IsCountCorrect(Bindings bindings)
{
return CalcIsCountCorrect().RunReader(bindings);
}
private static Reader<Bindings, bool> CalcIsCountCorrect()
{
Func<string, Func<Bindings, int>> partiallyAppliedLookupVar = name => bindings => LookupVar(name, bindings);
return Reader.Asks(partiallyAppliedLookupVar("count")).Bind(
count => Reader<Bindings>.Ask().Bind(
bindings => Reader<Bindings>.Return(
count == bindings.Count)));
}
private static int LookupVar(string name, Bindings bindings)
{
return bindings.GetValue(name).FromJust;
}
private static string FormatBindings(Bindings bindings)
{
Func<KeyValuePair<string, int>, string> formatBinding =
kvp => string.Format("(\"{0}\",{1})", kvp.Key, kvp.Value);
return string.Format("[{0}]", string.Join(",", bindings.Select(formatBinding)));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using MonadLib;
namespace ReaderHaskellDocsExample1
{
using Bindings = IDictionary<string, int>;
internal class Program
{
private static void Main()
{
var sampleBindings = new Dictionary<string, int>
{
{"count", 3},
{"1", 1},
{"b", 2}
};
Console.Write("Count is correct for bindings " + FormatBindings(sampleBindings) + ": ");
Console.WriteLine(IsCountCorrect(sampleBindings));
}
private static bool IsCountCorrect(Bindings bindings)
{
return CalcIsCountCorrect().RunReader(bindings);
}
private static Reader<Bindings, bool> CalcIsCountCorrect()
{
Func<Bindings, int> lookupVarPartiallyApplied = bindings => LookupVar("count", bindings);
return Reader.Asks(lookupVarPartiallyApplied).Bind(
count => Reader<Bindings>.Ask().Bind(
bindings => Reader<Bindings>.Return(
count == bindings.Count)));
}
private static int LookupVar(string name, Bindings bindings)
{
return bindings.GetValue(name).FromJust;
}
private static string FormatBindings(Bindings bindings)
{
Func<KeyValuePair<string, int>, string> formatBinding =
kvp => string.Format("(\"{0}\",{1})", kvp.Key, kvp.Value);
return string.Format("[{0}]", string.Join(",", bindings.Select(formatBinding)));
}
}
}
|
mit
|
C#
|
9df6d35234cdb078c3cd0d7ea182560fa3432c7d
|
add swagger comments
|
xstof/BigQuotes
|
QuoteApi/QuoteApi/Controllers/QuotesController.cs
|
QuoteApi/QuoteApi/Controllers/QuotesController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using QuoteApi.Services;
using QuoteApi.Domain;
namespace QuoteApi.Controllers
{
[Route("api/[controller]")]
public class QuotesController : Controller
{
private readonly IQuotesService quotesService;
public QuotesController(IQuotesService quotesService)
{
this.quotesService = quotesService;
}
/// <summary>
/// Retrieves random quote
/// </summary>
/// <returns>Random quote.</returns>
// GET api/quotes/random
[HttpGet("/api/quotes/random", Name="GetRandomQuote")]
[ProducesResponseType(typeof(Quote), 200)]
public ActionResult Get()
{
var quote = quotesService.GetRandomQuote();
return Ok(quote);
}
//// GET api/values/5
//[HttpGet("{id}")]
//public string Get(int id)
//{
// return "value";
//}
//// POST api/values
//[HttpPost]
//public void Post([FromBody]string value)
//{
//}
//// PUT api/values/5
//[HttpPut("{id}")]
//public void Put(int id, [FromBody]string value)
//{
//}
//// DELETE api/values/5
//[HttpDelete("{id}")]
//public void Delete(int id)
//{
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using QuoteApi.Services;
namespace QuoteApi.Controllers
{
[Route("api/[controller]")]
public class QuotesController : Controller
{
private readonly IQuotesService quotesService;
public QuotesController(IQuotesService quotesService)
{
this.quotesService = quotesService;
}
// GET api/quotes/random
[HttpGet("/api/quotes/random", Name="GetRandomQuote")]
public ActionResult Get()
{
var quote = quotesService.GetRandomQuote();
return Ok(quote);
}
//// GET api/values/5
//[HttpGet("{id}")]
//public string Get(int id)
//{
// return "value";
//}
//// POST api/values
//[HttpPost]
//public void Post([FromBody]string value)
//{
//}
//// PUT api/values/5
//[HttpPut("{id}")]
//public void Put(int id, [FromBody]string value)
//{
//}
//// DELETE api/values/5
//[HttpDelete("{id}")]
//public void Delete(int id)
//{
//}
}
}
|
mit
|
C#
|
16ecde8b056d6f7fe1e9fdd0042fb0cca094816d
|
Update version number.
|
Damnae/storybrew
|
editor/Properties/AssemblyInfo.cs
|
editor/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.14.*")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.13.*")]
|
mit
|
C#
|
ea2e951fddcf4fbe72a2533db8aea038358fab33
|
return to first position
|
rcseacord/CSharpSC,rcseacord/CSharpSC,rcseacord/CSharpSC
|
CSharpSC/NormB4Validate/ValidateString.cs
|
CSharpSC/NormB4Validate/ValidateString.cs
|
// The MIT License (MIT)
//
// Copyright (c) 2017 Robert C. Seacord
//
// 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;
using System.Text.RegularExpressions;
[assembly: CLSCompliant(true)]
namespace NormB4Validate
{
public class ValidateString
{
public static string NormalizeandValidate(string s)
{
// Validate by checking for angle brackets
Regex rgx = new Regex("[<>]", RegexOptions.IgnoreCase);
Match match = rgx.Match(s);
if (match.Success)
{
// Found black listed tag
throw new InvalidOperationException();
}
else
{
Console.WriteLine("input valid");
}
// Normalize to form KC
s = s.Normalize(NormalizationForm.FormKC);
return s;
}
public static void Main(string[] args)
{
// Assume input is user controlled
// \uFE64 is normalized to < and \uFE65 is normalized to > using the
// NFKC normalization form
string input = "\uFE64" + "script" + "\uFE65";
Console.WriteLine("unnormalized string: " + input);
input = NormalizeandValidate(input);
Console.WriteLine("normalized string: " + input);
Console.WriteLine("Press any key to close");
Console.ReadKey();
}
}
}
|
// The MIT License (MIT)
//
// Copyright (c) 2017 Robert C. Seacord
//
// 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;
using System.Text.RegularExpressions;
[assembly: CLSCompliant(true)]
namespace NormB4Validate
{
public class ValidateString
{
public static string NormalizeandValidate(string s)
{
// Normalize to form KC
s = s.Normalize(NormalizationForm.FormKC);
// Validate by checking for angle brackets
Regex rgx = new Regex("[<>]", RegexOptions.IgnoreCase);
Match match = rgx.Match(s);
if (match.Success)
{
// Found black listed tag
throw new InvalidOperationException();
}
else
{
Console.WriteLine("input valid");
}
return s;
}
public static void Main(string[] args)
{
// Assume input is user controlled
// \uFE64 is normalized to < and \uFE65 is normalized to > using the
// NFKC normalization form
string input = "\uFE64" + "script" + "\uFE65";
Console.WriteLine("unnormalized string: " + input);
input = NormalizeandValidate(input);
Console.WriteLine("normalized string: " + input);
Console.WriteLine("Press any key to close");
Console.ReadKey();
}
}
}
|
mit
|
C#
|
c9142f03e8b135e925f9ba4482f3e844a4720e2f
|
Bump version to 0.7.4
|
quisquous/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot
|
CactbotOverlay/Properties/AssemblyInfo.cs
|
CactbotOverlay/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.7.4.0")]
[assembly: AssemblyFileVersion("0.7.4.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.7.3.0")]
[assembly: AssemblyFileVersion("0.7.3.0")]
|
apache-2.0
|
C#
|
ebdb93ef885625786fbaae6350c4519e05e922cb
|
Bump version for 0.3.1
|
sqt/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot
|
CactbotOverlay/Properties/AssemblyInfo.cs
|
CactbotOverlay/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.3.1.0")]
[assembly: AssemblyFileVersion("0.3.1.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
|
apache-2.0
|
C#
|
b9480a096cebbb883a91661ee7019212f0b5c97a
|
Change assertion
|
ekincaglar/clarizen
|
Clarizen.Tests/Steps/Api_ProjectsSteps.cs
|
Clarizen.Tests/Steps/Api_ProjectsSteps.cs
|
using Clarizen.Tests.Context;
using Ekin.Clarizen.Data.Request;
using TechTalk.SpecFlow;
using Xunit;
using System;
using System.Collections.Generic;
using System.Text;
using Ekin.Clarizen;
using Microsoft.Extensions.Configuration;
using System.Linq;
namespace Clarizen.Tests.Steps
{
[Binding]
public class ProjectsSteps:BaseApiSteps
{
public ProjectsSteps(BaseContext context):base (context)
{
}
[Then(@"there are '(.*)' projects")]
public void ThenThereAreProjects(int expectedProjectCount)
{
var query = new query("SELECT name, state FROM project where state = 'Active'");
var results = Context.Api.ExecuteQuery(query);
Assert.True((results.Error == null), results.Error);
Assert.Equal(expectedProjectCount,results.Data.entities.Length);
}
}
}
|
using Clarizen.Tests.Context;
using Ekin.Clarizen.Data.Request;
using TechTalk.SpecFlow;
using Xunit;
using System;
using System.Collections.Generic;
using System.Text;
using Ekin.Clarizen;
using Microsoft.Extensions.Configuration;
using System.Linq;
namespace Clarizen.Tests.Steps
{
[Binding]
public class ProjectsSteps:BaseApiSteps
{
public ProjectsSteps(BaseContext context):base (context)
{
}
[Then(@"there are '(.*)' projects")]
public void ThenThereAreProjects(int expectedProjectCount)
{
var query = new query("SELECT name, state FROM project where state = 'Active'");
var results = Context.Api.ExecuteQuery(query);
Assert.True((results.Error == null), results.Error);
Assert.True(results.Data.entities.Length==expectedProjectCount);
}
}
}
|
mit
|
C#
|
4d8295f96403514a167af0e969bf3d34d2828fa2
|
add GA
|
cythilya/Dotchi,cythilya/Dotchi,cythilya/Dotchi
|
Dotchi/Dotchi/Views/Shared/_Layout.cshtml
|
Dotchi/Dotchi/Views/Shared/_Layout.cshtml
|
<!doctype html>
@{
ViewBag.Title = "吃什麼,どっち - 讓朋友幫你決定吃什麼";
ViewBag.Description = "吃什麼,どっち - 讓朋友幫你決定吃什麼";
ViewBag.Cover = "";
var currentURL = "http://dotchi.apphb.com" + HttpContext.Current.Request.RawUrl;
}
<html itemscope itemtype="http://schema.org/WebPage">
<head>
<meta charset="utf-8">
<title>@(ViewBag.Title)</title>
<meta name="description" content="@(ViewBag.Description)" />
<meta name="google-site-verification" content="66HCcYwJ0Hb8f3bZX2ZO0A2IR0BSgjjj7VEXPaoThrs" />
<meta itemprop="name" content="@(ViewBag.Title)">
<meta itemprop="description" content="@(ViewBag.Description)">
<meta itemprop="image" content="@(ViewBag.Cove)">
<meta property="og:title" content="@(ViewBag.Title)" />
<meta property="og:description" content="描述" />
<meta property="og:url" content="@(currentURL)" />
<meta property="og:site_name" content="Dotchi">
<meta property="og:type" content="article" />
<meta property="og:image" content="@(ViewBag.Cove)" />
<link rel="Shortcut Icon" type="image/x-icon" href="/Content/dotchi/img/favicon.ico">
<link rel="stylesheet" href="/Content/common/css/reset-font-min.css">
<link rel="stylesheet" href="/Content/common/css/clearfix.css">
<link rel="stylesheet" href="/Content/dotchi/css/basic.css">
<link rel="stylesheet" href="/Content/dotchi/css/style.css">
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-44647801-4', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
@RenderBody()
<script src="/Content/common/js/jquery-1.8.2.min.js"></script>
<script src="/Content/common/js/facebook.js" data-appid=1399777113657271></script>
<script src="/Content/common/js/jquery.cookie.js"></script>
<script src="/Content/common/js/jquery.fd.rating.js"></script>
<script src="/Content/dotchi/js/script.js"></script>
</body>
</html>
|
<!doctype html>
@{
ViewBag.Title = "吃什麼,どっち - 讓朋友幫你決定吃什麼";
ViewBag.Description = "吃什麼,どっち - 讓朋友幫你決定吃什麼";
ViewBag.Cover = "";
var currentURL = "http://dotchi.apphb.com" + HttpContext.Current.Request.RawUrl;
}
<html>
<head>
<meta charset="utf-8">
<title>@(ViewBag.Title)</title>
<meta name="description" content="@(ViewBag.Description)" />
<meta name="google-site-verification" content="66HCcYwJ0Hb8f3bZX2ZO0A2IR0BSgjjj7VEXPaoThrs" />
@*Schema.org markup for Google+ *@
<meta itemprop="name" content="@(ViewBag.Title)">
<meta itemprop="description" content="@(ViewBag.Description)">
<meta itemprop="image" content="@(ViewBag.Cove)">
@* Open Graph data *@
<meta property="og:title" content="@(ViewBag.Title)" />
<meta property="og:description" content="描述" />
<meta property="og:url" content="@(currentURL)" />
<meta property="og:site_name" content="Dotchi">
<meta property="og:type" content="article" />
<meta property="og:image" content="@(ViewBag.Cove)" />
<link rel="Shortcut Icon" type="image/x-icon" href="/Content/dotchi/img/favicon.ico">
<link rel="stylesheet" href="/Content/common/css/reset-font-min.css">
<link rel="stylesheet" href="/Content/common/css/clearfix.css">
<link rel="stylesheet" href="/Content/dotchi/css/basic.css">
<link rel="stylesheet" href="/Content/dotchi/css/style.css">
</head>
<body>
@RenderBody()
<script src="/Content/common/js/jquery-1.8.2.min.js"></script>
<script src="/Content/common/js/facebook.js" data-appid=1399777113657271></script>
<script src="/Content/common/js/jquery.cookie.js"></script>
<script src="/Content/common/js/jquery.fd.rating.js"></script>
<script src="/Content/dotchi/js/script.js"></script>
</body>
</html>
|
mit
|
C#
|
9b504272e41e9e6fadcb315eb732c05c9a458c0b
|
Make Header a property
|
UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu
|
osu.Game/Overlays/Profile/Sections/PaginatedContainerWithHeader.cs
|
osu.Game/Overlays/Profile/Sections/PaginatedContainerWithHeader.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Users;
namespace osu.Game.Overlays.Profile.Sections
{
public abstract class PaginatedContainerWithHeader<TModel> : PaginatedContainer<TModel>
{
private readonly string headerText;
private readonly CounterVisibilityState counterVisibilityState;
protected PaginatedContainerHeader Header { get; private set; }
protected PaginatedContainerWithHeader(Bindable<User> user, string headerText, CounterVisibilityState counterVisibilityState, string missing = "")
: base(user, missing)
{
this.headerText = headerText;
this.counterVisibilityState = counterVisibilityState;
}
protected override Drawable CreateHeaderContent => Header = new PaginatedContainerHeader(headerText, counterVisibilityState);
protected override void OnUserChanged(User user)
{
base.OnUserChanged(user);
Header.Current.Value = GetCount(user);
}
protected virtual int GetCount(User user) => 0;
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Users;
namespace osu.Game.Overlays.Profile.Sections
{
public abstract class PaginatedContainerWithHeader<TModel> : PaginatedContainer<TModel>
{
private readonly string headerText;
private readonly CounterVisibilityState counterVisibilityState;
protected PaginatedContainerHeader Header;
protected PaginatedContainerWithHeader(Bindable<User> user, string headerText, CounterVisibilityState counterVisibilityState, string missing = "")
: base(user, missing)
{
this.headerText = headerText;
this.counterVisibilityState = counterVisibilityState;
}
protected override Drawable CreateHeaderContent => Header = new PaginatedContainerHeader(headerText, counterVisibilityState);
protected override void OnUserChanged(User user)
{
base.OnUserChanged(user);
Header.Current.Value = GetCount(user);
}
protected virtual int GetCount(User user) => 0;
}
}
|
mit
|
C#
|
db4a585b265416e8cd3d4107a0ef85a5b5e03b8d
|
Fix running on < iOS 6.0
|
PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto
|
Source/Eto.Platform.iOS/EtoAppDelegate.cs
|
Source/Eto.Platform.iOS/EtoAppDelegate.cs
|
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Eto.Platform.iOS.Forms;
using Eto.Forms;
namespace Eto.Platform.iOS
{
[MonoTouch.Foundation.Register("EtoAppDelegate")]
public class EtoAppDelegate : UIApplicationDelegate
{
public EtoAppDelegate ()
{
}
public override bool FinishedLaunching (UIApplication application, NSDictionary launcOptions)
{
ApplicationHandler.Instance.Initialize(this);
return true;
}
}
}
|
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Eto.Platform.iOS.Forms;
using Eto.Forms;
namespace Eto.Platform.iOS
{
[MonoTouch.Foundation.Register("EtoAppDelegate")]
public class EtoAppDelegate : UIApplicationDelegate
{
public EtoAppDelegate ()
{
}
public override bool WillFinishLaunching (UIApplication application, NSDictionary launchOptions)
{
ApplicationHandler.Instance.Initialize(this);
return true;
}
}
}
|
bsd-3-clause
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.