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 |
|---|---|---|---|---|---|---|---|---|
165e0279685a356009f7de3eacfb869d18f2adf8 | Fix script order issue | rho24/Glimpse.NLog,rho24/Glimpse.NLog,sorenhl/Glimpse.NLog,sorenhl/Glimpse.NLog,rho24/Glimpse.NLog,sorenhl/Glimpse.NLog | Glimpse.NLog/Resource/NLogJsResource.cs | Glimpse.NLog/Resource/NLogJsResource.cs | using Glimpse.Core.Extensibility;
namespace Glimpse.NLog.Resource
{
public class NLogJsResource : MyFileResource, IDynamicClientScript
{
private const string InternalName = "glimpse_nlog";
public NLogJsResource() {
ResourceName = "Glimpse.NLog.Resource.glimpse.nlog.js";
ResourceType = @"application/x-javascript";
Name = InternalName;
}
public ScriptOrder Order {
get { return ScriptOrder.IncludeAfterClientInterfaceScript; }
}
public string GetResourceName() {
return InternalName;
}
}
} | using Glimpse.Core.Extensibility;
namespace Glimpse.NLog.Resource
{
public class NLogJsResource : MyFileResource, IDynamicClientScript
{
private const string InternalName = "glimpse_nlog";
public NLogJsResource() {
ResourceName = "Glimpse.NLog.Resource.glimpse.nlog.js";
ResourceType = @"application/x-javascript";
Name = InternalName;
}
public ScriptOrder Order {
get { return ScriptOrder.ClientInterfaceScript; }
}
public string GetResourceName() {
return InternalName;
}
}
} | mit | C# |
b83d3449430c7610030ca50a9e98c67adf489307 | Change name of a lifetime scope | HangfireIO/Hangfire.Autofac | HangFire.Autofac/AutofacJobActivator.cs | HangFire.Autofac/AutofacJobActivator.cs | using System;
using Autofac;
using Hangfire.Annotations;
namespace Hangfire
{
/// <summary>
/// Hangfire Job Activator based on Autofac IoC Container.
/// </summary>
public class AutofacJobActivator : JobActivator
{
/// <summary>
/// Tag used in setting up per-job lifetime scope registrations.
/// </summary>
public static readonly object LifetimeScopeTag = "BackgroundJobScope";
private readonly ILifetimeScope _lifetimeScope;
/// <summary>
/// Initializes a new instance of the <see cref="AutofacJobActivator"/>
/// class with the given Autofac Lifetime Scope.
/// </summary>
/// <param name="lifetimeScope">Container that will be used to create instance
/// of classes during job activation process.</param>
public AutofacJobActivator([NotNull] ILifetimeScope lifetimeScope)
{
if (lifetimeScope == null) throw new ArgumentNullException("lifetimeScope");
_lifetimeScope = lifetimeScope;
}
/// <inheritdoc />
public override object ActivateJob(Type jobType)
{
return _lifetimeScope.Resolve(jobType);
}
public override JobActivatorScope BeginScope()
{
return new AutofacScope(_lifetimeScope.BeginLifetimeScope(LifetimeScopeTag));
}
class AutofacScope : JobActivatorScope
{
private readonly ILifetimeScope _lifetimeScope;
public AutofacScope(ILifetimeScope lifetimeScope)
{
_lifetimeScope = lifetimeScope;
}
public override object Resolve(Type type)
{
return _lifetimeScope.Resolve(type);
}
public override void DisposeScope()
{
_lifetimeScope.Dispose();
}
}
}
}
| using System;
using Autofac;
using Hangfire.Annotations;
namespace Hangfire
{
/// <summary>
/// Hangfire Job Activator based on Autofac IoC Container.
/// </summary>
public class AutofacJobActivator : JobActivator
{
/// <summary>
/// Tag used in setting up per-job lifetime scope registrations.
/// </summary>
public static readonly object LifetimeScopeTag = (object) "HangfireJob";
private readonly ILifetimeScope _lifetimeScope;
/// <summary>
/// Initializes a new instance of the <see cref="AutofacJobActivator"/>
/// class with the given Autofac Lifetime Scope.
/// </summary>
/// <param name="lifetimeScope">Container that will be used to create instance
/// of classes during job activation process.</param>
public AutofacJobActivator([NotNull] ILifetimeScope lifetimeScope)
{
if (lifetimeScope == null) throw new ArgumentNullException("lifetimeScope");
_lifetimeScope = lifetimeScope;
}
/// <inheritdoc />
public override object ActivateJob(Type jobType)
{
return _lifetimeScope.Resolve(jobType);
}
public override JobActivatorScope BeginScope()
{
return new AutofacScope(_lifetimeScope.BeginLifetimeScope(LifetimeScopeTag));
}
class AutofacScope : JobActivatorScope
{
private readonly ILifetimeScope _lifetimeScope;
public AutofacScope(ILifetimeScope lifetimeScope)
{
_lifetimeScope = lifetimeScope;
}
public override object Resolve(Type type)
{
return _lifetimeScope.Resolve(type);
}
public override void DisposeScope()
{
_lifetimeScope.Dispose();
}
}
}
}
| mit | C# |
2edb2492eebd2e52b59c5d6509b085fad1a354ab | Handle url launch | NuGetPackageExplorer/NuGetPackageExplorer,campersau/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer | PackageExplorer/Utilities/UriHelper.cs | PackageExplorer/Utilities/UriHelper.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
namespace PackageExplorer
{
internal static class UriHelper
{
public static void OpenExternalLink(Uri licenseUrl)
{
try
{
if (IsRemoteUri(licenseUrl))
{
Process.Start(licenseUrl.AbsoluteUri);
}
}
catch // Possible Win32 exception: operation was canceled by the user. Nothing we can do.
{
}
}
public static bool IsRemoteUri(this Uri url)
{
if (url == null)
{
return false;
}
// mitigate security risk
if (url.IsFile || url.IsLoopback || url.IsUnc)
{
return false;
}
var scheme = url.Scheme;
return (scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase));
}
public static Dictionary<string, string> GetRequestParameters(this Uri uri)
{
if (uri == null)
{
return null;
}
var matches = Regex.Matches(uri.Query, @"[\?&](([^&=]+)=([^&=#]*))");
return matches.Cast<Match>().ToDictionary(
m => Uri.UnescapeDataString(m.Groups[2].Value),
m => Uri.UnescapeDataString(m.Groups[3].Value),
StringComparer.OrdinalIgnoreCase);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
namespace PackageExplorer
{
internal static class UriHelper
{
public static void OpenExternalLink(Uri licenseUrl)
{
if (IsRemoteUri(licenseUrl))
{
Process.Start(licenseUrl.AbsoluteUri);
}
}
public static bool IsRemoteUri(this Uri url)
{
if (url == null)
{
return false;
}
// mitigate security risk
if (url.IsFile || url.IsLoopback || url.IsUnc)
{
return false;
}
var scheme = url.Scheme;
return (scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase));
}
public static Dictionary<string, string> GetRequestParameters(this Uri uri)
{
if (uri == null)
{
return null;
}
var matches = Regex.Matches(uri.Query, @"[\?&](([^&=]+)=([^&=#]*))");
return matches.Cast<Match>().ToDictionary(
m => Uri.UnescapeDataString(m.Groups[2].Value),
m => Uri.UnescapeDataString(m.Groups[3].Value),
StringComparer.OrdinalIgnoreCase);
}
}
} | mit | C# |
b14c1534e1abcf2efde3374ebcd0accc75f649bf | add UDP_init() | yasokada/unity-151117-linemonitor-UI | Assets/SettingSend.cs | Assets/SettingSend.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
// for UDP send
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class SettingSend : MonoBehaviour {
public const string kCommandIpAddressPrefix = "192.168.10.";
public const string kDefaultCommandPort = "7000";
public const string kDefaultComBaud = "9600";
public InputField IF_ipadr;
public InputField IF_port;
public InputField IF_combaud;
public bool s_udp_isNotInit = true; // TODO: 1> rename to positive variable
UdpClient s_udp_client;
void Start () {
IF_ipadr.text = kCommandIpAddressPrefix;
IF_port.text = kDefaultCommandPort;
IF_combaud.text = kDefaultComBaud;
}
void UDP_init() {
s_udp_client = new UdpClient ();
s_udp_client.Client.ReceiveTimeout = 300; // msec
s_udp_client.Client.Blocking = false;
}
public void SendButtonClick() {
Debug.Log ("SendButton");
if (s_udp_isNotInit == true) {
s_udp_isNotInit = false;
UDP_init ();
}
}
}
// byte[] data = System.Text.Encoding.ASCII.GetBytes(text);
| using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class SettingSend : MonoBehaviour {
public const string kCommandIpAddressPrefix = "192.168.10.";
public const string kDefaultCommandPort = "7000";
public const string kDefaultComBaud = "9600";
public InputField IF_ipadr;
public InputField IF_port;
public InputField IF_combaud;
void Start () {
IF_ipadr.text = kCommandIpAddressPrefix;
IF_port.text = kDefaultCommandPort;
IF_combaud.text = kDefaultComBaud;
}
public void SendButtonClick() {
Debug.Log ("SendButton");
}
}
| mit | C# |
636e3c13f6e8958d0f1ffd929e9784ec2ba65000 | Change property to be read-only | terrajobst/git-istage,terrajobst/git-istage | src/git-istage/UI/FileDocument.cs | src/git-istage/UI/FileDocument.cs | using System.Text;
using LibGit2Sharp;
namespace GitIStage.UI;
internal sealed class FileDocument : Document
{
private readonly int _indexOfFirstFile;
private readonly string[] _lines;
private readonly TreeEntryChanges[] _changes;
private FileDocument(int indexOfFirstFile, string[] lines, TreeChanges changes, int width)
{
_indexOfFirstFile = indexOfFirstFile;
_lines = lines;
_changes = changes.ToArray();
Width = width;
}
public override int Height => _lines.Length;
public override int Width { get; }
public IReadOnlyList<TreeEntryChanges> Changes => _changes;
public override string GetLine(int index)
{
return _lines[index];
}
public TreeEntryChanges? GetChange(int index)
{
var changeIndex = index - _indexOfFirstFile;
if (changeIndex < 0 || changeIndex >= _changes.Length)
return null;
return _changes[changeIndex];
}
public static FileDocument Create(TreeChanges changes, bool viewStage)
{
var builder = new StringBuilder();
if (changes.Any())
{
builder.AppendLine();
builder.AppendLine(viewStage ? "Changes to be committed:" : "Changes not staged for commit:");
builder.AppendLine();
var indent = new string(' ', 8);
foreach (var c in changes)
{
var path = c.Path;
var change = (c.Status.ToString().ToLower() + ":").PadRight(12);
builder.Append(indent);
builder.Append(change);
builder.Append(path);
builder.AppendLine();
}
}
const int indexOfFirstFile = 3;
var lines = builder.Length == 0
? Array.Empty<string>()
: builder.ToString().Split(Environment.NewLine);
var width = lines.Select(l => l.Length)
.DefaultIfEmpty(0)
.Max();
return new FileDocument(indexOfFirstFile, lines, changes, width);
}
} | using System.Text;
using LibGit2Sharp;
namespace GitIStage.UI;
internal sealed class FileDocument : Document
{
private readonly int _indexOfFirstFile;
private readonly string[] _lines;
private readonly TreeEntryChanges[] _changes;
private FileDocument(int indexOfFirstFile, string[] lines, TreeChanges changes, int width)
{
_indexOfFirstFile = indexOfFirstFile;
_lines = lines;
_changes = changes.ToArray();
Width = width;
}
public override int Height => _lines.Length;
public override int Width { get; }
public TreeEntryChanges[] Changes => _changes;
public override string GetLine(int index)
{
return _lines[index];
}
public TreeEntryChanges? GetChange(int index)
{
var changeIndex = index - _indexOfFirstFile;
if (changeIndex < 0 || changeIndex >= _changes.Length)
return null;
return _changes[changeIndex];
}
public static FileDocument Create(TreeChanges changes, bool viewStage)
{
var builder = new StringBuilder();
if (changes.Any())
{
builder.AppendLine();
builder.AppendLine(viewStage ? "Changes to be committed:" : "Changes not staged for commit:");
builder.AppendLine();
var indent = new string(' ', 8);
foreach (var c in changes)
{
var path = c.Path;
var change = (c.Status.ToString().ToLower() + ":").PadRight(12);
builder.Append(indent);
builder.Append(change);
builder.Append(path);
builder.AppendLine();
}
}
const int indexOfFirstFile = 3;
var lines = builder.Length == 0
? Array.Empty<string>()
: builder.ToString().Split(Environment.NewLine);
var width = lines.Select(l => l.Length)
.DefaultIfEmpty(0)
.Max();
return new FileDocument(indexOfFirstFile, lines, changes, width);
}
} | mit | C# |
f3aa49934f853e64fcca1b31641b6e48f4895550 | Remove personal contact info. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | MagicalCryptoWallet.Backend/Startup.cs | MagicalCryptoWallet.Backend/Startup.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
namespace MagicalCryptoWallet.Backend
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "Magical Crypto API",
Description = "Privacy oriented Bitcoin Web API",
TermsOfService = "None",
License = new License { Name = "Use under MIT", Url = "https://github.com/nopara73/MagicalCryptoWallet/blob/master/LICENSE.md" }
});
// Set the comments path for the Swagger JSON and UI.
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "MagicalCryptoWallet.Backend.xml");
c.IncludeXmlComments(xmlPath);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Magical Crypto API V1");
});
app.UseMvc();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
namespace MagicalCryptoWallet.Backend
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "Magical Crypto API",
Description = "Privacy oriented Bitcoin Web API",
TermsOfService = "None",
Contact = new Contact { Name = "nopara73", Email = "adam.ficsor73@gmail.com", Url = "https://twitter.com/nopara73" },
License = new License { Name = "Use under MIT", Url = "https://github.com/nopara73/MagicalCryptoWallet/blob/master/LICENSE.md" }
});
// Set the comments path for the Swagger JSON and UI.
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "MagicalCryptoWallet.Backend.xml");
c.IncludeXmlComments(xmlPath);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Magical Crypto API V1");
});
app.UseMvc();
}
}
}
| mit | C# |
43e6b10564e8b0916a93b06af46756b870e432f0 | Bump to 0.4 | mpOzelot/Unity,github-for-unity/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity | common/SolutionInfo.cs | common/SolutionInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.4.0.0";
}
}
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.3.0.0";
}
}
| mit | C# |
5085c364fa13f84cd24ef1c99bc86e7635117608 | Bump version to 0.11 | mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity,mpOzelot/Unity | common/SolutionInfo.cs | common/SolutionInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.11.0.0";
}
}
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.10.0.0";
}
}
| mit | C# |
0cbde68a7d1c1a526cdde01e1b29e8f2804dd34a | Bump to 0.8 | mpOzelot/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | common/SolutionInfo.cs | common/SolutionInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.8.0.0";
}
}
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.7.0.0";
}
}
| mit | C# |
33764f4cd4e41ac62221a6ba56e1f4ff22aaae0e | test window | alloverme/apmathcloudweb | site/index.cshtml | site/index.cshtml | @{
var amplitudeRequest = Request.Params["amplitude"];
var amplitudeValue = 1;
var clear = int.TryParse(amplitudeRequest, out amplitudeValue);
var errorMssage = "no amplitude provided, please input http://apmath4oj.azurewebsites.net/mem.cshtml?amplitude=5";
}
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
@if(!clear){
Response.Write(String.Format("alert({0});", errorMssage));
}
var mouse = [480, 250],
count = 0;
var width = window.innerWidth;
var height = window.innerHeight;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var g = svg.selectAll("g")
.data(d3.range(25))
.enter().append("g")
.attr("transform", "translate(" + mouse + ")");
g.append("rect")
.attr("rx", 6)
.attr("ry", 6)
.attr("x", -12.5)
.attr("y", -12.5)
.attr("width", 25)
.attr("height", 25)
.attr("transform", function(d, i) { return "scale(" + (1 - d / 25) * 20 + ")"; })
.style("fill", d3.scale.category20c());
g.datum(function(d) {
return {center: mouse.slice(), angle: 0};
});
svg.on("mousemove", function() {
mouse = d3.mouse(this);
});
d3.timer(function() {
count++;
g.attr("transform", function(d, i) {
d.center[0] += (mouse[0] - d.center[0]) / (i + 5);
d.center[1] += (mouse[1] - d.center[1]) / (i + 5);
d.angle += Math.sin((count + i) / 10) * 7;
return "translate(" + d.center + ")rotate(" + d.angle + ")";
});
});
</script> | @{
var amplitudeRequest = Request.Params["amplitude"];
var amplitudeValue = 1;
var clear = int.TryParse(amplitudeRequest, out amplitudeValue);
var errorMssage = "no amplitude provided, please input http://apmath4oj.azurewebsites.net/mem.cshtml?amplitude=5";
}
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
@if(!clear){
Response.Write(String.Format("alert({0});", errorMssage));
}
var mouse = [480, 250],
count = 0;
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var g = svg.selectAll("g")
.data(d3.range(25))
.enter().append("g")
.attr("transform", "translate(" + mouse + ")");
g.append("rect")
.attr("rx", 6)
.attr("ry", 6)
.attr("x", -12.5)
.attr("y", -12.5)
.attr("width", 25)
.attr("height", 25)
.attr("transform", function(d, i) { return "scale(" + (1 - d / 25) * 20 + ")"; })
.style("fill", d3.scale.category20c());
g.datum(function(d) {
return {center: mouse.slice(), angle: 0};
});
svg.on("mousemove", function() {
mouse = d3.mouse(this);
});
d3.timer(function() {
count++;
g.attr("transform", function(d, i) {
d.center[0] += (mouse[0] - d.center[0]) / (i + 5);
d.center[1] += (mouse[1] - d.center[1]) / (i + 5);
d.angle += Math.sin((count + i) / 10) * 7;
return "translate(" + d.center + ")rotate(" + d.angle + ")";
});
});
</script> | mit | C# |
e717d6695bac6ee5b5bcf0b3c26942e6c3b039ca | update to 1.9 | matortheeternal/mod-analyzer | ModAnalyzer/Properties/AssemblyInfo.cs | ModAnalyzer/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("Mod Analyzer")]
[assembly: AssemblyDescription("Analyzes Bethesda Game mod archive files.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mod Picker, LLC")]
[assembly: AssemblyProduct("Mod Analyzer")]
[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.9.0.0")]
[assembly: AssemblyFileVersion("1.9.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Mod Analyzer")]
[assembly: AssemblyDescription("Analyzes Bethesda Game mod archive files.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mod Picker, LLC")]
[assembly: AssemblyProduct("Mod Analyzer")]
[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.8.3.0")]
[assembly: AssemblyFileVersion("1.8.3.0")]
| mit | C# |
b0530ae28c1442cee4b9d7a15ce620f906cdc82d | bump version | Fody/Janitor | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.5.2")]
[assembly: AssemblyFileVersion("1.5.2")]
| using System.Reflection;
[assembly: AssemblyVersion("1.5.1")]
[assembly: AssemblyFileVersion("1.5.1")]
| mit | C# |
b4d4d7ef1afc4d1ce13b57c3ffe703cfa9e3fc16 | Use ReflectionOnlyLoad() in the remote proxy reference prober | sadiqhirani/Nancy,blairconrad/Nancy,xt0rted/Nancy,davidallyoung/Nancy,blairconrad/Nancy,asbjornu/Nancy,sadiqhirani/Nancy,asbjornu/Nancy,jeff-pang/Nancy,asbjornu/Nancy,blairconrad/Nancy,NancyFx/Nancy,xt0rted/Nancy,damianh/Nancy,danbarua/Nancy,asbjornu/Nancy,jeff-pang/Nancy,danbarua/Nancy,JoeStead/Nancy,khellang/Nancy,davidallyoung/Nancy,asbjornu/Nancy,khellang/Nancy,xt0rted/Nancy,khellang/Nancy,jeff-pang/Nancy,jeff-pang/Nancy,JoeStead/Nancy,damianh/Nancy,blairconrad/Nancy,danbarua/Nancy,JoeStead/Nancy,davidallyoung/Nancy,NancyFx/Nancy,NancyFx/Nancy,JoeStead/Nancy,sadiqhirani/Nancy,danbarua/Nancy,davidallyoung/Nancy,davidallyoung/Nancy,khellang/Nancy,sadiqhirani/Nancy,damianh/Nancy,xt0rted/Nancy,NancyFx/Nancy | src/Nancy/Helpers/ProxyNancyReferenceProber.cs | src/Nancy/Helpers/ProxyNancyReferenceProber.cs | #if !CORE
namespace Nancy.Helpers
{
using System;
using System.Reflection;
using Nancy.Extensions;
internal class ProxyNancyReferenceProber : MarshalByRefObject
{
public bool HasReference(AssemblyName assemblyNameForProbing, AssemblyName referenceAssemblyName)
{
var assemblyForInspection = Assembly.ReflectionOnlyLoad(assemblyNameForProbing.Name);
return assemblyForInspection.IsReferencing(referenceAssemblyName);
}
}
}
#endif | #if !CORE
namespace Nancy.Helpers
{
using System;
using System.Reflection;
using Nancy.Extensions;
internal class ProxyNancyReferenceProber : MarshalByRefObject
{
public bool HasReference(AssemblyName assemblyNameForProbing, AssemblyName referenceAssemblyName)
{
var assemblyForInspection = Assembly.Load(assemblyNameForProbing);
return assemblyForInspection.IsReferencing(referenceAssemblyName);
}
}
}
#endif | mit | C# |
ed24db292eeae7997f12e7ce70ecc80f6f7acc73 | Fix HttpService NotFound server error. | dkackman/HockeySDK-Windows,ChristopheLav/HockeySDK-Windows,bitstadium/HockeySDK-Windows | Src/Kit.Core45/Services/HttpService.cs | Src/Kit.Core45/Services/HttpService.cs | namespace Microsoft.HockeyApp.Services
{
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Extensions;
internal class HttpService : IHttpService
{
internal const string ContentTypeHeader = "Content-Type";
internal const string ContentEncodingHeader = "Content-Encoding";
private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(100);
/// <summary>
/// Initializes a new instance of the <see cref="HttpService"/> class.
/// </summary>
internal HttpService()
{
}
public async Task PostAsync(Uri address, byte[] content, string contentType, string contentEncoding, TimeSpan timeout = default(TimeSpan))
{
if (address == null) throw new ArgumentNullException("address");
if (content == null) throw new ArgumentNullException("content");
if (contentType == null) throw new ArgumentNullException("contentType");
//#if DEBUG
// string result = System.Text.Encoding.UTF8.GetString(content, 0, content.Length);
//#endif
var request = WebRequest.CreateHttp(address);
request.Method = "POST";
request.ContentType = contentType;
if (!string.IsNullOrEmpty(contentEncoding))
{
request.Headers[ContentEncodingHeader] = contentEncoding;
}
using (Stream stream = await request.GetRequestStreamAsync())
{
stream.Write(content, 0, content.Length);
stream.Flush();
}
using (WebResponse response = await request.GetResponseAsync()) { }
}
public Stream CreateCompressedStream(Stream stream)
{
return stream;
}
public string GetContentEncoding()
{
return null;
}
}
}
| namespace Microsoft.HockeyApp.Services
{
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Extensions;
internal class HttpService : IHttpService
{
internal const string ContentTypeHeader = "Content-Type";
internal const string ContentEncodingHeader = "Content-Encoding";
private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(100);
/// <summary>
/// Initializes a new instance of the <see cref="HttpService"/> class.
/// </summary>
internal HttpService()
{
}
public async Task PostAsync(Uri address, byte[] content, string contentType, string contentEncoding, TimeSpan timeout = default(TimeSpan))
{
if (address == null) throw new ArgumentNullException("address");
if (content == null) throw new ArgumentNullException("content");
if (contentType == null) throw new ArgumentNullException("contentType");
var request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "POST";
if (!string.IsNullOrEmpty(contentEncoding))
{
request.Headers[ContentEncodingHeader] = contentEncoding;
}
using (Stream requestStream = await request.GetRequestStreamAsync())
{
await requestStream.WriteAsync(content, 0, content.Length);
}
using (WebResponse response = await request.GetResponseAsync()) {}
}
public Stream CreateCompressedStream(Stream stream)
{
return stream;
}
public string GetContentEncoding()
{
return null;
}
}
}
| mit | C# |
d7bbf4be4d56bdcd487d88a57e16c4c32e7c2abd | Add todo | VerkhovtsovPavel/BSUIR_Labs,VerkhovtsovPavel/BSUIR_Labs,VerkhovtsovPavel/BSUIR_Labs,VerkhovtsovPavel/BSUIR_Labs,VerkhovtsovPavel/BSUIR_Labs,VerkhovtsovPavel/BSUIR_Labs,VerkhovtsovPavel/BSUIR_Labs,VerkhovtsovPavel/BSUIR_Labs,VerkhovtsovPavel/BSUIR_Labs | source/Program.cs | source/Program.cs | using System;
using System.Windows.Forms;
using Course_project.Views;
//TODO Install MongoDB
//TODO Add collection in DB
//TODO Implement DAO layer(local DB)
//TODO Create base views(registration, login, addTask, taskViewer)
//TODO Implement base controlers
namespace Course_project
{
internal sealed class Program
{
[STAThread]
private static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new LoginView());
}
}
}
| using System;
using System.Windows.Forms;
using Course_project.Views;
namespace Course_project
{
internal sealed class Program
{
[STAThread]
private static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new LoginView());
}
}
}
| mit | C# |
abb8f1132ca233030ff232e67598149b627cc047 | Drop tables after tests. | SilkStack/Silk.Data.SQL.ORM | Silk.Data.SQL.ORM.Tests/SelectTests.cs | Silk.Data.SQL.ORM.Tests/SelectTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace Silk.Data.SQL.ORM.Tests
{
[TestClass]
public class SelectTests
{
[TestMethod]
public void SelectGuidSimpleModel()
{
var domain = new DataDomain();
var dataModel = domain.CreateDataModel<BasicPocoWithGuidId>();
foreach (var table in dataModel.Tables)
{
if (!table.Exists(TestDb.Provider))
table.Create(TestDb.Provider);
}
var sourceInstances = new[]
{
new BasicPocoWithGuidId { Data = "Hello World 1" },
new BasicPocoWithGuidId { Data = "Hello World 2" },
new BasicPocoWithGuidId { Data = "Hello World 3" }
};
dataModel.Insert(sourceInstances)
.Execute(TestDb.Provider);
var queriedInstances = dataModel.Select()
.Execute(TestDb.Provider);
Assert.AreEqual(sourceInstances.Length, queriedInstances.Count);
foreach (var sourceInstance in sourceInstances)
{
Assert.IsTrue(queriedInstances.Any(q => q.Id == sourceInstance.Id && q.Data == sourceInstance.Data));
}
foreach (var table in dataModel.Tables)
{
table.Drop(TestDb.Provider);
}
}
[TestMethod]
public void MultipleSelectGuidSimpleModel()
{
var domain = new DataDomain();
var dataModel = domain.CreateDataModel<BasicPocoWithGuidId>();
foreach (var table in dataModel.Tables)
{
if (!table.Exists(TestDb.Provider))
table.Create(TestDb.Provider);
}
var sourceInstances = new[]
{
new BasicPocoWithGuidId { Data = "Hello World 1" },
new BasicPocoWithGuidId { Data = "Hello World 2" },
new BasicPocoWithGuidId { Data = "Hello World 3" }
};
var (firstResults, lastResults) = dataModel
.Insert(sourceInstances)
.Select(limit: 1, offset: 0)
.Select(limit: 1, offset: 2)
.AsTransaction()
.Execute(TestDb.Provider);
Assert.AreEqual(1, firstResults.Count);
Assert.AreEqual(1, lastResults.Count);
Assert.AreEqual(sourceInstances[0].Data, firstResults.First().Data);
Assert.AreEqual(sourceInstances[2].Data, lastResults.First().Data);
foreach (var table in dataModel.Tables)
{
table.Drop(TestDb.Provider);
}
}
private class BasicPocoWithGuidId
{
public Guid Id { get; private set; }
public string Data { get; set; }
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace Silk.Data.SQL.ORM.Tests
{
[TestClass]
public class SelectTests
{
[TestMethod]
public void SelectGuidSimpleModel()
{
var domain = new DataDomain();
var dataModel = domain.CreateDataModel<BasicPocoWithGuidId>();
foreach (var table in dataModel.Tables)
{
if (!table.Exists(TestDb.Provider))
table.Create(TestDb.Provider);
}
var sourceInstances = new[]
{
new BasicPocoWithGuidId { Data = "Hello World 1" },
new BasicPocoWithGuidId { Data = "Hello World 2" },
new BasicPocoWithGuidId { Data = "Hello World 3" }
};
dataModel.Insert(sourceInstances)
.Execute(TestDb.Provider);
var queriedInstances = dataModel.Select()
.Execute(TestDb.Provider);
Assert.AreEqual(sourceInstances.Length, queriedInstances.Count);
foreach (var sourceInstance in sourceInstances)
{
Assert.IsTrue(queriedInstances.Any(q => q.Id == sourceInstance.Id && q.Data == sourceInstance.Data));
}
}
[TestMethod]
public void MultipleSelectGuidSimpleModel()
{
var domain = new DataDomain();
var dataModel = domain.CreateDataModel<BasicPocoWithGuidId>();
foreach (var table in dataModel.Tables)
{
if (!table.Exists(TestDb.Provider))
table.Create(TestDb.Provider);
}
var sourceInstances = new[]
{
new BasicPocoWithGuidId { Data = "Hello World 1" },
new BasicPocoWithGuidId { Data = "Hello World 2" },
new BasicPocoWithGuidId { Data = "Hello World 3" }
};
var (firstResults, lastResults) = dataModel
.Insert(sourceInstances)
.Select(limit: 1, offset: 0)
.Select(limit: 1, offset: 2)
.AsTransaction()
.Execute(TestDb.Provider);
Assert.AreEqual(1, firstResults.Count);
Assert.AreEqual(1, lastResults.Count);
Assert.AreEqual(sourceInstances[0].Data, firstResults.First().Data);
Assert.AreEqual(sourceInstances[2].Data, lastResults.First().Data);
}
private class BasicPocoWithGuidId
{
public Guid Id { get; private set; }
public string Data { get; set; }
}
}
}
| mit | C# |
4e7b4146fd635b1b9cd12d3612a4a5b33fef64b4 | Update SlimyYoyoProjectile.cs | Minesap/TheMinepack | Projectiles/SlimyYoyoProjectile.cs | Projectiles/SlimyYoyoProjectile.cs | using Terraria.ID;
using Terraria.ModLoader;
namespace TheMinepack.Projectiles
{
public class SlimyYoyoProjectile : ModProjectile
{
public override void SetDefaults()
{
projectile.CloneDefaults(ProjectileID.Code1);
projectile.name = "Slimy Yoyo";
projectile.width = 16;
projectile.scale = 1.05f;
projectile.height = 16;
projectile.penetrate = 10;
projectile.extraUpdates = 1;
ProjectileID.Sets.TrailCacheLength[projectile.type] = 4;
ProjectileID.Sets.TrailingMode[projectile.type] = 0;
aiType = ProjectileID.Code1;
}
public override void AI()
{
if (Main.rand.Next(15) == 0)
{
Projectile.NewProjectile(projectile.Center.X, projectile.Center.Y, 0f, 0f, 406, projectile.damage, projectile.knockBack, projectile.owner, 0f, 0f);
}
}
}
}
| using Terraria.ID;
using Terraria.ModLoader;
namespace TheMinepack.Projectiles
{
public class SlimyYoyoProjectile : ModProjectile
{
public override void SetDefaults()
{
projectile.CloneDefaults(ProjectileID.Code1);
projectile.name = "Slimy Yoyo";
projectile.width = 16;
projectile.scale = 1.05f;
projectile.height = 16;
projectile.penetrate = 10;
projectile.extraUpdates = 1;
ProjectileID.Sets.TrailCacheLength[projectile.type] = 4;
ProjectileID.Sets.TrailingMode[projectile.type] = 0;
aiType = ProjectileID.Code1;
}
}
} | mit | C# |
021e3f33692eb88b55afd573473b62af7b36193f | Fix menu order. | bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto | Source/Eto/Forms/Menu/ImageMenuItem.cs | Source/Eto/Forms/Menu/ImageMenuItem.cs | using System;
using Eto.Drawing;
using System.Collections.Generic;
namespace Eto.Forms
{
public static class ImageMenuExtensions
{
public static ImageMenuItem Add (this MenuItemCollection items, string text)
{
var item = new ImageMenuItem (items.Parent.Generator);
item.Text = text;
items.Add (item);
return item;
}
}
public interface IImageMenuItem : IMenuActionItem, ISubMenu
{
Image Image { get; set; }
}
public class ImageMenuItem : MenuActionItem, ISubMenuWidget
{
new IImageMenuItem Handler { get { return (IImageMenuItem)base.Handler; } }
readonly MenuItemCollection menuItems;
public ImageMenuItem()
: this((Generator)null)
{
}
public ImageMenuItem (Generator generator) : this (generator, typeof(IImageMenuItem))
{
}
protected ImageMenuItem (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
menuItems = new MenuItemCollection (this, Handler);
}
public override Image Image
{
get { return Handler.Image; }
set { Handler.Image = value; }
}
public void GenerateActions (IEnumerable<MenuItem> actionItems)
{
foreach (var mi in actionItems) {
this.Add(mi);
}
}
public void AddSeparator(int order)
{
this.Add(new SeparatorMenuItem
{
Order = order
});
}
public void Add(List<BaseAction> actions, string actionId, int order)
{
foreach (var a in actions)
{
if (a.ID == actionId)
{
var mi = a.CreateMenuItem();
mi.Order = order;
this.Add(mi);
break;
}
}
}
/// <summary>
/// Adds a menu item based on its Order.
/// </summary>
/// <param name="menuItem"></param>
public void Add(MenuItem menuItem)
{
AddMenuItem(this.menuItems, menuItem);
}
public void Remove(MenuItem menuItem)
{
this.menuItems.Remove(menuItem);
}
public IEnumerable<MenuItem> MenuItems
{
get
{
foreach (var m in this.menuItems)
yield return m;
}
}
/// <summary>
/// Adds a menu item to the specified collection based on its Order.
/// </summary>
/// <param name="menuItems"></param>
/// <param name="menuItem"></param>
public static void AddMenuItem(MenuItemCollection menuItems, MenuItem menuItem)
{
int previousIndex = -1;
if (menuItem.Order != 0)
for (var i = 0; i < menuItems.Count; ++i)
{
if (menuItems[i].Order <= menuItem.Order)
previousIndex = i;
else
break;
}
menuItems.Insert(previousIndex + 1, menuItem);
}
}
} | using System;
using Eto.Drawing;
using System.Collections.Generic;
namespace Eto.Forms
{
public static class ImageMenuExtensions
{
public static ImageMenuItem Add (this MenuItemCollection items, string text)
{
var item = new ImageMenuItem (items.Parent.Generator);
item.Text = text;
items.Add (item);
return item;
}
}
public interface IImageMenuItem : IMenuActionItem, ISubMenu
{
Image Image { get; set; }
}
public class ImageMenuItem : MenuActionItem, ISubMenuWidget
{
new IImageMenuItem Handler { get { return (IImageMenuItem)base.Handler; } }
readonly MenuItemCollection menuItems;
public ImageMenuItem()
: this((Generator)null)
{
}
public ImageMenuItem (Generator generator) : this (generator, typeof(IImageMenuItem))
{
}
protected ImageMenuItem (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
menuItems = new MenuItemCollection (this, Handler);
}
public override Image Image
{
get { return Handler.Image; }
set { Handler.Image = value; }
}
public void GenerateActions (IEnumerable<MenuItem> actionItems)
{
foreach (var mi in actionItems) {
this.Add(mi);
}
}
public void AddSeparator(int order)
{
this.Add(new SeparatorMenuItem
{
Order = order
});
}
public void Add(List<BaseAction> actions, string actionId, int order)
{
foreach (var a in actions)
{
if (a.ID == actionId)
{
var mi = a.CreateMenuItem();
mi.Order = order;
this.Add(mi);
break;
}
}
}
/// <summary>
/// Adds a menu item based on its Order.
/// </summary>
/// <param name="menuItem"></param>
public void Add(MenuItem menuItem)
{
AddMenuItem(this.menuItems, menuItem);
}
public void Remove(MenuItem menuItem)
{
this.menuItems.Remove(menuItem);
}
public IEnumerable<MenuItem> MenuItems
{
get
{
foreach (var m in this.menuItems)
yield return m;
}
}
/// <summary>
/// Adds a menu item to the specified collection based on its Order.
/// </summary>
/// <param name="menuItems"></param>
/// <param name="menuItem"></param>
public static void AddMenuItem(MenuItemCollection menuItems, MenuItem menuItem)
{
int previousIndex = -1;
if (menuItem.Order != 0)
for (var i = 0; i < menuItems.Count; ++i)
{
if (menuItems[i].Order <= menuItem.Order)
previousIndex = i;
else
break;
}
menuItems.Insert(Math.Max(0, previousIndex), menuItem);
}
}
} | bsd-3-clause | C# |
711e28c83e16c0332141ec9dd9f2a0a66c52a770 | fix json save | laktak/hjson-cs,hjson/hjson-cs,hjson/hjson-cs | src/HjsonValue.cs | src/HjsonValue.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace Hjson
{
public static class HjsonValue
{
public static JsonValue Load(string path)
{
if (Path.GetExtension(path).ToLower()==".json") return JsonValue.Load(path);
using (var s=File.OpenRead(path))
return Load(s);
}
public static JsonValue Load(Stream stream)
{
if (stream==null) throw new ArgumentNullException("stream");
return Load(new StreamReader(stream, true));
}
public static JsonValue Load(TextReader textReader)
{
if (textReader==null) throw new ArgumentNullException("textReader");
var ret=new HjsonReader(textReader).Read();
return JsonValue.ToJsonValue(ret);
}
public static JsonValue Parse(string hjsonString)
{
if (hjsonString==null) throw new ArgumentNullException("hjsonString");
return Load(new StringReader(hjsonString));
}
public static void Save(JsonValue json, string path)
{
if (Path.GetExtension(path).ToLower()==".json") { json.Save(path, true); return; }
using (var s=File.CreateText(path))
Save(json, s);
}
public static void Save(JsonValue json, Stream stream)
{
if (stream==null) throw new ArgumentNullException("stream");
Save(json, new StreamWriter(stream));
}
public static void Save(JsonValue json, TextWriter textWriter)
{
if (textWriter==null) throw new ArgumentNullException("textWriter");
new HjsonWriter().Save(json, textWriter, 0);
textWriter.Flush();
}
public static string SaveAsString(JsonValue json)
{
var sw=new StringWriter();
Save(json, sw);
return sw.ToString();
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace Hjson
{
public static class HjsonValue
{
public static JsonValue Load(string path)
{
if (Path.GetExtension(path)=="json") return JsonValue.Load(path);
using (var s=File.OpenRead(path))
return Load(s);
}
public static JsonValue Load(Stream stream)
{
if (stream==null) throw new ArgumentNullException("stream");
return Load(new StreamReader(stream, true));
}
public static JsonValue Load(TextReader textReader)
{
if (textReader==null) throw new ArgumentNullException("textReader");
var ret=new HjsonReader(textReader).Read();
return JsonValue.ToJsonValue(ret);
}
public static JsonValue Parse(string hjsonString)
{
if (hjsonString==null) throw new ArgumentNullException("hjsonString");
return Load(new StringReader(hjsonString));
}
public static void Save(JsonValue json, string path)
{
if (Path.GetExtension(path)=="json") { json.Save(path, true); return; }
using (var s=File.CreateText(path))
Save(json, s);
}
public static void Save(JsonValue json, Stream stream)
{
if (stream==null) throw new ArgumentNullException("stream");
Save(json, new StreamWriter(stream));
}
public static void Save(JsonValue json, TextWriter textWriter)
{
if (textWriter==null) throw new ArgumentNullException("textWriter");
new HjsonWriter().Save(json, textWriter, 0);
textWriter.Flush();
}
public static string SaveAsString(JsonValue json)
{
var sw=new StringWriter();
Save(json, sw);
return sw.ToString();
}
}
}
| mit | C# |
6cbd3cfb6367e5bcbd21b27883e63d8505727c76 | Fix checkbox selection (#2710) | petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard,OrchardCMS/Brochard,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2 | src/OrchardCore.Modules/OrchardCore.Settings/Views/Items/SiteSettingsDeploymentStep.Fields.Edit.cshtml | src/OrchardCore.Modules/OrchardCore.Settings/Views/Items/SiteSettingsDeploymentStep.Fields.Edit.cshtml | @model SiteSettingsDeploymentStepViewModel
@using System.Reflection
@{
var settings = Model.Settings;
}
<h5>@T["Site Settings"]</h5>
<fieldset class="form-group">
<span class="hint">@T["The site settings to add as part of the plan."]</span>
<ul class="list-group w-md-50">
@foreach (var setting in typeof(ISite).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var name = setting.Name;
var checkd = settings?.Contains(name);
<li class="list-group-item">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="@(Html.IdFor(m => m.Settings) + "-" + @name)" name="@Html.NameFor(m => m.Settings)" value="@name" checked="@checkd">
<label class="custom-control-label" for="@(Html.IdFor(m => m.Settings) + "-" + @name)">@name</label>
</div>
</li>
}
</ul>
</fieldset> | @model SiteSettingsDeploymentStepViewModel
@using System.Reflection
@{
var settings = Model.Settings;
}
<h5>@T["Site Settings"]</h5>
<fieldset class="form-group">
<span class="hint">@T["The site settings to add as part of the plan."]</span>
<ul class="list-group w-md-50">
@foreach (var setting in typeof(ISite).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var name = setting.Name;
var checkd = settings?.Contains(name);
<li class="list-group-item">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="@Html.IdFor(m => m.Settings)" name="@Html.NameFor(m => m.Settings)" value="@name" checked="@checkd">
<label class="custom-control-label" for="@Html.IdFor(m => m.Settings)">@name</label>
</div>
</li>
}
</ul>
</fieldset> | bsd-3-clause | C# |
43da68bc23f60b8c722bc3423f74364ae71fc56f | Add comment. | jmarolf/roslyn,xasx/roslyn,srivatsn/roslyn,dpoeschl/roslyn,swaroop-sridhar/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,pdelvo/roslyn,CaptainHayashi/roslyn,ErikSchierboom/roslyn,yeaicc/roslyn,khyperia/roslyn,mgoertz-msft/roslyn,mattwar/roslyn,bartdesmet/roslyn,jmarolf/roslyn,MattWindsor91/roslyn,mattscheffer/roslyn,MattWindsor91/roslyn,tvand7093/roslyn,genlu/roslyn,bkoelman/roslyn,tmeschter/roslyn,bartdesmet/roslyn,kelltrick/roslyn,pdelvo/roslyn,khyperia/roslyn,davkean/roslyn,amcasey/roslyn,mmitche/roslyn,dotnet/roslyn,Hosch250/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,Giftednewt/roslyn,davkean/roslyn,mattwar/roslyn,AnthonyDGreen/roslyn,jkotas/roslyn,tvand7093/roslyn,AlekseyTs/roslyn,tvand7093/roslyn,abock/roslyn,tmat/roslyn,panopticoncentral/roslyn,eriawan/roslyn,nguerrera/roslyn,eriawan/roslyn,yeaicc/roslyn,tmeschter/roslyn,agocke/roslyn,diryboy/roslyn,stephentoub/roslyn,OmarTawfik/roslyn,KirillOsenkov/roslyn,TyOverby/roslyn,AnthonyDGreen/roslyn,heejaechang/roslyn,TyOverby/roslyn,genlu/roslyn,MichalStrehovsky/roslyn,Hosch250/roslyn,amcasey/roslyn,MichalStrehovsky/roslyn,OmarTawfik/roslyn,gafter/roslyn,nguerrera/roslyn,VSadov/roslyn,pdelvo/roslyn,swaroop-sridhar/roslyn,wvdd007/roslyn,weltkante/roslyn,tmeschter/roslyn,mattwar/roslyn,lorcanmooney/roslyn,gafter/roslyn,ErikSchierboom/roslyn,reaction1989/roslyn,swaroop-sridhar/roslyn,aelij/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,AmadeusW/roslyn,KevinRansom/roslyn,abock/roslyn,CaptainHayashi/roslyn,jamesqo/roslyn,mmitche/roslyn,DustinCampbell/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,xasx/roslyn,weltkante/roslyn,reaction1989/roslyn,orthoxerox/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,nguerrera/roslyn,Hosch250/roslyn,paulvanbrenk/roslyn,orthoxerox/roslyn,agocke/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,heejaechang/roslyn,aelij/roslyn,drognanar/roslyn,tmat/roslyn,jamesqo/roslyn,OmarTawfik/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,AnthonyDGreen/roslyn,brettfo/roslyn,dpoeschl/roslyn,weltkante/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,wvdd007/roslyn,brettfo/roslyn,CaptainHayashi/roslyn,cston/roslyn,mattscheffer/roslyn,mavasani/roslyn,jcouv/roslyn,jkotas/roslyn,physhi/roslyn,srivatsn/roslyn,lorcanmooney/roslyn,mmitche/roslyn,robinsedlaczek/roslyn,orthoxerox/roslyn,stephentoub/roslyn,mattscheffer/roslyn,jasonmalinowski/roslyn,VSadov/roslyn,jmarolf/roslyn,abock/roslyn,bkoelman/roslyn,bkoelman/roslyn,shyamnamboodiripad/roslyn,MattWindsor91/roslyn,tmat/roslyn,Giftednewt/roslyn,agocke/roslyn,aelij/roslyn,VSadov/roslyn,gafter/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,DustinCampbell/roslyn,dotnet/roslyn,paulvanbrenk/roslyn,genlu/roslyn,physhi/roslyn,lorcanmooney/roslyn,MattWindsor91/roslyn,yeaicc/roslyn,drognanar/roslyn,mavasani/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,MichalStrehovsky/roslyn,shyamnamboodiripad/roslyn,TyOverby/roslyn,paulvanbrenk/roslyn,brettfo/roslyn,Giftednewt/roslyn,sharwell/roslyn,mavasani/roslyn,amcasey/roslyn,physhi/roslyn,tannergooding/roslyn,DustinCampbell/roslyn,cston/roslyn,dotnet/roslyn,dpoeschl/roslyn,jamesqo/roslyn,xasx/roslyn,robinsedlaczek/roslyn,tannergooding/roslyn,jcouv/roslyn,kelltrick/roslyn,robinsedlaczek/roslyn,mgoertz-msft/roslyn,drognanar/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,srivatsn/roslyn,reaction1989/roslyn,kelltrick/roslyn,diryboy/roslyn,jkotas/roslyn,khyperia/roslyn,cston/roslyn,davkean/roslyn | src/Features/Core/Portable/DesignerAttributes/DesignerAttributeDocumentData.cs | src/Features/Core/Portable/DesignerAttributes/DesignerAttributeDocumentData.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;
namespace Microsoft.CodeAnalysis.DesignerAttributes
{
/// <summary>
/// Marshalling type to pass designer attribute data to/from the OOP process.
/// </summary>
internal struct DesignerAttributeDocumentData : IEquatable<DesignerAttributeDocumentData>
{
public string FilePath;
public string DesignerAttributeArgument;
public bool ContainsErrors;
public bool NotApplicable;
public DesignerAttributeDocumentData(string filePath, string designerAttributeArgument, bool containsErrors, bool notApplicable)
{
FilePath = filePath;
DesignerAttributeArgument = designerAttributeArgument;
ContainsErrors = containsErrors;
NotApplicable = notApplicable;
}
public override bool Equals(object obj)
=> Equals((DesignerAttributeDocumentData)obj);
public bool Equals(DesignerAttributeDocumentData other)
{
return FilePath == other.FilePath &&
DesignerAttributeArgument == other.DesignerAttributeArgument &&
ContainsErrors == other.ContainsErrors &&
NotApplicable == other.NotApplicable;
}
public override int GetHashCode()
=> throw new NotImplementedException();
}
} | // 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;
namespace Microsoft.CodeAnalysis.DesignerAttributes
{
internal struct DesignerAttributeDocumentData : IEquatable<DesignerAttributeDocumentData>
{
public string FilePath;
public string DesignerAttributeArgument;
public bool ContainsErrors;
public bool NotApplicable;
public DesignerAttributeDocumentData(string filePath, string designerAttributeArgument, bool containsErrors, bool notApplicable)
{
FilePath = filePath;
DesignerAttributeArgument = designerAttributeArgument;
ContainsErrors = containsErrors;
NotApplicable = notApplicable;
}
public override bool Equals(object obj)
=> Equals((DesignerAttributeDocumentData)obj);
public bool Equals(DesignerAttributeDocumentData other)
{
return FilePath == other.FilePath &&
DesignerAttributeArgument == other.DesignerAttributeArgument &&
ContainsErrors == other.ContainsErrors &&
NotApplicable == other.NotApplicable;
}
public override int GetHashCode()
=> throw new NotImplementedException();
}
} | mit | C# |
2f0511820af61f6aadb19d628d8af31f627bb0f1 | make interface public | jbijlsma/IdentityServer4,chrisowhite/IdentityServer4,siyo-wang/IdentityServer4,MienDev/IdentityServer4,jbijlsma/IdentityServer4,siyo-wang/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,chrisowhite/IdentityServer4,MienDev/IdentityServer4,siyo-wang/IdentityServer4,chrisowhite/IdentityServer4 | src/IdentityServer4/ResponseHandling/Interfaces/IAuthorizeResponseGenerator.cs | src/IdentityServer4/ResponseHandling/Interfaces/IAuthorizeResponseGenerator.cs | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Models;
using IdentityServer4.Validation;
using System.Threading.Tasks;
namespace IdentityServer4.ResponseHandling
{
public interface IAuthorizeResponseGenerator
{
Task<AuthorizeResponse> CreateResponseAsync(ValidatedAuthorizeRequest request);
}
} | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Models;
using IdentityServer4.Validation;
using System.Threading.Tasks;
namespace IdentityServer4.ResponseHandling
{
interface IAuthorizeResponseGenerator
{
Task<AuthorizeResponse> CreateResponseAsync(ValidatedAuthorizeRequest request);
}
} | apache-2.0 | C# |
04a0c61443bbf5568b5c51a60412c8df1b68dcc3 | Update version to 1.0.0-beta. | RagingRudolf/CodeFirst.UCommerce | source/Core/Properties/AssemblyInfo.cs | source/Core/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("Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Core")]
[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("6d3b008c-8c6d-414e-80f7-5636b2a2ff5e")]
// 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")]
[assembly: AssemblyInformationalVersion("1.0.0-beta")] | 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("Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Core")]
[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("6d3b008c-8c6d-414e-80f7-5636b2a2ff5e")]
// 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")]
[assembly: AssemblyInformationalVersion("1.0.0-alpha")] | mit | C# |
fb5a996a776645f730bda10efee4ad4888a75330 | add onprem authentication sample | kenakamu/UCWA2.0-CS | UCWASDK/TestClient/TokenService.cs | UCWASDK/TestClient/TokenService.cs | using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace TestClient
{
public class TokenService
{
public const string tenant = ""; // i.e. "contoso.onmicrosoft.com";
public static string username = ""; // i.e. "user1@contoso.onmicrosoft.com";
public static string password = ""; // i.e. "password"
private static string clientId = ""; // i.e. "4611b759-70fb-4465-953f-17949b15490a";
private static string sfbResourceId = "00000004-0000-0ff1-ce00-000000000000";
private static string aadInstance = "https://login.microsoftonline.com/{0}";
static public string AquireAADToken(string resourceId = "")
{
if (string.IsNullOrEmpty(resourceId))
resourceId = sfbResourceId;
else
resourceId = new Uri(resourceId).Scheme + "://" + new Uri(resourceId).Host;
var authContext = new AuthenticationContext(string.Format(aadInstance, tenant));
var cred = new UserPasswordCredential(username, password);
AuthenticationResult authenticationResult = null;
try
{
authenticationResult = authContext.AcquireTokenAsync(resourceId, clientId, cred).Result;
}
catch (Exception ex)
{
}
return authenticationResult.AccessToken;
}
static public string AquireOnPremToken(string resourceId = "")
{
// You may want to consider cache the token as it only expired in 8 hours.
// https://msdn.microsoft.com/en-us/skype/ucwa/authenticationinucwa
using (HttpClient client = new HttpClient())
{
// Get OAuth service url
var response = client.GetAsync(resourceId).Result;
var wwwAuthenticate = response.Headers.WwwAuthenticate;
var uri = wwwAuthenticate.Where(x => x.Scheme == "MsRtcOAuth").First().Parameter.Split(',').Where(y => y.Contains("href")).First().Split('=')[1].Replace("\"", "");
// Obtain AccessToken
response = client.PostAsync(uri, new FormUrlEncodedContent(new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password) })).Result;
return JToken.Parse(response.Content.ReadAsStringAsync().Result)["access_token"].ToString();
}
}
static public void SignOut()
{
var authContext = new AuthenticationContext(string.Format(aadInstance, tenant));
authContext.TokenCache.Clear();
}
}
}
| using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestClient
{
public class TokenService
{
public const string tenant = ""; // i.e. "contoso.onmicrosoft.com";
public static string username = ""; // i.e. "user1@contoso.onmicrosoft.com";
public static string password = ""; // i.e. "password"
private static string clientId = ""; // i.e. "4611b759-70fb-4465-953f-17949b15490a";
private static string sfbResourceId = "00000004-0000-0ff1-ce00-000000000000";
private static string aadInstance = "https://login.microsoftonline.com/{0}";
static public string AquireAADToken(string resourceId = "")
{
if (string.IsNullOrEmpty(resourceId))
resourceId = sfbResourceId;
else
resourceId = new Uri(resourceId).Scheme + "://" + new Uri(resourceId).Host;
var authContext = new AuthenticationContext(string.Format(aadInstance, tenant));
var cred = new UserPasswordCredential(username, password);
AuthenticationResult authenticationResult = null;
try
{
authenticationResult = authContext.AcquireTokenAsync(resourceId, clientId, cred).Result;
}
catch (Exception ex)
{
}
return authenticationResult.AccessToken;
}
static public void SignOut()
{
var authContext = new AuthenticationContext(string.Format(aadInstance, tenant));
authContext.TokenCache.Clear();
}
}
}
| mit | C# |
3fff358302b0dd96546fa2e36acef4fbff940653 | make static member a const | dkackman/DynamicRestProxy,dkackman/DynamicRestProxy,jamesholcomb/DynamicRestProxy,jamesholcomb/DynamicRestProxy | UnitTestHelpers/CredentialStore.cs | UnitTestHelpers/CredentialStore.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace UnitTestHelpers
{
/// <summary>
/// This is a quick and dirty way to store service credentials in a place
/// that is easy to acces but stored outside of the source tree so that they
/// do not get checked into github
/// </summary>
public static class CredentialStore
{
private const string _root = @"d:\temp\"; //set this to wherever is appropriate for your keys
public static bool ObjectExists(string name)
{
return File.Exists(_root + name);
}
public static dynamic RetrieveObject(string name)
{
Debug.Assert(File.Exists(_root + name));
try
{
using (var file = File.OpenRead(_root + name))
using (var reader = new StreamReader(file))
{
string json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter());
}
}
catch (Exception e)
{
Debug.Assert(false, e.Message);
}
return null;
}
public static void StoreObject(string name, dynamic o)
{
using (var file = File.Open(_root + name, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(file))
{
string json = JsonConvert.SerializeObject(o);
writer.Write(json);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace UnitTestHelpers
{
/// <summary>
/// This is a quick and dirty way to store service credentials in a place
/// that is easy to acces but stored outside of the source tree so that they
/// do not get checked into github
/// </summary>
public static class CredentialStore
{
private static string _root = @"d:\temp\"; //set this to wherever is appropriate for your keys
public static bool ObjectExists(string name)
{
return File.Exists(_root + name);
}
public static dynamic RetrieveObject(string name)
{
Debug.Assert(File.Exists(_root + name));
try
{
using (var file = File.OpenRead(_root + name))
using (var reader = new StreamReader(file))
{
string json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter());
}
}
catch (Exception e)
{
Debug.Assert(false, e.Message);
}
return null;
}
public static void StoreObject(string name, dynamic o)
{
using (var file = File.Open(_root + name, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(file))
{
string json = JsonConvert.SerializeObject(o);
writer.Write(json);
}
}
}
}
| apache-2.0 | C# |
30d220ce7ee70e92891ea3d9e6c1428d5a6411b9 | Update ThrusterEmitterController.cs | highnet/Java-101,highnet/Java-101 | Unity/ThrusterEmitterController.cs | Unity/ThrusterEmitterController.cs | using UnityEngine;
using System.Collections;
public class ThrusterEmitterController : MonoBehaviour {
ParticleSystem ps;
AudioSource ac;
// Use this for initialization
void Start () {
ps = GetComponent<ParticleSystem>();
ac = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
}
void FixedUpdate()
{
bool SPACE_PRESSED = Input.GetKey(KeyCode.Space);
if (SPACE_PRESSED)
{
if (!ac.isPlaying)
{
ac.Play();
}
} else
{
ac.Stop();
}
var em = ps.emission;
em.enabled = SPACE_PRESSED;
}
}
| mit | C# | |
6faf44b95ac160c775a79bd46e1d1548fe28798a | Add missing properties to Image | carbon/Amazon | src/Amazon.Ec2/Models/Image.cs | src/Amazon.Ec2/Models/Image.cs | using System.Xml.Serialization;
namespace Amazon.Ec2
{
public class Image
{
// i386 | x86_64
[XmlElement("architecture")]
public string Architecture { get; set; }
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("enaSupport")]
public bool EnaSupport { get; set; }
[XmlElement("imageId")]
public string ImageId { get; set; }
[XmlElement("imageLocation")]
public string ImageLocation { get; set; }
[XmlElement("imageOwnerAlias")]
public string ImageOwnerAlias { get; set; }
[XmlElement("imageOwnerId")]
public long ImageOwnerId { get; set; }
// pending | available | invalid | deregistered | transient | failed | error
[XmlElement("imageState")]
public string ImageState { get; set; }
// machine | kernel | ramdisk
[XmlElement("imageType")]
public string ImageType { get; set; }
[XmlElement("isPublic")]
public bool IsPublic { get; set; }
[XmlElement("kernelId")]
public string KernelId { get; set; }
[XmlElement("name")]
public string Name { get; set; }
// Windows | blank
[XmlElement("platform")]
public string Platform { get; set; }
// ovm | xen
[XmlElement("hypervisor")]
public string Hypervisor { get; set; }
[XmlElement("ramDiskId")]
public string RamDiskId { get; set; }
// ebs | instance-store
[XmlElement("rootDeviceType")]
public string RootDeviceType { get; set; }
// hvm | paravirtual
[XmlElement("virtualizationType")]
public string VirtualizationType { get; set; }
}
}
| using System.Xml.Serialization;
namespace Amazon.Ec2
{
public class Image
{
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("enaSupport")]
public bool EnaSupport { get; set; }
[XmlElement("imageId")]
public string ImageId { get; set; }
[XmlElement("imageLocation")]
public string ImageLocation { get; set; }
[XmlElement("imageOwnerAlias")]
public string ImageOwnerAlias { get; set; }
[XmlElement("imageState")]
public string ImageState { get; set; }
[XmlElement("imageType")]
public string ImageType { get; set; }
[XmlElement("isPublic")]
public bool IsPublic { get; set; }
[XmlElement("kernelId")]
public string KernelId { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("architecture")]
public string Architecture { get; set; }
[XmlElement("platform")]
public string Platform { get; set; }
[XmlElement("hypervisor")]
public string Hypervisor { get; set; }
[XmlElement("ramDiskId")]
public string RamDiskId { get; set; }
[XmlElement("rootDeviceType")]
public string RootDeviceType { get; set; }
[XmlElement("virtualizationType")]
public string VirtualizationType { get; set; }
}
}
| mit | C# |
06affb3e9b9ad534f3cc00e587448ead0eb9195c | Fix warp/teleport ack data send (was scale inverted) | HelloKitty/Booma.Proxy | src/Booma.Proxy.Client.Unity.Ship/Handlers/Command/Bursting/GameBurstingCompletedEventCommandHandler.cs | src/Booma.Proxy.Client.Unity.Ship/Handlers/Command/Bursting/GameBurstingCompletedEventCommandHandler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using GladNet;
using UnityEngine;
namespace Booma.Proxy
{
//TODO: Temp disabled, it didn't work. Also, it didn't make other late joining clients see us.
[SceneTypeCreate(GameSceneType.Pioneer2)]
[SceneTypeCreate(GameSceneType.RagolDefault)]
public sealed class GameBurstingCompletedEventCommandHandler : Command60Handler<Sub60GameBurstingCompleteEventCommand>
{
private ICharacterSlotSelectedModel SlotModel { get; }
private IZoneSettings ZoneSettings { get; }
private ILocalPlayerData PlayerData { get; }
private IUnitScalerStrategy ScalerService { get; }
/// <inheritdoc />
public GameBurstingCompletedEventCommandHandler(ILog logger, [NotNull] ICharacterSlotSelectedModel slotModel, [NotNull] ILocalPlayerData playerData, [NotNull] IUnitScalerStrategy scalerService, [NotNull] IZoneSettings zoneSettings)
: base(logger)
{
SlotModel = slotModel ?? throw new ArgumentNullException(nameof(slotModel));
PlayerData = playerData ?? throw new ArgumentNullException(nameof(playerData));
ScalerService = scalerService ?? throw new ArgumentNullException(nameof(scalerService));
ZoneSettings = zoneSettings ?? throw new ArgumentNullException(nameof(zoneSettings));
}
/// <inheritdoc />
protected override async Task HandleSubMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, Sub60GameBurstingCompleteEventCommand command)
{
//It's possible we get this on OUR join. We may not be spawned yet.
if(!PlayerData.isWorldObjectSpawned)
return;
//TODO: At some point, this may not run on the main thread so this won't be safe.
GameObject playerWorldObject = PlayerData.WorldObject;
Vector3<float> scaledPosition = ScalerService.UnScale(playerWorldObject.transform.position).ToNetworkVector3();
float scaledRotation = ScalerService.UnScaleYRotation(playerWorldObject.transform.rotation.y);
//If have to send this message otherwise other client's won't know we're also in the same zone
//It's odd, but it's something we have to do.
await context.PayloadSendService.SendMessage(new Sub60FinishedWarpAckCommand(SlotModel.SlotSelected, ZoneSettings.ZoneId, scaledPosition, scaledRotation).ToPayload());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using GladNet;
using UnityEngine;
namespace Booma.Proxy
{
//TODO: Temp disabled, it didn't work. Also, it didn't make other late joining clients see us.
[SceneTypeCreate(GameSceneType.Pioneer2)]
[SceneTypeCreate(GameSceneType.RagolDefault)]
public sealed class GameBurstingCompletedEventCommandHandler : Command60Handler<Sub60GameBurstingCompleteEventCommand>
{
private ICharacterSlotSelectedModel SlotModel { get; }
private IZoneSettings ZoneSettings { get; }
private ILocalPlayerData PlayerData { get; }
private IUnitScalerStrategy ScalerService { get; }
/// <inheritdoc />
public GameBurstingCompletedEventCommandHandler(ILog logger, [NotNull] ICharacterSlotSelectedModel slotModel, [NotNull] ILocalPlayerData playerData, [NotNull] IUnitScalerStrategy scalerService, [NotNull] IZoneSettings zoneSettings)
: base(logger)
{
SlotModel = slotModel ?? throw new ArgumentNullException(nameof(slotModel));
PlayerData = playerData ?? throw new ArgumentNullException(nameof(playerData));
ScalerService = scalerService ?? throw new ArgumentNullException(nameof(scalerService));
ZoneSettings = zoneSettings ?? throw new ArgumentNullException(nameof(zoneSettings));
}
/// <inheritdoc />
protected override async Task HandleSubMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, Sub60GameBurstingCompleteEventCommand command)
{
//It's possible we get this on OUR join. We may not be spawned yet.
if(!PlayerData.isWorldObjectSpawned)
return;
//TODO: At some point, this may not run on the main thread so this won't be safe.
GameObject playerWorldObject = PlayerData.WorldObject;
float yaxisRotation = playerWorldObject.transform.rotation.eulerAngles.y;
Vector3<float> position = ScalerService.Scale(playerWorldObject.transform.position).ToNetworkVector3();
//When a remote game bursting is complete, we need to send an area/teleport ack.
await context.PayloadSendService.SendMessage(new Sub60FinishedWarpAckCommand(SlotModel.SlotSelected, 0, position, yaxisRotation).ToPayload());
}
}
}
| agpl-3.0 | C# |
60eb963c261658f27fd409e643583dbdc09198dc | Fix typo which caused bug in loading server configs. | Joshua-Ashton/TheGuin2 | src/ConfigSchema/BaseConfig.cs | src/ConfigSchema/BaseConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TheGuin2
{
public class ConfigDefault
{
public string DefaultDir;
}
public class DefaultConfigDefault : ConfigDefault
{
public DefaultConfigDefault()
{
DefaultDir = "{\n}";
}
}
public class BaseConfig<Schema> : BaseConfig<Schema, ConfigDefault>
{ }
public class BaseConfig<Schema, DefaultDir> where DefaultDir : ConfigDefault, new()
{
public static void Set(Schema newSchema, BaseServer server = null)
{
MakeDir(server);
if (server != null)
Globals.GetConfigSystem().SerialiseToFile<Schema>(newSchema, server.GetConfigDir() + "/" + typeof(Schema).Name + ".json");
else
Globals.GetConfigSystem().SerialiseToFile<Schema>(newSchema, typeof(Schema).Name + ".json");
}
private static void MakeDir(BaseServer server = null)
{
string path = "";
if (server != null)
path = StaticConfig.Paths.ConfigPath + "/" + server.GetConfigDir() + "/" + typeof(Schema).Name + ".json";
else
path = StaticConfig.Paths.ConfigPath + "/" + typeof(Schema).Name + ".json";
try
{
if (!File.Exists(path))
File.WriteAllText(path, new DefaultDir().DefaultDir);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static Schema Get(BaseServer server = null)
{
MakeDir(server);
if (server != null)
return Globals.GetConfigSystem().DeserialiseFile<Schema>(server.GetConfigDir() + "/" + typeof(Schema).Name + ".json");
else
return Globals.GetConfigSystem().DeserialiseFile<Schema>(typeof(Schema).Name + ".json");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TheGuin2
{
public class ConfigDefault
{
public string DefaultDir;
}
public class DefaultConfigDefault : ConfigDefault
{
public DefaultConfigDefault()
{
DefaultDir = "{\n}";
}
}
public class BaseConfig<Schema> : BaseConfig<Schema, ConfigDefault>
{ }
public class BaseConfig<Schema, DefaultDir> where DefaultDir : ConfigDefault, new()
{
public static void Set(Schema newSchema, BaseServer server = null)
{
MakeDir(server);
if (server != null)
Globals.GetConfigSystem().SerialiseToFile<Schema>(newSchema, server.GetConfigDir() + typeof(Schema).Name + ".json");
else
Globals.GetConfigSystem().SerialiseToFile<Schema>(newSchema, typeof(Schema).Name + ".json");
}
private static void MakeDir(BaseServer server = null)
{
string path = "";
if (server != null)
path = StaticConfig.Paths.ConfigPath + "/" + server.GetConfigDir() + "/" + typeof(Schema).Name + ".json";
else
path = StaticConfig.Paths.ConfigPath + "/" + typeof(Schema).Name + ".json";
try
{
if (!File.Exists(path))
File.WriteAllText(path, new DefaultDir().DefaultDir);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static Schema Get(BaseServer server = null)
{
MakeDir(server);
if (server != null)
return Globals.GetConfigSystem().DeserialiseFile<Schema>(server.GetConfigDir() + "/" + typeof(Schema).Name + ".json");
else
return Globals.GetConfigSystem().DeserialiseFile<Schema>(typeof(Schema).Name + ".json");
}
}
}
| mit | C# |
e592ba8eb59816de65083a37c6ff37816ad224c5 | Remove unnecessary private variable | mgj/MvvmCross-Dreams,mgj/MvvmCross-Dreams | Dreams.Droid/Setup.cs | Dreams.Droid/Setup.cs | using Android.Content;
using MvvmCross.Droid.Platform;
using MvvmCross.Core.ViewModels;
using MvvmCross.Platform.Platform;
using MvvmCross.Platform;
using artm.MvxPlugins.Logger.Services;
using artm.MvxPlugins.Logger.Droid.Services;
using artm.MvxPlugins.Dialog.Services;
using artm.MvxPlugins.Dialog.Droid.Services;
namespace Dreams.Droid
{
public class Setup : MvxAndroidSetup
{
public Setup(Context applicationContext)
: base(applicationContext)
{
}
protected override IMvxApplication CreateApp()
{
return new Core.App();
}
protected override IMvxTrace CreateDebugTrace()
{
return new DebugTrace();
}
protected override void InitializePlatformServices()
{
base.InitializePlatformServices();
Mvx.ConstructAndRegisterSingleton<IDialogService, DialogService>();
Mvx.RegisterSingleton<ILoggerService>(() => new LoggerService(ApplicationContext));
}
}
}
| using Android.Content;
using MvvmCross.Droid.Platform;
using MvvmCross.Core.ViewModels;
using MvvmCross.Platform.Platform;
using MvvmCross.Platform;
using artm.MvxPlugins.Logger.Services;
using artm.MvxPlugins.Logger.Droid.Services;
using artm.MvxPlugins.Dialog.Services;
using artm.MvxPlugins.Dialog.Droid.Services;
namespace Dreams.Droid
{
public class Setup : MvxAndroidSetup
{
private Context _applicationContext;
public Setup(Context applicationContext)
: base(applicationContext)
{
_applicationContext = applicationContext;
}
protected override IMvxApplication CreateApp()
{
return new Core.App();
}
protected override IMvxTrace CreateDebugTrace()
{
return new DebugTrace();
}
protected override void InitializePlatformServices()
{
base.InitializePlatformServices();
Mvx.ConstructAndRegisterSingleton<IDialogService, DialogService>();
Mvx.RegisterSingleton<ILoggerService>(() => new LoggerService(_applicationContext));
}
}
}
| apache-2.0 | C# |
cbbfb89619ff47ad72fa0127ce62d9668b1ba7b4 | Add failure notes | adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress | tests/SharpCompress.Test/Zip/ZipWriterTests.cs | tests/SharpCompress.Test/Zip/ZipWriterTests.cs | using SharpCompress.Common;
using Xunit;
namespace SharpCompress.Test.Zip
{
public class ZipWriterTests : WriterTests
{
public ZipWriterTests()
: base(ArchiveType.Zip)
{
}
// Failing on net461
[Fact]
public void Zip_Deflate_Write()
{
Write(CompressionType.Deflate, "Zip.deflate.noEmptyDirs.zip", "Zip.deflate.noEmptyDirs.zip");
}
// Failing on net461
[Fact]
public void Zip_BZip2_Write()
{
Write(CompressionType.BZip2, "Zip.bzip2.noEmptyDirs.zip", "Zip.bzip2.noEmptyDirs.zip");
}
// Failing on net461
[Fact]
public void Zip_None_Write()
{
Write(CompressionType.None, "Zip.none.noEmptyDirs.zip", "Zip.none.noEmptyDirs.zip");
}
// Failing on net461
[Fact]
public void Zip_LZMA_Write()
{
Write(CompressionType.LZMA, "Zip.lzma.noEmptyDirs.zip", "Zip.lzma.noEmptyDirs.zip");
}
// Failing on net461
[Fact]
public void Zip_PPMd_Write()
{
Write(CompressionType.PPMd, "Zip.ppmd.noEmptyDirs.zip", "Zip.ppmd.noEmptyDirs.zip");
}
[Fact]
public void Zip_Rar_Write()
{
Assert.Throws<InvalidFormatException>(() => Write(CompressionType.Rar, "Zip.ppmd.noEmptyDirs.zip", "Zip.ppmd.noEmptyDirs.zip"));
}
}
}
| using SharpCompress.Common;
using Xunit;
namespace SharpCompress.Test.Zip
{
public class ZipWriterTests : WriterTests
{
public ZipWriterTests()
: base(ArchiveType.Zip)
{
}
[Fact]
public void Zip_Deflate_Write()
{
Write(CompressionType.Deflate, "Zip.deflate.noEmptyDirs.zip", "Zip.deflate.noEmptyDirs.zip");
}
[Fact]
public void Zip_BZip2_Write()
{
Write(CompressionType.BZip2, "Zip.bzip2.noEmptyDirs.zip", "Zip.bzip2.noEmptyDirs.zip");
}
[Fact]
public void Zip_None_Write()
{
Write(CompressionType.None, "Zip.none.noEmptyDirs.zip", "Zip.none.noEmptyDirs.zip");
}
[Fact]
public void Zip_LZMA_Write()
{
Write(CompressionType.LZMA, "Zip.lzma.noEmptyDirs.zip", "Zip.lzma.noEmptyDirs.zip");
}
[Fact]
public void Zip_PPMd_Write()
{
Write(CompressionType.PPMd, "Zip.ppmd.noEmptyDirs.zip", "Zip.ppmd.noEmptyDirs.zip");
}
[Fact]
public void Zip_Rar_Write()
{
Assert.Throws<InvalidFormatException>(() => Write(CompressionType.Rar, "Zip.ppmd.noEmptyDirs.zip", "Zip.ppmd.noEmptyDirs.zip"));
}
}
}
| mit | C# |
0a9e914beda17d065453d9b329851c8880eaffa7 | update copyright info | NuGet/PoliteCaptcha | GlobalAssemblyInfo.cs | GlobalAssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("The NuGet Team")]
[assembly: AssemblyProduct("PoliteCaptcha")]
[assembly: AssemblyCopyright("Copyright (C) 2015 .NET Foundation")]
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: ComVisible(false)] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("The NuGet Team")]
[assembly: AssemblyProduct("PoliteCaptcha")]
[assembly: AssemblyCopyright("Copyright (C) 2012 OuterCurve Foundation")]
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: ComVisible(false)] | apache-2.0 | C# |
037e203da1854c175f416a2b0d45b4bcd1c35e28 | Improve pipeline interface so that StartWith is now static and actually creates the pipeline for us | HeadspringLabs/bulk-writer | src/BulkWriter/Pipeline/EtlPipeline.cs | src/BulkWriter/Pipeline/EtlPipeline.cs | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BulkWriter.Pipeline.Internal;
using BulkWriter.Pipeline.Steps;
namespace BulkWriter.Pipeline
{
public sealed class EtlPipeline : IEtlPipeline
{
private readonly Stack<IEtlPipelineStep> _pipelineSteps = new Stack<IEtlPipelineStep>();
private EtlPipeline()
{
}
public Task ExecuteAsync()
{
return ExecuteAsync(CancellationToken.None);
}
public Task ExecuteAsync(CancellationToken cancellationToken)
{
var finalStep = _pipelineSteps.Pop();
var finalTask = Task.Run(() => finalStep.Run(cancellationToken), cancellationToken);
while (_pipelineSteps.Count != 0)
{
var taskAction = _pipelineSteps.Pop();
Task.Run(() => taskAction.Run(cancellationToken), cancellationToken);
}
return finalTask;
}
public static IEtlPipelineStep<T, T> StartWith<T>(IEnumerable<T> input)
{
var pipeline = new EtlPipeline();
var etlPipelineSetupContext = new EtlPipelineContext(pipeline, (p, s) => pipeline._pipelineSteps.Push(s));
var step = new StartEtlPipelineStep<T>(etlPipelineSetupContext, input);
pipeline._pipelineSteps.Push(step);
return step;
}
}
}
| using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BulkWriter.Pipeline.Internal;
using BulkWriter.Pipeline.Steps;
namespace BulkWriter.Pipeline
{
public class EtlPipeline : IEtlPipeline
{
private readonly Stack<IEtlPipelineStep> _pipelineSteps = new Stack<IEtlPipelineStep>();
public Task ExecuteAsync()
{
return ExecuteAsync(CancellationToken.None);
}
public Task ExecuteAsync(CancellationToken cancellationToken)
{
var finalStep = _pipelineSteps.Pop();
var finalTask = Task.Run(() => finalStep.Run(cancellationToken), cancellationToken);
while (_pipelineSteps.Count != 0)
{
var taskAction = _pipelineSteps.Pop();
Task.Run(() => taskAction.Run(cancellationToken), cancellationToken);
}
return finalTask;
}
public IEtlPipelineStep<T, T> StartWith<T>(IEnumerable<T> input)
{
var etlPipelineSetupContext = new EtlPipelineContext(this, (p, s) => _pipelineSteps.Push(s));
var step = new StartEtlPipelineStep<T>(etlPipelineSetupContext, input);
_pipelineSteps.Push(step);
return step;
}
}
}
| apache-2.0 | C# |
4525917fd9339639e689ad0a09de50684aee4f6a | Change tab. | toroso/ruibarbo | tungsten.sampletest/Features/TabControlTest.cs | tungsten.sampletest/Features/TabControlTest.cs | using System.Linq;
using NUnit.Framework;
using tungsten.core.Elements;
using tungsten.nunit;
using tungsten.sampletest.AutomationLayer;
namespace tungsten.sampletest.Features
{
[TestFixture]
public class TabControlTest : TestBase
{
[Test]
public void TabItemCount()
{
var mainTabControl = MainWindow.MainTabControl;
mainTabControl.AssertThat(x => x.TabItems().Count(), Is.EqualTo(3));
}
[Test]
public void FirstTabItemIsSelected()
{
var mainTabControl = MainWindow.MainTabControl;
var tab1 = mainTabControl.TabItems().First();
tab1.AssertThat(x => x.IsSelected(), Is.True);
}
[Test]
public void TabControlHasFirstTabItemAsSelected()
{
var mainTabControl = MainWindow.MainTabControl;
mainTabControl.AssertThat(x => x.SelectedItem().Header(), Is.EqualTo("Tab 1"));
}
[Test]
public void ChangeToSecondTabItem()
{
var mainTabControl = MainWindow.MainTabControl;
var tab2 = mainTabControl.TabItems().First(x => x.Header().Equals("Tab 2"));
tab2.Click();
mainTabControl.AssertThat(x => x.SelectedItem().Header(), Is.EqualTo("Tab 2"));
}
}
} | using System.Linq;
using NUnit.Framework;
using tungsten.core.Elements;
using tungsten.nunit;
using tungsten.sampletest.AutomationLayer;
namespace tungsten.sampletest.Features
{
[TestFixture]
public class TabControlTest : TestBase
{
[Test]
public void TabItemCount()
{
var mainTabControl = MainWindow.MainTabControl;
mainTabControl.AssertThat(x => x.TabItems().Count(), Is.EqualTo(3));
}
[Test]
public void FirstTabItemIsSelected()
{
var mainTabControl = MainWindow.MainTabControl;
var tab1 = mainTabControl.TabItems().First();
tab1.AssertThat(x => x.IsSelected(), Is.True);
}
[Test]
public void TabControlHasFirstTabItemAsSelected()
{
var mainTabControl = MainWindow.MainTabControl;
mainTabControl.AssertThat(x => x.SelectedItem().Header(), Is.EqualTo("Tab 1"));
}
}
} | apache-2.0 | C# |
5835b787bddbba0cb8bcfa16b991a36695c3b84f | Fix build | danielwertheim/structurizer | build.cake | build.cake | #load "./buildconfig.cake"
var config = BuildConfig.Create(Context, BuildSystem);
Information("SrcDir: " + config.SrcDir);
Information("OutDir: " + config.OutDir);
Information("SemVer: " + config.SemVer);
Information("BuildVersion: " + config.BuildVersion);
Information("BuildProfile: " + config.BuildProfile);
Information("IsTeamCityBuild: " + config.IsTeamCityBuild);
Task("Default")
.IsDependentOn("InitOutDir")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.IsDependentOn("UnitTests");
Task("CI")
.IsDependentOn("Default")
.IsDependentOn("Pack");
/********************************************/
Task("InitOutDir").Does(() => {
EnsureDirectoryExists(config.OutDir);
CleanDirectory(config.OutDir);
});
Task("Restore").Does(() => {
foreach(var sln in GetFiles(config.SrcDir + "*.sln")) {
DotNetBuild(sln, settings =>
settings
.SetConfiguration(config.BuildProfile)
.SetVerbosity(Verbosity.Minimal)
.WithTarget("Restore")
.WithProperty("TreatWarningsAsErrors", "true"));
}
});
Task("Build").Does(() => {
foreach(var sln in GetFiles(config.SrcDir + "*.sln")) {
DotNetBuild(sln, settings =>
settings
.SetConfiguration(config.BuildProfile)
.SetVerbosity(Verbosity.Minimal)
.WithTarget("Rebuild")
.WithProperty("TreatWarningsAsErrors", "true")
.WithProperty("Version", config.SemVer)
.WithProperty("AssemblyVersion", config.BuildVersion)
.WithProperty("FileVersion", config.BuildVersion));
}
});
Task("UnitTests").Does(() => {
var settings = new DotNetCoreTestSettings {
Configuration = config.BuildProfile,
NoBuild = true
};
foreach(var testProj in GetFiles(config.SrcDir + "tests/**/*.UnitTests.csproj")) {
DotNetCoreTest(testProj.FullPath, settings);
}
});
Task("IntegrationTests").Does(() => {
var settings = new DotNetCoreTestSettings {
Configuration = config.BuildProfile,
NoBuild = true
};
foreach(var testProj in GetFiles(config.SrcDir + "tests/**/*.IntegrationTests.csproj")) {
DotNetCoreTest(testProj.FullPath, settings);
}
});
Task("Pack").Does(() => {
foreach(var sln in GetFiles(config.SrcDir + "projects/**/*.csproj")) {
DotNetBuild(sln, settings =>
settings
.SetConfiguration(config.BuildProfile)
.SetVerbosity(Verbosity.Minimal)
.WithTarget("Pack")
.WithProperty("TreatWarningsAsErrors", "true")
.WithProperty("Version", config.SemVer));
}
CopyFiles(
GetFiles(config.SrcDir + "projects/**/*.nupkg"),
config.OutDir);
});
RunTarget(config.Target); | #tool "nuget:?package=NUnit.ConsoleRunner"
#load "./buildconfig.cake"
var config = BuildConfig.Create(Context, BuildSystem);
var slns = config.SrcDir + "*.sln";
Task("Default")
.IsDependentOn("InitOutDir")
.IsDependentOn("NuGet-Restore")
.IsDependentOn("AssemblyVersion")
.IsDependentOn("Build")
.IsDependentOn("UnitTests");
Task("CI")
.IsDependentOn("Default")
.IsDependentOn("NuGet-Pack");
Task("InitOutDir")
.Does(() => {
EnsureDirectoryExists(config.OutDir);
CleanDirectory(config.OutDir);
});
Task("NuGet-Restore")
.Does(() => NuGetRestore(GetFiles(slns)));
Task("AssemblyVersion").Does(() => {
var file = config.SrcDir + "GlobalAssemblyVersion.cs";
var info = ParseAssemblyInfo(file);
CreateAssemblyInfo(file, new AssemblyInfoSettings {
Version = config.BuildVersion,
InformationalVersion = config.SemVer
});
});
Task("Build").Does(() => {
foreach(var sln in GetFiles(slns)) {
MSBuild(sln, new MSBuildSettings {
Verbosity = Verbosity.Minimal,
ToolVersion = MSBuildToolVersion.VS2015,
Configuration = config.BuildProfile,
PlatformTarget = PlatformTarget.MSIL
}.WithTarget("Rebuild"));
}
});
Task("UnitTests").Does(() =>
{
NUnit3(config.SrcDir + "**/*.UnitTests/bin/" + config.BuildProfile + "/*.UnitTests.dll", new NUnit3Settings {
NoResults = true,
NoHeader = true,
TeamCity = config.IsTeamCityBuild
});
});
Task("NuGet-Pack").Does(() => {
NuGetPack(GetFiles(config.SrcDir + "*.nuspec"), new NuGetPackSettings {
Version = config.SemVer,
BasePath = config.SrcDir,
OutputDirectory = config.OutDir,
Properties = new Dictionary<string, string>
{
{"Configuration", config.BuildProfile}
}
});
});
RunTarget(config.Target); | mit | C# |
aaf8d6f4f7d47545763fc162dc57dbf67decd0a3 | Move SourceType to Esprima namespace (#159) | sebastienros/esprima-dotnet,sebastienros/esprima-dotnet | src/Esprima/SourceType.cs | src/Esprima/SourceType.cs | namespace Esprima
{
public enum SourceType
{
Module,
Script
}
} | public enum SourceType
{
Module,
Script
} | bsd-3-clause | C# |
4134f66c78f7f039908fe853d3646b34ebd374b6 | Add SplashText | kennyvv/Alex,kennyvv/Alex,kennyvv/Alex,kennyvv/Alex | src/Alex/SplashTexts.cs | src/Alex/SplashTexts.cs | using System;
namespace Alex
{
internal static class SplashTexts
{
private static readonly string[] Texts =
{
"Inspired by ThinkOfDeath",
"Weird shit!",
"Uhm, random?",
"This %RANDOM% is a random number!",
"Has a menu!",
"Created in C#",
"O.M.G Why are you reading this?!",
"(Doesn't yet) Support MC:PE",
};
private static readonly Random Random = new Random();
public static string GetSplashText()
{
return Texts[Random.Next(Texts.Length - 1)].Replace("%RANDOM%", Random.Next().ToString());
}
}
}
| using System;
namespace Alex
{
internal static class SplashTexts
{
private static readonly string[] Texts =
{
"Inspired by ThinkOfDeath",
"Weird shit!",
"Works! (Except for many bugs)",
"Uhm, random?",
"This %RANDOM% is a random number!",
"Has a menu!",
"Created in C#",
"O.M.G Why are you reading this?!"
};
private static readonly Random Random = new Random();
public static string GetSplashText()
{
return Texts[Random.Next(Texts.Length - 1)].Replace("%RANDOM%", Random.Next().ToString());
}
}
}
| mpl-2.0 | C# |
fec0696b8e63bb8a4e3fec5130c4b48e1667f252 | fix koi message | 2sic/app-blog,2sic/app-blog,2sic/app-blog | shared/_Assets.cshtml | shared/_Assets.cshtml | @inherits Custom.Hybrid.Razor12
@{
// The Settings contains rules for predefined web resources
var webResources = Settings.WebResources;
// get CSS information about the current Theme
var pageCss = GetService<Connect.Koi.ICss>();
// show warning for admin if koi.json is missing
if(pageCss.IsUnknown && CmsContext.User.IsSiteAdmin) {
<div class='dnnFormMessage dnnFormWarning'>
@Html.Raw(Connect.Koi.Messages.CssInformationMissing) <br>
@Html.Raw(Connect.Koi.Messages.OnlyAdminsSeeThis)
</div>
}
// Include bootstrap 4 if the framework isn't known - then this file is still called, and we add Bootstrap to the page
// Note that the link and script tags are in the System Settings to make it easier to update a live installation
if(!pageCss.Is("bs4")) {
var resBs4 = webResources.Bootstrap4;
if(resBs4.Enabled) { @Html.Raw(webResources.Bootstrap4.Html) }
}
}
@* Include styles of the App *@
<link rel="stylesheet" href="@App.Path/dist/bs4.min.css" data-enableoptimizations="true" />
@* Include libaries / scripts *@
@if(DynamicModel.scripts == true) {
<script src="@App.Path/dist/scripts.min.js" data-enableoptimizations="true"></script>
<script src="@App.Path/dist/lib/sticky-sidebar.min.js" data-enableoptimizations="true"></script>
} | @inherits Custom.Hybrid.Razor12
@{
// The Settings contains rules for predefined web resources
var webResources = Settings.WebResources;
// get CSS information about the current Theme
var pageCss = GetService<Connect.Koi.ICss>();
// show warning for admin if koi.json is missing
if(pageCss.IsUnknown && CmsContext.User.IsSiteAdmin) {
<div class='dnnFormMessage dnnFormWarning'>
This component supports multiple CSS frameworks (Bootstrap3, Bootstrap4). It uses <a href='http://connect-koi.net/' target='_blank'>Koi</a> to detect the CSS framework of the theme/skin. Your theme doesn't broadcast it's CSS-Framework, so the output may look wrong. <br>
To fix this, <a href='http://connect-koi.net/dnn-themes'>add a koi.json file to your theme/skin folder</a>.<br>
<em>note: only admins see this message, and it will disappear when you add a correct koi.json</em>
</div>
}
// Include bootstrap 4 if the framework isn't known - then this file is still called, and we add Bootstrap to the page
// Note that the link and script tags are in the System Settings to make it easier to update a live installation
if(!pageCss.Is("bs4")) {
var resBs4 = webResources.Bootstrap4;
if(resBs4.Enabled) { @Html.Raw(webResources.Bootstrap4.Html) }
}
}
@* Include styles of the App *@
<link rel="stylesheet" href="@App.Path/dist/bs4.min.css" data-enableoptimizations="true" />
@* Include libaries / scripts *@
@if(DynamicModel.scripts == true) {
<script src="@App.Path/dist/scripts.min.js" data-enableoptimizations="true"></script>
<script src="@App.Path/dist/lib/sticky-sidebar.min.js" data-enableoptimizations="true"></script>
} | mit | C# |
f6b743dd06f1cf5b993bf8c709f9ba8188fecb65 | Use assert for internal API | ektrah/nsec | src/Cryptography/Oid.cs | src/Cryptography/Oid.cs | using System;
using System.Diagnostics;
namespace NSec.Cryptography
{
internal struct Oid
{
private readonly byte[] _bytes;
public Oid(
uint first,
uint second,
params uint[] rest)
{
int length = CalcLength(first * 40 + second);
for (int i = 0; i < rest.Length; i++)
length += CalcLength(rest[i]);
byte[] bytes = new byte[length];
int pos = Encode(first * 40 + second, bytes, 0);
for (int i = 0; i < rest.Length; i++)
pos += Encode(rest[i], bytes, pos);
_bytes = bytes;
}
public ReadOnlySpan<byte> Bytes => _bytes ?? ReadOnlySpan<byte>.Empty;
private static int CalcLength(
uint value)
{
int length = 0;
Debug.Assert((value & 0xF0000000) == 0);
if ((value & 0xFFE00000) != 0)
length++;
if ((value & 0xFFFFC000) != 0)
length++;
if ((value & 0xFFFFFF80) != 0)
length++;
length++;
return length;
}
private static int Encode(
uint value,
byte[] buffer,
int pos)
{
int start = pos;
Debug.Assert((value & 0xF0000000) == 0);
if ((value & 0xFFE00000) != 0)
buffer[pos++] = (byte)((value >> 21) & 0x7F | 0x80);
if ((value & 0xFFFFC000) != 0)
buffer[pos++] = (byte)((value >> 14) & 0x7F | 0x80);
if ((value & 0xFFFFFF80) != 0)
buffer[pos++] = (byte)((value >> 7) & 0x7F | 0x80);
buffer[pos++] = (byte)(value & 0x7F);
return pos - start;
}
}
}
| using System;
namespace NSec.Cryptography
{
internal struct Oid
{
private readonly byte[] _bytes;
public Oid(
uint first,
uint second,
params uint[] rest)
{
int length = CalcLength(first * 40 + second);
for (int i = 0; i < rest.Length; i++)
length += CalcLength(rest[i]);
byte[] bytes = new byte[length];
int pos = Encode(first * 40 + second, bytes, 0);
for (int i = 0; i < rest.Length; i++)
pos += Encode(rest[i], bytes, pos);
_bytes = bytes;
}
public ReadOnlySpan<byte> Bytes => _bytes ?? ReadOnlySpan<byte>.Empty;
private static int CalcLength(
uint value)
{
int length = 0;
if ((value & 0xF0000000) != 0)
throw new NotImplementedException();
if ((value & 0xFFE00000) != 0)
length++;
if ((value & 0xFFFFC000) != 0)
length++;
if ((value & 0xFFFFFF80) != 0)
length++;
length++;
return length;
}
private static int Encode(
uint value,
byte[] buffer,
int pos)
{
int start = pos;
if ((value & 0xF0000000) != 0)
throw new NotImplementedException();
if ((value & 0xFFE00000) != 0)
buffer[pos++] = (byte)((value >> 21) & 0x7F | 0x80);
if ((value & 0xFFFFC000) != 0)
buffer[pos++] = (byte)((value >> 14) & 0x7F | 0x80);
if ((value & 0xFFFFFF80) != 0)
buffer[pos++] = (byte)((value >> 7) & 0x7F | 0x80);
buffer[pos++] = (byte)(value & 0x7F);
return pos - start;
}
}
}
| mit | C# |
8a2ca72662e2b67ae32ac453221632bcbf450185 | Add Acknowledge to Event | dominicx/ZabbixApi,binking338/ZabbixApi,HenriqueCaires/ZabbixApi,HenriqueCaires/ZabbixApi | src/ZabbixApi/Services/EventService.cs | src/ZabbixApi/Services/EventService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZabbixApi.Entities;
using ZabbixApi.Helper;
using ZabbixApi;
using Newtonsoft.Json;
namespace ZabbixApi.Services
{
public interface IEventService
{
IList<Event> Get(object filter = null, IList<EventInclude> include = null);
IList<string> Acknowledge(IList<Event> events, string message = null);
IList<string> Acknowledge(IList<string> eventIds, string message = null);
}
public class EventService : ServiceBase<Event>, IEventService
{
public EventService(IContext context) : base(context, "event") { }
public IList<Event> Get(object filter = null, IList<EventInclude> include = null)
{
var includeHelper = new IncludeHelper(include == null ? 1 : include.Sum(x => (int)x));
var @params = new
{
output = "extend",
selectHosts = includeHelper.WhatShouldInclude(EventInclude.Hosts),
selectRelatedObject = includeHelper.WhatShouldInclude(EventInclude.RelatedObject),
select_alerts = includeHelper.WhatShouldInclude(EventInclude.Alerts),
select_acknowledges = includeHelper.WhatShouldInclude(EventInclude.Acknowledges),
filter = filter
};
return BaseGet(@params);
}
public IList<string> Acknowledge(IList<string> eventIds, string message = null)
{
return _context.SendRequest<EventidsResult>(
new
{
eventids = eventIds,
message = message,
},
_className + ".acknowledge"
).ids;
}
public IList<string> Acknowledge(IList<Event> events, string message = null)
{
return Acknowledge(events.Select(x => x.Id).ToList(), message);
}
public class EventidsResult : EntityResultBase
{
[JsonProperty("eventids")]
public override string[] ids { get; set; }
}
}
public enum EventInclude
{
All = 1,
None = 2,
Hosts = 4,
RelatedObject = 8,
Alerts = 16,
Acknowledges = 32
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZabbixApi.Entities;
using ZabbixApi.Helper;
using ZabbixApi;
namespace ZabbixApi.Services
{
public interface IEventService
{
IList<Event> Get(object filter = null, IList<EventInclude> include = null);
}
public class EventService : ServiceBase<Event>, IEventService
{
public EventService(IContext context) : base(context, "event") { }
public IList<Event> Get(object filter = null, IList<EventInclude> include = null)
{
var includeHelper = new IncludeHelper(include == null ? 1 : include.Sum(x => (int)x));
var @params = new
{
output = "extend",
selectHosts = includeHelper.WhatShouldInclude(EventInclude.Hosts),
selectRelatedObject = includeHelper.WhatShouldInclude(EventInclude.RelatedObject),
select_alerts = includeHelper.WhatShouldInclude(EventInclude.Alerts),
select_acknowledges = includeHelper.WhatShouldInclude(EventInclude.Acknowledges),
filter = filter
};
return BaseGet(@params);
}
}
public enum EventInclude
{
All = 1,
None = 2,
Hosts = 4,
RelatedObject = 8,
Alerts = 16,
Acknowledges = 32
}
}
| mit | C# |
20134062c3e8fdd1db360ffff8a2b36dc65d7be4 | Add comment | sonvister/Binance | src/Binance/WebSocket/UserData/SingleUserDataWebSocketClient.cs | src/Binance/WebSocket/UserData/SingleUserDataWebSocketClient.cs | using System;
using System.Linq;
using Binance.Api;
using Binance.WebSocket.Events;
using Microsoft.Extensions.Logging;
namespace Binance.WebSocket.UserData
{
public class SingleUserDataWebSocketClient : UserDataWebSocketClient, ISingleUserDataWebSocketClient
{
/// <summary>
/// Constructor.
/// </summary>
public SingleUserDataWebSocketClient()
: this (new BinanceApi(), new WebSocketStreamProvider())
{ }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="api"></param>
/// <param name="streamProvider"></param>
/// <param name="logger"></param>
public SingleUserDataWebSocketClient(IBinanceApi api, IWebSocketStreamProvider streamProvider, ILogger<SingleUserDataWebSocketClient> logger = null)
: base(api, streamProvider.CreateStream(), logger)
{ }
public override void Subscribe(string listenKey, IBinanceApiUser user, Action<UserDataEventArgs> callback)
{
Throw.IfNull(user, nameof(user));
// Ensure only one user is subscribed.
if (ListenKeys.Count > 0 && ListenKeys.Single().Value != user)
throw new InvalidOperationException($"{nameof(SingleUserDataWebSocketClient)}: Can only subscribe to a single a user.");
base.Subscribe(listenKey, user, callback);
}
}
}
| using System;
using System.Linq;
using Binance.Api;
using Binance.WebSocket.Events;
using Microsoft.Extensions.Logging;
namespace Binance.WebSocket.UserData
{
public class SingleUserDataWebSocketClient : UserDataWebSocketClient, ISingleUserDataWebSocketClient
{
/// <summary>
/// Constructor.
/// </summary>
public SingleUserDataWebSocketClient()
: this (new BinanceApi(), new WebSocketStreamProvider())
{ }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="api"></param>
/// <param name="streamProvider"></param>
/// <param name="logger"></param>
public SingleUserDataWebSocketClient(IBinanceApi api, IWebSocketStreamProvider streamProvider, ILogger<SingleUserDataWebSocketClient> logger = null)
: base(api, streamProvider.CreateStream(), logger)
{ }
public override void Subscribe(string listenKey, IBinanceApiUser user, Action<UserDataEventArgs> callback)
{
Throw.IfNull(user, nameof(user));
if (ListenKeys.Count > 0 && ListenKeys.Single().Value != user)
throw new InvalidOperationException($"{nameof(SingleUserDataWebSocketClient)}: Can only subscribe to a single a user.");
base.Subscribe(listenKey, user, callback);
}
}
}
| mit | C# |
52ba61ce8cd7c1bbd67006d0bcd65e3ffcbbe24f | Use "official" configuration repo. | LogosBible/Leeroy | src/Leeroy/Service.cs | src/Leeroy/Service.cs | using System;
using System.Net;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using Leeroy.Properties;
namespace Leeroy
{
public partial class Service : ServiceBase
{
public Service()
{
InitializeComponent();
Log.Info("Initializing service.");
ServicePointManager.DefaultConnectionLimit = 10;
GitHubClient.SetCredentials(Settings.Default.UserName, Settings.Default.Password);
}
internal void Start()
{
Log.Info("Starting service.");
m_tokenSource = new CancellationTokenSource();
Overseer overseer = new Overseer(m_tokenSource.Token, "Build", "Configuration", "master");
m_task = Task.Factory.StartNew(Program.FailOnException<object>(overseer.Run), m_tokenSource, TaskCreationOptions.LongRunning);
}
internal new void Stop()
{
Log.Info("Stopping service.");
// cancel and wait for all work
m_tokenSource.Cancel();
try
{
m_task.Wait();
}
catch (AggregateException)
{
// TODO: verify this contains a single OperationCanceledException
}
// shut down
m_task.Dispose();
m_tokenSource.Dispose();
}
protected override void OnStart(string[] args)
{
Start();
}
protected override void OnStop()
{
Stop();
}
CancellationTokenSource m_tokenSource;
Task m_task;
static readonly ILog Log = LogManager.GetCurrentClassLogger();
}
}
| using System;
using System.Net;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using Leeroy.Properties;
namespace Leeroy
{
public partial class Service : ServiceBase
{
public Service()
{
InitializeComponent();
Log.Info("Initializing service.");
ServicePointManager.DefaultConnectionLimit = 10;
GitHubClient.SetCredentials(Settings.Default.UserName, Settings.Default.Password);
}
internal void Start()
{
Log.Info("Starting service.");
m_tokenSource = new CancellationTokenSource();
Overseer overseer = new Overseer(m_tokenSource.Token, "BradleyGrainger", "Configuration", "master");
m_task = Task.Factory.StartNew(Program.FailOnException<object>(overseer.Run), m_tokenSource, TaskCreationOptions.LongRunning);
}
internal new void Stop()
{
Log.Info("Stopping service.");
// cancel and wait for all work
m_tokenSource.Cancel();
try
{
m_task.Wait();
}
catch (AggregateException)
{
// TODO: verify this contains a single OperationCanceledException
}
// shut down
m_task.Dispose();
m_tokenSource.Dispose();
}
protected override void OnStart(string[] args)
{
Start();
}
protected override void OnStop()
{
Stop();
}
CancellationTokenSource m_tokenSource;
Task m_task;
static readonly ILog Log = LogManager.GetCurrentClassLogger();
}
}
| mit | C# |
8b100f13b70aa00fdb69304500ea7e2a6a142322 | Fix the flakiness in secrets extension test (#17559) | AsrOneSdk/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net | sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/tests/ConfigurationSecretsFunctionalTests.cs | sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/tests/ConfigurationSecretsFunctionalTests.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.Configuration;
using NUnit.Framework;
namespace Azure.Extensions.AspNetCore.Configuration.Secrets.Tests
{
public class ConfigurationSecretsFunctionalTests: LiveTestBase<ConfigurationTestEnvironment>
{
[Test]
[Category("Live")]
public async Task SecretsAreLoadedFromKeyVault()
{
var vaultUri = new Uri(TestEnvironment.KeyVaultUrl);
var client = new SecretClient(vaultUri, TestEnvironment.Credential);
await client.SetSecretAsync("TestSecret1", "1");
await client.SetSecretAsync("TestSecret2", "2");
await client.SetSecretAsync("Nested--TestSecret3", "3");
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddAzureKeyVault(vaultUri, TestEnvironment.Credential);
IConfigurationRoot configuration = configurationBuilder.Build();
Assert.AreEqual("1", configuration["TestSecret1"]);
Assert.AreEqual("2", configuration["TestSecret2"]);
Assert.AreEqual("3", configuration["Nested:TestSecret3"]);
// KeyVault time resolution is 1sec we can't detect a change faster than that
await Task.Delay(TimeSpan.FromSeconds(1));
await client.SetSecretAsync("TestSecret1", "2");
configuration.Reload();
Assert.AreEqual("2", configuration["TestSecret1"]);
Assert.AreEqual("2", configuration["TestSecret2"]);
Assert.AreEqual("3", configuration["Nested:TestSecret3"]);
}
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.Configuration;
using NUnit.Framework;
namespace Azure.Extensions.AspNetCore.Configuration.Secrets.Tests
{
public class ConfigurationSecretsFunctionalTests: LiveTestBase<ConfigurationTestEnvironment>
{
[Test]
[Category("Live")]
public async Task SecretsAreLoadedFromKeyVault()
{
var vaultUri = new Uri(TestEnvironment.KeyVaultUrl);
var client = new SecretClient(vaultUri, TestEnvironment.Credential);
await client.SetSecretAsync("TestSecret1", "1");
await client.SetSecretAsync("TestSecret2", "2");
await client.SetSecretAsync("Nested--TestSecret3", "3");
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddAzureKeyVault(vaultUri, TestEnvironment.Credential);
IConfigurationRoot configuration = configurationBuilder.Build();
Assert.AreEqual("1", configuration["TestSecret1"]);
Assert.AreEqual("2", configuration["TestSecret2"]);
Assert.AreEqual("3", configuration["Nested:TestSecret3"]);
await client.SetSecretAsync("TestSecret1", "2");
configuration.Reload();
Assert.AreEqual("2", configuration["TestSecret1"]);
Assert.AreEqual("2", configuration["TestSecret2"]);
Assert.AreEqual("3", configuration["Nested:TestSecret3"]);
}
}
} | mit | C# |
337ac4ed6d46acf0489aa4401f54e16e01858a88 | Address an issue blocks query provider parameters being sent. | moegirlwiki/Kaleidoscope | src/Moegirlpedia.MediaWikiInterop.Primitives/Transform/QueryRequestSerializer.cs | src/Moegirlpedia.MediaWikiInterop.Primitives/Transform/QueryRequestSerializer.cs | using Moegirlpedia.MediaWikiInterop.Primitives.Action.Models;
using Moegirlpedia.MediaWikiInterop.Primitives.Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using Moegirlpedia.MediaWikiInterop.Primitives.Foundation.Query;
namespace Moegirlpedia.MediaWikiInterop.Primitives.Transform
{
public class QueryRequestSerializer : IRequestSerializer<QueryInputModel>
{
public Task<HttpContent> SerializeRequestAsync(QueryInputModel content,
CancellationToken ctkn = default(CancellationToken))
{
if (content == null) throw new ArgumentNullException(nameof(content));
return Task.Factory.StartNew<HttpContent>(() =>
{
return new FormUrlEncodedContent(GetKeyPairs(content));
}, ctkn);
}
internal List<KeyValuePair<string, string>> GetKeyPairs(QueryInputModel content)
{
// Intermediate Key-Value pair
var kvPairs = new List<KeyValuePair<string, string>>();
// Query providers
kvPairs.AddRange(content.m_queryProviders.SelectMany(k => k.GetParameters()));
// Query providers meta
kvPairs.AddRange(content.m_queryProviders.Select(i => i.GetType().GetTypeInfo().GetCustomAttribute<QueryProviderAttribute>())
.GroupBy(i => i.Category)
.Select(i => new KeyValuePair<string, string>(i.Key, string.Join("|", i.Select(a => a.Name)))));
// Base parameters
kvPairs.AddRange(content.ToKeyValuePairCollection());
// Set Raw continuation to true
kvPairs.Add(new KeyValuePair<string, string>("rawcontinue", "1"));
// Add format config
kvPairs.AddRange(JsonFormatConfig.FormatConfig);
return kvPairs;
}
}
}
| using Moegirlpedia.MediaWikiInterop.Primitives.Action.Models;
using Moegirlpedia.MediaWikiInterop.Primitives.Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Moegirlpedia.MediaWikiInterop.Primitives.Transform
{
public class QueryRequestSerializer : IRequestSerializer<QueryInputModel>
{
public Task<HttpContent> SerializeRequestAsync(QueryInputModel content,
CancellationToken ctkn = default(CancellationToken))
{
if (content == null) throw new ArgumentNullException(nameof(content));
return Task.Factory.StartNew<HttpContent>(() =>
{
// Intermediate Key-Value pair
var kvPairs = new List<KeyValuePair<string, string>>();
// Query providers
kvPairs.AddRange(content.m_queryProviders.SelectMany(k => k.ToKeyValuePairCollection()));
// Base parameters
kvPairs.AddRange(content.ToKeyValuePairCollection());
// Set Raw continuation to true
kvPairs.Add(new KeyValuePair<string, string>("rawcontinue", "1"));
// Add format config
kvPairs.AddRange(JsonFormatConfig.FormatConfig);
return new FormUrlEncodedContent(kvPairs);
}, ctkn);
}
}
}
| mit | C# |
52725c74829db5880e0460c72dbb84518f804781 | Fix Option<T>.ExpectNone | copygirl/EntitySystem | src/Utility/Option.cs | src/Utility/Option.cs | using System;
using System.Collections.Generic;
namespace EntitySystem.Utility
{
public struct Option<T> : IEquatable<Option<T>>
{
readonly T _value;
public bool HasValue { get; private set; }
public T Value => Expect(() =>
new InvalidOperationException($"Option has no value"));
public Option(T value, bool hasValue = true)
{ _value = value; HasValue = hasValue; }
public static Option<T> None { get; } = new Option<T>();
public static Option<T> Some(T value) => new Option<T>(value);
public T Expect(Func<Exception> func)
{ if (HasValue) return _value; else throw func(); }
public void ExpectNone(Func<Exception> func)
{ if (HasValue) throw func(); }
public T Or(T @default) => (HasValue ? Value : @default);
public T Or(Func<T> func) => (HasValue ? Value : func());
public Option<T> Or(Func<Option<T>> func) => (HasValue ? this : func());
public T OrDefault() => Or(default(T));
public Option<TResult> Map<TResult>(Func<T, TResult> func) =>
(HasValue ? Option<TResult>.Some(func(_value)) : Option<TResult>.None);
public Option<TResult> Map<TResult>(Func<T, Option<TResult>> func) =>
(HasValue ? func(_value) : Option<TResult>.None);
public Option<TResult> Cast<TResult>() =>
(HasValue ? (TResult)(object)_value : Option<TResult>.None);
public static implicit operator Option<T>(T value)
{
if (value == null) throw new ArgumentNullException(
"Implicit conversion to Option requires value to be non-null");
return Option<T>.Some(value);
}
public static explicit operator T(Option<T> option) => option.Value;
public override bool Equals(object obj) =>
((obj is Option<T>) && Equals((Option<T>)obj));
public bool Equals(Option<T> other) =>
Equals(other, EqualityComparer<T>.Default);
public bool Equals(Option<T> other, IEqualityComparer<T> comparer) =>
((HasValue == other.HasValue) &&
(!HasValue || comparer.Equals(_value, other.Value)));
public static bool operator ==(Option<T> left, Option<T> right) => left.Equals(right);
public static bool operator !=(Option<T> left, Option<T> right) => !left.Equals(right);
public override int GetHashCode() =>
(HasValue ? (_value?.GetHashCode() ?? 0) : 0);
public override string ToString() =>
$"{ GetType().GetFriendlyName() }.{ Map((value) => $"Some( { value.ToString()} )").Or("None") }";
}
}
| using System;
using System.Collections.Generic;
namespace EntitySystem.Utility
{
public struct Option<T> : IEquatable<Option<T>>
{
readonly T _value;
public bool HasValue { get; private set; }
public T Value => Expect(() =>
new InvalidOperationException($"Option has no value"));
public Option(T value, bool hasValue = true)
{ _value = value; HasValue = hasValue; }
public static Option<T> None { get; } = new Option<T>();
public static Option<T> Some(T value) => new Option<T>(value);
public T Expect(Func<Exception> func)
{ if (HasValue) return _value; else throw func(); }
public void ExpectNone(Func<Exception> func)
{ if (!HasValue) throw func(); }
public T Or(T @default) => (HasValue ? Value : @default);
public T Or(Func<T> func) => (HasValue ? Value : func());
public Option<T> Or(Func<Option<T>> func) => (HasValue ? this : func());
public T OrDefault() => Or(default(T));
public Option<TResult> Map<TResult>(Func<T, TResult> func) =>
(HasValue ? Option<TResult>.Some(func(_value)) : Option<TResult>.None);
public Option<TResult> Map<TResult>(Func<T, Option<TResult>> func) =>
(HasValue ? func(_value) : Option<TResult>.None);
public Option<TResult> Cast<TResult>() =>
(HasValue ? (TResult)(object)_value : Option<TResult>.None);
public static implicit operator Option<T>(T value)
{
if (value == null) throw new ArgumentNullException(
"Implicit conversion to Option requires value to be non-null");
return Option<T>.Some(value);
}
public static explicit operator T(Option<T> option) => option.Value;
public override bool Equals(object obj) =>
((obj is Option<T>) && Equals((Option<T>)obj));
public bool Equals(Option<T> other) =>
Equals(other, EqualityComparer<T>.Default);
public bool Equals(Option<T> other, IEqualityComparer<T> comparer) =>
((HasValue == other.HasValue) &&
(!HasValue || comparer.Equals(_value, other.Value)));
public static bool operator ==(Option<T> left, Option<T> right) => left.Equals(right);
public static bool operator !=(Option<T> left, Option<T> right) => !left.Equals(right);
public override int GetHashCode() =>
(HasValue ? (_value?.GetHashCode() ?? 0) : 0);
public override string ToString() =>
$"{ GetType().GetFriendlyName() }.{ Map((value) => $"Some( { value.ToString()} )").Or("None") }";
}
}
| mit | C# |
d7bd53837eaed31bf1cd320eaf10aad5c4a2821c | Remove irrellevant tests | appharbor/appharbor-cli | src/AppHarbor.Tests/CommandDispatcherTest.cs | src/AppHarbor.Tests/CommandDispatcherTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Castle.MicroKernel;
using Moq;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Castle.MicroKernel;
using Moq;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
[Theory]
[PropertyData("FooArguments")]
public void ShouldParseAndExecuteCommandWithArguments(string[] commands)
{
var kernelMock = new Mock<IKernel>();
var fooCommandType = typeof(FooCommand);
var commandDispatcher = new CommandDispatcher(new TypeNameMatcher<ICommand>(new Type[] { fooCommandType }), kernelMock.Object);
var commandMock = new Mock<FooCommand>();
kernelMock.Setup(x => x.Resolve(It.Is<Type>(y => y == fooCommandType))).Returns(commandMock.Object);
commandDispatcher.Dispatch(commands);
commandMock.Verify(x => x.Execute(
It.Is<string[]>(y => ArraysEqual(y, commands.Skip(1).ToArray()))), Times.Once());
}
[Theory]
[InlineAutoCommandData("bar")]
[InlineAutoCommandData("foobar")]
public void ShouldNotMatchCommandThatDoesntExist(string commandName)
{
var kernelMock = new Mock<IKernel>();
var fooCommandType = typeof(FooCommand);
var commandDispatcher = new CommandDispatcher(new TypeNameMatcher<ICommand>(new Type[] { fooCommandType }), kernelMock.Object);
var exception = Assert.Throws<ArgumentException>(() => commandDispatcher.Dispatch(new string[] { commandName }));
}
public static IEnumerable<object[]> FooArguments
{
get
{
yield return new object[] { new string[] { "foo" } };
yield return new object[] { new string[] { "Foo" } };
yield return new object[] { new string[] { "foo", "bar" } };
}
}
private static bool ArraysEqual<T>(T[] a1, T[] a2)
{
if (ReferenceEquals(a1, a2))
{
return true;
}
if (a1 == null || a2 == null)
{
return false;
}
if (a1.Length != a2.Length)
{
return false;
}
var comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a1.Length; i++)
{
if (!comparer.Equals(a1[i], a2[i]))
{
return false;
}
}
return true;
}
}
}
| mit | C# |
ee78bd1ae800e8919b73bbc10746dfbe1ecd5462 | Move foo command type to static variable | appharbor/appharbor-cli | src/AppHarbor.Tests/CommandDispatcherTest.cs | src/AppHarbor.Tests/CommandDispatcherTest.cs | using System;
using System.Linq;
using Castle.MicroKernel;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
private static Type FooCommandType = typeof(FooCommand);
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
[Theory, AutoCommandData]
public void ShouldDispatchHelpWhenNoCommand(
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
typeNameMatcher.Setup(x => x.GetMatchedType("help")).Returns(FooCommandType);
kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object);
commandDispatcher.Dispatch(new string[0]);
}
[Theory]
[InlineAutoCommandData("foo")]
[InlineAutoCommandData("foo:bar")]
public void ShouldDispatchCommandWithoutParameters(
string argument,
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
typeNameMatcher.Setup(x => x.GetMatchedType(argument)).Returns(FooCommandType);
kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object);
var dispatchArguments = new string[] { argument };
commandDispatcher.Dispatch(dispatchArguments);
command.Verify(x => x.Execute(It.Is<string[]>(y => !y.Any())));
}
[Theory]
[InlineAutoCommandData("foo:bar baz", "baz")]
[InlineAutoCommandData("foo baz", "baz")]
public void ShouldDispatchCommandWithParameter(
string argument,
string commandArgument,
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
typeNameMatcher.Setup(x => x.GetMatchedType(argument.Split().First())).Returns(FooCommandType);
kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object);
commandDispatcher.Dispatch(argument.Split());
command.Verify(x => x.Execute(It.Is<string[]>(y => y.Length == 1 && y.Any(z => z == commandArgument))));
}
}
}
| using System.Linq;
using Castle.MicroKernel;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
[Theory, AutoCommandData]
public void ShouldDispatchHelpWhenNoCommand(
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
var commandType = typeof(FooCommand);
typeNameMatcher.Setup(x => x.GetMatchedType("help")).Returns(commandType);
kernel.Setup(x => x.Resolve(commandType)).Returns(command.Object);
commandDispatcher.Dispatch(new string[0]);
}
[Theory]
[InlineAutoCommandData("foo")]
[InlineAutoCommandData("foo:bar")]
public void ShouldDispatchCommandWithoutParameters(
string argument,
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
var commandType = typeof(FooCommand);
typeNameMatcher.Setup(x => x.GetMatchedType(argument)).Returns(commandType);
kernel.Setup(x => x.Resolve(commandType)).Returns(command.Object);
var dispatchArguments = new string[] { argument };
commandDispatcher.Dispatch(dispatchArguments);
command.Verify(x => x.Execute(It.Is<string[]>(y => !y.Any())));
}
[Theory]
[InlineAutoCommandData("foo:bar baz", "baz")]
[InlineAutoCommandData("foo baz", "baz")]
public void ShouldDispatchCommandWithParameter(
string argument,
string commandArgument,
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
var commandType = typeof(FooCommand);
typeNameMatcher.Setup(x => x.GetMatchedType(argument.Split().First())).Returns(commandType);
kernel.Setup(x => x.Resolve(commandType)).Returns(command.Object);
commandDispatcher.Dispatch(argument.Split());
command.Verify(x => x.Execute(It.Is<string[]>(y => y.Length == 1 && y.Any(z => z == commandArgument))));
}
}
}
| mit | C# |
a1b8a1b617cd0ac0570b8523dce24848386f4dc8 | Remove watchFileSystem config section property - no longer needed | damiensawyer/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,damiensawyer/cassette,andrewdavey/cassette,honestegg/cassette,andrewdavey/cassette,honestegg/cassette,honestegg/cassette,damiensawyer/cassette | src/Cassette/CassetteConfigurationSection.cs | src/Cassette/CassetteConfigurationSection.cs | using System.Configuration;
namespace Cassette
{
public sealed class CassetteConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("debug", DefaultValue = null)]
public bool? Debug
{
get { return (bool?)this["debug"]; }
set { this["debug"] = value; }
}
[ConfigurationProperty("rewriteHtml", DefaultValue = true)]
public bool RewriteHtml
{
get { return (bool)this["rewriteHtml"]; }
set { this["rewriteHtml"] = value; }
}
[ConfigurationProperty("allowRemoteDiagnostics", DefaultValue = false)]
public bool AllowRemoteDiagnostics
{
get { return (bool)this["allowRemoteDiagnostics"]; }
set { this["allowRemoteDiagnostics"] = value; }
}
[ConfigurationProperty("cacheDirectory", DefaultValue = null)]
public string CacheDirectory
{
get { return (string)this["cacheDirectory"]; }
set { this["cacheDirectory"] = value; }
}
}
} | using System.Configuration;
namespace Cassette
{
public sealed class CassetteConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("debug", DefaultValue = null)]
public bool? Debug
{
get { return (bool?)this["debug"]; }
set { this["debug"] = value; }
}
[ConfigurationProperty("rewriteHtml", DefaultValue = true)]
public bool RewriteHtml
{
get { return (bool)this["rewriteHtml"]; }
set { this["rewriteHtml"] = value; }
}
[ConfigurationProperty("allowRemoteDiagnostics", DefaultValue = false)]
public bool AllowRemoteDiagnostics
{
get { return (bool)this["allowRemoteDiagnostics"]; }
set { this["allowRemoteDiagnostics"] = value; }
}
// TODO: Use it or lose it!
[ConfigurationProperty("watchFileSystem", DefaultValue = null)]
public bool? WatchFileSystem
{
get { return (bool?)this["watchFileSystem"]; }
set { this["watchFileSystem"] = value; }
}
[ConfigurationProperty("cacheDirectory", DefaultValue = null)]
public string CacheDirectory
{
get { return (string)this["cacheDirectory"]; }
set { this["cacheDirectory"] = value; }
}
}
} | mit | C# |
9eb2ab26dc8cdf202555a341f0d242c0b8c9c8ae | Make the intent clearer to accept bodyless PROPFIND | FubarDevelopment/WebDavServer,FubarDevelopment/WebDavServer,FubarDevelopment/WebDavServer | FubarDev.WebDavServer.AspNetCore/Formatters/WebDavXmlSerializerInputFormatter.cs | FubarDev.WebDavServer.AspNetCore/Formatters/WebDavXmlSerializerInputFormatter.cs | using Microsoft.AspNetCore.Mvc.Formatters;
namespace FubarDev.WebDavServer.AspNetCore.Formatters
{
public class WebDavXmlSerializerInputFormatter : XmlSerializerInputFormatter
{
public override bool CanRead(InputFormatterContext context)
{
var request = context.HttpContext.Request;
if (request.ContentType == null)
{
var contentLength = request.ContentLength;
if (contentLength.HasValue && contentLength.Value == 0)
{
switch (request.Method)
{
case "PROPFIND":
return true;
}
}
}
return base.CanRead(context);
}
}
}
| using Microsoft.AspNetCore.Mvc.Formatters;
namespace FubarDev.WebDavServer.AspNetCore.Formatters
{
public class WebDavXmlSerializerInputFormatter : XmlSerializerInputFormatter
{
public override bool CanRead(InputFormatterContext context)
{
var request = context.HttpContext.Request;
if (request.ContentType == null)
{
var contentLength = request.ContentLength;
if (request.Method == "PROPFIND" && contentLength.HasValue && contentLength.Value == 0)
{
return true;
}
}
return base.CanRead(context);
}
}
}
| mit | C# |
ceecba3a12b7cea6788d2897f449b1371fd8d2f4 | Simplify FunctionEntrypoint | martincostello/alexa-london-travel | src/LondonTravel.Skill/FunctionEntrypoint.cs | src/LondonTravel.Skill/FunctionEntrypoint.cs | // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using Alexa.NET.Request;
using Alexa.NET.Response;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.Json;
namespace MartinCostello.LondonTravel.Skill;
/// <summary>
/// A class representing the entry-point to a custom AWS Lambda runtime. This class cannot be inherited.
/// </summary>
/// <remarks>
/// See https://aws.amazon.com/blogs/developer/announcing-amazon-lambda-runtimesupport/.
/// </remarks>
public static class FunctionEntrypoint
{
/// <summary>
/// Runs the function using a custom runtime as an asynchronous operation.
/// </summary>
/// <param name="httpClient">The optional HTTP client to use.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns>
/// A <see cref="Task"/> representing the asynchronous operation to run the function.
/// </returns>
public static async Task RunAsync(
HttpClient httpClient = null,
CancellationToken cancellationToken = default)
{
var serializer = new JsonSerializer();
await using var function = new AlexaFunction();
using var bootstrap = LambdaBootstrapBuilder
.Create<SkillRequest, SkillResponse>(function.HandlerAsync, serializer)
.UseBootstrapHandler(function.InitializeAsync)
.UseHttpClient(httpClient)
.Build();
await bootstrap.RunAsync(cancellationToken);
}
/// <summary>
/// The main entry point for the custom runtime.
/// </summary>
/// <returns>
/// A <see cref="Task"/> representing the asynchronous operation to run the custom runtime.
/// </returns>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
private static async Task Main() => await RunAsync();
}
| // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using Alexa.NET.Request;
using Alexa.NET.Response;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.Json;
namespace MartinCostello.LondonTravel.Skill;
/// <summary>
/// A class representing the entry-point to a custom AWS Lambda runtime. This class cannot be inherited.
/// </summary>
/// <remarks>
/// See https://aws.amazon.com/blogs/developer/announcing-amazon-lambda-runtimesupport/.
/// </remarks>
public static class FunctionEntrypoint
{
/// <summary>
/// Runs the function using a custom runtime as an asynchronous operation.
/// </summary>
/// <param name="httpClient">The optional HTTP client to use.</param>
/// <param name="cancellationToken">The optional cancellation token to use.</param>
/// <returns>
/// A <see cref="Task"/> representing the asynchronous operation to run the function.
/// </returns>
public static async Task RunAsync(
HttpClient httpClient = null,
CancellationToken cancellationToken = default)
{
var serializer = new JsonSerializer();
await using var function = new AlexaFunction();
var builder = LambdaBootstrapBuilder
.Create<SkillRequest, SkillResponse>(function.HandlerAsync, serializer)
.UseBootstrapHandler(function.InitializeAsync);
if (httpClient is not null)
{
builder.UseHttpClient(httpClient);
}
using var bootstrap = builder.Build();
await bootstrap.RunAsync(cancellationToken);
}
/// <summary>
/// The main entry point for the custom runtime.
/// </summary>
/// <returns>
/// A <see cref="Task"/> representing the asynchronous operation to run the custom runtime.
/// </returns>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
private static async Task Main() => await RunAsync();
}
| apache-2.0 | C# |
e51de575d1b10972fe4ca5d4bf45d7f4a0f656ac | Fix ui when contentSummary has unclosed dom tags. | Kasperki/ASPWiki,Kasperki/ASPWiki | aspwiki/Views/Home/PageLink.cshtml | aspwiki/Views/Home/PageLink.cshtml | @using ASPWiki.Model
@model WikiPage
<article class="row" style="margin:15px;word-break:break-all;">
<div class="col-sm-12">
<a href="/Wiki/View/@Model.GetPathString()"><h3>@Model.Title</h3></a>
</div>
<div class="col-sm-12">
@Html.Raw(@Model.GetContentSummary())
</div>
<div class="col-sm-12">
@Html.Partial("~/Views/Wiki/Label.cshtml", Model.label)
<span>Written by: Unknown - Size: @Model.GetSizeKiloBytes() - @Html.DisplayFor(model => model.LastModified)</span>
<a href="#">5 <i class="fa fa-comment-o" aria-hidden="true"></i></a>
</div>
</article> | @using ASPWiki.Model
@model WikiPage
<article style="margin:15px;word-break:break-all;">
<a href="/Wiki/View/@Model.GetPathString()"><h3>@Model.Title</h3></a>
@Html.Raw(@Model.GetContentSummary())
@Html.Partial("~/Views/Wiki/Label.cshtml", Model.label)
<span>Written by: Unknown - Size: @Model.GetSizeKiloBytes() - @Html.DisplayFor(model => model.LastModified)</span>
<a href="#">5 <i class="fa fa-comment-o" aria-hidden="true"></i></a>
</article> | mit | C# |
76521acb592823315be8abd27847168bf2009a1d | Revert "Test" | Theliahh/non-violence,Theliahh/non-violence | src/NVTest/Controllers/Web/HomeController.cs | src/NVTest/Controllers/Web/HomeController.cs | using System;
using Microsoft.AspNet.Mvc;
namespace NVTest.Controllers.Web
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
return View();
}
}
}
| using System;
using Microsoft.AspNet.Mvc;
namespace NVTest.Controllers.Web
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
return View();
}
}//test
}
| apache-2.0 | C# |
42afd3a14a46a55c491de2d6824cb2ea29866091 | CHANGE CONFIG TO PRODUCTION !!! | tlaothong/dailysoccer,tlaothong/dailysoccer,tlaothong/dailysoccer,tlaothong/dailysoccer | DailySoccer2015/ApiApp/MongoAccess/MongoUtil.cs | DailySoccer2015/ApiApp/MongoAccess/MongoUtil.cs | using ApiApp.Models;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
namespace ApiApp.MongoAccess
{
static class MongoUtil
{
#region Fields
private static IMongoClient _client;
private static IMongoDatabase _database;
#endregion Fields
#region Constructors
static MongoUtil()
{
// Production config
var connectionString = WebConfigurationManager.AppSettings["primaryConnectionString"];
_client = new MongoClient(connectionString);
var dbName = WebConfigurationManager.AppSettings["primaryDatabaseName"];
// Test config
//var connectionString = WebConfigurationManager.AppSettings["testConnectionString"];
//_client = new MongoClient(connectionString);
//var dbName = WebConfigurationManager.AppSettings["testDatabaseName"];
_database = _client.GetDatabase(dbName);
}
#endregion Constructors
#region Methods
/// <summary>
/// ดึงข้อมูลจากตาราง
/// </summary>
/// <typeparam name="T">ข้อมูลที่ทำงานด้วย</typeparam>
/// <param name="tableName">ชื่อตาราง</param>
public static IMongoCollection<T> GetCollection<T>(string tableName)
{
return _database.GetCollection<T>(tableName);
}
#endregion Methods
}
}
| using ApiApp.Models;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
namespace ApiApp.MongoAccess
{
static class MongoUtil
{
#region Fields
private static IMongoClient _client;
private static IMongoDatabase _database;
#endregion Fields
#region Constructors
static MongoUtil()
{
// Production config
//var connectionString = WebConfigurationManager.AppSettings["primaryConnectionString"];
//_client = new MongoClient(connectionString);
//var dbName = WebConfigurationManager.AppSettings["primaryDatabaseName"];
// Test config
var connectionString = WebConfigurationManager.AppSettings["testConnectionString"];
_client = new MongoClient(connectionString);
var dbName = WebConfigurationManager.AppSettings["testDatabaseName"];
_database = _client.GetDatabase(dbName);
}
#endregion Constructors
#region Methods
/// <summary>
/// ดึงข้อมูลจากตาราง
/// </summary>
/// <typeparam name="T">ข้อมูลที่ทำงานด้วย</typeparam>
/// <param name="tableName">ชื่อตาราง</param>
public static IMongoCollection<T> GetCollection<T>(string tableName)
{
return _database.GetCollection<T>(tableName);
}
#endregion Methods
}
}
| mit | C# |
00f33e820b703a6bd2168062030d4fd489f5ec4b | Clean up: Pastel | ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth | GalleryMVC_With_Auth/Views/Images/Pastel.cshtml | GalleryMVC_With_Auth/Views/Images/Pastel.cshtml |
@{
ViewBag.Title = "Пастель";
}
<h2>@ViewBag.Title</h2>
<div class="grid">
@for (int i = 0; i < Directory.GetFiles(Server.MapPath("/Content/images/pastel/kondatuk_andr")).Length; i++)
{
<figure class="effect-milo">
<img src="~/Content/images/pastel/kondatuk_andr/@string.Format("{0}.jpg",i)" alt="img0@i" />
<figcaption>
<h2><span>Пастель</span></h2>
<p style="color: red">Автор - Кондатюк Андрей.</p>
<p style="color: red">Цена - 999$!</p>
<a href="#">View more</a>
</figcaption>
</figure>
}
</div> |
@{
ViewBag.Title = "Пастель";
}
<h2>@ViewBag.Title</h2>
<div class="grid">
@for (int i = 0; i < Directory.GetFiles(Server.MapPath("/Content/images/pastel/kondatuk_andr")).Length; i++)
{
<figure class="effect-milo">
<img src="~/Content/images/pastel/kondatuk_andr/@string.Format("{0}.jpg",i)" alt="img0@i" />
<figcaption>
<h2><span>Пастель</span></h2>
<p style="color: red">Автор - Кондатюк Андрей.</p>
<p style="color: red">Цена - 999$!</p>
<a href="#">View more</a>
</figcaption>
</figure>
}
@*@for (int i = 0; i < Directory.GetFiles(Server.MapPath("/Content/images/pastel/kondatuk_andr")).Length; i++)
{
<figure class="effect-dexter">
<img src="~/Content/images/pastel/kondatuk_andr/@string.Format("{0}.jpg",i)" alt="img0@i">
<figcaption>
<h2>О <span>Пастель</span></h2>
<p>Автор - Кондатюк Андрей. Цена - 999$!</p>
<a href="#">View more</a>
</figcaption>
</figure>
}*@
</div> | apache-2.0 | C# |
2b754700aa3e675f23638cc8e57a5f02cf06ff67 | Update DatesTests.cs | manuc66/JsonSubTypes | JsonSubTypes.Tests/DatesTests.cs | JsonSubTypes.Tests/DatesTests.cs | using System;
using Newtonsoft.Json;
using NUnit.Framework;
namespace JsonSubTypes.Tests
{
[TestFixture]
public class DatesTest
{
[JsonConverter(typeof(JsonSubtypes), nameof(SubTypeClass.Discriminator))]
[JsonSubtypes.KnownSubType(typeof(SubTypeClass), "SubTypeClass")]
public abstract class MainClass
{
}
public class SubTypeClass : MainClass
{
public string Discriminator => "SubTypeClass";
public DateTimeOffset? Date { get; set; }
}
[Test]
public void DeserializingSubTypeWithDateParsesCorrectly()
{
var json = "{ \"Discriminator\": \"SubTypeClass\", \"Date\": \"2020-06-28T00:00:00.00000+00:00\" }";
var obj = JsonConvert.DeserializeObject<MainClass>(json);
Assert.That(obj, Is.Not.Null);
Assert.That(obj, Is.InstanceOf<SubTypeClass>());
Assert.That(((SubTypeClass)obj).Date.HasValue, Is.True);
Assert.That(((SubTypeClass)obj).Date.Value.Offset, Is.EqualTo(TimeSpan.Zero));
}
}
}
| using System;
using Newtonsoft.Json;
using NUnit.Framework;
namespace JsonSubTypes.Tests
{
[TestFixture]
public class DatesTest
{
[JsonConverter(typeof(JsonSubtypes), nameof(SubTypeClass.Discriminator))]
public abstract class MainClass
{
}
public class SubTypeClass : MainClass
{
public string Discriminator => "SubTypeClass";
public DateTimeOffset? Date { get; set; }
}
[Test]
public void DeserializingSubTypeWithDateParsesCorrectly()
{
var json = "{ \"Discriminator\": \"MainClass\", \"Date\": \"2020-06-28T00:00:00.00000+00:00\" }";
var obj = JsonConvert.DeserializeObject<SubTypeClass>(json);
Assert.That(obj, Is.Not.Null);
Assert.That(obj.Date.HasValue, Is.True);
Assert.That(obj.Date.Value.Offset, Is.EqualTo(TimeSpan.Zero));
}
}
}
| mit | C# |
6663c06c7ef91f830bd8d1dc76c558f94feee6fb | Remove skip. | AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell | src/ResourceManager/Compute/Commands.Compute.Test/ScenarioTests/NewVhdVMTests.cs | src/ResourceManager/Compute/Commands.Compute.Test/ScenarioTests/NewVhdVMTests.cs | // ----------------------------------------------------------------------------------
//
// Copyright 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.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
namespace Microsoft.Azure.Commands.Compute.Test.ScenarioTests
{
public class NewVhdVMTests
{
public NewVhdVMTests(Xunit.Abstractions.ITestOutputHelper output)
{
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
}
[Fact]
[Trait(Category.AcceptanceType, Category.Flaky)]
public void TestWithValidVhdDiskFile()
{
ComputeTestController.NewInstance.RunPsTest("Test-NewAzureRmVhdVMWithValidDiskFile");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestWithInvalidVhdDiskFile()
{
ComputeTestController.NewInstance.RunPsTest("Test-NewAzureRmVhdVMWithInvalidDiskFile");
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright 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.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
namespace Microsoft.Azure.Commands.Compute.Test.ScenarioTests
{
public class NewVhdVMTests
{
public NewVhdVMTests(Xunit.Abstractions.ITestOutputHelper output)
{
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
}
[Fact(Skip = "Skip until necessary fixes done: https://github.com/Azure/azure-powershell/issues/5692")]
[Trait(Category.AcceptanceType, Category.Flaky)]
public void TestWithValidVhdDiskFile()
{
ComputeTestController.NewInstance.RunPsTest("Test-NewAzureRmVhdVMWithValidDiskFile");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestWithInvalidVhdDiskFile()
{
ComputeTestController.NewInstance.RunPsTest("Test-NewAzureRmVhdVMWithInvalidDiskFile");
}
}
}
| apache-2.0 | C# |
9746c9e1987e170e42e631dcdc2e9ed25b22d753 | Adjust FlanGrab sound effect pannng | Barleytree/NitoriWare,NitorInc/NitoriWare,uulltt/NitoriWare,plrusek/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare | Assets/Resources/Microgames/_Finished/FlanGrab/Scripts/FlanGrab_SightBehaviour.cs | Assets/Resources/Microgames/_Finished/FlanGrab/Scripts/FlanGrab_SightBehaviour.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlanGrab_SightBehaviour : MonoBehaviour {
private GameObject sightSprite;
[SerializeField]
private GameObject meteorInSight;
[SerializeField]
private AudioClip hitClip, missClip;
// Use this for initialization
void Start () {
Cursor.visible = false;
}
// Update is called once per frame
void Update () {
if (!MicrogameController.instance.getVictoryDetermined())
{
moveSightToMousePosition();
if (Input.GetMouseButtonDown(0))
{
CastRay();
}
}
// Deactivate Sight if game has ended
else
{
if (gameObject.activeInHierarchy)
{
gameObject.SetActive(false);
}
}
}
// move sight gameObject to cursor Position
void moveSightToMousePosition()
{
Vector2 mousePosition = CameraHelper.getCursorPosition();
transform.position = mousePosition;
}
// cast CircleCast and destroy every meteor which collider was captured by the CircleCast
void CastRay()
{
var position = new Vector2(transform.position.x, transform.position.y);
var radius = this.GetComponent<CircleCollider2D>().radius;
RaycastHit2D[] colliders = Physics2D.CircleCastAll(position, radius, new Vector2(0, 0));
foreach (RaycastHit2D r in colliders)
{
var objCollider = r.collider;
if (objCollider.name.Contains("Meteor"))
{
var objScript = objCollider.gameObject.GetComponent<FlanGrab_Meteor_BehaviourScript>();
objScript.destroyMeteor();
MicrogameController.instance.playSFX(hitClip, AudioHelper.getAudioPan(CameraHelper.getCursorPosition().x) * .75f);
return;
}
}
MicrogameController.instance.playSFX(missClip, AudioHelper.getAudioPan(CameraHelper.getCursorPosition().x) * .75f);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlanGrab_SightBehaviour : MonoBehaviour {
private GameObject sightSprite;
[SerializeField]
private GameObject meteorInSight;
[SerializeField]
private AudioClip hitClip, missClip;
// Use this for initialization
void Start () {
Cursor.visible = false;
}
// Update is called once per frame
void Update () {
if (!MicrogameController.instance.getVictoryDetermined())
{
moveSightToMousePosition();
if (Input.GetMouseButtonDown(0))
{
CastRay();
}
}
// Deactivate Sight if game has ended
else
{
if (gameObject.activeInHierarchy)
{
gameObject.SetActive(false);
}
}
}
// move sight gameObject to cursor Position
void moveSightToMousePosition()
{
Vector2 mousePosition = CameraHelper.getCursorPosition();
transform.position = mousePosition;
}
// cast CircleCast and destroy every meteor which collider was captured by the CircleCast
void CastRay()
{
var position = new Vector2(transform.position.x, transform.position.y);
var radius = this.GetComponent<CircleCollider2D>().radius;
RaycastHit2D[] colliders = Physics2D.CircleCastAll(position, radius, new Vector2(0, 0));
foreach (RaycastHit2D r in colliders)
{
var objCollider = r.collider;
if (objCollider.name.Contains("Meteor"))
{
var objScript = objCollider.gameObject.GetComponent<FlanGrab_Meteor_BehaviourScript>();
objScript.destroyMeteor();
MicrogameController.instance.playSFX(hitClip, AudioHelper.getAudioPan(CameraHelper.getCursorPosition().x));
return;
}
}
MicrogameController.instance.playSFX(missClip, AudioHelper.getAudioPan(CameraHelper.getCursorPosition().x));
}
}
| mit | C# |
a01267bc6f38c3dec3f1bf4caa020b671bf9ed79 | Remove "register for more config choices" | tpkelly/voting-application,tpkelly/voting-application,stevenhillcox/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application,JDawes-ScottLogic/voting-application,Generic-Voting-Application/voting-application,JDawes-ScottLogic/voting-application,JDawes-ScottLogic/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application,tpkelly/voting-application | VotingApplication/VotingApplication.Web/Views/Routes/UnregisteredDashboard.cshtml | VotingApplication/VotingApplication.Web/Views/Routes/UnregisteredDashboard.cshtml | <div ng-controller="UnregisteredDashboardController">
<form name="quickPollForm" ng-submit="createPoll(pollQuestion)">
<div id="question-block">
Your Question <br />
<input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required />
</div>
<div id="quickpoll-block">
<button type="submit" class="active-btn btn-medium shadowed" ng-disabled="quickPollForm.$invalid">Quick Poll</button>
</div>
</form>
<h3 class="centered-text horizontal-ruled">or</h3>
<div id="register-block">
<button class="active-btn btn-medium shadowed pull-left" ng-click="openLoginDialog()">Sign In</button>
<button class="active-btn btn-medium shadowed pull-right" ng-click="openRegisterDialog()">Register</button>
</div>
</div>
| <div ng-controller="UnregisteredDashboardController">
<div>
<h2>Regular Poller?</h2>
Register for more config choices. It's free!
</div>
<form name="quickPollForm" ng-submit="createPoll(pollQuestion)">
<div id="question-block">
Your Question <br />
<input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required />
</div>
<div id="quickpoll-block">
<button type="submit" class="active-btn btn-medium shadowed" ng-disabled="quickPollForm.$invalid">Quick Poll</button>
</div>
</form>
<h3 class="centered-text horizontal-ruled">or</h3>
<div id="register-block">
<button class="active-btn btn-medium shadowed pull-left" ng-click="openLoginDialog()">Sign In</button>
<button class="active-btn btn-medium shadowed pull-right" ng-click="openRegisterDialog()">Register</button>
</div>
</div>
| apache-2.0 | C# |
0d12aba7ca977ca5a8f080ff9d228d1ee5927f84 | Correct regex to match only full words | pootzko/InfluxData.Net | InfluxData.Net.InfluxDb/Helpers/QueryHelpers.cs | InfluxData.Net.InfluxDb/Helpers/QueryHelpers.cs | using System;
using System.Reflection;
using System.Text.RegularExpressions;
using InfluxData.Net.Common;
using System.Linq;
namespace InfluxData.Net.InfluxDb.Helpers
{
public static class QueryHelpers
{
public static string BuildParameterizedQuery(string query, object param)
{
Type t = param.GetType();
PropertyInfo[] pi = t.GetProperties();
foreach (var propertyInfo in pi)
{
var regex = $@"@{propertyInfo.Name}(?!\w)";
if(!Regex.IsMatch(query, regex) && Nullable.GetUnderlyingType(propertyInfo.GetType()) != null)
throw new ArgumentException($"Missing parameter identifier for @{propertyInfo.Name}");
var paramValue = propertyInfo.GetValue(param);
if (paramValue == null)
continue;
var paramType = paramValue.GetType();
if (!paramType.IsPrimitive && paramType != typeof(String) && paramType != typeof(DateTime))
throw new NotSupportedException($"The type {paramType.Name} is not a supported query parameter type.");
var sanitizedParamValue = paramValue;
if (paramType == typeof(String))
{
sanitizedParamValue = ((string)sanitizedParamValue).Sanitize();
}
while (Regex.IsMatch(query, regex))
{
var match = Regex.Match(query, regex);
query = query.Remove(match.Index, match.Length);
query = query.Insert(match.Index, $"{sanitizedParamValue}");
}
}
return query;
}
}
}
| using System;
using System.Reflection;
using System.Text.RegularExpressions;
using InfluxData.Net.Common;
using System.Linq;
namespace InfluxData.Net.InfluxDb.Helpers
{
public static class QueryHelpers
{
public static string BuildParameterizedQuery(string query, object param)
{
var paramRegex = "@([A-Za-z0-9åäöÅÄÖ'_-]+)";
var matches = Regex.Matches(query, paramRegex);
Type t = param.GetType();
PropertyInfo[] pi = t.GetProperties();
foreach(Match match in matches)
{
if (!pi.Any(x => match.Groups[0].Value.Contains(x.Name)))
throw new ArgumentException($"Missing parameter value for {match.Groups[0].Value}");
}
foreach (var propertyInfo in pi)
{
var paramValue = propertyInfo.GetValue(param);
var paramType = paramValue.GetType();
if(!paramType.IsPrimitive && paramType != typeof(String))
throw new NotSupportedException($"The type {paramType.Name} is not a supported query parameter type.");
var sanitizedParamValue = paramValue;
if(paramType == typeof(String)) {
sanitizedParamValue = ((string)sanitizedParamValue).Sanitize();
}
while (Regex.IsMatch(query, $"@{propertyInfo.Name}"))
{
var match = Regex.Match(query, $"@{propertyInfo.Name}");
query = query.Remove(match.Index, match.Length);
query = query.Insert(match.Index, $"{sanitizedParamValue}");
}
}
return query;
}
}
} | mit | C# |
81b4c46c48711a7c91ddb8456a9bc0dfa143fb67 | Comment added and cleaning | alexandredubois/openapi-csharp-client | Cdiscount.OpenApi.ProxyClient/Contract/Request/GetCartRequest.cs | Cdiscount.OpenApi.ProxyClient/Contract/Request/GetCartRequest.cs | using System;
namespace Cdiscount.OpenApi.ProxyClient.Contract.Request
{
/// <summary>
/// GetCart request object
/// </summary>
public class GetCartRequest
{
/// <summary>
/// Cart identifier
/// </summary>
public Guid CartGuid { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cdiscount.OpenApi.ProxyClient.Contract.Request
{
/// <summary>
/// GetCart request object
/// </summary>
public class GetCartRequest
{
public Guid CartGuid { get; set; }
}
}
| mit | C# |
5585cc890c82c95ebb6157ee03f4f3593bd72620 | Add test to prove that OnActivation is syncronous | jquintus/spikes,jquintus/spikes,jquintus/spikes,jquintus/spikes | ConsoleApps/FunWithSpikes/FunWithNinject/Initialization/Tests.cs | ConsoleApps/FunWithSpikes/FunWithNinject/Initialization/Tests.cs | namespace FunWithNinject.Initialization
{
using Ninject;
using NUnit.Framework;
using System.Threading;
[TestFixture]
public class Tests
{
[Test]
public void OnActivation_CanCallMethodOnImplementation()
{
// Assemble
var k = new StandardKernel();
k.Bind<IInitializable>()
.To<Initializable>()
.OnActivation(i => i.CallMe());
// Act
var initted = k.Get<IInitializable>();
// Assert
Assert.IsTrue(((Initializable)initted).CalledMe);
}
[Test]
public void OnActivation_CanCallMethodOnInterface()
{
// Assemble
var k = new StandardKernel();
k.Bind<IInitializable>()
.To<Initializable>()
.OnActivation(i => i.Init());
// Act
var initted = k.Get<IInitializable>();
// Assert
Assert.IsTrue(initted.IsInit);
}
[Test]
public void OnActivation_RunsSyncrhonously()
{
var currentId = Thread.CurrentThread.ManagedThreadId;
var k = new StandardKernel();
k.Bind<IFoo>()
.To<Foo>()
.OnActivation(i =>
{
Assert.AreEqual(currentId, Thread.CurrentThread.ManagedThreadId);
});
}
}
} | namespace FunWithNinject.Initialization
{
using Ninject;
using NUnit.Framework;
[TestFixture]
public class Tests
{
[Test]
public void OnActivation_CanCallMethodOnImplementation()
{
// Assemble
var k = new StandardKernel();
k.Bind<IInitializable>()
.To<Initializable>()
.OnActivation(i => i.CallMe());
// Act
var initted = k.Get<IInitializable>();
// Assert
Assert.IsTrue(((Initializable)initted).CalledMe);
}
[Test]
public void OnActivation_CanCallMethodOnInterface()
{
// Assemble
var k = new StandardKernel();
k.Bind<IInitializable>()
.To<Initializable>()
.OnActivation(i => i.Init());
// Act
var initted = k.Get<IInitializable>();
// Assert
Assert.IsTrue(initted.IsInit);
}
}
} | mit | C# |
f9677d7d28a2090f659b1b8dc879bffc59e191d8 | add missing styles | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | Dashen/Components/ListComponent.cs | Dashen/Components/ListComponent.cs | namespace Dashen.Components
{
public class ListComponent : Component<ListModel>
{
public override string GetJsx()
{
return @"
var ListComponent = React.createClass({
render: function() {
var items = (this.props.model.Items || []).map(function(item) {
return <li className=''>{item}</li>;
});
return (
<ul className='no-bullet'>{items}</ul>
);
}
});
";
}
}
}
| namespace Dashen.Components
{
public class ListComponent : Component<ListModel>
{
public override string GetJsx()
{
return @"
var ListComponent = React.createClass({
render: function() {
var items = (this.props.model.Items || []).map(function(item) {
return <li>{item}</li>;
});
return (
<ul>{items}</ul>
);
}
});
";
}
}
}
| lgpl-2.1 | C# |
083b7c9bf0d634c8c378e2a9956a52c94830dfc0 | update Quartz Management Contract | Paymentsense/Dapper.SimpleSave | PS.Mothership.Core/PS.Mothership.Core.Common/Contracts/IQuartzManagementService.cs | PS.Mothership.Core/PS.Mothership.Core.Common/Contracts/IQuartzManagementService.cs | using PS.Mothership.Core.Common.Constructs;
using PS.Mothership.Core.Common.Dto.DynamicRequest;
using PS.Mothership.Core.Common.Dto.QuartzManagement;
using PS.Mothership.Core.Common.Enums.QuartzManagement;
using Quartz;
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace PS.Mothership.Core.Common.Contracts
{
[ServiceContract(Name = "QuartzManagementService")]
public interface IQuartzManagementService
{
[OperationContract]
QuartzServerInfoDto GetQuartzServerInfo();
[OperationContract]
void ScheduleNewJob(string triggerName, string jobName, AvailableJobGroupsEnum jobGroupName,
string jobClass, IntervalUnit occurance, string interval, DateTimeOffset startTime, IEnumerable<DayOfWeek> dayOfWeek = null);
[OperationContract]
void PauseAllTriggers();
[OperationContract]
void ResumeAllTriggers();
[OperationContract]
void PauseJob(string jobName);
[OperationContract]
void ResumeJob(string jobName);
[OperationContract]
void PauseTrigger(string triggerName);
[OperationContract]
void ResumeTrigger(string triggerName);
[OperationContract]
PagedList<JobProfileDto> GetJobs(DataRequestDto dataRequestDto);
[OperationContract]
void ExecuteJobNow(string jobName);
[OperationContract]
void AddTriggerToJob(string triggerName, string jobName,
IntervalUnit occurance, string interval, DateTimeOffset startTime, IEnumerable<DayOfWeek> dayOfWeek = null);
[OperationContract]
void DeleteTriggerFromJob(string triggerName);
[OperationContract]
void RescheduleTrigger(string triggerName, IntervalUnit occurance, string interval, DateTimeOffset startTime,
IEnumerable<DayOfWeek> dayOfWeek = null);
}
}
| using PS.Mothership.Core.Common.Constructs;
using PS.Mothership.Core.Common.Dto.DynamicRequest;
using PS.Mothership.Core.Common.Dto.QuartzManagement;
using PS.Mothership.Core.Common.Enums.QuartzManagement;
using Quartz;
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace PS.Mothership.Core.Common.Contracts
{
[ServiceContract(Name = "QuartzManagementService")]
public interface IQuartzManagementService
{
[OperationContract]
QuartzServerInfoDto GetQuartzServerInfo();
[OperationContract]
void ScheduleNewJob(string triggerName, string jobName, AvailableJobGroupsEnum jobGroupName,
string jobClass, IntervalUnit occurance, string interval, DateTimeOffset startTime, IEnumerable<DayOfWeek> dayOfWeek = null);
[OperationContract]
void PauseAllTriggers();
[OperationContract]
void ResumeAllTriggers();
[OperationContract]
void PauseJob(string jobName);
[OperationContract]
void ResumeJob(string jobName);
[OperationContract]
void PauseTrigger(string triggerName);
[OperationContract]
void ResumeTrigger(string triggerName);
[OperationContract]
PagedList<JobProfileDto> GetJobs(DataRequestDto dataRequestDto);
[OperationContract]
void ExecuteJobNow(string jobName);
}
}
| mit | C# |
596ad24985e70f9f5affe74f4212c620967d5a93 | improve dispatcher | Shawak/shawlib | src/shawlib/Dispatcher.cs | src/shawlib/Dispatcher.cs | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ShawLib
{
public class Dispatcher
{
Thread thread;
Queue<Task> queue;
object lockQueue;
bool stop, wait;
public Dispatcher()
{
queue = new Queue<Task>();
lockQueue = new object();
thread = new Thread(taskDispatcher);
thread.IsBackground = true;
thread.Start();
}
public void Add(Action action)
{
Add(new Task(() => action()));
}
public void Add(Task task)
{
queue.Enqueue(task);
}
public void taskDispatcher()
{
Task task;
while (true)
{
if (stop && (!wait || wait && queue.Count == 0))
break;
else if (queue.Count > 0)
{
lock (lockQueue)
task = queue.Dequeue();
task.RunSynchronously();
}
else
{
Thread.Sleep(1);
}
}
}
public void Shutdown(bool waitForPendingTasks = true)
{
stop = true;
wait = waitForPendingTasks;
}
public void Join()
{
thread.Join();
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ShawLib
{
public class Dispatcher
{
Thread thread;
Queue<Task> queue;
object lockQueue;
bool stop;
public Dispatcher()
{
queue = new Queue<Task>();
lockQueue = new object();
stop = false;
thread = new Thread(taskDispatcher);
thread.IsBackground = true;
thread.Start();
}
public void Add(Action action)
{
Add(new Task(() => action()));
}
public void Add(Task task)
{
queue.Enqueue(task);
}
public void taskDispatcher()
{
while (!stop)
lock (lockQueue)
if (queue.Count > 0)
queue.Dequeue().RunSynchronously();
else
Thread.Sleep(1);
}
public void Shutdown()
{
stop = true;
}
public void Join()
{
thread.Join();
}
}
}
| mit | C# |
900b3f01c380ee3a7e93d293f4f71d65851fc5f9 | refactor properties to use backing fields | Pondidum/Stronk,Pondidum/Stronk | src/Stronk/StronkConfiguration.cs | src/Stronk/StronkConfiguration.cs | using System;
using System.Collections.Generic;
using Stronk.PropertySelection;
using Stronk.ValueConversion;
using Stronk.ValueSelection;
namespace Stronk
{
public class StronkConfiguration : IStronkConfiguration
{
public IEnumerable<IValueConverter> ValueConverters => _valueConverters;
public IEnumerable<IPropertySelector> PropertySelectors => _propertySelectors;
public IEnumerable<IValueSelector> ValueSelectors => _valueSelectors;
private readonly List<IValueConverter> _valueConverters;
private readonly List<IPropertySelector> _propertySelectors;
private readonly List<IValueSelector> _valueSelectors;
public StronkConfiguration()
{
_valueConverters = new List<IValueConverter>
{
new LambdaValueConverter<Uri>(val => new Uri(val)),
new EnumValueConverter(),
new FallbackValueConverter()
};
_propertySelectors = new List<IPropertySelector>
{
new PrivateSetterPropertySelector(),
new BackingFieldPropertySelector(),
};
_valueSelectors = new List<IValueSelector>
{
new PropertyNameValueSelector(),
};
}
}
}
| using System;
using System.Collections.Generic;
using Stronk.PropertySelection;
using Stronk.ValueConversion;
using Stronk.ValueSelection;
namespace Stronk
{
public class StronkConfiguration : IStronkConfiguration
{
public IEnumerable<IValueConverter> ValueConverters { get; }
public IEnumerable<IPropertySelector> PropertySelectors { get; }
public IEnumerable<IValueSelector> ValueSelectors { get; }
public StronkConfiguration()
{
ValueConverters = new IValueConverter[]
{
new LambdaValueConverter<Uri>(val => new Uri(val)),
new EnumValueConverter(),
new FallbackValueConverter()
};
PropertySelectors = new IPropertySelector[]
{
new PrivateSetterPropertySelector(),
new BackingFieldPropertySelector(),
};
ValueSelectors = new IValueSelector[]
{
new PropertyNameValueSelector(),
};
}
}
}
| lgpl-2.1 | C# |
bf7cb81cc7ad40aba68fb378d86bbeb3155a8fa7 | Add same type twices adds 2 operations to pending | brian-dot-net/writeasync,brian-dot-net/writeasync,brian-dot-net/writeasync | projects/TraceAnalysisSample/test/TraceAnalysisSample.Test.Unit/EventWindowTest.cs | projects/TraceAnalysisSample/test/TraceAnalysisSample.Test.Unit/EventWindowTest.cs | //-----------------------------------------------------------------------
// <copyright file="EventWindowTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TraceAnalysisSample.Test.Unit
{
using System;
using System.Threading.Tasks;
using Xunit;
public class EventWindowTest
{
public EventWindowTest()
{
}
[Fact]
public void Add_adds_operation_to_pending()
{
EventWindow window = new EventWindow();
int eventId = 1;
Guid instanceId = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
window.Add(eventId, instanceId);
Assert.Equal(1, window.GetPendingCount(eventId));
}
[Fact]
public void Add_same_type_twices_adds_2_operations_to_pending()
{
EventWindow window = new EventWindow();
int eventId = 1;
Guid instanceId1 = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
Guid instanceId2 = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2);
window.Add(eventId, instanceId1);
window.Add(eventId, instanceId2);
Assert.Equal(2, window.GetPendingCount(eventId));
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="EventWindowTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TraceAnalysisSample.Test.Unit
{
using System;
using System.Threading.Tasks;
using Xunit;
public class EventWindowTest
{
public EventWindowTest()
{
}
[Fact]
public void Add_adds_operation_to_pending()
{
EventWindow window = new EventWindow();
int eventId = 1;
Guid instanceId = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
window.Add(eventId, instanceId);
Assert.Equal(1, window.GetPendingCount(eventId));
}
}
}
| unlicense | C# |
6539ba1feee3d3ffb2010d2a92c8cf46229dbb27 | fix build break - make debugOutput back to be not readonly | Microsoft/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet | src/Core/Managed/Shared/Extensibility/Implementation/Tracing/F5DiagnosticsSender.cs | src/Core/Managed/Shared/Extensibility/Implementation/Tracing/F5DiagnosticsSender.cs | namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing
{
using System.Globalization;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation.Platform;
/// <summary>
/// This class is responsible for sending diagnostics information into VS debug output
/// for F5 experience.
/// </summary>
internal class F5DiagnosticsSender : IDiagnosticsSender
{
/// <summary>
/// VS debug output.
/// </summary>
protected IDebugOutput debugOutput;
/// <summary>
/// Initializes a new instance of the <see cref="F5DiagnosticsSender"/> class.
/// </summary>
public F5DiagnosticsSender()
{
this.debugOutput = PlatformSingleton.Current.GetDebugOutput();
}
public void Send(TraceEvent eventData)
{
if (this.debugOutput.IsLogging())
{
if (eventData.MetaData != null && !string.IsNullOrEmpty(eventData.MetaData.MessageFormat))
{
var message = eventData.Payload != null && eventData.Payload.Length > 0 ?
string.Format(CultureInfo.InvariantCulture, eventData.MetaData.MessageFormat, eventData.Payload) :
eventData.MetaData.MessageFormat;
this.debugOutput.WriteLine(message);
}
}
}
}
}
| namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing
{
using System.Globalization;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation.Platform;
/// <summary>
/// This class is responsible for sending diagnostics information into VS debug output
/// for F5 experience.
/// </summary>
internal class F5DiagnosticsSender : IDiagnosticsSender
{
/// <summary>
/// VS debug output.
/// </summary>
protected readonly IDebugOutput debugOutput;
/// <summary>
/// Initializes a new instance of the <see cref="F5DiagnosticsSender"/> class.
/// </summary>
public F5DiagnosticsSender()
{
this.debugOutput = PlatformSingleton.Current.GetDebugOutput();
}
public void Send(TraceEvent eventData)
{
if (this.debugOutput.IsLogging())
{
if (eventData.MetaData != null && !string.IsNullOrEmpty(eventData.MetaData.MessageFormat))
{
var message = eventData.Payload != null && eventData.Payload.Length > 0 ?
string.Format(CultureInfo.InvariantCulture, eventData.MetaData.MessageFormat, eventData.Payload) :
eventData.MetaData.MessageFormat;
this.debugOutput.WriteLine(message);
}
}
}
}
}
| mit | C# |
4887aeb38fdea96c76079c37a1189d988a5a2bed | Update SecurityDefinitionAppender.cs | RSuter/NSwag,aelbatal/NSwag,NSwag/NSwag,quails4Eva/NSwag,NSwag/NSwag,NSwag/NSwag,aelbatal/NSwag,NSwag/NSwag,aelbatal/NSwag,RSuter/NSwag,aelbatal/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,RSuter/NSwag,RSuter/NSwag,RSuter/NSwag | src/NSwag.CodeGeneration/SwaggerGenerators/WebApi/Processors/SecurityDefinitionAppender.cs | src/NSwag.CodeGeneration/SwaggerGenerators/WebApi/Processors/SecurityDefinitionAppender.cs | //-----------------------------------------------------------------------
// <copyright file="SecurityDefinitionAppender.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
namespace NSwag.CodeGeneration.SwaggerGenerators.WebApi.Processors
{
/// <summary>Appends the OAuth2 security scheme to the document's security definitions.</summary>
public class SecurityDefinitionAppender : IDocumentProcessor
{
private readonly string _name;
private readonly SwaggerSecurityScheme _swaggerSecurityScheme;
/// <summary>Initializes a new instance of the <see cref="SecurityDefinitionAppender" /> class.</summary>
/// <param name="name">The name/key of the security scheme/definition.</param>
/// <param name="swaggerSecurityScheme">The Swagger security scheme.</param>
public SecurityDefinitionAppender(string name, SwaggerSecurityScheme swaggerSecurityScheme)
{
_name = name;
_swaggerSecurityScheme = swaggerSecurityScheme;
}
/// <summary>Processes the specified Swagger document.</summary>
/// <param name="document">The document.</param>
public void Process(SwaggerService document)
{
document.SecurityDefinitions[_name] = _swaggerSecurityScheme;
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="SecurityDefinitionAppender.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
namespace NSwag.CodeGeneration.SwaggerGenerators.WebApi.Processors
{
/// <summary>Appends the OAuth2 security scheme to the document's security definitions.</summary>
public class SecurityDefinitionAppender : IDocumentProcessor
{
private readonly string _name;
private readonly SwaggerSecurityScheme _swaggerSecurityScheme;
/// <summary>Initializes a new instance of the <see cref="SecurityDefinitionAppender" /> class.</summary>
/// <param name="name">The name of the schema.</param>
/// <param name="swaggerSecurityScheme">The swagger security scheme.</param>
public SecurityDefinitionAppender(string name, SwaggerSecurityScheme swaggerSecurityScheme)
{
_name = name;
_swaggerSecurityScheme = swaggerSecurityScheme;
}
/// <summary>Processes the specified Swagger document.</summary>
/// <param name="document">The document.</param>
public void Process(SwaggerService document)
{
document.SecurityDefinitions[_name] = _swaggerSecurityScheme;
}
}
} | mit | C# |
0a6b4a63c395824dc7b2ba81a526ec1bc96675fc | Copy changes and companies house link on the company search page | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerAccount/SelectEmployer.cshtml | src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerAccount/SelectEmployer.cshtml | @{ViewBag.Title = "Search for your organisation"; }
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Enter Companies House number</h1>
<p>Use the Companies House number for an organisation that your apprentices will be employed through.</p>
<p><a href="https://beta.companieshouse.gov.uk/" rel="external" target="_blank">Find my Companies House number</a></p>
<form method="POST" action="@Url.Action("SelectEmployer")">
<div class="form-group @(TempData["companyNumberError"] != null ? "error" : "")">
@Html.AntiForgeryToken()
<label class="form-label" for="EmployerRef">Companies House number</label>
@if (TempData["companyNumberError"] != null)
{
<legend>
<span class="error-message">@TempData["companyNumberError"]</span>
</legend>
}
<input class="form-control form-control-3-4" id="EmployerRef" name="EmployerRef" type="text"
aria-required="true"/>
</div>
<button type="submit" class="button" id="submit">Continue</button>
</form>
</div>
</div>
@section breadcrumb {
<div class="breadcrumbs">
<ol>
<li><a href="/" class="back-link">Back to Your User Profile</a></li>
</ol>
</div>
} | @{ViewBag.Title = "Search for your organisation"; }
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Search for your organisation</h1>
<p>Use the companies house number for an organisation that your apprentices will be employed through.</p>
<form method="POST" action="@Url.Action("SelectEmployer")">
<div class="form-group @(TempData["companyNumberError"] != null ? "error" : "")">
@Html.AntiForgeryToken()
<label class="form-label" for="EmployerRef">Companies House number</label>
@if (TempData["companyNumberError"] != null)
{
<legend>
<span class="error-message">@TempData["companyNumberError"]</span>
</legend>
}
<input class="form-control form-control-3-4" id="EmployerRef" name="EmployerRef" type="text"
aria-required="true"/>
</div>
<button type="submit" class="button" id="submit">Continue</button>
</form>
</div>
</div>
@section breadcrumb {
<div class="breadcrumbs">
<ol>
<li><a href="/" class="back-link">Back to Your User Profile</a></li>
</ol>
</div>
} | mit | C# |
d373e22133e3c8ab972491b1cacf29b76c5b5a53 | Adjust grid height | EightBitBoy/EcoRealms | Assets/Scripts/Map/GridRenderer.cs | Assets/Scripts/Map/GridRenderer.cs | using UnityEngine;
using System.Collections;
namespace ecorealms.map {
public class GridRenderer : MonoBehaviour {
private const float WIDTH = 0.05f;
private const float HEIGHT = 0.05f;
private int linesX;
private int linesY;
private Material material;
public void Setup(int chunksX, int chunksY, int tilesX, int tilesY) {
this.linesX = chunksX * tilesX;
this.linesY = chunksY * tilesY;
Initialize();
}
private void Initialize() {
material = new Material((Shader.Find(" Diffuse")));
material.SetColor(0, Color.black);
for(int x = 0; x < linesX; x++){
AddLine("Line" + x, x, 0, x, linesY);
}
for(int y = 0; y < linesY; y++){
AddLine("Line" + y, 0, y, linesX, y);
}
}
private void AddLine(string name, float startX, float startY, float endX, float endY){
Vector3 start = new Vector3(startX, HEIGHT, startY);
Vector3 end = new Vector3(endX, HEIGHT, endY);
GameObject line = new GameObject(name);
LineRenderer renderer = line.AddComponent<LineRenderer>();
line.transform.SetParent(gameObject.transform);
renderer.material = material;
renderer.SetWidth(WIDTH, WIDTH);
renderer.SetPosition(0, start);
renderer.SetPosition(1, end);
}
}
}
| using UnityEngine;
using System.Collections;
namespace ecorealms.map {
public class GridRenderer : MonoBehaviour {
private const float WIDTH = 0.05f;
private const float HEIGHT = 0.1f;
private int linesX;
private int linesY;
private Material material;
public void Setup(int chunksX, int chunksY, int tilesX, int tilesY) {
this.linesX = chunksX * tilesX;
this.linesY = chunksY * tilesY;
Initialize();
}
private void Initialize() {
material = new Material((Shader.Find(" Diffuse")));
material.SetColor(0, Color.black);
for(int x = 0; x < linesX; x++){
AddLine("Line" + x, x, 0, x, linesY);
}
for(int y = 0; y < linesY; y++){
AddLine("Line" + y, 0, y, linesX, y);
}
}
private void AddLine(string name, float startX, float startY, float endX, float endY){
Vector3 start = new Vector3(startX, HEIGHT, startY);
Vector3 end = new Vector3(endX, HEIGHT, endY);
GameObject line = new GameObject(name);
LineRenderer renderer = line.AddComponent<LineRenderer>();
line.transform.SetParent(gameObject.transform);
renderer.material = material;
renderer.SetWidth(WIDTH, WIDTH);
renderer.SetPosition(0, start);
renderer.SetPosition(1, end);
}
}
}
| apache-2.0 | C# |
a2967b5f6f04d8af2bf814b0d09edf5eed814dc3 | Change bar chart type to bar instead of pie | nikspatel007/ChartJS.NET,nikspatel007/ChartJS.NET,nikspatel007/ChartJS.NET | ChartJS.NET/Charts/Bar/BarChart.cs | ChartJS.NET/Charts/Bar/BarChart.cs | using ChartJS.NET.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChartJS.NET.Charts.Bar
{
public class BarChart : BaseChart<BarDataSet, BarChartOptions>
{
private readonly BarChartOptions _barChartOptions = new BarChartOptions();
public override Enums.ChartTypes ChartType { get { return Enums.ChartTypes.Bar; } }
public override BarChartOptions ChartConfig
{
get { return _barChartOptions; }
}
}
}
| using ChartJS.NET.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChartJS.NET.Charts.Bar
{
public class BarChart : BaseChart<BarDataSet, BarChartOptions>
{
private readonly BarChartOptions _barChartOptions = new BarChartOptions();
public override Enums.ChartTypes ChartType { get { return Enums.ChartTypes.Pie; } }
public override BarChartOptions ChartConfig
{
get { return _barChartOptions; }
}
}
}
| mit | C# |
ee3877780cf240d995bd191957a04c690217e9af | Remove BufferStack default value (should always be explicitly provided). | naoey/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,NeoAdonis/osu-framework,peppy/osu-framework,NeoAdonis/osu-framework,default0/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,RedNesto/osu-framework,naoey/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,Tom94/osu-framework,default0/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,RedNesto/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework | osu.Framework/Allocation/BufferStack.cs | osu.Framework/Allocation/BufferStack.cs | // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
namespace osu.Framework.Allocation
{
public class BufferStack
{
private int maxAmountBuffers;
private Stack<byte[]> freeDataBuffers = new Stack<byte[]>();
private HashSet<byte[]> usedDataBuffers = new HashSet<byte[]>();
public BufferStack(int maxAmountBuffers)
{
this.maxAmountBuffers = maxAmountBuffers;
}
private byte[] findFreeBuffer(int minimumLength)
{
byte[] buffer = null;
if (freeDataBuffers.Count > 0)
buffer = freeDataBuffers.Pop();
if (buffer == null || buffer.Length < minimumLength)
buffer = new byte[minimumLength];
if (usedDataBuffers.Count < maxAmountBuffers)
usedDataBuffers.Add(buffer);
return buffer;
}
private void returnFreeBuffer(byte[] buffer)
{
if (usedDataBuffers.Remove(buffer))
// We are here if the element was successfully found and removed
freeDataBuffers.Push(buffer);
}
/// <summary>
/// Reserve a buffer from the texture buffer pool. This is used to avoid excessive amounts of heap allocations.
/// </summary>
/// <param name="minimumLength">The minimum length required of the reserved buffer.</param>
/// <returns>The reserved buffer.</returns>
public byte[] ReserveBuffer(int minimumLength)
{
byte[] buffer;
lock (freeDataBuffers)
buffer = findFreeBuffer(minimumLength);
return buffer;
}
/// <summary>
/// Frees a previously reserved buffer for future reservations.
/// </summary>
/// <param name="buffer">The buffer to be freed. If the buffer has not previously been reserved then this method does nothing.</param>
public void FreeBuffer(byte[] buffer)
{
lock (freeDataBuffers)
returnFreeBuffer(buffer);
}
}
}
| // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
namespace osu.Framework.Allocation
{
public class BufferStack
{
private int maxAmountBuffers;
private Stack<byte[]> freeDataBuffers = new Stack<byte[]>();
private HashSet<byte[]> usedDataBuffers = new HashSet<byte[]>();
public BufferStack(int maxAmountBuffers = 10)
{
this.maxAmountBuffers = maxAmountBuffers;
}
private byte[] findFreeBuffer(int minimumLength)
{
byte[] buffer = null;
if (freeDataBuffers.Count > 0)
buffer = freeDataBuffers.Pop();
if (buffer == null || buffer.Length < minimumLength)
buffer = new byte[minimumLength];
if (usedDataBuffers.Count < maxAmountBuffers)
usedDataBuffers.Add(buffer);
return buffer;
}
private void returnFreeBuffer(byte[] buffer)
{
if (usedDataBuffers.Remove(buffer))
// We are here if the element was successfully found and removed
freeDataBuffers.Push(buffer);
}
/// <summary>
/// Reserve a buffer from the texture buffer pool. This is used to avoid excessive amounts of heap allocations.
/// </summary>
/// <param name="minimumLength">The minimum length required of the reserved buffer.</param>
/// <returns>The reserved buffer.</returns>
public byte[] ReserveBuffer(int minimumLength)
{
byte[] buffer;
lock (freeDataBuffers)
buffer = findFreeBuffer(minimumLength);
return buffer;
}
/// <summary>
/// Frees a previously reserved buffer for future reservations.
/// </summary>
/// <param name="buffer">The buffer to be freed. If the buffer has not previously been reserved then this method does nothing.</param>
public void FreeBuffer(byte[] buffer)
{
lock (freeDataBuffers)
returnFreeBuffer(buffer);
}
}
}
| mit | C# |
5a94909c507d2b6d6969b57c7ff5f9fe0489865a | Update Participante.cs | riickky45/Triton | Acuanet/Acuanet/Participante.cs | Acuanet/Acuanet/Participante.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Acuanet
{
class Participante
{
public string nombre;
public int id;
public string snumero;
public string sclub;
public string id_tag;
public string direcc;
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Acuanet
{
class Participante
{
public string nombre;
public int id;
public string snumero;
public string id_tag;
}
}
| mit | C# |
4f4c20f6332a3f347ba2cc00e50fe933ff86334a | add child action only to banner/footer action methods | yfann/AuthorizationServer,s093294/Thinktecture.AuthorizationServer,s093294/Thinktecture.AuthorizationServer,IdentityModel/AuthorizationServer,yfann/AuthorizationServer,IdentityModel/AuthorizationServer | source/WebHost/Controllers/HomeController.cs | source/WebHost/Controllers/HomeController.cs | /*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license.txt
*/
using System.Web.Mvc;
using Thinktecture.AuthorizationServer.Interfaces;
namespace Thinktecture.AuthorizationServer.WebHost.Controllers
{
public class HomeController : Controller
{
IAuthorizationServerConfiguration config;
public HomeController(IAuthorizationServerConfiguration config)
{
this.config = config;
}
public ActionResult Index()
{
return View();
}
[ChildActionOnly]
public ActionResult Banner()
{
var global = config.GlobalConfiguration;
if (global != null)
{
ViewData["ServerName"] = global.AuthorizationServerName;
}
return PartialView("Banner");
}
[ChildActionOnly]
public ActionResult Footer()
{
return PartialView("Footer");
}
}
}
| /*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license.txt
*/
using System.Web.Mvc;
using Thinktecture.AuthorizationServer.Interfaces;
namespace Thinktecture.AuthorizationServer.WebHost.Controllers
{
public class HomeController : Controller
{
IAuthorizationServerConfiguration config;
public HomeController(IAuthorizationServerConfiguration config)
{
this.config = config;
}
public ActionResult Index()
{
return View();
}
public ActionResult Banner()
{
var global = config.GlobalConfiguration;
if (global != null)
{
ViewData["ServerName"] = global.AuthorizationServerName;
}
return PartialView("Banner");
}
public ActionResult Footer()
{
return PartialView("Footer");
}
}
}
| bsd-3-clause | C# |
db6b5d6fe1090483675d01ed2e792fb72a801c40 | Build vector object | eivindveg/PG3300-Innlevering1 | SnakeMess/Vector.cs | SnakeMess/Vector.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Vector
{
private int x
{
get;
set;
}
private int y
{
get;
set;
}
public Vector()
{
this.x = 0;
this.y = 0;
}
public Vector(int x, int y)
{
this.x = x;
this.y = y;
}
}
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Vector
{
private int x
{
get;
set;
}
private int y
{
get;
set;
}
}
| mit | C# |
87037e0da0b04bf2219b65fc8e35945cab11f167 | Revert "new capabilites, minor version" | G3N7/MonJobs | MonJobs/Properties/AssemblyInfo.cs | MonJobs/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MonJobs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MonJobs")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("763b7fef-ff24-407d-8dce-5313e6129941")]
// 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.12.1.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MonJobs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MonJobs")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("763b7fef-ff24-407d-8dce-5313e6129941")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.13.0.0")]
| mit | C# |
40871a0258c16982a18e407184edc35ccc39617b | Fix zero being interpreted as 1/1/1970 instead of DateTime.MinValue | Baggykiin/Curse.NET | Curse.NET/CurseApiConverters.cs | Curse.NET/CurseApiConverters.cs | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Curse.NET
{
internal class MillisecondEpochConverter : DateTimeConverterBase
{
private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(((int)(((DateTime)value - epoch).TotalMilliseconds)).ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null || (long) reader.Value == 0)
{
return DateTime.MinValue;
}
return epoch.AddMilliseconds((long)reader.Value);
}
}
/// <summary>
/// Converter for JSON integer properties that are set to null when they should've been set to zero.
/// </summary>
internal class NullableIntConverter : DateTimeConverterBase
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(((int)value).ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
{
return 0;
}
// Double cast is necessary to convert a boxed long first to a long, then to an int.
return (int)(long)reader.Value;
}
}
}
| using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Curse.NET
{
internal class MillisecondEpochConverter : DateTimeConverterBase
{
private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(((int)(((DateTime)value - epoch).TotalMilliseconds)).ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
{
return DateTime.MinValue;
}
return epoch.AddMilliseconds((long)reader.Value);
}
}
internal class NullableIntConverter : DateTimeConverterBase
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(((int)value).ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
{
return 0;
}
// Double cast is necessary to convert a boxed long first to a long, then to an int.
return (int)(long)reader.Value;
}
}
}
| mit | C# |
2f888599f3ae995e42877be46a85c2ee4317ad0c | Add another error message to LoycInterop example | jonathanvdc/Pixie,jonathanvdc/Pixie | Examples/LoycInterop/Program.cs | Examples/LoycInterop/Program.cs | using System;
using Pixie.Terminal;
using Pixie.Loyc;
using Pixie;
using Pixie.Transforms;
using Loyc.Syntax;
using Loyc;
using Loyc.Ecs;
using Loyc.Collections;
using Pixie.Markup;
namespace LoycInterop
{
public static class Program
{
public static void Main(string[] args)
{
// This example demonstrates how to translate an error
// generated by Loyc into a Pixie diagnostic.
// First, acquire a terminal log. We'll configure it to
// turn everything it sees into a diagnostic.
var log = new TransformLog(
TerminalLog.Acquire(),
new Func<LogEntry, LogEntry>[]
{
MakeDiagnostic
});
// Create a message sink that redirects messages to the log.
var messageSink = new PixieMessageSink(log);
// Next, we'll create a C# source file with some syntax errors
// in it.
var file = new SourceFile<ICharSource>(new UString("int int x = 10; class A"), "input.cs");
// Now, parse the document and watch the syntax error emerge
// as a Pixie diagnostic.
EcsLanguageService.Value.Parse(
file.Text,
file.FileName,
messageSink,
null,
true).ToArray<LNode>();
}
private static LogEntry MakeDiagnostic(LogEntry entry)
{
var newEntry = DiagnosticExtractor.Transform(entry, "program");
return new LogEntry(newEntry.Severity, WrapBox.WordWrap(newEntry.Contents));
}
}
}
| using System;
using Pixie.Terminal;
using Pixie.Loyc;
using Pixie;
using Pixie.Transforms;
using Loyc.Syntax;
using Loyc;
using Loyc.Ecs;
using Loyc.Collections;
using Pixie.Markup;
namespace LoycInterop
{
public static class Program
{
public static void Main(string[] args)
{
// This example demonstrates how to translate an error
// generated by Loyc into a Pixie diagnostic.
// First, acquire a terminal log. We'll configure it to
// turn everything it sees into a diagnostic.
var log = new TransformLog(
TerminalLog.Acquire(),
new Func<LogEntry, LogEntry>[]
{
MakeDiagnostic
});
// Create a message sink that redirects messages to the log.
var messageSink = new PixieMessageSink(log);
// Next, we'll create a C# source file with a syntax error
// in it.
var file = new SourceFile<ICharSource>(new UString("int int x = 10;"), "input.cs");
// Now, parse the document and watch the syntax error emerge
// as a Pixie diagnostic.
EcsLanguageService.Value.Parse(
file.Text,
file.FileName,
messageSink,
null,
true).ToArray<LNode>();
}
private static LogEntry MakeDiagnostic(LogEntry entry)
{
var newEntry = DiagnosticExtractor.Transform(entry, "program");
return new LogEntry(newEntry.Severity, WrapBox.WordWrap(newEntry.Contents));
}
}
}
| mit | C# |
f041ef22f7184d5718a96c1c123b6d8ce7ecce70 | Allow 0 for ports | HelloKitty/GladNet2.0,HelloKitty/GladNet2.0,HelloKitty/GladNet2,HelloKitty/GladNet2 | src/GladNet.Lidgren.Engine.Common/Network/Threading/Peer/LidgrenConnectionDetailsAdapter.cs | src/GladNet.Lidgren.Engine.Common/Network/Threading/Peer/LidgrenConnectionDetailsAdapter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using Lidgren.Network;
using GladNet.Engine.Common;
namespace GladNet.Lidgren.Engine.Common
{
//Basically the same as the PhotonServer details adapter.
/// <summary>
/// Lidgren details adapter for the <see cref="IConnectionDetails"/> interface.
/// </summary>
public class LidgrenConnectionDetailsAdapter : IConnectionDetails
{
/// <summary>
/// IPAddress of the remote peer.
/// </summary>
public IPAddress RemoteIP { get; }
/// <summary>
/// Remote port of the peer.
/// </summary>
public int RemotePort { get; }
/// <summary>
/// Local port the peer is connecting on.
/// </summary>
public int LocalPort { get; }
/// <summary>
/// AUID of the peer. (Application-wide unique)
/// </summary>
public int ConnectionID { get; }
/// <summary>
/// Creates a new adapter for the <see cref="IConnectionDetails"/> interface.
/// </summary>
/// <param name="remoteIP">Remote IP address of the connection.</param>
/// <param name="remotePort">Remote port of the connection.</param>
/// <param name="localPort">Local port of the connection.</param>
/// <param name="connectionID">Unique (port-wise) ID of the connection.</param>
public LidgrenConnectionDetailsAdapter(string remoteIP, int remotePort, int localPort, int uniqueIdentifier)
{
if (string.IsNullOrEmpty(remoteIP)) throw new ArgumentException("Value cannot be null or empty.", nameof(remoteIP));
if (remotePort < 0) throw new ArgumentOutOfRangeException(nameof(remotePort));
if (localPort < 0) throw new ArgumentOutOfRangeException(nameof(localPort));
RemoteIP = IPAddress.Parse(remoteIP);
RemotePort = remotePort;
LocalPort = localPort;
ConnectionID = uniqueIdentifier;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using Lidgren.Network;
using GladNet.Engine.Common;
namespace GladNet.Lidgren.Engine.Common
{
//Basically the same as the PhotonServer details adapter.
/// <summary>
/// Lidgren details adapter for the <see cref="IConnectionDetails"/> interface.
/// </summary>
public class LidgrenConnectionDetailsAdapter : IConnectionDetails
{
/// <summary>
/// IPAddress of the remote peer.
/// </summary>
public IPAddress RemoteIP { get; }
/// <summary>
/// Remote port of the peer.
/// </summary>
public int RemotePort { get; }
/// <summary>
/// Local port the peer is connecting on.
/// </summary>
public int LocalPort { get; }
/// <summary>
/// AUID of the peer. (Application-wide unique)
/// </summary>
public int ConnectionID { get; }
/// <summary>
/// Creates a new adapter for the <see cref="IConnectionDetails"/> interface.
/// </summary>
/// <param name="remoteIP">Remote IP address of the connection.</param>
/// <param name="remotePort">Remote port of the connection.</param>
/// <param name="localPort">Local port of the connection.</param>
/// <param name="connectionID">Unique (port-wise) ID of the connection.</param>
public LidgrenConnectionDetailsAdapter(string remoteIP, int remotePort, int localPort, int uniqueIdentifier)
{
if (string.IsNullOrEmpty(remoteIP)) throw new ArgumentException("Value cannot be null or empty.", nameof(remoteIP));
if (remotePort <= 0) throw new ArgumentOutOfRangeException(nameof(remotePort));
if (localPort <= 0) throw new ArgumentOutOfRangeException(nameof(localPort));
RemoteIP = IPAddress.Parse(remoteIP);
RemotePort = remotePort;
LocalPort = localPort;
ConnectionID = uniqueIdentifier;
}
}
}
| bsd-3-clause | C# |
f9990351b2a2afb9dacabb1821a4e97a845bff37 | Update UnitOfWorkManager to allow multiple DbContextFactory instances | aliencube/Entity-Context-Library,aliencube/Entity-Context-Library,aliencube/Entity-Context-Library | SourceCodes/03_Services/EntityContextLibrary/UnitOfWorkManager.cs | SourceCodes/03_Services/EntityContextLibrary/UnitOfWorkManager.cs | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Aliencube.EntityContextLibrary.Interfaces;
namespace Aliencube.EntityContextLibrary
{
/// <summary>
/// This represents an entity for the unit of work manager.
/// </summary>
public class UnitOfWorkManager : IUnitOfWorkManager
{
private readonly IEnumerable<IDbContextFactory> _contextFactories;
private bool _disposed;
/// <summary>
/// Initialises a new instance of the <c>UnitOfWorkManager</c> class.
/// </summary>
/// <param name="contextFactories">List of the <c>DbContextFactory</c> instances.</param>
public UnitOfWorkManager(params IDbContextFactory[] contextFactories)
{
if (contextFactories == null)
{
throw new ArgumentNullException("contextFactories");
}
if (contextFactories.Length == 0)
{
throw new InvalidOperationException("No parameter provided");
}
this._contextFactories = contextFactories;
}
/// <summary>
/// Creates a new <c>UnitOfWork</c> instance.
/// </summary>
/// <typeparam name="TContext"><c>DbContext</c> type instance.</typeparam>
/// <returns>Returns a new <c>UnitOfWork</c> instance.</returns>
public UnitOfWork<TContext> CreateInstance<TContext>() where TContext : DbContext
{
var contextFactory = this._contextFactories
.SingleOrDefault(p => p.DbContextType == typeof(TContext));
if (contextFactory == null)
{
throw new InvalidOperationException("No DbContext found");
}
return new UnitOfWork<TContext>(contextFactory);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing,
/// or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (this._disposed)
{
return;
}
//this._contextFactory.Dispose();
this._disposed = true;
}
}
} | using System;
using System.Data.Entity;
using Aliencube.EntityContextLibrary.Interfaces;
namespace Aliencube.EntityContextLibrary
{
/// <summary>
/// This represents an entity for the unit of work manager.
/// </summary>
public class UnitOfWorkManager : IUnitOfWorkManager
{
private readonly IDbContextFactory _contextFactory;
private bool _disposed;
/// <summary>
/// Initialises a new instance of the <c>UnitOfWorkManager</c> class.
/// </summary>
/// <param name="contextFactory"><c>DbContextFactory</c> instance.</param>
public UnitOfWorkManager(IDbContextFactory contextFactory)
{
if (contextFactory == null)
{
throw new ArgumentNullException("contextFactory");
}
this._contextFactory = contextFactory;
}
/// <summary>
/// Creates a new <c>UnitOfWork</c> instance.
/// </summary>
/// <typeparam name="TContext"><c>DbContext</c> type instance.</typeparam>
/// <returns>Returns a new <c>UnitOfWork</c> instance.</returns>
public UnitOfWork<TContext> CreateInstance<TContext>()
where TContext : DbContext
{
return new UnitOfWork<TContext>(this._contextFactory);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing,
/// or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (this._disposed)
{
return;
}
//this._contextFactory.Dispose();
this._disposed = true;
}
}
} | mit | C# |
1436faf16286bb9c7ab71a96fba46c6f76b0a621 | Update build.cake | jamesmontemagno/Xamarin.Plugins,predictive-technology-laboratory/Xamarin.Plugins | Media/build.cake | Media/build.cake | #addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "NuGetPack"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Build").Does (() =>
{
const string sln = "./Media.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Build")
.Does (() =>
{
NuGetPack ("./Media.Plugin.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
});
});
RunTarget (TARGET);
| #addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Build"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Build").Does (() =>
{
const string sln = "./Media.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Build")
.Does (() =>
{
NuGetPack ("./Media.Plugin.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
});
});
RunTarget (TARGET); | mit | C# |
ffcc5f7cc3cb3a437d10268fca825c2ae12d9320 | Add better exceptions for invalid keys | iridinite/shiftdrive | Client/Assets.cs | Client/Assets.cs | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
namespace ShiftDrive {
/// <summary>
/// A simple static container, for holding game assets like textures and meshes.
/// </summary>
internal static class Assets {
public static SpriteFont
fontDefault,
fontBold;
public static readonly Dictionary<string, Texture2D>
textures = new Dictionary<string, Texture2D>();
public static Model
mdlSkybox;
public static Effect
fxUnlit;
public static SoundEffect
sndUIConfirm,
sndUICancel,
sndUIAppear1,
sndUIAppear2,
sndUIAppear3,
sndUIAppear4;
public static Texture2D GetTexture(string name) {
if (!textures.ContainsKey(name.ToLowerInvariant()))
throw new KeyNotFoundException("Texture '" + name + "' was not found.");
return textures[name.ToLowerInvariant()];
}
}
}
| /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
namespace ShiftDrive {
/// <summary>
/// A simple static container, for holding game assets like textures and meshes.
/// </summary>
internal static class Assets {
public static SpriteFont
fontDefault,
fontBold;
public static readonly Dictionary<string, Texture2D>
textures = new Dictionary<string, Texture2D>();
public static Model
mdlSkybox;
public static Effect
fxUnlit;
public static SoundEffect
sndUIConfirm,
sndUICancel,
sndUIAppear1,
sndUIAppear2,
sndUIAppear3,
sndUIAppear4;
public static Texture2D GetTexture(string name) {
return textures[name.ToLowerInvariant()];
}
}
}
| bsd-3-clause | C# |
46852ddaadd24f84e28212d6bcad761891151c2f | Extend to allow various OP codes | Luke-Wolf/wolfybot | WolfyBot.Core/IRCMessageFactory.cs | WolfyBot.Core/IRCMessageFactory.cs | //
// Copyright 2014 luke
//
// 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.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
namespace WolfyBot.Core
{
public static class IRCMessageFactory
{
public static IRCMessage BuildActionMessage (String channel, String message)
{
return new IRCMessage (IRCCommand.ACTION, channel, message);
}
public static IRCMessage BuildJoinChannelMessage (String channel)
{
return new IRCMessage (IRCCommand.JOIN, channel);
}
public static IRCMessage BuildModeCommandMessage (String channel, String permissions, String target)
{
var parameters = String.Format ("{0} {1} {2}", channel, permissions, target);
return new IRCMessage (IRCCommand.MODE, parameters);
}
public static IRCMessage BuildKickCommandMessage (String channel, String user, String reason = "")
{
var parameters = String.Format ("{0} {1}", channel, user);
return new IRCMessage (IRCCommand.KICK, parameters, reason);
}
public static IRCMessage BuildSetNickMessage (String nick)
{
return new IRCMessage (IRCCommand.NICK, nick);
}
public static IRCMessage BuildOperMessage (String nick, String password)
{
var parameters = String.Format ("{0} {1}", nick, password);
return new IRCMessage (IRCCommand.OPER, parameters);
}
public static IRCMessage BuildPartMessage (String channel, String partMessage = "")
{
return new IRCMessage (IRCCommand.PART, channel, partMessage);
}
public static IRCMessage BuildSendPassMessage (String password)
{
return new IRCMessage (IRCCommand.PASS, password);
}
public static IRCMessage BuildPingMessage (String target)
{
return new IRCMessage (IRCCommand.PING, trailingParameters: target);
}
public static IRCMessage BuildPongMessage (String server)
{
return new IRCMessage (IRCCommand.PONG, trailingParameters: server);
}
public static IRCMessage BuildSendChannelMessage (String channel, String message)
{
return new IRCMessage (IRCCommand.PRIVMSG, channel, message);
}
public static IRCMessage BuildSetTopicMessage (String channel, String message)
{
return new IRCMessage (IRCCommand.TOPIC, channel, message);
}
public static IRCMessage BuildQuitMessage ()
{
return new IRCMessage (IRCCommand.QUIT);
}
public static IRCMessage BuildUserMessage (String name, String realName)
{
return new IRCMessage (IRCCommand.USER, String.Format ("{0} 0 *", name), realName);
}
}
}
| //
// Copyright 2014 luke
//
// 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.Security.Authentication.ExtendedProtection;
namespace WolfyBot.Core
{
public static class IRCMessageFactory
{
public static IRCMessage BuildActionMessage (String channel, String message)
{
return new IRCMessage (IRCCommand.ACTION, channel, message);
}
public static IRCMessage BuildJoinChannelMessage (String channel)
{
return new IRCMessage (IRCCommand.JOIN, channel);
}
public static IRCMessage BuildSetNickMessage (String nick)
{
return new IRCMessage (IRCCommand.NICK, nick);
}
public static IRCMessage BuildQuitMessage ()
{
return new IRCMessage (IRCCommand.QUIT);
}
public static IRCMessage BuildSendPassMessage (String password)
{
return new IRCMessage (IRCCommand.PASS, password);
}
public static IRCMessage BuildPingMessage (String target)
{
return new IRCMessage (IRCCommand.PING, trailingParameters: target);
}
public static IRCMessage BuildPongMessage (String server)
{
return new IRCMessage (IRCCommand.PONG, trailingParameters: server);
}
public static IRCMessage BuildSendChannelMessage (String channel, String message)
{
return new IRCMessage (IRCCommand.PRIVMSG, channel, message);
}
public static IRCMessage BuildLeaveChannelMessage (String channel)
{
return new IRCMessage (IRCCommand.PART, channel);
}
public static IRCMessage BuildUserMessage (String name, String realName)
{
return new IRCMessage (IRCCommand.USER, String.Format ("{0} 0 *", name), realName);
}
}
}
| apache-2.0 | C# |
dd5b726d29ee0a16ed8d8903705ea599b3d99755 | change the signature of the method | marinoscar/TrackingApp | Code/TrackingApp.Droid/PresenterBase.cs | Code/TrackingApp.Droid/PresenterBase.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace TrackingApp.Droid
{
public abstract class PresenterBase
{
public PresenterBase(IActivity activity)
{
Activity = activity;
BindView();
}
public virtual IActivity Activity { get; private set; }
/// <summary>
/// Bind the view events to the activity
/// </summary>
public abstract void BindView();
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace TrackingApp.Droid
{
public class PresenterBase
{
public PresenterBase(IActivity activity)
{
Activity = activity;
}
public virtual IActivity Activity { get; private set; }
}
} | mit | C# |
c471aca2af87bd8e4df62ef6bfeb1840a585ab81 | Fix vehicle eye rotation (#11447) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Client/Vehicle/VehicleSystem.cs | Content.Client/Vehicle/VehicleSystem.cs | using Content.Client.Eye;
using Content.Shared.Vehicle;
using Content.Shared.Vehicle.Components;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.Player;
using Robust.Shared.GameStates;
namespace Content.Client.Vehicle
{
public sealed class VehicleSystem : SharedVehicleSystem
{
[Dependency] private readonly IEyeManager _eyeManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly EyeLerpingSystem _lerpSys = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<RiderComponent, ComponentShutdown>(OnRiderShutdown);
SubscribeLocalEvent<RiderComponent, ComponentHandleState>(OnRiderHandleState);
SubscribeLocalEvent<RiderComponent, PlayerAttachedEvent>(OnRiderAttached);
SubscribeLocalEvent<RiderComponent, PlayerDetachedEvent>(OnRiderDetached);
}
private void OnRiderShutdown(EntityUid uid, RiderComponent component, ComponentShutdown args)
{
if (component.Vehicle != null)
_lerpSys.RemoveEye(component.Vehicle.Value);
if (uid == _playerManager.LocalPlayer?.ControlledEntity
&& TryComp(uid, out EyeComponent? eye)
&& eye.Eye != null)
{
_eyeManager.CurrentEye = eye.Eye;
}
component.Vehicle = null;
}
private void OnRiderAttached(EntityUid uid, RiderComponent component, PlayerAttachedEvent args)
{
UpdateEye(component);
}
private void OnRiderDetached(EntityUid uid, RiderComponent component, PlayerDetachedEvent args)
{
if (component.Vehicle != null)
_lerpSys.RemoveEye(component.Vehicle.Value);
}
private void UpdateEye(RiderComponent component)
{
if (!TryComp(component.Vehicle, out EyeComponent? eyeComponent) || eyeComponent.Eye == null)
return;
_lerpSys.AddEye(component.Vehicle.Value, eyeComponent);
_eyeManager.CurrentEye = eyeComponent.Eye;
}
private void OnRiderHandleState(EntityUid uid, RiderComponent component, ref ComponentHandleState args)
{
// Server should only be sending states for our entity.
if (args.Current is not RiderComponentState state) return;
component.Vehicle = state.Entity;
UpdateEye(component);
}
}
}
| using Content.Client.Buckle.Strap;
using Content.Shared.Vehicle;
using Content.Shared.Vehicle.Components;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.Player;
using Robust.Shared.GameStates;
namespace Content.Client.Vehicle
{
public sealed class VehicleSystem : SharedVehicleSystem
{
[Dependency] private readonly IEyeManager _eyeManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<RiderComponent, ComponentShutdown>(OnRiderShutdown);
SubscribeLocalEvent<RiderComponent, ComponentHandleState>(OnRiderHandleState);
SubscribeLocalEvent<RiderComponent, PlayerAttachedEvent>(OnRiderAttached);
SubscribeLocalEvent<RiderComponent, PlayerDetachedEvent>(OnRiderDetached);
}
private void OnRiderShutdown(EntityUid uid, RiderComponent component, ComponentShutdown args)
{
component.Vehicle = null;
UpdateEye(component);
}
private void OnRiderAttached(EntityUid uid, RiderComponent component, PlayerAttachedEvent args)
{
UpdateEye(component);
}
private void OnRiderDetached(EntityUid uid, RiderComponent component, PlayerDetachedEvent args)
{
UpdateEye(component);
}
private void UpdateEye(RiderComponent component)
{
if (!TryComp(component.Vehicle, out EyeComponent? eyeComponent))
{
TryComp(_playerManager.LocalPlayer?.ControlledEntity, out eyeComponent);
}
if (eyeComponent?.Eye == null) return;
_eyeManager.CurrentEye = eyeComponent.Eye;
}
private void OnRiderHandleState(EntityUid uid, RiderComponent component, ref ComponentHandleState args)
{
// Server should only be sending states for our entity.
if (args.Current is not RiderComponentState state) return;
component.Vehicle = state.Entity;
UpdateEye(component);
}
}
}
| mit | C# |
7b4b54786b36039cae1f5e563abe8b2c6252a976 | Update Stock.cs | IanMcT/StockMarketGame | SMG/SMG/Stock.cs | SMG/SMG/Stock.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SMG
{
class Stock
{
/// <summary>
/// Name of the Stock
/// </summary>
public string StockName;
/// <summary>
/// Description of the Stock
/// </summary>
public string StockDescription;
/// <summary>
/// The last four or so points for the Stock
/// </summary>
public decimal StockHistory;
/// <summary>
/// scale of one to ten determining if its going to be low risk or high risk
/// </summary>
public decimal StockRisk;
/// <summary>
/// what percent payout the stock is going to have
/// </summary>
public decimal StockReturn;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SMG
{
class Stock
{
}
}
| apache-2.0 | C# |
99e4a989128a6780794055203e36f0ac66bc0983 | Revert version update in top-level AssemblyVersionInfo | MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net | AssemblyVersionInfo.cs | AssemblyVersionInfo.cs | using System.Reflection;
// 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("5.12.1.0")]
[assembly: AssemblyFileVersion("5.12.1.0")]
| using System.Reflection;
// 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("5.13.0.0")]
[assembly: AssemblyFileVersion("5.13.0.0")]
| mit | C# |
167c73c890648626c1f3e51485d16e032fc69a70 | Change color of tank for debug purposes | RamiAhmed/NGJ16 | Assets/Scripts/Tank.cs | Assets/Scripts/Tank.cs | namespace Game
{
using UnityEngine;
[RequireComponent(typeof(Collider))]
public class Tank : MonoBehaviour
{
public PlayerController player;
[Range(10f, 1000f)]
public float max = 100f;
[Range(0.1f, 20f)]
public float leakRatePerSecond = 2f;
[ReadOnly]
private float current = 0f;
public bool isLeaking
{
get;
set;
}
private void OnEnable()
{
this.name = string.Concat("Player ", this.player.playerIndex, " Tank");
this.current = this.max;
}
private void Update()
{
if (!this.isLeaking)
{
return;
}
this.current -= 1f / this.leakRatePerSecond;
if (this.current <= 0f)
{
this.player.Die();
this.enabled = false;
}
// TODO: Debug ONLY
var frac = this.current / this.max;
this.GetComponent<Renderer>().material.color = new Color(frac, frac, frac);
}
private void OnCollisionEnter(Collision collision)
{
if (this.isLeaking)
{
return;
}
var other = collision.gameObject;
if (((1 << other.layer) & Layers.instance.playerLayer) == 0)
{
// not a player
return;
}
Debug.Log(this.ToString() + " start leaking");
this.isLeaking = true;
}
}
} | namespace Game
{
using UnityEngine;
[RequireComponent(typeof(Collider))]
public class Tank : MonoBehaviour
{
public PlayerController player;
[Range(10f, 1000f)]
public float max = 100f;
[Range(0.1f, 20f)]
public float leakRatePerSecond = 2f;
[ReadOnly]
private float current = 0f;
public bool isLeaking
{
get;
set;
}
private void OnEnable()
{
this.name = string.Concat("Player ", this.player.playerIndex, " Tank");
this.current = this.max;
}
private void Update()
{
if (!this.isLeaking)
{
return;
}
this.current -= 1f / this.leakRatePerSecond;
if (this.current <= 0f)
{
this.player.Die();
this.enabled = false;
}
}
private void OnCollisionEnter(Collision collision)
{
if (this.isLeaking)
{
return;
}
var other = collision.gameObject;
if (((1 << other.layer) & Layers.instance.playerLayer) == 0)
{
// not a player
return;
}
Debug.Log(this.ToString() + " start leaking");
this.isLeaking = true;
}
}
} | mit | C# |
c9c6e7b6a4c98f92fdf0aae0e9a7178907dd2d65 | Check if tree is dead when you want call metod to up maturity | AcessDeniedAD/ggj2016,AcessDeniedAD/ggj2016 | Assets/Scripts/Tree.cs | Assets/Scripts/Tree.cs | using UnityEngine;
using System.Collections;
public class Tree : MonoBehaviour {
#region Attributes creation
// Public attributes
public float treelife;
public float max_maturity;
// Private attributes
private float current_maturity = 0;
private int tree_level;
// private float timer = 0 ;// TODO delete
#endregion
#region Unity method
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// TODO to delete
/*timer += Time.deltaTime;
if (timer > 0.5) {
timer = 0;
up_maturity(3.5f);
}*/
}
void OnTriggerEnter(Collider other) {
if (other.tag == "Enemy") {
take_dammage(other.gameObject);
}
}
#endregion
#region Public method
public void take_dammage(GameObject ennemy){
EnnemisMain enemy = ennemy.GetComponent<EnnemisMain>();
treelife -= enemy.damage;
if (treelife == 0) {
// Call loose scene
Debug.Log("Your tree is dead");
}
}
/// <summary>
/// Up the maturity tree value
/// </summary>
/// <param name="maturity_to_up">Float value to increase maturity tree</param>
public void up_maturity(float maturity_to_up){
if (treelife != 0) {
if (max_maturity > current_maturity && (current_maturity + maturity_to_up) < max_maturity) {
current_maturity += maturity_to_up;
}
else if((current_maturity + maturity_to_up) > max_maturity && current_maturity < max_maturity){
current_maturity = max_maturity;
}
else{
Debug.Log("You're fucking tree are full maturity");
}
if (current_maturity == max_maturity) {
up_level_tree();
}
}
}
/// <summary>
/// Down the maturity tree value
/// </summary>
/// <param name="maturity_to_down">Float value to reduce maturity tree</param>
public void down_maturity(float maturity_to_down){
if (treelife != 0) {
if (current_maturity != 0 && (current_maturity - maturity_to_down) >= 0) {
current_maturity -= maturity_to_down;
} else if ((current_maturity - maturity_to_down) < max_maturity && current_maturity != 0) {
current_maturity = max_maturity;
} else {
Debug.Log ("You're fucking tree has no maturity");
}
}
}
#endregion
#region Private method
private void up_level_tree(){
// Method to up level of tree
}
#endregion
} | using UnityEngine;
using System.Collections;
public class Tree : MonoBehaviour {
#region Attributes creation
// Public attributes
public float treelife;
public float max_maturity;
// Private attributes
private float current_maturity;
private int tree_level;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
#endregion
#region Public method
public void take_dammage(GameObject ennemy){
EnnemisMain enemy = ennemy.GetComponent<EnnemisMain>();
treelife -= enemy.damage;
}
/// <summary>
/// Up the maturity tree value
/// </summary>
/// <param name="maturity_to_up">Float value to increase maturity tree</param>
public void up_maturity(float maturity_to_up){
if (max_maturity > current_maturity && (current_maturity + maturity_to_up) < max_maturity) {
current_maturity += max_maturity;
}
else if((current_maturity + maturity_to_up) > max_maturity && current_maturity < max_maturity){
current_maturity = max_maturity;
}
else{
Debug.LogError("You're fucking tree are full maturity");
}
if (current_maturity == max_maturity) {
up_level_tree();
}
}
/// <summary>
/// Down the maturity tree value
/// </summary>
/// <param name="maturity_to_down">Float value to reduce maturity tree</param>
public void down_maturity(float maturity_to_down){
if (current_maturity != 0 && (current_maturity - maturity_to_down) >= 0) {
current_maturity -= max_maturity;
}
else if((current_maturity - maturity_to_down) < max_maturity && current_maturity != 0){
current_maturity = max_maturity;
}
else{
Debug.LogError("You're fucking tree has no maturity");
}
}
#endregion
#region Private method
private void up_level_tree(){
// Method to up level of tree
}
#endregion
} | cc0-1.0 | C# |
11a596c58a3172e477ac4b4bd1ed9b9659280493 | Fix header names for rate limiting (#71) | vevix/DigitalOcean.API | DigitalOcean.API/Http/RateLimit.cs | DigitalOcean.API/Http/RateLimit.cs | using System.Collections.Generic;
using System.Linq;
using RestSharp;
namespace DigitalOcean.API.Http {
public class RateLimit : IRateLimit {
public RateLimit(IList<Parameter> headers) {
Limit = GetHeaderValue(headers, "Ratelimit-Limit");
Remaining = GetHeaderValue(headers, "Ratelimit-Remaining");
Reset = GetHeaderValue(headers, "Ratelimit-Reset");
}
#region IRateLimit Members
/// <summary>
/// The number of requests that can be made per hour.
/// </summary>
public int Limit { get; private set; }
/// <summary>
/// The number of requests that remain before you hit your request limit.
/// </summary>
public int Remaining { get; private set; }
/// <summary>
/// This represents the time when the oldest request will expire. The value is given in Unix epoch time.
/// </summary>
public int Reset { get; private set; }
#endregion
private static int GetHeaderValue(IEnumerable<Parameter> headers, string name) {
var header = headers.FirstOrDefault(x => x.Name == name);
int value;
return header != null && int.TryParse(header.Value.ToString(), out value) ? value : 0;
}
}
}
| using System.Collections.Generic;
using System.Linq;
using RestSharp;
namespace DigitalOcean.API.Http {
public class RateLimit : IRateLimit {
public RateLimit(IList<Parameter> headers) {
Limit = GetHeaderValue(headers, "RateLimit-Limit");
Remaining = GetHeaderValue(headers, "RateLimit-Remaining");
Reset = GetHeaderValue(headers, "RateLimit-Reset");
}
#region IRateLimit Members
/// <summary>
/// The number of requests that can be made per hour.
/// </summary>
public int Limit { get; private set; }
/// <summary>
/// The number of requests that remain before you hit your request limit.
/// </summary>
public int Remaining { get; private set; }
/// <summary>
/// This represents the time when the oldest request will expire. The value is given in Unix epoch time.
/// </summary>
public int Reset { get; private set; }
#endregion
private static int GetHeaderValue(IEnumerable<Parameter> headers, string name) {
var header = headers.FirstOrDefault(x => x.Name == name);
int value;
return header != null && int.TryParse(header.Value.ToString(), out value) ? value : 0;
}
}
}
| mit | C# |
fc4ccf712d98bb925dd1bfe164f9177dd548a16e | Bump version. | yojimbo87/ArangoDB-NET,kangkot/ArangoDB-NET | src/Arango/Arango.Client/API/ArangoClient.cs | src/Arango/Arango.Client/API/ArangoClient.cs | using System.Collections.Generic;
using System.Linq;
using Arango.Client.Protocol;
namespace Arango.Client
{
public static class ArangoClient
{
private static List<Connection> _connections = new List<Connection>();
public static string DriverName
{
get { return "ArangoDB-NET"; }
}
public static string DriverVersion
{
get { return "0.5.0"; }
}
public static void AddDatabase(string hostname, int port, bool isSecured, string userName, string password, string alias)
{
var connection = new Connection(hostname, port, isSecured, userName, password, alias);
_connections.Add(connection);
}
internal static Connection GetConnection(string alias)
{
return _connections.Where(connection => connection.Alias == alias).FirstOrDefault();
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Arango.Client.Protocol;
namespace Arango.Client
{
public static class ArangoClient
{
private static List<Connection> _connections = new List<Connection>();
public static string DriverName
{
get { return "ArangoDB-NET"; }
}
public static string DriverVersion
{
get { return "0.4.1"; }
}
public static void AddDatabase(string hostname, int port, bool isSecured, string userName, string password, string alias)
{
var connection = new Connection(hostname, port, isSecured, userName, password, alias);
_connections.Add(connection);
}
internal static Connection GetConnection(string alias)
{
return _connections.Where(connection => connection.Alias == alias).FirstOrDefault();
}
}
}
| mit | C# |
9d4339e6952b10c010ec9f2e2197cc8a78aaf803 | Fix a few typos in Color constraint logic | Confruggy/Discord.Net,RogueException/Discord.Net,LassieME/Discord.Net,AntiTcb/Discord.Net | src/Discord.Net.Core/Entities/Roles/Color.cs | src/Discord.Net.Core/Entities/Roles/Color.cs | using System;
using System.Diagnostics;
namespace Discord
{
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public struct Color
{
/// <summary> Gets the default user color value. </summary>
public static readonly Color Default = new Color(0);
/// <summary> Gets the encoded value for this color. </summary>
public uint RawValue { get; }
/// <summary> Gets the red component for this color. </summary>
public byte R => (byte)(RawValue >> 16);
/// <summary> Gets the green component for this color. </summary>
public byte G => (byte)(RawValue >> 8);
/// <summary> Gets the blue component for this color. </summary>
public byte B => (byte)(RawValue);
public Color(uint rawValue)
{
RawValue = rawValue;
}
public Color(byte r, byte g, byte b)
{
RawValue =
((uint)r << 16) |
((uint)g << 8) |
b;
}
public Color(float r, float g, float b)
{
if (r < 0.0f || r > 1.0f)
throw new ArgumentOutOfRangeException(nameof(r), "A float value must be within [0,1]");
if (g < 0.0f || g > 1.0f)
throw new ArgumentOutOfRangeException(nameof(g), "A float value must be within [0,1]");
if (b < 0.0f || b > 1.0f)
throw new ArgumentOutOfRangeException(nameof(b), "A float value must be within [0,1]");
RawValue =
((uint)(r * 255.0f) << 16) |
((uint)(g * 255.0f) << 8) |
(uint)(b * 255.0f);
}
public override string ToString() =>
$"#{Convert.ToString(RawValue, 16)}";
private string DebuggerDisplay =>
$"#{Convert.ToString(RawValue, 16)} ({RawValue})";
}
}
| using System;
using System.Diagnostics;
namespace Discord
{
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public struct Color
{
/// <summary> Gets the default user color value. </summary>
public static readonly Color Default = new Color(0);
/// <summary> Gets the encoded value for this color. </summary>
public uint RawValue { get; }
/// <summary> Gets the red component for this color. </summary>
public byte R => (byte)(RawValue >> 16);
/// <summary> Gets the green component for this color. </summary>
public byte G => (byte)(RawValue >> 8);
/// <summary> Gets the blue component for this color. </summary>
public byte B => (byte)(RawValue);
public Color(uint rawValue)
{
RawValue = rawValue;
}
public Color(byte r, byte g, byte b)
{
RawValue =
((uint)r << 16) |
((uint)g << 8) |
b;
}
public Color(float r, float g, float b)
{
if (r <= 0.0f && r >= 1.0f)
throw new ArgumentOutOfRangeException(nameof(r), "A float value must be within [0,1]");
if (g <= 0.0f || g >= 1.0f)
throw new ArgumentOutOfRangeException(nameof(g), "A float value must be within [0,1]");
if (b <= 0.0f || b >= 1.0f)
throw new ArgumentOutOfRangeException(nameof(b), "A float value must be within [0,1]");
RawValue =
((uint)(r * 255.0f) << 16) |
((uint)(g * 255.0f) << 8) |
(uint)(b * 255.0f);
}
public override string ToString() =>
$"#{Convert.ToString(RawValue, 16)}";
private string DebuggerDisplay =>
$"#{Convert.ToString(RawValue, 16)} ({RawValue})";
}
}
| mit | C# |
6fc1aadc889e54e0c420ebc5ab71b3c2dd998735 | Make private | weltkante/roslyn,bartdesmet/roslyn,eriawan/roslyn,sharwell/roslyn,dotnet/roslyn,eriawan/roslyn,mavasani/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,eriawan/roslyn,dotnet/roslyn,diryboy/roslyn,KevinRansom/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,diryboy/roslyn,dotnet/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn | src/Features/Core/Portable/DocumentIdSpan.cs | src/Features/Core/Portable/DocumentIdSpan.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Lightweight analog to <see cref="DocumentSpan"/> that should be used in features that care about
/// pointing at a particular location in a <see cref="Document"/> but do not want to root a potentially
/// very stale <see cref="Solution"/> snapshot that may keep around a lot of memory in a host.
/// </summary>
internal readonly struct DocumentIdSpan
{
private readonly Workspace _workspace;
private readonly DocumentId _documentId;
public readonly TextSpan SourceSpan;
public DocumentIdSpan(DocumentSpan documentSpan)
{
_workspace = documentSpan.Document.Project.Solution.Workspace;
_documentId = documentSpan.Document.Id;
SourceSpan = documentSpan.SourceSpan;
}
public async Task<DocumentSpan?> TryRehydrateAsync(CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
var document = await solution.GetDocumentAsync(_documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false);
return document == null ? null : new DocumentSpan(document, SourceSpan);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal readonly struct DocumentIdSpan
{
public readonly Workspace Workspace;
public readonly DocumentId DocumentId;
public readonly TextSpan SourceSpan;
public DocumentIdSpan(DocumentSpan documentSpan)
{
Workspace = documentSpan.Document.Project.Solution.Workspace;
DocumentId = documentSpan.Document.Id;
SourceSpan = documentSpan.SourceSpan;
}
public async Task<DocumentSpan?> TryRehydrateAsync(CancellationToken cancellationToken)
{
var solution = Workspace.CurrentSolution;
var document = await solution.GetDocumentAsync(DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false);
return document == null ? null : new DocumentSpan(document, SourceSpan);
}
}
}
| mit | C# |
7930aa4964b7576fea23635d35ac187388760123 | Update displayed version | EtienneLamoureux/TQVaultAE,Malgardian/TQVaultAE | src/TQVaultAE.GUI/Properties/AssemblyInfo.cs | src/TQVaultAE.GUI/Properties/AssemblyInfo.cs | //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
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("TQVaultAE")]
[assembly: AssemblyDescription("Extra bank space for Titan Quest Anniversary Edition")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("titanquest.net community")]
[assembly: AssemblyProduct("TQVaultAE")]
[assembly: AssemblyCopyright("Copyright © 2006-2012 by Brandon Wallace")]
[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("40473eaa-06cd-4833-898d-0793c3d1b755")]
// CLS compliant attribute
//[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("3.1.0")]
[assembly: AssemblyFileVersion("3.1.0")]
[assembly: NeutralResourcesLanguageAttribute("en-US")] | //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
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("TQVaultAE")]
[assembly: AssemblyDescription("Extra bank space for Titan Quest Anniversary Edition")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("titanquest.net community")]
[assembly: AssemblyProduct("TQVaultAE")]
[assembly: AssemblyCopyright("Copyright © 2006-2012 by Brandon Wallace")]
[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("40473eaa-06cd-4833-898d-0793c3d1b755")]
// CLS compliant attribute
//[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("3.0.0")]
[assembly: AssemblyFileVersion("3.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en-US")] | mit | C# |
2b86ecce8c86a57352dd68bd5033793e01d69a86 | Read configuration from external XML | pleonex/Ninokuni,pleonex/Ninokuni,pleonex/Ninokuni | Programs/NinoTweet/NinoTweet/Program.cs | Programs/NinoTweet/NinoTweet/Program.cs | //
// Program.cs
//
// Author:
// Benito Palacios Sánchez <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.IO;
using System.Xml.Linq;
using Libgame;
namespace NinoTweet
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length != 3)
return;
string xmlEdit = "Ninokuni español.xml";
var document = XDocument.Load(xmlEdit);
Configuration.Initialize(document);
string inputPath = args[1];
string outputPath = args[2];
Tweet tweet = new Tweet();
if (args[0] == "-e") {
tweet.Read(inputPath);
tweet.Export(outputPath);
} else if (args[0] == "-i") {
tweet.Import(inputPath);
tweet.Write(outputPath);
}
}
}
}
| //
// Program.cs
//
// Author:
// Benito Palacios Sánchez <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.IO;
using System.Xml.Linq;
using Libgame;
namespace NinoTweet
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length != 3)
return;
Configuration.Initialize(CreateConfiguration());
string inputPath = args[1];
string outputPath = args[2];
Tweet tweet = new Tweet();
if (args[0] == "-e") {
tweet.Read(inputPath);
tweet.Export(outputPath);
} else if (args[0] == "-i") {
tweet.Import(inputPath);
tweet.Write(outputPath);
}
}
private static XDocument CreateConfiguration()
{
XDocument xml = new XDocument();
XElement root = new XElement("Configuration");
root.Add(new XElement("RelativePaths"));
root.Add(new XElement("CharTables"));
XElement spchar = new XElement("SpecialChars");
root.Add(spchar);
spchar.Add(new XElement("Ellipsis", "…"));
spchar.Add(new XElement("QuoteOpen", "ワ"));
spchar.Add(new XElement("QuoteClose", "ン"));
spchar.Add(new XElement("FuriganaOpen", "【"));
spchar.Add(new XElement("FuriganaClose", "】"));
xml.Add(root);
return xml;
}
}
}
| apache-2.0 | C# |
5278f73bc8ef2ac5d5fe34ec3a86d6b684a6c8e2 | fix unit test | jefking/King.Service | King.Service.Unit.Tests/SafeProcessorTests.cs | King.Service.Unit.Tests/SafeProcessorTests.cs | namespace King.Service.Tests
{
using global::Azure.Data.Wrappers;
using King.Service;
using King.Service.Timing;
using NSubstitute;
using NUnit.Framework;
using System;
[TestFixture]
public class SafeProcessorTests
{
[Test]
public void Constructor()
{
new SafeProcessor<ProcHelper, int>();
}
[Test]
public void IsIProcessor()
{
Assert.IsNotNull(new SafeProcessor<ProcHelper, int>() as IProcessor<int>);
}
[Test]
public void Process()
{
var random = new Random();
var start = random.Next();
var set = random.Next();
ProcHelper.Testing = start;
var p = new SafeProcessor<ProcHelper, int>();
p.Process(set).Wait();
Assert.AreEqual(set, ProcHelper.Testing);
}
}
} | namespace King.Service.Tests
{
using global::Azure.Data.Wrappers;
using King.Service;
using King.Service.Timing;
using NSubstitute;
using NUnit.Framework;
using System;
[TestFixture]
public class SafeProcessorTests
{
[Test]
public void Constructor()
{
new SafeProcessor<ProcHelper, int>();
}
[Test]
public void IsIProcessor()
{
Assert.IsNotNull(new SafeProcessor<ProcHelper, int>() as IProcessor<int>);
}
[Test]
public async void Process()
{
var random = new Random();
var start = random.Next();
var set = random.Next();
ProcHelper.Testing = start;
var p = new SafeProcessor<ProcHelper, int>();
await p.Process(set);
Assert.AreEqual(set, ProcHelper.Testing);
}
}
} | mit | C# |
b53a54bdd4ee2294055324304d8fd82ef1ce9646 | Improve code | sakapon/Samples-2014,sakapon/Samples-2014,sakapon/Samples-2014 | RxSample/MouseRx2Wpf/EventsExtension.cs | RxSample/MouseRx2Wpf/EventsExtension.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace MouseRx2Wpf
{
public class EventsExtension
{
public Control Target { get; }
public IObservable<IObservable<Vector>> MouseDrag { get; }
public EventsExtension(Control target)
{
Target = target;
// Replace events with IObservable objects.
var mouseDown = Observable.FromEventPattern<MouseButtonEventArgs>(Target, nameof(Target.MouseDown)).Select(e => e.EventArgs);
var mouseUp = Observable.FromEventPattern<MouseButtonEventArgs>(Target, nameof(Target.MouseUp)).Select(e => e.EventArgs);
var mouseLeave = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(Target.MouseLeave)).Select(e => e.EventArgs);
var mouseMove = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(Target.MouseMove)).Select(e => e.EventArgs);
var mouseDownEnd = mouseUp.Merge(mouseLeave.Select(e => default(MouseButtonEventArgs)));
MouseDrag = mouseDown
.Select(e => e.GetPosition(Target))
.Select(p0 => mouseMove
.TakeUntil(mouseDownEnd)
.Select(e => e.GetPosition(Target) - p0));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace MouseRx2Wpf
{
public class EventsExtension
{
public Control Target { get; }
public IObservable<IObservable<Vector>> MouseDrag { get; }
public EventsExtension(Control target)
{
Target = target;
// Replace events with IObservable objects.
var mouseDown = Observable.FromEventPattern<MouseButtonEventArgs>(Target, nameof(Target.MouseDown)).Select(e => e.EventArgs);
var mouseUp = Observable.FromEventPattern<MouseButtonEventArgs>(Target, nameof(Target.MouseUp)).Select(e => e.EventArgs);
var mouseLeave = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(Target.MouseLeave)).Select(e => e.EventArgs);
var mouseMove = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(Target.MouseMove)).Select(e => e.EventArgs);
var mouseDownEnd = mouseUp.Merge(mouseLeave.Select(e => default(MouseButtonEventArgs)));
MouseDrag = mouseDown
.Select(e => e.GetPosition(Target))
.Select(p0 => mouseMove
.Select(e => e.GetPosition(Target) - p0)
.TakeUntil(mouseDownEnd));
}
}
}
| mit | C# |
e9337f4be3440df1ab5e148d53197157c58ff011 | fix comments | sebas77/Svelto.ECS,sebas77/Svelto-ECS | Svelto.ECS/IEntityViewStruct.cs | Svelto.ECS/IEntityViewStruct.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using Svelto.DataStructures;
using Svelto.Utilities;
namespace Svelto.ECS
{
///<summary>EntityStruct MUST implement IEntiyStruct</summary>
public interface IEntityStruct
{
EGID ID { get; set; }
}
///<summary>EntityViewStructs MUST implement IEntityViewStruct</summary>
public interface IEntityViewStruct:IEntityStruct
{}
///<summary>EntityViews can inherit from the EntityView class</summary>
public class EntityView : IEntityViewStruct
{
public EGID ID
{
get { return _ID; }
set { _ID = value; }
}
EGID _ID;
}
public struct EntityInfoView : IEntityStruct
{
public EGID ID { get; set; }
public IEntityBuilder[] entityToBuild;
}
public static class EntityView<T> where T: IEntityStruct, new()
{
internal static readonly FasterList<KeyValuePair<Type, ActionCast<T>>> cachedFields;
static EntityView()
{
cachedFields = new FasterList<KeyValuePair<Type, ActionCast<T>>>();
var type = typeof(T);
var fields = type.GetFields(BindingFlags.Public |
BindingFlags.Instance);
for (int i = fields.Length - 1; i >= 0; --i)
{
var field = fields[i];
ActionCast<T> setter = FastInvoke<T>.MakeSetter(field);
cachedFields.Add(new KeyValuePair<Type, ActionCast<T>>(field.FieldType, setter));
}
}
internal static void InitCache()
{}
internal static void BuildEntityView(EGID ID, out T entityView)
{
entityView = new T { ID = ID };
}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using Svelto.DataStructures;
using Svelto.Utilities;
namespace Svelto.ECS
{
///<summary>EntityStruct MUST implement IEntiyStruct</summary>
public interface IEntityStruct
{
EGID ID { get; set; }
}
///<summary>EntityViews and EntityViewStructs MUST implement IEntityView</summary>
public interface IEntityViewStruct:IEntityStruct
{}
public class EntityView : IEntityViewStruct
{
public EGID ID
{
get { return _ID; }
set { _ID = value; }
}
EGID _ID;
}
public struct EntityInfoView : IEntityStruct
{
public EGID ID { get; set; }
public IEntityBuilder[] entityToBuild;
}
public static class EntityView<T> where T: IEntityStruct, new()
{
internal static readonly FasterList<KeyValuePair<Type, ActionCast<T>>> cachedFields;
static EntityView()
{
cachedFields = new FasterList<KeyValuePair<Type, ActionCast<T>>>();
var type = typeof(T);
var fields = type.GetFields(BindingFlags.Public |
BindingFlags.Instance);
for (int i = fields.Length - 1; i >= 0; --i)
{
var field = fields[i];
ActionCast<T> setter = FastInvoke<T>.MakeSetter(field);
cachedFields.Add(new KeyValuePair<Type, ActionCast<T>>(field.FieldType, setter));
}
}
internal static void InitCache()
{}
internal static void BuildEntityView(EGID ID, out T entityView)
{
entityView = new T { ID = ID };
}
}
}
| mit | C# |
3ddd3a060e6d62af757471256cc26f4c0c5d7a6e | Fix types in ITransducer comments | AndrewGaspar/TD.Net | TD.Core/ITransducer.cs | TD.Core/ITransducer.cs | namespace TD
{
/// <summary>
/// Describes a computation as taking inputs of type TInput and producing results of type TResult.
///
/// A transducer cannot independently perform any computation - you must apply a reducer to it
/// so that the transducer has a sink for its computations.
/// </summary>
/// <typeparam name="TInput">The type of the inputs to this computation.</typeparam>
/// <typeparam name="TResult">The type of the results produced by this computation.</typeparam>
public interface ITransducer<TInput, TResult>
{
/// <summary>
/// Produces a reducer by application of another reducer. The produced reducer will take
/// input of type TResult and apply results of type TInput to the applied reducer.
/// </summary>
/// <typeparam name="TReduction">
/// The type of the reduced value that is produced as an aggregation
/// of the values applied to the created reducer.
/// </typeparam>
/// <param name="next">A computation that takes a value of type TInput and returns a reduction of type Reduction.</param>
/// <returns>A new reducer that wraps the supplied reducer and takes as input type TResult.</returns>
IReducer<TReduction, TInput> Apply<TReduction>(IReducer<TReduction, TResult> next);
}
}
| namespace TD
{
/// <summary>
/// Describes a computation as taking inputs of type To and producing results of type From.
///
/// A transducer cannot independently perform any computation - you must apply a reducer to it
/// so that the transducer has a sink for its computations.
/// </summary>
/// <typeparam name="TInput">The type of the inputs to this computation.</typeparam>
/// <typeparam name="TResult">The type of the results produced by this computation.</typeparam>
public interface ITransducer<TInput, TResult>
{
/// <summary>
/// Produces a reducer by application of another reducer. The produced reducer will take
/// input of type From and apply results of type To to the applied reducer.
/// </summary>
/// <typeparam name="TReduction">
/// The type of the reduced value that is produced as an aggregation
/// of the values applied to the created reducer.
/// </typeparam>
/// <param name="next">A computation that takes a value of type To and returns a reduction of type Reduction.</param>
/// <returns>A new reducer that wraps the supplied reducer and takes as input type From.</returns>
IReducer<TReduction, TInput> Apply<TReduction>(IReducer<TReduction, TResult> next);
}
}
| mit | C# |
78ba69214a2ce5448b77e748ea4fccb5444fecea | Update ControlStoryboardOption.cs | PedroLamas/XamlBehaviors,Microsoft/XamlBehaviors,Microsoft/XamlBehaviors,Microsoft/XamlBehaviors,PedroLamas/XamlBehaviors,PedroLamas/XamlBehaviors | src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Media/ControlStoryboardOption.cs | src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Media/ControlStoryboardOption.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Xaml.Interactions.Media
{
/// <summary>
/// Represents operations that can be applied to <seealso cref="Windows.UI.Xaml.Media.Animation.Storyboard"/>.
/// </summary>
public enum ControlStoryboardOption
{
/// <summary>
/// Specifies the play operation.
/// </summary>
Play,
/// <summary>
/// Specifies the stop operation.
/// </summary>
Stop,
/// <summary>
/// Specifies the TogglePlayPause operation.
/// </summary>
TogglePlayPause,
/// <summary>
/// Specifies the pause operation.
/// </summary>
Pause,
/// <summary>
/// Specifies the resume operation.
/// </summary>
Resume,
/// <summary>
/// Specifies the SkipToFill operation.
/// </summary>
SkipToFill
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Xaml.Interactions.Media
{
/// <summary>
/// Represents operations that can be applied to <seealso cref="Windows.UI.Xaml.Media.Animation.Storyboard"/>.
/// </summary>
public enum ControlStoryboardOption
{
/// <summary>
/// Specifies the play operation.
/// </summary>
Play,
/// <summary>
/// Specifies the stop operation.
/// </summary>
Stop,
/// <summary>
/// Specifies the TogglePlayPause operation.
/// </summary>
TogglePlayPause,
/// <summary>
/// Specifies the pause operation.
/// </summary>
Pause,
/// <summary>
/// Specifies the resume operation.
/// </summary>
Resume,
/// <summary>
/// Specifies the SkipToFill operation.
/// </summary>
SkipToFill
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.