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 |
|---|---|---|---|---|---|---|---|---|
76e0fc251c104a6acc9f4d8f86463dfe8c2cea4e
|
Add Repeat attribute (dotnet/extensions#1375)
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/Testing/src/xunit/ConditionalFactAttribute.cs
|
src/Testing/src/xunit/ConditionalFactAttribute.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;
using Xunit;
using Xunit.Sdk;
namespace Microsoft.AspNetCore.Testing.xunit
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[XunitTestCaseDiscoverer("Microsoft.AspNetCore.Testing.xunit." + nameof(ConditionalFactDiscoverer), "Microsoft.AspNetCore.Testing")]
public class ConditionalFactAttribute : FactAttribute
{
}
}
|
// 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;
using Xunit;
using Xunit.Sdk;
namespace Microsoft.AspNetCore.Testing.xunit
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[XunitTestCaseDiscoverer("Microsoft.AspNetCore.Testing.xunit." + nameof(ConditionalFactDiscoverer), "Microsoft.AspNetCore.Testing")]
public class ConditionalFactAttribute : FactAttribute
{
}
}
|
apache-2.0
|
C#
|
ffea18032a2da9ffd93a8d167a63f94dfe19f4a9
|
delete the test repos
|
octokit/octokit.net,forki/octokit.net,eriawan/octokit.net,shiftkey-tester/octokit.net,khellang/octokit.net,octokit-net-test-org/octokit.net,devkhan/octokit.net,Sarmad93/octokit.net,hitesh97/octokit.net,octokit-net-test-org/octokit.net,Red-Folder/octokit.net,naveensrinivasan/octokit.net,ChrisMissal/octokit.net,gabrielweyer/octokit.net,kolbasov/octokit.net,ivandrofly/octokit.net,shiftkey/octokit.net,takumikub/octokit.net,fffej/octokit.net,shiftkey/octokit.net,nsrnnnnn/octokit.net,gabrielweyer/octokit.net,fake-organization/octokit.net,rlugojr/octokit.net,alfhenrik/octokit.net,hahmed/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,thedillonb/octokit.net,M-Zuber/octokit.net,chunkychode/octokit.net,alfhenrik/octokit.net,dampir/octokit.net,khellang/octokit.net,SamTheDev/octokit.net,adamralph/octokit.net,kdolan/octokit.net,Sarmad93/octokit.net,dlsteuer/octokit.net,thedillonb/octokit.net,TattsGroup/octokit.net,SmithAndr/octokit.net,M-Zuber/octokit.net,magoswiat/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,mminns/octokit.net,eriawan/octokit.net,bslliw/octokit.net,yonglehou/octokit.net,octokit/octokit.net,SLdragon1989/octokit.net,mminns/octokit.net,SamTheDev/octokit.net,dampir/octokit.net,shana/octokit.net,TattsGroup/octokit.net,octokit-net-test/octokit.net,daukantas/octokit.net,gdziadkiewicz/octokit.net,editor-tools/octokit.net,michaKFromParis/octokit.net,brramos/octokit.net,devkhan/octokit.net,yonglehou/octokit.net,ivandrofly/octokit.net,nsnnnnrn/octokit.net,hahmed/octokit.net,editor-tools/octokit.net,SmithAndr/octokit.net,cH40z-Lord/octokit.net,gdziadkiewicz/octokit.net,shana/octokit.net,rlugojr/octokit.net,shiftkey-tester/octokit.net,chunkychode/octokit.net,geek0r/octokit.net,darrelmiller/octokit.net
|
clean-up-after-tests/Program.cs
|
clean-up-after-tests/Program.cs
|
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Octokit;
using Octokit.Tests.Integration;
namespace clean_up_after_tests
{
class Program
{
static readonly Regex _repoNameRegex = new Regex(@"\-[0-9]{17}$");
static void Main()
{
if (Helper.Credentials == null)
{
Console.WriteLine("The environment variable OCTOKIT_GITHUBUSERNAME and OCTOKIT_GITHUBPASSWORD must be set. Exiting.");
Console.WriteLine();
}
else
{
DeleteRepos().Wait();
}
#if DEBUG
Console.WriteLine("Press ENTER to quit.");
Console.ReadLine();
Console.WriteLine();
#endif
}
static async Task DeleteRepos()
{
var api = new GitHubClient("Octokit.net/clean-up-after-test.exe")
{
Credentials = Helper.Credentials
};
Console.WriteLine("Getting all repositories for the test account.");
var repos = await api.Repository.GetAllForCurrent();
foreach (var repo in repos)
{
if (_repoNameRegex.IsMatch(repo.Name))
{
await api.Repository.Delete(repo.Owner.Login, repo.Name);
Console.WriteLine("Deleted {0}.", repo.FullName);
}
else
Console.WriteLine("Skipped {0}.", repo.FullName);
}
}
}
}
|
using System;
using Octokit.Tests.Integration;
namespace clean_up_after_tests
{
class Program
{
static void Main()
{
if (Helper.Credentials == null)
{
Console.WriteLine("The environment variable OCTOKIT_GITHUBUSERNAME and OCTOKIT_GITHUBPASSWORD must be set. Exiting.");
Console.WriteLine();
}
#if DEBUG
Console.WriteLine("Press ENTER to quit.");
Console.ReadLine();
Console.WriteLine();
#endif
}
}
}
|
mit
|
C#
|
a19399498065ef1ecd42b78c6e171168ce7692c1
|
Remove redundant property attribute
|
mstrother/BmpListener
|
BmpListener/Bmp/BmpPeerHeader.cs
|
BmpListener/Bmp/BmpPeerHeader.cs
|
using System;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace BmpListener.Bmp
{
public class PeerHeader
{
public PeerHeader(byte[] data)
{
Decode(data);
}
public PeerType PeerType { get; private set; }
public bool IsPostPolicy { get; private set; }
public ulong PeerDistinguisher { get; private set; }
public IPAddress PeerAddress { get; private set; }
public uint PeerAS { get; private set; }
public IPAddress PeerBGPId { get; private set; }
public DateTime Timestamp { get; private set; }
public void Decode(byte[] data)
{
PeerType = (PeerType) data[0];
var flags = data[1];
if ((flags & (1 << 6)) != 0)
IsPostPolicy = true;
if ((flags & (1 << 7)) != 0)
{
var ipBytes = data.Skip(10).Take(16).ToArray();
PeerAddress = new IPAddress(ipBytes);
}
else
{
var ipBytes = data.Skip(22).Take(4).ToArray();
PeerAddress = new IPAddress(ipBytes);
}
PeerDistinguisher = BitConverter.ToUInt64(data.Skip(2).Take(8).Reverse().ToArray(), 0);
PeerAS = data.ToUInt32(26);
var bytes = new byte[4];
Buffer.BlockCopy(data, 30, bytes, 0, 4);
PeerBGPId = new IPAddress(bytes);
var seconds = data.ToUInt32(34);
var microSeconds = data.ToUInt32(38);
Timestamp =
DateTimeOffset.FromUnixTimeSeconds(seconds).AddTicks(microSeconds * 10).DateTime.ToUniversalTime();
}
}
}
|
using System;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace BmpListener.Bmp
{
public class PeerHeader
{
public PeerHeader(byte[] data)
{
Decode(data);
}
[JsonConverter(typeof(StringEnumConverter))]
public PeerType PeerType { get; private set; }
public bool IsPostPolicy { get; private set; }
public ulong PeerDistinguisher { get; private set; }
public IPAddress PeerAddress { get; private set; }
public uint PeerAS { get; private set; }
public IPAddress PeerBGPId { get; private set; }
public DateTime Timestamp { get; private set; }
public void Decode(byte[] data)
{
PeerType = (PeerType) data[0];
var flags = data[1];
if ((flags & (1 << 6)) != 0)
IsPostPolicy = true;
if ((flags & (1 << 7)) != 0)
{
var ipBytes = data.Skip(10).Take(16).ToArray();
PeerAddress = new IPAddress(ipBytes);
}
else
{
var ipBytes = data.Skip(22).Take(4).ToArray();
PeerAddress = new IPAddress(ipBytes);
}
PeerDistinguisher = BitConverter.ToUInt64(data.Skip(2).Take(8).Reverse().ToArray(), 0);
PeerAS = data.ToUInt32(26);
var bytes = new byte[4];
Buffer.BlockCopy(data, 30, bytes, 0, 4);
PeerBGPId = new IPAddress(bytes);
var seconds = data.ToUInt32(34);
var microSeconds = data.ToUInt32(38);
Timestamp =
DateTimeOffset.FromUnixTimeSeconds(seconds).AddTicks(microSeconds * 10).DateTime.ToUniversalTime();
}
}
}
|
mit
|
C#
|
f090ac53cdedc4e071754eb8afa738e48d96246f
|
Fix github version scraping
|
sqt/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot,sqt/cactbot
|
CactbotOverlay/VersionChecker.cs
|
CactbotOverlay/VersionChecker.cs
|
using System;
using System.Text.RegularExpressions;
namespace Cactbot {
// This class can determine the current plugin version, as well as the latest version
// released of the plugin on GitHub. It is inspired by the work of anoyetta in
// https://github.com/anoyetta/ACT.SpecialSpellTimer/blob/master/ACT.SpecialSpellTimer.Core/UpdateChecker.cs
class VersionChecker {
private ILogger logger_ = null;
public const string kReleaseUrl = "http://github.com/quisquous/cactbot/releases/latest";
public const string kIssueUrl = "http://github.com/quisquous/cactbot/issues";
public VersionChecker(ILogger logger) {
logger_ = logger;
}
public Version GetLocalVersion() {
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
}
public Version GetRemoteVersion() {
string html;
try {
var web = new System.Net.WebClient();
var page_stream = web.OpenRead(kReleaseUrl);
var reader = new System.IO.StreamReader(page_stream);
html = reader.ReadToEnd();
} catch (Exception e) {
logger_.LogError("Error fetching most recent github release: " + e.Message + "\n" + e.StackTrace);
return new Version();
}
var pattern = @"<h1(\s.*?)?\sclass=""[^""]*release-title[^""]*"".*?>(?<Header>.*?)</h1>";
var regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
var match = regex.Match(html);
if (!match.Success) {
logger_.LogError("Error parsing most recent github release, no match found. Please report an issue at " + kIssueUrl);
return new Version();
}
string header_string = match.Groups["Header"].Value;
pattern = @"<a\s.*?>\s*(?<ReleaseTitle>.*?)\s*</a>";
regex = new Regex(pattern, RegexOptions.IgnoreCase);
match = regex.Match(header_string);
if (!match.Success) {
logger_.LogError("Error parsing most recent github release, no match found. Please report an issue at " + kIssueUrl);
return new Version();
}
string version_string = match.Groups["ReleaseTitle"].Value;
pattern = @"(?<VersionNumber>(?<Major>[0-9]+)\.(?<Minor>[0-9]+)\.(?<Revision>[0-9+]))";
regex = new Regex(pattern);
match = regex.Match(version_string);
if (!match.Success) {
logger_.LogError("Error parsing most recent github release, no version number found. Please report an issue at " + kIssueUrl);
return new Version();
}
return new Version(int.Parse(match.Groups["Major"].Value), int.Parse(match.Groups["Minor"].Value), int.Parse(match.Groups["Revision"].Value));
}
}
} // namespace Cactbot
|
using System;
using System.Text.RegularExpressions;
namespace Cactbot {
// This class can determine the current plugin version, as well as the latest version
// released of the plugin on GitHub. It is inspired by the work of anoyetta in
// https://github.com/anoyetta/ACT.SpecialSpellTimer/blob/master/ACT.SpecialSpellTimer.Core/UpdateChecker.cs
class VersionChecker {
private ILogger logger_ = null;
public const string kReleaseUrl = "http://github.com/quisquous/cactbot/releases/latest";
public const string kIssueUrl = "http://github.com/quisquous/cactbot/issues";
public VersionChecker(ILogger logger) {
logger_ = logger;
}
public Version GetLocalVersion() {
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
}
public Version GetRemoteVersion() {
string html;
try {
var web = new System.Net.WebClient();
var page_stream = web.OpenRead(kReleaseUrl);
var reader = new System.IO.StreamReader(page_stream);
html = reader.ReadToEnd();
} catch (Exception e) {
logger_.LogError("Error fetching most recent github release: " + e.Message + "\n" + e.StackTrace);
return new Version();
}
var pattern = @"<h1(\s.*?)?\sclass=""release-title"".*?>(?<Header>.*?)</h1>";
var regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
var match = regex.Match(html);
if (!match.Success) {
logger_.LogError("Error parsing most recent github release, no match found. Please report an issue at " + kIssueUrl);
return new Version();
}
string header_string = match.Groups["Header"].Value;
pattern = @"<a\s.*?>\s*(?<ReleaseTitle>.*?)\s*</a>";
regex = new Regex(pattern, RegexOptions.IgnoreCase);
match = regex.Match(header_string);
if (!match.Success) {
logger_.LogError("Error parsing most recent github release, no match found. Please report an issue at " + kIssueUrl);
return new Version();
}
string version_string = match.Groups["ReleaseTitle"].Value;
pattern = @"(?<VersionNumber>(?<Major>[0-9]+)\.(?<Minor>[0-9]+)\.(?<Revision>[0-9+]))";
regex = new Regex(pattern);
match = regex.Match(version_string);
if (!match.Success) {
logger_.LogError("Error parsing most recent github release, no version number found. Please report an issue at " + kIssueUrl);
return new Version();
}
return new Version(int.Parse(match.Groups["Major"].Value), int.Parse(match.Groups["Minor"].Value), int.Parse(match.Groups["Revision"].Value));
}
}
} // namespace Cactbot
|
apache-2.0
|
C#
|
10db62603a9bf449b0f796308eb022f074524c20
|
Test for empty session id
|
thisdata/thisdata-dotnet
|
tests/ClientTests.cs
|
tests/ClientTests.cs
|
using System;
using System.Web;
using System.IO;
using NUnit.Framework;
using ThisData;
namespace ThisData.Net.Tests
{
[TestFixture]
public class ClientTests
{
private HttpRequest _request;
private string _signature;
private string _payload;
private Client _client;
[SetUp]
public void Setup()
{
_client = new ThisData.Client("");
_request = new HttpRequest(string.Empty, "https://thisdata.com", string.Empty);
_signature = "291264d1d4b3857e872d67b7587d3702b28519a0e3ce689d688372b7d31f6af484439a1885f21650ac073e48119d496f44dc97d3dc45106409d345f057443c6b";
_payload = "{\"version\":1,\"was_user\":null,\"alert\":{\"id\":533879540905150463,\"description\":null}}";
HttpContext.Current = new HttpContext(_request, new HttpResponse(new StringWriter()));
}
[Test]
public void ValidateWebhook_WithValidSecret()
{
string secret = "hello";
Assert.IsTrue(_client.ValidateWebhook(secret, _signature, _payload));
}
[Test]
public void ValidateWebhook_WithInvalidSecret()
{
string secret = "goodbye";
Assert.IsFalse(_client.ValidateWebhook(secret, _signature, _payload));
}
[Test]
public void Track_EventWithUserId()
{
Assert.DoesNotThrow(() => _client.Track("log-in", userId: "123456"));
}
[Test]
public void Track_EventWithoutUserId()
{
Assert.DoesNotThrow(() => _client.Track("log-in"));
}
[Test]
public void GetSessionId_WhenNoSessionAvailable()
{
string id = _client.GetSessionId();
Assert.AreEqual(string.Empty, id);
}
}
}
|
using System;
using System.Web;
using System.IO;
using NUnit.Framework;
using ThisData;
namespace ThisData.Net.Tests
{
[TestFixture]
public class ClientTests
{
private HttpRequest _request;
private string _signature;
private string _payload;
private Client _client;
[SetUp]
public void Setup()
{
_client = new ThisData.Client("");
_request = new HttpRequest(string.Empty, "https://thisdata.com", string.Empty);
_signature = "291264d1d4b3857e872d67b7587d3702b28519a0e3ce689d688372b7d31f6af484439a1885f21650ac073e48119d496f44dc97d3dc45106409d345f057443c6b";
_payload = "{\"version\":1,\"was_user\":null,\"alert\":{\"id\":533879540905150463,\"description\":null}}";
HttpContext.Current = new HttpContext(_request, new HttpResponse(new StringWriter()));
}
[Test]
public void ValidateWebhook_WithValidSecret()
{
string secret = "hello";
Assert.IsTrue(_client.ValidateWebhook(secret, _signature, _payload));
}
[Test]
public void ValidateWebhook_WithInvalidSecret()
{
string secret = "goodbye";
Assert.IsFalse(_client.ValidateWebhook(secret, _signature, _payload));
}
[Test]
public void Track_EventWithUserId()
{
Assert.DoesNotThrow(() => _client.Track("log-in", userId: "123456"));
}
[Test]
public void Track_EventWithoutUserId()
{
Assert.DoesNotThrow(() => _client.Track("log-in"));
}
[Test]
public void GetSessionId_DoesNotExplodeWithNoSession()
{
Assert.DoesNotThrow(() => _client.GetSessionId());
}
}
}
|
mit
|
C#
|
b43046946eb61ec0a52632f74314e93bcfb9ae93
|
Rename variable
|
appharbor/appharbor-cli
|
src/AppHarbor/MaskedConsoleInput.cs
|
src/AppHarbor/MaskedConsoleInput.cs
|
using System;
namespace AppHarbor
{
public class MaskedConsoleInput : IMaskedInput
{
public virtual string Get()
{
string input = "";
ConsoleKeyInfo consoleKey;
do
{
consoleKey = Console.ReadKey(true);
if (consoleKey.Key != ConsoleKey.Backspace && consoleKey.Key != ConsoleKey.Enter)
{
input += consoleKey.KeyChar;
Console.Write("*");
}
else if (consoleKey.Key == ConsoleKey.Backspace && input.Length > 0)
{
input = input.Substring(0, (input.Length - 1));
Console.Write("\b \b");
}
}
while (consoleKey.Key != ConsoleKey.Enter);
return input;
}
}
}
|
using System;
namespace AppHarbor
{
public class MaskedConsoleInput : IMaskedInput
{
public virtual string Get()
{
string input = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
input += key.KeyChar;
Console.Write("*");
}
else if (key.Key == ConsoleKey.Backspace && input.Length > 0)
{
input = input.Substring(0, (input.Length - 1));
Console.Write("\b \b");
}
}
while (key.Key != ConsoleKey.Enter);
return input;
}
}
}
|
mit
|
C#
|
87c330c397af51a54d08803c8f351328a9d89f01
|
Set AzureTenantId from options
|
serilog/serilog-sinks-mssqlserver
|
src/Serilog.Sinks.MSSqlServer/Configuration/Implementations/Microsoft.Extensions.Configuration/MicrosoftExtensionsSinkOptionsProvider.cs
|
src/Serilog.Sinks.MSSqlServer/Configuration/Implementations/Microsoft.Extensions.Configuration/MicrosoftExtensionsSinkOptionsProvider.cs
|
using System;
using System.Globalization;
using Microsoft.Extensions.Configuration;
namespace Serilog.Sinks.MSSqlServer.Configuration
{
internal class MicrosoftExtensionsSinkOptionsProvider : IMicrosoftExtensionsSinkOptionsProvider
{
public MSSqlServerSinkOptions ConfigureSinkOptions(MSSqlServerSinkOptions sinkOptions, IConfigurationSection config)
{
if (config == null)
{
return sinkOptions;
}
ReadTableOptions(config, sinkOptions);
ReadBatchSettings(config, sinkOptions);
ReadAzureManagedIdentitiesOptions(config, sinkOptions);
return sinkOptions;
}
private static void ReadTableOptions(IConfigurationSection config, MSSqlServerSinkOptions sinkOptions)
{
SetProperty.IfNotNull<string>(config["tableName"], val => sinkOptions.TableName = val);
SetProperty.IfNotNull<string>(config["schemaName"], val => sinkOptions.SchemaName = val);
SetProperty.IfNotNull<bool>(config["autoCreateSqlTable"], val => sinkOptions.AutoCreateSqlTable = val);
}
private static void ReadBatchSettings(IConfigurationSection config, MSSqlServerSinkOptions sinkOptions)
{
SetProperty.IfNotNull<int>(config["batchPostingLimit"], val => sinkOptions.BatchPostingLimit = val);
SetProperty.IfNotNull<string>(config["batchPeriod"], val => sinkOptions.BatchPeriod = TimeSpan.Parse(val, CultureInfo.InvariantCulture));
SetProperty.IfNotNull<bool>(config["eagerlyEmitFirstEvent"], val => sinkOptions.EagerlyEmitFirstEvent = val);
}
private static void ReadAzureManagedIdentitiesOptions(IConfigurationSection config, MSSqlServerSinkOptions sinkOptions)
{
SetProperty.IfNotNull<bool>(config["useAzureManagedIdentity"], val => sinkOptions.UseAzureManagedIdentity = val);
SetProperty.IfNotNull<string>(config["azureServiceTokenProviderResource"], val => sinkOptions.AzureServiceTokenProviderResource = val);
SetProperty.IfNotNull<string>(config["azureTenantId"], val => sinkOptions.AzureTenantId = val);
}
}
}
|
using System;
using System.Globalization;
using Microsoft.Extensions.Configuration;
namespace Serilog.Sinks.MSSqlServer.Configuration
{
internal class MicrosoftExtensionsSinkOptionsProvider : IMicrosoftExtensionsSinkOptionsProvider
{
public MSSqlServerSinkOptions ConfigureSinkOptions(MSSqlServerSinkOptions sinkOptions, IConfigurationSection config)
{
if (config == null)
{
return sinkOptions;
}
ReadTableOptions(config, sinkOptions);
ReadBatchSettings(config, sinkOptions);
ReadAzureManagedIdentitiesOptions(config, sinkOptions);
return sinkOptions;
}
private static void ReadTableOptions(IConfigurationSection config, MSSqlServerSinkOptions sinkOptions)
{
SetProperty.IfNotNull<string>(config["tableName"], val => sinkOptions.TableName = val);
SetProperty.IfNotNull<string>(config["schemaName"], val => sinkOptions.SchemaName = val);
SetProperty.IfNotNull<bool>(config["autoCreateSqlTable"], val => sinkOptions.AutoCreateSqlTable = val);
}
private static void ReadBatchSettings(IConfigurationSection config, MSSqlServerSinkOptions sinkOptions)
{
SetProperty.IfNotNull<int>(config["batchPostingLimit"], val => sinkOptions.BatchPostingLimit = val);
SetProperty.IfNotNull<string>(config["batchPeriod"], val => sinkOptions.BatchPeriod = TimeSpan.Parse(val, CultureInfo.InvariantCulture));
SetProperty.IfNotNull<bool>(config["eagerlyEmitFirstEvent"], val => sinkOptions.EagerlyEmitFirstEvent = val);
}
private static void ReadAzureManagedIdentitiesOptions(IConfigurationSection config, MSSqlServerSinkOptions sinkOptions)
{
SetProperty.IfNotNull<bool>(config["useAzureManagedIdentity"], val => sinkOptions.UseAzureManagedIdentity = val);
SetProperty.IfNotNull<string>(config["azureServiceTokenProviderResource"], val => sinkOptions.AzureServiceTokenProviderResource = val);
}
}
}
|
apache-2.0
|
C#
|
4a74cc7180ff28c7efd343ffa82ef746fff028ec
|
make the HIcon class sealed
|
milleniumbug/Taxonomy
|
TaxonomyWpf/NativeExplorerInterface.cs
|
TaxonomyWpf/NativeExplorerInterface.cs
|
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace TaxonomyWpf
{
public static class NativeExplorerInterface
{
[StructLayout(LayoutKind.Sequential)]
private struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
private const uint SHGFI_ICON = 0x100;
private const uint SHGFI_LARGEICON = 0x0; // 'Large icon
private const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll")]
private static extern IntPtr SHGetFileInfo(
string pszPath,
uint dwFileAttributes,
ref SHFILEINFO psfi,
uint cbSizeFileInfo,
uint uFlags);
[DllImport("user32.dll")]
private static extern bool DestroyIcon(IntPtr handle);
public sealed class HIcon : IDisposable
{
public IntPtr IconHandle { get; private set; }
public void Dispose()
{
DestroyIcon(IconHandle);
IconHandle = IntPtr.Zero;
}
public HIcon(IntPtr iconHandle)
{
IconHandle = iconHandle;
}
}
public static void OpenContextMenuForFile(string path)
{
}
public static HIcon GetHIconForFile(string path)
{
IntPtr hImg;
string fName = path;
SHFILEINFO shinfo = new SHFILEINFO();
hImg = SHGetFileInfo(
fName,
0,
ref shinfo,
(uint)Marshal.SizeOf(shinfo),
SHGFI_ICON | SHGFI_LARGEICON);
// TODO: "You should call this function from a background thread. Failure to do so could cause the UI to stop responding."
return new HIcon(shinfo.hIcon);
}
}
}
|
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace TaxonomyWpf
{
public static class NativeExplorerInterface
{
[StructLayout(LayoutKind.Sequential)]
private struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
private const uint SHGFI_ICON = 0x100;
private const uint SHGFI_LARGEICON = 0x0; // 'Large icon
private const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll")]
private static extern IntPtr SHGetFileInfo(
string pszPath,
uint dwFileAttributes,
ref SHFILEINFO psfi,
uint cbSizeFileInfo,
uint uFlags);
[DllImport("user32.dll")]
private static extern bool DestroyIcon(IntPtr handle);
public class HIcon : IDisposable
{
public IntPtr IconHandle { get; private set; }
public void Dispose()
{
DestroyIcon(IconHandle);
IconHandle = IntPtr.Zero;
}
public HIcon(IntPtr iconHandle)
{
IconHandle = iconHandle;
}
}
public static void OpenContextMenuForFile(string path)
{
}
public static HIcon GetHIconForFile(string path)
{
IntPtr hImg;
string fName = path;
SHFILEINFO shinfo = new SHFILEINFO();
hImg = SHGetFileInfo(
fName,
0,
ref shinfo,
(uint)Marshal.SizeOf(shinfo),
SHGFI_ICON | SHGFI_LARGEICON);
// TODO: "You should call this function from a background thread. Failure to do so could cause the UI to stop responding."
return new HIcon(shinfo.hIcon);
}
}
}
|
mit
|
C#
|
3b56d027f19699988a10eb5e534702a873be51b1
|
Enable automatic database migrations
|
johanhelsing/vaskelista,johanhelsing/vaskelista
|
Vaskelista/Migrations/Configuration.cs
|
Vaskelista/Migrations/Configuration.cs
|
namespace Vaskelista.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Vaskelista.Models.VaskelistaContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "Vaskelista.Models.VaskelistaContext";
}
protected override void Seed(Vaskelista.Models.VaskelistaContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
|
namespace Vaskelista.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Vaskelista.Models.VaskelistaContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "Vaskelista.Models.VaskelistaContext";
}
protected override void Seed(Vaskelista.Models.VaskelistaContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
|
mit
|
C#
|
b0598c6f7457f8ce4889b1a466d9fe55b829a601
|
add test
|
MartinRL/WebDevApi
|
WebDevApi.Test/CustomerResourceTest.cs
|
WebDevApi.Test/CustomerResourceTest.cs
|
using FluentAssertions;
using Nancy;
using Nancy.Testing;
using Xunit;
namespace WebDevApi.Test
{
public class CustomerResourceTest
{
[Fact]
public void get_should_return_customer_as_json()
{
var browser = new Browser(new Bootstrapper());
var response = browser.Get("/customers/1", with =>
{
with.Header("accept", "application/json");
with.HttpRequest();
});
response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Body.AsString().Should().Be(
@"{
""customer"": {
""id"": 1,
""cpr"": 180173XXXX,
""secondaryPhoneNumber"": ""+46707318625"",
""name"": {
""first"": ""Martin"",
""last"": ""Rosén-Lidholm""
}
""email"": ""mrol@telenor.dk"",
""address"": {
""street"": ""Nils Anderssons gata"",
""houseNumber"": 12,
""postalCode"": 21836,
""city"": ""Bunkeflostrand"",
""country"": ""Sverige"",
}
""balance"": 322.50,
""electiveServices"": [
{ ""name"": ""5 GB data"" },
{ ""name"": ""Udlandsopkald"" },
]
""receivePromomotionsPermissions"": {
""sms"": false,
""email"": true,
""phoneCall"": false
}
}
}");
}
[Fact]
public void put_to_existing_id_should_update_customer()
{
var browser = new Browser(new Bootstrapper());
var response = browser.Put("/customers/1", browserContext => browserContext.Body(
@"{
""customer"": {
""id"": 1,
""cpr"": 180173XXXX,
""secondaryPhoneNumber"": ""+46707318625"",
""name"": {
""first"": ""Martin"",
""last"": ""Rosén-Lidholm""
}
""email"": ""mrl@mvno.dk"",
""address"": {
""street"": ""Nils Anderssons gata"",
""houseNumber"": 12,
""postalCode"": 21836,
""city"": ""Bunkeflostrand"",
""country"": ""Sverige"",
}
""balance"": 322.50,
""electiveServices"": [
{ ""name"": ""5 GB data"" },
{ ""name"": ""Udlandsopkald"" },
]
""receivePromomotionsPermissions"": {
""sms"": true,
""email"": true,
""phoneCall"": false
}
}
}")).Then.Get("/customers/1", with =>
{
with.Header("accept", "application/json");
with.HttpRequest();
});
response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Body.AsString().Should().Be(
@"{
""customer"": {
""id"": 1,
""cpr"": 180173XXXX,
""secondaryPhoneNumber"": ""+46707318625"",
""name"": {
""first"": ""Martin"",
""last"": ""Rosén-Lidholm""
}
""email"": ""mrl@mvno.dk"",
""address"": {
""street"": ""Nils Anderssons gata"",
""houseNumber"": 12,
""postalCode"": 21836,
""city"": ""Bunkeflostrand"",
""country"": ""Sverige"",
}
""balance"": 322.50,
""electiveServices"": [
{ ""name"": ""5 GB data"" },
{ ""name"": ""Udlandsopkald"" },
]
""receivePromomotionsPermissions"": {
""sms"": true,
""email"": true,
""phoneCall"": false
}
}
}");
}
}
}
|
using FluentAssertions;
using Nancy;
using Nancy.Testing;
using Xunit;
namespace WebDevApi.Test
{
public class CustomerResourceTest
{
[Fact]
public void get_should_return_customer_as_json()
{
var browser = new Browser(new Bootstrapper());
var response = browser.Get("/customers/1", with =>
{
with.Header("accept", "application/json");
with.HttpRequest();
});
response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Body.AsString().Should().Be(
@"{
""customer"": {
""id"": 1,
""cpr"": 180173XXXX,
""secondaryPhoneNumber"": ""+46707318625"",
""name"": {
""first"": ""Martin"",
""last"": ""Rosén-Lidholm""
}
""email"": ""mrol@telenor.dk"",
""address"": {
""street"": ""Nils Anderssons gata"",
""houseNumber"": 12,
""postalCode"": 21836,
""city"": ""Bunkeflostrand"",
""country"": ""Sverige"",
}
""balance"": 322.50,
""electiveServices"": [
{ ""name"": ""5 GB data"" },
{ ""name"": ""Udlandsopkald"" },
]
""receivePromomotionsPermissions"": {
""sms"": false,
""email"": true,
""phoneCall"": false
}
}
}");
}
}
}
|
mit
|
C#
|
7331ee97b730a60fd9234b2f0e2bbf27325017da
|
Tidy up AssemblyInfo.cs
|
rlipscombe/vs-welcome-page
|
WelcomePage/Properties/AssemblyInfo.cs
|
WelcomePage/Properties/AssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WelcomePage")]
[assembly: AssemblyDescription("WelcomePage Visual Studio Extension")]
[assembly: AssemblyCompany("Roger Lipscombe")]
[assembly: AssemblyProduct("WelcomePage")]
[assembly: AssemblyCopyright("Copyright (c) 2013 Roger Lipscombe")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System;
using System.Reflection;
using System.Resources;
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("WelcomePage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Roger Lipscombe")]
[assembly: AssemblyProduct("WelcomePage")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
apache-2.0
|
C#
|
d1cea2109a62cd12475d7f9aaca17aace3beb875
|
change protection level
|
pashchuk/graphic_modeling-labs,pashchuk/graphic_modeling-labs
|
lab2/MainVindowViewModel.cs
|
lab2/MainVindowViewModel.cs
|
using System.ComponentModel;
namespace lab1
{
public class MainVindowViewModel : INotifyPropertyChanged
{
private double _m = 10, _r = 10;
public double M
{
get { return _m; }
set
{
_m = value;
OnPropertyChanged(nameof(M));
}
}
public double R
{
get { return _r; }
set
{
_r = value;
OnPropertyChanged(nameof(R));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string property)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
|
using System.ComponentModel;
namespace lab1
{
public class MainVindowViewModel : INotifyPropertyChanged
{
private double _m = 10, _r = 10;
public double M
{
get { return _m; }
set
{
_m = value;
OnPropertyChanged(nameof(M));
}
}
public double R
{
get { return _r; }
set
{
_r = value;
OnPropertyChanged(nameof(R));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
|
mit
|
C#
|
c34e70e987112045e325e085c4ba2c03f176ccfe
|
Update example
|
chris-peterson/Spiffy,danvallejo/Spiffy,danvallejo/Spiffy
|
src/Tests/TestConsoleApp/Program.cs
|
src/Tests/TestConsoleApp/Program.cs
|
using System;
using System.Threading;
using Spiffy.Monitoring;
namespace TestConsoleApp
{
class Program
{
static void Main()
{
// this should be the first line of your application
NLog.Initialize();
// key-value-pairs set here appear in every event message
GlobalEventContext.Instance
.Set("Application", "TestConsole");
using (var context = new EventContext())
{
context["MyCustomValue"] = "foo";
using (context.Time("LongRunning"))
{
DoSomethingLongRunning();
}
try
{
DoSomethingDangerous();
}
catch (Exception ex)
{
context.IncludeException(ex);
}
}
}
static void DoSomethingLongRunning()
{
Thread.Sleep(1000);
}
static void DoSomethingDangerous()
{
if (new Random().Next(100) == 0)
{
throw new ApplicationException("you were unlucky!", new NullReferenceException());
}
}
}
}
|
using System;
using System.Threading;
using Spiffy.Monitoring;
namespace TestConsoleApp
{
class Program
{
static void Main()
{
GlobalEventContext.Instance.Set("Application", "TestConsole");
NLog.Initialize();
using (var context = new EventContext())
{
context["CustomValue"] = "foo";
using (context.Time("WarmUpCache"))
{
Thread.Sleep(1000);
}
context.IncludeException(new ApplicationException("bar", new NullReferenceException()));
}
}
}
}
|
mit
|
C#
|
b4b82eee62dbbe4e61f2bdf9ca65e9aa4704fca2
|
Add test.
|
diryboy/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,sharwell/roslyn,MichalStrehovsky/roslyn,diryboy/roslyn,sharwell/roslyn,VSadov/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,brettfo/roslyn,AlekseyTs/roslyn,VSadov/roslyn,jmarolf/roslyn,sharwell/roslyn,davkean/roslyn,tmat/roslyn,heejaechang/roslyn,AmadeusW/roslyn,tannergooding/roslyn,gafter/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,DustinCampbell/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,weltkante/roslyn,DustinCampbell/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,xasx/roslyn,AlekseyTs/roslyn,abock/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,heejaechang/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,swaroop-sridhar/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,reaction1989/roslyn,xasx/roslyn,jcouv/roslyn,eriawan/roslyn,dotnet/roslyn,abock/roslyn,mavasani/roslyn,diryboy/roslyn,aelij/roslyn,mavasani/roslyn,agocke/roslyn,reaction1989/roslyn,swaroop-sridhar/roslyn,reaction1989/roslyn,jmarolf/roslyn,DustinCampbell/roslyn,weltkante/roslyn,dotnet/roslyn,jcouv/roslyn,nguerrera/roslyn,stephentoub/roslyn,wvdd007/roslyn,eriawan/roslyn,AmadeusW/roslyn,genlu/roslyn,gafter/roslyn,aelij/roslyn,brettfo/roslyn,physhi/roslyn,mgoertz-msft/roslyn,genlu/roslyn,brettfo/roslyn,davkean/roslyn,gafter/roslyn,dotnet/roslyn,heejaechang/roslyn,tmat/roslyn,nguerrera/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,aelij/roslyn,KevinRansom/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,agocke/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,panopticoncentral/roslyn,davkean/roslyn,VSadov/roslyn,physhi/roslyn,agocke/roslyn,AmadeusW/roslyn,tmat/roslyn,tannergooding/roslyn,xasx/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,swaroop-sridhar/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,jcouv/roslyn,abock/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,stephentoub/roslyn,MichalStrehovsky/roslyn
|
src/EditorFeatures/CSharpTest/UseCompoundAssignment/UseCompoundAssignmentTests.cs
|
src/EditorFeatures/CSharpTest/UseCompoundAssignment/UseCompoundAssignmentTests.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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment;
using Microsoft.CodeAnalysis.CSharp.UseDefaultLiteral;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCompoundAssignment
{
public class UseCompoundAssignmentTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseCompoundAssignmentDiagnosticAnalyzer(), new CSharpUseCompoundAssignmentCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)]
public async Task TestAddExpression()
{
await TestInRegularAndScriptAsync(
@"public class C
{
void M(int a)
{
a [||]= a + 10;
}
}",
@"public class C
{
void M(int a)
{
a += 10;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)]
public async Task TestSubtractExpression()
{
await TestInRegularAndScriptAsync(
@"public class C
{
void M(int a)
{
a [||]= a - 10;
}
}",
@"public class C
{
void M(int a)
{
a -= 10;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)]
public async Task TestMultiplyExpression()
{
await TestInRegularAndScriptAsync(
@"public class C
{
void M(int a)
{
a [||]= a * 10;
}
}",
@"public class C
{
void M(int a)
{
a *= 10;
}
}");
}
}
}
|
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment;
using Microsoft.CodeAnalysis.CSharp.UseDefaultLiteral;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCompoundAssignment
{
public class UseCompoundAssignmentTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseCompoundAssignmentDiagnosticAnalyzer(), new CSharpUseCompoundAssignmentCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)]
public async Task TestAddExpression()
{
await TestInRegularAndScriptAsync(
@"public class C
{
void M(int a)
{
a [||]= a + 10;
}
}",
@"public class C
{
void M(int a)
{
a += 10;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)]
public async Task TestSubtractExpression()
{
await TestInRegularAndScriptAsync(
@"public class C
{
void M(int a)
{
a [||]= a - 10;
}
}",
@"public class C
{
void M(int a)
{
a -= 10;
}
}");
}
}
}
|
mit
|
C#
|
1f4cd4138aa94a1fe9d58f3915dc7cdc6f10a1b4
|
Debug log store saves logs only when debugger is attached
|
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
|
src/Server/Bit.Owin/Implementations/DebugLogStore.cs
|
src/Server/Bit.Owin/Implementations/DebugLogStore.cs
|
#define DEBUG
using System;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Diagnostics;
namespace Bit.Owin.Implementations
{
public class DebugLogStore : ILogStore
{
private readonly IContentFormatter _formatter;
public DebugLogStore(IContentFormatter formatter)
{
_formatter = formatter;
}
protected DebugLogStore()
{
}
public virtual void SaveLog(LogEntry logEntry)
{
if (Debugger.IsAttached)
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
public virtual async Task SaveLogAsync(LogEntry logEntry)
{
if (Debugger.IsAttached)
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
}
}
|
#define DEBUG
using System;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Diagnostics;
namespace Bit.Owin.Implementations
{
public class DebugLogStore : ILogStore
{
private readonly IContentFormatter _formatter;
public DebugLogStore(IContentFormatter formatter)
{
_formatter = formatter;
}
protected DebugLogStore()
{
}
public virtual void SaveLog(LogEntry logEntry)
{
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
public virtual async Task SaveLogAsync(LogEntry logEntry)
{
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
}
}
|
mit
|
C#
|
9502cf08b04976cbf80610db545baf64b5f1ec39
|
Use null-forgiving operator rather than assertion
|
ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework
|
osu.Framework/Extensions/ObjectExtensions/ObjectExtensions.cs
|
osu.Framework/Extensions/ObjectExtensions/ObjectExtensions.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.Diagnostics.CodeAnalysis;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
public static T AsNonNull<T>(this T? obj)
where T : class
{
return obj!;
}
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
}
}
|
// 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
public static T AsNonNull<T>(this T? obj)
where T : class
{
Trace.Assert(obj != null);
Debug.Assert(obj != null);
return obj;
}
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
}
}
|
mit
|
C#
|
7af33cce1b4b712538ea55a584e1243240126110
|
Make sure ToSourceSpan always returns a legal SourceSpan
|
jonathanvdc/Pixie,jonathanvdc/Pixie
|
Pixie.Loyc/SourceHelpers.cs
|
Pixie.Loyc/SourceHelpers.cs
|
using System;
using Pixie.Code;
using Loyc.Syntax;
namespace Pixie.Loyc
{
/// <summary>
/// Helper methods that bride the divide between Loyc and Pixie
/// source source references.
/// </summary>
public static class SourceHelpers
{
/// <summary>
/// Creates a Pixie source region that is equivalent to a
/// Loyc source range.
/// </summary>
/// <param name="range">A source range.</param>
/// <returns>A source region.</returns>
public static SourceRegion ToSourceRegion(this SourceRange range)
{
return new SourceRegion(ToSourceSpan(range));
}
/// <summary>
/// Creates a Pixie source span that is equivalent to a
/// Loyc source range.
/// </summary>
/// <param name="range">A source range.</param>
/// <returns>A source span.</returns>
public static SourceSpan ToSourceSpan(this SourceRange range)
{
var document = ToSourceDocument(range.Source);
var clampedStartOffset = Math.Max(0, Math.Min(document.Length - 1, range.StartIndex));
var clampedEndOffset = Math.Max(0, Math.Min(document.Length - 1, range.EndIndex));
return new SourceSpan(
document,
clampedStartOffset,
clampedEndOffset - clampedStartOffset);
}
/// <summary>
/// Wraps a Loyc source file in a Pixie source document.
/// </summary>
/// <param name="sourceFile">A Loyc source file to wrap.</param>
/// <returns>A Pixie source document.</returns>
public static SourceDocument ToSourceDocument(this ISourceFile sourceFile)
{
return new LoycSourceDocument(sourceFile);
}
}
}
|
using System;
using Pixie.Code;
using Loyc.Syntax;
namespace Pixie.Loyc
{
/// <summary>
/// Helper methods that bride the divide between Loyc and Pixie
/// source source references.
/// </summary>
public static class SourceHelpers
{
/// <summary>
/// Creates a Pixie source region that is equivalent to a
/// Loyc source range.
/// </summary>
/// <param name="range">A source range.</param>
/// <returns>A source region.</returns>
public static SourceRegion ToSourceRegion(this SourceRange range)
{
return new SourceRegion(ToSourceSpan(range));
}
/// <summary>
/// Creates a Pixie source span that is equivalent to a
/// Loyc source range.
/// </summary>
/// <param name="range">A source range.</param>
/// <returns>A source span.</returns>
public static SourceSpan ToSourceSpan(this SourceRange range)
{
return new SourceSpan(
ToSourceDocument(range.Source),
range.StartIndex,
range.Length);
}
/// <summary>
/// Wraps a Loyc source file in a Pixie source document.
/// </summary>
/// <param name="sourceFile">A Loyc source file to wrap.</param>
/// <returns>A Pixie source document.</returns>
public static SourceDocument ToSourceDocument(this ISourceFile sourceFile)
{
return new LoycSourceDocument(sourceFile);
}
}
}
|
mit
|
C#
|
b25b65b279338c56740307c8e1bbc02d3de28544
|
Add TabPage constructor to pass single control for the tab and padding
|
l8s/Eto,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1
|
Source/Eto/Forms/Controls/TabPage.cs
|
Source/Eto/Forms/Controls/TabPage.cs
|
using System;
using System.Collections;
using Eto.Drawing;
using System.Collections.ObjectModel;
namespace Eto.Forms
{
public interface ITabPage : IContainer
{
string Text { get; set; }
Image Image { get; set; }
}
/// <summary>
/// Enhanced tab pages that support
/// additional functionality
/// </summary>
public interface ITabPage2 : ITabPage
{
/// <summary>
/// If true, a dirty indicator is displayed
/// so that the user knows the contents of the page
/// are dirty, i.e. need saving.
/// </summary>
bool Dirty { get; set; }
}
public class TabPage : Container, IImageListItem
{
ITabPage handler;
public TabPage (Control control, Padding? padding = null)
: this (control.Generator)
{
this.AddDockedControl (control, padding);
}
public TabPage (Generator g = null) : this (g, typeof(ITabPage))
{
}
protected TabPage (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
handler = (ITabPage)Handler;
}
public event EventHandler<EventArgs> Click;
public void OnClick (EventArgs e)
{
if (Click != null)
Click (this, e);
}
public string Text {
get { return handler.Text; }
set { handler.Text = value; }
}
public Image Image {
get { return handler.Image; }
set { handler.Image = value; }
}
public virtual string Key { get; set; }
}
public class TabPageCollection : Collection<TabPage>
{
TabControl control;
internal TabPageCollection (TabControl control)
{
this.control = control;
}
protected override void InsertItem (int index, TabPage item)
{
base.InsertItem (index, item);
control.InsertTab (index, item);
}
protected override void ClearItems ()
{
base.ClearItems ();
control.ClearTabs ();
}
protected override void RemoveItem (int index)
{
control.RemoveTab (index, this [index]);
base.RemoveItem (index);
}
}
}
|
using System;
using System.Collections;
using Eto.Drawing;
using System.Collections.ObjectModel;
namespace Eto.Forms
{
public interface ITabPage : IContainer
{
string Text { get; set; }
Image Image { get; set; }
}
/// <summary>
/// Enhanced tab pages that support
/// additional functionality
/// </summary>
public interface ITabPage2 : ITabPage
{
/// <summary>
/// If true, a dirty indicator is displayed
/// so that the user knows the contents of the page
/// are dirty, i.e. need saving.
/// </summary>
bool Dirty { get; set; }
}
public class TabPage : Container, IImageListItem
{
ITabPage handler;
public TabPage () : this (Generator.Current)
{
}
public TabPage (Generator g) : this (g, typeof(ITabPage))
{
}
protected TabPage (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
handler = (ITabPage)Handler;
}
public event EventHandler<EventArgs> Click;
public void OnClick (EventArgs e)
{
if (Click != null)
Click (this, e);
}
public string Text {
get { return handler.Text; }
set { handler.Text = value; }
}
public Image Image {
get { return handler.Image; }
set { handler.Image = value; }
}
public virtual string Key { get; set; }
}
public class TabPageCollection : Collection<TabPage>
{
TabControl control;
internal TabPageCollection (TabControl control)
{
this.control = control;
}
protected override void InsertItem (int index, TabPage item)
{
base.InsertItem (index, item);
control.InsertTab (index, item);
}
protected override void ClearItems ()
{
base.ClearItems ();
control.ClearTabs ();
}
protected override void RemoveItem (int index)
{
control.RemoveTab (index, this [index]);
base.RemoveItem (index);
}
}
}
|
bsd-3-clause
|
C#
|
34c2c2a068283e26a0a0813caaa4345daf6180f8
|
Update AssemblyInfo.cs
|
danshapir/DOTNET.Stringifier
|
Stringify/Properties/AssemblyInfo.cs
|
Stringify/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("Stringify")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Stringify")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c66b1953-134e-4256-9980-553474b994b2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Stringify")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Stringify")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c66b1953-134e-4256-9980-553474b994b2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
e0c9b161851405b43b1757fd5c4f77483c3c8872
|
use IsLocal in DatabaseInfo
|
NaamloosDT/ModCore,NaamloosDT/ModCore
|
ModCore/Database/DatabaseInfo.cs
|
ModCore/Database/DatabaseInfo.cs
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using ModCore.Logic.EntityFramework.AttributeImpl;
namespace ModCore.Database
{
[Table("mcore_database_info")]
public class DatabaseInfo
{
[Column("id")]
public int Id { get; set; }
[Index("meta_key_key", IsUnique = true, IsLocal = true)]
[Column("meta_key")]
[Required]
public string MetaKey { get; set; }
[Column("meta_value")]
[Required]
public string MetaValue { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using ModCore.Logic.EntityFramework.AttributeImpl;
namespace ModCore.Database
{
[Table("mcore_database_info")]
public class DatabaseInfo
{
[Column("id")]
public int Id { get; set; }
[Index("mcore_database_info_meta_key_key", IsUnique = true)]
[Column("meta_key")]
[Required]
public string MetaKey { get; set; }
[Column("meta_value")]
[Required]
public string MetaValue { get; set; }
}
}
|
mit
|
C#
|
f97eaad7414dd9653059c714911e6b823bc132ff
|
Add test for SimpleJson List deserialization bug
|
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
|
src/tests/UnitTests/Primitives/SerializationTests.cs
|
src/tests/UnitTests/Primitives/SerializationTests.cs
|
using GitHub.Unity;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace UnitTests.Primitives
{
[TestFixture]
class SerializationTests
{
[Test]
public void DateTimeSerializationRoundTrip()
{
var dt1 = DateTimeOffset.ParseExact("2018-05-01T12:04:29.0000000-02:00", Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
var dt2 = DateTimeOffset.ParseExact("2018-05-01T12:04:29.000-02:00", Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
var dt3 = DateTimeOffset.ParseExact("2018-05-01T12:04:29-02:00", Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
var str1 = dt1.ToJson();
var ret1 = str1.FromJson<DateTimeOffset>();
Assert.AreEqual(dt1, ret1);
var str2 = dt2.ToJson();
var ret2 = str2.FromJson<DateTimeOffset>();
Assert.AreEqual(dt2, ret2);
var str3 = dt3.ToJson();
var ret3 = str3.FromJson<DateTimeOffset>();
Assert.AreEqual(dt3, ret3);
Assert.AreEqual(dt1, dt2);
Assert.AreEqual(dt2, dt3);
}
class TestData
{
public List<string> Things { get; set; } = new List<string>();
}
[Test]
public void ListDeserializesCorrectly()
{
var data = new TestData();
data.Things.Add("something");
var json = data.ToJson();
var ret = json.FromJson<TestData>();
CollectionAssert.AreEquivalent(data.Things, ret.Things);
}
}
}
|
using GitHub.Unity;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace UnitTests.Primitives
{
[TestFixture]
class SerializationTests
{
[Test]
public void DateTimeSerializationRoundTrip()
{
var dt1 = DateTimeOffset.ParseExact("2018-05-01T12:04:29.0000000-02:00", Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
var dt2 = DateTimeOffset.ParseExact("2018-05-01T12:04:29.000-02:00", Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
var dt3 = DateTimeOffset.ParseExact("2018-05-01T12:04:29-02:00", Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
var str1 = dt1.ToJson();
var ret1 = str1.FromJson<DateTimeOffset>();
Assert.AreEqual(dt1, ret1);
var str2 = dt2.ToJson();
var ret2 = str2.FromJson<DateTimeOffset>();
Assert.AreEqual(dt2, ret2);
var str3 = dt3.ToJson();
var ret3 = str3.FromJson<DateTimeOffset>();
Assert.AreEqual(dt3, ret3);
Assert.AreEqual(dt1, dt2);
Assert.AreEqual(dt2, dt3);
}
}
}
|
mit
|
C#
|
9240b2e3fe54a27e506d56961e25473dcb2a0eb7
|
Change Json Library
|
CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity
|
Assets/Scripts/CloudBread/JsonParser.cs
|
Assets/Scripts/CloudBread/JsonParser.cs
|
using System;
using System.IO;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using JsonFx.Json;
// Json Library Change
namespace AssemblyCSharp
{
public class JsonParser
{
public JsonParser ()
{
}
public static string Write(object obj){
return JsonUtility.ToJson(obj);
// return JsonFx.Json.JsonWriter.Serialize (obj);
}
public static string Write(Dictionary<string, object> obj){
return JsonUtility.ToJson (obj);
// return JsonWriter.Serialize (obj);
}
public static string WritePretty(Dictionary<string,object>[] obj){
return WritePretty (obj);;
}
public static string WritePretty(object obj){
// JsonWriterSettings settings = new JsonWriterSettings();
// settings.PrettyPrint = true;
// JsonFx.Json.JsonDataWriter writer = new JsonDataWriter(settings);
//
// StringWriter wr = new StringWriter();
// writer.Serialize(wr, obj);
// string json = wr.ToString();
string json = JsonUtility.ToJson (obj);
return json;
}
public static Dictionary<string, object> Read(string json){
var requestDic= JsonReader.Deserialize < Dictionary<string, object>>(json);
return requestDic;
}
public static object Read2Object (string json){
// var requestDic= JsonReader.Deserialize <List<string>>(json);
var requestDic = JsonReader.Deserialize (json);
return requestDic;
}
public static T Read<T>(string json){
return JsonReader.Deserialize<T> (json);
}
}
}
|
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using JsonFx.Json;
namespace AssemblyCSharp
{
public class JsonParser
{
public JsonParser ()
{
}
public static string Write(object obj){
return JsonFx.Json.JsonWriter.Serialize (obj);
}
public static string Write(Dictionary<string, object> obj){
return JsonWriter.Serialize (obj);
}
public static string WritePretty(Dictionary<string,object>[] obj){
JsonWriterSettings settings = new JsonWriterSettings();
settings.PrettyPrint = true;
JsonFx.Json.JsonDataWriter writer = new JsonDataWriter(settings);
StringWriter wr = new StringWriter();
writer.Serialize(wr, obj);
string json = wr.ToString();
return json;
}
public static string WritePretty(object obj){
JsonWriterSettings settings = new JsonWriterSettings();
settings.PrettyPrint = true;
JsonFx.Json.JsonDataWriter writer = new JsonDataWriter(settings);
StringWriter wr = new StringWriter();
writer.Serialize(wr, obj);
string json = wr.ToString();
return json;
}
public static Dictionary<string, object> Read(string json){
var requestDic= JsonReader.Deserialize < Dictionary<string, object>>(json);
return requestDic;
}
public static object Read2Object (string json){
// var requestDic= JsonReader.Deserialize <List<string>>(json);
var requestDic = JsonReader.Deserialize (json);
return requestDic;
}
public static T Read<T>(string json){
return JsonReader.Deserialize<T> (json);
}
}
}
|
mit
|
C#
|
d5d365f022967365a3aeee0909cbea8693e81c80
|
set character position on correct side of door collider
|
virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,whoa-algebraic/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,virtuoushub/game-off-2016
|
Assets/Scripts/RoomNavigationManager.cs
|
Assets/Scripts/RoomNavigationManager.cs
|
using UnityEngine;
using System.Collections;
public class RoomNavigationManager : MonoBehaviour {
public GameObject PlayerGameObject;
public GameObject[] RoomPrefabs;
private GameObject activeRoomPrefab;
void Awake() {
activeRoomPrefab = Instantiate(RoomPrefabs[0]);
activeRoomPrefab.GetComponent<RoomDetails>().Doors[0].GetComponent<DoorDetails>().SetConnectedDoor(1, 1);
}
// Change room prefab
public void ChangeRoom(int connectedRoomId, int connectedDoorId) {
// remove current room prefab from scene
Destroy(activeRoomPrefab);
// spawn connectedRoom and save reference
activeRoomPrefab = Instantiate(GetRoomPrefabById(connectedRoomId));
// place player near connected door
// find position of connected door
Vector3 connectedDoorPosition = GetDoorPosition(connectedDoorId);
// determin if player should be on the left or right side of the door's location
bool spawnCharacterOnLeftOfDoor = isDoorOnRight(connectedDoorPosition);
// position player slightly off of door's location
float characterOffsetX = 2f;
if (spawnCharacterOnLeftOfDoor) {
characterOffsetX *= -1;
}
PlayerGameObject.transform.localPosition = new Vector3(connectedDoorPosition.x + characterOffsetX, connectedDoorPosition.y, 0);
}
// assumes that a valid ID is provided, if not bad things will happen
// TODO how can this be done safer, or throw an error if no room is found with the given ID?
GameObject GetRoomPrefabById(int id) {
GameObject roomPrefab = new GameObject();
// loop through all the room prefabs
foreach(GameObject room in RoomPrefabs) {
if(room.GetComponent<RoomDetails>().Id == id) {
roomPrefab = room;
}
}
return roomPrefab;
}
// assumes that a valid ID is provided, if not bad things will happen
// TODO how can this be done safer, or throw an error if no room is found with the given ID?
// TODO perhaps change roomDetail's Door array into an array of DoorDetails rather than GameObjects
Vector3 GetDoorPosition(int doorId) {
Vector3 doorPosition = Vector3.zero;
foreach(GameObject door in activeRoomPrefab.GetComponent<RoomDetails>().Doors) {
if(door.GetComponent<DoorDetails>().Id == doorId) {
doorPosition = door.transform.position;
}
}
return doorPosition;
}
bool isDoorOnRight(Vector3 doorPosition) {
if(doorPosition.x > 0) {
return true;
}
return false;
}
}
|
using UnityEngine;
using System.Collections;
public class RoomNavigationManager : MonoBehaviour {
public GameObject PlayerGameObject;
public GameObject[] RoomPrefabs;
private GameObject activeRoomPrefab;
void Awake() {
activeRoomPrefab = Instantiate(RoomPrefabs[0]);
activeRoomPrefab.GetComponent<RoomDetails>().Doors[0].GetComponent<DoorDetails>().SetConnectedDoor(1, 1);
}
// Change room prefab
public void ChangeRoom(int connectedRoomId, int connectedDoorId) {
// remove current room prefab from scene
Destroy(activeRoomPrefab);
// spawn connectedRoom and save reference
activeRoomPrefab = Instantiate(GetRoomPrefabById(connectedRoomId));
// place player near connected door
// find position of connected door
Vector3 connectedDoorPosition = GetDoorPosition(connectedDoorId);
// determin if player should be on the left or right side of the door's location
bool spawnCharacterOnLeftOfDoor = isDoorOnRight(connectedDoorPosition);
// position player slightly off of door's location
PlayerGameObject.transform.localPosition = new Vector3(connectedDoorPosition.x - 2, connectedDoorPosition.y, 0); // TODO calculate proper position using spawnCharacterOnLeft
}
// assumes that a valid ID is provided, if not bad things will happen
// TODO how can this be done safer, or throw an error if no room is found with the given ID?
GameObject GetRoomPrefabById(int id) {
GameObject roomPrefab = new GameObject();
// loop through all the room prefabs
foreach(GameObject room in RoomPrefabs) {
if(room.GetComponent<RoomDetails>().Id == id) {
roomPrefab = room;
}
}
return roomPrefab;
}
// assumes that a valid ID is provided, if not bad things will happen
// TODO how can this be done safer, or throw an error if no room is found with the given ID?
// TODO perhaps change roomDetail's Door array into an array of DoorDetails rather than GameObjects
Vector3 GetDoorPosition(int doorId) {
Vector3 doorPosition = Vector3.zero;
foreach(GameObject door in activeRoomPrefab.GetComponent<RoomDetails>().Doors) {
if(door.GetComponent<DoorDetails>().Id == doorId) {
doorPosition = door.transform.position;
}
}
return doorPosition;
}
bool isDoorOnRight(Vector3 doorPosition) {
if(doorPosition.x > 0) {
return true;
}
return false;
}
}
|
mit
|
C#
|
f823b64e04dad0ab6a2ff995185a53a8386f7c81
|
Clean up and licenses
|
SimplePersistence/SimplePersistence.Model
|
SimplePersistence.Model/src/SimplePersistence.Model/EntityWithSoftDeleteAndVersionAsLong.cs
|
SimplePersistence.Model/src/SimplePersistence.Model/EntityWithSoftDeleteAndVersionAsLong.cs
|
#region License
// The MIT License (MIT)
//
// Copyright (c) 2016 SimplePersistence
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
namespace SimplePersistence.Model
{
/// <summary>
/// Represents an entity that has an unique identifier, soft delete and version info,
/// using a long for the <see cref="IHaveVersion{T}.Version"/>.
/// </summary>
/// <typeparam name="TIdentity">The identifier type</typeparam>
public abstract class EntityWithSoftDeleteAndVersionAsLong<TIdentity>
: Entity<TIdentity>, IHaveSoftDelete, IHaveVersion<long>
{
#region Implementation of IHaveSoftDelete
/// <summary>
/// Is the entity deleted?
/// </summary>
public virtual bool Deleted { get; set; }
#endregion
#region Implementation of IHaveVersion<TVersion>
/// <summary>
/// The entity version
/// </summary>
public virtual long Version { get; set; }
#endregion
}
}
|
namespace SimplePersistence.Model
{
/// <summary>
/// Represents an entity that has an unique identifier, soft delete and version info,
/// using a long for the <see cref="IHaveVersion{T}.Version"/>.
/// </summary>
/// <typeparam name="TIdentity">The identifier type</typeparam>
public abstract class EntityWithSoftDeleteAndVersionAsLong<TIdentity>
: Entity<TIdentity>, IHaveSoftDelete, IHaveVersion<long>
{
#region Implementation of IHaveSoftDelete
/// <summary>
/// Is the entity deleted?
/// </summary>
public virtual bool Deleted { get; set; }
#endregion
#region Implementation of IHaveVersion<TVersion>
/// <summary>
/// The entity version
/// </summary>
public virtual long Version { get; set; }
#endregion
}
}
|
mit
|
C#
|
7fdbeb8c1ef4b1b0ce8c4fb397617d770896280a
|
add GetAssembly()
|
TakeAsh/cs-TakeAshUtility
|
TakeAshUtility/AssemblyHelper.cs
|
TakeAshUtility/AssemblyHelper.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace TakeAshUtility {
public static class AssemblyHelper {
public static T GetAttribute<T>(this Assembly assembly)
where T : Attribute {
if (assembly == null) {
return null;
}
return Attribute.GetCustomAttribute(assembly, typeof(T)) as T;
}
/// <summary>
/// Get Assembly that has specified name from CurrentDomain
/// </summary>
/// <param name="name">The name of Assembly</param>
/// <returns>
/// <list type="bullet">
/// <item>not null, if the Assembly is found.</item>
/// <item>null, if the Assembly is not found.</item>
/// </list>
/// </returns>
public static Assembly GetAssembly(string name) {
return String.IsNullOrEmpty(name) ?
null :
AppDomain.CurrentDomain
.GetAssemblies()
.Where(assembly => assembly.GetName().Name == name)
.FirstOrDefault();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace TakeAshUtility {
public static class AssemblyHelper {
public static T GetAttribute<T>(this Assembly assembly)
where T : Attribute {
if (assembly == null) {
return null;
}
return Attribute.GetCustomAttribute(assembly, typeof(T)) as T;
}
}
}
|
mit
|
C#
|
5a9dce8ea8f353710600058e9bf6029b9520c49b
|
Update tests
|
cube-soft/Cube.Core,cube-soft/Cube.Core
|
Tests/Operations/FileInfoTest.cs
|
Tests/Operations/FileInfoTest.cs
|
/* ------------------------------------------------------------------------- */
///
/// Copyright (c) 2010 CubeSoft, Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/* ------------------------------------------------------------------------- */
using System.IO;
using NUnit.Framework;
using Cube.FileSystem;
namespace Cube.Tests
{
/* --------------------------------------------------------------------- */
///
/// FileInfoTest
///
/// <summary>
/// FileInfo の拡張メソッドのテスト用クラスです。
/// </summary>
///
/* --------------------------------------------------------------------- */
[Parallelizable]
[TestFixture]
class FileInfoTest : FileResource
{
/* ----------------------------------------------------------------- */
///
/// GetTypeName
///
/// <summary>
/// ファイルの種類を表す文字列を取得するテストを実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase("Sample.txt")]
[TestCase("NotExist.dummy")]
public void GetTypeName(string filename)
{
var info = new FileInfo(Example(filename));
Assert.That(info.GetTypeName(), Is.Not.Null.Or.Empty);
}
}
}
|
/* ------------------------------------------------------------------------- */
///
/// Copyright (c) 2010 CubeSoft, Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/* ------------------------------------------------------------------------- */
using System.IO;
using NUnit.Framework;
using Cube.FileSystem;
namespace Cube.Tests
{
/* --------------------------------------------------------------------- */
///
/// FileInfoTest
///
/// <summary>
/// FileInfo の拡張メソッドのテスト用クラスです。
/// </summary>
///
/* --------------------------------------------------------------------- */
[Parallelizable]
[TestFixture]
class FileInfoTest : FileResource
{
/* ----------------------------------------------------------------- */
///
/// GetTypeName
///
/// <summary>
/// ファイルの種類を表す文字列を取得するテストを実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[TestCase("Sample.txt")]
public void GetTypeName(string filename)
{
var info = new FileInfo(Example(filename));
Assert.That(info.GetTypeName(), Is.Not.Null.Or.Empty);
}
}
}
|
apache-2.0
|
C#
|
a8dfcdebf9c6ec918742ce58210a622e656f628d
|
Add obsolete wrappers for compatability
|
deckar01/libsodium-net,fraga/libsodium-net,BurningEnlightenment/libsodium-net,adamcaudill/libsodium-net,deckar01/libsodium-net,bitbeans/libsodium-net,tabrath/libsodium-core,fraga/libsodium-net,BurningEnlightenment/libsodium-net,adamcaudill/libsodium-net,bitbeans/libsodium-net
|
libsodium-net/SodiumCore.cs
|
libsodium-net/SodiumCore.cs
|
using System;
using System.Runtime.InteropServices;
namespace Sodium
{
/// <summary>
/// libsodium core information.
/// </summary>
public static class SodiumCore
{
static SodiumCore()
{
SodiumLibrary.init();
}
/// <summary>Gets random bytes</summary>
/// <param name="count">The count of bytes to return.</param>
/// <returns>An array of random bytes.</returns>
public static byte[] GetRandomBytes(int count)
{
var buffer = new byte[count];
SodiumLibrary.randombytes_buff(buffer, count);
return buffer;
}
/// <summary>
/// Returns the version of libsodium in use.
/// </summary>
/// <returns>
/// The sodium version string.
/// </returns>
public static string SodiumVersionString()
{
var ptr = SodiumLibrary.sodium_version_string();
return Marshal.PtrToStringAnsi(ptr);
}
[Obsolete("Use SodiumLibrary.is64")]
internal static bool Is64
{
get
{
return SodiumLibrary.is64;
}
}
[Obsolete("Use SodiumLibrary.isRunningOnMono")]
internal static bool IsRunningOnMono()
{
return SodiumLibrary.isRunningOnMono;
}
[Obsolete("Use SodiumLibrary.name")]
internal static string LibraryName()
{
return SodiumLibrary.name;
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace Sodium
{
/// <summary>
/// libsodium core information.
/// </summary>
public static class SodiumCore
{
static SodiumCore()
{
SodiumLibrary.init();
}
/// <summary>Gets random bytes</summary>
/// <param name="count">The count of bytes to return.</param>
/// <returns>An array of random bytes.</returns>
public static byte[] GetRandomBytes(int count)
{
var buffer = new byte[count];
SodiumLibrary.randombytes_buff(buffer, count);
return buffer;
}
/// <summary>
/// Returns the version of libsodium in use.
/// </summary>
/// <returns>
/// The sodium version string.
/// </returns>
public static string SodiumVersionString()
{
var ptr = SodiumLibrary.sodium_version_string();
return Marshal.PtrToStringAnsi(ptr);
}
}
}
|
mit
|
C#
|
924e2fbdbb410bc3d586ec8a03e9995022bf0711
|
Use component
|
CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction
|
CollAction/Views/Donation/Donate.cshtml
|
CollAction/Views/Donation/Donate.cshtml
|
@using Stripe
@using Microsoft.Extensions.Options
@inject IOptions<RequestOptions> StripeOptions
@{
ViewData["Title"] = "Donate";
}
<div id="donation-box" />
|
@using Stripe
@using Microsoft.Extensions.Options
@inject IOptions<RequestOptions> StripeOptions
@{
ViewData["Title"] = "Donate";
}
<h1>Donate</h1>
<form action="your-server-side-code" method="POST">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="@StripeOptions.Value.ApiKey"
data-name="CollAction Donation"
data-label="Donate"
data-description="Widget"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto"
data-zip-code="true">
</script>
</form>
|
agpl-3.0
|
C#
|
0afa3fa423f2e5994bd08037df548905e3488e14
|
Make LocalizationManager use English by default
|
NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,uulltt/NitoriWare,plrusek/NitoriWare
|
Assets/Scripts/Localization/LocalizationManager.cs
|
Assets/Scripts/Localization/LocalizationManager.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class LocalizationManager : MonoBehaviour
{
private const string NotFoundString = "LOCALIZED TEXT NOT FOUND";
public static LocalizationManager instance;
[SerializeField]
private string forceLanguage;
private string language;
private Dictionary<string, string> localizedText;
void Awake ()
{
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
else
instance = this;
if (transform.parent == null)
DontDestroyOnLoad(gameObject);
language = (forceLanguage == "" ? Application.systemLanguage.ToString() : forceLanguage);
loadLocalizedText("Languages/" + language + ".json");
}
public void loadLocalizedText(string filename)
{
localizedText = new Dictionary<string, string>();
string filePath = Path.Combine(Application.streamingAssetsPath, filename);
if (!File.Exists(filePath))
{
filePath = filePath.Replace(language, "English");
Debug.Log("Language " + language + " not found. Using English");
}
if (File.Exists(filePath))
{
string jsonString = File.ReadAllText(filePath);
LocalizationData loadedData = JsonUtility.FromJson<LocalizationData>(jsonString);
for (int i = 0; i < loadedData.items.Length; i++)
{
localizedText.Add(loadedData.items[i].key, loadedData.items[i].value);
}
}
else
Debug.LogError("No English json found!");
}
public string getLanguage()
{
return language;
}
public void setLanguage(string language)
{
//TODO make loading async and revisit this
}
public string getLocalizedValue(string key)
{
return (localizedText == null) ? "No language set" : getLocalizedValue(key, NotFoundString);
}
public string getLocalizedValue(string key, string defaultString)
{
if (localizedText == null)
return defaultString;
if (!localizedText.ContainsKey(key))
{
Debug.LogWarning("Language " + getLanguage() + " does not have a value for key " + key);
return defaultString;
}
return localizedText[key];
}
public string getLocalizedValueNoWarnings(string key, string defaultString)
{
return (localizedText == null) ? defaultString : (localizedText.ContainsKey(key) ? localizedText[key] : defaultString);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class LocalizationManager : MonoBehaviour
{
private const string NotFoundString = "LOCALIZED TEXT NOT FOUND";
public static LocalizationManager instance;
[SerializeField]
private string forceLanguage;
private string language;
private Dictionary<string, string> localizedText;
void Awake ()
{
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
else
instance = this;
if (transform.parent == null)
DontDestroyOnLoad(gameObject);
language = (forceLanguage == "" ? Application.systemLanguage.ToString() : forceLanguage);
loadLocalizedText("Languages/" + language + ".json");
}
public void loadLocalizedText(string filename)
{
localizedText = new Dictionary<string, string>();
string filePath = Path.Combine(Application.streamingAssetsPath, filename);
if (File.Exists(filePath))
{
string jsonString = File.ReadAllText(filePath);
LocalizationData loadedData = JsonUtility.FromJson<LocalizationData>(jsonString);
for (int i = 0; i < loadedData.items.Length; i++)
{
localizedText.Add(loadedData.items[i].key, loadedData.items[i].value);
}
}
else
Debug.LogError("Cannot find language" + filename + " in StreamingAssets/Languages/");
}
public string getLanguage()
{
return language;
}
public void setLanguage(string language)
{
//TODO make loading async and revisit this
}
public string getLocalizedValue(string key)
{
return (localizedText == null) ? "No language set" : getLocalizedValue(key, NotFoundString);
}
public string getLocalizedValue(string key, string defaultString)
{
if (localizedText == null)
return defaultString;
if (!localizedText.ContainsKey(key))
{
Debug.LogWarning("Language " + getLanguage() + " does not have a value for key " + key);
return defaultString;
}
return localizedText[key];
}
public string getLocalizedValueNoWarnings(string key, string defaultString)
{
return (localizedText == null) ? defaultString : (localizedText.ContainsKey(key) ? localizedText[key] : defaultString);
}
}
|
mit
|
C#
|
41e1b35006858deee994a553ca65bbc90148a494
|
Add code to leave triggerboxes
|
stacy89/Authentic-Realities,stacy89/Authentic-Realities,stacy89/Authentic-Realities
|
Assets/scipts/MainPlayerController.cs
|
Assets/scipts/MainPlayerController.cs
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class MainPlayerController : MonoBehaviour {
public float speed;
public GameObject cube1;
public GameObject cube2;
public GameObject cube3;
public GameObject cube4;
public GameObject cube5;
public GameObject cube6;
private Rigidbody rb;
private int count;
public GameManager gameManager;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("Starting Stats"))
{
cube1.SetActive (true);
}
if (other.gameObject.CompareTag ("Marriage"))
{
cube2.SetActive (true);
}
if (other.gameObject.CompareTag ("Housing"))
{
cube3.SetActive (true);
}
if (other.gameObject.CompareTag ("Vacation"))
{
cube4.SetActive (true);
}
if (other.gameObject.CompareTag ("Retirement Party"))
{
cube5.SetActive (true);
}
if (other.gameObject.CompareTag ("Retirement"))
{
cube6.SetActive (true);
}
// if (other.gameObject.CompareTag (""))
// {
// gameManager.GameOver ();
// Debug.Log ("hey");
// //gameManager.GameOver();
// }
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag ("Starting Stats")) {
cube1.SetActive (false);
}
if (other.gameObject.CompareTag ("Marriage")) {
cube2.SetActive (false);
}
if (other.gameObject.CompareTag ("Housing")) {
cube3.SetActive (false);
}
if (other.gameObject.CompareTag ("Vacation")) {
cube4.SetActive (false);
}
if (other.gameObject.CompareTag ("Retirement Party")) {
cube5.SetActive (false);
}
if (other.gameObject.CompareTag ("Retirement")) {
cube6.SetActive (false);
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class MainPlayerController : MonoBehaviour {
public float speed;
public GameObject cube1;
public GameObject cube2;
public GameObject cube3;
public GameObject cube4;
public GameObject cube5;
public GameObject cube6;
private Rigidbody rb;
private int count;
public GameManager gameManager;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("Starting Stats"))
{
cube1.SetActive (true);
}
if (other.gameObject.CompareTag ("Marriage"))
{
cube2.SetActive (true);
}
if (other.gameObject.CompareTag ("Housing"))
{
cube3.SetActive (true);
}
if (other.gameObject.CompareTag ("Vacation"))
{
cube4.SetActive (true);
}
if (other.gameObject.CompareTag ("Retirement Party"))
{
cube5.SetActive (true);
}
if (other.gameObject.CompareTag ("Retirement"))
{
cube6.SetActive (true);
}
// if (other.gameObject.CompareTag (""))
// {
// gameManager.GameOver ();
// Debug.Log ("hey");
// //gameManager.GameOver();
// }
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag ("Starting Stats")) {
cube2.SetActive (false);
}
}
}
|
mit
|
C#
|
6b4e684ca81fc00eae79a1f8f47f5e867c1d89c2
|
Add virtual keyword to TryGetProps()
|
ForsakenShell/CommunityCoreLibrary,RimWorldCCLTeam/CommunityCoreLibrary,isistoy/CommunityCoreLibrary
|
DLL_Project/Verbs/Verb_ShootExtended.cs
|
DLL_Project/Verbs/Verb_ShootExtended.cs
|
using RimWorld;
using Verse;
namespace CommunityCoreLibrary
{
public class Verb_ShootExtended : Verb_LaunchProjectile
{
private int pelletCount;
private float expMin;
private float expMid;
private float expMax;
private bool gotProps;
protected override int ShotsPerBurst => verbProps.burstShotCount;
// XML data into verb
protected virtual void TryGetProps()
{
if (gotProps)
//Already done, pass
return;
var props = verbProps as VerbProperties_Extended;
if (props == null)
{
CCL_Log.Error("Extended properties not found!", "Verb_ShootExtended");
pelletCount = 1;
expMin = 10;
expMid = 50;
expMax = 20;
}
else
{
pelletCount = props.pelletCount;
expMin = props.experienceGain.min;
expMid = props.experienceGain.mid;
expMax = props.experienceGain.max;
}
gotProps = true;
}
public override void WarmupComplete()
{
TryGetProps();
base.WarmupComplete();
if (!CasterIsPawn || CasterPawn.skills == null)
return;
var xp = expMin;
if (currentTarget.Thing != null && currentTarget.Thing.def.category == ThingCategory.Pawn)
{
xp = currentTarget.Thing.HostileTo(caster) ? expMax : expMid;
}
CasterPawn.skills.Learn(SkillDefOf.Shooting, xp);
}
protected override bool TryCastShot()
{
if (!base.TryCastShot()) return false;
var i = 1;
while (i < pelletCount && base.TryCastShot())
{
i++;
}
MoteThrower.ThrowStatic(caster.Position, ThingDefOf.Mote_ShotFlash, 9f);
return true;
}
}
}
|
using RimWorld;
using Verse;
namespace CommunityCoreLibrary
{
public class Verb_ShootExtended : Verb_LaunchProjectile
{
private int pelletCount;
private float expMin;
private float expMid;
private float expMax;
private bool gotProps;
protected override int ShotsPerBurst => verbProps.burstShotCount;
// XML data into verb
protected void TryGetProps()
{
if (gotProps)
//Already done, pass
return;
var props = verbProps as VerbProperties_Extended;
if (props == null)
{
CCL_Log.Error("Extended properties not found!", "Verb_ShootExtended");
pelletCount = 1;
expMin = 10;
expMid = 50;
expMax = 20;
}
else
{
pelletCount = props.pelletCount;
expMin = props.experienceGain.min;
expMid = props.experienceGain.mid;
expMax = props.experienceGain.max;
}
gotProps = true;
}
public override void WarmupComplete()
{
TryGetProps();
base.WarmupComplete();
if (!CasterIsPawn || CasterPawn.skills == null)
return;
var xp = expMin;
if (currentTarget.Thing != null && currentTarget.Thing.def.category == ThingCategory.Pawn)
{
xp = currentTarget.Thing.HostileTo(caster) ? expMax : expMid;
}
CasterPawn.skills.Learn(SkillDefOf.Shooting, xp);
}
protected override bool TryCastShot()
{
if (!base.TryCastShot()) return false;
var i = 1;
while (i < pelletCount && base.TryCastShot())
{
i++;
}
MoteThrower.ThrowStatic(caster.Position, ThingDefOf.Mote_ShotFlash, 9f);
return true;
}
}
}
|
unlicense
|
C#
|
748a4748d44b501e87f406c2c5d2f2bf05a9eb78
|
Fix memory leak
|
Quickshot/DupImageLib,Quickshot/DupImage
|
DupImageLib/ImageMagickTransformer.cs
|
DupImageLib/ImageMagickTransformer.cs
|
using System.IO;
using ImageMagick;
namespace DupImageLib
{
/// <summary>
/// Implements IImageTransformer interface using Magick.NET for image transforms.
/// </summary>
public class ImageMagickTransformer : IImageTransformer
{
public byte[] TransformImage(Stream stream, int width, int height)
{
// Read image
var img = new MagickImage(stream);
var settings = new QuantizeSettings
{
ColorSpace = ColorSpace.Gray,
Colors = 256
};
img.Quantize(settings);
var size = new MagickGeometry(width, height) { IgnoreAspectRatio = true };
img.Resize(size);
img.Format = MagickFormat.Gray;
return img.ToByteArray();
}
}
}
|
using System.IO;
using ImageMagick;
namespace DupImageLib
{
/// <summary>
/// Implements IImageTransformer interface using Magick.NET for image transforms.
/// </summary>
public class ImageMagickTransformer : IImageTransformer
{
public byte[] TransformImage(Stream stream, int width, int height)
{
// Read image
var img = new MagickImage(stream);
var settings = new QuantizeSettings
{
ColorSpace = ColorSpace.Gray,
Colors = 256
};
img.Quantize(settings);
var size = new MagickGeometry(width, height) { IgnoreAspectRatio = true };
img.Resize(size);
var imgPixels = img.GetPixels().GetValues();
return imgPixels;
}
}
}
|
unknown
|
C#
|
4882556659cb85ce12b62c204e576e2b51c99223
|
Set version.
|
Talagozis/EvolutionaryComputation
|
EvolutionaryComputation/Properties/AssemblyInfo.cs
|
EvolutionaryComputation/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("EvolutionaryComputation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Talagozis")]
[assembly: AssemblyProduct("EvolutionaryComputation")]
[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.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.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("EvolutionaryComputation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Talagozis")]
[assembly: AssemblyProduct("EvolutionaryComputation")]
[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.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
apache-2.0
|
C#
|
51e609edb1bd3b80620b2502325c022ef3093b33
|
Modify IBiggyStore to include all CRUD methods, remove IUpdateableBiggyStore #103
|
jjchiw/biggy,xivSolutions/biggy,garethbrown/biggy,jjchiw/biggy,garethbrown/biggy,jjchiw/biggy,garethbrown/biggy
|
Biggy/IBiggyStore.cs
|
Biggy/IBiggyStore.cs
|
using System.Collections.Generic;
using System.Linq;
namespace Biggy
{
public interface IBiggyStore<T> {
List<T> Load();
void SaveAll(List<T> items);
void Clear();
T Add(T item);
List<T> Add(List<T> items);
T Update(T item);
T Remove(T item);
List<T> Remove(List<T> items);
}
public interface IQueryableBiggyStore<T> : IBiggyStore<T> {
IQueryable<T> AsQueryable();
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Biggy
{
public interface IBiggyStore<T>
{
List<T> Load();
void SaveAll(List<T> items);
void Clear();
T Add(T item);
List<T> Add(List<T> items);
}
public interface IUpdateableBiggyStore<T> : IBiggyStore<T>
{
T Update(T item);
T Remove(T item);
List<T> Remove(List<T> items);
}
public interface IQueryableBiggyStore<T> : IBiggyStore<T>
{
IQueryable<T> AsQueryable();
}
}
|
bsd-3-clause
|
C#
|
63849684692d62211120b7577826a1d26cda6e04
|
Fix Necronomicon not turning the correct number of pages when cycling
|
samfun123/KtaneTwitchPlays
|
TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/NecronomiconComponentSolver.cs
|
TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/NecronomiconComponentSolver.cs
|
using System;
using System.Collections;
using UnityEngine;
public class NecronomiconComponentSolver : ComponentSolver
{
public NecronomiconComponentSolver(TwitchModule module) :
base(module)
{
_component = Module.BombComponent.GetComponent(ComponentType);
selectables = Module.BombComponent.GetComponent<KMSelectable>().Children;
ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Cycle all the pages using !{0} cycle. Submit a specific page using !{0} page 3.");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
inputCommand = inputCommand.ToLowerInvariant().Trim();
string[] split = inputCommand.Split(new[] { ' ', ',', ';' }, System.StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 1 && split[0].EqualsAny("cycle", "c", "pages"))
{
yield return null;
yield return DoInteractionClick(selectables[0]);
int pagesTurned = 0;
for (int i = 0; i < 8; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return new WaitForSecondsWithCancel(2.25f, false, this);
if (CoroutineCanceller.ShouldCancel)
break;
pagesTurned = i;
yield return DoInteractionClick(selectables[1]);
}
if (CoroutineCanceller.ShouldCancel)
{
for (int i = pagesTurned; i < 8; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return DoInteractionClick(selectables[1]);
}
}
}
else if (split.Length == 2 && split[0].EqualsAny("page", "p") && int.TryParse(split[1], out int pageNumber) && pageNumber.InRange(1, 8))
{
yield return null;
yield return DoInteractionClick(selectables[0]);
int pagesTurned = 0;
for (int i = 1; i < pageNumber; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
if (CoroutineCanceller.ShouldCancel)
break;
pagesTurned = i;
yield return DoInteractionClick(selectables[1]);
}
if (CoroutineCanceller.ShouldCancel)
{
for (int i = pagesTurned; i < 7; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return DoInteractionClick(selectables[1]);
}
}
yield return "solve";
yield return "strike";
}
}
protected override IEnumerator ForcedSolveIEnumerator()
{
yield return null;
yield return RespondToCommandInternal("page " + _component.GetValue<int>("correctPage"));
}
static NecronomiconComponentSolver()
{
ComponentType = ReflectionHelper.FindType("necronomiconScript");
}
private static readonly Type ComponentType;
private readonly object _component;
private readonly KMSelectable[] selectables;
}
|
using System;
using System.Collections;
using UnityEngine;
public class NecronomiconComponentSolver : ComponentSolver
{
public NecronomiconComponentSolver(TwitchModule module) :
base(module)
{
_component = Module.BombComponent.GetComponent(ComponentType);
selectables = Module.BombComponent.GetComponent<KMSelectable>().Children;
ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Cycle all the pages using !{0} cycle. Submit a specific page using !{0} page 3.");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
inputCommand = inputCommand.ToLowerInvariant().Trim();
string[] split = inputCommand.Split(new[] { ' ', ',', ';' }, System.StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 1 && split[0].EqualsAny("cycle", "c", "pages"))
{
yield return null;
yield return DoInteractionClick(selectables[0]);
int pagesTurned = 0;
for (int i = 0; i < 7; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return new WaitForSecondsWithCancel(2.25f, false, this);
if (CoroutineCanceller.ShouldCancel)
break;
pagesTurned = i;
yield return DoInteractionClick(selectables[1]);
}
for (int i = pagesTurned; i < 7; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return DoInteractionClick(selectables[1]);
}
}
else if (split.Length == 2 && split[0].EqualsAny("page", "p") && int.TryParse(split[1], out int pageNumber) && pageNumber.InRange(1, 8))
{
yield return null;
yield return DoInteractionClick(selectables[0]);
int pagesTurned = 0;
for (int i = 1; i < pageNumber; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
if (CoroutineCanceller.ShouldCancel)
break;
pagesTurned = i;
yield return DoInteractionClick(selectables[1]);
}
if (CoroutineCanceller.ShouldCancel)
{
for (int i = pagesTurned; i < 7; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return DoInteractionClick(selectables[1]);
}
}
yield return "solve";
yield return "strike";
}
}
protected override IEnumerator ForcedSolveIEnumerator()
{
yield return null;
yield return RespondToCommandInternal("page " + _component.GetValue<int>("correctPage"));
}
static NecronomiconComponentSolver()
{
ComponentType = ReflectionHelper.FindType("necronomiconScript");
}
private static readonly Type ComponentType;
private readonly object _component;
private readonly KMSelectable[] selectables;
}
|
mit
|
C#
|
d5078bc5e3a14a311dbc4f9369153cb669190c19
|
Attach SetEditorOnly function to GameObjects rather than MonoBehaviors
|
YesAndGames/YesAndEngine
|
Editor/YesAndEditor/YesAndEditorUtil.cs
|
Editor/YesAndEditor/YesAndEditorUtil.cs
|
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.Linq;
namespace YesAndEditor {
// Static class packed to the brim with helpful Unity editor utilities.
public static class YesAndEditorUtil {
// Forcefully mark open loaded scenes dirty and save them.
[MenuItem ("File/Force Save")]
public static void ForceSaveOpenScenes () {
EditorSceneManager.MarkAllScenesDirty ();
EditorSceneManager.SaveOpenScenes ();
}
// Mark an object editor-only.
public static void SetEditorOnly(this GameObject obj, bool editorOnly = true) {
if (editorOnly) {
obj.gameObject.hideFlags ^= HideFlags.NotEditable;
obj.gameObject.hideFlags ^= HideFlags.HideAndDontSave;
}
else {
obj.gameObject.hideFlags &= HideFlags.NotEditable;
obj.gameObject.hideFlags &= HideFlags.HideAndDontSave;
}
}
}
}
|
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.Linq;
namespace YesAndEditor {
// Static class packed to the brim with helpful Unity editor utilities.
public static class YesAndEditorUtil {
// Forcefully mark open loaded scenes dirty and save them.
[MenuItem ("File/Force Save")]
public static void ForceSaveOpenScenes () {
EditorSceneManager.MarkAllScenesDirty ();
EditorSceneManager.SaveOpenScenes ();
}
// Mark an object editor-only.
public static void SetEditorOnly(this MonoBehaviour obj, bool editorOnly = true) {
if (editorOnly) {
obj.gameObject.hideFlags ^= HideFlags.NotEditable;
obj.gameObject.hideFlags ^= HideFlags.HideAndDontSave;
}
else {
obj.gameObject.hideFlags &= HideFlags.NotEditable;
obj.gameObject.hideFlags &= HideFlags.HideAndDontSave;
}
}
}
}
|
apache-2.0
|
C#
|
23729245f76e9b35bfa6d821568262ab718430c0
|
make sure events aren't null
|
JaredGG/GameWork
|
GameWork.Core.States/Event/EventStateTransition.cs
|
GameWork.Core.States/Event/EventStateTransition.cs
|
using System;
namespace GameWork.Core.States.Event
{
public abstract class EventStateTransition
{
internal event Action<string> EnterStateEvent;
internal event Action<string> ExitStateEvent;
protected virtual void OnEnter(string fromStateName)
{
}
protected virtual void OnExit(string toStateName)
{
}
protected virtual void EnterState(string toStateName)
{
EnterStateEvent?.Invoke(toStateName);
}
protected virtual void ExitState(string toStateName)
{
ExitStateEvent?.Invoke(toStateName);
}
internal virtual void Enter(string fromStateName)
{
OnEnter(fromStateName);
}
internal virtual void Exit(string toStateName)
{
OnExit(toStateName);
}
}
}
|
using System;
namespace GameWork.Core.States.Event
{
public abstract class EventStateTransition
{
internal event Action<string> EnterStateEvent;
internal event Action<string> ExitStateEvent;
protected virtual void OnEnter(string fromStateName)
{
}
protected virtual void OnExit(string toStateName)
{
}
protected virtual void EnterState(string toStateName)
{
EnterStateEvent(toStateName);
}
protected virtual void ExitState(string toStateName)
{
ExitStateEvent(toStateName);
}
internal virtual void Enter(string fromStateName)
{
OnEnter(fromStateName);
}
internal virtual void Exit(string toStateName)
{
OnExit(toStateName);
}
}
}
|
mit
|
C#
|
caadf5a0055a5a93af6706cf302abb6be01ff263
|
Add FileNameType.InstanceAllowStartWithDots, which allows file names starting with the dot character.
|
PenguinF/sandra-three
|
Eutherion/Win/Storage/FileNameType.cs
|
Eutherion/Win/Storage/FileNameType.cs
|
#region License
/*********************************************************************************
* FileNameType.cs
*
* Copyright (c) 2004-2019 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
#endregion
using Eutherion.Localization;
using System.IO;
namespace Eutherion.Win.Storage
{
/// <summary>
/// Specialized PType that only accepts strings that are legal file names.
/// </summary>
public sealed class FileNameType : PType.Filter<string>
{
public static readonly PTypeErrorBuilder FileNameTypeError
= new PTypeErrorBuilder(new LocalizedStringKey(nameof(FileNameTypeError)));
public static readonly FileNameType Instance = new FileNameType(allowStartWithDots: false);
/// <summary>
/// <see cref="FileNameType"/> instance that allows file names starting with dots.
/// Dangerous to use in settings files, better only use for <see cref="SettingsAutoSave"/>.
/// </summary>
public static readonly FileNameType InstanceAllowStartWithDots = new FileNameType(allowStartWithDots: true);
private readonly bool allowStartWithDots;
private FileNameType(bool allowStartWithDots) : base(PType.CLR.String) => this.allowStartWithDots = allowStartWithDots;
public override bool IsValid(string fileName, out ITypeErrorBuilder typeError)
=> !string.IsNullOrEmpty(fileName)
&& (allowStartWithDots || !fileName.StartsWith("."))
&& fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0
? ValidValue(out typeError)
: InvalidValue(FileNameTypeError, out typeError);
}
}
|
#region License
/*********************************************************************************
* FileNameType.cs
*
* Copyright (c) 2004-2019 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
#endregion
using Eutherion.Localization;
using System.IO;
namespace Eutherion.Win.Storage
{
/// <summary>
/// Specialized PType that only accepts strings that are legal file names.
/// </summary>
public sealed class FileNameType : PType.Filter<string>
{
public static readonly PTypeErrorBuilder FileNameTypeError
= new PTypeErrorBuilder(new LocalizedStringKey(nameof(FileNameTypeError)));
public static readonly FileNameType Instance = new FileNameType();
private FileNameType() : base(PType.CLR.String) { }
public override bool IsValid(string fileName, out ITypeErrorBuilder typeError)
=> !string.IsNullOrEmpty(fileName)
&& !fileName.StartsWith(".")
&& fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0
? ValidValue(out typeError)
: InvalidValue(FileNameTypeError, out typeError);
}
}
|
apache-2.0
|
C#
|
a34455eb9289fb950db75874f44996db933ba17d
|
Update cli command start
|
WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework
|
Framework.Cli/Command/CommandStart.cs
|
Framework.Cli/Command/CommandStart.cs
|
namespace Framework.Cli.Command
{
using Framework.Cli.Config;
using Microsoft.Extensions.CommandLineUtils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
/// <summary>
/// Cli start command.
/// </summary>
internal class CommandStart : CommandBase
{
public CommandStart(AppCli appCli)
: base(appCli, "start", "Start server and open client in browser")
{
}
protected internal override void Execute()
{
ConfigCli configCli = ConfigCli.Load();
if (configCli.EnvironmentNameGet() != "DEV")
{
if (UtilCliInternal.ConsoleReadYesNo(string.Format("Start with {0} database?", configCli.EnvironmentName)) == false)
{
return;
}
}
UtilFramework.NodeClose();
string folderName = UtilFramework.FolderName + @"Application.Server/";
// Version tag and build only .NET Core server.
UtilCliInternal.VersionBuild(() =>
{
UtilCliInternal.DotNet(folderName, "build");
});
UtilCliInternal.DotNet(folderName, "run --no-build", false);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
UtilCliInternal.OpenWebBrowser("http://localhost:5000/"); // For port setting see also: Application.Server\Properties\launchSettings.json (applicationUrl, sslPort)
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// Ubuntu list all running processes: 'ps'
// To reboot Ubuntu type on Windows command prompt: 'wsl -t Ubuntu-18.04'
// Ubuntu show processes tool: 'htop'
UtilCliInternal.ConsoleWriteLineColor("Info: Stop server with command 'killall -g -SIGKILL Application.Server'", ConsoleColor.Cyan); // Info
}
}
}
}
|
namespace Framework.Cli.Command
{
using Framework.Cli.Config;
using Microsoft.Extensions.CommandLineUtils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
/// <summary>
/// Cli start command.
/// </summary>
internal class CommandStart : CommandBase
{
public CommandStart(AppCli appCli)
: base(appCli, "start", "Start server and open client in browser")
{
}
protected internal override void Execute()
{
// Build angular client
//var commandBuild = new CommandBuild(AppCli);
//UtilCli.OptionSet(ref commandBuild.OptionClientOnly, true);
//commandBuild.Execute();
UtilFramework.NodeClose();
string folderName = UtilFramework.FolderName + @"Application.Server/";
// Version tag and build only .NET Core server.
UtilCliInternal.VersionBuild(() =>
{
UtilCliInternal.DotNet(folderName, "build");
});
UtilCliInternal.DotNet(folderName, "run --no-build", false);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
UtilCliInternal.OpenWebBrowser("http://localhost:5000/"); // For port setting see also: Application.Server\Properties\launchSettings.json (applicationUrl, sslPort)
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// Ubuntu list all running processes: 'ps'
// To reboot Ubuntu type on Windows command prompt: 'wsl -t Ubuntu-18.04'
// Ubuntu show processes tool: 'htop'
UtilCliInternal.ConsoleWriteLineColor("Info: Stop server with command 'killall -g -SIGKILL Application.Server'", ConsoleColor.Cyan); // Info
}
}
}
}
|
mit
|
C#
|
7989dc49b6c40c5164a16acbedb23b477c6d1046
|
Create node_modules/@types after project creation
|
paulvanbrenk/nodejstools,kant2002/nodejstools,kant2002/nodejstools,lukedgr/nodejstools,kant2002/nodejstools,paulvanbrenk/nodejstools,Microsoft/nodejstools,lukedgr/nodejstools,paulvanbrenk/nodejstools,Microsoft/nodejstools,kant2002/nodejstools,paulvanbrenk/nodejstools,kant2002/nodejstools,paulvanbrenk/nodejstools,Microsoft/nodejstools,Microsoft/nodejstools,lukedgr/nodejstools,lukedgr/nodejstools,lukedgr/nodejstools,Microsoft/nodejstools
|
Nodejs/Product/ProjectWizard/NpmWizardExtension.cs
|
Nodejs/Product/ProjectWizard/NpmWizardExtension.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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TemplateWizard;
namespace Microsoft.NodejsTools.ProjectWizard
{
/// <summary>
/// Provides a project wizard extension which will optionally do an
/// npm install after the project is created.
/// </summary>
public sealed class NpmWizardExtension : IWizard
{
#region IWizard Members
public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
{
}
public void ProjectFinishedGenerating(EnvDTE.Project project)
{
Debug.Assert(project != null && project.Object != null);
Debug.Assert(project.Object is INodePackageModulesCommands);
// Create the "node_modules/@types" folder before opening any files (which creates the
// context for the project). This allows tsserver to start watching for type definitions
// before any are installed (which is needed as "npm install" runs async, so the modules
// usually aren't installed before the project context is loaded).
var fullname = project.FullName;
var projectFolder = Path.GetDirectoryName(fullname);
Directory.CreateDirectory(Path.Combine(projectFolder, @"node_modules\@types"));
((INodePackageModulesCommands)project.Object).InstallMissingModulesAsync();
}
public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
{
}
public void RunFinished()
{
}
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
}
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
#endregion
}
}
|
// 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.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.TemplateWizard;
namespace Microsoft.NodejsTools.ProjectWizard
{
/// <summary>
/// Provides a project wizard extension which will optionally do an
/// npm install after the project is created.
/// </summary>
public sealed class NpmWizardExtension : IWizard
{
#region IWizard Members
public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
{
}
public void ProjectFinishedGenerating(EnvDTE.Project project)
{
Debug.Assert(project != null && project.Object != null);
Debug.Assert(project.Object is INodePackageModulesCommands);
((INodePackageModulesCommands)project.Object).InstallMissingModulesAsync();
}
public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
{
}
public void RunFinished()
{
}
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
}
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
#endregion
}
}
|
apache-2.0
|
C#
|
4de71072386269d48813d508c085d305bbb79d32
|
Update url
|
Franklin89/Blog,Franklin89/Blog
|
build.cake
|
build.cake
|
// The following environment variables need to be set for Publish target:
// NETLIFY_TOKEN
#tool "nuget:https://api.nuget.org/v3/index.json?package=Wyam&version=2.0.0"
#addin "nuget:https://api.nuget.org/v3/index.json?package=Cake.Wyam&version=2.0.0"
#addin "NetlifySharp"
using NetlifySharp;
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
Task("Build")
.Does(() =>
{
Wyam(new WyamSettings
{
Recipe = "Blog",
Theme = "CleanBlog",
UpdatePackages = true
});
});
Task("Preview")
.Does(() =>
{
Wyam(new WyamSettings
{
Recipe = "Blog",
Theme = "CleanBlog",
UpdatePackages = true,
Preview = true,
Watch = true
});
});
Task("Netlify")
.Does(() =>
{
var netlifyToken = EnvironmentVariable("NETLIFY_TOKEN");
if(string.IsNullOrEmpty(netlifyToken))
{
throw new Exception("Could not get Netlify token environment variable");
}
Information("Deploying output to Netlify");
var client = new NetlifyClient(netlifyToken);
client.UpdateSite($"matteo.netlify.com", MakeAbsolute(Directory("./output")).FullPath).SendAsync().Wait();
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Preview");
Task("BuildServer")
.IsDependentOn("Build")
.IsDependentOn("Netlify");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
// The following environment variables need to be set for Publish target:
// NETLIFY_TOKEN
#tool "nuget:https://api.nuget.org/v3/index.json?package=Wyam&version=2.0.0"
#addin "nuget:https://api.nuget.org/v3/index.json?package=Cake.Wyam&version=2.0.0"
#addin "NetlifySharp"
using NetlifySharp;
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
Task("Build")
.Does(() =>
{
Wyam(new WyamSettings
{
Recipe = "Blog",
Theme = "CleanBlog",
UpdatePackages = true
});
});
Task("Preview")
.Does(() =>
{
Wyam(new WyamSettings
{
Recipe = "Blog",
Theme = "CleanBlog",
UpdatePackages = true,
Preview = true,
Watch = true
});
});
Task("Netlify")
.Does(() =>
{
var netlifyToken = EnvironmentVariable("NETLIFY_TOKEN");
if(string.IsNullOrEmpty(netlifyToken))
{
throw new Exception("Could not get Netlify token environment variable");
}
Information("Deploying output to Netlify");
var client = new NetlifyClient(netlifyToken);
client.UpdateSite($"priceless-elion-c49c9c.netlify.com", MakeAbsolute(Directory("./output")).FullPath).SendAsync().Wait();
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Preview");
Task("BuildServer")
.IsDependentOn("Build")
.IsDependentOn("Netlify");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
mit
|
C#
|
133c01c171e531f674bb356440329ddd9331f1b8
|
Add empty constructor for GenericPosition
|
Visagalis/Oxide,Visagalis/Oxide,LaserHydra/Oxide,LaserHydra/Oxide
|
Oxide.Core/Libraries/Covalence/IPlayerCharacter.cs
|
Oxide.Core/Libraries/Covalence/IPlayerCharacter.cs
|
namespace Oxide.Core.Libraries.Covalence
{
/// <summary>
/// Represents a position of a point in 3D space
/// </summary>
public class GenericPosition
{
public readonly float X, Y, Z;
public GenericPosition()
{
}
public GenericPosition(float x, float y, float z)
{
X = x; Y = y; Z = z;
}
public override string ToString() => $"({X}, {Y}, {Z})";
}
/// <summary>
/// Represents a generic character controlled by a player
/// </summary>
public interface IPlayerCharacter
{
/// <summary>
/// Gets the owner of this character
/// </summary>
ILivePlayer Owner { get; }
/// <summary>
/// Gets the object that backs this character, if available
/// </summary>
object Object { get; }
/// <summary>
/// Gets the position of this character
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
void Position(out float x, out float y, out float z);
/// <summary>
/// Gets the position of this character
/// </summary>
/// <returns></returns>
GenericPosition Position();
#region Manipulation
/// <summary>
/// Causes this character to die
/// </summary>
void Kill();
/// <summary>
/// Teleports this character to the specified position
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
void Teleport(float x, float y, float z);
#endregion
}
}
|
namespace Oxide.Core.Libraries.Covalence
{
/// <summary>
/// Represents a position of a point in 3D space
/// </summary>
public struct GenericPosition
{
public readonly float X, Y, Z;
public GenericPosition(float x, float y, float z)
{
X = x; Y = y; Z = z;
}
public override string ToString() => $"({X}, {Y}, {Z})";
}
/// <summary>
/// Represents a generic character controlled by a player
/// </summary>
public interface IPlayerCharacter
{
/// <summary>
/// Gets the owner of this character
/// </summary>
ILivePlayer Owner { get; }
/// <summary>
/// Gets the object that backs this character, if available
/// </summary>
object Object { get; }
/// <summary>
/// Gets the position of this character
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
void Position(out float x, out float y, out float z);
/// <summary>
/// Gets the position of this character
/// </summary>
/// <returns></returns>
GenericPosition Position();
#region Manipulation
/// <summary>
/// Causes this character to die
/// </summary>
void Kill();
/// <summary>
/// Teleports this character to the specified position
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
void Teleport(float x, float y, float z);
#endregion
}
}
|
mit
|
C#
|
4060ee7a42af7d990a62603d78b9b238ab379e77
|
Fix cake error
|
stormpath/stormpath-dotnet-owin-middleware
|
build.cake
|
build.cake
|
var configuration = Argument("configuration", "Debug");
Task("Clean")
.Does(() =>
{
CleanDirectory("./artifacts/");
});
Task("Restore")
.Does(() =>
{
DotNetCoreRestore();
});
Task("Build")
.Does(() =>
{
var projects = GetFiles("./src/**/*.csproj");
Console.WriteLine("Building {0} projects", projects.Count());
foreach (var project in projects)
{
DotNetCoreBuild(project.FullPath, new DotNetCoreBuildSettings
{
Configuration = configuration
});
}
});
Task("Pack")
.Does(() =>
{
new List<string>
{
"Stormpath.Owin.Abstractions",
"Stormpath.Owin.Middleware",
"Stormpath.Owin.Views.Precompiled"
}.ForEach(name =>
{
DotNetCorePack("./src/" + name + ".csproj", new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = "./artifacts/"
});
});
});
Task("Test")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.Does(() =>
{
new List<string>
{
"Stormpath.Owin.UnitTest"
}.ForEach(name =>
{
DotNetCoreTest("./test/" + name + ".csproj");
});
});
Task("Default")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.IsDependentOn("Pack");
var target = Argument("target", "Default");
RunTarget(target);
|
var configuration = Argument("configuration", "Debug");
Task("Clean")
.Does(() =>
{
CleanDirectory("./artifacts/");
});
Task("Restore")
.Does(() =>
{
DotNetCoreRestore();
});
Task("Build")
.Does(() =>
{
DotNetCoreBuild("./src/**/*.csproj", new DotNetCoreBuildSettings
{
Configuration = configuration
});
});
Task("Pack")
.Does(() =>
{
new List<string>
{
"Stormpath.Owin.Abstractions",
"Stormpath.Owin.Middleware",
"Stormpath.Owin.Views.Precompiled"
}.ForEach(name =>
{
DotNetCorePack("./src/" + name + ".csproj", new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = "./artifacts/"
});
});
});
Task("Test")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.Does(() =>
{
new List<string>
{
"Stormpath.Owin.UnitTest"
}.ForEach(name =>
{
DotNetCoreTest("./test/" + name + ".csproj");
});
});
Task("Default")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.IsDependentOn("Pack");
var target = Argument("target", "Default");
RunTarget(target);
|
apache-2.0
|
C#
|
a0a6bac7e3d7fe5a2c0d50e27cc8468c7d2486a5
|
set nuget package include symbols fiels
|
dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap
|
build.cake
|
build.cake
|
#addin "nuget:https://www.nuget.org/api/v2?package=Newtonsoft.Json&version=9.0.1"
#load "./build/index.cake"
var target = Argument("target", "Default");
var build = BuildParameters.Create(Context);
var util = new Util(Context, build);
Task("Clean")
.Does(() =>
{
if (DirectoryExists("./artifacts"))
{
DeleteDirectory("./artifacts", true);
}
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
ArgumentCustomization = args =>
{
args.Append($"/p:VersionSuffix={build.Version.Suffix}");
return args;
}
};
DotNetCoreRestore(settings);
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
var settings = new DotNetCoreBuildSettings
{
Configuration = build.Configuration,
VersionSuffix = build.Version.Suffix,
ArgumentCustomization = args =>
{
args.Append($"/p:InformationalVersion={build.Version.VersionWithSuffix()}");
return args;
}
};
foreach (var project in build.ProjectFiles)
{
DotNetCoreBuild(project.FullPath, settings);
}
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
foreach (var testProject in build.TestProjectFiles)
{
DotNetCoreTest(testProject.FullPath);
}
});
Task("Pack")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = build.Configuration,
VersionSuffix = build.Version.Suffix,
IncludeSymbols = true,
OutputDirectory = "./artifacts/packages"
};
foreach (var project in build.ProjectFiles)
{
DotNetCorePack(project.FullPath, settings);
}
});
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("Test")
.IsDependentOn("Pack")
.Does(() =>
{
util.PrintInfo();
});
Task("Version")
.Does(() =>
{
Information($"{build.FullVersion()}");
});
Task("Print")
.Does(() =>
{
util.PrintInfo();
});
RunTarget(target);
|
#addin "nuget:https://www.nuget.org/api/v2?package=Newtonsoft.Json&version=9.0.1"
#load "./build/index.cake"
var target = Argument("target", "Default");
var build = BuildParameters.Create(Context);
var util = new Util(Context, build);
Task("Clean")
.Does(() =>
{
if (DirectoryExists("./artifacts"))
{
DeleteDirectory("./artifacts", true);
}
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
ArgumentCustomization = args =>
{
args.Append($"/p:VersionSuffix={build.Version.Suffix}");
return args;
}
};
DotNetCoreRestore(settings);
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
var settings = new DotNetCoreBuildSettings
{
Configuration = build.Configuration,
VersionSuffix = build.Version.Suffix,
ArgumentCustomization = args =>
{
args.Append($"/p:InformationalVersion={build.Version.VersionWithSuffix()}");
return args;
}
};
foreach (var project in build.ProjectFiles)
{
DotNetCoreBuild(project.FullPath, settings);
}
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
foreach (var testProject in build.TestProjectFiles)
{
DotNetCoreTest(testProject.FullPath);
}
});
Task("Pack")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = build.Configuration,
VersionSuffix = build.Version.Suffix,
OutputDirectory = "./artifacts/packages"
};
foreach (var project in build.ProjectFiles)
{
DotNetCorePack(project.FullPath, settings);
}
});
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("Test")
.IsDependentOn("Pack")
.Does(() =>
{
util.PrintInfo();
});
Task("Version")
.Does(() =>
{
Information($"{build.FullVersion()}");
});
Task("Print")
.Does(() =>
{
util.PrintInfo();
});
RunTarget(target);
|
mit
|
C#
|
cbd24719e7c66f37f04bd170b6d83ee2d078061f
|
Add missing doc. Update NuGet.
|
maxmind/GeoIP2-dotnet
|
GeoIP2/Responses/AnonymousIPResponse.cs
|
GeoIP2/Responses/AnonymousIPResponse.cs
|
using Newtonsoft.Json;
namespace MaxMind.GeoIP2.Responses
{
/// <summary>
/// This class represents the GeoIP2 Anonymous IP response.
/// </summary>
public class AnonymousIPResponse : AbstractResponse
{
/// <summary>
/// Constructor
/// </summary>
public AnonymousIPResponse() { }
/// <summary>
/// Returns true if the IP address belongs to any sort of anonymous network.
/// </summary>
[JsonProperty("is_anonymous")]
public bool IsAnonymous { get; internal set; }
/// <summary>
/// Returns true if the IP address belongs to an anonymous VPN system.
/// </summary>
[JsonProperty("is_anonymous_vpn")]
public bool IsAnonymousVpn { get; internal set; }
/// <summary>
/// Returns true if the IP address belongs to a hosting provider.
/// </summary>
[JsonProperty("is_hosting_provider")]
public bool IsHostingProvider { get; internal set; }
/// <summary>
/// Returns true if the IP address belongs to a public proxy.
/// </summary>
[JsonProperty("is_public_proxy")]
public bool IsPublicProxy { get; internal set; }
/// <summary>
/// Returns true if IP is a Tor exit node.
/// </summary>
[JsonProperty("is_tor_exit_node")]
public bool IsTorExitNode { get; internal set; }
/// <summary>
/// The IP address that the data in the model is for. If you
/// performed a "me" lookup against the web service, this will be the
/// externally routable IP address for the system the code is running
/// on. If the system is behind a NAT, this may differ from the IP
/// address locally assigned to it.
/// </summary>
[JsonProperty("ip_address")]
public string IPAddress { get; internal set; }
}
}
|
using Newtonsoft.Json;
namespace MaxMind.GeoIP2.Responses
{
/// <summary>
/// This class represents the GeoIP2 Anonymous IP response.
/// </summary>
public class AnonymousIPResponse : AbstractResponse
{
/// <summary>
/// Constructor
/// </summary>
public AnonymousIPResponse() { }
/// <summary>
/// Returns true if the IP address belongs to any sort of anonymous network.
/// </summary>
[JsonProperty("is_anonymous")]
public bool IsAnonymous { get; internal set; }
/// <summary>
/// Returns true if the IP address belongs to an anonymous VPN system.
/// </summary>
[JsonProperty("is_anonymous_vpn")]
public bool IsAnonymousVpn { get; internal set; }
/// <summary>
/// Returns true if the IP address belongs to a hosting provider.
/// </summary>
[JsonProperty("is_hosting_provider")]
public bool IsHostingProvider { get; internal set; }
/// <summary>
/// Returns true if the IP address belongs to a public proxy.
/// </summary>
[JsonProperty("is_public_proxy")]
public bool IsPublicProxy { get; internal set; }
[JsonProperty("is_tor_exit_node")]
public bool IsTorExitNode { get; internal set; }
/// <summary>
/// The IP address that the data in the model is for. If you
/// performed a "me" lookup against the web service, this will be the
/// externally routable IP address for the system the code is running
/// on. If the system is behind a NAT, this may differ from the IP
/// address locally assigned to it.
/// </summary>
[JsonProperty("ip_address")]
public string IPAddress { get; internal set; }
}
}
|
apache-2.0
|
C#
|
df01ae544c28da88e18146f0f8126194f388bddc
|
Remove unused field from previous commit
|
developerforce/visual-studio-tools
|
src/Salesforce.VisualStudio.Services/ConnectedService/SalesforceConnectedServiceProvider.cs
|
src/Salesforce.VisualStudio.Services/ConnectedService/SalesforceConnectedServiceProvider.cs
|
using Microsoft.VisualStudio.ConnectedServices;
using System;
using System.ComponentModel.Composition;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace Salesforce.VisualStudio.Services.ConnectedService
{
[Export(typeof(ConnectedServiceProvider))]
[ExportMetadata(Constants.ProviderId, Constants.ProviderIdValue)]
internal class SalesforceConnectedServiceProvider : ConnectedServiceProvider
{
public SalesforceConnectedServiceProvider()
{
this.Category = Resources.ConnectedServiceProvider_Category;
this.CreatedBy = Resources.ConnectedServiceProvider_CreatedBy;
this.Description = Resources.ConnectedServiceProvider_Description;
this.Icon = new BitmapImage(new Uri("pack://application:,,/" + Assembly.GetAssembly(this.GetType()).ToString() + ";component/ConnectedService/Views/Resources/ProviderIcon.png"));
this.MoreInfoUri = new Uri(Constants.MoreInfoLink);
this.Name = Resources.ConnectedServiceProvider_Name;
this.Version = typeof(SalesforceConnectedServiceProvider).Assembly.GetName().Version;
}
public override Task<ConnectedServiceConfigurator> CreateConfiguratorAsync(ConnectedServiceProviderHost host)
{
ConnectedServiceConfigurator wizard = new SalesforceConnectedServiceWizard(host);
return Task.FromResult(wizard);
}
}
}
|
using Microsoft.VisualStudio.ConnectedServices;
using System;
using System.ComponentModel.Composition;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Salesforce.VisualStudio.Services.ConnectedService
{
[Export(typeof(ConnectedServiceProvider))]
[ExportMetadata(Constants.ProviderId, Constants.ProviderIdValue)]
internal class SalesforceConnectedServiceProvider : ConnectedServiceProvider
{
private BitmapImage icon;
public SalesforceConnectedServiceProvider()
{
this.Category = Resources.ConnectedServiceProvider_Category;
this.CreatedBy = Resources.ConnectedServiceProvider_CreatedBy;
this.Description = Resources.ConnectedServiceProvider_Description;
this.Icon = new BitmapImage(new Uri("pack://application:,,/" + Assembly.GetAssembly(this.GetType()).ToString() + ";component/ConnectedService/Views/Resources/ProviderIcon.png"));
this.MoreInfoUri = new Uri(Constants.MoreInfoLink);
this.Name = Resources.ConnectedServiceProvider_Name;
this.Version = typeof(SalesforceConnectedServiceProvider).Assembly.GetName().Version;
}
public override Task<ConnectedServiceConfigurator> CreateConfiguratorAsync(ConnectedServiceProviderHost host)
{
ConnectedServiceConfigurator wizard = new SalesforceConnectedServiceWizard(host);
return Task.FromResult(wizard);
}
}
}
|
bsd-3-clause
|
C#
|
77c4d73ae967f6645cdfc928ea920a12f04a4b1a
|
write exceptions on migration error
|
mehrandvd/Tralus,mehrandvd/Tralus
|
Framework/Source/Tralus.Framework.PowerShell/Migration/Cmdlets/UpdateTralusDatabaseCmdlet.cs
|
Framework/Source/Tralus.Framework.PowerShell/Migration/Cmdlets/UpdateTralusDatabaseCmdlet.cs
|
using System;
using System.Linq;
using System.Management.Automation;
namespace Tralus.Framework.PowerShell.Migration
{
[Cmdlet(VerbsData.Update, "TralusDatabase", SupportsShouldProcess = true)]
public class UpdateTralusDatabaseCmdlet : TralusMigrationCmdletBase
{
protected override void ProcessRecord()
{
base.ProcessRecord();
var migrator = GetMigrator();
var migrationBundles = migrator.GetMigrationPlan();
if (!migrationBundles.Any())
{
WriteWarning("No pending migration.");
return;
}
var bundleNumber = 1;
foreach (var migrationBundle in migrationBundles)
{
WriteObject($"\n{bundleNumber++}. Migrating ({migrationBundle}):");
foreach (var applyingMigration in migrationBundle.MigrationNames)
{
WriteObject($"\t-[{applyingMigration}]");
}
if (ShouldProcess("Database", $"Applying migration up to: [{migrationBundle.TargetMigrationName}]"))
{
try
{
var dbMigrator = migrationBundle.GetNewMigrator();
dbMigrator.Update(migrationBundle.TargetMigrationName);
}
catch (Exception exception)
{
WriteObject(exception.ToString());
throw;
}
WriteObject("\tDone.\n");
}
}
}
}
}
|
using System.Linq;
using System.Management.Automation;
namespace Tralus.Framework.PowerShell.Migration
{
[Cmdlet(VerbsData.Update, "TralusDatabase", SupportsShouldProcess = true)]
public class UpdateTralusDatabaseCmdlet : TralusMigrationCmdletBase
{
protected override void ProcessRecord()
{
base.ProcessRecord();
var migrator = GetMigrator();
var migrationBundles = migrator.GetMigrationPlan();
if (!migrationBundles.Any())
{
WriteWarning("No pending migration.");
return;
}
var bundleNumber = 1;
foreach (var migrationBundle in migrationBundles)
{
WriteObject($"\n{bundleNumber++}. Migrating ({migrationBundle}):");
foreach (var applyingMigration in migrationBundle.MigrationNames)
{
WriteObject($"\t-[{applyingMigration}]");
}
if (ShouldProcess("Database", $"Applying migration up to: [{migrationBundle.TargetMigrationName}]"))
{
var dbMigrator = migrationBundle.GetNewMigrator();
dbMigrator.Update(migrationBundle.TargetMigrationName);
WriteObject("\tDone.\n");
}
}
}
}
}
|
apache-2.0
|
C#
|
a319fbe7ddef4ee8c29da2c2233fc95f5438db14
|
Change way to handle default for version of SqlServer in batch xml element
|
Seddryck/NBi,Seddryck/NBi
|
NBi.Xml/Decoration/Command/SqlRunXml.cs
|
NBi.Xml/Decoration/Command/SqlRunXml.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core.Etl;
using NBi.Xml.Items;
using System.IO;
using NBi.Core.Batch;
using NBi.Xml.Settings;
using System.ComponentModel;
namespace NBi.Xml.Decoration.Command
{
public class SqlRunXml : DecorationCommandXml, IBatchRunCommand
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("path")]
public string InternalPath { get; set; }
[XmlIgnore]
public string FullPath
{
get
{
var fullPath = string.Empty;
if (!Path.IsPathRooted(InternalPath) || string.IsNullOrEmpty(Settings.BasePath))
fullPath = InternalPath + Name;
else
fullPath = Settings.BasePath + InternalPath + Name;
return fullPath;
}
}
[XmlAttribute("version")]
public string Version { get; set; }
[XmlAttribute("connectionString")]
public string SpecificConnectionString { get; set; }
[XmlIgnore]
public string ConnectionString
{
get
{
if (!string.IsNullOrEmpty(SpecificConnectionString) && SpecificConnectionString.StartsWith("@"))
return Settings.GetReference(SpecificConnectionString.Remove(0, 1)).ConnectionString;
if (!String.IsNullOrWhiteSpace(SpecificConnectionString))
return SpecificConnectionString;
if (Settings != null && Settings.GetDefault(SettingsXml.DefaultScope.Decoration) != null)
return Settings.GetDefault(SettingsXml.DefaultScope.Decoration).ConnectionString;
return string.Empty;
}
}
public SqlRunXml()
{
Version = "SqlServer2014";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core.Etl;
using NBi.Xml.Items;
using System.IO;
using NBi.Core.Batch;
using NBi.Xml.Settings;
using System.ComponentModel;
namespace NBi.Xml.Decoration.Command
{
public class SqlRunXml : DecorationCommandXml, IBatchRunCommand
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("path")]
public string InternalPath { get; set; }
[XmlIgnore]
public string FullPath
{
get
{
var fullPath = string.Empty;
if (!Path.IsPathRooted(InternalPath) || string.IsNullOrEmpty(Settings.BasePath))
fullPath = InternalPath + Name;
else
fullPath = Settings.BasePath + InternalPath + Name;
return fullPath;
}
}
[XmlAttribute("version")]
[DefaultValue("SqlServer2014")]
public string Version { get; set; }
[XmlAttribute("connectionString")]
public string SpecificConnectionString { get; set; }
[XmlIgnore]
public string ConnectionString
{
get
{
if (!string.IsNullOrEmpty(SpecificConnectionString) && SpecificConnectionString.StartsWith("@"))
return Settings.GetReference(SpecificConnectionString.Remove(0, 1)).ConnectionString;
if (!String.IsNullOrWhiteSpace(SpecificConnectionString))
return SpecificConnectionString;
if (Settings != null && Settings.GetDefault(SettingsXml.DefaultScope.Decoration) != null)
return Settings.GetDefault(SettingsXml.DefaultScope.Decoration).ConnectionString;
return string.Empty;
}
}
public SqlRunXml()
{
}
}
}
|
apache-2.0
|
C#
|
3c8f2a51b5f45692ab58dff0bb7e842225c7f907
|
Clean Up
|
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
|
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api/Authentication/AuthenticationService.cs
|
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api/Authentication/AuthenticationService.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using SFA.DAS.CommitmentsV2.Authentication;
using SFA.DAS.CommitmentsV2.Types;
using IAuthenticationService = SFA.DAS.CommitmentsV2.Authentication.IAuthenticationService;
namespace SFA.DAS.CommitmentsV2.Api.Authentication
{
public class AuthenticationService : IAuthenticationService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public AuthenticationService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public IEnumerable<string> GetAllUserRoles()
{
return _httpContextAccessor.HttpContext.User.Identities.SelectMany(i => i.FindAll(i.RoleClaimType).Select(c => c.Value));
}
public bool IsUserInRole(string role)
{
return _httpContextAccessor.HttpContext.User.IsInRole(role);
}
public Party GetUserParty()
{
var isEmployer = IsUserInRole(Role.Employer);
var isProvider = IsUserInRole(Role.Provider);
// The client app should be one _or_ the other (not both, not neither).
if (isEmployer ^ isProvider)
{
return isEmployer ? Party.Employer : Party.Provider;
}
//This method may need revisiting in future, as it does not support TransferSenders, who are in the Employer role. Specific endpoints will be
//made available for TransferSender functionality, so perhaps it doesn't matter - in this case, we would just need to assert that the user is
//in the Employer role and thereby infer that they must be the TransferSender in that context. Alternatively, could another implementation of this
//be created for use within the TransferSender functionality? This would assert that the user is in the Employer role, and return TransferSender
//as the Party, or otherwise throw an exception.
throw new ArgumentException($"Unable to map User Role (IsEmployer:{isEmployer}, IsProvider:{isProvider}) to Party");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using SFA.DAS.CommitmentsV2.Authentication;
using SFA.DAS.CommitmentsV2.Types;
using IAuthenticationService = SFA.DAS.CommitmentsV2.Authentication.IAuthenticationService;
namespace SFA.DAS.CommitmentsV2.Api.Authentication
{
public class AuthenticationService : IAuthenticationService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public AuthenticationService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public IEnumerable<string> GetAllUserRoles()
{
return _httpContextAccessor.HttpContext.User.Identities.SelectMany(i => i.FindAll(i.RoleClaimType).Select(c => c.Value));
}
public bool IsUserInRole(string role)
{
return _httpContextAccessor.HttpContext.User.IsInRole(role);
}
public Party GetUserParty()
{
var isEmployer = IsUserInRole(Role.Employer);
var isProvider = IsUserInRole(Role.Provider);
// The client app should be one _or_ the other (not both, not neither).
if (isEmployer ^ isProvider)
{
return isEmployer ? Party.Employer : Party.Provider;
}
//This method may need revisiting in future, as it does not support TransferSenders, who are in the Employer role. Specific endpoints will be
//made available for TransferSender functionality, so perhaps it doesn't matter - in this case, we would just need to assert that the user is
//in the Employer role and thereby infer that they must be the TransferSender in that context. Alternatively, could another implementation of this
//be created for use within the TransferSender functionality? This would assert that the user is in the Employer role, and return TransferSender
//as the Party, or otherwise throw an exception.
#if DEBUG
return Party.Employer;
#endif
throw new ArgumentException($"Unable to map User Role (IsEmployer:{isEmployer}, IsProvider:{isProvider}) to Party");
}
}
}
|
mit
|
C#
|
80147fc4fda3a59b56ceb1360583a649d2f7b395
|
remove repeated notifications
|
swsch/FacePalm
|
FacePalm/LineBase.cs
|
FacePalm/LineBase.cs
|
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Controls;
using System.Windows.Media;
using FacePalm.Annotations;
namespace FacePalm {
public abstract class LineBase : INotifyPropertyChanged {
private Marker _m1;
private Marker _m2;
public string Id { get; set; }
public string Description { get; set; }
public bool Visible { get; set; } = true;
public Marker M1 {
get => _m1;
set {
_m1 = value;
M1.PropertyChanged += MarkerPropertyChanged;
}
}
public Marker M2 {
get => _m2;
set {
_m2 = value;
M2.PropertyChanged += MarkerPropertyChanged;
}
}
public bool IsDefined => M1.IsDefined && M2.IsDefined;
public Brush BackgroundBrush => IsDefined ? MarkerBrush.Background : MarkerBrush.Transparent;
public virtual event PropertyChangedEventHandler PropertyChanged;
private void MarkerPropertyChanged(object sender, PropertyChangedEventArgs e) {
OnPropertyChanged(e.PropertyName);
}
[NotifyPropertyChangedInvocator]
private void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void DrawLine(Canvas canvas, double scale) {
}
}
}
|
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Controls;
using System.Windows.Media;
using FacePalm.Annotations;
namespace FacePalm {
public abstract class LineBase : INotifyPropertyChanged {
private Marker _m1;
private Marker _m2;
public string Id { get; set; }
public string Description { get; set; }
public bool Visible { get; set; } = true;
public Marker M1 {
get => _m1;
set {
_m1 = value;
M1.PropertyChanged += MarkerPropertyChanged;
}
}
public Marker M2 {
get => _m2;
set {
_m2 = value;
M2.PropertyChanged += MarkerPropertyChanged;
}
}
public bool IsDefined => M1.IsDefined && M2.IsDefined;
public Brush BackgroundBrush => IsDefined ? MarkerBrush.Background : MarkerBrush.Transparent;
public virtual event PropertyChangedEventHandler PropertyChanged;
private void MarkerPropertyChanged(object sender, PropertyChangedEventArgs e) {
OnPropertyChanged(nameof(IsDefined));
OnPropertyChanged(nameof(Brush));
OnPropertyChanged(nameof(BackgroundBrush));
}
[NotifyPropertyChangedInvocator]
private void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void DrawLine(Canvas canvas, double scale) {
}
}
}
|
mit
|
C#
|
ff1af2036da056aa873254daf811e8177a106940
|
update getString() to use getElementWithLikeSearch()
|
yasokada/unity-160820-Inventory-UI
|
Assets/DataBaseManager.cs
|
Assets/DataBaseManager.cs
|
using UnityEngine;
//using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using NS_MyStringUtil;
/*
* - update getString() to use getElementWithLikeSearch()
* - add getElementWithLikeSearch()
* - add dictionary [m_dic]
* - add [kIndex_checkDate]
* - add [kIndex_XXX] such as kIndex_row
* v0.1 2016 Aug. 23
* - add LoadCsvResouce()
*/
namespace NS_DataBaseManager
{
public class DataBaseManager {
Dictionary <string, string> m_dic;
public const int kIndex_caseNo = 0;
public const int kIndex_row = 1;
public const int kIndex_column = 2;
public const int kIndex_name = 3;
public const int kIndex_about = 4;
public const int kIndex_url = 5;
public const int kIndex_checkDate = 6;
public void LoadCsvResouce() {
if (m_dic == null) {
m_dic = new Dictionary<string, string>();
}
TextAsset csv = Resources.Load ("inventory") as TextAsset;
StringReader reader = new StringReader (csv.text);
string line = "";
string itmnm;
while (reader.Peek () != -1) {
line = reader.ReadLine ();
itmnm = MyStringUtil.ExtractCsvColumn (line, kIndex_name);
m_dic.Add (itmnm, line);
}
}
public string getString() {
string res = getElementWithLikeSearch (m_dic, "2SK4017");
return res;
}
private static string getElementWithLikeSearch(Dictionary<string, string> myDic, string searchKey) {
//Dictionaryの規定値は「null, null」なので、空文字を返したい場合はnull判定を入れる
return myDic.Where(n => n.Key.Contains(searchKey)).FirstOrDefault().Value;
}
}
}
|
using UnityEngine;
//using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using NS_MyStringUtil;
/*
* - add getElementWithLikeSearch()
* - add dictionary [m_dic]
* - add [kIndex_checkDate]
* - add [kIndex_XXX] such as kIndex_row
* v0.1 2016 Aug. 23
* - add LoadCsvResouce()
*/
namespace NS_DataBaseManager
{
public class DataBaseManager {
Dictionary <string, string> m_dic;
// string m_dataString;
public const int kIndex_caseNo = 0;
public const int kIndex_row = 1;
public const int kIndex_column = 2;
public const int kIndex_name = 3;
public const int kIndex_about = 4;
public const int kIndex_url = 5;
public const int kIndex_checkDate = 6;
public void LoadCsvResouce() {
if (m_dic == null) {
m_dic = new Dictionary<string, string>();
}
TextAsset csv = Resources.Load ("inventory") as TextAsset;
StringReader reader = new StringReader (csv.text);
string line = "";
string itmnm;
while (reader.Peek () != -1) {
line = reader.ReadLine ();
itmnm = MyStringUtil.ExtractCsvColumn (line, kIndex_name);
m_dic.Add (itmnm, line);
}
// m_dataString = line;
}
public string getString() {
return "dummy";
// return m_dataString;
}
private static string getElementWithLikeSearch(Dictionary<string, string> myDic, string searchKey) {
//Dictionaryの規定値は「null, null」なので、空文字を返したい場合はnull判定を入れる
return myDic.Where(n => n.Key.Contains(searchKey)).FirstOrDefault().Value;
}
}
}
|
mit
|
C#
|
2e853fca631cffa0369b1a86f787114eb4af53f8
|
Fix a few
|
prepare/websocket-sharp,sinha-abhishek/websocket-sharp,microdee/websocket-sharp,hybrid1969/websocket-sharp,alberist/websocket-sharp,juoni/websocket-sharp,sta/websocket-sharp,alberist/websocket-sharp,prepare/websocket-sharp,juoni/websocket-sharp,Liryna/websocket-sharp,zq513705971/WebSocketApp,sta/websocket-sharp,hybrid1969/websocket-sharp,prepare/websocket-sharp,jogibear9988/websocket-sharp,microdee/websocket-sharp,microdee/websocket-sharp,TabbedOut/websocket-sharp,pjc0247/websocket-sharp-unity,zhangwei900808/websocket-sharp,2Toad/websocket-sharp,jjrdk/websocket-sharp,sinha-abhishek/websocket-sharp,TabbedOut/websocket-sharp,pjc0247/websocket-sharp-unity,jmptrader/websocket-sharp,hybrid1969/websocket-sharp,pjc0247/websocket-sharp-unity,zq513705971/WebSocketApp,sinha-abhishek/websocket-sharp,zq513705971/WebSocketApp,2Toad/websocket-sharp,jmptrader/websocket-sharp,alberist/websocket-sharp,jjrdk/websocket-sharp,sta/websocket-sharp,2Toad/websocket-sharp,2Toad/websocket-sharp,sinha-abhishek/websocket-sharp,pjc0247/websocket-sharp-unity,TabbedOut/websocket-sharp,jogibear9988/websocket-sharp,sta/websocket-sharp,jmptrader/websocket-sharp,zhangwei900808/websocket-sharp,microdee/websocket-sharp,juoni/websocket-sharp,juoni/websocket-sharp,hybrid1969/websocket-sharp,zhangwei900808/websocket-sharp,TabbedOut/websocket-sharp,alberist/websocket-sharp,Liryna/websocket-sharp,jogibear9988/websocket-sharp,zhangwei900808/websocket-sharp,prepare/websocket-sharp,jogibear9988/websocket-sharp,Liryna/websocket-sharp,jmptrader/websocket-sharp,zq513705971/WebSocketApp
|
websocket-sharp/Server/ServerState.cs
|
websocket-sharp/Server/ServerState.cs
|
#region License
/*
* ServerState.cs
*
* The MIT License
*
* Copyright (c) 2013-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp.Server
{
internal enum ServerState
{
Ready,
Start,
ShuttingDown,
Stop
}
}
|
#region License
/*
* ServerState.cs
*
* The MIT License
*
* Copyright (c) 2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp.Server
{
internal enum ServerState
{
Ready,
Start,
ShuttingDown,
Stop
}
}
|
mit
|
C#
|
f474e5f5e756905b1801c68a0ac1475d8f62ee07
|
Update Iri.cs
|
mganss/HtmlSanitizer
|
src/HtmlSanitizer/Iri.cs
|
src/HtmlSanitizer/Iri.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ganss.XSS
{
/// <summary>
/// Represents an Internationalized Resource Identifier.
/// </summary>
public class Iri
{
/// <summary>
/// Gets or sets the value of the IRI.
/// </summary>
/// <value>
/// The value of the IRI.
/// </value>
public string Value { get; private set; }
/// <summary>
/// Gets a value indicating whether the IRI is absolute.
/// </summary>
/// <value>
/// <c>true</c> if the IRI is absolute; otherwise, <c>false</c>.
/// </value>
public bool IsAbsolute => !string.IsNullOrEmpty(Scheme);
/// <summary>
/// Gets or sets the scheme of the IRI, e.g. "https".
/// </summary>
/// <value>
/// The scheme of the IRI.
/// </value>
public string? Scheme { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Iri"/> class.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="scheme">The scheme.</param>
public Iri(string value, string? scheme = null)
{
Value = value;
Scheme = scheme;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ganss.XSS
{
/// <summary>
/// Represents an Internationalized Resource Identifier
/// </summary>
public class Iri
{
/// <summary>
/// Gets or sets the value of the IRI.
/// </summary>
/// <value>
/// The value of the IRI.
/// </value>
public string Value { get; private set; }
/// <summary>
/// Gets a value indicating whether the IRI is absolute.
/// </summary>
/// <value>
/// <c>true</c> if the IRI is absolute; otherwise, <c>false</c>.
/// </value>
public bool IsAbsolute => !string.IsNullOrEmpty(Scheme);
/// <summary>
/// Gets or sets the scheme of the IRI, e.g. http.
/// </summary>
/// <value>
/// The scheme of the IRI.
/// </value>
public string? Scheme { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Iri"/> class.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="scheme">The scheme.</param>
public Iri(string value, string? scheme = null)
{
Value = value;
Scheme = scheme;
}
}
}
|
mit
|
C#
|
e0a39211495604411fc0f214a045e48365b410f1
|
handle nested invokes
|
neilthompson19/nslim,unclebob/nslim
|
source/mtee/Operators/DefaultRuntime.cs
|
source/mtee/Operators/DefaultRuntime.cs
|
// Copyright © Syterra Software Inc. All rights reserved.
// The use and distribution terms for this software are covered by the Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file license.txt at the root of this distribution. By using this software in any fashion, you are agreeing
// to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
using System;
using System.Collections.Generic;
using fitnesse.mtee.engine;
using fitnesse.mtee.exception;
using fitnesse.mtee.model;
namespace fitnesse.mtee.operators {
public class DefaultRuntime<T>: RuntimeOperator<T> {
public bool TryCreate(Processor<T> processor, string memberName, Tree<T> parameters, ref TypedValue result) {
var runtimeType = processor.ParseString<RuntimeType>(memberName);
if (parameters.Branches.Count == 0) {
result = runtimeType.CreateInstance();
}
else {
RuntimeMember member = runtimeType.GetConstructor(parameters.Branches.Count);
result = member.Invoke(GetParameterList(processor, TypedValue.Void, parameters, member));
}
return true;
}
public bool TryInvoke(Processor<T> processor, TypedValue instance, string memberName, Tree<T> parameters, ref TypedValue result) {
RuntimeMember member = RuntimeType.GetInstance(instance, memberName, parameters.Branches.Count);
result = member.Invoke(GetParameterList(processor, instance, parameters, member));
return true;
}
private static object[] GetParameterList(Processor<T> processor, TypedValue instance, Tree<T> parameters, RuntimeMember member) {
var parameterList = new List<object>();
int i = 0;
foreach (Tree<T> parameter in parameters.Branches) {
TypedValue parameterValue;
try {
parameterValue = processor.Parse(member.GetParameterType(i), instance, parameter);
}
catch (Exception e) {
throw new ParseException<T>(string.Format("Parse parameter {0} for '{1}' failed.", i+1, member.Name), parameter.Value, e);
}
parameterList.Add(parameterValue.Value);
i++;
}
return parameterList.ToArray();
}
}
}
|
// Copyright © Syterra Software Inc. All rights reserved.
// The use and distribution terms for this software are covered by the Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file license.txt at the root of this distribution. By using this software in any fashion, you are agreeing
// to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
using System;
using System.Collections.Generic;
using fitnesse.mtee.engine;
using fitnesse.mtee.exception;
using fitnesse.mtee.model;
namespace fitnesse.mtee.operators {
public class DefaultRuntime<T>: RuntimeOperator<T> {
public bool TryCreate(Processor<T> processor, string memberName, Tree<T> parameters, ref TypedValue result) {
var runtimeType = processor.ParseString<RuntimeType>(memberName);
if (parameters.Branches.Count == 0) {
result = runtimeType.CreateInstance();
}
else {
RuntimeMember member = runtimeType.GetConstructor(parameters.Branches.Count);
result = member.Invoke(GetParameterList(processor, parameters, member));
}
return true;
}
public bool TryInvoke(Processor<T> processor, TypedValue instance, string memberName, Tree<T> parameters, ref TypedValue result) {
RuntimeMember member = RuntimeType.GetInstance(instance, memberName, parameters.Branches.Count);
result = member.Invoke(GetParameterList(processor, parameters, member));
return true;
}
private static object[] GetParameterList(Processor<T> processor, Tree<T> parameters, RuntimeMember member) {
var parameterList = new List<object>();
int i = 0;
foreach (Tree<T> parameter in parameters.Branches) {
TypedValue parameterValue;
try {
parameterValue = processor.Parse(member.GetParameterType(i), parameter);
}
catch (Exception e) {
throw new ParseException<T>(string.Format("Parse parameter {0} for '{1}' failed.", i+1, member.Name), parameter.Value, e);
}
parameterList.Add(parameterValue.Value);
i++;
}
return parameterList.ToArray();
}
}
}
|
epl-1.0
|
C#
|
69ab015b38b6859f4215f99b90a501f65a1383ba
|
Revert "conf"
|
Portafolio-titulo2017-Grupo3/Sistema_escritorio_NET
|
OrionEscritorio/OrionEscritorio/TEST_RAMA.Designer.cs
|
OrionEscritorio/OrionEscritorio/TEST_RAMA.Designer.cs
|
namespace OrionEscritorio
{
partial class TEST_RAMA
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(58, 97);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// TEST_RAMA
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.button1);
this.Name = "TEST_RAMA";
this.Text = "Nombre Cambiado";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
}
}
|
namespace OrionEscritorio
{
partial class TEST_RAMA
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(37, 54);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// TEST_RAMA
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.button1);
this.Name = "TEST_RAMA";
this.Text = "Nombre Cambiado";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
}
}
|
mit
|
C#
|
2c00a4791ca25d79bca0a06e80fd504ffead61a8
|
Add Scheduler note
|
carbon/Amazon
|
src/Amazon.Core/Scheduling/Scheduler.cs
|
src/Amazon.Core/Scheduling/Scheduler.cs
|
using System;
using System.Threading.Tasks;
namespace Amazon.Scheduling
{
public static class Scheduler
{
public static async Task<T> ExecuteAsync<T>(this RetryPolicy policy, Func<Task<T>> action)
{
Exception lastError;
int retryCount = 0;
do
{
if (retryCount > 0)
{
await Task.Delay(policy.GetDelay(retryCount)).ConfigureAwait(false);
}
try
{
return await action().ConfigureAwait(false);
}
catch (Exception ex) when (ex.IsTransient())
{
lastError = ex;
}
retryCount++;
}
while (policy.ShouldRetry(retryCount));
// TODO: Throw aggregate exception
throw lastError;
}
private static bool IsTransient(this Exception ex)
{
return ex is IException { IsTransient: true };
}
}
}
// NOTES:
// Used by Kinesis
|
using System;
using System.Threading.Tasks;
namespace Amazon.Scheduling
{
public static class Scheduler
{
public static async Task<T> ExecuteAsync<T>(this RetryPolicy policy, Func<Task<T>> action)
{
Exception lastError;
int retryCount = 0;
do
{
if (retryCount > 0)
{
await Task.Delay(policy.GetDelay(retryCount)).ConfigureAwait(false);
}
try
{
return await action().ConfigureAwait(false);
}
catch (Exception ex) when (ex.IsTransient())
{
lastError = ex;
}
retryCount++;
}
while (policy.ShouldRetry(retryCount));
// TODO: Throw aggregate exception
throw lastError;
}
private static bool IsTransient(this Exception ex)
{
return ex is IException { IsTransient: true };
}
}
}
|
mit
|
C#
|
fbdf635f7f12804a2bd5cf69e0beee796a6c3dc8
|
Fix typo in TextAlignLast.cs
|
AngleSharp/AngleSharp.Css,AngleSharp/AngleSharp.Css,AngleSharp/AngleSharp.Css
|
src/AngleSharp.Css/Dom/TextAlignLast.cs
|
src/AngleSharp.Css/Dom/TextAlignLast.cs
|
namespace AngleSharp.Css.Dom
{
/// <summary>
/// An enumeration with all possible text last alignments.
/// </summary>
public enum TextAlignLast : byte
{
/// <summary>
/// The affected line is aligned per the value of text-align, unless
/// text-align is justify, in which case the effect is the same as
/// setting text-align-last to left.
/// </summary>
Auto,
/// <summary>
/// The same as left if direction is left-to-right and right if direction
/// is right-to-left.
/// </summary>
Start,
/// <summary>
/// The same as right if direction is left-to-right and left if direction
/// is right-to-left.
/// </summary>
End,
/// <summary>
/// The inline contents are aligned to the left edge of the line box.
/// </summary>
Left,
/// <summary>
/// The inline contents are aligned to the right edge of the line box.
/// </summary>
Right,
/// <summary>
/// The inline contents are centered within the line box.
/// </summary>
Center,
/// <summary>
/// The text is justified. Text should line up their left and right edges
/// to the left and right content edges of the paragraph.
/// </summary>
Justify
}
}
|
namespace AngleSharp.Css.Dom
{
/// <summary>
/// An enumeration with all possible text last alignments.
/// </summary>
public enum TextAlignLast : byte
{
/// <summary>
/// The affected line is aligned per the value of text-align, unless
/// text-align is justify, in which case the effect is the same as
/// etting text-align-last to left.
/// </summary>
Auto,
/// <summary>
/// The same as left if direction is left-to-right and right if direction
/// is right-to-left.
/// </summary>
Start,
/// <summary>
/// The same as right if direction is left-to-right and left if direction
/// is right-to-left.
/// </summary>
End,
/// <summary>
/// The inline contents are aligned to the left edge of the line box.
/// </summary>
Left,
/// <summary>
/// The inline contents are aligned to the right edge of the line box.
/// </summary>
Right,
/// <summary>
/// The inline contents are centered within the line box.
/// </summary>
Center,
/// <summary>
/// The text is justified. Text should line up their left and right edges
/// to the left and right content edges of the paragraph.
/// </summary>
Justify
}
}
|
mit
|
C#
|
132a6226bfebc30c075c1e19c4f4bd1de4d409bd
|
Initialize CreateCommand with an ApplicationConfiguration rather than IFileSystem
|
appharbor/appharbor-cli
|
src/AppHarbor/Commands/CreateCommand.cs
|
src/AppHarbor/Commands/CreateCommand.cs
|
using System;
namespace AppHarbor.Commands
{
public class CreateCommand : ICommand
{
private readonly AppHarborClient _appHarborClient;
private readonly ApplicationConfiguration _applicationConfiguration;
public CreateCommand(AppHarborClient appHarborClient, ApplicationConfiguration applicationConfiguration)
{
_appHarborClient = appHarborClient;
_applicationConfiguration = applicationConfiguration;
}
public void Execute(string[] arguments)
{
_appHarborClient.CreateApplication(arguments[0], arguments[1]);
throw new NotImplementedException();
}
}
}
|
using System;
namespace AppHarbor.Commands
{
public class CreateCommand : ICommand
{
private readonly AppHarborClient _appHarborClient;
private readonly IFileSystem _fileSystem;
public CreateCommand(AppHarborClient appHarborClient, IFileSystem fileSystem)
{
_appHarborClient = appHarborClient;
_fileSystem = fileSystem;
}
public void Execute(string[] arguments)
{
_appHarborClient.CreateApplication(arguments[0], arguments[1]);
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
aefa58bdc4b1dabf5f8bb8832867b01ca5e39d26
|
Optimize DefinitionList collection changed handler.
|
wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,SuperJMN/Avalonia
|
src/Avalonia.Controls/DefinitionList.cs
|
src/Avalonia.Controls/DefinitionList.cs
|
using System.Collections;
using System.Collections.Specialized;
using Avalonia.Collections;
#nullable enable
namespace Avalonia.Controls
{
public abstract class DefinitionList<T> : AvaloniaList<T> where T : DefinitionBase
{
public DefinitionList()
{
ResetBehavior = ResetBehavior.Remove;
CollectionChanged += OnCollectionChanged;
}
internal bool IsDirty = true;
private Grid? _parent;
internal Grid? Parent
{
get => _parent;
set => SetParent(value);
}
private void SetParent(Grid? value)
{
_parent = value;
var idx = 0;
foreach (T definition in this)
{
definition.Parent = value;
definition.Index = idx++;
}
}
internal void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var idx = 0;
foreach (T definition in this)
{
definition.Index = idx++;
}
UpdateDefinitionParent(e.NewItems, false);
UpdateDefinitionParent(e.OldItems, true);
IsDirty = true;
}
private void UpdateDefinitionParent(IList? items, bool wasRemoved)
{
if (items is null)
{
return;
}
var count = items.Count;
for (var i = 0; i < count; i++)
{
var definition = (DefinitionBase) items[i];
if (wasRemoved)
{
definition.OnExitParentTree();
}
else
{
definition.Parent = Parent;
definition.OnEnterParentTree();
}
}
}
}
}
|
using System;
using System.Collections.Specialized;
using System.Linq;
using Avalonia.Collections;
namespace Avalonia.Controls
{
public abstract class DefinitionList<T> : AvaloniaList<T> where T : DefinitionBase
{
public DefinitionList()
{
ResetBehavior = ResetBehavior.Remove;
CollectionChanged += OnCollectionChanged;
}
internal bool IsDirty = true;
private Grid _parent;
internal Grid Parent
{
get => _parent;
set => SetParent(value);
}
private void SetParent(Grid value)
{
_parent = value;
foreach (var pair in this.Select((definitions, index) => (definitions, index)))
{
pair.definitions.Parent = value;
pair.definitions.Index = pair.index;
}
}
internal void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
foreach (var nI in this.Select((d, i) => (d, i)))
nI.d._parentIndex = nI.i;
foreach (var nD in e.NewItems?.Cast<DefinitionBase>()
?? Enumerable.Empty<DefinitionBase>())
{
nD.Parent = this.Parent;
nD.OnEnterParentTree();
}
foreach (var oD in e.OldItems?.Cast<DefinitionBase>()
?? Enumerable.Empty<DefinitionBase>())
{
oD.OnExitParentTree();
}
IsDirty = true;
}
}
}
|
mit
|
C#
|
def6ae13145e7cf2532e9385b571fd1dfd81d143
|
Set CreateOnly to false by defaultso publish is true by default.
|
mdavid/nuget,mdavid/nuget
|
src/CommandLine/Commands/PushCommand.cs
|
src/CommandLine/Commands/PushCommand.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using NuGet.Common;
namespace NuGet.Commands {
[Export(typeof(ICommand))]
[Command(typeof(NuGetResources), "push", "PushCommandDescription", AltName="pu",
MinArgs = 2, MaxArgs = 2, UsageDescriptionResourceName = "PushCommandUsageDescription",
UsageSummaryResourceName = "PushCommandUsageSummary")]
public class PushCommand : Command {
private string _apiKey;
private string _packagePath;
[Option(typeof(NuGetResources), "PushCommandPublishDescription", AltName = "co")]
public bool CreateOnly { get; set; }
[Option(typeof(NuGetResources), "PushCommandSourceDescription", AltName = "src")]
public string Source { get; set; }
public override void ExecuteCommand() {
//Frist argument should be the package
_packagePath = Arguments[0];
//Second argument should be the API Key
_apiKey = Arguments[1];
GalleryServer gallery;
if (String.IsNullOrEmpty(Source)) {
gallery = new GalleryServer();
}
else {
gallery = new GalleryServer(Source);
}
ZipPackage pkg = new ZipPackage(_packagePath);
Console.WriteLine(NuGetResources.PushCommandCreatingPackage, pkg.Id, pkg.Version);
using (Stream pkgStream = pkg.GetStream()) {
gallery.CreatePackage(_apiKey, pkgStream);
}
Console.WriteLine(NuGetResources.PushCommandPackageCreated);
if (!CreateOnly) {
var cmd = new PublishCommand();
cmd.Console = Console;
cmd.Source = Source;
cmd.Arguments = new List<string> { pkg.Id, pkg.Version.ToString(), _apiKey };
cmd.Execute();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using NuGet.Common;
namespace NuGet.Commands {
[Export(typeof(ICommand))]
[Command(typeof(NuGetResources), "push", "PushCommandDescription", AltName="pu",
MinArgs = 2, MaxArgs = 2, UsageDescriptionResourceName = "PushCommandUsageDescription",
UsageSummaryResourceName = "PushCommandUsageSummary")]
public class PushCommand : Command {
private string _apiKey;
private string _packagePath;
[Option(typeof(NuGetResources), "PushCommandPublishDescription", AltName = "co")]
public bool CreateOnly { get; set; }
[Option(typeof(NuGetResources), "PushCommandSourceDescription", AltName = "src")]
public string Source { get; set; }
public PushCommand() {
CreateOnly = true;
}
public override void ExecuteCommand() {
//Frist argument should be the package
_packagePath = Arguments[0];
//Second argument should be the API Key
_apiKey = Arguments[1];
GalleryServer gallery;
if (String.IsNullOrEmpty(Source)) {
gallery = new GalleryServer();
}
else {
gallery = new GalleryServer(Source);
}
ZipPackage pkg = new ZipPackage(_packagePath);
Console.WriteLine(NuGetResources.PushCommandCreatingPackage, pkg.Id, pkg.Version);
using (Stream pkgStream = pkg.GetStream()) {
gallery.CreatePackage(_apiKey, pkgStream);
}
Console.WriteLine(NuGetResources.PushCommandPackageCreated);
if (!CreateOnly) {
var cmd = new PublishCommand();
cmd.Console = Console;
cmd.Source = Source;
cmd.Arguments = new List<string> { pkg.Id, pkg.Version.ToString(), _apiKey };
cmd.Execute();
}
}
}
}
|
apache-2.0
|
C#
|
f6a9a8d213e69c23fa7469f4b3c0d284ee857343
|
Fix whitespace
|
spicypixel/cs-concurrency-kit,spicypixel/cs-concurrency-kit,spicypixel/cs-concurrency-kit
|
Source/SpicyPixel.Threading.Unity/SharedConcurrentBehaviour.cs
|
Source/SpicyPixel.Threading.Unity/SharedConcurrentBehaviour.cs
|
/*
Author: Aaron Oneal, http://aarononeal.info
Copyright (c) 2012 Spicy Pixel, http://spicypixel.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 UnityEngine;
using System.Collections;
using System.Threading.Tasks;
using SpicyPixel.Threading;
using SpicyPixel.Threading.Tasks;
using System;
namespace SpicyPixel.Threading
{
class SharedConcurrentBehaviour : ConcurrentBehaviour
{
static ConcurrentBehaviour sharedInstance;
internal static new ConcurrentBehaviour SharedInstance {
get {
if(sharedInstance == null)
sharedInstance = CreateSharedInstance();
return sharedInstance;
}
}
static ConcurrentBehaviour CreateSharedInstance() {
GameObject go = new GameObject("Shared Concurrency Kit Scheduler");
if (!Application.isEditor)
DontDestroyOnLoad(go);
go.hideFlags = HideFlags.HideAndDontSave;
var sharedInstance = go.AddComponent<SharedConcurrentBehaviour>();
AppDomain.CurrentDomain.DomainUnload += (sender, e) => {
if(sharedInstance != null)
sharedInstance.OnDomainUnload();
};
return sharedInstance;
}
//void OnApplicationQuit()
void OnDomainUnload()
{
if(gameObject != null) {
GameObject.DestroyImmediate(gameObject);
}
sharedInstance = null;
}
}
}
|
/*
Author: Aaron Oneal, http://aarononeal.info
Copyright (c) 2012 Spicy Pixel, http://spicypixel.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 UnityEngine;
using System.Collections;
using System.Threading.Tasks;
using SpicyPixel.Threading;
using SpicyPixel.Threading.Tasks;
using System;
namespace SpicyPixel.Threading
{
class SharedConcurrentBehaviour : ConcurrentBehaviour
{
static ConcurrentBehaviour sharedInstance;
internal static new ConcurrentBehaviour SharedInstance {
get {
if(sharedInstance == null)
sharedInstance = CreateSharedInstance();
return sharedInstance;
}
}
static ConcurrentBehaviour CreateSharedInstance() {
GameObject go = new GameObject("Shared Concurrency Kit Scheduler");
if (!Application.isEditor)
DontDestroyOnLoad(go);
go.hideFlags = HideFlags.HideAndDontSave;
var sharedInstance = go.AddComponent<SharedConcurrentBehaviour>();
AppDomain.CurrentDomain.DomainUnload += (sender, e) => {
if(sharedInstance != null)
sharedInstance.OnDomainUnload();
};
return sharedInstance;
}
//void OnApplicationQuit()
void OnDomainUnload()
{
if(gameObject != null) {
GameObject.DestroyImmediate(gameObject);
}
sharedInstance = null;
}
}
}
|
mit
|
C#
|
04d5c90fc4d887100b99a1a6a92a2d5aa20bb849
|
Comment on custom display option properties
|
bcemmett/SurveyMonkeyApi-v3,davek17/SurveyMonkeyApi-v3
|
SurveyMonkey/Containers/QuestionDisplayOptionsCustomOptions.cs
|
SurveyMonkey/Containers/QuestionDisplayOptionsCustomOptions.cs
|
using Newtonsoft.Json;
using System.Collections.Generic;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class QuestionDisplayOptionsCustomOptions
{
public List<string> OptionSet { get; set; }
public int StartingPosition { get; set; } //slider questions
public int StepSize { get; set; } //slider questions
public string Color { get; set; } //star rating questions
}
}
|
using Newtonsoft.Json;
using System.Collections.Generic;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class QuestionDisplayOptionsCustomOptions
{
public List<string> OptionSet { get; set; }
public int StartingPosition { get; set; }
public int StepSize { get; set; }
public string Color { get; set; }
}
}
|
mit
|
C#
|
3d856e7f604a61dbc382473dd3ad108008e8362f
|
Add GetHistory method
|
tsolarin/readline,tsolarin/readline
|
src/ReadLine/ReadLine.cs
|
src/ReadLine/ReadLine.cs
|
using System.Collections.Generic;
namespace System
{
public static class ReadLine
{
private static KeyHandler _keyHandler;
private static List<string> _history;
public static Func<string, int, string[]> AutoCompletionHandler { private get; set; }
static ReadLine()
{
_history = new List<string>();
}
public static void AddHistory(params string[] text) => _history.AddRange(text);
public static List<string> GetHistory() => _history;
public static void ClearHistory() => _history = new List<string>();
public static string Read()
{
_keyHandler = new KeyHandler(_history, AutoCompletionHandler);
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
_keyHandler.Handle(keyInfo);
keyInfo = Console.ReadKey(true);
}
Console.WriteLine();
string text = _keyHandler.Text;
_history.Add(text);
return text;
}
}
}
|
using System.Collections.Generic;
namespace System
{
public static class ReadLine
{
private static KeyHandler _keyHandler;
private static List<string> _history;
public static List<string> History
{
get
{
return _history;
}
}
public static Func<string, int, string[]> AutoCompletionHandler { private get; set; }
static ReadLine()
{
_history = new List<string>();
}
public static void AddHistory(params string[] text) => _history.AddRange(text);
public static void ClearHistory() => _history = new List<string>();
public static string Read()
{
_keyHandler = new KeyHandler(_history, AutoCompletionHandler);
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
_keyHandler.Handle(keyInfo);
keyInfo = Console.ReadKey(true);
}
Console.WriteLine();
string text = _keyHandler.Text;
_history.Add(text);
return text;
}
}
}
|
mit
|
C#
|
996466763b3a56644db6769f570f595e2b55b99d
|
Add comment to count word number.
|
AxeDotNet/AxePractice.CSharpViaTest
|
src/CSharpViaTest.Collections/30_MapReducePractices/CountNumberOfWordsInMultipleTextFiles.cs
|
src/CSharpViaTest.Collections/30_MapReducePractices/CountNumberOfWordsInMultipleTextFiles.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using CSharpViaTest.Collections.Helpers;
using Xunit;
namespace CSharpViaTest.Collections._30_MapReducePractices
{
[SuperEasy]
public class CountNumberOfWordsInMultipleTextFiles
{
#region Please modifies the code to pass the test
// You can add additional functions for readability and performance considerations.
static int CountNumberOfWords(IEnumerable<Stream> streams)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_count_number_of_words()
{
const int fileCount = 5;
const int wordsInEachFile = 10;
Stream[] streams = Enumerable
.Repeat(0, fileCount)
.Select(_ => TextStreamFactory.Create(wordsInEachFile))
.ToArray();
int count = CountNumberOfWords(streams);
Assert.Equal(fileCount * wordsInEachFile, count);
foreach (Stream stream in streams) { stream.Dispose(); }
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using CSharpViaTest.Collections.Helpers;
using Xunit;
namespace CSharpViaTest.Collections._30_MapReducePractices
{
[SuperEasy]
public class CountNumberOfWordsInMultipleTextFiles
{
#region Please modifies the code to pass the test
static int CountNumberOfWords(IEnumerable<Stream> streams)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_count_number_of_words()
{
const int fileCount = 5;
const int wordsInEachFile = 10;
Stream[] streams = Enumerable
.Repeat(0, fileCount)
.Select(_ => TextStreamFactory.Create(wordsInEachFile))
.ToArray();
int count = CountNumberOfWords(streams);
Assert.Equal(fileCount * wordsInEachFile, count);
foreach (Stream stream in streams) { stream.Dispose(); }
}
}
}
|
mit
|
C#
|
8b88083853a2f937fcb947a8248cf6642721bd14
|
Add total memory to cat indices response
|
gayancc/elasticsearch-net,starckgates/elasticsearch-net,LeoYao/elasticsearch-net,robertlyson/elasticsearch-net,tkirill/elasticsearch-net,KodrAus/elasticsearch-net,ststeiger/elasticsearch-net,CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,geofeedia/elasticsearch-net,cstlaurent/elasticsearch-net,ststeiger/elasticsearch-net,KodrAus/elasticsearch-net,geofeedia/elasticsearch-net,robrich/elasticsearch-net,robertlyson/elasticsearch-net,adam-mccoy/elasticsearch-net,DavidSSL/elasticsearch-net,junlapong/elasticsearch-net,cstlaurent/elasticsearch-net,RossLieberman/NEST,adam-mccoy/elasticsearch-net,robertlyson/elasticsearch-net,tkirill/elasticsearch-net,faisal00813/elasticsearch-net,wawrzyn/elasticsearch-net,wawrzyn/elasticsearch-net,tkirill/elasticsearch-net,SeanKilleen/elasticsearch-net,RossLieberman/NEST,abibell/elasticsearch-net,CSGOpenSource/elasticsearch-net,azubanov/elasticsearch-net,robrich/elasticsearch-net,starckgates/elasticsearch-net,UdiBen/elasticsearch-net,elastic/elasticsearch-net,adam-mccoy/elasticsearch-net,KodrAus/elasticsearch-net,abibell/elasticsearch-net,abibell/elasticsearch-net,cstlaurent/elasticsearch-net,azubanov/elasticsearch-net,jonyadamit/elasticsearch-net,junlapong/elasticsearch-net,azubanov/elasticsearch-net,TheFireCookie/elasticsearch-net,SeanKilleen/elasticsearch-net,TheFireCookie/elasticsearch-net,wawrzyn/elasticsearch-net,DavidSSL/elasticsearch-net,mac2000/elasticsearch-net,ststeiger/elasticsearch-net,faisal00813/elasticsearch-net,UdiBen/elasticsearch-net,starckgates/elasticsearch-net,UdiBen/elasticsearch-net,jonyadamit/elasticsearch-net,gayancc/elasticsearch-net,DavidSSL/elasticsearch-net,RossLieberman/NEST,gayancc/elasticsearch-net,geofeedia/elasticsearch-net,LeoYao/elasticsearch-net,SeanKilleen/elasticsearch-net,CSGOpenSource/elasticsearch-net,mac2000/elasticsearch-net,joehmchan/elasticsearch-net,LeoYao/elasticsearch-net,joehmchan/elasticsearch-net,TheFireCookie/elasticsearch-net,robrich/elasticsearch-net,faisal00813/elasticsearch-net,mac2000/elasticsearch-net,joehmchan/elasticsearch-net,jonyadamit/elasticsearch-net,junlapong/elasticsearch-net
|
src/Nest/Domain/Cat/CatIndicesRecord.cs
|
src/Nest/Domain/Cat/CatIndicesRecord.cs
|
using Newtonsoft.Json;
namespace Nest
{
[JsonObject]
public class CatIndicesRecord : ICatRecord
{
[JsonProperty("docs.count")]
public string DocsCount { get; set; }
[JsonProperty("docs.deleted")]
public string DocsDeleted { get; set; }
[JsonProperty("health")]
public string Health { get; set; }
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("pri")]
public string Primary { get; set; }
[JsonProperty("pri.store.size")]
public string PrimaryStoreSize { get; set; }
[JsonProperty("rep")]
public string Replica { get; set; }
[JsonProperty("store.size")]
public string StoreSize { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("tm")]
public string TotalMemory { get; set; }
}
}
|
using Newtonsoft.Json;
namespace Nest
{
[JsonObject]
public class CatIndicesRecord : ICatRecord
{
[JsonProperty("docs.count")]
public string DocsCount { get; set; }
[JsonProperty("docs.deleted")]
public string DocsDeleted { get; set; }
[JsonProperty("health")]
public string Health { get; set; }
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("pri")]
public string Primary { get; set; }
[JsonProperty("pri.store.size")]
public string PrimaryStoreSize { get; set; }
[JsonProperty("rep")]
public string Replica { get; set; }
[JsonProperty("store.size")]
public string StoreSize { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
}
}
|
apache-2.0
|
C#
|
ba59eec3f51b5e0b3cc747136064d3d1e3d680a3
|
Switch to version 1.3.0
|
rbouallou/Zebus,Abc-Arbitrage/Zebus,AtwooTM/Zebus,biarne-a/Zebus
|
src/SharedVersionInfo.cs
|
src/SharedVersionInfo.cs
|
using System.Reflection;
[assembly: AssemblyVersion("1.3.0")]
[assembly: AssemblyFileVersion("1.3.0")]
[assembly: AssemblyInformationalVersion("1.3.0")]
|
using System.Reflection;
[assembly: AssemblyVersion("1.3.0")]
[assembly: AssemblyFileVersion("1.3.0")]
[assembly: AssemblyInformationalVersion("1.3.0-new-subs01")]
|
mit
|
C#
|
df59caf8c188509d40eadf7ed2c8af923294ed38
|
Remove forced WebGL test code
|
HelloKitty/317refactor
|
src/Client/Rs317.Client.Unity/Platform/RsUnityPlatform.cs
|
src/Client/Rs317.Client.Unity/Platform/RsUnityPlatform.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace Rs317.Sharp
{
public static class RsUnityPlatform
{
public static bool isWebGLBuild => Application.platform == RuntimePlatform.WebGLPlayer;
public static bool isPlaystationBuild => Application.platform == RuntimePlatform.PS4 || Application.platform == RuntimePlatform.PS3;
public static bool isAndroidMobileBuild => Application.platform == RuntimePlatform.Android;
public static bool isInEditor => Application.isEditor;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace Rs317.Sharp
{
public static class RsUnityPlatform
{
public static bool isWebGLBuild => true;
public static bool isPlaystationBuild => Application.platform == RuntimePlatform.PS4 || Application.platform == RuntimePlatform.PS3;
public static bool isAndroidMobileBuild => Application.platform == RuntimePlatform.Android;
public static bool isInEditor => Application.isEditor;
}
}
|
mit
|
C#
|
78408818c17bcc50eb941ee211531e4f13725152
|
Add Insurance to Governance menu
|
croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/website-application
|
source/CroquetAustraliaWebsite.Application/app/Infrastructure/PublicNavigationBar.cs
|
source/CroquetAustraliaWebsite.Application/app/Infrastructure/PublicNavigationBar.cs
|
using System.Collections.Generic;
namespace CroquetAustraliaWebsite.Application.App.Infrastructure
{
public static class PublicNavigationBar
{
public static IEnumerable<NavigationItem> GetNavigationItems()
{
return new[]
{
new NavigationItem("Contact Us",
new NavigationItem("Office & Board", "~/governance/contact-us"),
new NavigationItem("Committees", "~/governance/contact-us#committees"),
new NavigationItem("Appointed Officers", "~/governance/contact-us#appointed-officers"),
new NavigationItem("State Associations", "~/governance/state-associations")),
new NavigationItem("Governance",
new NavigationItem("Background", "~/governance/background"),
new NavigationItem("Constitution, Regulations & Policies", "~/governance/constitution-regulations-and-policies"),
new NavigationItem("Members", "~/governance/members"),
new NavigationItem("Board Meeting Minutes", "~/governance/minutes/board-meeting-minutes"),
new NavigationItem("Insurance", "~/governance/insurance")),
new NavigationItem("Tournaments", "~/tournaments"),
new NavigationItem("Disciplines",
new NavigationItem("Association Croquet",
new NavigationItem("Coaching", "~/disciplines/association-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/association-croquet/refereeing")),
new NavigationItem("Golf Croquet",
new NavigationItem("Coaching", "~/disciplines/golf-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/golf-croquet/refereeing"),
new NavigationItem("Resources", "~/disciplines/golf-croquet/resources")))
};
}
}
}
|
using System.Collections.Generic;
namespace CroquetAustraliaWebsite.Application.App.Infrastructure
{
public static class PublicNavigationBar
{
public static IEnumerable<NavigationItem> GetNavigationItems()
{
return new[]
{
new NavigationItem("Contact Us",
new NavigationItem("Office & Board", "~/governance/contact-us"),
new NavigationItem("Committees", "~/governance/contact-us#committees"),
new NavigationItem("Appointed Officers", "~/governance/contact-us#appointed-officers"),
new NavigationItem("State Associations", "~/governance/state-associations")),
new NavigationItem("Governance",
new NavigationItem("Background", "~/governance/background"),
new NavigationItem("Constitution, Regulations & Policies", "~/governance/constitution-regulations-and-policies"),
new NavigationItem("Members", "~/governance/members"),
new NavigationItem("Board Meeting Minutes", "~/governance/minutes/board-meeting-minutes")),
new NavigationItem("Tournaments", "~/tournaments"),
new NavigationItem("Disciplines",
new NavigationItem("Association Croquet",
new NavigationItem("Coaching", "~/disciplines/association-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/association-croquet/refereeing")),
new NavigationItem("Golf Croquet",
new NavigationItem("Coaching", "~/disciplines/golf-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/golf-croquet/refereeing"),
new NavigationItem("Resources", "~/disciplines/golf-croquet/resources")))
};
}
}
}
|
mit
|
C#
|
903813cb4ee2e600b286a7cbb2f57054529191f4
|
Move method GetScheme to StringUtils and remove LinkParser
|
mysticmind/reversemarkdown-net
|
src/ReverseMarkdown/StringUtils.cs
|
src/ReverseMarkdown/StringUtils.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace ReverseMarkdown
{
public static class StringUtils
{
public static string Chomp(this string content)
{
return content.Trim().TrimEnd('\r', '\n');
}
public static IEnumerable<string> ReadLines(this string content)
{
string line;
using (var sr = new StringReader(content))
while ((line = sr.ReadLine()) != null)
yield return line;
}
/// <summary>
/// <para>Gets scheme for provided uri string to overcome different behavior between windows/linux. https://github.com/dotnet/corefx/issues/1745</para>
/// Assume http for url starting with //
/// <para>Assume file for url starting with /</para>
/// Otherwise give what <see cref="Uri.Scheme" /> gives us.
/// <para>If non parseable by Uri, return empty string. Will never return null</para>
/// </summary>
/// <returns></returns>
internal static string GetScheme(string url) {
var isValidUri = Uri.TryCreate(url, UriKind.Absolute, out Uri uri);
//IETF RFC 3986
if (Regex.IsMatch(url, "^//[^/]")) {
return "http";
}
//Unix style path
else if (Regex.IsMatch(url, "^/[^/]")) {
return "file";
}
else if (isValidUri) {
return uri.Scheme;
}
else {
return String.Empty;
}
}
}
}
|
using System.Collections.Generic;
using System.IO;
namespace ReverseMarkdown
{
public static class StringUtils
{
public static string Chomp(this string content)
{
return content.Trim().TrimEnd('\r', '\n');
}
public static IEnumerable<string> ReadLines(this string content)
{
string line;
using (var sr = new StringReader(content))
while ((line = sr.ReadLine()) != null)
yield return line;
}
}
}
|
mit
|
C#
|
69282294f3e414b4c93fdca6002b99c8f90f8998
|
Implement ProfileUpdate message, see #1.
|
DreamNetwork/Platform-Server,DreamNetwork/Platform-Server
|
src/platform/Networking/Messages/ProfileUpdateResponse.cs
|
src/platform/Networking/Messages/ProfileUpdateResponse.cs
|
using System;
using System.Collections.Generic;
namespace DreamNetwork.PlatformServer.Networking.Messages
{
[Message(3u << 16 | 1u, MessageDirection.ToClient)]
public class ProfileUpdateResponse : Message
{
public bool Success { get; set; }
public string[] FailedFields { get; set; }
}
[Message(3u << 16 | 0u, MessageDirection.ToClient)]
public class ProfileUpdate : Message
{
public Guid ClientGuid { get; set; }
public Dictionary<string, object> ProfileFields { get; set; }
}
}
|
namespace DreamNetwork.PlatformServer.Networking.Messages
{
[Message(3u << 16 | 1u, MessageDirection.ToClient)]
public class ProfileUpdateResponse : Message
{
public bool Success { get; set; }
public string[] FailedFields { get; set; }
}
}
|
agpl-3.0
|
C#
|
0bf38687683ff829d3a51e00525b1381a03b3d92
|
Fix drag and drop method signature bug
|
chrisblock/Bumblebee,Bumblebee/Bumblebee,toddmeinershagen/Bumblebee,toddmeinershagen/Bumblebee,Bumblebee/Bumblebee,chrisblock/Bumblebee,qchicoq/Bumblebee,kool79/Bumblebee,qchicoq/Bumblebee,kool79/Bumblebee
|
Bumblebee/Implementation/DragAction.cs
|
Bumblebee/Implementation/DragAction.cs
|
using System;
using Bumblebee.Interfaces;
namespace Bumblebee.Implementation
{
public class DragAction<TParent> where TParent : IBlock
{
private TParent Parent { get; set; }
private IDraggable Draggable { get; set; }
public DragAction(TParent parent, Func<TParent, IDraggable> getDraggable)
{
Parent = parent;
Draggable = getDraggable.Invoke(parent);
}
public TParent AndDrop(Func<TParent, IHasBackingElement> getDropzone)
{
PerformDragAndDrop(getDropzone);
return Parent.Session.CurrentBlock<TParent>();
}
public TCustomResult AndDrop<TCustomResult>(Func<TParent, IHasBackingElement> getDropzone) where TCustomResult : IBlock
{
PerformDragAndDrop(getDropzone);
return Parent.Session.CurrentBlock<TCustomResult>();
}
public TParent AndDrop(int x, int y)
{
PerformDragAndDrop(x, y);
return Parent.Session.CurrentBlock<TParent>();
}
public TCustomResult AndDrop<TCustomResult>(int x, int y) where TCustomResult : IBlock
{
PerformDragAndDrop(x, y);
return Parent.Session.CurrentBlock<TCustomResult>();
}
private void PerformDragAndDrop(Func<TParent, IHasBackingElement> getDropzone)
{
var dropzone = getDropzone.Invoke(Parent);
Draggable.GetDragAndDropPerformer().DragAndDrop(Draggable.Tag, dropzone.Tag);
}
private void PerformDragAndDrop(int x, int y)
{
Draggable.GetDragAndDropPerformer().DragAndDrop(Draggable.Tag, x, y);
}
}
}
|
using System;
using Bumblebee.Interfaces;
namespace Bumblebee.Implementation
{
public class DragAction<TParent> where TParent : IBlock
{
private TParent Parent { get; set; }
private IDraggable Draggable { get; set; }
public DragAction(TParent parent, Func<TParent, IDraggable> getDraggable)
{
Parent = parent;
Draggable = getDraggable.Invoke(parent);
}
public TParent AndDrop(Func<TParent, IBlock> getDropzone)
{
PerformDragAndDrop(getDropzone);
return Parent.Session.CurrentBlock<TParent>();
}
public TCustomResult AndDrop<TCustomResult>(Func<TParent, IHasBackingElement> getDropzone) where TCustomResult : IBlock
{
PerformDragAndDrop(getDropzone);
return Parent.Session.CurrentBlock<TCustomResult>();
}
public TParent AndDrop(int x, int y)
{
PerformDragAndDrop(x, y);
return Parent.Session.CurrentBlock<TParent>();
}
public TCustomResult AndDrop<TCustomResult>(int x, int y) where TCustomResult : IBlock
{
PerformDragAndDrop(x, y);
return Parent.Session.CurrentBlock<TCustomResult>();
}
private void PerformDragAndDrop(Func<TParent, IHasBackingElement> getDropzone)
{
var dropzone = getDropzone.Invoke(Parent);
Draggable.GetDragAndDropPerformer().DragAndDrop(Draggable.Tag, dropzone.Tag);
}
private void PerformDragAndDrop(int x, int y)
{
Draggable.GetDragAndDropPerformer().DragAndDrop(Draggable.Tag, x, y);
}
}
}
|
mit
|
C#
|
2f8c0cb098c1db580989ee069ad2e601e3333952
|
Add label sample that uses a link
|
iainx/xwt,directhex/xwt,cra0zy/xwt,hamekoz/xwt,mono/xwt,TheBrainTech/xwt,lytico/xwt,sevoku/xwt,mminns/xwt,antmicro/xwt,residuum/xwt,steffenWi/xwt,akrisiun/xwt,mminns/xwt,hwthomas/xwt
|
Samples/Samples/Labels.cs
|
Samples/Samples/Labels.cs
|
//
// Labels.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
namespace Samples
{
public class Labels: VBox
{
public Labels ()
{
Label la = new Label ("Simple label");
PackStart (la);
la = new Label ("Label with red background") {
BackgroundColor = new Xwt.Drawing.Color (1, 0, 0)
};
PackStart (la);
la = new Label ("Label with red background and blue foreground") {
BackgroundColor = new Xwt.Drawing.Color (1, 0, 0),
TextColor = new Xwt.Drawing.Color (0, 0, 1)
};
PackStart (la);
la = new Label ("A crazy long label text with a lots of content and information in it but fortunately it should appear wrapped");
la.Wrap = WrapMode.Word;
PackStart (la);
la = new Label ("Another Label with red background") {
BackgroundColor = new Xwt.Drawing.Color (1, 0, 0),
TextColor = new Xwt.Drawing.Color (0, 0, 1)
};
PackStart (la);
la = new Label () { Markup = "Label with <b>bold</b> and <span color='#ff0000'>red</span> text" };
PackStart (la);
la = new Label () { Markup = "Label with a <a href='http://xamarin.com'>link</a> to a web site." };
PackStart (la);
}
}
}
|
//
// Labels.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
namespace Samples
{
public class Labels: VBox
{
public Labels ()
{
Label la = new Label ("Simple label");
PackStart (la);
la = new Label ("Label with red background") {
BackgroundColor = new Xwt.Drawing.Color (1, 0, 0)
};
PackStart (la);
la = new Label ("Label with red background and blue foreground") {
BackgroundColor = new Xwt.Drawing.Color (1, 0, 0),
TextColor = new Xwt.Drawing.Color (0, 0, 1)
};
PackStart (la);
la = new Label ("A crazy long label text with a lots of content and information in it but fortunately it should appear wrapped");
la.Wrap = WrapMode.Word;
PackStart (la);
la = new Label ("Another Label with red background") {
BackgroundColor = new Xwt.Drawing.Color (1, 0, 0),
TextColor = new Xwt.Drawing.Color (0, 0, 1)
};
PackStart (la);
la = new Label () { Markup = "Label with <b>bold</b> and <span color='#ff0000'>red</span> text" };
PackStart (la);
}
}
}
|
mit
|
C#
|
af59b6f2c2bf21401c39bfaafb54dbbd5a062d50
|
Fix for serialization errors with Loadout events caused by game bug
|
DarkWanderer/DW.Inara.LogUploader
|
Interfaces/Events/ModuleEngineering.cs
|
Interfaces/Events/ModuleEngineering.cs
|
namespace DW.ELA.Interfaces.Events
{
using Newtonsoft.Json;
public class ModuleEngineering
{
[JsonProperty("Engineer")]
public string Engineer { get; set; }
[JsonProperty("EngineerID")]
public ulong EngineerId { get; set; }
[JsonProperty("BlueprintID")]
public ulong BlueprintId { get; set; }
[JsonProperty("BlueprintName")]
public string BlueprintName { get; set; }
[JsonProperty("Level")]
public short Level { get; set; }
[JsonProperty("Quality")]
public double Quality { get; set; }
[JsonProperty("Modifiers")]
public Modifier[] Modifiers { get; set; }
[JsonProperty("ExperimentalEffect")]
public string ExperimentalEffect { get; set; }
[JsonProperty("ExperimentalEffect_Localised")]
public string ExperimentalEffectLocalised { get; set; }
}
}
|
namespace DW.ELA.Interfaces.Events
{
using Newtonsoft.Json;
public class ModuleEngineering
{
[JsonProperty("Engineer")]
public string Engineer { get; set; }
[JsonProperty("EngineerID")]
public ulong EngineerId { get; set; }
[JsonProperty("BlueprintID")]
public long BlueprintId { get; set; }
[JsonProperty("BlueprintName")]
public string BlueprintName { get; set; }
[JsonProperty("Level")]
public short Level { get; set; }
[JsonProperty("Quality")]
public double Quality { get; set; }
[JsonProperty("Modifiers")]
public Modifier[] Modifiers { get; set; }
[JsonProperty("ExperimentalEffect")]
public string ExperimentalEffect { get; set; }
[JsonProperty("ExperimentalEffect_Localised")]
public string ExperimentalEffectLocalised { get; set; }
}
}
|
mit
|
C#
|
c578d296367d6949ce5df18546e72a5ee0dab8bd
|
Allow variable parameters in CompositeOperation constructor
|
MHeasell/Mappy,MHeasell/Mappy
|
Mappy/Operations/CompositeOperation.cs
|
Mappy/Operations/CompositeOperation.cs
|
namespace Mappy.Operations
{
using System.Collections.Generic;
using System.Linq;
public class CompositeOperation : IReplayableOperation
{
private readonly IEnumerable<IReplayableOperation> ops;
public CompositeOperation(IEnumerable<IReplayableOperation> ops)
{
this.ops = ops;
}
public CompositeOperation(params IReplayableOperation[] ops)
{
this.ops = ops;
}
public void Execute()
{
foreach (IReplayableOperation op in this.ops)
{
op.Execute();
}
}
public void Undo()
{
foreach (IReplayableOperation op in this.ops.Reverse())
{
op.Undo();
}
}
}
}
|
namespace Mappy.Operations
{
using System.Collections.Generic;
using System.Linq;
public class CompositeOperation : IReplayableOperation
{
private readonly IEnumerable<IReplayableOperation> ops;
public CompositeOperation(IReplayableOperation op1, IReplayableOperation op2)
: this(new[] { op1, op2 })
{
}
public CompositeOperation(IEnumerable<IReplayableOperation> ops)
{
this.ops = ops;
}
public void Execute()
{
foreach (IReplayableOperation op in this.ops)
{
op.Execute();
}
}
public void Undo()
{
foreach (IReplayableOperation op in this.ops.Reverse())
{
op.Undo();
}
}
}
}
|
mit
|
C#
|
0b66e5abc1d950512557316d5c0dfeefe31b2648
|
update TraceTransaction return type
|
Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum
|
src/Nethereum.Parity/RPC/Trace/TraceTransaction.cs
|
src/Nethereum.Parity/RPC/Trace/TraceTransaction.cs
|
using System.Threading.Tasks;
using Nethereum.JsonRpc.Client;
using Newtonsoft.Json.Linq;
namespace Nethereum.Parity.RPC.Trace
{
/// <Summary>
/// Returns all traces of given transaction
/// </Summary>
public class TraceTransaction : RpcRequestResponseHandler<JArray>, ITraceTransaction
{
public TraceTransaction(IClient client) : base(client, ApiMethods.trace_transaction.ToString())
{
}
public async Task<JArray> SendRequestAsync(string transactionHash, object id = null)
{
return await base.SendRequestAsync(id, transactionHash);
}
public RpcRequest BuildRequest(string transactionHash, object id = null)
{
return base.BuildRequest(id, transactionHash);
}
}
}
|
using System.Threading.Tasks;
using Nethereum.JsonRpc.Client;
using Newtonsoft.Json.Linq;
namespace Nethereum.Parity.RPC.Trace
{
/// <Summary>
/// Returns all traces of given transaction
/// </Summary>
public class TraceTransaction : RpcRequestResponseHandler<JObject>, ITraceTransaction
{
public TraceTransaction(IClient client) : base(client, ApiMethods.trace_transaction.ToString())
{
}
public async Task<JObject> SendRequestAsync(string transactionHash, object id = null)
{
return await base.SendRequestAsync(id, transactionHash);
}
public RpcRequest BuildRequest(string transactionHash, object id = null)
{
return base.BuildRequest(id, transactionHash);
}
}
}
|
mit
|
C#
|
bca0ce6f764ebed35c5018bf14ada179159c7b8b
|
Document model updated as per save document changes.
|
aykanatm/ProjectMarkdown
|
ProjectMarkdown/Model/DocumentModel.cs
|
ProjectMarkdown/Model/DocumentModel.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
using ProjectMarkdown.Annotations;
namespace ProjectMarkdown.Model
{
public class DocumentModel : INotifyPropertyChanged
{
public DocumentMetadata Metadata
{
get { return _metadata; }
set
{
if (Equals(value, _metadata)) return;
_metadata = value;
OnPropertyChanged(nameof(Metadata));
}
}
public DocumentMarkdown Markdown
{
get { return _markdown; }
set
{
if (Equals(value, _markdown)) return;
_markdown = value;
OnPropertyChanged(nameof(Markdown));
}
}
public DocumentHtml Html
{
get { return _html; }
set
{
if (Equals(value, _html)) return;
_html = value;
OnPropertyChanged(nameof(Html));
}
}
private DocumentMetadata _metadata;
private DocumentMarkdown _markdown;
private DocumentHtml _html;
public event PropertyChangedEventHandler PropertyChanged;
public DocumentModel(string documentName)
{
Metadata = new DocumentMetadata(documentName);
Markdown = new DocumentMarkdown("");
Html = new DocumentHtml("".ToUri());
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
using ProjectMarkdown.Annotations;
namespace ProjectMarkdown.Model
{
public class DocumentModel : INotifyPropertyChanged
{
private string _header;
private string _markdownText;
private Uri _source;
public string Header
{
get { return _header; }
set
{
if (value == _header) return;
_header = value;
OnPropertyChanged(nameof(Header));
}
}
public string MarkdownText
{
get { return _markdownText; }
set
{
if (value == _markdownText) return;
_markdownText = value;
OnPropertyChanged(nameof(MarkdownText));
}
}
public Uri Source
{
get { return _source; }
set
{
if (Equals(value, _source)) return;
_source = value;
OnPropertyChanged(nameof(Source));
}
}
public string MarkdownPath { get; set; }
public string HtmlPath { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public DocumentModel(string documentName)
{
Header = documentName;
MarkdownText = "";
Source = "".ToUri();
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
mit
|
C#
|
dcd8cfaf003c2521ee377feec39cf6bd83ee105f
|
Update Fun.cs
|
divega/UdfCodeFirstSample
|
UdfCodeFirstSample/Fun.cs
|
UdfCodeFirstSample/Fun.cs
|
using System;
using System.Data.Entity;
namespace UdfCodeFirstSample
{
public static class Fun
{
[DbFunction("CodeFirstDatabaseSchema", "GetAge")]
public static int? GetAge(DateTime? birthDate)
{
// this in-memory implementation will not be invoked when working on LINQ to Entities
// see Migrations for the T-SQL definition of the function
int? age = null;
if (birthDate.HasValue)
{
DateTime today = DateTime.Today;
age = today.Year - birthDate.Value.Year;
if (birthDate > today.AddYears(-age.Value))
{
age--;
}
}
return age;
}
}
}
|
using System;
using System.Data.Entity;
namespace UdfCodeFirstSample
{
public static class Fun
{
[DbFunction("CodeFirstDatabaseSchema", "GetAge")]
public static int? GetAge(DateTime? birthDate)
{
// this in-memory implementation will not be invoked when working on LINQ to Entities
int? age = null;
if (birthDate.HasValue)
{
DateTime today = DateTime.Today;
age = today.Year - birthDate.Value.Year;
if (birthDate > today.AddYears(-age.Value))
{
age--;
}
}
return age;
}
}
}
|
apache-2.0
|
C#
|
55d226fa6fb5d2bd448aece39aae17f3624d7851
|
добавить ItemConverterType для свойства ButtonActions
|
vknet/vk,vknet/vk
|
VkNet/Model/ClientInfo.cs
|
VkNet/Model/ClientInfo.cs
|
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using VkNet.Enums;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.GroupUpdate;
using VkNet.Utils;
using VkNet.Utils.JsonConverter;
namespace VkNet.Model
{
/// <summary>
/// Информация о доступных пользователю функциях.
/// </summary>
[Serializable]
public class ClientInfo
{
/// <summary>
/// Массив кнопок, которые поддерживает клиент.
/// </summary>
[JsonProperty("button_actions", ItemConverterType = typeof(SafetyEnumJsonConverter))]
public IEnumerable<KeyboardButtonActionType> ButtonActions { get; set; }
/// <summary>
/// Поддерживается ли клавиатура ботов клиентом.
/// </summary>
[JsonProperty("keyboard")]
public bool Keyboard { get; set; }
/// <summary>
/// Поддерживается ли inline-клавиатура ботов клиентом.
/// </summary>
[JsonProperty("inline_keyboard")]
public bool InlineKeyboard { get; set; }
/// <summary>
/// Id используемого языка.
/// </summary>
[JsonProperty("lang_id")]
public Language LangId { get; set; }
#region Методы
/// <summary>
/// </summary>
/// <param name="response"> </param>
/// <returns> </returns>
public static ClientInfo FromJson(VkResponse response)
{
return new ClientInfo
{
ButtonActions = response["button_actions"].ToReadOnlyCollectionOf<KeyboardButtonActionType>(x => x),
Keyboard = response["keyboard"],
InlineKeyboard = response["inline_keyboard"],
LangId = response["lang_id"].ToEnum<Language>()
};
}
/// <summary>
/// Преобразование класса <see cref="ClientInfo" /> в <see cref="VkParameters" />
/// </summary>
/// <param name="response"> Ответ сервера. </param>
/// <returns>Результат преобразования в <see cref="MessageNew" /></returns>
public static implicit operator ClientInfo(VkResponse response)
{
if (response == null)
{
return null;
}
return response.HasToken()
? FromJson(response)
: null;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using VkNet.Enums;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.GroupUpdate;
using VkNet.Utils;
namespace VkNet.Model
{
/// <summary>
/// Информация о доступных пользователю функциях.
/// </summary>
[Serializable]
public class ClientInfo
{
/// <summary>
/// Массив кнопок, которые поддерживает клиент.
/// </summary>
[JsonProperty("button_actions")]
public IEnumerable<KeyboardButtonActionType> ButtonActions { get; set; }
/// <summary>
/// Поддерживается ли клавиатура ботов клиентом.
/// </summary>
[JsonProperty("keyboard")]
public bool Keyboard { get; set; }
/// <summary>
/// Поддерживается ли inline-клавиатура ботов клиентом.
/// </summary>
[JsonProperty("inline_keyboard")]
public bool InlineKeyboard { get; set; }
/// <summary>
/// Id используемого языка.
/// </summary>
[JsonProperty("lang_id")]
public Language LangId { get; set; }
#region Методы
/// <summary>
/// </summary>
/// <param name="response"> </param>
/// <returns> </returns>
public static ClientInfo FromJson(VkResponse response)
{
return new ClientInfo
{
ButtonActions = response["button_actions"].ToReadOnlyCollectionOf<KeyboardButtonActionType>(x => x),
Keyboard = response["keyboard"],
InlineKeyboard = response["inline_keyboard"],
LangId = response["lang_id"].ToEnum<Language>()
};
}
/// <summary>
/// Преобразование класса <see cref="ClientInfo" /> в <see cref="VkParameters" />
/// </summary>
/// <param name="response"> Ответ сервера. </param>
/// <returns>Результат преобразования в <see cref="MessageNew" /></returns>
public static implicit operator ClientInfo(VkResponse response)
{
if (response == null)
{
return null;
}
return response.HasToken()
? FromJson(response)
: null;
}
#endregion
}
}
|
mit
|
C#
|
5761a9bd5f1a285d60b365e07f0ed8c598058dad
|
Check for nulls in Paragraphs members too.
|
PenguinF/sandra-three
|
Sandra.UI.WF/Storage/SettingComment.cs
|
Sandra.UI.WF/Storage/SettingComment.cs
|
/*********************************************************************************
* SettingComment.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sandra.UI.WF.Storage
{
/// <summary>
/// Represents a comment in a setting file.
/// </summary>
public class SettingComment
{
public IEnumerable<string> Paragraphs { get; }
/// <summary>
/// Initializes a new instance of <see cref="SettingComment"/>.
/// </summary>
/// <exception cref="ArgumentNullException">
/// <paramref name="text"/> is null.
/// </exception>
public SettingComment(string text)
{
if (text == null) throw new ArgumentNullException(nameof(text));
Paragraphs = new string[] { text };
}
/// <summary>
/// Initializes a new instance of <see cref="SettingComment"/>.
/// </summary>
/// <exception cref="ArgumentNullException">
/// <paramref name="paragraphs"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// One or more strings in <paramref name="paragraphs"/> are null.
/// </exception>
public SettingComment(params string[] paragraphs)
{
if (paragraphs == null) throw new ArgumentNullException(nameof(paragraphs));
if (paragraphs.Any(x => x == null)) throw new ArgumentException("At least one paragraph is null.", nameof(paragraphs));
Paragraphs = paragraphs;
}
/// <summary>
/// Initializes a new instance of <see cref="SettingComment"/>.
/// </summary>
/// <exception cref="ArgumentNullException">
/// <paramref name="paragraphs"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// One or more strings in <paramref name="paragraphs"/> are null.
/// </exception>
public SettingComment(IEnumerable<string> paragraphs)
{
if (paragraphs == null) throw new ArgumentNullException(nameof(paragraphs));
if (paragraphs.Any(x => x == null)) throw new ArgumentException("At least one paragraph is null.", nameof(paragraphs));
Paragraphs = paragraphs;
}
}
}
|
/*********************************************************************************
* SettingComment.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
using System;
using System.Collections.Generic;
namespace Sandra.UI.WF.Storage
{
/// <summary>
/// Represents a comment in a setting file.
/// </summary>
public class SettingComment
{
public IEnumerable<string> Paragraphs { get; }
/// <summary>
/// Initializes a new instance of <see cref="SettingComment"/>.
/// </summary>
/// <exception cref="ArgumentNullException">
/// <paramref name="text"/> is null.
/// </exception>
public SettingComment(string text)
{
if (text == null) throw new ArgumentNullException(nameof(text));
Paragraphs = new string[] { text };
}
/// <summary>
/// Initializes a new instance of <see cref="SettingComment"/>.
/// </summary>
/// <exception cref="ArgumentNullException">
/// <paramref name="paragraphs"/> is null.
/// </exception>
public SettingComment(params string[] paragraphs)
{
if (paragraphs == null) throw new ArgumentNullException(nameof(paragraphs));
Paragraphs = paragraphs;
}
/// <summary>
/// Initializes a new instance of <see cref="SettingComment"/>.
/// </summary>
/// <exception cref="ArgumentNullException">
/// <paramref name="paragraphs"/> is null.
/// </exception>
public SettingComment(IEnumerable<string> paragraphs)
{
if (paragraphs == null) throw new ArgumentNullException(nameof(paragraphs));
Paragraphs = paragraphs;
}
}
}
|
apache-2.0
|
C#
|
d32ce420759697c03b38c352ec9884cc2d81c2c5
|
Update CompositionRootSetup.cs
|
tiksn/TIKSN-Exchange
|
TIKSN.Exchange/CompositionRootSetup.cs
|
TIKSN.Exchange/CompositionRootSetup.cs
|
using Autofac;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using TIKSN.Data;
using TIKSN.Data.LiteDB;
using TIKSN.DependencyInjection;
using TIKSN.Exchange.Commands;
using TIKSN.Finance.ForeignExchange;
using TIKSN.Finance.ForeignExchange.Data;
using TIKSN.Finance.ForeignExchange.Data.LiteDB;
namespace TIKSN.Exchange
{
public class CompositionRootSetup : AutofacCompositionRootSetupBase
{
public CompositionRootSetup(IConfigurationRoot configurationRoot) : base(configurationRoot)
{
}
protected override void ConfigureContainerBuilder(ContainerBuilder builder)
{
builder.RegisterType<ExchangeRateRepository>().As<IExchangeRateRepository>().InstancePerLifetimeScope();
builder.RegisterType<ForeignExchangeRepository>().As<IForeignExchangeRepository>().InstancePerLifetimeScope();
builder.RegisterType<DatabaseProvider>().As<ILiteDbDatabaseProvider>().SingleInstance();
builder.RegisterType<UnitOfWorkFactory>().As<IUnitOfWorkFactory>().InstancePerLifetimeScope();
builder.RegisterType<ExchangeRateService>().As<IExchangeRateService>().InstancePerLifetimeScope();
builder.RegisterType<TextLocalizer>().As<IStringLocalizer>().SingleInstance();
}
protected override void ConfigureOptions(IServiceCollection services, IConfigurationRoot configuration)
{
}
protected override void ConfigureServices(IServiceCollection services)
{
}
}
}
|
using Autofac;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using TIKSN.Data;
using TIKSN.DependencyInjection;
using TIKSN.Finance.ForeignExchange;
using TIKSN.Finance.ForeignExchange.Data;
using TIKSN.Finance.ForeignExchange.Data.LiteDB;
namespace TIKSN.Exchange
{
public class CompositionRootSetup : AutofacCompositionRootSetupBase
{
public CompositionRootSetup(IConfigurationRoot configurationRoot) : base(configurationRoot)
{
}
protected override void ConfigureContainerBuilder(ContainerBuilder builder)
{
builder.RegisterType<ExchangeRateRepository>().As<IExchangeRateRepository>().InstancePerLifetimeScope();
builder.RegisterType<ForeignExchangeRepository>().As<IForeignExchangeRepository>().InstancePerLifetimeScope();
builder.RegisterType<UnitOfWorkFactory>().As<IUnitOfWorkFactory>().InstancePerLifetimeScope();
builder.RegisterType<ExchangeRateService>().As<IExchangeRateService>().InstancePerLifetimeScope();
builder.RegisterType<TextLocalizer>().As<IStringLocalizer>().SingleInstance();
}
protected override void ConfigureOptions(IServiceCollection services, IConfigurationRoot configuration)
{
}
protected override void ConfigureServices(IServiceCollection services)
{
}
}
}
|
mit
|
C#
|
e4e56bc668d7db933cbf680da34f23ce12796766
|
add credentials
|
Alex141/CalcBinding
|
CalcBinding/Properties/AssemblyInfo.cs
|
CalcBinding/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("CalcBinding")]
[assembly: AssemblyDescription("Advanced binding markup extension")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Alexander Zinchenko")]
[assembly: AssemblyProduct("CalcBinding")]
[assembly: AssemblyCopyright("Copyright © Alexander Zinchenko 2014-2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2f50352b-c0e5-4814-9e09-246cbc1c83b8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.3.0.0")]
[assembly: AssemblyFileVersion("2.3.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CalcBinding")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CalcBinding")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2f50352b-c0e5-4814-9e09-246cbc1c83b8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.3.0.0")]
[assembly: AssemblyFileVersion("2.3.0.0")]
|
apache-2.0
|
C#
|
60fda840f4d8b2aae8b0c9fb36a6fb917c5eb3ca
|
Change CssSelector to a class
|
Carbon/Css
|
src/Carbon.Css/Model/CssSelector.cs
|
src/Carbon.Css/Model/CssSelector.cs
|
using System.Collections;
using System.Collections.Generic;
using Carbon.Css.Parser;
namespace Carbon.Css
{
public class CssSelector : IEnumerable<CssSequence>
{
private readonly IReadOnlyList<CssSequence> items; // comma seperated
public CssSelector(IReadOnlyList<CssSequence> items)
{
this.items = items;
}
public int Count => items.Count;
public CssSequence this[int index] => items[index];
public bool Contains(NodeKind kind)
{
foreach (var part in items)
{
if (part.Contains(kind)) return true;
}
return false;
}
public override string ToString()
{
return string.Join(", ", items);
}
public static CssSelector Parse(string text)
{
using (var parser = new CssParser(text))
{
return parser.ReadSelector();
}
}
#region IEnumerator
public IEnumerator<CssSequence> GetEnumerator() => items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => items.GetEnumerator();
#endregion
}
}
// a:hover
// #id
// .className
// .className, .anotherName (Multiselector or group)
|
using System.Collections;
using System.Collections.Generic;
using Carbon.Css.Parser;
namespace Carbon.Css
{
public readonly struct CssSelector : IEnumerable<CssSequence>
{
private readonly IReadOnlyList<CssSequence> items; // comma seperated
public CssSelector(IReadOnlyList<CssSequence> items)
{
this.items = items;
}
public int Count => items.Count;
public CssSequence this[int index] => items[index];
public bool Contains(NodeKind kind)
{
foreach (var part in items)
{
if (part.Contains(kind)) return true;
}
return false;
}
public override string ToString()
{
return string.Join(", ", items);
}
public static CssSelector Parse(string text)
{
using (var parser = new CssParser(text))
{
return parser.ReadSelector();
}
}
#region IEnumerator
public IEnumerator<CssSequence> GetEnumerator() => items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => items.GetEnumerator();
#endregion
}
}
// a:hover
// #id
// .className
// .className, .anotherName (Multiselector or group)
|
mit
|
C#
|
4d576aeccb8c8b5047ca389e05059425e38e88c9
|
select Ignore over Explicit because the Explicit test is still being run
|
fluffynuts/NExpect,fluffynuts/NExpect,cobussmit74/NExpect,cobussmit74/NExpect
|
src/CoreConsumer/TestConsumption.cs
|
src/CoreConsumer/TestConsumption.cs
|
using NUnit.Framework;
using NExpect;
using static NExpect.Expectations;
namespace CoreConsumer
{
[TestFixture]
public class TestConsumption
{
[Test]
public void ShouldBeAbleToExpect_Pass()
{
// Arrange
// Pre-Assert
// Act
PerformExpectation(1, 1);
// Assert
}
[Test]
[Ignore("Run to see stack trace")]
public void ShouldBeAbleToExpect_Fail()
{
// Arrange
// Pre-Assert
// Act
PerformExpectation(1, 2);
// Assert
}
private static void PerformExpectation(int left, int right)
{
Expect(left).To.Equal(right);
}
}
}
|
using NUnit.Framework;
using NExpect;
using static NExpect.Expectations;
namespace CoreConsumer
{
[TestFixture]
public class TestConsumption
{
[Test]
public void ShouldBeAbleToExpect_Pass()
{
// Arrange
// Pre-Assert
// Act
PerformExpectation(1, 1);
// Assert
}
[Test]
[Explicit("Run to see stack trace")]
public void ShouldBeAbleToExpect_Fail()
{
// Arrange
// Pre-Assert
// Act
PerformExpectation(1, 2);
// Assert
}
private static void PerformExpectation(int left, int right)
{
Expect(left).To.Equal(right);
}
}
}
|
bsd-3-clause
|
C#
|
da4998c6489e232e09223ef3f4c3573af3be491e
|
Create 8.3.2 release
|
dontjee/hyde
|
src/Hyde/Properties/AssemblyInfo.cs
|
src/Hyde/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( "TechSmith.Hyde" )]
[assembly: AssemblyDescription( "Object to Entity mapper for Windows Azure" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "TechSmith Corporation" )]
[assembly: AssemblyProduct( "TechSmith.Hyde" )]
[assembly: AssemblyCopyright( "Copyright © TechSmith Corporation 2015" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible( false )]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid( "11ec1efe-84f9-4d94-8c4f-e85432258e69" )]
// 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( "8.3.2.0" )]
[assembly: AssemblyFileVersion( "8.3.2.0" )]
[assembly: InternalsVisibleTo( "TechSmith.Hyde.Test" )]
|
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( "TechSmith.Hyde" )]
[assembly: AssemblyDescription( "Object to Entity mapper for Windows Azure" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "TechSmith Corporation" )]
[assembly: AssemblyProduct( "TechSmith.Hyde" )]
[assembly: AssemblyCopyright( "Copyright © TechSmith Corporation 2015" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible( false )]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid( "11ec1efe-84f9-4d94-8c4f-e85432258e69" )]
// 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( "8.3.1.0" )]
[assembly: AssemblyFileVersion( "8.3.1.0" )]
[assembly: InternalsVisibleTo( "TechSmith.Hyde.Test" )]
|
bsd-3-clause
|
C#
|
ebef439780030c7c151ac8107c89a2452f3282ca
|
remove dead code
|
Pondidum/Stronk,Pondidum/Stronk
|
src/Stronk.Tests/ExtensionsTests.cs
|
src/Stronk.Tests/ExtensionsTests.cs
|
using Shouldly;
using System;
using System.Collections.Generic;
using System.Linq;
using Stronk.ValueConversion;
using Xunit;
namespace Stronk.Tests
{
public class ExtensionsTests
{
private readonly List<IValueConverter> _valueConverters;
public ExtensionsTests()
{
_valueConverters = Default.ValueConverters.ToList();
}
[Fact]
public void When_a_value_converter_is_added()
{
_valueConverters.Add(new DtoValueConverter());
_valueConverters.Last().ShouldBeOfType<DtoValueConverter>();
}
[Fact]
public void When_selecting_type_names_of_instances()
{
var types = new IValueConverter[]
{
new LambdaValueConverter<Uri>(x => new Uri(x)),
new LambdaValueConverter<Guid>(x => Guid.Parse(x)),
new CsvValueConverter(),
new LambdaValueConverter<List<Dictionary<string, int>>>(x => new List<Dictionary<string, int>>())
};
types.SelectTypeNames().ShouldBe(new []
{
"LambdaValueConverter<Uri>",
"LambdaValueConverter<Guid>",
"CsvValueConverter",
"LambdaValueConverter<List<Dictionary<String, Int32>>>"
});
}
[Fact]
public void When_selecting_type_names_of_types()
{
var types = new[]
{
typeof(LambdaValueConverter<Uri>),
typeof(LambdaValueConverter<Guid>),
typeof(CsvValueConverter),
typeof(LambdaValueConverter<List<Dictionary<string, int>>>)
};
types.SelectTypeNames().ShouldBe(new []
{
"LambdaValueConverter<Uri>",
"LambdaValueConverter<Guid>",
"CsvValueConverter",
"LambdaValueConverter<List<Dictionary<String, Int32>>>"
});
}
private class Dto { }
private class DtoValueConverter : IValueConverter
{
public bool CanMap(Type target) => target == typeof(Dto);
public object Map(ValueConverterArgs e) => new Dto();
}
}
}
|
using Shouldly;
using System;
using System.Collections.Generic;
using System.Linq;
using Stronk.PropertyMappers;
using Stronk.PropertyWriters;
using Stronk.ValueConversion;
using Xunit;
namespace Stronk.Tests
{
public class ExtensionsTests
{
private readonly List<IValueConverter> _valueConverters;
public ExtensionsTests()
{
_valueConverters = Default.ValueConverters.ToList();
}
[Fact]
public void When_a_value_converter_is_added()
{
_valueConverters.Add(new DtoValueConverter());
_valueConverters.Last().ShouldBeOfType<DtoValueConverter>();
}
[Fact]
public void When_selecting_type_names_of_instances()
{
var types = new IValueConverter[]
{
new LambdaValueConverter<Uri>(x => new Uri(x)),
new LambdaValueConverter<Guid>(x => Guid.Parse(x)),
new CsvValueConverter(),
new LambdaValueConverter<List<Dictionary<string, int>>>(x => new List<Dictionary<string, int>>())
};
types.SelectTypeNames().ShouldBe(new []
{
"LambdaValueConverter<Uri>",
"LambdaValueConverter<Guid>",
"CsvValueConverter",
"LambdaValueConverter<List<Dictionary<String, Int32>>>"
});
}
[Fact]
public void When_selecting_type_names_of_types()
{
var types = new[]
{
typeof(LambdaValueConverter<Uri>),
typeof(LambdaValueConverter<Guid>),
typeof(CsvValueConverter),
typeof(LambdaValueConverter<List<Dictionary<string, int>>>)
};
types.SelectTypeNames().ShouldBe(new []
{
"LambdaValueConverter<Uri>",
"LambdaValueConverter<Guid>",
"CsvValueConverter",
"LambdaValueConverter<List<Dictionary<String, Int32>>>"
});
}
private static void InsertIndexShouldBeBefore<T>(IEnumerable<T> collection, Type search, Type inserted)
{
var converters = collection.Select(c => c.GetType()).ToList();
var searchIndex = converters.IndexOf(search);
var insertIndex = converters.IndexOf(inserted);
insertIndex.ShouldBe(searchIndex - 1);
}
private static void InsertIndexShouldBeAfter<T>(IEnumerable<T> collection, Type search, Type inserted)
{
var converters = collection.Select(c => c.GetType()).ToList();
var searchIndex = converters.IndexOf(search);
var insertIndex = converters.IndexOf(inserted);
insertIndex.ShouldBe(searchIndex + 1);
}
private class Dto { }
private class DtoValueConverter : IValueConverter
{
public bool CanMap(Type target) => target == typeof(Dto);
public object Map(ValueConverterArgs e) => new Dto();
}
private class DtoPropertyMapper : IPropertyMapper
{
public string Select(PropertyMapperArgs args) => "dto";
}
private class DtoPropertyWriter : IPropertyWriter
{
public IEnumerable<PropertyDescriptor> Select(PropertyWriterArgs args) => Enumerable.Empty<PropertyDescriptor>();
}
private class UnusedPropertyMapper : IPropertyMapper
{
public string Select(PropertyMapperArgs args)
{
throw new NotSupportedException();
}
}
private class UnusedPropertyWriter : IPropertyWriter
{
public IEnumerable<PropertyDescriptor> Select(PropertyWriterArgs args)
{
throw new NotSupportedException();
}
}
}
}
|
lgpl-2.1
|
C#
|
d2b67f160692fb8421ec30083e10a5f558f70c92
|
Add HiddenAt property in TraktSyncSeasonsLastActivities
|
henrikfroehling/TraktApiSharp
|
Source/Lib/TraktApiSharp/Objects/Get/Syncs/Activities/TraktSyncSeasonsLastActivities.cs
|
Source/Lib/TraktApiSharp/Objects/Get/Syncs/Activities/TraktSyncSeasonsLastActivities.cs
|
namespace TraktApiSharp.Objects.Get.Syncs.Activities
{
using Newtonsoft.Json;
using System;
/// <summary>A collection of UTC datetimes of last activities for seasons.</summary>
public class TraktSyncSeasonsLastActivities
{
/// <summary>Gets or sets the UTC datetime, when a season was lastly rated.</summary>
[JsonProperty(PropertyName = "rated_at")]
public DateTime? RatedAt { get; set; }
/// <summary>Gets or sets the UTC datetime, when a season was lastly added to the watchlist.</summary>
[JsonProperty(PropertyName = "watchlisted_at")]
public DateTime? WatchlistedAt { get; set; }
/// <summary>Gets or sets the UTC datetime, when a season was lastly commented.</summary>
[JsonProperty(PropertyName = "commented_at")]
public DateTime? CommentedAt { get; set; }
/// <summary>Gets or sets the UTC datetime, when a season was lastly hidden.</summary>
[JsonProperty(PropertyName = "hidden_at")]
public DateTime? HiddenAt { get; set; }
}
}
|
namespace TraktApiSharp.Objects.Get.Syncs.Activities
{
using Newtonsoft.Json;
using System;
/// <summary>A collection of UTC datetimes of last activities for seasons.</summary>
public class TraktSyncSeasonsLastActivities
{
/// <summary>Gets or sets the UTC datetime, when a season was lastly rated.</summary>
[JsonProperty(PropertyName = "rated_at")]
public DateTime? RatedAt { get; set; }
/// <summary>Gets or sets the UTC datetime, when a season was lastly added to the watchlist.</summary>
[JsonProperty(PropertyName = "watchlisted_at")]
public DateTime? WatchlistedAt { get; set; }
/// <summary>Gets or sets the UTC datetime, when a season was lastly commented.</summary>
[JsonProperty(PropertyName = "commented_at")]
public DateTime? CommentedAt { get; set; }
}
}
|
mit
|
C#
|
3a475ecdac81d42954a3d72560456d6c7486c84c
|
revert AsyncAspectTests.cs
|
AspectCore/Abstractions,AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Lite
|
core/test/AspectCore.Tests/Injector/AsyncBlockTest.cs
|
core/test/AspectCore.Tests/Injector/AsyncBlockTest.cs
|
using AspectCore.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace AspectCore.Tests.Injector
{
public class Intercept1 : AbstractInterceptorAttribute
{
public override Task Invoke(AspectContext context, AspectDelegate next)
{
context.Parameters[0] = "lemon";
return context.Invoke(next);
}
}
public interface IService1
{
Task<string> GetValue(string val);
}
public class Service1 : IService1
{
[Intercept1]
public async Task<string> GetValue(string val)
{
await Task.Delay(3000);
return val;
}
}
public class AsyncBlockTest : InjectorTestBase
{
[Fact]
public void AsyncBlock()
{
var builder = new ProxyGeneratorBuilder();
builder.Configure(_ => { });
var proxyGenerator = builder.Build();
var proxy = proxyGenerator.CreateInterfaceProxy<IService1, Service1>();
// IService proxy = new Service();
var startTime = DateTime.Now;
Console.WriteLine($"{startTime}:start");
var val = proxy.GetValue("le");
var endTime = DateTime.Now;
Assert.True((endTime - startTime).TotalSeconds < 2);
Console.WriteLine($"{endTime}:should return immediately");
Console.WriteLine($"{DateTime.Now}:{val.Result}");
}
}
}
|
using AspectCore.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace AspectCore.Tests.Injector
{
public class Intercept1 : AbstractInterceptorAttribute
{
public override Task Invoke(AspectContext context, AspectDelegate next)
{
context.Parameters[0] = "lemon";
return context.Invoke(next);
}
}
public interface IService1
{
Task<string> GetValue(string val);
}
public class Service1 : IService1
{
[Intercept1]
public async Task<string> GetValue(string val)
{
await Task.Delay(3000);
return val;
}
}
public class AsyncBlockTest : InjectorTestBase
{
private readonly ITestOutputHelper _output;
public AsyncBlockTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void AsyncBlock()
{
var builder = new ProxyGeneratorBuilder();
builder.Configure(_ => { });
var proxyGenerator = builder.Build();
var proxy = proxyGenerator.CreateInterfaceProxy<IService1, Service1>();
// IService proxy = new Service();
var startTime = DateTime.Now;
_output.WriteLine($"{startTime}:start");
var val = proxy.GetValue("le");
var endTime = DateTime.Now;
Assert.True((endTime - startTime).TotalSeconds < 2);
_output.WriteLine($"{endTime}:should return immediately");
var result = val.Result;
var resultTime = DateTime.Now;
_output.WriteLine($"{resultTime}:{result}");
Assert.True((resultTime - startTime).TotalSeconds > 2);
}
}
}
|
mit
|
C#
|
b47ced8c583d88cbec7fd5c89adc4f58ca3254b0
|
Fix failing test
|
naoey/osu,naoey/osu,smoogipooo/osu,NeoAdonis/osu,naoey/osu,UselessToucan/osu,johnneijzen/osu,DrabWeb/osu,EVAST9919/osu,EVAST9919/osu,smoogipoo/osu,ZLima12/osu,ppy/osu,johnneijzen/osu,2yangk23/osu,DrabWeb/osu,peppy/osu-new,ZLima12/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,2yangk23/osu,peppy/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,DrabWeb/osu,ppy/osu,ppy/osu,smoogipoo/osu
|
osu.Game.Rulesets.Mania.Tests/ManiaDifficultyCalculatorTest.cs
|
osu.Game.Rulesets.Mania.Tests/ManiaDifficultyCalculatorTest.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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.3683365342338796d, "diffcalc-test")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override LegacyDifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
|
// 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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.2676066895468976, "diffcalc-test")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override LegacyDifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
|
mit
|
C#
|
71a871d7d1dede52cc9d75b435b7a70b664befc3
|
Add loved enum on BeatmapApproval
|
UselessToucan/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu-new,EVAST9919/osu,UselessToucan/osu,ppy/osu,ppy/osu,UselessToucan/osu,2yangk23/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,smoogipoo/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,2yangk23/osu,johnneijzen/osu,peppy/osu
|
osu.Game/Online/API/Requests/GetUserRecentActivitiesRequest.cs
|
osu.Game/Online/API/Requests/GetUserRecentActivitiesRequest.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 osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class GetUserRecentActivitiesRequest : PaginatedAPIRequest<List<APIRecentActivity>>
{
private readonly long userId;
public GetUserRecentActivitiesRequest(long userId, int page = 0, int itemsPerPage = 5)
: base(page, itemsPerPage)
{
this.userId = userId;
}
protected override string Target => $"users/{userId}/recent_activity";
}
public enum RecentActivityType
{
Achievement,
BeatmapPlaycount,
BeatmapsetApprove,
BeatmapsetDelete,
BeatmapsetRevive,
BeatmapsetUpdate,
BeatmapsetUpload,
Medal,
Rank,
RankLost,
UserSupportAgain,
UserSupportFirst,
UserSupportGift,
UsernameChange,
}
public enum BeatmapApproval
{
Ranked,
Approved,
Qualified,
Loved
}
}
|
// 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 osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class GetUserRecentActivitiesRequest : PaginatedAPIRequest<List<APIRecentActivity>>
{
private readonly long userId;
public GetUserRecentActivitiesRequest(long userId, int page = 0, int itemsPerPage = 5)
: base(page, itemsPerPage)
{
this.userId = userId;
}
protected override string Target => $"users/{userId}/recent_activity";
}
public enum RecentActivityType
{
Achievement,
BeatmapPlaycount,
BeatmapsetApprove,
BeatmapsetDelete,
BeatmapsetRevive,
BeatmapsetUpdate,
BeatmapsetUpload,
Medal,
Rank,
RankLost,
UserSupportAgain,
UserSupportFirst,
UserSupportGift,
UsernameChange,
}
public enum BeatmapApproval
{
Ranked,
Approved,
Qualified,
}
}
|
mit
|
C#
|
a2d0d9ac88d108ab82bfb07f618181416aea5b98
|
Disable parallelization
|
rmandvikar/csharp-extensions,rmandvikar/csharp-extensions
|
tests/rm.ExtensionsTest/Properties/AssemblyInfo.cs
|
tests/rm.ExtensionsTest/Properties/AssemblyInfo.cs
|
using NUnit.Framework;
[assembly: Parallelizable(ParallelScope.None)]
|
using NUnit.Framework;
[assembly: Parallelizable(ParallelScope.All)]
|
mit
|
C#
|
ecfa6b3eb72a113c6d28cd8e06cdee2603e1bdec
|
Change Interactive to IInteractable
|
manio143/ShadowsOfShadows
|
src/Consoles/MainConsole.cs
|
src/Consoles/MainConsole.cs
|
using SadConsole;
using System.Linq;
using Microsoft.Xna.Framework;
using ShadowsOfShadows.Entities;
using ShadowsOfShadows.Renderables;
namespace ShadowsOfShadows.Consoles
{
public class TestEntity : Entity {}
public class MainConsole : Console
{
private Room testRoom = new Room (new[]{ new TestEntity () });
public MainConsole (int width, int height) : base(width, height)
{
testRoom.Entities.First ().Renderable = new ConsoleRenderable ('A');
testRoom.Entities.First ().Transform.Position = new Point (1,1);
}
public override void Draw (System.TimeSpan delta)
{
base.Draw (delta);
foreach (var entity in testRoom.Entities) {
var consoleObject = entity.Renderable.ConsoleObject;
consoleObject.Position = entity.Transform.Position;
consoleObject.Draw (delta);
}
}
}
}
|
using SadConsole;
using System.Linq;
using Microsoft.Xna.Framework;
using ShadowsOfShadows.Renderables;
namespace ShadowsOfShadows.Consoles
{
public class TestEntity : Entity {}
public class MainConsole : Console
{
private Room testRoom = new Room (new[]{ new TestEntity () });
public MainConsole (int width, int height) : base(width, height)
{
testRoom.Entities.First ().Renderable = new ConsoleRenderable ('A');
testRoom.Entities.First ().Transform.Position = new Point (1,1);
}
public override void Draw (System.TimeSpan delta)
{
base.Draw (delta);
foreach (var entity in testRoom.Entities) {
var consoleObject = entity.Renderable.ConsoleObject;
consoleObject.Position = entity.Transform.Position;
consoleObject.Draw (delta);
}
}
}
}
|
mit
|
C#
|
a20ca0def90118d4d59a01d142b04f3c04349bfd
|
Add Snapshots option to listing shares
|
Azure/azure-storage-net,erezvani1529/azure-storage-net
|
Lib/Common/File/ShareListingDetails.cs
|
Lib/Common/File/ShareListingDetails.cs
|
//-----------------------------------------------------------------------
// <copyright file="ShareListingDetails.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.File
{
using System;
/// <summary>
/// Specifies which details to include when listing the shares in this storage account.
/// </summary>
[Flags]
public enum ShareListingDetails
{
/// <summary>
/// No additional details.
/// </summary>
None = 0x0,
/// <summary>
/// Retrieve share metadata.
/// </summary>
Metadata = 0x1,
/// <summary>
/// Retrieve share snapshots.
/// </summary>
Snapshots = 0x2,
/// <summary>
/// Retrieve all available details.
/// </summary>
All = Metadata | Snapshots
}
}
|
//-----------------------------------------------------------------------
// <copyright file="ShareListingDetails.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.File
{
using System;
/// <summary>
/// Specifies which details to include when listing the shares in this storage account.
/// </summary>
[Flags]
public enum ShareListingDetails
{
/// <summary>
/// No additional details.
/// </summary>
None = 0x0,
/// <summary>
/// Retrieve share metadata.
/// </summary>
Metadata = 0x1,
/// <summary>
/// Retrieve all available details.
/// </summary>
All = Metadata
}
}
|
apache-2.0
|
C#
|
86d3cad4c32e01389e9c4896ffc6e4c66af1464c
|
Fix #61, MapLocators should trim the fragment from the URI
|
NMFCode/NMF
|
Models/Models/Repository/MapLocator.cs
|
Models/Models/Repository/MapLocator.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace NMF.Models.Repository
{
public abstract class MapLocator : IModelLocator
{
public IDictionary<Uri, string> Mappings { get; private set; }
public MapLocator()
{
Mappings = new Dictionary<Uri, string>();
}
public MapLocator(IDictionary<Uri, string> mappings)
{
Mappings = mappings;
}
public bool CanLocate(Uri uri)
{
return Mappings != null && Mappings.ContainsKey(uri);
}
public Uri GetRepositoryUri(Uri uri)
{
if (!uri.IsAbsoluteUri)
{
return uri;
}
// throw away the fragment
return new Uri(uri.GetLeftPart(UriPartial.Query));
}
public abstract Stream Open(Uri repositoryId);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace NMF.Models.Repository
{
public abstract class MapLocator : IModelLocator
{
public IDictionary<Uri, string> Mappings { get; private set; }
public MapLocator()
{
Mappings = new Dictionary<Uri, string>();
}
public MapLocator(IDictionary<Uri, string> mappings)
{
Mappings = mappings;
}
public bool CanLocate(Uri uri)
{
return Mappings != null && Mappings.ContainsKey(uri);
}
public Uri GetRepositoryUri(Uri uri)
{
return uri;
}
public abstract Stream Open(Uri repositoryId);
}
}
|
bsd-3-clause
|
C#
|
d15b39a99b021414e2ff0e00ac2712bec51e2134
|
Update BaseTest.cs
|
JamesYing/JCWX
|
test/FrameworkCoreTest/BaseTest.cs
|
test/FrameworkCoreTest/BaseTest.cs
|
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WX.Api;
using WX.Framework;
using WX.Logger;
using WX.Model;
namespace FrameworkCoreTest
{
public abstract class BaseTest
{
private static string tokenfile = "token.txt";
static BaseTest()
{
//ApiAccessTokenManager.Instance.SetAppIdentity(m_appIdentity);
}
protected IApiClient m_client = new DefaultApiClient();
protected Mock<DefaultApiClient> mock_client = new Mock<DefaultApiClient>();
// protected Mock<ILogger> mock_logger = new Mock<ILogger>();
public virtual string GetCurrentToken()
{
if (File.Exists(tokenfile))
{
var strs = File.ReadAllText(tokenfile, Encoding.UTF8);
var splitstrs = strs.Split(new char[] { '|' });
var token = splitstrs[0];
var expirtime = DateTime.Parse(splitstrs[1]);
if (expirtime <= DateTime.Now)
{
return GetToken();
}
return token;
}
else
{
return GetToken();
}
}
private string GetToken()
{
var token = ApiAccessTokenManager.Instance.GetCurrentToken();
var expirtime = ApiAccessTokenManager.Instance.ExpireTime;
File.WriteAllText(tokenfile, token + "|" + expirtime.ToString(), Encoding.UTF8);
return token;
}
}
}
|
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WX.Api;
using WX.Framework;
using WX.Logger;
using WX.Model;
namespace FrameworkCoreTest
{
public abstract class BaseTest
{
private static string tokenfile = "token.txt";
static BaseTest()
{
//ApiAccessTokenManager.Instance.SetAppIdentity(m_appIdentity);
}
protected IApiClient m_client = new DefaultApiClient();
protected Mock<DefaultApiClient> mock_client = new Mock<DefaultApiClient>();
// protected Mock<ILogger> mock_logger = new Mock<ILogger>();
public virtual string GetCurrentToken()
{
if (File.Exists(tokenfile))
{
var strs = File.ReadAllText(tokenfile, Encoding.UTF8);
var splitstrs = strs.Split(new char[] { '|' });
var token = splitstrs[0];
var expirtime = DateTime.Parse(splitstrs[1]);
if (expirtime <= DateTime.Now)
{
return GetToken();
}
return token;
}
else
{
return GetToken();
}
}
private string GetToken()
{
var token = GetCurrentToken();
var expirtime = ApiAccessTokenManager.Instance.ExpireTime;
File.WriteAllText(tokenfile, token + "|" + expirtime.ToString(), Encoding.UTF8);
return token;
}
}
}
|
mit
|
C#
|
9f3dcaa67019914cff40aa3332cd341f413945e0
|
Update Viktor.cs
|
FireBuddy/adevade
|
AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs
|
AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs
|
using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
.// var End = enemy.GetWaypoints().Last();
var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
|
using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
var End = enemy.GetWaypoints().Last();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
|
mit
|
C#
|
3e51475d2f4a96e2ccbf2cf28796ec8b51a774dd
|
Add TagName/TagMode properties
|
bigfont/StackOverflow,bigfont/StackOverflow,bigfont/StackOverflow,bigfont/StackOverflow
|
AspNetCorePlayground/TagHelpers/MyFirstTagHelper.cs
|
AspNetCorePlayground/TagHelpers/MyFirstTagHelper.cs
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace AspNetCorePlayground.TagHelpers
{
public class MyFirst : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
// get the existing content
var childContent = await output.GetChildContentAsync();
var innerHtml = childContent.GetContent();
// wrap all the PreContent, Content, and PostContent in a paragraph tag.
output.TagName = "p";
output.TagMode = TagMode.StartTagAndEndTag; // optional
ModifyTagHelperContent(output);
}
public void ModifyTagHelperContent(TagHelperOutput output)
{
// outside of the TagName tag
output.PreElement.SetHtmlContent("<p>PreElement.SetHtmlContent</p>");
output.PostElement.SetHtmlContent("<p>PostElement.SetHtmlContent</p>");
// inside the TagName tag
output.PreContent.SetHtmlContent("<i>PreContent.SetHtmlContent</i>, ");
output.PostContent.SetHtmlContent("<i>PostContent.SetHtmlContent</i>.");
output.Content.SetContent("Content.SetContent, "); // replaces existing content
output.Content.Append("Content.Append, ");
output.Content.AppendHtml("<i>Content.AppendHtml</i>, ");
}
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace AspNetCorePlayground.TagHelpers
{
public class MyFirst : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = await output.GetChildContentAsync();
var innerHtml = childContent.GetContent();
output.Content.SetContent("Content.SetContent, "); // [replaces existing content]
output.Content.Append("Content.Append, "); // [append new content]
output.Content.AppendFormat("Content.AppendFormat {0} {1} {2}, ", "Foo", "Bar", "Baz");
output.Content.AppendHtml("<strong>Content.AppendHtml</strong>.");
output.PreContent.SetHtmlContent("<p>PreContent.SetHtmlContent</p>");
output.PostContent.SetHtmlContent("<p>PostContent.SetHtmlContent</p>");
output.PreElement.SetHtmlContent("<p>PreElement.SetHtmlContent</p>");
output.PostElement.SetHtmlContent("<p>PostElement.SetHtmlContent</p>");
}
}
}
|
mit
|
C#
|
fbef6dc1a001c07d2d44d3887f9f773c124eaa24
|
update assembly values
|
CityofSantaMonica/SODA.NET,chrismetcalf/SODA.NET
|
Source/SODA/Properties/AssemblyInfo.cs
|
Source/SODA/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("SODA")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("City of Santa Monica")]
[assembly: AssemblyProduct("SODA")]
[assembly: AssemblyCopyright("Copyright © City of Santa Monica 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d0894220-e3ab-4093-be46-50e268a9d9bb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Source")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard Company")]
[assembly: AssemblyProduct("Source")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d0894220-e3ab-4093-be46-50e268a9d9bb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
497d3fb93163c3c64262a8f5abd9291b506e744b
|
Replace log4net dependency with LibLog
|
Elders/Multithreading.Scheduler
|
src/Elders.Multithreading.Scheduler/Properties/AssemblyInfo.cs
|
src/Elders.Multithreading.Scheduler/Properties/AssemblyInfo.cs
|
// <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitleAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyDescriptionAttribute("The idea is to create a dedicated threads for a particular work. The WorkPool class does not use the standard .NET thread pool.")]
[assembly: ComVisibleAttribute(false)]
[assembly: AssemblyProductAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyCopyrightAttribute("Copyright © 2015")]
[assembly: AssemblyVersionAttribute("1.1.0.0")]
[assembly: AssemblyFileVersionAttribute("1.1.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.1.0+1.Branch.master.Sha.25442a58c8498465a9335b9bb288b5450d3d2cba")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "1.1.0.0";
}
}
|
// <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitleAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyDescriptionAttribute("The idea is to create a dedicated threads for a particular work. The WorkPool class does not use the standard .NET thread pool.")]
[assembly: ComVisibleAttribute(false)]
[assembly: AssemblyProductAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyCopyrightAttribute("Copyright © 2015")]
[assembly: AssemblyVersionAttribute("1.1.0.0")]
[assembly: AssemblyFileVersionAttribute("1.1.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.1.0-beta.1+0.Branch.release/1.1.0.Sha.c42b1e80ff319dc8fecfcd9396662a96fcafbfaf")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "1.1.0.0";
}
}
|
apache-2.0
|
C#
|
497f9908785fc85685f25bdc616f5fafda3916eb
|
update versin
|
Weingartner/XUnitRemote
|
XUnitRemote/Properties/AssemblyInfo.cs
|
XUnitRemote/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("XUnitRemote")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weingartner")]
[assembly: AssemblyProduct("XUnitRemote")]
[assembly: AssemblyCopyright("Copyright © Weingartner Machinenbau Gmbh 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("21248cf4-3629-4cfa-8632-9e4468a0526e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.12")]
[assembly: AssemblyFileVersion("1.0.0.12")]
|
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("XUnitRemote")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weingartner")]
[assembly: AssemblyProduct("XUnitRemote")]
[assembly: AssemblyCopyright("Copyright © Weingartner Machinenbau Gmbh 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("21248cf4-3629-4cfa-8632-9e4468a0526e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.11")]
[assembly: AssemblyFileVersion("1.0.0.11")]
|
mit
|
C#
|
bcf45f50872076aaab6706e9200ed047d293df22
|
Update Host startup.cs
|
Arch/ApiHelp,Arch/ApiHelp,Arch/ApiHelp,Arch/ApiHelp
|
src/Host/Startup.cs
|
src/Host/Startup.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.ApiHelp;
using Microsoft.AspNetCore.ApiHelp.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Host
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc()
.AddApiHelp(options => {
options.IgnoreObsoleteApi = true;
options.GenerateStrategy = DocumentGenerateStrategy.Eager;
options.IncludeSupportedMediaType = false;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseApiHelp(new ApiHelpUIOptions {
UI = ApiHelpUI.Swagger,
});
app.UseMvc();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.ApiHelp;
using Microsoft.AspNetCore.ApiHelp.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Host
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc()
.AddApiHelp(options => {
options.IgnoreObsoleteApi = true;
options.GenerateStrategy = DocumentGenerateStrategy.Lazy;
options.IncludeSupportedMediaType = false;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseApiHelp(new ApiHelpUIOptions {
UI = ApiHelpUI.Swagger,
});
app.UseMvc();
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.