Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix operation on wrong node | namespace SearchingBinaryTree
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class BinarySearchTree
{
public Node Root { get; private set; }
public void Add(Node node) {
if(Root!=null) {
Node current = Root;
while(current != null) {
if (current.Value > node.Value)
{
if (current.Right != null) {
current = current.Right;
continue;
}
Root.Right = node;
current = null;
}
else
{
if (current.Left != null) {
current = current.Left;
continue;
}
Root.Left = node;
current = null;
}
}
} else {
Root = node;
}
}
}
}
| namespace SearchingBinaryTree
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class BinarySearchTree
{
public Node Root { get; private set; }
public void Add(Node node) {
if(Root!=null) {
Node current = Root;
while(current != null) {
if (current.Value > node.Value)
{
if (current.Right != null) {
current = current.Right;
continue;
}
current.Right = node;
current = null;
}
else
{
if (current.Left != null) {
current = current.Left;
continue;
}
current.Left = node;
current = null;
}
}
} else {
Root = node;
}
}
}
}
|
Add override to test migration, so it happens every time | using System;
using IonFar.SharePoint.Migration;
using Microsoft.SharePoint.Client;
namespace TestApplication.Migrations
{
[Migration(10001)]
public class ShowTitle : IMigration
{
public void Up(ClientContext clientContext, ILogger logger)
{
clientContext.Load(clientContext.Web, w => w.Title);
clientContext.ExecuteQuery();
Console.WriteLine("Your site title is: " + clientContext.Web.Title);
}
}
}
| using System;
using IonFar.SharePoint.Migration;
using Microsoft.SharePoint.Client;
namespace TestApplication.Migrations
{
[Migration(10001, true)]
public class ShowTitle : IMigration
{
public void Up(ClientContext clientContext, ILogger logger)
{
clientContext.Load(clientContext.Web, w => w.Title);
clientContext.ExecuteQuery();
Console.WriteLine("Your site title is: " + clientContext.Web.Title);
}
}
}
|
Remove RegexOptions.Compiled for code paths executed during cold start | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Text.RegularExpressions;
namespace Microsoft.Azure.WebJobs
{
/// <summary>
/// Attribute used to indicate the name to use for a job function.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class FunctionNameAttribute : Attribute
{
private string _name;
/// <summary>
/// Initializes a new instance of the <see cref="FunctionNameAttribute"/> class with a given name.
/// </summary>
/// <param name="name">Name of the function.</param>
public FunctionNameAttribute(string name)
{
this._name = name;
}
/// <summary>
/// Gets the function name.
/// </summary>
public string Name => _name;
/// <summary>
/// Validation for name.
/// </summary>
public static readonly Regex FunctionNameValidationRegex = new Regex(@"^[a-z][a-z0-9_\-]{0,127}$(?<!^host$)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Text.RegularExpressions;
namespace Microsoft.Azure.WebJobs
{
/// <summary>
/// Attribute used to indicate the name to use for a job function.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class FunctionNameAttribute : Attribute
{
private string _name;
/// <summary>
/// Initializes a new instance of the <see cref="FunctionNameAttribute"/> class with a given name.
/// </summary>
/// <param name="name">Name of the function.</param>
public FunctionNameAttribute(string name)
{
this._name = name;
}
/// <summary>
/// Gets the function name.
/// </summary>
public string Name => _name;
/// <summary>
/// Validation for name.
/// RegexOptions.Compiled is specifically removed as it impacts the cold start.
/// </summary>
public static readonly Regex FunctionNameValidationRegex = new Regex(@"^[a-z][a-z0-9_\-]{0,127}$(?<!^host$)", RegexOptions.IgnoreCase);
}
}
|
Add Articles rep into DI scope | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AustinSite
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| using AustinSite.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AustinSite
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddScoped<ArticlesRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
|
Add retry logic for test clean up | using System;
namespace TestUtility
{
public partial class TestAssets
{
private class TestProject : ITestProject
{
private bool _disposed;
public string Name { get; }
public string BaseDirectory { get; }
public string Directory { get; }
public bool ShadowCopied { get; }
public TestProject(string name, string baseDirectory, string directory, bool shadowCopied)
{
this.Name = name;
this.BaseDirectory = baseDirectory;
this.Directory = directory;
this.ShadowCopied = shadowCopied;
}
~TestProject()
{
throw new InvalidOperationException($"{nameof(ITestProject)}.{nameof(Dispose)}() not called for {this.Name}");
}
public virtual void Dispose()
{
if (_disposed)
{
throw new InvalidOperationException($"{nameof(ITestProject)} for {this.Name} already disposed.");
}
if (this.ShadowCopied)
{
System.IO.Directory.Delete(this.BaseDirectory, recursive: true);
if (System.IO.Directory.Exists(this.BaseDirectory))
{
throw new InvalidOperationException($"{nameof(ITestProject)} directory still exists: '{this.BaseDirectory}'");
}
}
this._disposed = true;
GC.SuppressFinalize(this);
}
}
}
}
| using System;
using System.Threading;
namespace TestUtility
{
public partial class TestAssets
{
private class TestProject : ITestProject
{
private bool _disposed;
public string Name { get; }
public string BaseDirectory { get; }
public string Directory { get; }
public bool ShadowCopied { get; }
public TestProject(string name, string baseDirectory, string directory, bool shadowCopied)
{
this.Name = name;
this.BaseDirectory = baseDirectory;
this.Directory = directory;
this.ShadowCopied = shadowCopied;
}
~TestProject()
{
throw new InvalidOperationException($"{nameof(ITestProject)}.{nameof(Dispose)}() not called for {this.Name}");
}
public virtual void Dispose()
{
if (_disposed)
{
throw new InvalidOperationException($"{nameof(ITestProject)} for {this.Name} already disposed.");
}
if (this.ShadowCopied)
{
var retries = 0;
while (retries <= 5)
{
try
{
System.IO.Directory.Delete(this.BaseDirectory, recursive: true);
break;
}
catch
{
Thread.Sleep(1000);
retries++;
}
}
if (System.IO.Directory.Exists(this.BaseDirectory))
{
throw new InvalidOperationException($"{nameof(ITestProject)} directory still exists: '{this.BaseDirectory}'");
}
}
this._disposed = true;
GC.SuppressFinalize(this);
}
}
}
}
|
Move EditorBrowsable to class level | /*
JustMock Lite
Copyright © 2019 Progress Software 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 System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
public static MethodBase GetContext()
{
return resolver.GetContext();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void CaptureContext()
{
resolver.CaptureContext();
}
}
}
| /*
JustMock Lite
Copyright © 2019 Progress Software 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 System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
public static MethodBase GetContext()
{
return resolver.GetContext();
}
public static void CaptureContext()
{
resolver.CaptureContext();
}
}
}
|
Use a lower maxTreeLevel precision | using System.Linq;
using Raven.Client.Indexes;
namespace Raven.TimeZones
{
public class ZoneShapesIndex : AbstractIndexCreationTask<ZoneShape>
{
public ZoneShapesIndex()
{
Map = shapes => from shape in shapes
select new
{
shape.Zone,
_ = SpatialGenerate("location", shape.Shape)
};
}
}
}
| using System.Linq;
using Raven.Abstractions.Indexing;
using Raven.Client.Indexes;
namespace Raven.TimeZones
{
public class ZoneShapesIndex : AbstractIndexCreationTask<ZoneShape>
{
public ZoneShapesIndex()
{
Map = shapes => from shape in shapes
select new
{
shape.Zone,
_ = SpatialGenerate("location", shape.Shape, SpatialSearchStrategy.GeohashPrefixTree, 3)
};
}
}
}
|
Clean up reading templates from embedded resources. | using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using EnumsNET;
using Microsoft.Extensions.FileProviders;
namespace SJP.Schematic.Reporting.Html
{
internal class TemplateProvider : ITemplateProvider
{
public string GetTemplate(ReportTemplate template)
{
if (!template.IsValid())
throw new ArgumentException($"The { nameof(ReportTemplate) } provided must be a valid enum.", nameof(template));
var resource = GetResource(template);
return GetResourceAsString(resource);
}
private static IFileInfo GetResource(ReportTemplate template)
{
var templateKey = template.ToString();
var templateFileName = templateKey + TemplateExtension;
var resourceFiles = _fileProvider.GetDirectoryContents("/");
var templateResource = resourceFiles.FirstOrDefault(r => r.Name.EndsWith(templateFileName));
if (templateResource == null)
throw new NotSupportedException($"The given template: { templateKey } is not a supported template.");
return templateResource;
}
private static string GetResourceAsString(IFileInfo fileInfo)
{
if (fileInfo == null)
throw new ArgumentNullException(nameof(fileInfo));
using (var stream = new MemoryStream())
using (var reader = fileInfo.CreateReadStream())
{
reader.CopyTo(stream);
return Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length);
}
}
private static readonly IFileProvider _fileProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly(), Assembly.GetExecutingAssembly().GetName().Name + ".Html.Templates");
private const string TemplateExtension = ".cshtml";
}
}
| using System;
using System.IO;
using System.Linq;
using System.Reflection;
using EnumsNET;
using Microsoft.Extensions.FileProviders;
namespace SJP.Schematic.Reporting.Html
{
internal class TemplateProvider : ITemplateProvider
{
public string GetTemplate(ReportTemplate template)
{
if (!template.IsValid())
throw new ArgumentException($"The { nameof(ReportTemplate) } provided must be a valid enum.", nameof(template));
var resource = GetResource(template);
return GetResourceAsString(resource);
}
private static IFileInfo GetResource(ReportTemplate template)
{
var templateKey = template.ToString();
var templateFileName = templateKey + TemplateExtension;
var resourceFiles = _fileProvider.GetDirectoryContents("/");
var templateResource = resourceFiles.FirstOrDefault(r => r.Name.EndsWith(templateFileName));
if (templateResource == null)
throw new NotSupportedException($"The given template: { templateKey } is not a supported template.");
return templateResource;
}
private static string GetResourceAsString(IFileInfo fileInfo)
{
if (fileInfo == null)
throw new ArgumentNullException(nameof(fileInfo));
using (var stream = fileInfo.CreateReadStream())
using (var reader = new StreamReader(stream))
return reader.ReadToEnd();
}
private static readonly IFileProvider _fileProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly(), Assembly.GetExecutingAssembly().GetName().Name + ".Html.Templates");
private const string TemplateExtension = ".cshtml";
}
}
|
Fix import status succeeded spelling error | using System;
using System.Collections.Generic;
using System.Text;
namespace Alexa.NET.Management.Package
{
public enum ImportStatus
{
FAILED,
IN_PROGRESS,
SUCCEEEDED
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Alexa.NET.Management.Package
{
public enum ImportStatus
{
FAILED,
IN_PROGRESS,
SUCCEEDED
}
}
|
Make cursor redundancy more redundant | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnlockCursorOnStart : MonoBehaviour
{
void Start()
{
Invoke("unlockCursor", .1f);
}
void unlockCursor()
{
Cursor.lockState = GameController.DefaultCursorMode;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnlockCursorOnStart : MonoBehaviour
{
[SerializeField]
bool forceOnUpdate = true;
void Start()
{
Invoke("unlockCursor", .1f);
}
void unlockCursor()
{
Cursor.lockState = GameController.DefaultCursorMode;
}
private void Update()
{
if (Cursor.lockState != GameController.DefaultCursorMode)
Cursor.lockState = GameController.DefaultCursorMode;
}
}
|
Use {0:c} rather than ToString("c") where possible. | @if (Model.DiscountedPrice != Model.Price)
{
<b class="inactive-price" style="text-decoration:line-through" title="@T("Was {0}", Model.Price.ToString("c"))">@Model.Price.ToString("c")</b>
<b class="discounted-price" title="@T("Now {0}", Model.DiscountedPrice.ToString("c"))">@Model.DiscountedPrice.ToString("c")</b>
<span class="discount-comment">@Model.DiscountComment</span>
}
else
{
<b>@Model.Price.ToString("c")</b>
}
| @if (Model.DiscountedPrice != Model.Price)
{
<b class="inactive-price" style="text-decoration:line-through" title="@T("Was {0:c}", Model.Price)">@Model.Price.ToString("c")</b>
<b class="discounted-price" title="@T("Now {0:c}", Model.DiscountedPrice)">@Model.DiscountedPrice.ToString("c")</b>
<span class="discount-comment">@Model.DiscountComment</span>
}
else
{
<b>@Model.Price.ToString("c")</b>
}
|
Use Persist value from config. | using System;
using System.Collections.Generic;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing;
namespace RawRabbit.Common
{
public interface IBasicPropertiesProvider
{
IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null);
}
public class BasicPropertiesProvider : IBasicPropertiesProvider
{
public IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null)
{
var properties = new BasicProperties
{
MessageId = Guid.NewGuid().ToString(),
Persistent = true,
Headers = new Dictionary<string, object>
{
{ PropertyHeaders.Sent, DateTime.UtcNow.ToString("u") },
{ PropertyHeaders.MessageType, typeof(TMessage).FullName }
}
};
custom?.Invoke(properties);
return properties;
}
}
}
| using System;
using System.Collections.Generic;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing;
using RawRabbit.Configuration;
namespace RawRabbit.Common
{
public interface IBasicPropertiesProvider
{
IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null);
}
public class BasicPropertiesProvider : IBasicPropertiesProvider
{
private readonly RawRabbitConfiguration _config;
public BasicPropertiesProvider(RawRabbitConfiguration config)
{
_config = config;
}
public IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null)
{
var properties = new BasicProperties
{
MessageId = Guid.NewGuid().ToString(),
Persistent = _config.PersistentDeliveryMode,
Headers = new Dictionary<string, object>
{
{ PropertyHeaders.Sent, DateTime.UtcNow.ToString("u") },
{ PropertyHeaders.MessageType, typeof(TMessage).FullName }
}
};
custom?.Invoke(properties);
return properties;
}
}
}
|
Add util extention for rendering GUI. | #region Using
using System;
using System.Numerics;
using Emotion.Graphics.Objects;
using Emotion.Primitives;
#endregion
namespace Emotion.Plugins.ImGuiNet
{
public static class ImGuiExtensions
{
public static Tuple<Vector2, Vector2> GetImGuiUV(this Texture t, Rectangle? uv = null)
{
Rectangle reqUv;
if (uv == null)
reqUv = new Rectangle(0, 0, t.Size);
else
reqUv = (Rectangle) uv;
Vector2 uvOne = new Vector2(
reqUv.X / t.Size.X,
reqUv.Y / t.Size.Y * -1
);
Vector2 uvTwo = new Vector2(
(reqUv.X + reqUv.Size.X) / t.Size.X,
(reqUv.Y + reqUv.Size.Y) / t.Size.Y * -1
);
return new Tuple<Vector2, Vector2>(uvOne, uvTwo);
}
}
} | #region Using
using System;
using System.Numerics;
using Emotion.Graphics;
using Emotion.Graphics.Objects;
using Emotion.Primitives;
using ImGuiNET;
#endregion
namespace Emotion.Plugins.ImGuiNet
{
public static class ImGuiExtensions
{
public static Tuple<Vector2, Vector2> GetImGuiUV(this Texture t, Rectangle? uv = null)
{
Rectangle reqUv;
if (uv == null)
reqUv = new Rectangle(0, 0, t.Size);
else
reqUv = (Rectangle) uv;
Vector2 uvOne = new Vector2(
reqUv.X / t.Size.X,
reqUv.Y / t.Size.Y * -1
);
Vector2 uvTwo = new Vector2(
(reqUv.X + reqUv.Size.X) / t.Size.X,
(reqUv.Y + reqUv.Size.Y) / t.Size.Y * -1
);
return new Tuple<Vector2, Vector2>(uvOne, uvTwo);
}
public static void RenderUI(this RenderComposer composer)
{
ImGuiNetPlugin.RenderUI(composer);
}
}
} |
Test for loading import from data url | namespace AngleSharp.Core.Tests.Library
{
using AngleSharp.Core.Tests.Mocks;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
[TestFixture]
public class PageImportTests
{
[Test]
public async Task ImportPageFromVirtualRequest()
{
var requester = new MockRequester();
var receivedRequest = new TaskCompletionSource<String>();
requester.OnRequest = request => receivedRequest.SetResult(request.Address.Href);
var config = Configuration.Default.WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true, new[] { requester });
var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("<!doctype html><link rel=import href=http://example.com/test.html>"));
var link = document.QuerySelector<IHtmlLinkElement>("link");
var result = await receivedRequest.Task;
Assert.AreEqual("import", link.Relation);
Assert.IsNotNull(link.Import);
Assert.AreEqual("http://example.com/test.html", result);
}
}
}
| namespace AngleSharp.Core.Tests.Library
{
using AngleSharp.Core.Tests.Mocks;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
[TestFixture]
public class PageImportTests
{
[Test]
public async Task ImportPageFromVirtualRequest()
{
var requester = new MockRequester();
var receivedRequest = new TaskCompletionSource<String>();
requester.OnRequest = request => receivedRequest.SetResult(request.Address.Href);
var config = Configuration.Default.WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true, new[] { requester });
var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("<!doctype html><link rel=import href=http://example.com/test.html>"));
var link = document.QuerySelector<IHtmlLinkElement>("link");
var result = await receivedRequest.Task;
Assert.AreEqual("import", link.Relation);
Assert.IsNotNull(link.Import);
Assert.AreEqual("http://example.com/test.html", result);
}
[Test]
public async Task ImportPageFromDataRequest()
{
var receivedRequest = new TaskCompletionSource<Boolean>();
var config = Configuration.Default.WithDefaultLoader(setup =>
{
setup.IsResourceLoadingEnabled = true;
setup.Filter = request =>
{
receivedRequest.SetResult(true);
return true;
};
});
var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("<!doctype html><link rel=import href='data:text/html,<div>foo</div>'>"));
var link = document.QuerySelector<IHtmlLinkElement>("link");
var finished = await receivedRequest.Task;
Assert.AreEqual("import", link.Relation);
Assert.IsNotNull(link.Import);
Assert.AreEqual("foo", link.Import.QuerySelector("div").TextContent);
}
}
}
|
Add Device & Thing Titles to Endpoint GridList | @model PagedList.IPagedList<DynThings.Data.Models.Endpoint>
<table class="table striped hovered border bordered">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>GUID</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.EndPointType.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.GUID)
</td>
<td>
@Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
</tbody>
</table>
<div id="EndPointsListPager">
<input id="EndPointCurrentPage" value="@Model.PageNumber.ToString()" hidden />
@Html.PagedListPager(Model, page => Url.Action("ListPV", new { page }))
</div>
| @model PagedList.IPagedList<DynThings.Data.Models.Endpoint>
<table class="table striped hovered border bordered">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>Device</th>
<th>Thing</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.EndPointType.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Device.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Thing.Title)
</td>
<td>
@Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
</tbody>
</table>
<div id="EndPointsListPager">
<input id="EndPointCurrentPage" value="@Model.PageNumber.ToString()" hidden />
@Html.PagedListPager(Model, page => Url.Action("ListPV", new { page }))
</div>
|
Use IConfiguration instead of IConfigurationRoot | using LiteDB;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
namespace TIKSN.Data.LiteDB
{
/// <summary>
/// Create LiteDB database
/// </summary>
public class LiteDbDatabaseProvider : ILiteDbDatabaseProvider
{
private readonly IConfigurationRoot _configuration;
private readonly string _connectionStringKey;
private readonly IFileProvider _fileProvider;
public LiteDbDatabaseProvider(IConfigurationRoot configuration, string connectionStringKey,
IFileProvider fileProvider = null)
{
this._configuration = configuration;
this._connectionStringKey = connectionStringKey;
this._fileProvider = fileProvider;
}
/// <summary>
/// Creates LiteDB database with mapper
/// </summary>
/// <param name="mapper">Mapper</param>
/// <returns></returns>
public LiteDatabase GetDatabase(BsonMapper mapper)
{
var connectionString =
new ConnectionString(this._configuration.GetConnectionString(this._connectionStringKey));
if (this._fileProvider != null)
{
connectionString.Filename = this._fileProvider.GetFileInfo(connectionString.Filename).PhysicalPath;
}
return new LiteDatabase(connectionString);
}
/// <summary>
/// Creates LiteDB database
/// </summary>
/// <returns></returns>
public LiteDatabase GetDatabase() => this.GetDatabase(null);
}
}
| using LiteDB;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
namespace TIKSN.Data.LiteDB
{
/// <summary>
/// Create LiteDB database
/// </summary>
public class LiteDbDatabaseProvider : ILiteDbDatabaseProvider
{
private readonly IConfiguration _configuration;
private readonly string _connectionStringKey;
private readonly IFileProvider _fileProvider;
public LiteDbDatabaseProvider(IConfiguration configuration, string connectionStringKey,
IFileProvider fileProvider = null)
{
this._configuration = configuration;
this._connectionStringKey = connectionStringKey;
this._fileProvider = fileProvider;
}
/// <summary>
/// Creates LiteDB database with mapper
/// </summary>
/// <param name="mapper">Mapper</param>
/// <returns></returns>
public LiteDatabase GetDatabase(BsonMapper mapper)
{
var connectionString =
new ConnectionString(this._configuration.GetConnectionString(this._connectionStringKey));
if (this._fileProvider != null)
{
connectionString.Filename = this._fileProvider.GetFileInfo(connectionString.Filename).PhysicalPath;
}
return new LiteDatabase(connectionString);
}
/// <summary>
/// Creates LiteDB database
/// </summary>
/// <returns></returns>
public LiteDatabase GetDatabase() => this.GetDatabase(null);
}
}
|
Remove the silly `stop` alias for `kill`. | /*
* SDB - Mono Soft Debugger Client
* Copyright 2013 Alex Rønne Petersen
*
* 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.Collections.Generic;
namespace Mono.Debugger.Client.Commands
{
sealed class KillCommand : Command
{
public override string[] Names
{
get { return new[] { "kill", "stop" }; }
}
public override string Summary
{
get { return "Kill the inferior process."; }
}
public override string Syntax
{
get { return "kill|stop"; }
}
public override void Process(string args)
{
if (Debugger.State == State.Exited)
Log.Error("No inferior process");
else
Debugger.Kill();
}
}
}
| /*
* SDB - Mono Soft Debugger Client
* Copyright 2013 Alex Rønne Petersen
*
* 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.Collections.Generic;
namespace Mono.Debugger.Client.Commands
{
sealed class KillCommand : Command
{
public override string[] Names
{
get { return new[] { "kill" }; }
}
public override string Summary
{
get { return "Kill the inferior process."; }
}
public override string Syntax
{
get { return "kill|stop"; }
}
public override void Process(string args)
{
if (Debugger.State == State.Exited)
Log.Error("No inferior process");
else
Debugger.Kill();
}
}
}
|
Drop audio in summary videos | using System.Diagnostics;
namespace Cams
{
public static class VideoConverter
{
public static bool CodecCopy(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -codec copy {outputFile}");
}
public static bool Concat(string listFilePath, string outputFile)
{
return Run($"-y -safe 0 -f concat -i {listFilePath} -c copy {outputFile}");
}
public static bool FastForward(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -filter:v \"setpts = 0.01 * PTS\" {outputFile}");
}
public static bool CheckValidVideoFile(string inputFile)
{
return Run($"-v error -i {inputFile} -f null -");
}
static bool Run(string args)
{
using (var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "ffmpeg",
Arguments = args
}
})
{
process.Start();
process.WaitForExit();
return process.ExitCode == 0;
}
}
}
}
| using System.Diagnostics;
namespace Cams
{
public static class VideoConverter
{
public static bool CodecCopy(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -codec copy {outputFile}");
}
public static bool Concat(string listFilePath, string outputFile)
{
return Run($"-y -safe 0 -f concat -i {listFilePath} -c copy {outputFile}");
}
public static bool FastForward(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -filter:v \"setpts = 0.01 * PTS\" -an {outputFile}");
}
public static bool CheckValidVideoFile(string inputFile)
{
return Run($"-v error -i {inputFile} -f null -");
}
static bool Run(string args)
{
using (var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "ffmpeg",
Arguments = args
}
})
{
process.Start();
process.WaitForExit();
return process.ExitCode == 0;
}
}
}
}
|
Update application template with working code to prevent the main thread from exiting | using System;
namespace $safeprojectname$
{
public class Program
{
public static void Main()
{
}
}
}
| using System;
namespace $safeprojectname$
{
public class Program
{
public static void Main()
{
// Insert your code below this line
// The main() method has to end with this infinite loop.
// Do not use the NETMF style : Thread.Sleep(Timeout.Infinite)
while (true)
{
Thread.Sleep(200);
}
}
}
}
|
Add properties and methods about connection. Implement `IDisposable` interface. | namespace PcscDotNet
{
public class PcscConnection
{
public PcscContext Context { get; private set; }
public IPcscProvider Provider { get; private set; }
public string ReaderName { get; private set; }
public PcscConnection(PcscContext context, string readerName)
{
Provider = (Context = context).Provider;
ReaderName = readerName;
}
}
}
| using System;
namespace PcscDotNet
{
public class PcscConnection : IDisposable
{
public PcscContext Context { get; private set; }
public SCardHandle Handle { get; private set; }
public bool IsConnect => Handle.HasValue;
public bool IsDisposed { get; private set; } = false;
public SCardProtocols Protocols { get; private set; } = SCardProtocols.Undefined;
public IPcscProvider Provider { get; private set; }
public string ReaderName { get; private set; }
public PcscConnection(PcscContext context, string readerName)
{
Provider = (Context = context).Provider;
ReaderName = readerName;
}
~PcscConnection()
{
Dispose();
}
public unsafe PcscConnection Connect(SCardShare shareMode, SCardProtocols protocols, PcscExceptionHandler onException = null)
{
SCardHandle handle;
Provider.SCardConnect(Context.Handle, ReaderName, shareMode, protocols, &handle, &protocols).ThrowIfNotSuccess(onException);
Handle = handle;
Protocols = protocols;
return this;
}
public PcscConnection Disconnect(SCardDisposition disposition = SCardDisposition.Leave, PcscExceptionHandler onException = null)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(PcscConnection), nameof(Disconnect));
DisconnectInternal(disposition, onException);
return this;
}
public void Dispose()
{
if (IsDisposed) return;
DisconnectInternal();
IsDisposed = true;
GC.SuppressFinalize(this);
}
private void DisconnectInternal(SCardDisposition disposition = SCardDisposition.Leave, PcscExceptionHandler onException = null)
{
if (!IsConnect) return;
Provider.SCardDisconnect(Handle, disposition).ThrowIfNotSuccess(onException);
Handle = SCardHandle.Default;
Protocols = SCardProtocols.Undefined;
}
}
}
|
Print to STDOUT - 2> is broken on Mono/OS X | using System;
using System.Linq;
namespace Gherkin.AstGenerator
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: Gherkin.AstGenerator.exe test-feature-file.feature");
return 100;
}
var startTime = Environment.TickCount;
foreach (var featureFilePath in args)
{
try
{
var astText = AstGenerator.GenerateAst(featureFilePath);
Console.WriteLine(astText);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
}
var endTime = Environment.TickCount;
if (Environment.GetEnvironmentVariable("GHERKIN_PERF") != null)
{
Console.Error.WriteLine(endTime - startTime);
}
return 0;
}
}
}
| using System;
using System.Linq;
namespace Gherkin.AstGenerator
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: Gherkin.AstGenerator.exe test-feature-file.feature");
return 100;
}
var startTime = Environment.TickCount;
foreach (var featureFilePath in args)
{
try
{
var astText = AstGenerator.GenerateAst(featureFilePath);
Console.WriteLine(astText);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return 1;
}
}
var endTime = Environment.TickCount;
if (Environment.GetEnvironmentVariable("GHERKIN_PERF") != null)
{
Console.Error.WriteLine(endTime - startTime);
}
return 0;
}
}
}
|
Make Status Effects UI better positioned. | using Content.Client.Utility;
using Robust.Client.Graphics;
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.IoC;
namespace Content.Client.UserInterface
{
/// <summary>
/// The status effects display on the right side of the screen.
/// </summary>
public sealed class StatusEffectsUI : Control
{
private readonly VBoxContainer _vBox;
private TextureRect _healthStatusRect;
public StatusEffectsUI()
{
_vBox = new VBoxContainer {GrowHorizontal = GrowDirection.Begin};
AddChild(_vBox);
_vBox.AddChild(_healthStatusRect = new TextureRect
{
Texture = IoCManager.Resolve<IResourceCache>().GetTexture("/Textures/Mob/UI/Human/human0.png")
});
SetAnchorAndMarginPreset(LayoutPreset.TopRight);
MarginTop = 200;
}
public void SetHealthIcon(Texture texture)
{
_healthStatusRect.Texture = texture;
}
}
}
| using Content.Client.Utility;
using Robust.Client.Graphics;
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.IoC;
namespace Content.Client.UserInterface
{
/// <summary>
/// The status effects display on the right side of the screen.
/// </summary>
public sealed class StatusEffectsUI : Control
{
private readonly VBoxContainer _vBox;
private TextureRect _healthStatusRect;
public StatusEffectsUI()
{
_vBox = new VBoxContainer {GrowHorizontal = GrowDirection.Begin};
AddChild(_vBox);
_vBox.AddChild(_healthStatusRect = new TextureRect
{
TextureScale = (2, 2),
Texture = IoCManager.Resolve<IResourceCache>().GetTexture("/Textures/Mob/UI/Human/human0.png")
});
SetAnchorAndMarginPreset(LayoutPreset.TopRight);
MarginTop = 200;
MarginRight = 10;
}
public void SetHealthIcon(Texture texture)
{
_healthStatusRect.Texture = texture;
}
}
}
|
Add IsActive and ThrowIfNotActiveWithGivenName to AppLock interface | using System;
namespace RapidCore.Locking
{
/// <summary>
/// When implemented in a downstream locker provider, this instance contains a handle to the underlying lock instance
/// </summary>
public interface IDistributedAppLock : IDisposable
{
/// <summary>
/// The name of the lock acquired
/// </summary>
string Name { get; set; }
}
} | using System;
namespace RapidCore.Locking
{
/// <summary>
/// When implemented in a downstream locker provider, this instance contains a handle to the underlying lock instance
/// </summary>
public interface IDistributedAppLock : IDisposable
{
/// <summary>
/// The name of the lock acquired
/// </summary>
string Name { get; set; }
/// <summary>
/// Determines whether the lock has been taken in the underlying source and is still active
/// </summary>
bool IsActive { get; set; }
/// <summary>
/// When implemented in a downstream provider it will verify that the current instance of the lock is in an
/// active (locked) state and has the name given to the method
/// </summary>
/// <param name="name"></param>
/// <exception cref="InvalidOperationException">
/// When the lock is either not active, or has a different name than provided in <paramref name="name"/>
/// </exception>
void ThrowIfNotActiveWithGivenName(string name);
}
} |
Use JsonProperty attribute and remove unused types | /* Empiria Extensions ****************************************************************************************
* *
* Module : Cognitive Services Component : Service provider *
* Assembly : Empiria.Cognition.dll Pattern : Data Transfer Objects *
* Type : TranslatorDataTypes License : Please read LICENSE.txt file *
* *
* Summary : Define data types for Microsoft Azure Cognition Translator Services. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
namespace Empiria.Cognition.Providers {
/// <summary>Summary : Define data types for Microsoft Azure Cognition Translator Services.</summary>
internal class Alignment {
internal string Proj {
get; set;
}
}
internal class SentenceLength {
internal int[] SrcSentLen {
get; set;
}
internal int[] TransSentLen {
get; set;
}
}
internal class Translation {
internal string Text {
get; set;
}
internal TextResult Transliteration {
get; set;
}
internal string To {
get; set;
}
internal Alignment Alignment {
get; set;
}
internal SentenceLength SentLen {
get; set;
}
}
internal class DetectedLanguage {
internal string Language {
get; set;
}
internal float Score {
get; set;
}
}
internal class TextResult {
internal string Text {
get; set;
}
internal string Script {
get; set;
}
}
internal class TranslatorDataTypes {
internal DetectedLanguage DetectedLanguage {
get; set;
}
internal TextResult SourceText {
get; set;
}
internal Translation[] Translations {
get; set;
}
}
}
| /* Empiria Extensions ****************************************************************************************
* *
* Module : Cognitive Services Component : Service provider *
* Assembly : Empiria.Cognition.dll Pattern : Data Transfer Objects *
* Type : TranslatorDataTypes License : Please read LICENSE.txt file *
* *
* Summary : Define data types for Microsoft Azure Cognition Translator Services. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
using Newtonsoft.Json;
namespace Empiria.Cognition.Providers {
internal class Translation {
[JsonProperty]
internal string Text {
get; set;
}
[JsonProperty]
internal string To {
get; set;
}
}
internal class TranslatorResult {
[JsonProperty]
internal Translation[] Translations {
get; set;
}
}
}
|
Add comments to vision quickstart. | // Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START vision_quickstart]
using Google.Cloud.Vision.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
var client = ImageAnnotatorClient.Create();
var image = Image.FromFile("wakeupcat.jpg");
var response = client.DetectLabels(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
}
}
}
// [END vision_quickstart] | // Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START vision_quickstart]
using Google.Cloud.Vision.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// Instantiates a client
var client = ImageAnnotatorClient.Create();
// Load the image file into memory
var image = Image.FromFile("wakeupcat.jpg");
// Performs label detection on the image file
var response = client.DetectLabels(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
}
}
}
// [END vision_quickstart]
|
Print source and destination addresses on ICMPv6 packets |
using TAP;
using System;
using System.Net;
public class TAPCfgTest {
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start("Device name");
Console.WriteLine("Got device name: {0}", dev.DeviceName);
dev.MTU = 1280;
dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
dev.Enabled = true;
while (true) {
EthernetFrame frame = dev.Read();
if (frame == null)
break;
if (frame.EtherType == EtherType.IPv6) {
IPv6Packet packet = new IPv6Packet(frame.Payload);
if (packet.NextHeader == ProtocolType.ICMPv6) {
ICMPv6Type type = (ICMPv6Type) packet.Payload[0];
Console.WriteLine("Got ICMPv6 packet type {0}", type);
Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload));
}
}
Console.WriteLine("Read Ethernet frame of type {0}",
frame.EtherType);
Console.WriteLine("Source address: {0}",
BitConverter.ToString(frame.SourceAddress));
Console.WriteLine("Destination address: {0}",
BitConverter.ToString(frame.DestinationAddress));
}
}
}
|
using TAP;
using System;
using System.Net;
public class TAPCfgTest {
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start("Device name");
Console.WriteLine("Got device name: {0}", dev.DeviceName);
dev.MTU = 1280;
dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
dev.Enabled = true;
while (true) {
EthernetFrame frame = dev.Read();
if (frame == null)
break;
if (frame.EtherType == EtherType.IPv6) {
IPv6Packet packet = new IPv6Packet(frame.Payload);
if (packet.NextHeader == ProtocolType.ICMPv6) {
ICMPv6Type type = (ICMPv6Type) packet.Payload[0];
Console.WriteLine("Got ICMPv6 packet type {0}", type);
Console.WriteLine("Src: {0}", packet.Source);
Console.WriteLine("Dst: {0}", packet.Destination);
Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload));
}
}
Console.WriteLine("Read Ethernet frame of type {0}",
frame.EtherType);
Console.WriteLine("Source address: {0}",
BitConverter.ToString(frame.SourceAddress));
Console.WriteLine("Destination address: {0}",
BitConverter.ToString(frame.DestinationAddress));
}
}
}
|
Switch to .Dispose() from .Close(). | using System;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace apod_api
{
public sealed class APOD_API
{
public APOD_API()
{
date = DateTime.Today;
}
public void sendRequest()
{
generateURL();
WebRequest request = WebRequest.Create(api_url);
api_response = request.GetResponse();
Stream responseStream = api_response.GetResponseStream();
sr = new StreamReader(responseStream);
myAPOD = JsonConvert.DeserializeObject<APOD>(sr.ReadToEnd());
sr.Close();
responseStream.Close();
api_response.Close();
}
public APOD_API setDate(DateTime newDate)
{
date = newDate;
return this;
}
private void generateURL()
{
api_url = api + "?api_key=" + api_key + "&date=" + date.ToString("yyyy-MM-dd");
}
private string api_key = "DEMO_KEY";
private string api = "https://api.nasa.gov/planetary/apod";
private string api_url;
private DateTime date;
private WebResponse api_response;
private StreamReader sr;
private APOD myAPOD;
public APOD apod { get { return myAPOD; } }
}
} | using System;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace apod_api
{
public sealed class APOD_API
{
public APOD_API()
{
date = DateTime.Today;
}
public void sendRequest()
{
generateURL();
WebRequest request = WebRequest.Create(api_url);
api_response = request.GetResponse();
Stream responseStream = api_response.GetResponseStream();
sr = new StreamReader(responseStream);
myAPOD = JsonConvert.DeserializeObject<APOD>(sr.ReadToEnd());
sr.Dispose();
responseStream.Dispose();
api_response.Dispose();
}
public APOD_API setDate(DateTime newDate)
{
date = newDate;
return this;
}
private void generateURL()
{
api_url = api + "?api_key=" + api_key + "&date=" + date.ToString("yyyy-MM-dd");
}
private string api_key = "DEMO_KEY";
private string api = "https://api.nasa.gov/planetary/apod";
private string api_url;
private DateTime date;
private WebResponse api_response;
private StreamReader sr;
private APOD myAPOD;
public APOD apod { get { return myAPOD; } }
}
} |
Fix UpdateManager NRE for soundspawn | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundSpawn : MonoBehaviour
{
public AudioSource audioSource;
//We need to handle this manually to prevent multiple requests grabbing sound pool items in the same frame
public bool isPlaying = false;
private float waitLead = 0;
public void PlayOneShot()
{
audioSource.PlayOneShot(audioSource.clip);
WaitForPlayToFinish();
}
public void PlayNormally()
{
audioSource.Play();
WaitForPlayToFinish();
}
void WaitForPlayToFinish()
{
waitLead = 0f;
UpdateManager.Add(CallbackType.UPDATE, UpdateMe);
}
void UpdateMe()
{
waitLead += Time.deltaTime;
if (waitLead > 0.2f)
{
if (!audioSource.isPlaying)
{
UpdateManager.Remove(CallbackType.UPDATE, UpdateMe);
isPlaying = false;
waitLead = 0f;
}
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundSpawn : MonoBehaviour
{
public AudioSource audioSource;
//We need to handle this manually to prevent multiple requests grabbing sound pool items in the same frame
public bool isPlaying = false;
private float waitLead = 0;
public void PlayOneShot()
{
audioSource.PlayOneShot(audioSource.clip);
WaitForPlayToFinish();
}
public void PlayNormally()
{
audioSource.Play();
WaitForPlayToFinish();
}
void WaitForPlayToFinish()
{
waitLead = 0f;
UpdateManager.Add(CallbackType.UPDATE, UpdateMe);
}
private void OnDisable()
{
if(isPlaying)
{
UpdateManager.Remove(CallbackType.UPDATE, UpdateMe);
isPlaying = false;
}
}
void UpdateMe()
{
waitLead += Time.deltaTime;
if (waitLead > 0.2f)
{
if (!audioSource.isPlaying)
{
UpdateManager.Remove(CallbackType.UPDATE, UpdateMe);
isPlaying = false;
waitLead = 0f;
}
}
}
}
|
Add exit code to console app; return HostFactory.Run result | // Copyright 2014 Ron Griffin, ...
//
// 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 Topshelf;
namespace MassTransit.Host.RabbitMQ
{
/// <summary>
/// Entry point of the host process used to construct the Topshelf service.
/// </summary>
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<ServiceHost>(s =>
{
s.ConstructUsing(name => new ServiceHost());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("MassTransit RabbitMQ Service Bus Host");
x.SetDisplayName("MassTransitServiceBusHost");
x.SetServiceName("MassTransitServiceBusHost");
});
//TODO: extra parameter stuff
}
}
}
| // Copyright 2014 Ron Griffin, ...
//
// 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 Magnum.Extensions;
using Topshelf;
namespace MassTransit.Host.RabbitMQ
{
/// <summary>
/// Entry point of the host process used to construct the Topshelf service.
/// </summary>
class Program
{
static void Main(string[] args)
{
var exitCode = HostFactory.Run(x =>
{
x.Service<ServiceHost>(s =>
{
s.ConstructUsing(name => new ServiceHost());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("MassTransit RabbitMQ Service Bus Host");
x.SetDisplayName("MassTransitServiceBusHost");
x.SetServiceName("MassTransitServiceBusHost");
});
//TODO: extra parameter stuff
Environment.Exit((int)exitCode);
}
}
}
|
Fix windows key blocking applying when window is inactive / when watching a replay | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Game.Configuration;
namespace osu.Desktop.Windows
{
public class GameplayWinKeyBlocker : Component
{
private Bindable<bool> allowScreenSuspension;
private Bindable<bool> disableWinKey;
private GameHost host;
[BackgroundDependencyLoader]
private void load(GameHost host, OsuConfigManager config)
{
this.host = host;
allowScreenSuspension = host.AllowScreenSuspension.GetBoundCopy();
allowScreenSuspension.BindValueChanged(_ => updateBlocking());
disableWinKey = config.GetBindable<bool>(OsuSetting.GameplayDisableWinKey);
disableWinKey.BindValueChanged(_ => updateBlocking(), true);
}
private void updateBlocking()
{
bool shouldDisable = disableWinKey.Value && !allowScreenSuspension.Value;
if (shouldDisable)
host.InputThread.Scheduler.Add(WindowsKey.Disable);
else
host.InputThread.Scheduler.Add(WindowsKey.Enable);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Game;
using osu.Game.Configuration;
namespace osu.Desktop.Windows
{
public class GameplayWinKeyBlocker : Component
{
private Bindable<bool> disableWinKey;
private Bindable<bool> localUserPlaying;
[Resolved]
private GameHost host { get; set; }
[BackgroundDependencyLoader(true)]
private void load(OsuGame game, OsuConfigManager config)
{
localUserPlaying = game.LocalUserPlaying.GetBoundCopy();
localUserPlaying.BindValueChanged(_ => updateBlocking());
disableWinKey = config.GetBindable<bool>(OsuSetting.GameplayDisableWinKey);
disableWinKey.BindValueChanged(_ => updateBlocking(), true);
}
private void updateBlocking()
{
bool shouldDisable = disableWinKey.Value && localUserPlaying.Value;
if (shouldDisable)
host.InputThread.Scheduler.Add(WindowsKey.Disable);
else
host.InputThread.Scheduler.Add(WindowsKey.Enable);
}
}
}
|
Make PublicIp variable lazy again. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco.Variables
{
public class PublicIpVariable : IVariableProvider
{
string _lastIp;
DateTime _lastUpdate;
public Dictionary<string, Func<string>> GetVariables()
{
var now = DateTime.Now;
if (now - _lastUpdate > TimeSpan.FromMinutes(1))
{
_lastIp = new WebClient().DownloadString("http://icanhazip.com").Trim();
_lastUpdate = now;
}
return new Dictionary<string, Func<string>>()
{
{ "publicIp", () => _lastIp }
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco.Variables
{
public class PublicIpVariable : IVariableProvider
{
string _lastIp;
DateTime _lastUpdate;
public Dictionary<string, Func<string>> GetVariables()
{
Func<string> getIp = () =>
{
var now = DateTime.Now;
if (now - _lastUpdate > TimeSpan.FromMinutes(1))
{
_lastIp = new WebClient().DownloadString("http://icanhazip.com").Trim();
_lastUpdate = now;
}
return _lastIp;
};
return new Dictionary<string, Func<string>>()
{
{ "publicIp", getIp }
};
}
}
}
|
Fix grammar in test name | using System.IO;
using Xunit;
namespace TfsHipChat.Tests
{
public class TfsIdentityTests
{
[Fact]
public void Url_ShouldReturnTheServerUrl_WhenDeserializedByValidXml()
{
const string serverUrl = "http://some-tfs-server.com";
const string tfsIdentityXml = "<TeamFoundationServer url=\"" + serverUrl + "\" />";
var serializer = new System.Xml.Serialization.XmlSerializer(typeof (TfsIdentity));
string url = null;
using (var reader = new StringReader(tfsIdentityXml))
{
var tfsIdentity = serializer.Deserialize(reader) as TfsIdentity;
if (tfsIdentity != null) url = tfsIdentity.Url;
}
Assert.Equal(url, serverUrl);
}
}
}
| using System.IO;
using Xunit;
namespace TfsHipChat.Tests
{
public class TfsIdentityTests
{
[Fact]
public void Url_ShouldReturnTheServerUrl_WhenDeserializedUsingValidXml()
{
const string serverUrl = "http://some-tfs-server.com";
const string tfsIdentityXml = "<TeamFoundationServer url=\"" + serverUrl + "\" />";
var serializer = new System.Xml.Serialization.XmlSerializer(typeof (TfsIdentity));
string url = null;
using (var reader = new StringReader(tfsIdentityXml))
{
var tfsIdentity = serializer.Deserialize(reader) as TfsIdentity;
if (tfsIdentity != null) url = tfsIdentity.Url;
}
Assert.Equal(url, serverUrl);
}
}
}
|
Add option to enable prefetch or not. | namespace LoadTests
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using EasyConsole;
using SqlStreamStore.Streams;
public class ReadAll : LoadTest
{
protected override async Task RunAsync(CancellationToken ct)
{
Output.WriteLine("");
Output.WriteLine(ConsoleColor.Green, "Appends events to streams and reads them all back in a single task.");
Output.WriteLine("");
var streamStore = GetStore();
await new AppendExpectedVersionAnyParallel()
.Append(streamStore, ct);
int readPageSize = Input.ReadInt("Read page size: ", 1, 10000);
var stopwatch = Stopwatch.StartNew();
int count = 0;
var position = Position.Start;
ReadAllPage page;
do
{
page = await streamStore.ReadAllForwards(position, readPageSize, cancellationToken: ct);
count += page.Messages.Length;
Console.Write($"\r> Read {count}");
position = page.NextPosition;
} while (!page.IsEnd);
stopwatch.Stop();
var rate = Math.Round((decimal)count / stopwatch.ElapsedMilliseconds * 1000, 0);
Output.WriteLine("");
Output.WriteLine($"> {count} messages read in {stopwatch.Elapsed} ({rate} m/s)");
}
}
} | namespace LoadTests
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using EasyConsole;
using SqlStreamStore.Streams;
public class ReadAll : LoadTest
{
protected override async Task RunAsync(CancellationToken ct)
{
Output.WriteLine("");
Output.WriteLine(ConsoleColor.Green, "Appends events to streams and reads them all back in a single task.");
Output.WriteLine("");
var streamStore = GetStore();
await new AppendExpectedVersionAnyParallel()
.Append(streamStore, ct);
int readPageSize = Input.ReadInt("Read page size: ", 1, 10000);
var prefectch = Input.ReadEnum<YesNo>("Prefetch: ");
var stopwatch = Stopwatch.StartNew();
int count = 0;
var position = Position.Start;
ReadAllPage page;
do
{
page = await streamStore.ReadAllForwards(position, readPageSize, prefetchJsonData: prefectch == YesNo.Yes, cancellationToken: ct);
count += page.Messages.Length;
Console.Write($"\r> Read {count}");
position = page.NextPosition;
} while (!page.IsEnd);
stopwatch.Stop();
var rate = Math.Round((decimal)count / stopwatch.ElapsedMilliseconds * 1000, 0);
Output.WriteLine("");
Output.WriteLine($"> {count} messages read in {stopwatch.Elapsed} ({rate} m/s)");
}
private enum YesNo
{
Yes,
No
}
}
} |
Comment code according to presentation's flow | using System;
using System.Threading.Tasks;
using static System.Console;
namespace AsyncLambda
{
class Program
{
static async Task Main()
{
WriteLine("Started");
try
{
Process(async () =>
{
await Task.Delay(500);
throw new Exception();
});
}
catch (Exception)
{
WriteLine("Catch");
}
await Task.Delay(2000);
WriteLine("Finished");
}
private static void Process(Action action)
{
action();
}
private static void Process(Func<Task> action)
{
action();
}
}
} | using System;
using System.Threading.Tasks;
using static System.Console;
namespace AsyncLambda
{
class Program
{
static async Task Main()
{
WriteLine("Started");
try
{
Process(async () =>
{
await Task.Delay(500);
throw new Exception();
});
}
catch (Exception)
{
WriteLine("Catch");
}
await Task.Delay(2000);
WriteLine("Finished");
}
private static void Process(Action action)
{
action();
}
// private static void Process(Func<Task> action)
// {
// action();
// }
}
} |
Set default render quality to medium | // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Visuals.Media.Imaging;
namespace Avalonia.Media
{
public class RenderOptions
{
/// <summary>
/// Defines the <see cref="BitmapInterpolationMode"/> property.
/// </summary>
public static readonly StyledProperty<BitmapInterpolationMode> BitmapInterpolationModeProperty =
AvaloniaProperty.RegisterAttached<RenderOptions, AvaloniaObject, BitmapInterpolationMode>(
"BitmapInterpolationMode",
BitmapInterpolationMode.HighQuality,
inherits: true);
/// <summary>
/// Gets the value of the BitmapInterpolationMode attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's left coordinate.</returns>
public static BitmapInterpolationMode GetBitmapInterpolationMode(AvaloniaObject element)
{
return element.GetValue(BitmapInterpolationModeProperty);
}
/// <summary>
/// Sets the value of the BitmapInterpolationMode attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The left value.</param>
public static void SetBitmapInterpolationMode(AvaloniaObject element, BitmapInterpolationMode value)
{
element.SetValue(BitmapInterpolationModeProperty, value);
}
}
}
| // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Visuals.Media.Imaging;
namespace Avalonia.Media
{
public class RenderOptions
{
/// <summary>
/// Defines the <see cref="BitmapInterpolationMode"/> property.
/// </summary>
public static readonly StyledProperty<BitmapInterpolationMode> BitmapInterpolationModeProperty =
AvaloniaProperty.RegisterAttached<RenderOptions, AvaloniaObject, BitmapInterpolationMode>(
"BitmapInterpolationMode",
BitmapInterpolationMode.MediumQuality,
inherits: true);
/// <summary>
/// Gets the value of the BitmapInterpolationMode attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's left coordinate.</returns>
public static BitmapInterpolationMode GetBitmapInterpolationMode(AvaloniaObject element)
{
return element.GetValue(BitmapInterpolationModeProperty);
}
/// <summary>
/// Sets the value of the BitmapInterpolationMode attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The left value.</param>
public static void SetBitmapInterpolationMode(AvaloniaObject element, BitmapInterpolationMode value)
{
element.SetValue(BitmapInterpolationModeProperty, value);
}
}
}
|
Remove unnecessary event callback in WPF demo | using System.Drawing;
using System.Windows;
namespace NetSparkle.TestAppWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Sparkle _sparkle;
public MainWindow()
{
InitializeComponent();
// remove the netsparkle key from registry
try
{
Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree("Software\\Microsoft\\NetSparkle.TestAppWPF");
}
catch { }
_sparkle = new Sparkle("https://deadpikle.github.io/NetSparkle/files/sample-app/appcast.xml", SystemIcons.Application); //, "NetSparkleTestApp.exe");
_sparkle.RunningFromWPF = true;
_sparkle.CloseWPFWindow += _sparkle_CloseWPFWindow;
_sparkle.StartLoop(true, true);
}
private void _sparkle_CloseWPFWindow()
{
Dispatcher.Invoke(() => {
Application.Current.Shutdown();
});
}
private void button1_Click(object sender, RoutedEventArgs e)
{
_sparkle.CheckForUpdatesAtUserRequest();
// _sparkle.StopLoop();
// Close();
}
}
}
| using System.Drawing;
using System.Windows;
namespace NetSparkle.TestAppWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Sparkle _sparkle;
public MainWindow()
{
InitializeComponent();
// remove the netsparkle key from registry
try
{
Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree("Software\\Microsoft\\NetSparkle.TestAppWPF");
}
catch { }
_sparkle = new Sparkle("https://deadpikle.github.io/NetSparkle/files/sample-app/appcast.xml", SystemIcons.Application); //, "NetSparkleTestApp.exe");
_sparkle.RunningFromWPF = true;
_sparkle.StartLoop(true, true);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
_sparkle.CheckForUpdatesAtUserRequest();
// _sparkle.StopLoop();
// Close();
}
}
}
|
Remove Include from clause types. | using System;
namespace AutoQueryable.Models.Enums
{
[Flags]
public enum ClauseType : short
{
Select = 1 << 1,
Top = 1 << 2,
Take = 1 << 3,
Skip = 1 << 4,
OrderBy = 1 << 5,
OrderByDesc = 1 << 6,
Include = 1 << 7,
GroupBy = 1 << 8,
First = 1 << 9,
Last = 1 << 10,
WrapWith = 1 << 11
}
} | using System;
namespace AutoQueryable.Models.Enums
{
[Flags]
public enum ClauseType : short
{
Select = 1 << 1,
Top = 1 << 2,
Take = 1 << 3,
Skip = 1 << 4,
OrderBy = 1 << 5,
OrderByDesc = 1 << 6,
GroupBy = 1 << 8,
First = 1 << 9,
Last = 1 << 10,
WrapWith = 1 << 11
}
} |
Fix "Widget Mouse Down" event property friendly names | using System.Windows.Input;
namespace DesktopWidgets.Events
{
internal class WidgetMouseDownEvent : WidgetEventBase
{
public MouseButton MouseButton { get; set; }
}
} | using System.ComponentModel;
using System.Windows.Input;
namespace DesktopWidgets.Events
{
internal class WidgetMouseDownEvent : WidgetEventBase
{
[DisplayName("Mouse Button")]
public MouseButton MouseButton { get; set; }
}
} |
Fix version and update copyright | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xamarin.Social")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin, Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012 Xamarin, Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xamarin.Social")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012-2013 Xamarin Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.2.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
Set navigation bar translucent to false to fix views overlapping. Fix bug | using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
namespace Example_Drawing
{
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
#region -= declarations and properties =-
protected UIWindow window;
protected UINavigationController mainNavController;
protected Example_Drawing.Screens.iPad.Home.HomeScreen iPadHome;
#endregion
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create our window
window = new UIWindow (UIScreen.MainScreen.Bounds);
window.MakeKeyAndVisible ();
// instantiate our main navigatin controller and add it's view to the window
mainNavController = new UINavigationController ();
iPadHome = new Example_Drawing.Screens.iPad.Home.HomeScreen ();
mainNavController.PushViewController (iPadHome, false);
window.RootViewController = mainNavController;
//
return true;
}
}
}
| using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
namespace Example_Drawing
{
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
#region -= declarations and properties =-
protected UIWindow window;
protected UINavigationController mainNavController;
protected Example_Drawing.Screens.iPad.Home.HomeScreen iPadHome;
#endregion
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create our window
window = new UIWindow (UIScreen.MainScreen.Bounds);
window.MakeKeyAndVisible ();
// instantiate our main navigatin controller and add it's view to the window
mainNavController = new UINavigationController ();
mainNavController.NavigationBar.Translucent = false;
iPadHome = new Example_Drawing.Screens.iPad.Home.HomeScreen ();
mainNavController.PushViewController (iPadHome, false);
window.RootViewController = mainNavController;
//
return true;
}
}
}
|
Fix incorrectly implemented async test. | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SGEnviro;
namespace SGEnviroTest
{
[TestClass]
public class ApiTest
{
private string apiKey;
[TestInitialize]
public void TestInitialize()
{
apiKey = ConfigurationManager.AppSettings["ApiKey"];
}
[TestMethod]
public void TestApiCanRetrieve()
{
var api = new SGEnviroApi(apiKey);
var result = api.GetPsiUpdateAsync().Result;
Assert.IsNotNull(result);
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SGEnviro;
namespace SGEnviroTest
{
[TestClass]
public class ApiTest
{
private string apiKey;
[TestInitialize]
public void TestInitialize()
{
apiKey = ConfigurationManager.AppSettings["ApiKey"];
}
[TestMethod]
public async Task TestApiCanRetrieve()
{
var api = new SGEnviroApi(apiKey);
var result = await api.GetPsiUpdateAsync();
Assert.IsNotNull(result);
}
}
}
|
Increment minor version - breaking changes. | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("RestKit")]
[assembly: AssemblyDescription("SIMPLE http client wrapper that eliminates the boilerplate code you don't want to write.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RestKit")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("de3a6223-af0a-4583-bdfb-63957829e7ba")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
[assembly: CLSCompliant(true)]
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("RestKit")]
[assembly: AssemblyDescription("SIMPLE http client wrapper that eliminates the boilerplate code you don't want to write.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RestKit")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("de3a6223-af0a-4583-bdfb-63957829e7ba")]
[assembly: AssemblyVersion("1.1.0.1")]
[assembly: AssemblyFileVersion("1.1.0.1")]
[assembly: CLSCompliant(true)]
|
Fix crashing in the case of empty args | using CommandLine;
namespace ProcessGremlinApp
{
public class ArgumentParser
{
public bool TryParse(string[] args, out Arguments arguments)
{
string invokedVerb = null;
object invokedVerbInstance = null;
var options = new Options();
if (Parser.Default.ParseArguments(
args,
options,
(verb, subOptions) =>
{
invokedVerb = verb;
invokedVerbInstance = subOptions;
}) && invokedVerbInstance is CommonOptions)
{
arguments = new Arguments(invokedVerb, invokedVerbInstance);
return true;
}
arguments = null;
return false;
}
}
} | using CommandLine;
namespace ProcessGremlinApp
{
public class ArgumentParser
{
public bool TryParse(string[] args, out Arguments arguments)
{
if (args != null && args.Length != 0)
{
string invokedVerb = null;
object invokedVerbInstance = null;
var options = new Options();
if (Parser.Default.ParseArguments(
args,
options,
(verb, subOptions) =>
{
invokedVerb = verb;
invokedVerbInstance = subOptions;
}) && invokedVerbInstance is CommonOptions)
{
arguments = new Arguments(invokedVerb, invokedVerbInstance);
return true;
}
}
arguments = null;
return false;
}
}
} |
Write usage information if no parameters are specified | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
if (args.Any())
{
commandDispatcher.Dispatch(args);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
if (args.Any())
{
commandDispatcher.Dispatch(args);
}
Console.WriteLine("Usage: appharbor COMMAND [command-options]");
Console.WriteLine("");
}
}
}
|
Increment the version to 1.1. | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lurking Window Detector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lurking Window Detector")]
[assembly: AssemblyCopyright("Copyright (c) 2016 KAMADA Ken'ichi")]
[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("700adee8-5d49-40f3-a3ae-05dc23501663")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lurking Window Detector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lurking Window Detector")]
[assembly: AssemblyCopyright("Copyright (c) 2016 KAMADA Ken'ichi")]
[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("700adee8-5d49-40f3-a3ae-05dc23501663")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
Remove superfluous StringComparison.Ordinal argument from ReadOnlySpan<char>.StarstWith(...) call, since the overload without a StringComparison in fact performs ordinal comparison semantics and the original call ultimately calls into the overload with no StringComparison argument anyway. In other words, you only have to specify StringComparison for span StartsWith calls when you are NOT using ordinal comparisons. | namespace Parsley;
partial class Grammar
{
public static Parser<string> Keyword(string word)
{
if (word.Any(ch => !char.IsLetter(ch)))
throw new ArgumentException("Keywords may only contain letters.", nameof(word));
return input =>
{
var peek = input.Peek(word.Length + 1);
if (peek.StartsWith(word, StringComparison.Ordinal))
{
if (peek.Length == word.Length || !char.IsLetter(peek[^1]))
{
input.Advance(word.Length);
return new Parsed<string>(word, input.Position);
}
}
return new Error<string>(input.Position, ErrorMessage.Expected(word));
};
}
}
| namespace Parsley;
partial class Grammar
{
public static Parser<string> Keyword(string word)
{
if (word.Any(ch => !char.IsLetter(ch)))
throw new ArgumentException("Keywords may only contain letters.", nameof(word));
return input =>
{
var peek = input.Peek(word.Length + 1);
if (peek.StartsWith(word))
{
if (peek.Length == word.Length || !char.IsLetter(peek[^1]))
{
input.Advance(word.Length);
return new Parsed<string>(word, input.Position);
}
}
return new Error<string>(input.Position, ErrorMessage.Expected(word));
};
}
}
|
Refresh IP address not often than 1 time per minute. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco.Variables
{
public class PublicIpVariable : IVariableProvider
{
public Dictionary<string, Func<string>> GetVariables()
{
return new Dictionary<string, Func<string>>()
{
{ "publicIp", () => new WebClient().DownloadString("http://icanhazip.com").Trim() }
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco.Variables
{
public class PublicIpVariable : IVariableProvider
{
string _lastIp;
DateTime _lastUpdate;
public Dictionary<string, Func<string>> GetVariables()
{
var now = DateTime.Now;
if (now - _lastUpdate > TimeSpan.FromMinutes(1))
{
_lastIp = new WebClient().DownloadString("http://icanhazip.com").Trim();
_lastUpdate = now;
}
return new Dictionary<string, Func<string>>()
{
{ "publicIp", () => _lastIp }
};
}
}
}
|
Change InitModel from public to protected | using Andromeda2D.Entities;
using Andromeda2D.Entities.Components;
using Andromeda2D.Entities.Components.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Andromeda.Entities.Components
{
/// <summary>
/// A controller for a model
/// </summary>
/// <typeparam name="TModel">The model type</typeparam>
public abstract class Controller<TModel> : Component
where TModel : IModel
{
Entity _entity;
/// <summary>
/// Sets the model of the controller
/// </summary>
/// <param name="model">The model to set to this controller</param>
protected void SetControllerModel(TModel model)
{
this._model = model;
}
private TModel _model;
/// <summary>
/// The model of this controller
/// </summary>
public TModel Model
{
get => _model;
}
public abstract void InitModel();
public override void OnComponentInit(Entity entity)
{
InitModel();
}
}
}
| using Andromeda2D.Entities;
using Andromeda2D.Entities.Components;
using Andromeda2D.Entities.Components.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Andromeda.Entities.Components
{
/// <summary>
/// A controller for a model
/// </summary>
/// <typeparam name="TModel">The model type</typeparam>
public abstract class Controller<TModel> : Component
where TModel : IModel
{
Entity _entity;
/// <summary>
/// Sets the model of the controller
/// </summary>
/// <param name="model">The model to set to this controller</param>
protected void SetControllerModel(TModel model)
{
this._model = model;
}
private TModel _model;
/// <summary>
/// The model of this controller
/// </summary>
public TModel Model
{
get => _model;
}
protected abstract void InitModel();
public override void OnComponentInit(Entity entity)
{
InitModel();
}
}
}
|
Make program maximized on start | using System;
using Gtk;
namespace VideoAggregator
{
class MainClass
{
public static void Main (string[] args)
{
Application.Init ();
MainWindow win = new MainWindow ();
win.Show ();
Application.Run ();
}
}
}
| using System;
using Gtk;
namespace VideoAggregator
{
class MainClass
{
public static void Main (string[] args)
{
Application.Init ();
MainWindow win = new MainWindow ();
win.Maximize ();
win.Show ();
Application.Run ();
}
}
}
|
Create output directory if needed for jpg slicing. | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CuberLib
{
public class ImageTile
{
private Image image;
private Size size;
public ImageTile(string inputFile, int xSize, int ySize)
{
if (!File.Exists(inputFile)) throw new FileNotFoundException();
image = Image.FromFile(inputFile);
size = new Size(xSize, ySize);
}
public void GenerateTiles(string outputPath)
{
int xMax = image.Width;
int yMax = image.Height;
int tileWidth = xMax / size.Width;
int tileHeight = yMax / size.Height;
for (int x = 0; x < size.Width; x++)
{
for (int y = 0; y < size.Height; y++)
{
string outputFileName = Path.Combine(outputPath, string.Format("{0}_{1}.jpg", x, y));
Rectangle tileBounds = new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
Bitmap target = new Bitmap(tileWidth, tileHeight);
using (Graphics graphics = Graphics.FromImage(target))
{
graphics.DrawImage(
image,
new Rectangle(0, 0, tileWidth, tileHeight),
tileBounds,
GraphicsUnit.Pixel);
}
target.Save(outputFileName, ImageFormat.Jpeg);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CuberLib
{
public class ImageTile
{
private Image image;
private Size size;
public ImageTile(string inputFile, int xSize, int ySize)
{
if (!File.Exists(inputFile)) throw new FileNotFoundException();
image = Image.FromFile(inputFile);
size = new Size(xSize, ySize);
}
public void GenerateTiles(string outputPath)
{
int xMax = image.Width;
int yMax = image.Height;
int tileWidth = xMax / size.Width;
int tileHeight = yMax / size.Height;
if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); }
for (int x = 0; x < size.Width; x++)
{
for (int y = 0; y < size.Height; y++)
{
string outputFileName = Path.Combine(outputPath, string.Format("{0}_{1}.jpg", x, y));
Rectangle tileBounds = new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
Bitmap target = new Bitmap(tileWidth, tileHeight);
using (Graphics graphics = Graphics.FromImage(target))
{
graphics.DrawImage(
image,
new Rectangle(0, 0, tileWidth, tileHeight),
tileBounds,
GraphicsUnit.Pixel);
}
target.Save(outputFileName, ImageFormat.Jpeg);
}
}
}
}
}
|
Add note about things to add for vehicles | using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BatteryCommander.Web.Models
{
public class Vehicle
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public int UnitId { get; set; }
public virtual Unit Unit { get; set; }
// Notes, What's broken about it?
[Required]
public VehicleStatus Status { get; set; } = VehicleStatus.FMC;
[Required, StringLength(10)]
public String Bumper { get; set; }
[Required]
public VehicleType Type { get; set; } = VehicleType.HMMWV;
// public String Registration { get; set; }
// public String Serial { get; set; }
[Required]
public int Seats { get; set; } = 2;
// TroopCapacity?
// Chalk Order?
// LIN?
// Fuel Card? Towbar? Water Buffalo?
// Fuel Level?
// Driver, A-Driver, Passengers, Assigned Section?
public enum VehicleType : byte
{
HMMWV = 0,
MTV = 1
}
public enum VehicleStatus : byte
{
Unknown = 0,
FMC = 1,
NMC = byte.MaxValue
}
}
} | using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BatteryCommander.Web.Models
{
public class Vehicle
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public int UnitId { get; set; }
public virtual Unit Unit { get; set; }
// Notes, What's broken about it?
[Required]
public VehicleStatus Status { get; set; } = VehicleStatus.FMC;
[Required, StringLength(10)]
public String Bumper { get; set; }
[Required]
public VehicleType Type { get; set; } = VehicleType.HMMWV;
// public String Registration { get; set; }
// public String Serial { get; set; }
[Required]
public int Seats { get; set; } = 2;
// TroopCapacity?
// Chalk Order?
// LIN?
// Fuel Card? Towbar? Water Buffalo?
// Fuel Level?
// Driver, A-Driver, Passengers, Assigned Section?
// Has JBC-P?
public enum VehicleType : byte
{
HMMWV = 0,
MTV = 1
}
public enum VehicleStatus : byte
{
Unknown = 0,
FMC = 1,
NMC = byte.MaxValue
}
}
} |
Add a second contact to initial sample data | using System;
using SocialToolBox.Core.Database;
using SocialToolBox.Core.Database.Serialization;
using SocialToolBox.Crm.Contact.Event;
namespace SocialToolBox.Sample.Web
{
/// <summary>
/// Data initially available in the system.
/// </summary>
public static class InitialData
{
public static readonly Id UserVictorNicollet = Id.Parse("aaaaaaaaaaa");
public static readonly Id ContactBenjaminFranklin = Id.Parse("aaaaaaaaaab");
/// <summary>
/// Generates sample data.
/// </summary>
public static void AddTo(SocialModules modules)
{
var t = modules.Database.OpenReadWriteCursor();
AddContactsTo(modules, t);
}
/// <summary>
/// Generates sample contacts.
/// </summary>
private static void AddContactsTo(SocialModules modules, ICursor t)
{
foreach (var ev in new IContactEvent[]
{
new ContactCreated(ContactBenjaminFranklin, DateTime.Parse("2013/09/26"),UserVictorNicollet),
new ContactNameUpdated(ContactBenjaminFranklin, DateTime.Parse("2013/09/26"),UserVictorNicollet,"Benjamin","Franklin"),
}) modules.Contacts.Stream.AddEvent(ev, t);
}
}
} | using System;
using SocialToolBox.Core.Database;
using SocialToolBox.Crm.Contact.Event;
namespace SocialToolBox.Sample.Web
{
/// <summary>
/// Data initially available in the system.
/// </summary>
public static class InitialData
{
public static readonly Id UserVictorNicollet = Id.Parse("aaaaaaaaaaa");
public static readonly Id ContactBenjaminFranklin = Id.Parse("aaaaaaaaaab");
public static readonly Id ContactJuliusCaesar = Id.Parse("aaaaaaaaaac");
/// <summary>
/// Generates sample data.
/// </summary>
public static void AddTo(SocialModules modules)
{
var t = modules.Database.OpenReadWriteCursor();
AddContactsTo(modules, t);
}
/// <summary>
/// Generates sample contacts.
/// </summary>
private static void AddContactsTo(SocialModules modules, ICursor t)
{
foreach (var ev in new IContactEvent[]
{
new ContactCreated(ContactBenjaminFranklin, DateTime.Parse("2013/09/26"),UserVictorNicollet),
new ContactNameUpdated(ContactBenjaminFranklin, DateTime.Parse("2013/09/26"),UserVictorNicollet,"Benjamin","Franklin"),
new ContactCreated(ContactJuliusCaesar, DateTime.Parse("2013/09/27"),UserVictorNicollet),
new ContactNameUpdated(ContactJuliusCaesar, DateTime.Parse("2013/09/27"),UserVictorNicollet,"Julius","Caesar")
}) modules.Contacts.Stream.AddEvent(ev, t);
}
}
} |
Fix tests by creating a score processor | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System.Collections.Generic;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Gameplay
{
/// <summary>
/// Static class providing a <see cref="Create"/> convenience method to retrieve a correctly-initialised <see cref="GameplayState"/> instance in testing scenarios.
/// </summary>
public static class TestGameplayState
{
/// <summary>
/// Creates a correctly-initialised <see cref="GameplayState"/> instance for use in testing.
/// </summary>
public static GameplayState Create(Ruleset ruleset, IReadOnlyList<Mod>? mods = null, Score? score = null)
{
var beatmap = new TestBeatmap(ruleset.RulesetInfo);
var workingBeatmap = new TestWorkingBeatmap(beatmap);
var playableBeatmap = workingBeatmap.GetPlayableBeatmap(ruleset.RulesetInfo, mods);
return new GameplayState(playableBeatmap, ruleset, mods, score);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System.Collections.Generic;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Gameplay
{
/// <summary>
/// Static class providing a <see cref="Create"/> convenience method to retrieve a correctly-initialised <see cref="GameplayState"/> instance in testing scenarios.
/// </summary>
public static class TestGameplayState
{
/// <summary>
/// Creates a correctly-initialised <see cref="GameplayState"/> instance for use in testing.
/// </summary>
public static GameplayState Create(Ruleset ruleset, IReadOnlyList<Mod>? mods = null, Score? score = null)
{
var beatmap = new TestBeatmap(ruleset.RulesetInfo);
var workingBeatmap = new TestWorkingBeatmap(beatmap);
var playableBeatmap = workingBeatmap.GetPlayableBeatmap(ruleset.RulesetInfo, mods);
var scoreProcessor = ruleset.CreateScoreProcessor();
scoreProcessor.ApplyBeatmap(playableBeatmap);
return new GameplayState(playableBeatmap, ruleset, mods, score, scoreProcessor);
}
}
}
|
Fix for slow high score loading | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodeBreaker.Core;
using CodeBreaker.Core.Storage;
using Microsoft.EntityFrameworkCore;
namespace CodeBreaker.WebApp.Storage
{
public class ScoreStore : IScoreStore
{
private readonly CodeBreakerDbContext _dbContext;
public ScoreStore(CodeBreakerDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<Score[]> GetScores(int page, int size)
{
return (await _dbContext.Scores.ToListAsync())
.OrderBy(s => s.Attempts)
.ThenBy(s => s.Duration)
.Skip(page * size).Take(size)
.ToArray();
}
public async Task SaveScore(Score score)
{
await _dbContext.Scores.AddAsync(score);
await _dbContext.SaveChangesAsync();
}
public Task<bool> ScoreExists(Guid gameId)
{
return _dbContext.Scores.AnyAsync(s => s.GameId == gameId);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodeBreaker.Core;
using CodeBreaker.Core.Storage;
using Microsoft.EntityFrameworkCore;
namespace CodeBreaker.WebApp.Storage
{
public class ScoreStore : IScoreStore
{
private readonly CodeBreakerDbContext _dbContext;
public ScoreStore(CodeBreakerDbContext dbContext)
{
_dbContext = dbContext;
}
public Task<Score[]> GetScores(int page, int size)
{
return _dbContext.Scores
.OrderBy(s => s.Attempts)
.ThenBy(s => s.Duration)
.Skip(page * size).Take(size)
.ToArrayAsync();
}
public async Task SaveScore(Score score)
{
await _dbContext.Scores.AddAsync(score);
await _dbContext.SaveChangesAsync();
}
public Task<bool> ScoreExists(Guid gameId)
{
return _dbContext.Scores.AnyAsync(s => s.GameId == gameId);
}
}
} |
Add default RequestRuntime to service registration | using System;
using System.Collections.Generic;
using Glimpse.Web;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse
{
public class GlimpseWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
services.AddTransient<IRequestAuthorizerProvider, DefaultRequestAuthorizerProvider>();
services.AddTransient<IRequestHandlerProvider, DefaultRequestHandlerProvider>();
return services;
}
}
} | using System;
using System.Collections.Generic;
using Glimpse.Web;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse
{
public class GlimpseWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
services.AddTransient<IRequestAuthorizerProvider, DefaultRequestAuthorizerProvider>();
services.AddTransient<IRequestHandlerProvider, DefaultRequestHandlerProvider>();
services.AddTransient<IRequestRuntimeProvider, DefaultRequestRuntimeProvider>();
return services;
}
}
} |
Add AssemblyDescription to SIM.Telemetry project | 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("SIM.Telemetry")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SIM.Telemetry")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b91b2024-3f75-4df7-8dcc-111fb5ccaf5d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SIM.Telemetry")]
[assembly: AssemblyDescription("'SIM.Telemetry' is used to track Sitecore Instance Manager utilisation statistics")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SIM.Telemetry")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b91b2024-3f75-4df7-8dcc-111fb5ccaf5d")]
// 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")]
|
Use deep equality rather than string comparison. | using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Nest.Tests.Unit
{
public static class JsonExtensions
{
internal static bool JsonEquals(this string json, string otherjson)
{
var nJson = JObject.Parse(json).ToString();
var nOtherJson = JObject.Parse(otherjson).ToString();
//Assert.AreEqual(nOtherJson, nJson);
return nJson == nOtherJson;
}
}
}
| using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Nest.Tests.Unit
{
public static class JsonExtensions
{
internal static bool JsonEquals(this string json, string otherjson)
{
var nJson = JObject.Parse(json);
var nOtherJson = JObject.Parse(otherjson);
return JToken.DeepEquals(nJson, nOtherJson);
}
}
}
|
Replace integer error code with enum | using Newtonsoft.Json;
namespace MessageBird.Objects
{
public class Error
{
[JsonProperty("code")]
public int Code { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("parameter")]
public string Parameter { get; set; }
}
}
| using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace MessageBird.Objects
{
public enum ErrorCode
{
RequestNotAllowed = 2,
MissingParameters = 9,
InvalidParameters = 10,
NotFound = 20,
NotEnoughBalance = 25,
ApiNotFound = 98,
InternalError = 99
}
public class Error
{
[JsonProperty("code")]
public ErrorCode Code { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("parameter")]
public string Parameter { get; set; }
}
}
|
Remove "hide during breaks" option | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Configuration
{
public enum HUDVisibilityMode
{
Never,
[Description("Hide during gameplay")]
HideDuringGameplay,
[Description("Hide during breaks")]
HideDuringBreaks,
Always
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Configuration
{
public enum HUDVisibilityMode
{
Never,
[Description("Hide during gameplay")]
HideDuringGameplay,
Always
}
}
|
Rename variable to make it read better | using System;
using System.Collections.Generic;
using System.Linq;
using Fitbit.Models;
using Newtonsoft.Json.Linq;
namespace Fitbit.Api.Portable
{
internal static class JsonDotNetSerializerExtensions
{
/// <summary>
/// GetFriends has to do some custom manipulation with the returned representation
/// </summary>
/// <param name="serializer"></param>
/// <param name="friendsJson"></param>
/// <returns></returns>
internal static List<UserProfile> GetFriends(this JsonDotNetSerializer serializer, string friendsJson)
{
if (string.IsNullOrWhiteSpace(friendsJson))
{
throw new ArgumentNullException("friendsJson", "friendsJson can not be empty, null or whitespace.");
}
// todo: additional error checking of json string required
serializer.RootProperty = "user";
var users = JToken.Parse(friendsJson)["friends"];
return users.Children().Select(serializer.Deserialize<UserProfile>).ToList();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Fitbit.Models;
using Newtonsoft.Json.Linq;
namespace Fitbit.Api.Portable
{
internal static class JsonDotNetSerializerExtensions
{
/// <summary>
/// GetFriends has to do some custom manipulation with the returned representation
/// </summary>
/// <param name="serializer"></param>
/// <param name="friendsJson"></param>
/// <returns></returns>
internal static List<UserProfile> GetFriends(this JsonDotNetSerializer serializer, string friendsJson)
{
if (string.IsNullOrWhiteSpace(friendsJson))
{
throw new ArgumentNullException("friendsJson", "friendsJson can not be empty, null or whitespace.");
}
// todo: additional error checking of json string required
serializer.RootProperty = "user";
var friends = JToken.Parse(friendsJson)["friends"];
return friends.Children().Select(serializer.Deserialize<UserProfile>).ToList();
}
}
} |
Undo version number bump from personal build | 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("CloudSearch")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CloudSearch")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("8ace1017-c436-4f00-b040-84f7619af92f")]
// 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.2")]
[assembly: AssemblyFileVersion("1.0.0.2")]
| 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("CloudSearch")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CloudSearch")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("8ace1017-c436-4f00-b040-84f7619af92f")]
// 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.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
|
Fix use of obsolete API | using System;
using TagLib;
public class SetPictures
{
public static void Main(string [] args)
{
if(args.Length < 2) {
Console.Error.WriteLine("USAGE: mono SetPictures.exe AUDIO_PATH IMAGE_PATH_1[...IMAGE_PATH_N]");
return;
}
TagLib.File file = TagLib.File.Create(args[0]);
Console.WriteLine("Current picture count: " + file.Tag.Pictures.Length);
Picture [] pictures = new Picture[args.Length - 1];
for(int i = 1; i < args.Length; i++) {
Picture picture = Picture.CreateFromPath(args[i]);
pictures[i - 1] = picture;
}
file.Tag.Pictures = pictures;
file.Save();
Console.WriteLine("New picture count: " + file.Tag.Pictures.Length);
}
}
| using System;
using TagLib;
public class SetPictures
{
public static void Main(string [] args)
{
if(args.Length < 2) {
Console.Error.WriteLine("USAGE: mono SetPictures.exe AUDIO_PATH IMAGE_PATH_1[...IMAGE_PATH_N]");
return;
}
TagLib.File file = TagLib.File.Create(args[0]);
Console.WriteLine("Current picture count: " + file.Tag.Pictures.Length);
Picture [] pictures = new Picture[args.Length - 1];
for(int i = 1; i < args.Length; i++) {
Picture picture = new Picture(args[i]);
pictures[i - 1] = picture;
}
file.Tag.Pictures = pictures;
file.Save();
Console.WriteLine("New picture count: " + file.Tag.Pictures.Length);
}
}
|
Support full API available for worklogs | using AxosoftAPI.NET.Core.Interfaces;
using AxosoftAPI.NET.Models;
namespace AxosoftAPI.NET.Interfaces
{
public interface IWorkLogs : IGetAllResource<WorkLog>, ICreateResource<WorkLog>, IDeleteResource<WorkLog>
{
}
}
| using AxosoftAPI.NET.Core.Interfaces;
using AxosoftAPI.NET.Models;
namespace AxosoftAPI.NET.Interfaces
{
public interface IWorkLogs : IResource<WorkLog>
{
}
}
|
Use a PrivateAdditionalLibrary for czmq.lib instead of a public one | // Copyright 2015 Palm Stone Games, Inc. All Rights Reserved.
using System.IO;
namespace UnrealBuildTool.Rules
{
public class ue4czmq : ModuleRules
{
public ue4czmq(TargetInfo Target)
{
// Include paths
//PublicIncludePaths.AddRange(new string[] {});
//PrivateIncludePaths.AddRange(new string[] {});
// Dependencies
PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", });
//PrivateDependencyModuleNames.AddRange(new string[] {});
// Dynamically loaded modules
//DynamicallyLoadedModuleNames.AddRange(new string[] {});
// Definitions
Definitions.Add("WITH_UE4CZMQ=1");
LoadLib(Target);
}
public void LoadLib(TargetInfo Target)
{
string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name));
// CZMQ
string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq"));
PublicAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib"));
PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes"));
// LIBZMQ
string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq"));
PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes"));
}
}
} | // Copyright 2015 Palm Stone Games, Inc. All Rights Reserved.
using System.IO;
namespace UnrealBuildTool.Rules
{
public class ue4czmq : ModuleRules
{
public ue4czmq(TargetInfo Target)
{
// Include paths
//PublicIncludePaths.AddRange(new string[] {});
//PrivateIncludePaths.AddRange(new string[] {});
// Dependencies
PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", });
//PrivateDependencyModuleNames.AddRange(new string[] {});
// Dynamically loaded modules
//DynamicallyLoadedModuleNames.AddRange(new string[] {});
// Definitions
Definitions.Add("WITH_UE4CZMQ=1");
LoadLib(Target);
}
public void LoadLib(TargetInfo Target)
{
string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name));
// CZMQ
string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq"));
PrivateAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib"));
PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes"));
// LIBZMQ
string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq"));
PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes"));
}
}
} |
Fix failing test for TestContent in test redaction | using System;
using NBi.Xml;
using NUnit.Framework;
namespace NBi.Testing.Unit.Xml
{
[TestFixture]
public class XmlManagerTest
{
[Test]
public void Load_ValidFile_Success()
{
var filename = DiskOnFile.CreatePhysicalFile("TestSuite.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteSample.xml");
var manager = new XmlManager();
manager.Load(filename);
Assert.That(manager.TestSuite, Is.Not.Null);
}
[Test]
public void Load_ValidFile_TestContentIsCorrect()
{
var filename = DiskOnFile.CreatePhysicalFile("TestSuite.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteSample.xml");
var manager = new XmlManager();
manager.Load(filename);
Assert.That(manager.TestSuite.Tests[0].Content, Is.Not.Null);
}
[Test]
public void Load_InvalidFile_Successfully()
{
var filename = DiskOnFile.CreatePhysicalFile("TestSuiteInvalidSyntax.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteInvalidSyntax.xml");
var manager = new XmlManager();
Assert.Throws<ArgumentException>(delegate { manager.Load(filename); });
}
}
}
| using System;
using NBi.Xml;
using NUnit.Framework;
namespace NBi.Testing.Unit.Xml
{
[TestFixture]
public class XmlManagerTest
{
[Test]
public void Load_ValidFile_Success()
{
var filename = DiskOnFile.CreatePhysicalFile("TestSuite.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteSample.xml");
var manager = new XmlManager();
manager.Load(filename);
Assert.That(manager.TestSuite, Is.Not.Null);
}
[Test]
public void Load_ValidFile_TestContentIsCorrect()
{
var filename = DiskOnFile.CreatePhysicalFile("TestContentIsCorrect.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteSample.xml");
var manager = new XmlManager();
manager.Load(filename);
Assert.That(manager.TestSuite.Tests[0].Content, Is.Not.Null);
}
[Test]
public void Load_InvalidFile_Successfully()
{
var filename = DiskOnFile.CreatePhysicalFile("TestSuiteInvalidSyntax.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteInvalidSyntax.xml");
var manager = new XmlManager();
Assert.Throws<ArgumentException>(delegate { manager.Load(filename); });
}
}
}
|
Allow File to not Exist in FileBrowse | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace poshsecframework.PShell
{
class psfilenameeditor : System.Drawing.Design.UITypeEditor
{
public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return System.Drawing.Design.UITypeEditorEditStyle.Modal;
}
[RefreshProperties(System.ComponentModel.RefreshProperties.All)]
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
if (context == null || context.Instance == null)
{
return base.EditValue(context, provider, value);
}
else
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Select " + context.PropertyDescriptor.DisplayName;
dlg.FileName = (string)value;
dlg.Filter = "All Files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
value = dlg.FileName;
}
dlg.Dispose();
dlg = null;
return value;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace poshsecframework.PShell
{
class psfilenameeditor : System.Drawing.Design.UITypeEditor
{
public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return System.Drawing.Design.UITypeEditorEditStyle.Modal;
}
[RefreshProperties(System.ComponentModel.RefreshProperties.All)]
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
if (context == null || context.Instance == null)
{
return base.EditValue(context, provider, value);
}
else
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Select " + context.PropertyDescriptor.DisplayName;
dlg.FileName = (string)value;
dlg.Filter = "All Files (*.*)|*.*";
dlg.CheckFileExists = false;
if (dlg.ShowDialog() == DialogResult.OK)
{
value = dlg.FileName;
}
dlg.Dispose();
dlg = null;
return value;
}
}
}
}
|
Add some readonly 's to tests | using System;
using Villermen.RuneScapeCacheTools.Cache;
using Villermen.RuneScapeCacheTools.Cache.RuneTek5;
using Xunit;
using Xunit.Abstractions;
namespace RuneScapeCacheToolsTests
{
public class RuneTek5CacheTests : IDisposable
{
private ITestOutputHelper _output;
private RuneTek5Cache _cache;
public RuneTek5CacheTests(ITestOutputHelper output)
{
_output = output;
_cache = new RuneTek5Cache("TestData");
}
/// <summary>
/// Test for a file that exists, an archive file that exists and a file that doesn't exist.
/// </summary>
[Fact]
public void TestGetFile()
{
var file = _cache.GetFile(12, 3);
var fileData = file.Data;
Assert.True(fileData.Length > 0, "File's data is empty.");
var archiveFile = _cache.GetFile(17, 5);
var archiveEntry = archiveFile.Entries[255];
Assert.True(archiveEntry.Length > 0, "Archive entry's data is empty.");
try
{
_cache.GetFile(40, 30);
Assert.True(false, "Cache returned a file that shouldn't exist.");
}
catch (CacheException exception)
{
Assert.True(exception.Message.Contains("incomplete"), "Non-existent file cache exception had the wrong message.");
}
}
public void Dispose()
{
_cache?.Dispose();
}
}
} | using System;
using Villermen.RuneScapeCacheTools.Cache;
using Villermen.RuneScapeCacheTools.Cache.RuneTek5;
using Xunit;
using Xunit.Abstractions;
namespace RuneScapeCacheToolsTests
{
public class RuneTek5CacheTests : IDisposable
{
private readonly ITestOutputHelper _output;
private readonly RuneTek5Cache _cache;
public RuneTek5CacheTests(ITestOutputHelper output)
{
_output = output;
_cache = new RuneTek5Cache("TestData");
}
/// <summary>
/// Test for a file that exists, an archive file that exists and a file that doesn't exist.
/// </summary>
[Fact]
public void TestGetFile()
{
var file = _cache.GetFile(12, 3);
var fileData = file.Data;
Assert.True(fileData.Length > 0, "File's data is empty.");
var archiveFile = _cache.GetFile(17, 5);
var archiveEntry = archiveFile.Entries[255];
Assert.True(archiveEntry.Length > 0, "Archive entry's data is empty.");
try
{
_cache.GetFile(40, 30);
Assert.True(false, "Cache returned a file that shouldn't exist.");
}
catch (CacheException exception)
{
Assert.True(exception.Message.Contains("incomplete"), "Non-existent file cache exception had the wrong message.");
}
}
public void Dispose()
{
_cache?.Dispose();
}
}
} |
Delete break from the test | // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Linq;
using PInvoke;
using Xunit;
using Xunit.Abstractions;
using static PInvoke.WtsApi32;
public class WtsApi32Facts
{
private readonly ITestOutputHelper output;
public WtsApi32Facts(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void CheckWorkingOfWtsSafeMemoryGuard()
{
System.Diagnostics.Debugger.Break();
WtsSafeSessionInfoGuard wtsSafeMemoryGuard = new WtsSafeSessionInfoGuard();
int sessionCount = 0;
Assert.True(WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref wtsSafeMemoryGuard, ref sessionCount));
Assert.NotEqual(0, sessionCount);
var list = wtsSafeMemoryGuard.Take(sessionCount).ToList();
foreach (var ses in list)
{
this.output.WriteLine($"{ses.pWinStationName}, {ses.SessionID}, {ses.State}");
}
}
}
| // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Linq;
using PInvoke;
using Xunit;
using Xunit.Abstractions;
using static PInvoke.WtsApi32;
public class WtsApi32Facts
{
private readonly ITestOutputHelper output;
public WtsApi32Facts(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void CheckWorkingOfWtsSafeMemoryGuard()
{
WtsSafeSessionInfoGuard wtsSafeMemoryGuard = new WtsSafeSessionInfoGuard();
int sessionCount = 0;
Assert.True(WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref wtsSafeMemoryGuard, ref sessionCount));
Assert.NotEqual(0, sessionCount);
var list = wtsSafeMemoryGuard.Take(sessionCount).ToList();
foreach (var ses in list)
{
this.output.WriteLine($"{ses.pWinStationName}, {ses.SessionID}, {ses.State}");
}
}
}
|
Use IntervalReachedEventArgs instead of EventArgs. | using System;
using Microsoft.SPOT;
namespace IntervalTimer
{
public delegate void IntervalEventHandler(object sender, EventArgs e);
public class IntervalTimer
{
public TimeSpan ShortDuration { get; set; }
public TimeSpan LongDuration { get; set; }
public IntervalTimer(TimeSpan shortDuration, TimeSpan longDuration)
{
ShortDuration = shortDuration;
LongDuration = longDuration;
}
public IntervalTimer(int shortSeconds, int longSeconds)
{
ShortDuration = new TimeSpan(0, 0, shortSeconds);
LongDuration = new TimeSpan(0, 0, longSeconds);
}
}
}
| using System;
using Microsoft.SPOT;
namespace IntervalTimer
{
public delegate void IntervalEventHandler(object sender, IntervalReachedEventArgs e);
public class IntervalTimer
{
public TimeSpan ShortDuration { get; set; }
public TimeSpan LongDuration { get; set; }
public IntervalTimer(TimeSpan shortDuration, TimeSpan longDuration)
{
ShortDuration = shortDuration;
LongDuration = longDuration;
}
public IntervalTimer(int shortSeconds, int longSeconds)
{
ShortDuration = new TimeSpan(0, 0, shortSeconds);
LongDuration = new TimeSpan(0, 0, longSeconds);
}
}
}
|
Fix a bug that causes the application to not start. This happen because the Start method was not begin called. | using System;
using System.Web;
using System.Web.Configuration;
using ZMQ;
namespace Nohros.Toolkit.RestQL
{
public class Global : HttpApplication
{
static readonly Context zmq_context_;
#region .ctor
static Global() {
zmq_context_ = new Context(ZMQ.Context.DefaultIOThreads);
}
#endregion
protected void Application_Start(object sender, EventArgs e) {
string config_file_name =
WebConfigurationManager.AppSettings[Strings.kConfigFileNameKey];
string config_file_path = Server.MapPath(config_file_name);
Settings settings = new Settings.Loader()
.Load(config_file_path, Strings.kConfigRootNodeName);
var factory = new HttpQueryApplicationFactory(settings);
Application[Strings.kApplicationKey] = factory.CreateQueryApplication();
}
protected void Session_Start(object sender, EventArgs e) {
}
protected void Application_BeginRequest(object sender, EventArgs e) {
}
protected void Application_AuthenticateRequest(object sender, EventArgs e) {
}
protected void Application_Error(object sender, EventArgs e) {
}
protected void Session_End(object sender, EventArgs e) {
}
protected void Application_End(object sender, EventArgs e) {
var app = Application[Strings.kApplicationKey] as HttpQueryApplication;
if (app != null) {
app.Stop();
app.Dispose();
}
zmq_context_.Dispose();
}
}
}
| using System;
using System.Web;
using System.Web.Configuration;
using ZMQ;
namespace Nohros.Toolkit.RestQL
{
public class Global : HttpApplication
{
static readonly Context zmq_context_;
#region .ctor
static Global() {
zmq_context_ = new Context(ZMQ.Context.DefaultIOThreads);
}
#endregion
protected void Application_Start(object sender, EventArgs e) {
string config_file_name =
WebConfigurationManager.AppSettings[Strings.kConfigFileNameKey];
string config_file_path = Server.MapPath(config_file_name);
Settings settings = new Settings.Loader()
.Load(config_file_path, Strings.kConfigRootNodeName);
var factory = new HttpQueryApplicationFactory(settings);
HttpQueryApplication app = factory.CreateQueryApplication();
Application[Strings.kApplicationKey] = app;
app.Start();
}
protected void Session_Start(object sender, EventArgs e) {
}
protected void Application_BeginRequest(object sender, EventArgs e) {
}
protected void Application_AuthenticateRequest(object sender, EventArgs e) {
}
protected void Application_Error(object sender, EventArgs e) {
}
protected void Session_End(object sender, EventArgs e) {
}
protected void Application_End(object sender, EventArgs e) {
var app = Application[Strings.kApplicationKey] as HttpQueryApplication;
if (app != null) {
app.Stop();
app.Dispose();
}
zmq_context_.Dispose();
}
}
}
|
Add RandomAI() method for fast generation of simple random players | using UnityEngine;
public class Settings {
public static Player
p1 = new RandomAI(null, 1, Color.red, Resources.Load<Sprite>("Sprites/x"), "X"),
p2 = new RandomAI(null, 2, Color.blue, Resources.Load<Sprite>("Sprites/o"), "O");
}
| using UnityEngine;
public class Settings {
public static Player p1 = RandomAI(true), p2 = RandomAI(false);
public static RandomAI RandomAI(bool firstPlayer)
{
int turn = firstPlayer ? 1 : 2;
Color color = firstPlayer ? Color.red : Color.blue;
Sprite sprite =
Resources.Load<Sprite>("Sprites/" + (firstPlayer ? "x" : "o"));
string name = firstPlayer ? "X" : "O";
return new RandomAI(null, turn, color, sprite, name);
}
}
|
Add two (currently failing) tests. Hopefully the new wikiextractor will deal with these corner cases (unissued, unilluminating). | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AvsAnLib;
using ExpressionToCodeLib;
using NUnit.Framework;
namespace AvsAn_Test {
public class StandardCasesWork {
[TestCase("an", "unanticipated result")]
[TestCase("a", "unanimous vote")]
[TestCase("an", "honest decision")]
[TestCase("a", "honeysuckle shrub")]
[TestCase("an", "0800 number")]
[TestCase("an", "∞ of oregano")]
[TestCase("a", "NASA scientist")]
[TestCase("an", "NSA analyst")]
[TestCase("a", "FIAT car")]
[TestCase("an", "FAA policy")]
[TestCase("an", "A")]
public void DoTest(string article, string word) {
PAssert.That(() => AvsAn.Query(word).Article == article);
}
[TestCase("a", "", "")]
[TestCase("a", "'", "'")]
[TestCase("an", "N", "N ")]
[TestCase("a", "NASA", "NAS")]
public void CheckOddPrefixes(string article, string word, string prefix) {
PAssert.That(() => AvsAn.Query(word).Article == article && AvsAn.Query(word).Prefix == prefix);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AvsAnLib;
using ExpressionToCodeLib;
using NUnit.Framework;
namespace AvsAn_Test {
public class StandardCasesWork {
[TestCase("an", "unanticipated result")]
[TestCase("a", "unanimous vote")]
[TestCase("an", "honest decision")]
[TestCase("a", "honeysuckle shrub")]
[TestCase("an", "0800 number")]
[TestCase("an", "∞ of oregano")]
[TestCase("a", "NASA scientist")]
[TestCase("an", "NSA analyst")]
[TestCase("a", "FIAT car")]
[TestCase("an", "FAA policy")]
[TestCase("an", "A")]
[TestCase("a", "uniformed agent")]
[TestCase("an", "unissued permit")]
[TestCase("an", "unilluminating argument")]
public void DoTest(string article, string word) {
PAssert.That(() => AvsAn.Query(word).Article == article);
}
[TestCase("a", "", "")]
[TestCase("a", "'", "'")]
[TestCase("an", "N", "N ")]
[TestCase("a", "NASA", "NAS")]
public void CheckOddPrefixes(string article, string word, string prefix) {
PAssert.That(() => AvsAn.Query(word).Article == article && AvsAn.Query(word).Prefix == prefix);
}
}
}
|
Add AggressiveInlining for Rotate and Get functions | namespace NHasher
{
internal static class HashExtensions
{
public static ulong RotateLeft(this ulong original, int bits)
{
return (original << bits) | (original >> (64 - bits));
}
public static uint RotateLeft(this uint original, int bits)
{
return (original << bits) | (original >> (32 - bits));
}
internal static unsafe ulong GetUInt64(this byte[] data, int position)
{
// we only read aligned longs, so a simple casting is enough
fixed (byte* pbyte = &data[position])
{
return *((ulong*)pbyte);
}
}
internal static unsafe uint GetUInt32(this byte[] data, int position)
{
// we only read aligned longs, so a simple casting is enough
fixed (byte* pbyte = &data[position])
{
return *((uint*)pbyte);
}
}
}
}
| using System.Runtime.CompilerServices;
namespace NHasher
{
internal static class HashExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong RotateLeft(this ulong original, int bits)
{
return (original << bits) | (original >> (64 - bits));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint RotateLeft(this uint original, int bits)
{
return (original << bits) | (original >> (32 - bits));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe ulong GetUInt64(this byte[] data, int position)
{
// we only read aligned longs, so a simple casting is enough
fixed (byte* pbyte = &data[position])
{
return *((ulong*)pbyte);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe uint GetUInt32(this byte[] data, int position)
{
// we only read aligned longs, so a simple casting is enough
fixed (byte* pbyte = &data[position])
{
return *((uint*)pbyte);
}
}
}
}
|
Change constants file. Fixed path to MonkeyHelper. | using Telerik.TestingFramework.Controls.KendoUI;
using Telerik.WebAii.Controls.Html;
using Telerik.WebAii.Controls.Xaml;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using ArtOfTest.Common.UnitTesting;
using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.Controls.HtmlControls;
using ArtOfTest.WebAii.Controls.HtmlControls.HtmlAsserts;
using ArtOfTest.WebAii.Design;
using ArtOfTest.WebAii.Design.Execution;
using ArtOfTest.WebAii.ObjectModel;
using ArtOfTest.WebAii.Silverlight;
using ArtOfTest.WebAii.Silverlight.UI;
namespace MonkeyTests
{
public static class Constans
{
public static string BrowserWaitUntilReady = @"MonkeyHelper\Steps\BrowserWaitUntilReady.tstest";
public static string NavigationToBaseUrl = @"MonkeyHelper\Steps\NavigationToBaseUrl.tstest";
public static string ClickOnElement = @"MonkeyHelper\Steps\ClickOnElement.tstest";
}
}
| using Telerik.TestingFramework.Controls.KendoUI;
using Telerik.WebAii.Controls.Html;
using Telerik.WebAii.Controls.Xaml;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using ArtOfTest.Common.UnitTesting;
using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.Controls.HtmlControls;
using ArtOfTest.WebAii.Controls.HtmlControls.HtmlAsserts;
using ArtOfTest.WebAii.Design;
using ArtOfTest.WebAii.Design.Execution;
using ArtOfTest.WebAii.ObjectModel;
using ArtOfTest.WebAii.Silverlight;
using ArtOfTest.WebAii.Silverlight.UI;
namespace MonkeyTests
{
public static class Constans
{
public static string BrowserWaitUntilReady = @"MonkeyTests\MonkeyHelper\Steps\MonkeyHelper_BrowserWaitUntilReady.tstest";
public static string NavigationToBaseUrl = @"MonkeyTests\MonkeyHelper\Steps\MonkeyHelper_NavigationToBaseUrl.tstest";
public static string ClickOnElement = @"MonkeyTests\MonkeyHelper\Steps\MonkeyHelper_ClickOnElement.tstest";
}
}
|
Make lights not appear in menu | using UnityEngine;
using System.Collections;
public class LightManager {
Material LightOnMaterial;
Material LightOffMaterial;
public bool IsOn = true;
// Use this for initialization
public void UpdateLights() {
GameObject[] allLights = GameObject.FindGameObjectsWithTag ("Light");
foreach (GameObject i in allLights) {
i.SetActive (IsOn);
}
SpriteRenderer[] bitmaps = GameObject.FindObjectsOfType<SpriteRenderer>();
if (IsOn) {
foreach (SpriteRenderer i in bitmaps) {
i.material = LightOnMaterial;
}
} else {
foreach (SpriteRenderer i in bitmaps) {
i.material = LightOffMaterial;
}
}
}
public void SetLights(bool enabled) {
IsOn = enabled;
UpdateLights ();
}
private static LightManager instance;
public static LightManager Instance
{
get
{
if(instance==null)
{
instance = new LightManager();
instance.LightOnMaterial = Resources.Load("Materials/LightOnMaterial", typeof(Material)) as Material;
instance.LightOffMaterial = Resources.Load("Materials/LightOffMaterial", typeof(Material)) as Material;
}
return instance;
}
}
}
| using UnityEngine;
using System.Collections;
public class LightManager {
Material LightOnMaterial;
Material LightOffMaterial;
public bool IsOn = true;
// Use this for initialization
public void UpdateLights() {
bool lightOn = IsOn;
if (!Application.loadedLevelName.StartsWith ("Level"))
lightOn = false;
GameObject[] allLights = GameObject.FindGameObjectsWithTag ("Light");
foreach (GameObject i in allLights) {
i.SetActive (lightOn);
}
SpriteRenderer[] bitmaps = GameObject.FindObjectsOfType<SpriteRenderer>();
if (lightOn) {
foreach (SpriteRenderer i in bitmaps) {
i.material = LightOnMaterial;
}
} else {
foreach (SpriteRenderer i in bitmaps) {
i.material = LightOffMaterial;
}
}
}
public void SetLights(bool enabled) {
IsOn = enabled;
UpdateLights ();
}
private static LightManager instance;
public static LightManager Instance
{
get
{
if(instance==null)
{
instance = new LightManager();
instance.LightOnMaterial = Resources.Load("Materials/LightOnMaterial", typeof(Material)) as Material;
instance.LightOffMaterial = Resources.Load("Materials/LightOffMaterial", typeof(Material)) as Material;
}
return instance;
}
}
}
|
Use property instead of field for CompositeDisposable | using Avalonia.Controls;
using System.Reactive.Disposables;
namespace WalletWasabi.Gui.Behaviors
{
public class CommandOnDoubleClickBehavior : CommandBasedBehavior<Control>
{
private CompositeDisposable _disposables;
protected override void OnAttached()
{
_disposables = new CompositeDisposable();
base.OnAttached();
_disposables.Add(AssociatedObject.AddHandler(Control.PointerPressedEvent, (sender, e) =>
{
if(e.ClickCount == 2)
{
e.Handled = ExecuteCommand();
}
}));
}
protected override void OnDetaching()
{
base.OnDetaching();
_disposables.Dispose();
}
}
}
| using Avalonia.Controls;
using System.Reactive.Disposables;
namespace WalletWasabi.Gui.Behaviors
{
public class CommandOnDoubleClickBehavior : CommandBasedBehavior<Control>
{
private CompositeDisposable Disposables { get; set; }
protected override void OnAttached()
{
Disposables = new CompositeDisposable();
base.OnAttached();
Disposables.Add(AssociatedObject.AddHandler(Control.PointerPressedEvent, (sender, e) =>
{
if (e.ClickCount == 2)
{
e.Handled = ExecuteCommand();
}
}));
}
protected override void OnDetaching()
{
base.OnDetaching();
Disposables?.Dispose();
}
}
}
|
Change printLn to print all values followed by a newline | using Mond.Binding;
namespace Mond.Libraries.Console
{
[MondClass("")]
internal class ConsoleOutputClass
{
private ConsoleOutputLibrary _consoleOutput;
public static MondValue Create(ConsoleOutputLibrary consoleOutput)
{
MondValue prototype;
MondClassBinder.Bind<ConsoleOutputClass>(out prototype);
var instance = new ConsoleOutputClass();
instance._consoleOutput = consoleOutput;
var obj = new MondValue(MondValueType.Object);
obj.UserData = instance;
obj.Prototype = prototype;
obj.Lock();
return obj;
}
[MondFunction("print")]
public void Print(params MondValue[] arguments)
{
foreach (var v in arguments)
{
_consoleOutput.Out.Write((string)v);
}
}
[MondFunction("printLn")]
public void PrintLn(params MondValue[] arguments)
{
if (arguments.Length == 0)
_consoleOutput.Out.WriteLine();
foreach (var v in arguments)
{
_consoleOutput.Out.Write((string)v);
_consoleOutput.Out.WriteLine();
}
}
}
}
| using Mond.Binding;
namespace Mond.Libraries.Console
{
[MondClass("")]
internal class ConsoleOutputClass
{
private ConsoleOutputLibrary _consoleOutput;
public static MondValue Create(ConsoleOutputLibrary consoleOutput)
{
MondValue prototype;
MondClassBinder.Bind<ConsoleOutputClass>(out prototype);
var instance = new ConsoleOutputClass();
instance._consoleOutput = consoleOutput;
var obj = new MondValue(MondValueType.Object);
obj.UserData = instance;
obj.Prototype = prototype;
obj.Lock();
return obj;
}
[MondFunction("print")]
public void Print(params MondValue[] arguments)
{
foreach (var v in arguments)
{
_consoleOutput.Out.Write((string)v);
}
}
[MondFunction("printLn")]
public void PrintLn(params MondValue[] arguments)
{
foreach (var v in arguments)
{
_consoleOutput.Out.Write((string)v);
}
_consoleOutput.Out.WriteLine();
}
}
}
|
Set the version to a trepidatious 0.5 | 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("HALClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HALClient")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("HALClient.Tests")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HALClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HALClient")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("HALClient.Tests")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
|
Use UserVisibilityHint to detect ViewPager change instead of MenuVisibility, this fixes an Exception. | using System;
using System.Collections.Generic;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Database;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V4.Widget;
using Android.Support.V4.View;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Utilities;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Fragment = Android.Support.V4.App.Fragment;
using Toolbar = Android.Support.V7.Widget.Toolbar;
using SearchView = Android.Support.V7.Widget.SearchView;
namespace Android.Utilities
{
public abstract class TabFragment : Fragment
{
public abstract string Title { get; }
protected virtual void OnGotFocus() { }
protected virtual void OnLostFocus() { }
public virtual void Refresh() { }
public override void SetMenuVisibility(bool visible)
{
base.SetMenuVisibility(visible);
if (visible)
OnGotFocus();
else
OnLostFocus();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Database;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V4.Widget;
using Android.Support.V4.View;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Utilities;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Fragment = Android.Support.V4.App.Fragment;
using Toolbar = Android.Support.V7.Widget.Toolbar;
using SearchView = Android.Support.V7.Widget.SearchView;
namespace Android.Utilities
{
public abstract class TabFragment : Fragment
{
public abstract string Title { get; }
protected virtual void OnGotFocus() { }
protected virtual void OnLostFocus() { }
public virtual void Refresh() { }
public override void SetMenuVisibility(bool visible)
{
base.SetMenuVisibility(visible);
/*if (visible)
OnGotFocus();
else
OnLostFocus();*/
}
public override bool UserVisibleHint
{
get
{
return base.UserVisibleHint;
}
set
{
base.UserVisibleHint = value;
if (value)
OnGotFocus();
else
OnLostFocus();
}
}
}
} |
Use null propagation when invoking ValueWrittenToOutputRegister to prevent possible race condition. | namespace SimpSim.NET
{
public class Registers
{
public delegate void ValueWrittenToOutputRegisterHandler(char output);
public event ValueWrittenToOutputRegisterHandler ValueWrittenToOutputRegister;
private readonly byte[] _array;
public Registers()
{
_array = new byte[16];
}
public byte this[byte register]
{
get
{
return _array[register];
}
set
{
_array[register] = value;
if (register == 0x0f && ValueWrittenToOutputRegister != null)
ValueWrittenToOutputRegister((char)value);
}
}
}
} | namespace SimpSim.NET
{
public class Registers
{
public delegate void ValueWrittenToOutputRegisterHandler(char output);
public event ValueWrittenToOutputRegisterHandler ValueWrittenToOutputRegister;
private readonly byte[] _array;
public Registers()
{
_array = new byte[16];
}
public byte this[byte register]
{
get
{
return _array[register];
}
set
{
_array[register] = value;
if (register == 0x0f)
ValueWrittenToOutputRegister?.Invoke((char)value);
}
}
}
} |
Add test showing problem with "continue with". | using NUnit.Framework;
namespace ZimmerBot.Core.Tests.BotTests
{
[TestFixture]
public class ContinueTests : TestHelper
{
[Test]
public void CanContinueWithEmptyTarget()
{
BuildBot(@"
> Hello
: Hi
! continue
> *
! weight 0.5
: What can I help you with?
");
AssertDialog("Hello", "Hi\nWhat can I help you with?");
}
[Test]
public void CanContinueWithLabel()
{
BuildBot(@"
> Yo
: Yaj!
! continue at HowIsItGoing
<HowIsItGoing>
: How is it going?
>
: What can I help you with?
");
AssertDialog("Yo!", "Yaj!\nHow is it going?");
}
[Test]
public void CanContinueWithNewInput()
{
BuildBot(@"
> Yo
: Yaj!
! continue with Having Fun
> Having Fun
: is it fun
>
: What can I help you with?
");
AssertDialog("Yo!", "Yaj!\nis it fun");
}
}
}
| using NUnit.Framework;
namespace ZimmerBot.Core.Tests.BotTests
{
[TestFixture]
public class ContinueTests : TestHelper
{
[Test]
public void CanContinueWithEmptyTarget()
{
BuildBot(@"
> Hello
: Hi
! continue
> *
! weight 0.5
: What can I help you with?
");
AssertDialog("Hello", "Hi\nWhat can I help you with?");
}
[Test]
public void CanContinueWithLabel()
{
BuildBot(@"
> Yo
: Yaj!
! continue at HowIsItGoing
<HowIsItGoing>
: How is it going?
>
: What can I help you with?
");
AssertDialog("Yo!", "Yaj!\nHow is it going?");
}
[Test]
public void CanContinueWithNewInput()
{
BuildBot(@"
> Yo
: Yaj!
! continue with Having Fun
> Having Fun
: is it fun
>
: What can I help you with?
");
AssertDialog("Yo!", "Yaj!\nis it fun");
}
[Test]
public void CanContinueWithParameters()
{
BuildBot(@"
> Yo +
: Yaj!
! continue with Some <1>
> Some +
: Love '<1>'
");
AssertDialog("Yo Mouse", "Yaj!\nLove 'Mouse'");
}
}
}
|
Set suitable default settings, in accordance with the prophecy | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LaunchNumbering
{
public class LNSettings : GameParameters.CustomParameterNode
{
public override GameParameters.GameMode GameMode => GameParameters.GameMode.ANY;
public override bool HasPresets => false;
public override string Section => "Launch Numbering";
public override int SectionOrder => 1;
public override string Title => "Vessel Defaults";
[GameParameters.CustomParameterUI("Numbering Scheme")]
public NumberScheme Scheme { get; set; }
[GameParameters.CustomParameterUI("Show Bloc numbers")]
public bool ShowBloc { get; set; }
[GameParameters.CustomParameterUI("Bloc Numbering Scheme")]
public NumberScheme BlocScheme { get; set; }
public enum NumberScheme
{
Arabic,
Roman
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LaunchNumbering
{
public class LNSettings : GameParameters.CustomParameterNode
{
public override GameParameters.GameMode GameMode => GameParameters.GameMode.ANY;
public override bool HasPresets => false;
public override string Section => "Launch Numbering";
public override int SectionOrder => 1;
public override string Title => "Vessel Defaults";
[GameParameters.CustomParameterUI("Numbering Scheme")]
public NumberScheme Scheme { get; set; }
[GameParameters.CustomParameterUI("Show Bloc numbers")]
public bool ShowBloc { get; set; } = true;
[GameParameters.CustomParameterUI("Bloc Numbering Scheme")]
public NumberScheme BlocScheme { get; set; } = NumberScheme.Roman;
public enum NumberScheme
{
Arabic,
Roman
}
}
}
|
Use Regex in namespace pattern | using System;
using dnlib.DotNet;
namespace Confuser.Core.Project.Patterns {
/// <summary>
/// A function that compare the namespace of definition.
/// </summary>
public class NamespaceFunction : PatternFunction {
internal const string FnName = "namespace";
/// <inheritdoc />
public override string Name {
get { return FnName; }
}
/// <inheritdoc />
public override int ArgumentCount {
get { return 1; }
}
/// <inheritdoc />
public override object Evaluate(IDnlibDef definition) {
if (!(definition is TypeDef) && !(definition is IMemberDef))
return false;
object ns = Arguments[0].Evaluate(definition);
var type = definition as TypeDef;
if (type == null)
type = ((IMemberDef)definition).DeclaringType;
while (type.IsNested)
type = type.DeclaringType;
return type != null && type.Namespace == ns.ToString();
}
}
} | using System;
using System.Text.RegularExpressions;
using dnlib.DotNet;
namespace Confuser.Core.Project.Patterns {
/// <summary>
/// A function that compare the namespace of definition.
/// </summary>
public class NamespaceFunction : PatternFunction {
internal const string FnName = "namespace";
/// <inheritdoc />
public override string Name {
get { return FnName; }
}
/// <inheritdoc />
public override int ArgumentCount {
get { return 1; }
}
/// <inheritdoc />
public override object Evaluate(IDnlibDef definition) {
if (!(definition is TypeDef) && !(definition is IMemberDef))
return false;
var ns = Arguments[0].Evaluate(definition).ToString();
var type = definition as TypeDef;
if (type == null)
type = ((IMemberDef)definition).DeclaringType;
while (type.IsNested)
type = type.DeclaringType;
return type != null && Regex.IsMatch(type.Namespace, ns);
}
}
} |
Access dos not support such join syntax. | using System;
using System.Linq;
using LinqToDB;
using NUnit.Framework;
namespace Tests.UserTests
{
[TestFixture]
public class Issue1556Tests : TestBase
{
[Test]
public void Issue1556Test([DataSources(ProviderName.Sybase, ProviderName.OracleNative)] string context)
{
using (var db = GetDataContext(context))
{
AreEqual(
from p in db.Parent
from c in db.Child
where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID)
select new { p, c }
,
db.Parent
.InnerJoin(db.Child,
(p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID),
(p,c) => new { p, c }));
}
}
}
}
| using System;
using System.Linq;
using LinqToDB;
using NUnit.Framework;
namespace Tests.UserTests
{
[TestFixture]
public class Issue1556Tests : TestBase
{
[Test]
public void Issue1556Test(
[DataSources(ProviderName.Sybase, ProviderName.OracleNative, ProviderName.Access)] string context)
{
using (var db = GetDataContext(context))
{
AreEqual(
from p in db.Parent
from c in db.Child
where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID)
select new { p, c }
,
db.Parent
.InnerJoin(db.Child,
(p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID),
(p,c) => new { p, c }));
}
}
}
}
|
Clean up stream after use. | using System.IO;
using System.Text;
using Antlr4.Runtime;
using GraphQL.Language;
using GraphQL.Parsing;
namespace GraphQL.Execution
{
public class AntlrDocumentBuilder : IDocumentBuilder
{
public Document Build(string data)
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(data));
var reader = new StreamReader(stream);
var input = new AntlrInputStream(reader);
var lexer = new GraphQLLexer(input);
var tokens = new CommonTokenStream(lexer);
var parser = new GraphQLParser(tokens);
var documentTree = parser.document();
var vistor = new GraphQLVisitor();
return vistor.Visit(documentTree) as Document;
}
}
}
| using System.IO;
using System.Text;
using Antlr4.Runtime;
using GraphQL.Language;
using GraphQL.Parsing;
namespace GraphQL.Execution
{
public class AntlrDocumentBuilder : IDocumentBuilder
{
public Document Build(string data)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
using (var reader = new StreamReader(stream))
{
var input = new AntlrInputStream(reader);
var lexer = new GraphQLLexer(input);
var tokens = new CommonTokenStream(lexer);
var parser = new GraphQLParser(tokens);
var documentTree = parser.document();
var vistor = new GraphQLVisitor();
return vistor.Visit(documentTree) as Document;
}
}
}
}
|
Set failure rate to max 5% | using System;
using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.Logging;
class ChaosHandler : IHandleMessages<object>
{
readonly ILog Log = LogManager.GetLogger<ChaosHandler>();
readonly double Thresshold = ThreadLocalRandom.NextDouble() * 0.50;
public Task Handle(object message, IMessageHandlerContext context)
{
var result = ThreadLocalRandom.NextDouble();
if (result < Thresshold) throw new Exception($"Random chaos ({Thresshold * 100:N}% failure)");
return Task.FromResult(0);
}
}
| using System;
using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.Logging;
class ChaosHandler : IHandleMessages<object>
{
readonly ILog Log = LogManager.GetLogger<ChaosHandler>();
readonly double Thresshold = ThreadLocalRandom.NextDouble() * 0.05;
public Task Handle(object message, IMessageHandlerContext context)
{
var result = ThreadLocalRandom.NextDouble();
if (result < Thresshold) throw new Exception($"Random chaos ({Thresshold * 100:N}% failure)");
return Task.FromResult(0);
}
}
|
Change throw exception due to appharbor build | using System;
using System.Collections.Generic;
using System.Linq;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
using PhotoLife.Models.Enums;
using PhotoLife.Services.Contracts;
namespace PhotoLife.Services
{
public class CategoryService : ICategoryService
{
private readonly IRepository<Category> categoryRepository;
private readonly IUnitOfWork unitOfWork;
public CategoryService(IRepository<Category> categoryRepository, IUnitOfWork unitOfWork)
{
if (categoryRepository == null)
{
throw new ArgumentNullException(nameof(categoryRepository));
}
if (unitOfWork == null)
{
throw new ArgumentNullException(nameof(unitOfWork));
}
this.categoryRepository = categoryRepository;
this.unitOfWork = unitOfWork;
}
public Category GetCategoryByName(CategoryEnum categoryEnum)
{
return this.categoryRepository.GetAll.FirstOrDefault(c => c.Name.Equals(categoryEnum));
}
public IEnumerable<Category> GetAll()
{
return this.categoryRepository.GetAll.ToList();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
using PhotoLife.Models.Enums;
using PhotoLife.Services.Contracts;
namespace PhotoLife.Services
{
public class CategoryService : ICategoryService
{
private readonly IRepository<Category> categoryRepository;
private readonly IUnitOfWork unitOfWork;
public CategoryService(IRepository<Category> categoryRepository, IUnitOfWork unitOfWork)
{
if (categoryRepository == null)
{
throw new ArgumentNullException("categoryRepository");
}
if (unitOfWork == null)
{
throw new ArgumentNullException("unitOfWork");
}
this.categoryRepository = categoryRepository;
this.unitOfWork = unitOfWork;
}
public Category GetCategoryByName(CategoryEnum categoryEnum)
{
return this.categoryRepository.GetAll.FirstOrDefault(c => c.Name.Equals(categoryEnum));
}
public IEnumerable<Category> GetAll()
{
return this.categoryRepository.GetAll.ToList();
}
}
}
|
Print 'data' fields for generic events | namespace SyncTrayzor.SyncThing.ApiClient
{
public class GenericEvent : Event
{
public override void Visit(IEventVisitor visitor)
{
visitor.Accept(this);
}
public override string ToString()
{
return $"<GenericEvent ID={this.Id} Type={this.Type} Time={this.Time}>";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SyncTrayzor.SyncThing.ApiClient
{
public class GenericEvent : Event
{
public override void Visit(IEventVisitor visitor)
{
visitor.Accept(this);
}
[JsonProperty("data")]
public JToken Data { get; set; }
public override string ToString()
{
return $"<GenericEvent ID={this.Id} Type={this.Type} Time={this.Time} Data={this.Data.ToString(Formatting.None)}>";
}
}
}
|
Use EmptyLineBotLogger in unit tests. | // Copyright 2017-2018 Dirk Lemstra (https://github.com/dlemstra/line-bot-sdk-dotnet)
//
// Dirk Lemstra licenses this file to you 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:
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
namespace Line.Tests
{
[ExcludeFromCodeCoverage]
public sealed class TestConfiguration : ILineConfiguration
{
private TestConfiguration()
{
}
public string ChannelAccessToken => "ChannelAccessToken";
public string ChannelSecret => "ChannelSecret";
public static ILineConfiguration Create()
{
return new TestConfiguration();
}
public static ILineBot CreateBot()
{
return new LineBot(new TestConfiguration(), TestHttpClient.Create(), null);
}
public static ILineBot CreateBot(TestHttpClient httpClient)
{
return new LineBot(new TestConfiguration(), httpClient, null);
}
public static ILineBot CreateBot(ILineBotLogger logger)
{
return new LineBot(new TestConfiguration(), TestHttpClient.Create(), logger);
}
}
}
| // Copyright 2017-2018 Dirk Lemstra (https://github.com/dlemstra/line-bot-sdk-dotnet)
//
// Dirk Lemstra licenses this file to you 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:
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
namespace Line.Tests
{
[ExcludeFromCodeCoverage]
public sealed class TestConfiguration : ILineConfiguration
{
private TestConfiguration()
{
}
public string ChannelAccessToken => "ChannelAccessToken";
public string ChannelSecret => "ChannelSecret";
public static ILineConfiguration Create()
{
return new TestConfiguration();
}
public static ILineBot CreateBot()
{
return new LineBot(new TestConfiguration(), TestHttpClient.Create(), new EmptyLineBotLogger());
}
public static ILineBot CreateBot(TestHttpClient httpClient)
{
return new LineBot(new TestConfiguration(), httpClient, new EmptyLineBotLogger());
}
public static ILineBot CreateBot(ILineBotLogger logger)
{
return new LineBot(new TestConfiguration(), TestHttpClient.Create(), logger);
}
}
}
|
Add Find method to expression map | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NRules.RuleModel
{
/// <summary>
/// Sorted readonly map of named expressions.
/// </summary>
public class ExpressionMap : IEnumerable<NamedExpressionElement>
{
private readonly SortedDictionary<string, NamedExpressionElement> _expressions;
public ExpressionMap(IEnumerable<NamedExpressionElement> expressions)
{
_expressions = new SortedDictionary<string, NamedExpressionElement>(expressions.ToDictionary(x => x.Name));
}
/// <summary>
/// Number of expressions in the map.
/// </summary>
public int Count => _expressions.Count;
/// <summary>
/// Retrieves expression by name.
/// </summary>
/// <param name="name">Expression name.</param>
/// <returns>Matching expression.</returns>
public NamedExpressionElement this[string name]
{
get
{
var found = _expressions.TryGetValue(name, out var result);
if (!found)
{
throw new ArgumentException(
$"Expression with the given name not found. Name={name}", nameof(name));
}
return result;
}
}
public IEnumerator<NamedExpressionElement> GetEnumerator()
{
return _expressions.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NRules.RuleModel
{
/// <summary>
/// Sorted readonly map of named expressions.
/// </summary>
public class ExpressionMap : IEnumerable<NamedExpressionElement>
{
private readonly SortedDictionary<string, NamedExpressionElement> _expressions;
public ExpressionMap(IEnumerable<NamedExpressionElement> expressions)
{
_expressions = new SortedDictionary<string, NamedExpressionElement>(expressions.ToDictionary(x => x.Name));
}
/// <summary>
/// Number of expressions in the map.
/// </summary>
public int Count => _expressions.Count;
/// <summary>
/// Retrieves expression by name.
/// </summary>
/// <param name="name">Expression name.</param>
/// <returns>Matching expression.</returns>
public NamedExpressionElement this[string name]
{
get
{
var found = _expressions.TryGetValue(name, out var result);
if (!found)
{
throw new ArgumentException(
$"Expression with the given name not found. Name={name}", nameof(name));
}
return result;
}
}
/// <summary>
/// Retrieves expression by name.
/// </summary>
/// <param name="name">Expression name.</param>
/// <returns>Matching expression or <c>null</c>.</returns>
public NamedExpressionElement Find(string name)
{
_expressions.TryGetValue(name, out var result);
return result;
}
public IEnumerator<NamedExpressionElement> GetEnumerator()
{
return _expressions.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} |
Support debugging of modified assemblies | using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Cecil;
using System;
using System.IO;
namespace AspectInjector.BuildTask
{
public class AspectInjectorBuildTask : Task
{
[Required]
public string Assembly { get; set; }
[Required]
public string OutputPath { get; set; }
public override bool Execute()
{
try
{
Console.WriteLine("Aspect Injector has started for {0}", Assembly);
var assemblyResolver = new DefaultAssemblyResolver();
assemblyResolver.AddSearchDirectory(OutputPath);
string assemblyFile = Path.Combine(OutputPath, Assembly + ".exe");
var assembly = AssemblyDefinition.ReadAssembly(assemblyFile,
new ReaderParameters
{
ReadingMode = Mono.Cecil.ReadingMode.Deferred,
AssemblyResolver = assemblyResolver
});
Console.WriteLine("Assembly has been loaded");
var injector = new AspectInjector();
injector.Process(assembly);
Console.WriteLine("Assembly has been patched");
assembly.Write(assemblyFile);
Console.WriteLine("Assembly has been written");
}
catch (Exception e)
{
this.Log.LogErrorFromException(e, false, true, null);
Console.Error.WriteLine(e.Message);
return false;
}
return true;
}
}
} | using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Cecil;
using System;
using System.IO;
namespace AspectInjector.BuildTask
{
public class AspectInjectorBuildTask : Task
{
[Required]
public string Assembly { get; set; }
[Required]
public string OutputPath { get; set; }
public override bool Execute()
{
try
{
Console.WriteLine("Aspect Injector has started for {0}", Assembly);
var assemblyResolver = new DefaultAssemblyResolver();
assemblyResolver.AddSearchDirectory(OutputPath);
string assemblyFile = Path.Combine(OutputPath, Assembly + ".exe");
string pdbFile = Path.Combine(OutputPath, Assembly + ".pdb");
var assembly = AssemblyDefinition.ReadAssembly(assemblyFile,
new ReaderParameters
{
ReadingMode = Mono.Cecil.ReadingMode.Deferred,
AssemblyResolver = assemblyResolver,
ReadSymbols = true
});
Console.WriteLine("Assembly has been loaded");
var injector = new AspectInjector();
injector.Process(assembly);
Console.WriteLine("Assembly has been patched");
assembly.Write(assemblyFile, new WriterParameters()
{
WriteSymbols = true
});
Console.WriteLine("Assembly has been written");
}
catch (Exception e)
{
this.Log.LogErrorFromException(e, false, true, null);
Console.Error.WriteLine(e.Message);
return false;
}
return true;
}
}
} |
Use propert initializers instead of constructor | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AllReady.Models
{
public class Activity
{
public Activity()
{
Tasks = new List<AllReadyTask>();
UsersSignedUp = new List<ActivitySignup>();
RequiredSkills = new List<ActivitySkill>();
}
public int Id { get; set; }
[Display(Name = "Tenant")]
public int TenantId { get; set; }
public Tenant Tenant { get; set; }
[Display(Name = "Campaign")]
public int CampaignId { get; set; }
public Campaign Campaign { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[Display(Name = "Start date")]
public DateTime StartDateTimeUtc { get; set; }
[Display(Name = "End date")]
public DateTime EndDateTimeUtc { get; set; }
public Location Location { get; set; }
public List<AllReadyTask> Tasks { get; set; }
public List<ActivitySignup> UsersSignedUp { get; set; }
public ApplicationUser Organizer { get; set; }
[Display(Name = "Image")]
public string ImageUrl { get; set; }
[Display(Name = "Required skills")]
public List<ActivitySkill> RequiredSkills { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AllReady.Models
{
public class Activity
{
public int Id { get; set; }
[Display(Name = "Tenant")]
public int TenantId { get; set; }
public Tenant Tenant { get; set; }
[Display(Name = "Campaign")]
public int CampaignId { get; set; }
public Campaign Campaign { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[Display(Name = "Start date")]
public DateTime StartDateTimeUtc { get; set; }
[Display(Name = "End date")]
public DateTime EndDateTimeUtc { get; set; }
public Location Location { get; set; }
public List<AllReadyTask> Tasks { get; set; } = new List<AllReadyTask>();
public List<ActivitySignup> UsersSignedUp { get; set; } = new List<ActivitySignup>();
public ApplicationUser Organizer { get; set; }
[Display(Name = "Image")]
public string ImageUrl { get; set; }
[Display(Name = "Required skills")]
public List<ActivitySkill> RequiredSkills { get; set; } = new List<ActivitySkill>();
}
} |
Allow non-default Command Settings to be passed to GetSqlCommand() | /*
* SqlServerHelpers
* SqlConnectionExtensions - Extension methods for SqlConnection
* Authors:
* Josh Keegan 26/05/2015
*/
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlServerHelpers.ExtensionMethods
{
public static class SqlConnectionExtensions
{
public static SqlCommand GetSqlCommand(this SqlConnection conn, SqlTransaction trans = null)
{
return getSqlCommand(null, conn, trans);
}
public static SqlCommand GetSqlCommand(this SqlConnection conn, string txtCmd, SqlTransaction trans = null)
{
return getSqlCommand(txtCmd, conn, trans);
}
private static SqlCommand getSqlCommand(string txtCmd, SqlConnection conn, SqlTransaction trans)
{
SqlCommand command = new SqlCommand(txtCmd, conn, trans);
// Apply default command settings
if (Settings.Command != null)
{
if (Settings.Command.CommandTimeout != null)
{
command.CommandTimeout = (int) Settings.Command.CommandTimeout;
}
// TODO: Support more default settings as they're added to CommandSettings
}
return command;
}
}
}
| /*
* SqlServerHelpers
* SqlConnectionExtensions - Extension methods for SqlConnection
* Authors:
* Josh Keegan 26/05/2015
*/
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlServerHelpers.ExtensionMethods
{
public static class SqlConnectionExtensions
{
#region Public Methods
public static SqlCommand GetSqlCommand(this SqlConnection conn, SqlTransaction trans = null,
CommandSettings commandSettings = null)
{
return getSqlCommand(null, conn, trans, commandSettings);
}
public static SqlCommand GetSqlCommand(this SqlConnection conn, string txtCmd, SqlTransaction trans = null,
CommandSettings commandSettings = null)
{
return getSqlCommand(txtCmd, conn, trans, commandSettings);
}
public static SqlCommand GetSqlCommand(this SqlConnection conn, CommandSettings commandSettings)
{
return GetSqlCommand(conn, null, commandSettings);
}
#endregion
#region Private Methods
private static SqlCommand getSqlCommand(string txtCmd, SqlConnection conn, SqlTransaction trans,
CommandSettings commandSettings)
{
// If no command settings have been supplied, use the default ones as defined statically in Settings
if (commandSettings == null)
{
commandSettings = Settings.Command;
}
// Make the command
SqlCommand command = new SqlCommand(txtCmd, conn, trans);
// Apply command settings
if (commandSettings != null)
{
if (commandSettings.CommandTimeout != null)
{
command.CommandTimeout = (int) commandSettings.CommandTimeout;
}
// TODO: Support more default settings as they're added to CommandSettings
}
return command;
}
#endregion
}
}
|
Add whitespace on test file | using NUnit.Framework;
using UnityEngine.Formats.Alembic.Sdk;
namespace UnityEditor.Formats.Alembic.Exporter.UnitTests
{
class EditorTests
{
[Test]
public void MarshalTests()
{
Assert.AreEqual(72,System.Runtime.InteropServices.Marshal.SizeOf(typeof(aePolyMeshData)));
}
}
} | using NUnit.Framework;
using UnityEngine.Formats.Alembic.Sdk;
namespace UnityEditor.Formats.Alembic.Exporter.UnitTests
{
class EditorTests
{
[Test]
public void MarshalTests()
{
Assert.AreEqual(72,System.Runtime.InteropServices.Marshal.SizeOf(typeof(aePolyMeshData)));
}
}
}
|
Set notification for sintrom control days | using System;
using System.Collections.Generic;
using System.Text;
using TFG.Model;
namespace TFG.Logic {
public class SintromLogic {
private static SintromLogic _instance;
public static SintromLogic Instance() {
if (_instance == null) {
_instance = new SintromLogic();
}
return _instance;
}
private SintromLogic() { }
public NotificationItem GetNotificationitem() {
var sintromItems = DBHelper.Instance.GetSintromItemFromDate(DateTime.Now);
if (sintromItems.Count > 0) {
var sintromItem = sintromItems[0];
var title = HealthModulesInfo.GetStringFromResourceName("sintrom_name");
var description =
string.Format(HealthModulesInfo.GetStringFromResourceName("sintrom_notification_description"),
sintromItem.Fraction, sintromItem.Medicine);
return new NotificationItem(title, description, true);
}
return null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using TFG.Model;
namespace TFG.Logic {
public class SintromLogic {
private static SintromLogic _instance;
public static SintromLogic Instance() {
if (_instance == null) {
_instance = new SintromLogic();
}
return _instance;
}
private SintromLogic() { }
public NotificationItem GetNotificationitem() {
var controlday = DBHelper.Instance.GetSintromINRItemFromDate(DateTime.Now);
var title = HealthModulesInfo.GetStringFromResourceName("sintrom_name");
//Control Day Notification
if (controlday.Count > 0 && controlday[0].Control) {
var description =
string.Format(HealthModulesInfo.GetStringFromResourceName("sintrom_notification_control_description"));
return new NotificationItem(title, description, true);
}
//Treatment Day Notification
var sintromItems = DBHelper.Instance.GetSintromItemFromDate(DateTime.Now);
if (sintromItems.Count > 0) {
var sintromItem = sintromItems[0];
var description =
string.Format(HealthModulesInfo.GetStringFromResourceName("sintrom_notification_description"),
sintromItem.Fraction, sintromItem.Medicine);
return new NotificationItem(title, description, true);
}
//No Notification
return null;
}
}
}
|
Remove version attributes from assembly info | 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("LazyStorage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LazyStorage")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("LazyStorage.Tests")]
// 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("4538ca36-f57b-4bec-b9d1-3540fdd28ae3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LazyStorage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LazyStorage")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("LazyStorage.Tests")]
// 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("4538ca36-f57b-4bec-b9d1-3540fdd28ae3")]
|
Change version number to 1.2.1 | /*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.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("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| /*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.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("1.2.1.0")]
[assembly: AssemblyFileVersion("1.2.1.0")]
|
Test filenames are case insensitive too. | using SRPCommon.Interfaces;
using SRPCommon.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SRPTests.TestRenderer
{
// Implementation of IWorkspace that finds test files.
class TestWorkspace : IWorkspace
{
private readonly string _baseDir;
private readonly Dictionary<string, string> _files;
public TestWorkspace(string baseDir)
{
_baseDir = baseDir;
// Find all files in the TestScripts dir.
_files = Directory.EnumerateFiles(_baseDir, "*", SearchOption.AllDirectories)
.ToDictionary(path => Path.GetFileName(path));
}
public string FindProjectFile(string name)
{
string path;
if (_files.TryGetValue(name, out path))
{
return path;
}
return null;
}
public string GetAbsolutePath(string path)
{
if (Path.IsPathRooted(path))
{
return path;
}
return Path.Combine(_baseDir, path);
}
}
}
| using SRPCommon.Interfaces;
using SRPCommon.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SRPTests.TestRenderer
{
// Implementation of IWorkspace that finds test files.
class TestWorkspace : IWorkspace
{
private readonly string _baseDir;
private readonly Dictionary<string, string> _files;
public TestWorkspace(string baseDir)
{
_baseDir = baseDir;
// Find all files in the TestScripts dir.
_files = Directory.EnumerateFiles(_baseDir, "*", SearchOption.AllDirectories)
.ToDictionary(path => Path.GetFileName(path), StringComparer.OrdinalIgnoreCase);
}
public string FindProjectFile(string name)
{
string path;
if (_files.TryGetValue(name, out path))
{
return path;
}
return null;
}
public string GetAbsolutePath(string path)
{
if (Path.IsPathRooted(path))
{
return path;
}
return Path.Combine(_baseDir, path);
}
}
}
|
Fix bug in file selection | using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, excludedDirectoryNames)
.Select(x => TarEntry.CreateEntryFromFile(x.FullName));
foreach (var entry in entries)
{
archive.WriteEntry(entry, true);
}
archive.Close();
}
private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
return directory.GetFiles("*", SearchOption.TopDirectoryOnly)
.Concat(directory.GetDirectories()
.Where(x => excludedDirectories.Contains(x.Name))
.SelectMany(x => GetFiles(x, excludedDirectories)));
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, excludedDirectoryNames)
.Select(x => TarEntry.CreateEntryFromFile(x.FullName));
foreach (var entry in entries)
{
archive.WriteEntry(entry, true);
}
archive.Close();
}
private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
return directory.GetFiles("*", SearchOption.TopDirectoryOnly)
.Concat(directory.GetDirectories()
.Where(x => !excludedDirectories.Contains(x.Name))
.SelectMany(x => GetFiles(x, excludedDirectories)));
}
}
}
|
Use RuntimeInformation class to check environment. | // dnlib: See LICENSE.txt for more info
using System;
using System.IO;
namespace dnlib.IO {
static class DataReaderFactoryFactory {
static readonly bool isUnix;
static DataReaderFactoryFactory() {
// See http://mono-project.com/FAQ:_Technical#Mono_Platforms for platform detection.
int p = (int)Environment.OSVersion.Platform;
if (p == 4 || p == 6 || p == 128)
isUnix = true;
}
public static DataReaderFactory Create(string fileName, bool mapAsImage) {
var creator = CreateDataReaderFactory(fileName, mapAsImage);
if (creator is not null)
return creator;
return ByteArrayDataReaderFactory.Create(File.ReadAllBytes(fileName), fileName);
}
static DataReaderFactory CreateDataReaderFactory(string fileName, bool mapAsImage) {
if (!isUnix)
return MemoryMappedDataReaderFactory.CreateWindows(fileName, mapAsImage);
else
return MemoryMappedDataReaderFactory.CreateUnix(fileName, mapAsImage);
}
}
}
| // dnlib: See LICENSE.txt for more info
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace dnlib.IO {
static class DataReaderFactoryFactory {
static readonly bool isUnix;
static DataReaderFactoryFactory() {
// See http://mono-project.com/FAQ:_Technical#Mono_Platforms for platform detection.
int p = (int)Environment.OSVersion.Platform;
if (p == 4 || p == 6 || p == 128)
isUnix = true;
#if NETSTANDARD
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
isUnix = true;
#endif
}
public static DataReaderFactory Create(string fileName, bool mapAsImage) {
var creator = CreateDataReaderFactory(fileName, mapAsImage);
if (creator is not null)
return creator;
return ByteArrayDataReaderFactory.Create(File.ReadAllBytes(fileName), fileName);
}
static DataReaderFactory CreateDataReaderFactory(string fileName, bool mapAsImage) {
if (!isUnix)
return MemoryMappedDataReaderFactory.CreateWindows(fileName, mapAsImage);
else
return MemoryMappedDataReaderFactory.CreateUnix(fileName, mapAsImage);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.